Browse Source

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

Yannick Warnier 11 years ago
parent
commit
cf81b35bd1

+ 2 - 0
main/admin/session_list.php

@@ -163,3 +163,5 @@ echo '<a href="'.api_get_path(WEB_CODE_PATH).'admin/session_category_list.php">'
 echo '</div>';
 echo Display::grid_html('sessions');
 Display::display_footer();
+
+

+ 11 - 11
main/coursecopy/classes/Announcement.class.php

@@ -13,31 +13,31 @@ class Announcement extends Resource
 	/**
 	 * The title of the announcement
 	 */
-	var $title;
+    public $title;
 	/**
 	 * The content of the announcement
 	 */
-	var $content;
+    public $content;
 	/**
 	 * The date on which this announcement was made
 	 */
-	var $date;
+    public $date;
 	/**
 	 * The display order of this announcement
 	 */
-	var $display_order;
+    public $display_order;
 	/**
 	 * Has the e-mail been sent?
 	 */
-	var $email_sent;
+    public $email_sent;
 	
-	var $attachment_path;
+    public $attachment_path;
 	
-	var $attachment_filename;
+    public $attachment_filename;
 	
-	var $attachment_size;
+    public $attachment_size;
 	
-	var $attachment_comment;
+    public $attachment_comment;
 	
 	/**
 	 * Create a new announcement
@@ -47,7 +47,8 @@ class Announcement extends Resource
 	 * @param string $date
 	 * @param int display_order
 	 */
-	function Announcement($id, $title, $content, $date, $display_order, $email_sent, $path, $filename, $size, $comment) {
+	function Announcement($id, $title, $content, $date, $display_order, $email_sent, $path, $filename, $size, $comment) 
+{
 		parent::Resource($id,RESOURCE_ANNOUNCEMENT);
 		
 		$this->content	= $content;
@@ -71,4 +72,3 @@ class Announcement extends Resource
 		echo $this->date.': '.$this->title;
 	}
 }
-?>

+ 10 - 6
main/coursecopy/classes/Attendance.class.php

@@ -6,10 +6,11 @@ require_once 'Resource.class.php';
  * @package chamilo.backup
  */
 
-class Attendance extends Resource {
+class Attendance extends Resource
+{
 		
-	var $params = array();	
-	var $attendance_calendar = array();	
+    public $params = array();
+    public $attendance_calendar = array();
 	
 	
 	/**
@@ -17,17 +18,20 @@ class Attendance extends Resource {
 	 * 
 	 * @param array parameters	
 	 */
-	public function __construct($params) {
+    public function __construct($params)
+    {
 		parent::Resource($params['id'], RESOURCE_ATTENDANCE);
 		$this->params = $params;
 	}
 
-	public function show() {
+    public function show()
+    {
 		parent::show();
 		echo $this->params['name'];
 	}
 	
-	public function add_attendance_calendar($data) {		
+    public function add_attendance_calendar($data)
+    {
 		$this->attendance_calendar[] = $data;
 	}	
 }

+ 43 - 32
main/coursecopy/classes/Course.class.php

@@ -12,17 +12,18 @@ require_once 'Event.class.php';
  */
 class Course
 {
-	var $resources;
-	var $code;
-	var $path;
-	var $destination_path;
-	var $destination_db;
-	var $encoding;
+    public $resources;
+    public $code;
+    public $path;
+    public $destination_path;
+    public $destination_db;
+    public $encoding;
 
 	/**
 	 * Create a new Course-object
 	 */
-	function __construct() {
+    function __construct()
+    {
 		$this->resources    = array();
 		$this->code         = '';
 		$this->path         = '';
@@ -33,28 +34,30 @@ class Course
 	/**
 	 * Check if a resource links to the given resource
 	 */
-	function is_linked_resource(& $resource_to_check) {
-		foreach($this->resources as $type => $resources) {
-			if (is_array($resources)) {
-				foreach($resources as $id => $resource) {
-					if( $resource->links_to($resource_to_check) ) {
-						return true;
-					}
-					if ($type == RESOURCE_LEARNPATH && get_class($resource)=='CourseCopyLearnpath') {
-						if($resource->has_item($resource_to_check)) {
-							return true;
-						}
-					}
-				}
-			}
-		}
-		return false;
-	}
+    function is_linked_resource(& $resource_to_check)
+    {
+        foreach ($this->resources as $type => $resources) {
+            if (is_array($resources)) {
+                foreach ($resources as $id => $resource) {
+                    if ($resource->links_to($resource_to_check) ) {
+                        return true;
+                    }
+                    if ($type == RESOURCE_LEARNPATH && get_class($resource)=='CourseCopyLearnpath') {
+                        if ($resource->has_item($resource_to_check)) {
+                            return true;
+                        }
+                    }
+                }
+            }
+        }
+        return false;
+    }
 
 	/**
 	 * Add a resource from a given type to this course
 	 */
-	function add_resource(& $resource) {
+    function add_resource(& $resource)
+    {
 		$this->resources[$resource->get_type()][$resource->get_id()] = $resource;
 	}
 
@@ -64,16 +67,21 @@ class Course
 	 * given type. If no type is given, check if course has resources of any
 	 * type.
 	 */
-	function has_resources($resource_type = null) {
+    function has_resources($resource_type = null)
+    {
 		if( $resource_type != null) {
-			return is_array($this->resources[$resource_type]) && ( count($this->resources[$resource_type]) > 0 );
+            return isset($this->resources[$resource_type]) && is_array($this->resources[$resource_type]) && (count(
+                    $this->resources[$resource_type]
+                ) > 0);
 		}
 		return (count($this->resources) > 0);
 	}
+
 	/**
 	 * Show this course resources
 	 */
-	function show()	{/*
+    function show()
+    { /*
 		echo '<pre>';
 		print_r($this);
 		echo '</pre>';*/
@@ -84,7 +92,8 @@ class Course
 	 * This sample text is to be used for course language or encoding detection if there is missing (meta)data in the archive.
 	 * @return string	The resulting sample text extracted from some common resources' data fields.
 	 */
-	public function get_sample_text() {
+    public function get_sample_text()
+    {
 
 		$sample_text = '';
 		foreach ($this->resources as $type => & $resources) {
@@ -324,7 +333,8 @@ class Course
     /**
 	* Serialize the course with the best serializer available
 	*/
-	public static function serialize($course) {
+    public static function serialize($course)
+    {
 		if (extension_loaded('igbinary')) {
 			return igbinary_serialize($course);
 		} else {
@@ -335,11 +345,12 @@ class Course
 	/**
 	* Unserialize the course with the best serializer available
 	*/
-	public static function unserialize($course) {
+    public static function unserialize($course)
+    {
 		if (extension_loaded('igbinary')) {
 			return igbinary_unserialize($course);
 		} else {
 			return unserialize($course);
 		}
 	}
-}
+}

+ 17 - 15
main/coursecopy/classes/CourseArchiver.class.php

@@ -12,7 +12,8 @@ require_once 'Course.class.php';
  *
  * @todo Use archive-folder of Chamilo?
  */
-class CourseArchiver {
+class CourseArchiver
+{
 
     /**
      * Delete old temp-dirs
@@ -33,7 +34,8 @@ class CourseArchiver {
      * Write a course and all its resources to a zip-file.
      * @return string A pointer to the zip-file
      */
-    static function write_course($course) {
+    static function write_course($course)
+    {
         $perm_dirs = api_get_permissions_for_new_directories();
 
         CourseArchiver::clean_backup_dir();
@@ -70,11 +72,10 @@ class CourseArchiver {
             error_log(__FILE__ . ' line ' . __LINE__ . ': ' . (ini_get('track_errors') != false ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
         }
         
-        //Documents
         
         // Copy all documents to the temp-dir        
-        if (is_array($course->resources[RESOURCE_DOCUMENT])) {
-            foreach ($course->resources[RESOURCE_DOCUMENT] as $id => $document) {
+        if (isset($course->resources[RESOURCE_DOCUMENT]) && is_array($course->resources[RESOURCE_DOCUMENT])) {
+            foreach ($course->resources[RESOURCE_DOCUMENT] as $document) {
                 if ($document->file_type == DOCUMENT) {
                     $doc_dir = $backup_dir . $document->path;
                     @mkdir(dirname($doc_dir), $perm_dirs, true);
@@ -88,32 +89,32 @@ class CourseArchiver {
         }
 
         // Copy all scorm documents to the temp-dir
-        if (is_array($course->resources[RESOURCE_SCORM])) {
-            foreach ($course->resources[RESOURCE_SCORM] as $id => $document) {
+        if (isset($course->resources[RESOURCE_SCORM]) && is_array($course->resources[RESOURCE_SCORM])) {
+            foreach ($course->resources[RESOURCE_SCORM] as $document) {
                 $doc_dir = dirname($backup_dir . $document->path);
                 @mkdir($doc_dir, $perm_dirs, true);
                 copyDirTo($course->path . $document->path, $doc_dir, false);
             }
         }
 
-        //Copy calendar attachments
+        // Copy calendar attachments.
 
-        if (is_array($course->resources[RESOURCE_EVENT])) {
+        if (isset($course->resources[RESOURCE_EVENT]) && is_array($course->resources[RESOURCE_EVENT])) {
             $doc_dir = dirname($backup_dir . '/upload/calendar/');
             @mkdir($doc_dir, $perm_dirs, true);
             copyDirTo($course->path . 'upload/calendar/', $doc_dir, false);
         }
 
-        //Copy learningpath author image		
-        if (is_array($course->resources[RESOURCE_LEARNPATH])) {
+        // Copy Learning path author image.
+        if (isset($course->resources[RESOURCE_LEARNPATH]) && is_array($course->resources[RESOURCE_LEARNPATH])) {
             $doc_dir = dirname($backup_dir . '/upload/learning_path/');
             @mkdir($doc_dir, $perm_dirs, true);
             copyDirTo($course->path . 'upload/learning_path/', $doc_dir, false);
         }
 
-        //Copy announcements attachments
+        // Copy announcements attachments.
 
-        if (is_array($course->resources[RESOURCE_ANNOUNCEMENT])) {
+        if (isset($course->resources[RESOURCE_ANNOUNCEMENT]) && is_array($course->resources[RESOURCE_ANNOUNCEMENT])) {
             $doc_dir = dirname($backup_dir . '/upload/announcements/');
             @mkdir($doc_dir, $perm_dirs, true);
             copyDirTo($course->path . 'upload/announcements/', $doc_dir, false);
@@ -162,7 +163,7 @@ class CourseArchiver {
         $new_filename = uniqid('') . '.zip';
         $new_dir = api_get_path(SYS_ARCHIVE_PATH);
         if (is_dir($new_dir) && is_writable($new_dir)) {
-            move_uploaded_file($file, api_get_path(SYS_ARCHIVE_PATH) . '' . $new_filename);
+            move_uploaded_file($file, api_get_path(SYS_ARCHIVE_PATH).$new_filename);
             return $new_filename;
         }
         return false;
@@ -174,7 +175,8 @@ class CourseArchiver {
      * @param boolean $delete Delete the file after reading the course?
      * @todo Check if the archive is a correct Chamilo-export
      */
-    static function read_course($filename, $delete = false) {
+    static function read_course($filename, $delete = false)
+    {
         CourseArchiver::clean_backup_dir();
         // Create a temp directory
         $tmp_dir_name = 'CourseArchiver_' . uniqid('');

+ 82 - 64
main/coursecopy/classes/CourseBuilder.class.php

@@ -29,7 +29,8 @@ require_once 'Attendance.class.php';
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package chamilo.backup
  */
-class CourseBuilder {
+class CourseBuilder
+{
     /** Course */
     public $course;
 
@@ -59,8 +60,9 @@ class CourseBuilder {
     /**
      * Create a new CourseBuilder
      */
-    function __construct($type='', $course = null) {
-        global $_course;
+	public function __construct($type='', $course = null)
+    {
+        $_course = api_get_course_info();
 
         if (!empty($course['official_code'])){
             $_course = $course;
@@ -80,7 +82,8 @@ class CourseBuilder {
      *
      * @param type $array
      */
-    function set_tools_to_build($array) {
+    function set_tools_to_build($array)
+    {
         $this->tools_to_build = $array;
     }
 
@@ -88,7 +91,8 @@ class CourseBuilder {
      *
      * @param type $array
      */
-    function set_tools_specific_id_list($array) {
+    function set_tools_specific_id_list($array)
+    {
         $this->specific_id_list = $array;
     }
 
@@ -96,7 +100,8 @@ class CourseBuilder {
      * Get the created course
      * @return course The course
      */
-    function get_course() {
+	function get_course()
+    {
         return $this->course;
     }
 
@@ -108,7 +113,8 @@ class CourseBuilder {
      * @param bool     true if you want to get the elements that exists in the course and
      *                 in the session, (session_id = 0 or session_id = X)
      */
-    function build($session_id = 0, $course_code = '', $with_base_content = false) {
+	function build($session_id = 0, $course_code = '', $with_base_content = false)
+    {
         $table_link       = Database :: get_course_table(TABLE_LINKED_RESOURCES);
         $table_properties = Database :: get_course_table(TABLE_ITEM_PROPERTY);
 
@@ -117,35 +123,8 @@ class CourseBuilder {
 
         foreach ($this->tools_to_build as $tool) {
             $function_build = 'build_'.$tool;
-            $this->$function_build($session_id, $course_code, $with_base_content, $this->specific_id_list[$tool]);
-        }
-
-        if (!empty($session_id) && !empty($course_code)) {
-            /*$this->build_documents($session_id, $course_code, $with_base_content);
-            $this->build_quizzes($session_id, $course_code,   $with_base_content);
-            $this->build_glossary($session_id, $course_code,  $with_base_content);
-            $this->build_learnpaths($session_id, $course_code,$with_base_content);
-            $this->build_links($session_id, $course_code, $with_base_content);
-            $this->build_course_descriptions($session_id, $course_code, $with_base_content);
-            $this->build_wiki($session_id, $course_code, $with_base_content);
-            //$this->build_thematic($session_id, $course_code, $with_base_content);
-            $this->build_thematic();
-            $this->build_attendance();*/
-        } else {
-            /*$this->build_events();
-            $this->build_announcements();
-            $this->build_links();
-            $this->build_tool_intro();
-            $this->build_documents();
-            $this->build_course_descriptions();
-            $this->build_wiki();
-            $this->build_quizzes();
-            $this->build_learnpaths();
-            $this->build_surveys();
-            $this->build_glossary();
-            $this->build_thematic();
-            $this->build_attendance();*/
-
+            $specificIdList = isset($this->specific_id_list[$tool]) ? $this->specific_id_list[$tool] : null;
+            $this->$function_build($session_id, $course_code, $with_base_content, $specificIdList);
         }
 
         //TABLE_LINKED_RESOURCES is the "resource" course table, which is deprecated, apparently
@@ -180,7 +159,8 @@ class CourseBuilder {
     /**
      * Build the documents
      */
-    function build_documents($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+	function build_documents($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
 
         $course_info     = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
@@ -265,7 +245,8 @@ class CourseBuilder {
     /**
      * Build the forums
      */
-    function build_forums($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array()) {
+	function build_forums($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array())
+    {
         $course_info     = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
 
@@ -283,7 +264,8 @@ class CourseBuilder {
     /**
      * Build a forum-category
      */
-    function build_forum_category($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array()) {
+	function build_forum_category($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array())
+    {
         $table = Database :: get_course_table(TABLE_FORUM_CATEGORY);
         $course_info     = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
@@ -299,7 +281,8 @@ class CourseBuilder {
     /**
      * Build the forum-topics
      */
-    function build_forum_topics($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array()) {
+	function build_forum_topics($session_id = 0, $course_code = null, $with_base_content = false, $id_list = array())
+    {
         $table = Database :: get_course_table(TABLE_FORUM_THREAD);
         $course_info     = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
@@ -317,7 +300,8 @@ class CourseBuilder {
      * Build the forum-posts
      * TODO: All tree structure of posts should be built, attachments for example.
      */
-    function build_forum_posts($thread_id = null, $forum_id = null, $only_first_post = false) {
+    function build_forum_posts($thread_id = null, $forum_id = null, $only_first_post = false)
+    {
         $table = Database :: get_course_table(TABLE_FORUM_POST);
         $course_id = api_get_course_int_id();
         $sql = "SELECT * FROM $table WHERE c_id = $course_id ";
@@ -337,7 +321,8 @@ class CourseBuilder {
     /**
      * Build the links
      */
-    function build_links($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+	function build_links($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
         $course_info = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
 
@@ -382,7 +367,8 @@ class CourseBuilder {
     /**
      * Build tool intro
      */
-    function build_tool_intro($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+	function build_tool_intro($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
         $table = Database :: get_course_table(TABLE_TOOL_INTRO);
         $course_id = api_get_course_int_id();
         $sql = "SELECT * FROM $table WHERE c_id = $course_id ";
@@ -396,7 +382,8 @@ class CourseBuilder {
     /**
      * Build a link category
      */
-    function build_link_category($id, $course_code = '') {
+	function build_link_category($id, $course_code = '')
+    {
         $course_info = api_get_course_info($course_code);
         $course_id         = $course_info['real_id'];
 
@@ -415,7 +402,8 @@ class CourseBuilder {
     /**
      * Build the Quizzes
      */
-    function build_quizzes($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+    function build_quizzes($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
         $course_info = api_get_course_info($course_code);
         $table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
         $table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
@@ -463,7 +451,8 @@ class CourseBuilder {
     /**
      * Build the Quiz-Questions
      */
-    function build_quiz_questions($course_code = null) {
+	function build_quiz_questions($course_code = null)
+    {
         $course_info = api_get_course_info($course_code);
         $course_id   = $course_info['real_id'];
 
@@ -474,12 +463,14 @@ class CourseBuilder {
 
         // Building normal tests.
         $sql = "SELECT * FROM $table_que WHERE c_id = $course_id ";
-        $db_result = Database::query($sql);
 
+        $db_result = Database::query($sql);
         while ($obj = Database::fetch_object($db_result)) {
+
             $question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture, $obj->level, $obj->extra);
             $sql = 'SELECT * FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id = '.$obj->id;
             $db_result2 = Database::query($sql);
+
             while ($obj2 = Database::fetch_object($db_result2)) {
                 $question->add_answer($obj2->id, $obj2->answer, $obj2->correct, $obj2->comment, $obj2->ponderation, $obj2->position, $obj2->hotspot_coordinates, $obj2->hotspot_type);
                 if ($obj->type == MULTIPLE_ANSWER_TRUE_FALSE) {
@@ -498,21 +489,38 @@ class CourseBuilder {
         // Building a fictional test for collecting orphan questions.
         $build_orphan_questions = !empty($_POST['recycle_option']); // When a course is emptied this option should be activated (true).
 
-        $sql = "SELECT questions.*
-                FROM $table_que as questions
-                LEFT JOIN $table_rel as quizz_questions
-                    ON (questions.id = quizz_questions.question_id AND questions.c_id = $course_id AND quizz_questions.c_id = $course_id)
-                LEFT JOIN $table_qui as exercices
-                    ON (exercice_id = exercices.id AND exercices.c_id = $course_id AND questions.c_id = $course_id)
-                WHERE  questions.c_id = $course_id AND
-                       exercices.c_id = $course_id AND
-                       (quizz_questions.exercice_id IS NULL OR exercices.active = -1) "; // active = -1 means "deleted" test.
+        //1st union gets the orphan questions from deleted exercises
+        //2nd union gets the orphan questions from question that were deleted in a exercise.
+        $sql = " (
+                    SELECT question_id, q.* FROM $table_que q INNER JOIN $table_rel r
+                    ON (q.c_id = r.c_id AND q.id = r.question_id)
+                    INNER JOIN $table_qui ex
+                    ON (ex.id = r.exercice_id AND ex.c_id = r.c_id )
+                    WHERE ex.c_id = $course_id AND ex.active = '-1'
+                 )
+                 UNION
+                 (
+                    SELECT question_id, q.* FROM $table_que q left
+                    OUTER JOIN $table_rel r
+                    ON (q.c_id = r.c_id AND q.id = r.question_id)
+                    WHERE q.c_id = $course_id AND r.question_id is null
+                 )
+                 UNION
+                 (
+                    SELECT question_id, q.* FROM $table_que q
+                    INNER JOIN $table_rel r
+                    ON (q.c_id = r.c_id AND q.id = r.question_id)
+                    WHERE r.c_id = $course_id AND (r.exercice_id = '-1' OR r.exercice_id = '0')
+                 )
+        ";
 
         $db_result = Database::query($sql);
         if (Database::num_rows($db_result) > 0) {
             $build_orphan_questions = true;
+            $orphanQuestionIds = array();
             while ($obj = Database::fetch_object($db_result)) {
                 //Avoid adding the same question twice
+                $obj->id = $obj->question_id;
                 if (!isset($this->course->resources[$obj->id])) {
                     $question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level, $obj->extra);
                     $sql = "SELECT * FROM $table_ans WHERE c_id = $course_id AND question_id = ".$obj->id;
@@ -521,6 +529,7 @@ class CourseBuilder {
                         while ($obj2 = Database::fetch_object($db_result2)) {
                             $question->add_answer($obj2->id, $obj2->answer, $obj2->correct, $obj2->comment, $obj2->ponderation, $obj2->position, $obj2->hotspot_coordinates, $obj2->hotspot_type);
                         }
+                        $orphanQuestionIds[] = $obj->id;
                     }
                     $this->course->add_resource($question);
                 }
@@ -530,16 +539,26 @@ class CourseBuilder {
         if ($build_orphan_questions) {
             $obj = array(
                 'id' => -1,
-                'title' => get_lang('OrphanQuestions', '')
+                'title' => get_lang('OrphanQuestions', ''),
+                'type' => 2
             );
-            $this->course->add_resource(new Quiz((object)$obj));
+            $newQuiz = new Quiz((object)$obj);
+            var_dump($orphanQuestionIds);
+            if (!empty($orphanQuestionIds)) {
+                foreach ($orphanQuestionIds as $index => $orphanId) {
+                    $order = $index + 1;
+                    $newQuiz->add_question($orphanId, $order);
+                }
+            }
+            $this->course->add_resource($newQuiz);
         }
     }
 
     /**
      * Build the orphan questions
      */
-    function build_quiz_orphan_questions() {
+    function build_quiz_orphan_questions()
+    {
         $table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
         $table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
         $table_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
@@ -562,13 +581,11 @@ class CourseBuilder {
         if (Database::num_rows($db_result) > 0) {
             $orphan_questions = new Quiz(-1, get_lang('OrphanQuestions', ''), '', 0, 0, 1, '', 0); // Tjis is the fictional test for collecting orphan questions.
             $this->course->add_resource($orphan_questions);
-            while ($obj = Database::fetch_object($db_result))
-            {
+            while ($obj = Database::fetch_object($db_result)) {
                 $question = new QuizQuestion($obj->id, $obj->question, $obj->description, $obj->ponderation, $obj->type, $obj->position, $obj->picture,$obj->level,$obj->extra);
                 $sql = 'SELECT * FROM '.$table_ans.' WHERE question_id = '.$obj->id;
                 $db_result2 = Database::query($sql);
-                while ($obj2 = Database::fetch_object($db_result2))
-                {
+                while ($obj2 = Database::fetch_object($db_result2)) {
                     $question->add_answer($obj2->id, $obj2->answer, $obj2->correct, $obj2->comment, $obj2->ponderation, $obj2->position, $obj2->hotspot_coordinates, $obj2->hotspot_type);
                 }
                 $this->course->add_resource($question);
@@ -579,7 +596,8 @@ class CourseBuilder {
     /**
      * Build the Surveys
      */
-    function build_surveys($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array()) {
+	function build_surveys($session_id = 0, $course_code = '', $with_base_content = false, $id_list = array())
+    {
         $table_survey = Database :: get_course_table(TABLE_SURVEY);
         $table_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
         $course_id = api_get_course_int_id();

+ 26 - 15
main/coursecopy/classes/CourseRecycler.class.php

@@ -303,7 +303,8 @@ class CourseRecycler
     /**
      * Recycle quizzes - doesn't remove the questions and their answers, as they might still be used later
      */
-    function recycle_quizzes() {
+    function recycle_quizzes()
+    {
         if ($this->course->has_resources(RESOURCE_QUIZ)) {
             $table_qui_que = Database :: get_course_table(TABLE_QUIZ_QUESTION);
             $table_qui_ans = Database :: get_course_table(TABLE_QUIZ_ANSWER);
@@ -319,7 +320,7 @@ class CourseRecycler
             // This value is set in CourseBuilder::quiz_build_questions()
             $delete_orphan_questions = in_array(-1, $ids);
             $ids = implode(',', $ids);
-            
+
             if (!empty($ids)) {
                 // Deletion of the tests first. Questions in these tests are
                 //   not deleted and become orphan at this point
@@ -331,19 +332,29 @@ class CourseRecycler
 
             // Identifying again and deletion of the orphan questions, if it was desired.
             if ($delete_orphan_questions) {
-                $sql = 'SELECT questions.id '.
-                       ' FROM '.$table_qui_que.' as questions '.
-                       ' LEFT JOIN '.$table_rel.' as quizz_questions '.
-                       '   ON questions.id=quizz_questions.question_id '.
-                       ' LEFT JOIN '.$table_qui.' as exercices '.
-                       '   ON exercice_id=exercices.id '.
-                       ' WHERE '.
-                       '   questions.c_id = '.$this->course_id.' AND '.
-                       '   quizz_questions.c_id = '.$this->course_id.' AND '.
-                       '   exercices.c_id = '.$this->course_id.' AND '.
-                       '   quizz_questions.exercice_id IS NULL OR '.
-                       '   exercices.active = -1';
-                       // active = -1 means "deleted" test.
+
+                $sql = " (
+                        SELECT q.id, ex.c_id FROM $table_qui_que q
+                        INNER JOIN $table_rel r
+                        ON (q.c_id = r.c_id AND q.id = r.question_id)
+                        INNER JOIN $table_qui ex
+                        ON (ex.id = r.exercice_id AND ex.c_id = r.c_id)
+                        WHERE ex.c_id = ".$this->course_id." AND (ex.active = '-1' OR ex.id = '-1')
+                    )
+                    UNION
+                    (
+                        SELECT q.id, r.c_id FROM $table_qui_que q
+                        LEFT OUTER JOIN $table_rel r
+                        ON (q.c_id = r.c_id AND q.id = r.question_id)
+                        WHERE q.c_id = ".$this->course_id." AND r.question_id is null
+                    )
+                    UNION
+                    (
+                        SELECT q.id, r.c_id FROM $table_qui_que q
+                        INNER JOIN $table_rel r
+                        ON (q.c_id = r.c_id AND q.id = r.question_id)
+                        WHERE r.c_id = ".$this->course_id." AND (r.exercice_id = '-1' OR r.exercice_id = '0')
+                    )";
                 $db_result = Database::query($sql);
                 if (Database::num_rows($db_result) > 0) {
                     $orphan_ids = array();

+ 106 - 119
main/coursecopy/classes/CourseRestorer.class.php

@@ -45,53 +45,57 @@ class CourseRestorer
 	/**
 	 * The course-object
 	 */
-	var $course;
-
-	var $destination_course_info;
+    public $course;
+    public $destination_course_info;
 
 	/**
 	 * What to do with files with same name (FILE_SKIP, FILE_RENAME or
 	 * FILE_OVERWRITE)
 	 */
-	var $file_option;
-	var $set_tools_invisible_by_default;
-	var $skip_content;
-    var $tools_to_restore = array(
-                            'announcements',
-                            'attendance',
-                            'course_descriptions',
-                            'documents',
-                            'events',
-                            'forum_category',
-                            'forums',
-                           // 'forum_topics',
-                            'glossary',
-                            'quizzes',
-                            'links',
-                            'learnpaths',
-                            'surveys',
-                            //'scorm_documents', ??
-                            'tool_intro',
-                            'thematic',
-                            'wiki'
-        );
+    public $file_option;
+    public $set_tools_invisible_by_default;
+    public $skip_content;
+    public $tools_to_restore = array(
+        'announcements',
+        'attendance',
+        'course_descriptions',
+        'documents',
+        'events',
+        'forum_category',
+        'forums',
+       // 'forum_topics',
+        'glossary',
+        'quizzes',
+        'links',
+        'learnpaths',
+        'surveys',
+        //'scorm_documents', ??
+        'tool_intro',
+        'thematic',
+        'wiki'
+    );
 
     /** Setting per tool */
-    var $tool_copy_settings = array();
+    public $tool_copy_settings = array();
 
     /**
      * If true adds the text "copy" in the title of an item (only for LPs right now)
      *
      **/
-    var $add_text_in_items = false;
+    public $add_text_in_items = false;
 
 	/**
 	 * Create a new CourseRestorer
 	 */
-	function __construct($course) {
+    public function __construct($course)
+    {
 		$this->course							= $course;
 		$course_info 							= api_get_course_info($this->course->code);
-		$this->course_origin_id 				= $course_info['real_id'];
+        if (!empty($course_info)) {
+		    $this->course_origin_id 				= $course_info['real_id'];
+        } else {
+            $this->course_origin_id = null;
+        }
 		$this->file_option 						= FILE_RENAME;
 		$this->set_tools_invisible_by_default 	= false;
 		$this->skip_content 					= array();
@@ -99,16 +103,18 @@ class CourseRestorer
 
 	/**
 	 * Set the file-option
-	 * @param constant $options What to do with files with same name (FILE_SKIP,
-	 * FILE_RENAME or FILE_OVERWRITE)
+	 * @param constant $options What to do with files with same name (FILE_SKIP, FILE_RENAME or FILE_OVERWRITE)
 	 */
-	function set_file_option($option) {
+    function set_file_option($option)
+    {
 		$this->file_option = $option;
 	}
-    function set_add_text_in_items($status) {
+    function set_add_text_in_items($status)
+    {
         $this->add_text_in_items = $status;
     }
-    function set_tool_copy_settings($array) {
+    function set_tool_copy_settings($array)
+    {
         $this->tool_copy_settings = $array;
     }
 
@@ -119,7 +125,12 @@ class CourseRestorer
 	 * @param	bool	Course settings are going to be restore?
 
 	 */
-	function restore($destination_course_code = '', $session_id = 0, $update_course_settings = false, $respect_base_content = false) {
+    public function restore(
+        $destination_course_code = '',
+        $session_id = 0,
+        $update_course_settings = false,
+        $respect_base_content = false
+    ) {
 		if ($destination_course_code == '') {
 			$course_info = api_get_course_info();
 			$this->destination_course_info = $course_info;
@@ -134,6 +145,7 @@ class CourseRestorer
         //Getting first teacher (for the forums)
         $teacher_list = CourseManager::get_teacher_list_from_course_code($course_info['code']);
         $this->first_teacher_id = api_get_user_id();
+
         if (!empty($teacher_list)) {
             foreach ($teacher_list  as $teacher) {
                 $this->first_teacher_id = $teacher['user_id'];
@@ -171,37 +183,6 @@ class CourseRestorer
             $this->$function_build($session_id, $respect_base_content, $destination_course_code);
         }
 
-        /*
-		$this->restore_links($session_id);
-		$this->restore_documents($session_id, $destination_course_code);
-		$this->restore_quizzes($session_id, $respect_base_content);
-		$this->restore_glossary($session_id);
-		$this->restore_learnpaths($session_id, $respect_base_content);
-		$this->restore_course_descriptions($session_id);
-		$this->restore_wiki($session_id);
-		$this->restore_thematic($session_id);
-		$this->restore_attendance($session_id);
-
-		if (!empty($session_id)) {
-
-		} else {
-			//$this->restore_links();
-			$this->restore_tool_intro();
-			$this->restore_events();
-			$this->restore_announcements();
-			//$this->restore_documents();
-			$this->restore_scorm_documents();
-			//$this->restore_course_descriptions();
-			//$this->restore_quizzes(); // after restore_documents! (for correct import of sound/video)
-			//$this->restore_learnpaths();
-			$this->restore_surveys();
-			$this->restore_student_publication();
-			//$this->restore_glossary();
-			//$this->restore_wiki();
-			//$this->restore_thematic();
-			//$this->restore_attendance();
-		}*/
-
 		if ($update_course_settings) {
 		    $this->restore_course_settings($destination_course_code);
 		}
@@ -246,28 +227,6 @@ class CourseRestorer
 				}
 			}
 		}
-
-		/*
-		// Restore the linked-resources
-		$table = Database :: get_course_table(TABLE_LINKED_RESOURCES);
-		foreach ($this->course->resources as $type => $resources) {
-			if (is_array($resources))
-				foreach ($resources as $id => $resource) {
-					$linked_resources = $resource->get_linked_resources();
-					foreach ($linked_resources as $to_type => $to_ids) {
-						foreach ($to_ids as $index => $to_id) {
-							$to_resource = $this->course->resources[$to_type][$to_id];
-							$sql = "INSERT INTO ".$table." SET
-
-									source_type = '".$type."',
-									source_id = '".$resource->destination_id."',
-									resource_type='".$to_type."',
-									resource_id='".$to_resource->destination_id."' ";
-							Database::query($sql);
-						}
-					}
-				}
-		}*/
 	}
 
 	/**
@@ -275,7 +234,8 @@ class CourseRestorer
 	 *
 	 * @return unknown_type
 	 */
-	function restore_course_settings($destination_course_code) {
+    function restore_course_settings($destination_course_code)
+    {
 	    $origin_course_info = api_get_course_info($destination_course_code);
 	    $course_info = $this->course->info;
 	    $params['course_language'] = $course_info['language'];
@@ -294,7 +254,8 @@ class CourseRestorer
      * @param   int session id
      *
 	 */
-	function restore_documents($session_id = 0, $respect_base_content = false, $destination_course_code = '') {
+    function restore_documents($session_id = 0, $respect_base_content = false, $destination_course_code = '')
+    {
 		$perm 			= api_get_permissions_for_new_directories();
         $course_info 	= api_get_course_info($destination_course_code);
         if ($this->course->has_resources(RESOURCE_DOCUMENT)) {
@@ -640,7 +601,8 @@ class CourseRestorer
 	 * Restore scorm documents
 	 * TODO @TODO check that the restore function with renaming doesn't break the scorm structure!
 	 */
-	function restore_scorm_documents() {
+	function restore_scorm_documents()
+    {
 		$perm = api_get_permissions_for_new_directories();
 
 		if ($this->course->has_resources(RESOURCE_SCORM)) {
@@ -700,7 +662,8 @@ class CourseRestorer
 	/**
 	 * Restore forums
 	 */
-	function restore_forums() {
+	function restore_forums()
+    {
 		if ($this->course->has_resources(RESOURCE_FORUM)) {
 			$table_forum = Database::get_course_table(TABLE_FORUM);
 			$resources = $this->course->resources;
@@ -752,7 +715,8 @@ class CourseRestorer
 	/**
 	 * Restore forum-categories
 	 */
-	function restore_forum_category($my_id = null) {
+	function restore_forum_category($my_id = null)
+    {
 		$forum_cat_table = Database :: get_course_table(TABLE_FORUM_CATEGORY);
 		$resources = $this->course->resources;
         if (!empty($resources[RESOURCE_FORUMCATEGORY])) {
@@ -790,7 +754,8 @@ class CourseRestorer
 	/**
 	 * Restore a forum-topic
 	 */
-	function restore_topic($thread_id, $forum_id) {
+	function restore_topic($thread_id, $forum_id)
+    {
 		$table = Database :: get_course_table(TABLE_FORUM_THREAD);
 		$topic = $this->course->resources[RESOURCE_FORUMTOPIC][$thread_id];
 
@@ -826,7 +791,8 @@ class CourseRestorer
 	 * Restore a forum-post
 	 * @TODO Restore tree-structure of posts. For example: attachments to posts.
 	 */
-	function restore_post($id, $topic_id, $forum_id) {
+    function restore_post($id, $topic_id, $forum_id)
+    {
 		$table_post = Database :: get_course_table(TABLE_FORUM_POST);
 		$post = $this->course->resources[RESOURCE_FORUMPOST][$id];
         $params = (array) $post->obj;
@@ -846,7 +812,8 @@ class CourseRestorer
 	/**
 	 * Restore links
 	 */
-	function restore_links($session_id = 0) {
+	function restore_links($session_id = 0)
+    {
 		if ($this->course->has_resources(RESOURCE_LINK)) {
 			$link_table = Database :: get_course_table(TABLE_LINK);
 			$resources = $this->course->resources;
@@ -879,7 +846,8 @@ class CourseRestorer
 	/**
 	 * Restore tool intro
 	 */
-	function restore_tool_intro() {
+	function restore_tool_intro()
+    {
 		if ($this->course->has_resources(RESOURCE_TOOL_INTRO)) {
 			$tool_intro_table = Database :: get_course_table(TABLE_TOOL_INTRO);
 			$resources = $this->course->resources;
@@ -898,14 +866,16 @@ class CourseRestorer
 	/**
 	 * Restore a link-category
 	 */
-	function restore_link_category($id,$session_id = 0) {
+    function restore_link_category($id, $session_id = 0)
+    {
 		$condition_session = "";
 		if (!empty($session_id)) {
 			$condition_session = " , session_id = '$session_id' ";
 		}
 
-		if ($id == 0)
+        if ($id == 0) {
 			return 0;
+        }
 		$link_cat_table = Database :: get_course_table(TABLE_LINK_CATEGORY);
 		$resources = $this->course->resources;
 		$link_cat = $resources[RESOURCE_LINKCATEGORY][$id];
@@ -926,7 +896,8 @@ class CourseRestorer
 	/**
 	 * Restore events
 	 */
-	function restore_events() {
+    function restore_events()
+    {
 		if ($this->course->has_resources(RESOURCE_EVENT)) {
 			$table = Database :: get_course_table(TABLE_AGENDA);
 			$resources = $this->course->resources;
@@ -987,7 +958,8 @@ class CourseRestorer
 	/**
 	 * Restore course-description
 	 */
-	function restore_course_descriptions($session_id = 0) {
+    function restore_course_descriptions($session_id = 0)
+    {
 		if ($this->course->has_resources(RESOURCE_COURSEDESCRIPTION)) {
 			$table = Database :: get_course_table(TABLE_COURSE_DESCRIPTION);
 			$resources = $this->course->resources;
@@ -1018,7 +990,8 @@ class CourseRestorer
 	/**
 	 * Restore announcements
 	 */
-	function restore_announcements() {
+    function restore_announcements()
+    {
 		if ($this->course->has_resources(RESOURCE_ANNOUNCEMENT)) {
 			$table = Database :: get_course_table(TABLE_ANNOUNCEMENT);
 			$resources = $this->course->resources;
@@ -1082,7 +1055,8 @@ class CourseRestorer
 	/**
 	 * Restore Quiz
 	 */
-	function restore_quizzes($session_id = 0, $respect_base_content = false) {
+    function restore_quizzes($session_id = 0, $respect_base_content = false)
+    {
 		if ($this->course->has_resources(RESOURCE_QUIZ)) {
 			$table_qui = Database :: get_course_table(TABLE_QUIZ_TEST);
 			$table_rel = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
@@ -1100,9 +1074,10 @@ class CourseRestorer
                 }
 
 				$doc = '';
-				if (strlen($quiz->sound) > 0) {
-					if ($this->course->resources[RESOURCE_DOCUMENT][$quiz->sound]->is_restored()) {
-						echo $sql = "SELECT path FROM ".$table_doc." WHERE c_id = ".$this->destination_course_id."  AND id = ".$resources[RESOURCE_DOCUMENT][$quiz->sound]->destination_id;
+                if (!empty($quiz->sound)) {
+                    if (isset($this->course->resources[RESOURCE_DOCUMENT][$quiz->sound]) &&
+                        $this->course->resources[RESOURCE_DOCUMENT][$quiz->sound]->is_restored()) {
+                        $sql = "SELECT path FROM ".$table_doc." WHERE c_id = ".$this->destination_course_id."  AND id = ".$resources[RESOURCE_DOCUMENT][$quiz->sound]->destination_id;
 						$doc = Database::query($sql);
 						$doc = Database::fetch_object($doc);
 						$doc = str_replace('/audio/', '', $doc->path);
@@ -1140,7 +1115,7 @@ class CourseRestorer
                         'text_when_finished' => $quiz->text_when_finished,
                         'expired_time' => (int)$quiz->expired_time,
                     );
-                  
+
                     if ($respect_base_content) {
                         $my_session_id = $quiz->session_id;
                         if (!empty($quiz->session_id)) {
@@ -1178,9 +1153,10 @@ class CourseRestorer
 	 * Restore quiz-questions
      * @params int question id
 	 */
-	function restore_quiz_question($id) {
+    function restore_quiz_question($id)
+    {
 		$resources = $this->course->resources;
-		$question = $resources[RESOURCE_QUIZQUESTION][$id];
+        $question = isset($resources[RESOURCE_QUIZQUESTION][$id]) ? $resources[RESOURCE_QUIZQUESTION][$id] : null;
 
 		$new_id = 0;
 
@@ -1331,7 +1307,8 @@ class CourseRestorer
 	/**
 	 * Restore surveys
 	 */
-	function restore_surveys() {
+    function restore_surveys()
+    {
 		if ($this->course->has_resources(RESOURCE_SURVEY)) {
 			$table_sur = Database :: get_course_table(TABLE_SURVEY);
 			$table_que = Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -1474,7 +1451,8 @@ class CourseRestorer
 	/**
 	 * Check availability of a survey code
 	 */
-	function is_survey_code_available($survey_code)	{
+    function is_survey_code_available($survey_code)
+    {
 		$table_sur = Database :: get_course_table(TABLE_SURVEY);
 		$sql = "SELECT * FROM $table_sur WHERE c_id = ".$this->destination_course_id." AND code='".self::DBUTF8escapestring($survey_code)."'";
 		$result = Database::query($sql);
@@ -1484,7 +1462,8 @@ class CourseRestorer
 	/**
 	 * Restore survey-questions
 	 */
-	function restore_survey_question($id, $survey_id) {
+    function restore_survey_question($id, $survey_id)
+    {
 		$resources = $this->course->resources;
 		$question = $resources[RESOURCE_SURVEYQUESTION][$id];
 
@@ -1537,7 +1516,8 @@ class CourseRestorer
 	/**
 	 * Restore learnpaths
 	 */
-	function restore_learnpaths($session_id = 0, $respect_base_content = false) {
+	function restore_learnpaths($session_id = 0, $respect_base_content = false)
+    {
 		if ($this->course->has_resources(RESOURCE_LEARNPATH)) {
 			$table_main 	= Database::get_course_table(TABLE_LP_MAIN);
 			$table_item 	= Database::get_course_table(TABLE_LP_ITEM);
@@ -1948,7 +1928,8 @@ class CourseRestorer
 	/**
 	* Restore Thematics
 	*/
-	function restore_thematic($session_id = 0) {
+    function restore_thematic($session_id = 0)
+    {
 		if ($this->course->has_resources(RESOURCE_THEMATIC)) {
 			$table_thematic 		= Database :: get_course_table(TABLE_THEMATIC);
 			$table_thematic_advance = Database :: get_course_table(TABLE_THEMATIC_ADVANCE);
@@ -1997,7 +1978,8 @@ class CourseRestorer
 	* Restore Attendance
 	*/
 
-	function restore_attendance($session_id = 0) {
+    function restore_attendance($session_id = 0)
+    {
 		if ($this->course->has_resources(RESOURCE_ATTENDANCE)) {
 			$table_attendance 		   = Database :: get_course_table(TABLE_ATTENDANCE);
 			$table_attendance_calendar = Database :: get_course_table(TABLE_ATTENDANCE_CALENDAR);
@@ -2026,19 +2008,24 @@ class CourseRestorer
 		}
 	}
 
-    function DBUTF8($str) {
+    function DBUTF8($str)
+    {
 		if (UTF8_CONVERT) {
             $str = utf8_encode($str);
         }
 		return $str;
 	}
 
-	function DBUTF8escapestring($str) {
-		if (UTF8_CONVERT) $str = utf8_encode($str);
+    function DBUTF8escapestring($str)
+    {
+        if (UTF8_CONVERT) {
+            $str = utf8_encode($str);
+        }
 		return Database::escape_string($str);
 	}
 
-    function DBUTF8_array($array) {
+    function DBUTF8_array($array)
+    {
         if (UTF8_CONVERT) {
             foreach ($array as &$item)  {
                 $item = utf8_encode($item);

+ 6 - 5
main/coursecopy/classes/CourseSelectForm.class.php

@@ -16,7 +16,8 @@ class CourseSelectForm
 	 * @param array $hidden_fiels Hidden fields to add to the form.
 	 * @param boolean the document array will be serialize. This is used in the course_copy.php file
 	 */
-	static function display_form($course, $hidden_fields = null, $avoid_serialize=false) {
+	static function display_form($course, $hidden_fields = null, $avoid_serialize=false)
+    {
         global $charset;
 		$resource_titles[RESOURCE_EVENT]                = get_lang('Events');
 		$resource_titles[RESOURCE_ANNOUNCEMENT] 		= get_lang('Announcements');
@@ -360,7 +361,7 @@ class CourseSelectForm
 
 		//Create the resource DOCUMENT objects
 		//Loading the results from the checkboxes of ethe javascript
-		$resource       = $_POST['resource'][RESOURCE_DOCUMENT];
+		$resource       = isset($_POST['resource'][RESOURCE_DOCUMENT]) ? $_POST['resource'][RESOURCE_DOCUMENT] : null;
 
 		$course_info 	= api_get_course_info($course_code);
 		$table_doc 		= Database::get_course_table(TABLE_DOCUMENT);
@@ -470,8 +471,8 @@ class CourseSelectForm
 					case RESOURCE_DOCUMENT:
 						// Mark folders to import which are not selected by the user to import,
 						// but in which a document was selected.
-						$documents = $_POST['resource'][RESOURCE_DOCUMENT];
-						if (is_array($resources))
+						$documents = isset($_POST['resource'][RESOURCE_DOCUMENT]) ? $_POST['resource'][RESOURCE_DOCUMENT] : null;
+						if (!empty($resources) && is_array($resources))
 							foreach($resources as $id => $obj) {
 								if ($obj->file_type == 'folder' && ! isset($_POST['resource'][RESOURCE_DOCUMENT][$id]) && is_array($documents)) {
 									foreach($documents as $id_to_check => $post_value) {
@@ -485,7 +486,7 @@ class CourseSelectForm
 								}
 							}
 					default :
-						if (is_array($resources)) {
+						if (!empty($resources) && is_array($resources)) {
 							foreach ($resources as $id => $obj) {
 								$resource_is_used_elsewhere = $course->is_linked_resource($obj);
                                 //var_dump($obj, $resource_is_used_elsewhere);

+ 2 - 2
main/cron/import_csv.php

@@ -4,8 +4,8 @@ if (PHP_SAPI !='cli') {
     die('Run this script through the command line or comment this line in the code');
 }
 
-$_SERVER['SERVER_NAME'] = 'elo.encora.be';
-$_SERVER['HTTP_HOST'] = 'elo.encora.be';
+//$_SERVER['SERVER_NAME'] = '';
+//$_SERVER['HTTP_HOST'] = '';
 
 require_once __DIR__.'/../inc/global.inc.php';
 require_once api_get_path(LIBRARY_PATH).'log.class.php';

+ 0 - 1
main/css/base.css

@@ -2601,7 +2601,6 @@ div.admin_section h4 {
 }
 
 .question_options input[type="text"] {
-    width: 80px;
     padding:0px;
     margin:2px 2px 2px 0px;
 }

+ 41 - 41
main/exercice/answer.class.php

@@ -48,19 +48,19 @@ class Answer {
 	 * @author 	Olivier Brouckaert
 	 * @param 	integer	Question ID that answers belong to
 	 */
-	function Answer($questionId, $course_id = null) {
-
-		$this->questionId			= intval($questionId);
-		$this->answer				= array();
-		$this->correct				= array();
-		$this->comment				= array();
-		$this->weighting			= array();
-		$this->position				= array();
-		$this->hotspot_coordinates	= array();
-		$this->hotspot_type 		= array();
-		$this->destination  		= array();
-		// clears $new_* arrays
-		$this->cancel();
+	function Answer($questionId, $course_id = null)
+    {
+        $this->questionId			= intval($questionId);
+        $this->answer				= array();
+        $this->correct				= array();
+        $this->comment				= array();
+        $this->weighting			= array();
+        $this->position				= array();
+        $this->hotspot_coordinates	= array();
+        $this->hotspot_type 		= array();
+        $this->destination  		= array();
+        // clears $new_* arrays
+        $this->cancel();
 
         if (!empty($course_id)) {
             $course_info = api_get_course_info_by_id($course_id);
@@ -71,15 +71,15 @@ class Answer {
         $this->course    = $course_info;
         $this->course_id = $course_info['real_id'];
 
-		// fills arrays
-		$objExercise = new Exercise($this->course_id);
-		$objExercise->read($_REQUEST['exerciseId']);
-		if ($objExercise->random_answers=='1') {
-			$this->readOrderedBy('rand()', '');// randomize answers
-		} else {
-			$this->read(); // natural order
-		}
-	}
+        // fills arrays
+        $objExercise = new Exercise($this->course_id);
+        $objExercise->read($_REQUEST['exerciseId']);
+        if ($objExercise->random_answers == '1') {
+            $this->readOrderedBy('rand()', '');// randomize answers
+        } else {
+            $this->read(); // natural order
+        }
+    }
 
 	/**
 	 * Clears $new_* arrays
@@ -114,7 +114,7 @@ class Answer {
 		$i=1;
 
 		// while a record is found
-		while($object=Database::fetch_object($result)) {
+		while ($object=Database::fetch_object($result)) {
 			$this->id[$i]					= $object->id;
 			$this->answer[$i]				= $object->answer;
 			$this->correct[$i]				= $object->correct;
@@ -145,18 +145,17 @@ class Answer {
 			$order = 'ASC';
 		}
 
-
 		$TBL_ANSWER   = Database::get_course_table(TABLE_QUIZ_ANSWER);
 		$TBL_QUIZ     = Database::get_course_table(TABLE_QUIZ_QUESTION);
 		$questionId=intval($this->questionId);
 
 		$sql = "SELECT type FROM $TBL_QUIZ WHERE c_id = {$this->course_id} AND id = $questionId";
-		$result_question=Database::query($sql);
-		$question_type=Database::fetch_array($result_question);
+		$result_question = Database::query($sql);
+		$question_type = Database::fetch_array($result_question);
 
-		$sql="SELECT answer,correct,comment,ponderation,position, hotspot_coordinates, hotspot_type, destination, id_auto " .
-				"FROM $TBL_ANSWER WHERE c_id = {$this->course_id} AND question_id='".$questionId."'   " .
-				"ORDER BY $field $order";
+		$sql = "SELECT answer,correct,comment,ponderation,position, hotspot_coordinates, hotspot_type, destination, id_auto " .
+               "FROM $TBL_ANSWER WHERE c_id = {$this->course_id} AND question_id='".$questionId."'   " .
+               "ORDER BY $field $order";
 		$result=Database::query($sql);
 
 		$i=1;
@@ -187,7 +186,7 @@ class Answer {
 			$this->autoId[$i]		= $doubt_data->id_auto;
 			$i++;
 	    }
-        $this->nbrAnswers=$i-1;
+        $this->nbrAnswers = $i-1;
 	}
 
 
@@ -249,10 +248,10 @@ class Answer {
 		$TBL_ANSWER = Database::get_course_table(TABLE_QUIZ_ANSWER);
 
 		$auto_id = intval($auto_id);
-		$sql="SELECT id, answer FROM $TBL_ANSWER WHERE c_id = {$this->course_id} AND id_auto='$auto_id'";
+		$sql="SELECT id, answer, id_auto FROM $TBL_ANSWER WHERE c_id = {$this->course_id} AND id_auto='$auto_id'";
 		$rs = Database::query($sql);
 
-		if (Database::num_rows($rs)>0) {
+		if (Database::num_rows($rs) > 0) {
 			$row = Database::fetch_array($rs);
 			return $row;
 		}
@@ -279,7 +278,8 @@ class Answer {
 	 * @author Yannick Warnier <ywarnier@beeznest.org>
 	 * @return array	List of answers where each answer is an array of (id, answer, comment, grade) and grade=weighting
 	 */
-	 function getAnswersList($decode = false) {
+	 function getAnswersList($decode = false)
+     {
 	 	$list = array();
 	 	for($i = 1; $i<=$this->nbrAnswers;$i++){
 	 		if(!empty($this->answer[$i])){
@@ -291,14 +291,14 @@ class Answer {
 	 			}
 
 	 			$list[] = array(
-						'id'            => $i,
-						'answer'        => $this->answer[$i],
-						'comment'       => $this->comment[$i],
-						'grade'         => $this->weighting[$i],
-						'hotspot_coord' => $this->hotspot_coordinates[$i],
-						'hotspot_type'	=> $this->hotspot_type[$i],
-						'correct'		=> $this->correct[$i],
-						'destination'	=> $this->destination[$i]
+                    'id'            => $i,
+                    'answer'        => $this->answer[$i],
+                    'comment'       => $this->comment[$i],
+                    'grade'         => $this->weighting[$i],
+                    'hotspot_coord' => $this->hotspot_coordinates[$i],
+                    'hotspot_type'	=> $this->hotspot_type[$i],
+                    'correct'		=> $this->correct[$i],
+                    'destination'	=> $this->destination[$i]
 				);
 	 		}
 	 	}

+ 36 - 39
main/exercice/exercise.class.php

@@ -1894,20 +1894,13 @@ class Exercise {
      * @todo    reduce parameters of this function
      * @return  string  html code
      */
-    public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array()) {
+    public function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array())
+    {
         global $debug;
         global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
 
         $feedback_type = $this->selectFeedbackType();
 
-        /*
-        if ($from == 'exercise_show') {
-            if (api_is_allowed_to_edit()) {
-                //For teachers
-                $feedback_type = EXERCISE_FEEDBACK_TYPE_END;
-            }
-        }*/
-
         require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
 
         if ($debug) error_log("<------ manage_answer ------> ");
@@ -2055,13 +2048,13 @@ class Exercise {
                         $resultans = Database::query($queryans);
                         $choice = Database::result($resultans,0,"answer");
 
-                        $studentChoice=($choice == $numAnswer)?1:0;
+                        $studentChoice = ($choice == $numAnswer)?1:0;
                         if ($studentChoice) {
                             $questionScore+=$answerWeighting;
                             $totalScore+=$answerWeighting;
                         }
                     } else {
-                        $studentChoice=($choice == $numAnswer)?1:0;
+                        $studentChoice = ($choice == $numAnswer)?1:0;
                         if ($studentChoice) {
                             $questionScore+=$answerWeighting;
                             $totalScore+=$answerWeighting;
@@ -2069,7 +2062,7 @@ class Exercise {
                     }
                     break;
                 // for multiple answers
-                case MULTIPLE_ANSWER_TRUE_FALSE :
+                case MULTIPLE_ANSWER_TRUE_FALSE:
                     if ($from_database) {
                         $choice = array();
                         $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." and question_id = ".$questionId;
@@ -2103,7 +2096,7 @@ class Exercise {
                     }
                     $totalScore = $questionScore;
                     break;
-                case MULTIPLE_ANSWER : //2
+                case MULTIPLE_ANSWER: //2
                     if ($from_database) {
                         $choice = array();
                         $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
@@ -2131,7 +2124,7 @@ class Exercise {
 
                     if ($debug) error_log("studentChoice: $studentChoice");
                     break;
-                case GLOBAL_MULTIPLE_ANSWER :
+                case GLOBAL_MULTIPLE_ANSWER:
                     if ($from_database) {
                         $choice = array();
                         $queryans = "SELECT answer FROM $TBL_TRACK_ATTEMPT WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
@@ -2212,7 +2205,7 @@ class Exercise {
                             }
                         }
                     } else {
-                        $studentChoice=$choice[$numAnswer];
+                        $studentChoice = $choice[$numAnswer];
                         if ($answerCorrect == 1) {
                             if ($studentChoice) {
                                 $real_answers[$answerId] = true;
@@ -2229,7 +2222,7 @@ class Exercise {
                     }
                     break;
                 // for fill in the blanks
-                case FILL_IN_BLANKS :
+                case FILL_IN_BLANKS:
                     // the question is encoded like this
                     // [A] B [C] D [E] F::10,10,10@1
                     // number 1 before the "@" means that is a switchable fill in blank question
@@ -2370,7 +2363,7 @@ class Exercise {
                     }
                     break;
                 // for free answer
-                case FREE_ANSWER :
+                case FREE_ANSWER:
                     if ($from_database) {
                         $query  = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
                         $resq   = Database::query($query);
@@ -2397,7 +2390,7 @@ class Exercise {
                         }
                     }
                     break;
-                case ORAL_EXPRESSION :
+                case ORAL_EXPRESSION:
                     if ($from_database) {
                         $query  = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
                         $resq   = Database::query($query);
@@ -2421,18 +2414,20 @@ class Exercise {
                         }
                     }
                     break;
-                // for matching
-                case MATCHING :
+                case MATCHING:
                     if ($from_database) {
-                        $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct=0';
+
+                        $sql_answer = 'SELECT id, answer, id_auto FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct = 0';
                         $res_answer = Database::query($sql_answer);
-                        // getting the real answer
-                        $real_list =array();
+                        // Getting the real answer
+                        $real_list = array();
                         while ($real_answer = Database::fetch_array($res_answer)) {
-                            $real_list[$real_answer['id']]= $real_answer['answer'];
+                            $real_list[$real_answer['id']] = $real_answer['answer'];
                         }
-                        $sql_select_answer = 'SELECT id, answer, correct, id_auto FROM '.$table_ans.'
-                                              WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct <> 0 ORDER BY id_auto';
+
+                        $sql_select_answer = 'SELECT id, answer, correct, id_auto, ponderation FROM '.$table_ans.'
+                                              WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct <> 0
+                                              ORDER BY id_auto';
                         $res_answers = Database::query($sql_select_answer);
 
                         $questionScore = 0;
@@ -2444,22 +2439,27 @@ class Exercise {
                             $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
 
                             $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
-                                                WHERE exe_id = '$exeId' AND question_id = '$questionId' AND position='$i_answer_id_auto'";
-
+                                                WHERE exe_id = '$exeId' AND question_id = '$questionId' AND position = '$i_answer_id_auto'";
                             $res_user_answer = Database::query($sql_user_answer);
 
                             if (Database::num_rows($res_user_answer)>0 ) {
-                                $s_user_answer = Database::result($res_user_answer,0,0); //  rich - good looking
+                                $s_user_answer = Database::result($res_user_answer, 0, 0); //  rich - good looking
+
+                                //$s_user_answer = Database::result($res_user_answer, 0, 1); //  rich - good looking
                             } else {
                                 $s_user_answer = 0;
                             }
-                            $i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
+
+                            //$i_answerWeighting = $objAnswerTmp->selectWeighting($i_answer_id);
+                            $i_answerWeighting = $a_answers['ponderation'];
+
                             $user_answer = '';
+
                             if (!empty($s_user_answer)) {
                                 if ($s_user_answer == $i_answer_correct_answer) {
                                     $questionScore  += $i_answerWeighting;
                                     $totalScore     += $i_answerWeighting;
-                                    $user_answer = '<span>'.$real_list[$i_answer_correct_answer].'</span>';
+                                    $user_answer = '<span>'.$real_list[$i_answer_id].'</span>';
                                 } else {
                                     $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
                                 }
@@ -2474,22 +2474,22 @@ class Exercise {
                                 echo '</tr>';
                             }
                         }
-                        break(2); //break the switch and the "for" condition
+                        break(2); // break the switch and the "for" condition
                     } else {
-                        $numAnswer=$objAnswerTmp->selectAutoId($answerId);
+                        $numAnswer = $objAnswerTmp->selectAutoId($answerId);
                         if ($answerCorrect) {
                             if ($answerCorrect == $choice[$numAnswer]) {
                                 $questionScore  += $answerWeighting;
                                 $totalScore     += $answerWeighting;
+
                                 $user_answer = '<span>'.$answer_matching[$choice[$numAnswer]].'</span>';
                             } else {
                                 $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$choice[$numAnswer]].'</span>';
                             }
-                            $matching[$numAnswer] =  $choice[$numAnswer];
+                            $matching[$numAnswer] = $choice[$numAnswer];
                         }
                         break;
                     }
-                // for hotspot with no order
                 case HOT_SPOT :
                     if ($from_database) {
                         if ($show_result) {
@@ -2990,9 +2990,8 @@ class Exercise {
 
         //Fixes multiple answer question in order to be exact
         if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
-            //var_dump($answer_correct_array, $real_answers);
             $diff = @array_diff($answer_correct_array, $real_answers);
-            //var_dump($diff);
+
             /*
              * All good answers or nothing works like exact
             $counter = 1;
@@ -3181,8 +3180,6 @@ class Exercise {
         }
         unset ($objAnswerTmp);
 
-
-
         $totalWeighting += $questionWeighting;
         // Store results directly in the database
         // For all in one page exercises, the results will be

+ 64 - 35
main/exercice/exercise.lib.php

@@ -87,35 +87,46 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
 
     	if ($answerType == MATCHING) {
             $s .= '<table class="data_table">';
+            // Iterate through answers
+    		$x = 1;
+            //mark letters for each answer
+    		$letter = 'A';
+    		$answer_matching = array();
+            $cpt1 = array();
+            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
+                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
+                $numAnswer = $objAnswerTmp->selectAutoId($answerId);
+
+                $answer = $objAnswerTmp->selectAnswer($answerId);
+                if ($answerCorrect == 0) {
+                    // options (A, B, C, ...) that will be put into the list-box
+                    // have the "correct" field set to 0 because they are answer
+                    $cpt1[$x] = $letter;
+    				$answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer);
+                    $x++;
+                    $letter++;
+                }
+            }
 
-    		$x = 1; //iterate through answers
-    		$letter = 'A'; //mark letters for each answer
-    		$answer_matching = $cpt1 = array();
-
-    		for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
-    			$answerCorrect = $objAnswerTmp->isCorrect($answerId);
-    			$numAnswer = $objAnswerTmp->selectAutoId($answerId);
-    			$answer=$objAnswerTmp->selectAnswer($answerId);
-    			if ($answerCorrect==0) {
-    				// options (A, B, C, ...) that will be put into the list-box
-    				// have the "correct" field set to 0 because they are answer
-    				$cpt1[$x] = $letter;
-    				$answer_matching[$x]=$objAnswerTmp->selectAnswerByAutoId($numAnswer);
-    				$x++; $letter++;
-    			}
-    		}
-    		$i = 1;
+            $i = 1;
 
-    		$select_items[0]['id'] = 0;
-    		$select_items[0]['letter'] = '--';
-    		$select_items[0]['answer'] = '';
+            $select_items[0]['id'] = 0;
+            $select_items[0]['letter'] = '--';
+            $select_items[0]['answer'] = '';
+            foreach ($answer_matching as $id => $value) {
+                $select_items[$i]['id'] 	= $value['id'];
+                $select_items[$i]['letter'] = $cpt1[$id];
+                $select_items[$i]['answer'] = $value['answer'];
+                $i++;
+            }
+
+            $user_choice_array_position = array();
+            if (!empty($user_choice)) {
+                foreach ($user_choice as $item) {
+                    $user_choice_array_position[$item['position']] = $item['answer'];
+                }
+            }
 
-    		foreach ($answer_matching as $id => $value) {
-    			$select_items[$i]['id'] 	= $value['id'];
-    			$select_items[$i]['letter'] = $cpt1[$id];
-    			$select_items[$i]['answer'] = $value['answer'];
-    			$i ++;
-    		}
     		$num_suggestions = ($nbrAnswers - $x) + 1;
 
     	} elseif ($answerType == FREE_ANSWER) {
@@ -196,6 +207,7 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
         	}
         }
 
+
     	for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
     		$answer          = $objAnswerTmp->selectAnswer($answerId);
     		$answerCorrect   = $objAnswerTmp->isCorrect($answerId);
@@ -407,6 +419,7 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
     				$student_answer_list = $correct_answer_list[0];
                 }
 
+
     			if (!empty($correct_answer_list) && !empty($student_answer_list)) {
     			    $correct_answer_list = $correct_answer_list[0];
     			    $i = 0;
@@ -424,13 +437,26 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
     			            	$value = str_replace('&nbsp;', '',  trim($value[0]));
     			            }
                             $correct_item = preg_quote($correct_item);
-                            $correct_item = api_preg_replace('|/|', '\/', $correct_item);   // to prevent error if there is a / in the text to find
-    			            $answer = api_preg_replace('/'.$correct_item.'/', Display::input('text', "choice[$questionId][]", $value), $answer, 1);
+                            // to prevent error if there is a / in the text to find
+                            $correct_item = api_preg_replace('|/|', '\/', $correct_item);
+
+                            $size = strlen($correct_item) * 10 + 10;
+                            $attributes['style'] = 'width: '.$size.'px';
+
+    			            $answer = api_preg_replace('/'.$correct_item.'/', Display::input('text', "choice[$questionId][]", $value, $attributes), $answer, 1);
     			        }
     			        $i++;
     			    }
     			} else {
-    				$answer = api_preg_replace('/\[[^]]+\]/', Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+
+                    foreach ($correct_answer_list[0] as $item) {
+                        $size = strlen($item) * 10 + 10;
+                        $attributes['style'] = 'width: '.$size.'px';
+                        $pattern = '/\['.$item.'+\]/';
+                        $answer = api_preg_replace($pattern, Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+                    }
+                    //$answer = api_preg_replace('/\[[^]]+\]/', Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+
     			}
     			$s .= $answer;
             } elseif ($answerType == MATCHING) {
@@ -451,7 +477,7 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
     			            <select name="choice['.$questionId.']['.$numAnswer.']">';
 
     				// fills the list-box
-    				foreach ($select_items as $key=>$val) {
+    				foreach ($select_items as $key => $val) {
     					// set $debug_mark_answer to true at function start to
     					// show the correct answer with a suffix '-x'
     					$selected = '';
@@ -460,16 +486,18 @@ function showQuestion($questionId, $only_questions = false, $origin = false, $cu
     							$selected = 'selected="selected"';
     						}
     					}
-    					if (isset($user_choice[$matching_correct_answer]) && $val['id'] == $user_choice[$matching_correct_answer]['answer']) {
+                        //$user_choice_array_position
+                        if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
     					    $selected = 'selected="selected"';
     					}
-    					$s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].$help.'</option>';
+    					/*if (isset($user_choice_array[$matching_correct_answer]) && $val['id'] == $user_choice_array[$matching_correct_answer]['answer']) {
+    					    $selected = 'selected="selected"';
+    					}*/
+    					$s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].'</option>';
 
     				}  // end foreach()
 
     				$s .= '</select></td>';
-    				//print_r($select_items);
-    				//right part (answers)
     				$s.='<td width="45%" valign="top" >';
     				if (isset($select_items[$lines_count])) {
     					$s.='<span style="float:left; width:5%;"><b>'.$select_items[$lines_count]['letter'].'.</b></span>'.
@@ -2133,13 +2161,14 @@ function display_question_list_by_attempt($objExercise, $exe_id, $save_user_resu
         foreach ($question_list as $questionId) {
 
             // creates a temporary Question object
-            $objQuestionTmp = Question :: read($questionId);
+            $objQuestionTmp = Question::read($questionId);
 
             //this variable commes from exercise_submit_modal.php
             ob_start();
 
             // We're inside *one* question. Go through each possible answer for this question
             $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null, 'exercise_result', array(), $save_user_result, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result);
+
             if (empty($result)) {
                 continue;
             }

+ 10 - 9
main/exercice/exercise_result.php

@@ -30,12 +30,12 @@ require_once '../inc/global.inc.php';
 require_once 'exercise.lib.php';
 
 if ($_GET['origin']=='learnpath') {
-	require_once '../newscorm/learnpath.class.php';
-	require_once '../newscorm/learnpathItem.class.php';
-	require_once '../newscorm/scorm.class.php';
-	require_once '../newscorm/scormItem.class.php';
-	require_once '../newscorm/aicc.class.php';
-	require_once '../newscorm/aiccItem.class.php';
+    require_once '../newscorm/learnpath.class.php';
+    require_once '../newscorm/learnpathItem.class.php';
+    require_once '../newscorm/scorm.class.php';
+    require_once '../newscorm/scormItem.class.php';
+    require_once '../newscorm/aicc.class.php';
+    require_once '../newscorm/aiccItem.class.php';
 }
 require_once api_get_path(LIBRARY_PATH).'exercise_show_functions.lib.php';
 require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
@@ -133,10 +133,11 @@ if ($objExercise->selectAttempts() > 0) {
 
 Display :: display_normal_message(get_lang('Saved').'<br />',false);
 
-//Display questions
+// Display questions
 display_question_list_by_attempt($objExercise, $exe_id, true);
 
 //If is not valid
+
 $session_control_key = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
 if (isset($session_control_key) && !exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) {
 	$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
@@ -163,7 +164,7 @@ if ($origin != 'learnpath') {
 	$lp_mode =  $_SESSION['lp_mode'];
 	$url = '../newscorm/lp_controller.php?cidReq='.api_get_course_id().'&action=view&lp_id='.$learnpath_id.'&lp_item_id='.$learnpath_item_id.'&exeId='.$exercise_stat_info['exe_id'].'&fb_type='.$objExercise->feedback_type;
 	$href = ($lp_mode == 'fullscreen')?' window.opener.location.href="'.$url.'" ':' top.location.href="'.$url.'"';
-    
+
     if (api_is_allowed_to_session_edit()) {
         Session::erase('objExercise');
         Session::erase('exe_id');
@@ -172,4 +173,4 @@ if ($origin != 'learnpath') {
 	echo "<script>window.parent.API.void_save_asset('$total_score', '$total_weight', 0, 'completed');</script>";
     echo '<script type="text/javascript">'.$href.'</script>';
 	echo '</body></html>';
-}
+}

+ 6 - 6
main/exercice/exercise_show.php

@@ -61,7 +61,7 @@ if ( empty ( $action ) ) {              $action         = $_REQUEST['action']; }
 $id = intval($_REQUEST['id']); //exe id
 
 if (empty($id)) {
-	api_not_allowed(true);
+    api_not_allowed(true);
 }
 
 if (api_is_course_session_coach(api_get_user_id(), api_get_course_id(), api_get_session_id())) {
@@ -70,7 +70,7 @@ if (api_is_course_session_coach(api_get_user_id(), api_get_course_id(), api_get_
     }
 }
 
-$is_allowedToEdit = api_is_allowed_to_edit(null,true) || $is_courseTutor || api_is_session_admin() || api_is_drh();
+$is_allowedToEdit = api_is_allowed_to_edit(null, true) || $is_courseTutor || api_is_session_admin() || api_is_drh();
 
 //Getting results from the exe_id. This variable also contain all the information about the exercise
 $track_exercise_info = get_exercise_track_exercise_info($id);
@@ -428,12 +428,12 @@ foreach ($questionList as $questionId) {
             </tr></table>';
 
             if ($answerType!= HOT_SPOT_DELINEATION) {
-                $item_list=explode('@@',$destination);
-                //print_R($item_list);
+                $item_list = explode('@@',$destination);
+
                 $try = $item_list[0];
                 $lp = $item_list[1];
-                $destinationid= $item_list[2];
-                $url=$item_list[3];
+                $destinationid = $item_list[2];
+                $url = $item_list[3];
                 $table_resume='';
             } else {
                 if ($next==0) {

+ 6 - 6
main/exercice/exercise_submit.php

@@ -215,7 +215,6 @@ if ($objExercise->selectAttempts() > 0) {
 if ($debug) { error_log("4. Setting the exe_id: $exe_id");} ;
 
 //5. Getting user exercise info (if the user took the exam before) - generating exe_id
-//var_dump($learnpath_id.' - '.$learnpath_item_id.' - '.$learnpath_item_view_id);
 $exercise_stat_info = $objExercise->get_stat_track_exercise_info($learnpath_id, $learnpath_item_id, $learnpath_item_view_id);
 
 $clock_expired_time = null;
@@ -875,16 +874,16 @@ if (!empty($error)) {
             }
 
             function save_now_all(validate) {
-            	//1. Input choice
+            	// 1. Input choice.
            		var my_choice = $(\'*[name*="choice"]\').serialize();
 
-           		//2. Reminder
+           		// 2. Reminder.
            		var remind_list = $(\'*[name*="remind_list"]\').serialize();
 
-           		//3. Hotspots
+           		// 3. Hotspots.
            		var hotspot = $(\'*[name*="hotspot"]\').serialize();
 
-           		//Question list
+           		// Question list.
            		var question_list = ['.implode(',', $questionList).'];
 
            		var free_answers = {};
@@ -901,7 +900,8 @@ if (!empty($error)) {
                    		}
                		}
            		});
-           		//lok+(fgt)= data base
+
+           		// lok+(fgt)= data base
            		free_answers = $.param(free_answers);
 
           		$("#save_all_reponse").html("'.addslashes(Display::return_icon('loading1.gif')).'");

+ 71 - 79
main/exercice/question_pool.php

@@ -27,7 +27,7 @@ require_once 'exercise.lib.php';
 
 $this_section = SECTION_COURSES;
 
-$is_allowedToEdit=api_is_allowed_to_edit(null,true);
+$is_allowedToEdit = api_is_allowed_to_edit(null,true);
 
 if (empty($delete)) {
     $delete = intval($_GET['delete']);
@@ -112,7 +112,7 @@ if ($is_allowedToEdit) {
 			// destruction of the Question object
 			unset($new_question_obj);
 			unset($old_question_obj);
-            if (!$objExcercise instanceOf Exercise) {
+            if (!$objExercise instanceOf Exercise) {
                 $objExercise = new Exercise();
                 $objExercise->read($fromExercise);
             }
@@ -142,7 +142,7 @@ if ($is_allowedToEdit) {
 		// destruction of the Question object
 		unset($objQuestionTmp);
 
-        if (!$objExcercise instanceOf Exercise) {
+        if (!$objExercise instanceOf Exercise) {
         	$objExercise = new Exercise();
             $objExercise->read($fromExercise);
         }
@@ -162,22 +162,6 @@ if ($is_allowedToEdit) {
 			$current_course     = api_get_course_info();
 
 			foreach ($question_data as $old_question_id) {
-				/*
-				$recup = intval($recup);
-				// if the question exists
-				if($objQuestionTmp = Question :: read($recup)) {
-					// adds the exercise ID represented by $fromExercise into the list of exercises for the current question
-					$objQuestionTmp->addToList($fromExercise);
-				}
-				// destruction of the Question object
-				unset($objQuestionTmp);
-		        if(!$objExcercise instanceOf Exercise) {
-		        	$objExercise = new Exercise();
-		            $objExercise->read($fromExercise);
-		        }
-				// adds the question ID represented by $recup into the list of questions for the current exercise
-				$objExercise->addToList($recup);
-				*/
 
 				//Reading the source question
 				$old_question_obj = Question::read($old_question_id, $origin_course_id);
@@ -202,7 +186,7 @@ if ($is_allowedToEdit) {
 					unset($new_question_obj);
 					unset($old_question_obj);
 
-					if (!$objExcercise instanceOf Exercise) {
+					if (!$objExercise instanceOf Exercise) {
 						$objExercise = new Exercise();
 						$objExercise->read($fromExercise);
 					}
@@ -210,8 +194,6 @@ if ($is_allowedToEdit) {
 			}
 		}
 		Session::write('objExercise',$objExercise);
-//		header("Location: admin.php?".api_get_cidreq()."&exerciseId=$fromExercise");
-//		exit();
 	}
 }
 
@@ -231,7 +213,7 @@ if (!$is_allowedToEdit) {
 $confirmYourChoice = addslashes(api_htmlentities(get_lang('ConfirmYourChoice'),ENT_QUOTES,$charset));
 
 $htmlHeadXtra[] = "
-<script type='text/javascript'>
+<script>
 	function submit_form(obj) {
 		document.question_pool.submit();
 	}
@@ -261,8 +243,7 @@ echo '<div class="actions">';
 	if (isset($fromExercise) && $fromExercise > 0) {
 		echo '<a href="admin.php?'.api_get_cidreq().'&exerciseId='.$fromExercise.'">'.Display::return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).'</a>';
 		$titleAdd = get_lang('AddQuestionToTest');
-	}
-	else {
+    } else {
 		echo '<a href="exercice.php?'.api_get_cidReq().'">'.Display::return_icon('back.png', get_lang('BackToExercisesList'),'',ICON_SIZE_MEDIUM).'</a>';
 		echo "<a href='admin.php?exerciseId=0'>".Display::return_icon('add_question.gif', get_lang('NewQu'), '', 32)."</a>";
 		$titleAdd = get_lang('ManageAllQuestions');
@@ -429,21 +410,18 @@ if ($exerciseId > 0) {
 	            $TBL_QUESTIONS qu
 	            $from
 	        WHERE
-	            qt.question_id=qu.id
+	            qt.question_id = qu.id
 	            AND qt.exercice_id=$exerciseId
 	            AND qt.c_id=$selected_course
 	            AND qu.c_id=$selected_course
 	            $where
-	        ORDER BY
-	            question_order";
+            ORDER BY question_order";
     $result=Database::query($sql);
     while($row = Database::fetch_array($result, 'ASSOC')) {
         $main_question_list[] = $row;
     }
 } elseif ($exerciseId == -1) {
-	//
-	// if we have selected the option 'Orphan questions' in the list-box 'Filter'
-	//
+	// If we have selected the option 'Orphan questions' in the list-box 'Filter'
 	$level_where = '';
 	$from = '';
 	if (isset($courseCategoryId) && $courseCategoryId > 0) {
@@ -457,22 +435,47 @@ if ($exerciseId > 0) {
 	if (isset($answerType) && $answerType >0 -1 ) {
 		$answer_where = ' AND type='.$answerType;
 	}
-	$sql = "SELECT DISTINCT * FROM $TBL_QUESTIONS qu $from WHERE qu.c_id=$selected_course AND qu.id NOT IN (SELECT question_id FROM $TBL_EXERCICE_QUESTION WHERE c_id=$selected_course ) $level_where $answer_where";
+	/*$sql = "SELECT DISTINCT * FROM $TBL_QUESTIONS qu $from
+            WHERE qu.c_id = $selected_course AND qu.id NOT IN (
+              SELECT question_id FROM $TBL_EXERCICE_QUESTION
+              WHERE c_id=$selected_course
+            ) $level_where $answer_where";*/
+
+    // @todo fix this query with the new id field
+
+    $sql = " (
+                SELECT q.* FROM $TBL_QUESTIONS q INNER JOIN $TBL_EXERCICE_QUESTION r
+                ON (q.c_id = r.c_id AND q.id = r.question_id)
+                INNER JOIN $TBL_EXERCICES ex
+                ON (ex.id = r.exercice_id AND ex.c_id = r.c_id ) $from
+                WHERE ex.c_id = '$selected_course' AND ex.active = '-1'   $level_where $answer_where
+             )
+             UNION
+             (
+                SELECT q.* FROM $TBL_QUESTIONS q
+                LEFT OUTER JOIN $TBL_EXERCICE_QUESTION r
+                ON (q.c_id = r.c_id AND q.id = r.question_id)
+                WHERE q.c_id = '$selected_course' AND r.question_id is null $level_where $answer_where
+             )
+             UNION
+             (
+                SELECT q.* FROM $TBL_QUESTIONS q
+                INNER JOIN $TBL_EXERCICE_QUESTION r
+                ON (q.c_id = r.c_id AND q.id = r.question_id)
+                WHERE r.c_id = '$selected_course' AND (r.exercice_id = '-1' OR r.exercice_id = '0') $level_where $answer_where
+             )";
     $result = Database::query($sql);
     while($row = Database::fetch_array($result, 'ASSOC')) {
         $main_question_list[] = $row;
     }
-}
-else {
-	//
+} else {
 	// All tests for selected course
-	//
-	// if we have not selected any option in the list-box 'Filter'
+    // If we have not selected any option in the list-box 'Filter'
 	$filter = '';
 	$from = '';
 	if (isset($courseCategoryId) && $courseCategoryId > 0) {
 		$from = ", $TBL_COURSE_REL_CATEGORY crc ";
-		$filter .= " AND crc.c_id=$selected_course AND crc.question_id=qu.id AND crc.category_id=$courseCategoryId";
+		$filter .= " AND crc.c_id = $selected_course AND crc.question_id = qu.id AND crc.category_id = $courseCategoryId";
 	}
 	if (isset($exerciseLevel) && $exerciseLevel != -1) {
 		$filter .= ' AND level='.$exerciseLevel.' ';
@@ -480,14 +483,6 @@ else {
 	if (isset($answerType) && $answerType > 0) {
 		$filter .= ' AND qu.type='.$answerType.' ';
 	}
-//	// why these lines ?
-//  if ($objExercise->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
-//      $filter .= ' AND qu.type <> '.HOT_SPOT_DELINEATION.' ';
-//  }
-//  // fwhy
-  //
-  // if in session
-  //
   if (!empty($session_id) && $session_id != '-1') {
     $main_question_list = array();
     if (!empty($course_list))
@@ -541,8 +536,14 @@ else {
   else {
   	//
     // All tests for the course selected, not in session
-    //
-  	$sql = "SELECT DISTINCT qu.id, question, qu.type, level, q.session_id FROM $TBL_QUESTIONS as qu, $TBL_EXERCICE_QUESTION as qt, $TBL_EXERCICES as q $from WHERE qu.c_id=$selected_course AND qt.c_id=$selected_course AND q.c_id=$selected_course AND qu.id = qt.question_id AND q.id = qt.exercice_id $filter ORDER BY session_id ASC";
+            $sql = "SELECT DISTINCT qu.id, question, qu.type, level, q.session_id
+                    FROM $TBL_QUESTIONS as qu, $TBL_EXERCICE_QUESTION as qt, $TBL_EXERCICES as q $from
+                    WHERE   qu.c_id = $selected_course AND
+                            qt.c_id = $selected_course AND
+                            q.c_id = $selected_course AND
+                            qu.id = qt.question_id AND
+                            q.id = qt.exercice_id $filter
+                    ORDER BY session_id ASC";
   	$result = Database::query($sql);
   	while($row = Database::fetch_array($result, 'ASSOC')) {
   		$main_question_list[] = $row;
@@ -578,31 +579,26 @@ if ($fromExercise <= 0) { // NOT IN A TEST - IN THE COURSE
 		$actionIcon1 = "edit";
 		$actionIcon2 = "delete";
 		$questionTagA = 1;	// we are in the course, question title can be a link to the question edit page
-	}
-	else { // NOT IN A TEST - NOT IN THE COURSE
+    } else { // NOT IN A TEST - NOT IN THE COURSE
 		$actionLabel = get_lang('Reuse');
 		$actionIcon1 = get_lang('MustBeInATest');
 		$actionIcon2 = "";
 		$questionTagA = 0;	// we are not in this course, to messy if we link to the question in another course
 	}
-}
-else { // IN A TEST - IN THE COURSE
+} else { // IN A TEST - IN THE COURSE
 	if ($selected_course == api_get_course_int_id()) {
 		$actionLabel = get_lang('Reuse');
 		$actionIcon1 = "add";
 		$actionIcon2 = "";
 		$questionTagA = 1;
-	}
-	else { // IN A TEST - NOT IN THE COURSE
+    } else { // IN A TEST - NOT IN THE COURSE
 		$actionLabel = get_lang('Reuse');
 		$actionIcon1 = "clone";
 		$actionIcon2 = "";
 		$questionTagA = 0;
 	}
 }
-//
-// display table
-//
+// Display table
 $header = array();
 $header[] = array(get_lang('QuestionUpperCaseFirstLetter'), false, array("style"=>"text-align:center"), '');
 $header[] = array(get_lang('Type'), false, array("style"=>"text-align:center"), array("style"=>"text-align:center"), '');
@@ -677,7 +673,6 @@ function reset_menu_exo_lvl_type() {
 	$courseCategoryId = 0;
 }
 
-//
 // return the <a> link to admin question, if needed
 // hubert.borderiou 13-10-2011
 function get_a_tag_for_question($in_addA, $in_fromex, $in_questionid, $in_questiontype, $in_questionname) {
@@ -711,23 +706,21 @@ $session_id, $exerciseId);
 
 */
 
-//
-// return the <a> html code for delete, add, clone, edit a question
-// hubert.borderiou 13-10-2011
-// in_action = the code of the action triggered by the button
-// from_exercice = the id of the current exercice from which we click on question pool
-// in_questionid = the id of the current question
-// in_questiontype = the code of the type of the current question
-// in_questionname = the name of the question
-// in_selected_course = the if of the course chosen in the FILTERING MENU
-// in_courseCategoryId = the id of the category chosen in the FILTERING MENU
-// in_exerciseLevel = the level of the exercice chosen in the FILTERING MENU
-// in_answerType = the code of the type of the question chosen in the FILTERING MENU
-// in_session_id = the id of the session_id chosen in the FILTERING MENU
-// in_exercice_id = the id of the exercice chosen in the FILTERING MENU
-function get_action_icon_for_question($in_action, $from_exercice, $in_questionid, $in_questiontype, $in_questionname,
-    $in_selected_course, $in_courseCategoryId, $in_exerciseLevel, $in_answerType, $in_session_id, $in_exercice_id
-) {
+/*
+    Return the <a> html code for delete, add, clone, edit a question hubert.borderiou 13-10-2011
+    in_action = the code of the action triggered by the button
+    from_exercice = the id of the current exercice from which we click on question pool
+    in_questionid = the id of the current question
+    in_questiontype = the code of the type of the current question
+    in_questionname = the name of the question
+    in_selected_course = the if of the course chosen in the FILTERING MENU
+    in_courseCategoryId = the id of the category chosen in the FILTERING MENU
+    in_exerciseLevel = the level of the exercice chosen in the FILTERING MENU
+    in_answerType = the code of the type of the question chosen in the FILTERING MENU
+    in_session_id = the id of the session_id chosen in the FILTERING MENU
+    in_exercice_id = the id of the exercice chosen in the FILTERING MENU
+ */
+function get_action_icon_for_question($in_action, $from_exercice, $in_questionid, $in_questiontype, $in_questionname, $in_selected_course, $in_courseCategoryId, $in_exerciseLevel, $in_answerType, $in_session_id, $in_exercice_id) {
 
 	$res = "";
 	$getParams = "&selected_course=$in_selected_course&courseCategoryId=$in_courseCategoryId&exerciseId=$in_exercice_id&exerciseLevel=$in_exerciseLevel&answerType=$in_answerType&session_id=$in_session_id";
@@ -749,8 +742,7 @@ function get_action_icon_for_question($in_action, $from_exercice, $in_questionid
 				$res = "<a href='".api_get_self()."?".api_get_cidreq()."&recup=$in_questionid&fromExercise=$from_exercice$getParams'>";
 				$res .= Display::return_icon("view_more_stats.gif", get_lang('InsertALinkToThisQuestionInTheExercise'));
 				$res .= "</a>";
-			}
-			else {
+            } else {
 				$res = "-";
 			}
 			unset($myObjEx);
@@ -767,8 +759,8 @@ function get_action_icon_for_question($in_action, $from_exercice, $in_questionid
 	return $res;
 }
 
-// return the icon for the question type
-// hubert.borderiou 13-10-2011
+/* return the icon for the question type
+ hubert.borderiou 13-10-2011*/
 function get_question_type_for_question($in_selectedcourse, $in_questionid) {
 	$myObjQuestion = Question::read($in_questionid, $in_selectedcourse);
     $questionType = null;

+ 67 - 69
main/exercice/testcategory.class.php

@@ -2,13 +2,12 @@
 /* For licensing terms, see /license.txt */
 /** @author hubert.borderiou  **/
 
-if (!class_exists('Testcategory')):
-
-class Testcategory {
+class Testcategory
+{
 	public $id;
 	public $name;
 	public $description;
-	
+
 	/**
 	 * Constructor of the class Category
 	 * @author - Hubert Borderiou
@@ -29,7 +28,7 @@ class Testcategory {
 			$this->description = $in_description;
 		}
 	}
-	
+
 	/** return the Testcategory object with id=in_id
 	 */
 	function getCategory($in_id) {
@@ -45,7 +44,7 @@ class Testcategory {
 			$this->description  = $row['description'];
 		}
 	}
-	
+
 	/** add Testcategory in the database if name doesn't already exists
 		*/
 	function addCategoryInBDD() {
@@ -67,13 +66,13 @@ class Testcategory {
 		}
 		else {
 			return false;
-		}		
+		}
 	}
-	
-	/** 
+
+	/**
      * Removes the category with id=in_id from the database if no question use this category
      * @todo I'm removing the $in_id parameter because it seems that you're using $this->id instead of $in_id after confirmation delete this
-     * jmontoya 
+     * jmontoya
 	 */
 	//function removeCategory($in_id) {
     function removeCategory() {
@@ -85,11 +84,11 @@ class Testcategory {
 			return false;
 		} else {
 			return true;
-		}		
+		}
 	}
-	
 
-	/** modify category name or description of category with id=in_id 
+
+	/** modify category name or description of category with id=in_id
 	 */
 	//function modifyCategory($in_id, $in_name, $in_description) {
     function modifyCategory() {
@@ -106,8 +105,8 @@ class Testcategory {
 			return true;
 		}
 	}
-	
-	/** 
+
+	/**
      * Gets the number of question of category id=in_id
      * @todo I'm removing the $in_id parameter because it seems that you're using $this->id instead of $in_id after confirmation delete this
      * jmontoya
@@ -121,15 +120,15 @@ class Testcategory {
 		$row = Database::fetch_array($res);
 		return $row['nb'];
 	}
-	
+
 	function display($in_color="#E0EBF5") {
 		echo "<textarea style='background-color:$in_color; width:60%; height:100px;'>";
 		print_r($this);
 		echo "</textarea>";
 	}
-	
-	
-	
+
+
+
 	/** return an array of all Category objects in the database
 	If in_field=="" Return an array of all category objects in the database
 	Otherwise, return an array of all in_field value in the database (in_field = id or name or description)
@@ -137,8 +136,8 @@ class Testcategory {
 	public static function getCategoryListInfo($in_field="", $in_courseid="") {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
-		}		
-		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);		
+		}
+		$t_cattable = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$in_field = Database::escape_string($in_field);
 		$tabres = array();
 		if ($in_field=="") {
@@ -158,7 +157,7 @@ class Testcategory {
 		}
 		return $tabres;
 	}
-		
+
 
 	/**
 	 Return the testcategory id for question with question_id = $in_questionid
@@ -170,7 +169,7 @@ class Testcategory {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
 		}
-		$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);		
+		$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
 		$question_id = Database::escape_string($in_questionid);
 		$sql = "SELECT category_id FROM $t_cattable WHERE question_id='$question_id' AND c_id=$in_courseid";
 		$res = Database::query($sql);
@@ -179,9 +178,9 @@ class Testcategory {
 			$result = $data['category_id'];
 		}
 		return $result;
-	}		
-	
-	
+	}
+
+
 	/**
 	 * true if question id has a category
 	 */
@@ -191,8 +190,8 @@ class Testcategory {
 		}
 		return false;
 	}
-	
-	
+
+
 	/**
 	 Return the category name for question with question_id = $in_questionid
 	 In this version, a question has only 1 category.
@@ -201,10 +200,10 @@ class Testcategory {
 	public static function getCategoryNameForQuestion($in_questionid, $in_courseid="") {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
-		}		
+		}
 		$catid = Testcategory::getCategoryForQuestion($in_questionid, $in_courseid);
 		$result = "";	// result
-		$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);		
+		$t_cattable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
 		$catid = Database::escape_string($catid);
 		$sql = "SELECT title FROM $t_cattable WHERE id='$catid' AND c_id=$in_courseid";
 		$res = Database::query($sql);
@@ -214,7 +213,7 @@ class Testcategory {
 		}
 		return $result;
 	}
-	
+
 	/**
 	 * return the list of differents categories ID for a test
 	 * input : test_id
@@ -227,15 +226,15 @@ class Testcategory {
 		$quiz = new Exercise();
 		$quiz->read($in_testid);
 		$tabQuestionList = $quiz->selectQuestionList();
-		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???		
+		// the array given by selectQuestionList start at indice 1 and not at indice 0 !!! ???
 		for ($i=1; $i <= count($tabQuestionList); $i++) {
 			if (!in_array(Testcategory::getCategoryForQuestion($tabQuestionList[$i]), $tabcat)) {
 				$tabcat[] = Testcategory::getCategoryForQuestion($tabQuestionList[$i]);
 			}
 		}
 		return $tabcat;
-	}	
-	
+	}
+
 	/**
 	 * return the list of differents categories NAME for a test
 	 * input : test_id
@@ -261,8 +260,8 @@ class Testcategory {
 	public static function getNumberOfCategoriesForTest($in_testid) {
 		return count(Testcategory::getListOfCategoriesIDForTest($in_testid));
 	}
-	
-	
+
+
 	/**
 	 * return the number of question of a category id in a test
 	 * input : test_id, category_id
@@ -279,10 +278,10 @@ class Testcategory {
 			if (Testcategory::getCategoryForQuestion($tabQuestionList[$i]) == $in_categoryid) {
 				$nbCatResult++;
 			}
-		}		
+		}
 		return $nbCatResult;
 	}
-	
+
 	/**
 	 * return the number of question for a test using random by category
 	 * input  : test_id, number of random question (min 1)
@@ -305,8 +304,8 @@ class Testcategory {
 		}
 		return $nbquestionresult;
 	}
-	
-	
+
+
 	/**
 	 * Return an array (id=>name)
 	 * tabresult[0] = get_lang('NoCategory');
@@ -315,7 +314,7 @@ class Testcategory {
 	static function getCategoriesIdAndName($in_courseid="") {
 		if (empty($in_courseid) || $in_courseid=="") {
 			$in_courseid = api_get_course_int_id();
-		}		
+		}
 	 	$tabcatobject = Testcategory::getCategoryListInfo("", $in_courseid);
 	 	$tabresult = array("0"=>get_lang('NoCategorySelected'));
 	 	for ($i=0; $i < count($tabcatobject); $i++) {
@@ -323,7 +322,7 @@ class Testcategory {
 	 	}
 	 	return $tabresult;
 	}
-	
+
 	/**
 		* return an array of question_id for each category
 		* tabres[0] = array of question id with category id = 0 (i.e. no category)
@@ -336,7 +335,7 @@ class Testcategory {
 		$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
 		$TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
         $in_exerciceId = intval($in_exerciceId);
-		$sql = "SELECT qrc.question_id, qrc.category_id FROM $TBL_QUESTION_REL_CATEGORY qrc, $TBL_EXERCICE_QUESTION eq 
+		$sql = "SELECT qrc.question_id, qrc.category_id FROM $TBL_QUESTION_REL_CATEGORY qrc, $TBL_EXERCICE_QUESTION eq
                 WHERE exercice_id=$in_exerciceId AND eq.question_id=qrc.question_id AND eq.c_id=".api_get_course_int_id()." AND eq.c_id=qrc.c_id ORDER BY category_id, question_id";
 		$res = Database::query($sql);
 		while ($data = Database::fetch_array($res)) {
@@ -347,8 +346,8 @@ class Testcategory {
 		}
 		return $tabres;
 	}
-	
-	
+
+
 	/**
 	 * return a tab of $in_number random elements of $in_tab
 	 */
@@ -360,31 +359,31 @@ class Testcategory {
 		}
 		return $tabres;
 	}
-	
+
 	/**
 	 * display the category
 	 */
 	public static function displayCategoryAndTitle($in_questionID, $in_display_category_name = 1) {
         echo self::returnCategoryAndTitle($in_questionID, $in_display_category_name);
 	}
-    
-    
+
+
     public static function returnCategoryAndTitle($in_questionID, $in_display_category_name = 1) {
-        $is_student = !(api_is_allowed_to_edit(null,true) || api_is_session_admin());	
+        $is_student = !(api_is_allowed_to_edit(null,true) || api_is_session_admin());
         $objExercise = $_SESSION['objExercise'];
         if (!empty($objExercise)) {
             $in_display_category_name = $objExercise->display_category_name;
         }
         $content = null;
 		if (Testcategory::getCategoryNameForQuestion($in_questionID) != "" && ($in_display_category_name == 1 || !$is_student)) {
-            $content .= '<div class="page-header">';            
+            $content .= '<div class="page-header">';
             $content .= '<h4>'.get_lang('Category').": ".Testcategory::getCategoryNameForQuestion($in_questionID).'</h4>';
             $content .= "</div>";
 		}
         return $content;
 	}
-	
-	
+
+
 	/**
 		* Display signs [+] and/or (>0) after question title if question has options
 		* scoreAlwaysPositive and/or uncheckedMayScore
@@ -397,7 +396,7 @@ class Testcategory {
 			echo "<span style='font-size:75%'> [+]</span>";
 		}
 	}
-	
+
 	/**
 	 * sortTabByBracketLabel ($tabCategoryQuestions)
 	 * key of $tabCategoryQuestions are the categopy id (0 for not in a category)
@@ -420,7 +419,7 @@ class Testcategory {
 		}
 		return $tabResult;
 	}
-	
+
 	/**
 		* return total score for test exe_id for all question in the category $in_cat_id for user
 		* If no question for this category, return ""
@@ -431,8 +430,8 @@ class Testcategory {
         $in_cat_id = intval($in_cat_id);
         $in_exe_id = intval($in_exe_id);
         $in_user_id = intval($in_user_id);
-        
-		$query = "SELECT DISTINCT marks, exe_id, user_id, ta.question_id, category_id FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc 
+
+		$query = "SELECT DISTINCT marks, exe_id, user_id, ta.question_id, category_id FROM $tbl_track_attempt ta , $tbl_question_rel_category qrc
                   WHERE ta.question_id=qrc.question_id AND qrc.category_id=$in_cat_id AND exe_id=$in_exe_id AND user_id=$in_user_id";
 		$res = Database::query($query);
 		$totalcatscore = "";
@@ -441,7 +440,7 @@ class Testcategory {
 		}
 		return $totalcatscore;
 	}
-	
+
 
     /**
      * return the number max of question in a category
@@ -462,8 +461,8 @@ class Testcategory {
 		}
         return $res_num_max;
     }
-    
-    /**     
+
+    /**
      * Returns a category summary report
      * @params int exercise id
      * @params array prefilled array with the category_id, score, and weight example: array(1 => array('score' => '10', 'total' => 20));
@@ -471,37 +470,37 @@ class Testcategory {
     public static function get_stats_table_by_attempt($exercise_id, $category_list = array()) {
         if (empty($category_list)) {
             return null;
-        }          
+        }
         $category_name_list = Testcategory::getListOfCategoriesNameForTest($exercise_id);
-                
+
         $table = new HTML_Table(array('class' => 'data_table'));
         $table->setHeaderContents(0, 0, get_lang('Categories'));
         $table->setHeaderContents(0, 1, get_lang('AbsoluteScore'));
         $table->setHeaderContents(0, 2, get_lang('RelativeScore'));
         $row = 1;
-        
+
         $none_category = array();
         if (isset($category_list['none'])) {
-            $none_category = $category_list['none'];                    
-            unset($category_list['none']);            
+            $none_category = $category_list['none'];
+            unset($category_list['none']);
         }
-        
+
         $total = array();
         if (isset($category_list['total'])) {
             $total = $category_list['total'];
             unset($category_list['total']);
         }
         if (count($category_list) > 1) {
-            foreach ($category_list as $category_id => $category_item) {            
+            foreach ($category_list as $category_id => $category_item) {
                 $table->setCellContents($row, 0, $category_name_list[$category_id]);
-                $table->setCellContents($row, 1, show_score($category_item['score'], $category_item['total'], false));            
+                $table->setCellContents($row, 1, show_score($category_item['score'], $category_item['total'], false));
                 $table->setCellContents($row, 2, show_score($category_item['score'], $category_item['total'], true, false, true));
                 $row++;
             }
 
             if (!empty($none_category)) {
                 $table->setCellContents($row, 0, get_lang('None'));
-                $table->setCellContents($row, 1, show_score($none_category['score'], $none_category['total'], false));            
+                $table->setCellContents($row, 1, show_score($none_category['score'], $none_category['total'], false));
                 $table->setCellContents($row, 2, show_score($none_category['score'], $none_category['total'], true, false, true));
                 $row++;
             }
@@ -515,4 +514,3 @@ class Testcategory {
         return null;
     }
 }
-endif;

+ 23 - 20
main/inc/ajax/exercise.ajax.php

@@ -39,7 +39,9 @@ switch ($action) {
         }
         // get index row - i.e. user click to sort $sord = $_GET['sord'];
         // get the direction
-        if (!$sidx) $sidx = 1;
+        if (!$sidx) {
+            $sidx = 1;
+        }
 
         $track_exercise        = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
         $user_table            = Database::get_main_table(TABLE_MAIN_USER);
@@ -178,19 +180,19 @@ switch ($action) {
         }
         break;
     case 'add_question_to_reminder':
-    	$objExercise  = $_SESSION['objExercise'];
-    	if (empty($objExercise)) {
-    		echo 0;
-    		exit;
-    	} else {
-    		$objExercise->edit_question_to_remind($_REQUEST['exe_id'], $_REQUEST['question_id'], $_REQUEST['action']);
-    	}
-    	break;
+        $objExercise  = $_SESSION['objExercise'];
+        if (empty($objExercise)) {
+            echo 0;
+            exit;
+        } else {
+            $objExercise->edit_question_to_remind($_REQUEST['exe_id'], $_REQUEST['question_id'], $_REQUEST['action']);
+        }
+        break;
     case 'save_exercise_by_now':
         $course_info = api_get_course_info($course_code);
         $course_id = $course_info['real_id'];
 
-        //Use have permissions?
+        // Use have permissions?
         if (api_is_allowed_to_session_edit()) {
 
             //"all" or "simple" strings means that there's one or all questions exercise type
@@ -212,20 +214,22 @@ switch ($action) {
             //Attempt id
             $exe_id = $_REQUEST['exe_id'];
 
-            if ($debug) error_log("exe_id = $exe_id ");
-            if ($debug) error_log("type = $type ");
-            if ($debug) error_log("choice = ".print_r($choice, 1)." ");
-            if ($debug) error_log("hot_spot_coordinates = ".print_r($hot_spot_coordinates,1));
-            if ($debug) error_log("remind_list = ".print_r($remind_list, 1));
+            if ($debug) {
+                error_log("exe_id = $exe_id ");
+                error_log("type = $type ");
+                error_log("choice = ".print_r($choice, 1)." ");
+                error_log("hot_spot_coordinates = ".print_r($hot_spot_coordinates, 1));
+                error_log("remind_list = ".print_r($remind_list, 1));
+            }
 
-            //Exercise information
+            // Exercise information.
             $objExercise             = isset($_SESSION['objExercise']) ? $_SESSION['objExercise'] : null;
 
-            //Question info
+            // Question info.
             $question_id             = intval($_REQUEST['question_id']);
             $question_list           = $_SESSION['questionList'];
 
-            //If exercise or question is not set then exit
+            // If exercise or question is not set then exit.
             if (empty($question_list) || empty($objExercise)) {
                 echo 'error';
                 exit;
@@ -274,7 +278,6 @@ switch ($action) {
             	}
             }
 
-
             //No exe id? Can't save answer.
             if (empty($exe_id)) {
                 //Fires an error
@@ -296,7 +299,7 @@ switch ($action) {
 
             unset($objQuestionTmp);
 
-            //Looping the question list
+            // Looping the question list
 
             foreach ($question_list as $my_question_id) {
                 if ($debug) error_log("Saving question_id = $my_question_id ");

+ 12 - 6
main/inc/ajax/model.ajax.php

@@ -318,26 +318,32 @@ switch ($action) {
     	break;
     case 'get_work_user_list_all':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
         }
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
         break;
     case 'get_work_user_list_others':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname',  'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname',  'title', 'sent_date', 'actions');
         }
         $where_condition .= " AND u.user_id <> ".api_get_user_id();
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
         break;
     case 'get_work_user_list':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
         }
         $where_condition .= " AND u.user_id = ".api_get_user_id();
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);

+ 3 - 3
main/template/default/work/view.tpl

@@ -1,7 +1,7 @@
 <div class="page-header">
-    <h2>{{ work.title}}</h2>
+    <h2>{{ work.title }}</h2>
 </div>
 
 <p>
-{{ work.description}}
-</p>
+{{ work.description }}
+</p>

+ 1 - 0
main/work/downloadfolder.inc.php

@@ -65,6 +65,7 @@ if (api_is_allowed_to_edit()) {
  			        work.parent_id = $work_id AND
  			        work.filetype = 'file' AND
  			        props.visibility<>'2' AND
+ 			        work.active = 1 AND
  			        work.post_group_id = $groupId
             ";
 

+ 8 - 3
main/work/edit.php

@@ -1,4 +1,5 @@
 <?php
+/* For licensing terms, see /license.txt */
 
 use ChamiloSession as Session;
 
@@ -58,13 +59,17 @@ $is_author = false;
 
 $work_item = get_work_data_by_id($item_id);
 
-//Get the author ID for that document from the item_property table
+// Get the author ID for that document from the item_property table
 $is_author = user_is_author($item_id);
+
 if (!$is_author) {
-    Display::display_warning_message(get_lang('NotAllowed'));
-    Display::display_footer();
+    api_not_allowed(true);
 }
 
+// Student's can't edit work
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed(true);
+}
 
 if (!empty($my_folder_data)) {
     $homework = get_work_assignment_by_id($my_folder_data['id']);

+ 18 - 19
main/work/upload.php

@@ -59,7 +59,7 @@ $is_author = false;
 $parent_data['qualification'] = intval($parent_data['qualification']);
 
 //  @todo add an option to allow/block multiple attempts.
-
+/*
 if (!empty($parent_data) && !empty($parent_data['qualification'])) {
     $count =  get_work_count_by_student($user_id, $work_id);
     if ($count >= 1) {
@@ -72,7 +72,7 @@ if (!empty($parent_data) && !empty($parent_data['qualification'])) {
         Display::display_footer();
         exit;
     }
-}
+}*/
 
 if (!empty($my_folder_data)) {
     $homework = get_work_assignment_by_id($my_folder_data['id']);
@@ -134,17 +134,15 @@ if ($submitGroupWorkUrl) {
 $form->addElement('hidden', 'id', $work_id);
 $form->addElement('hidden', 'contains_file', 0, array('id'=>'contains_file_id'));
 $form->addElement('text', 'title', get_lang('Title'), array('id' => 'file_upload', 'class' => 'span4'));
-//$form->addElement('html_editor', 'description', get_lang("Description"));
 $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'Work', 'Width' => '100%', 'Height' => '200'));
 
-$form->addElement('hidden', 'active',   1);
+$form->addElement('hidden', 'active', 1);
 $form->addElement('hidden', 'accepted', 1);
 $form->addElement('hidden', 'sec_token', $token);
 
 $text = get_lang('Send');
 $class = 'upload';
 
-
 // fix the Ok button when we see the tool in the learn path
 if ($origin == 'learnpath') {
     $form->addElement('html', '<div style="margin-left:137px">');
@@ -171,14 +169,17 @@ $succeed = false;
 if ($form->validate()) {
     if ($student_can_edit_in_session && $check) {
 
-        //check the token inserted into the form
+        // Check the token inserted into the form
 
         if (isset($_POST['submitWork'])) {
             $url = null;
             $contains_file = 0;
 
+            $title  = isset($_POST['title']) ? $_POST['title'] : null;
+            $description = isset($_POST['description']) ? $_POST['description'] : null;
+
             if ($_POST['contains_file'] && !empty($_FILES['file']['size'])) {
-                $updir = $currentCourseRepositorySys . 'work/'; //directory path to upload
+                $updir = $currentCourseRepositorySys.'work/'; //directory path to upload
 
                 // Try to add an extension to the file if it has'nt one
                 $new_file_name = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);
@@ -208,7 +209,7 @@ if ($form->validate()) {
                 $new_file_name = api_get_unique_id();
                 $curdirpath = basename($my_folder_data['url']);
 
-                //if we come from the group tools the groupid will be saved in $work_table
+                // If we come from the group tools the groupid will be saved in $work_table
                 $result = move_uploaded_file($_FILES['file']['tmp_name'], $updir.$curdirpath.'/'.$new_file_name);
 
                 if ($result) {
@@ -229,21 +230,20 @@ if ($form->validate()) {
                 $error_message .= Display::return_message(get_lang('NoSpace'), 'warning');
             } else {
                 $active = '1';
-                //author      	= '" . Database::escape_string($authors) . "',
-                $sql_add_publication = "INSERT INTO " . $work_table . " SET
+                $sql_add_publication = "INSERT INTO ".$work_table." SET
                                    c_id 		= $course_id ,
-                                   url         	= '" . $url . "',
-                                   title       	= '" . Database::escape_string($title) . "',
-                                   description	= '" . Database::escape_string($description) . "',
+                                   url         	= '".$url . "',
+                                   title       	= '".Database::escape_string($title)."',
+                                   description	= '".Database::escape_string($description)."',
                                    contains_file = '".$contains_file."',
-                                   active		= '" . $active . "',
+                                   active		= '" . $active."',
                                    accepted		= '1',
                                    post_group_id = '".$group_id."',
                                    sent_date	=  '".api_get_utc_datetime()."',
                                    parent_id 	=  '".$work_id."' ,
                                    session_id	= '".intval($id_session)."' ,
                                    user_id 		= '".$user_id."'";
-                //var_dump($sql_add_publication);exit;
+
                 Database::query($sql_add_publication);
                 $id = Database::insert_id();
             }
@@ -276,7 +276,7 @@ if ($form->validate()) {
                 $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), $session_id, null, null, 2);
             }
 
-            $emailsubject = "[" . api_get_setting('siteName') . "] ".get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$_course['name']."  ";
+            $subject = "[" . api_get_setting('siteName') . "] ".get_lang('SendMailBody')."\n".get_lang('CourseName')." : ".$_course['name']."  ";
 
             foreach ($user_list as $user_data) {
                 $to_user_id = $user_data['user_id'];
@@ -288,18 +288,17 @@ if ($form->validate()) {
                 $url = api_get_path(WEB_CODE_PATH)."work/work.php?".api_get_cidreq()."&amp;id=".$work_id;
                 $emailbody .= $url;
 
-                MessageManager::send_message_simple($to_user_id, $emailsubject, $emailbody);
+                MessageManager::send_message_simple($to_user_id, $subject, $emailbody);
             }
         }
         $message = get_lang('DocAdd');
         event_upload($id);
-        $error_message .= Display :: return_message(get_lang('DocAdd'));
+        $error_message .= Display::return_message(get_lang('DocAdd'));
 
         $script = 'work_list.php';
         if ($is_allowed_to_edit) {
             $script = 'work_list_all.php';
         }
-
         header('Location: '.api_get_path(WEB_CODE_PATH).'work/'.$script.'?'.api_get_cidreq().'&id='.$work_id.'&error_message='.$error_message);
         exit;
     }

+ 11 - 9
main/work/view.php

@@ -1,5 +1,7 @@
 <?php
 
+/* For licensing terms, see /license.txt */
+
 $language_file = array('exercice', 'work', 'document', 'admin');
 
 require_once '../inc/global.inc.php';
@@ -7,11 +9,11 @@ $current_course_tool  = TOOL_STUDENTPUBLICATION;
 
 require_once 'work.lib.php';
 
-$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : null;
+$id = isset($_GET['id']) ? intval($_GET['id']) : null;
 $work = get_work_data_by_id($id);
 
 if (empty($id) || empty($work)) {
-	api_not_allowed();
+    api_not_allowed();
 }
 $interbreadcrumb[] = array ('url' => 'work.php', 'name' => get_lang('StudentPublications'));
 
@@ -20,17 +22,17 @@ $course_info = api_get_course_info();
 
 if (user_is_author($id) || $course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1) {
     $url_dir = 'work.php?&id=' . $my_folder_data['id'];
-    $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);	
-    $interbreadcrumb[] = array ('url' => '#','name' =>  $work['title']);	
+    $interbreadcrumb[] = array ('url' => $url_dir,'name' =>  $my_folder_data['title']);
+    $interbreadcrumb[] = array ('url' => '#','name' =>  $work['title']);
 
     if (($course_info['show_score'] == 0 && $work['active'] == 1 && $work['accepted'] == 1) || api_is_allowed_to_edit() || ($work['user_id'] == api_get_user_id() && $work['active'] == 1 && $work['accepted'] == 1)) {
-        $tpl = new Template();		
+        $tpl = new Template();
         $tpl->assign('work', $work);
-        $template = $tpl->get_template('work/view.tpl');	
+        $template = $tpl->get_template('work/view.tpl');
         $content  = $tpl->fetch($template);
         $tpl->assign('content', $content);
-        $tpl->display_one_col_template();	
+        $tpl->display_one_col_template();
     } else {
-        api_not_allowed();	
+        api_not_allowed();
     }
-}
+}

+ 10 - 9
main/work/work.lib.php

@@ -247,7 +247,7 @@ function get_work_data_by_id($id) {
 	$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;
 }
@@ -1773,7 +1773,7 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                 //Firstname, lastname, username
                 $work['firstname'] = Display::div($work['firstname'], array('class' => $class));
                 $work['lastname'] = Display::div($work['lastname'], array('class' => $class));
-                $work['username'] = Display::div($work['username'], array('class' => $class));
+                //$work['username'] = Display::div($work['username'], array('class' => $class));
 
                 if (strlen($work['title']) > 30) {
                     $short_title = substr($work['title'],0,27).'...';
@@ -1782,11 +1782,10 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                     $work['title'] = Display::div($work['title'], array('class' => $class));
                 }
 
-
-                //Type
+                // Type.
                 $work['type'] = build_document_icon_tag('file', $work['file']);
 
-                //File name
+                // File name.
                 $link_to_download = null;
 
                 if ($work['contains_file']) {
@@ -1799,11 +1798,11 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
 
                 $work['qualification'] = $qualification_string;
 
-                //Date
+                // Date.
                 $work_date = api_convert_and_format_date($work['sent_date']);
                 $work['sent_date'] = date_to_str_ago(api_get_local_time($work['sent_date'])).' '.$add_string.'<br />'.$work_date;
 
-                //Actions
+                // Actions.
                 $url = api_get_path(WEB_CODE_PATH).'work/';
                 $action = '';
                 if ($is_allowed_to_edit) {
@@ -1841,7 +1840,9 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                     }
                 } elseif ($is_author && (empty($work['qualificator_id']) || $work['qualificator_id'] == 0)) {
                     if (api_is_allowed_to_session_edit(false, true)) {
-                        $action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'"  >'.Display::return_icon('edit.png', get_lang('Modify'),array(), ICON_SIZE_SMALL).'</a>';
+                        //$action .= '<a href="'.$url.'edit.php?'.api_get_cidreq().'&item_id='.$item_id.'&id='.$work['parent_id'].'" title="'.get_lang('Modify').'"  >'.Display::return_icon('edit.png', get_lang('Modify'),array(), ICON_SIZE_SMALL).'</a>';
+                        $action .= '<a href="'.$url.'view.php?'.api_get_cidreq().'&id='.$item_id.'" title="'.get_lang('Modify').'">'.
+                            Display::return_icon('default.png', get_lang('View'),array(), ICON_SIZE_SMALL).'</a>';
                     } else {
                         $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
                     }
@@ -1852,7 +1853,7 @@ function get_work_user_list($start, $limit, $column, $direction, $work_id, $wher
                     $action .= Display::return_icon('edit_na.png', get_lang('Modify'),array(), ICON_SIZE_SMALL);
                 }
 
-                //Status
+                // Status.
                 if (empty($work['qualificator_id'])) {
                     $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
                 } else {

+ 9 - 8
main/work/work_list.php

@@ -68,23 +68,26 @@ if (api_is_allowed_to_session_edit(false, true) && !empty($workId)) {
 }
 echo '</div>';
 
-
 $error_message = isset($_GET['error_message']) ? Security::remove_XSS($_GET['error_message']) : null;
 if (!empty($error_message)) {
     echo $error_message;
 }
 
+if (!empty($my_folder_data['description'])) {
+    echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description']).'</p></div></p>';
+}
 
 $check_qualification = intval($my_folder_data['qualification']);
 
 if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {
     $type = 'simple';
-    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    //$columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'), get_lang('Status'), get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => 'true'),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
@@ -94,12 +97,13 @@ if (!empty($work_data['enable_qualification']) && !empty($check_qualification))
     );
 } else {
     $type = 'complex';
-    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    //$columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => "true"),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         //array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
@@ -116,9 +120,6 @@ $extra_params['autowidth'] = 'true';
 
 //height auto
 $extra_params['height'] = 'auto';
-//$extra_params['excel'] = 'excel';
-
-//$extra_params['rowList'] = array(10, 20 ,30);
 
 $extra_params['sortname'] = 'firstname';
 $url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_work_user_list&work_id='.$workId.'&type='.$type;

+ 10 - 8
main/work/work_list_all.php

@@ -8,8 +8,6 @@ $language_file = array('exercice', 'work', 'document', 'admin', 'gradebook');
 require_once '../inc/global.inc.php';
 $current_course_tool  = TOOL_STUDENTPUBLICATION;
 
-/*	Configuration settings */
-
 api_protect_course_script(true);
 
 // Including necessary files
@@ -78,7 +76,6 @@ if (api_is_allowed_to_session_edit(false, true) && !empty($workId)) {
     }
     echo $display_output;
 }
-
 echo '</div>';
 
 if (empty($error_message)) {
@@ -88,17 +85,21 @@ if (!empty($error_message)) {
     echo $error_message;
 }
 
-// User works
+if (!empty($my_folder_data['description'])) {
+    echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description']).'</p></div></p>';
+}
+
 $check_qualification = intval($my_folder_data['qualification']);
 
 if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {
     $type = 'simple';
-    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    //$columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'10',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => 'true'),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
@@ -108,12 +109,13 @@ if (!empty($work_data['enable_qualification']) && !empty($check_qualification))
     );
 } else {
     $type = 'complex';
-    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    //$columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'10',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => "true"),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         //array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),

+ 9 - 7
main/work/work_list_others.php

@@ -67,24 +67,25 @@ $interbreadcrumb[] = array ('url' => api_get_path(WEB_CODE_PATH).'work/work_list
 Display :: display_header(null);
 
 echo '<div class="actions">';
-echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'">'.Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
+echo '<a href="'.api_get_path(WEB_CODE_PATH).'work/work.php?'.api_get_cidreq().'&origin='.$origin.'&gradebook='.$gradebook.'">'.
+        Display::return_icon('back.png', get_lang('BackToWorksList'),'',ICON_SIZE_MEDIUM).'</a>';
 echo '</div>';
 
-
 if (!empty($my_folder_data['description'])) {
-    echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description'], STUDENT).'</p></div></p>';
+    echo '<p><div><strong>'.get_lang('Description').':</strong><p>'.Security::remove_XSS($my_folder_data['description']).'</p></div></p>';
 }
 
 $check_qualification = intval($my_folder_data['qualification']);
 
 if (!empty($work_data['enable_qualification']) && !empty($check_qualification)) {
     $type = 'simple';
-    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    //$columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
+    $columns        = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Qualification'), get_lang('Date'),  get_lang('Status'), get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => 'true'),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),
@@ -94,12 +95,13 @@ if (!empty($work_data['enable_qualification']) && !empty($check_qualification))
     );
 } else {
     $type = 'complex';
-    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    //$columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('LoginName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
+    $columns  = array(get_lang('Type'), get_lang('FirstName'), get_lang('LastName'), get_lang('Title'), get_lang('Date'),  get_lang('Actions'));
     $column_model   = array (
         array('name'=>'type',           'index'=>'file',            'width'=>'12',   'align'=>'left', 'search' => 'false'),
         array('name'=>'firstname',      'index'=>'firstname',       'width'=>'35',   'align'=>'left', 'search' => 'true'),
         array('name'=>'lastname',		'index'=>'lastname',        'width'=>'35',   'align'=>'left', 'search' => 'true'),
-        array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
+        //array('name'=>'username',       'index'=>'username',        'width'=>'30',   'align'=>'left', 'search' => 'true'),
         array('name'=>'title',          'index'=>'title',           'width'=>'40',   'align'=>'left', 'search' => 'false', 'wrap_cell' => "true"),
         //                array('name'=>'file',           'index'=>'file',            'width'=>'20',   'align'=>'left', 'search' => 'false'),
         //array('name'=>'qualification',	'index'=>'qualification',	'width'=>'20',   'align'=>'left', 'search' => 'true'),