Browse Source

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

Yannick Warnier 10 years ago
parent
commit
700f09004c

+ 13 - 7
main/course_home/activity.php

@@ -53,6 +53,15 @@ if (api_is_platform_admin()) {
 	}
 }
 
+// Course legal
+$enabled = api_get_plugin_setting('courselegal', 'tool_enable');
+$pluginExtra = null;
+if ($enabled == 'true') {
+    require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
+    $plugin = CourseLegalPlugin::create();
+    $pluginExtra = $plugin->getTeacherLink();
+}
+
 //	COURSE ADMIN ONLY VIEW
 
 // Start of tools for CourseAdmins (teachers/tutors)
@@ -66,6 +75,7 @@ if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, tr
 		<div class="confirmation-message" id="id_confirmation_message" style="display:none"></div>
 	</div>';
 
+    $content .= $pluginExtra;
 
 	if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
         $content .= '<div class="courseadminview">
@@ -79,22 +89,19 @@ if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, tr
     $content .= return_block(get_lang('Authoring'),  $items, 'course-tools-author');
 
     $my_list = CourseHome::get_tools_category(TOOL_INTERACTION);
-
     $list2 = CourseHome::get_tools_category(TOOL_COURSE_PLUGIN);
 
     $my_list = array_merge($my_list,$list2);
     $items =  CourseHome::show_tools_category($my_list);
-
     $content .= return_block(get_lang('Interaction'),  $items, 'course-tools-interaction');
 
     $my_list = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
     $items = CourseHome::show_tools_category($my_list);
-
     $content .= return_block(get_lang('Administration'),  $items , 'course-tools-administration');
 
 } elseif (api_is_coach()) {
+    $content .= $pluginExtra;
 	if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
-
 		$content .= '<div class="row">
 			<span class="viewcaption">'.get_lang('SessionData').'</span>
 			<table class="course_activity_home">';
@@ -103,10 +110,9 @@ if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, tr
 	}
 
     $content .=  '<div class="row">';
-				$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
-				$content .= CourseHome::show_tools_category($my_list);
+    $my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
+    $content .= CourseHome::show_tools_category($my_list);
     $content .= '</div>';
-    //	TOOLS AUTHORING
 
 } else {
 	$my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);

+ 66 - 21
main/course_info/legal.php

@@ -1,4 +1,5 @@
 <?php
+/* For licensing terms, see /license.txt */
 
 use \ChamiloSession as Session;
 
@@ -10,9 +11,9 @@ $cidReset = true;
 require_once '../inc/global.inc.php';
 $this_section = SECTION_COURSES;
 
-$course_code    = isset($_REQUEST['course_code'])  ? $_REQUEST['course_code'] : null;
-$session_id     = isset($_REQUEST['session_id']) ? intval($_REQUEST['session_id']) : null;
-$user_id        = api_get_user_id();
+$course_code = isset($_REQUEST['course_code']) ? $_REQUEST['course_code'] : null;
+$session_id = isset($_REQUEST['session_id']) ? intval($_REQUEST['session_id']) : null;
+$user_id = api_get_user_id();
 
 if (empty($course_code)) {
     api_not_allowed();
@@ -21,10 +22,48 @@ if (empty($course_code)) {
 $course_info = CourseManager::get_course_information($course_code);
 $course_legal = $course_info['legal'];
 
+$enabled = api_get_plugin_setting('courselegal', 'tool_enable');
+$pluginExtra = null;
+$pluginLegal = false;
+if ($enabled == 'true') {
+    $pluginLegal = true;
+    require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
+    $plugin = CourseLegalPlugin::create();
+    $data = $plugin->getData($course_info['real_id'], $session_id);
+
+    $userData = $plugin->getUserAcceptedLegal(
+        $user_id,
+        $course_info['real_id'],
+        $session_id
+    );
+
+    if (!empty($data)) {
+        $course_legal = $data['content'];
+    }
+
+    if (isset($_GET['web_agreement_link'])) {
+        $plugin->saveUserMailLegal(
+            $_GET['web_agreement_link'],
+            $user_id,
+            $course_info['real_id'],
+            $session_id
+        );
+    }
+}
+
 // Build the form
 $form = new FormValidator('legal', 'GET', api_get_self().'?course_code='.$course_code.'&session_id='.$session_id);
+$pluginMessage = null;
+if ($pluginLegal && isset($userData)) {
+    if ($userData['web_agreement'] == 1 && empty($userData['mail_agreement'])) {
+        $pluginMessage = Display::return_message(get_lang('YouNeedToConfirmYourAgreementCheckYourEmail'));
+    }
+}
 $form->addElement('header', get_lang('CourseLegalAgreement'));
 $form->addElement('label', null, $course_legal);
+if ($pluginLegal && !empty($plugin)) {
+    $form->addElement('label', null, $plugin->getCurrentFile($course_info['real_id'], $session_id));
+}
 $form->addElement('hidden', 'course_code', $course_code);
 $form->addElement('hidden', 'session_id', $session_id);
 $form->addElement('checkbox', 'accept_legal', null, get_lang('AcceptLegal'));
@@ -34,9 +73,9 @@ $variable = 'accept_legal_'.$user_id.'_'.$course_info['real_id'].'_'.$session_id
 
 if ($form->validate()) {
     $accept_legal = $form->exportValue('accept_legal');
-        
+
     if ($accept_legal == 1) {
-        CourseManager::save_user_legal($user_id, $course_code, $session_id);        
+        CourseManager::save_user_legal($user_id, $course_code, $session_id);
         if (api_check_user_access_to_legal($course_info['visibility'])) {
             Session::write($variable, true);
         }
@@ -51,36 +90,42 @@ if (api_check_user_access_to_legal($course_info['visibility']) && Session::read(
 $url = api_get_course_url($course_code, $session_id);
 
 if (empty($session_id)) {
-    if (CourseManager::is_user_subscribed_in_course($user_id, $course_code) || api_check_user_access_to_legal($course_info['visibility'])) {    
-        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code);
+    if (CourseManager::is_user_subscribed_in_course($user_id, $course_code) ||
+        api_check_user_access_to_legal($course_info['visibility'])
+    ) {
+        $user_accepted_legal = CourseManager::is_user_accepted_legal(
+            $user_id,
+            $course_code
+        );
         if ($user_accepted_legal || $user_pass_open_course) {
             //Redirect to course home
             header('Location: '.$url);
             exit;
-        }           
-    } else {   
-        api_not_allowed();        
-    }    
+        }
+    } else {
+        api_not_allowed();
+    }
 } else {
-    
+
     if (api_is_platform_admin()) {
         header('Location: '.$url);
     }
-    
+
     $user_session_status = SessionManager::get_user_status_in_session($user_id, $course_code, $session_id);
-    
-    if (isset($user_session_status) || api_check_user_access_to_legal($course_info['visibility'])) {        
-        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code, $session_id);        
+
+    if (isset($user_session_status) || api_check_user_access_to_legal($course_info['visibility'])) {
+        $user_accepted_legal = CourseManager::is_user_accepted_legal($user_id, $course_code, $session_id);
         if ($user_accepted_legal || $user_pass_open_course) {
-            //Redirect to course session home
+            // Redirect to course session home.
             header('Location: '.$url);
             exit;
-        }          
+        }
     } else {
         api_not_allowed();
-    }  
+    }
 }
 
-Display :: display_header($nameTools);
+Display :: display_header();
+echo $pluginMessage;
 $form->display();
-Display :: display_footer();
+Display :: display_footer();

+ 19 - 10
main/coursecopy/classes/CourseRestorer.class.php

@@ -1263,11 +1263,15 @@ class CourseRestorer
 		}
 	}
 
-	/**
-	 * Restore Quiz
-	 */
-    public function restore_quizzes($session_id = 0, $respect_base_content = false)
-    {
+    /**
+     * Restore Quiz
+     * @param int $session_id
+     * @param bool $respect_base_content
+     */
+    public 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);
@@ -1309,7 +1313,9 @@ class CourseRestorer
                     );
 
 					global $_custom;
-					if (isset($_custom['exercises_clean_dates_when_restoring']) && $_custom['exercises_clean_dates_when_restoring']) {
+					if (isset($_custom['exercises_clean_dates_when_restoring']) &&
+                        $_custom['exercises_clean_dates_when_restoring']
+                    ) {
 						$quiz->start_time = null;
 						$quiz->end_time   = null;
 					}
@@ -1418,7 +1424,10 @@ class CourseRestorer
 
             if ($new_id) {
                 if (!empty($question->picture)) {
-                    $question_temp = Question::read($new_id, $this->destination_course_info['real_id']);
+                    $question_temp = Question::read(
+                        $new_id,
+                        $this->destination_course_info['real_id']
+                    );
 
                     $documentPath = api_get_path(SYS_COURSE_PATH).$this->destination_course_info['path'].'/document';
                     // picture path
@@ -1452,7 +1461,7 @@ class CourseRestorer
                             c_id = ".$this->destination_course_id." ,
                             id = '".$index."',
                             question_id = '".$new_id."',
-                            answer = '".self::DBUTF8escapestring($answer['answer'])."',
+                            answer = '".api_htmlentities(self::DBUTF8escapestring($answer['answer']))."',
                             correct = '".$answer['correct']."',
                             comment = '".self::DBUTF8escapestring($answer['comment'])."',
                             ponderation = '".$answer['ponderation']."',
@@ -1550,8 +1559,7 @@ class CourseRestorer
                 } else {
                     $new_options = array();
                     if (isset($question->question_options)) {
-                        foreach($question->question_options as $obj) {
-
+                        foreach ($question->question_options as $obj) {
                             $item = array();
                             $item['question_id'] = $new_id;
                             $item['c_id'] = $this->destination_course_id;
@@ -1561,6 +1569,7 @@ class CourseRestorer
                             $question_option_id = Database::insert($table_options, $item);
                             $new_options[$obj->obj->id] = $question_option_id;
                         }
+
                         foreach($correct_answers as $answer_id => $correct_answer) {
                             $params = array();
                             $params['correct'] = $new_options[$correct_answer];

+ 3 - 5
main/coursecopy/import_backup.php

@@ -6,10 +6,6 @@
  * @author Bart Mollet <bart.mollet@hogent.be>
  * @package chamilo.backup
  */
-/**
- * Code
- */
-/*	INIT SECTION */
 
 // Language files that need to be included
 $language_file = array('exercice', 'coursebackup', 'admin');
@@ -131,7 +127,9 @@ if ((isset($_POST['action']) &&
 	}
 } else {
 	$user = api_get_user_info();
-	$backups = CourseArchiver::get_available_backups($is_platformAdmin ?null:$user['user_id']);
+	$backups = CourseArchiver::get_available_backups(
+        $is_platformAdmin ? null : $user['user_id']
+    );
 	$backups_available = count($backups) > 0;
 
 	$form = new FormValidator('import_backup_form', 'post', api_get_path(WEB_CODE_PATH).'coursecopy/import_backup.php?'.api_get_cidreq(), '', 'multipart/form-data');

+ 8 - 8
main/inc/global.inc.php

@@ -114,13 +114,15 @@ if (empty($_configuration['statistics_database']) && $already_installed) {
 }
 global $database_connection;
 // Connect to the server database and select the main chamilo database.
+// When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
 if (!($conn_return = @Database::connect(
     array(
         'server'        => $_configuration['db_host'],
         'username'      => $_configuration['db_user'],
         'password'      => $_configuration['db_password'],
-        'persistent'    => $_configuration['db_persistent_connection'] // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
-    )))) {
+        'persistent'    => $_configuration['db_persistent_connection']
+    )))
+) {
     $global_error_code = 3;
     // The database server is not available or credentials are invalid.
     require $includePath.'/global_error_message.inc.php';
@@ -180,7 +182,7 @@ if (!Database::select_db($_configuration['main_database'], $database_connection)
     die();
 }
 
-/*   Initialization of the default encodings */
+/* Initialization of the default encodings */
 // The platform's character set must be retrieved at this early moment.
 $sql = "SELECT selected_value FROM settings_current WHERE variable = 'platform_charset';";
 $result = Database::query($sql);
@@ -317,8 +319,6 @@ if (file_exists($mail_conf)) {
 
 // ===== "who is logged in?" module section =====
 
-
-
 // check and modify the date of user in the track.e.online table
 if (!$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
     LoginCheck(isset($_user['user_id']) ? $_user['user_id'] : '');
@@ -327,9 +327,9 @@ if (!$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
 // ===== end "who is logged in?" module section =====
 
 if (api_get_setting('server_type') == 'test') {
-    //error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
-    ini_set('display_errors', '1');
-    error_reporting(-1);
+    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
+    /*ini_set('display_errors', '1');
+    error_reporting(-1);*/
 } else {
     /*
     Server type is not test

+ 123 - 68
main/inc/lib/course.lib.php

@@ -1,8 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt*/
 
+require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
+require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
+
 /**
- * This is the course library for Chamilo.
+ * Class CourseManager
+ *
+ *  This is the course library for Chamilo.
  *
  * All main course functions should be placed here.
  *
@@ -16,16 +21,6 @@
  *
  * @package chamilo.library
  */
-
-/*    INIT SECTION */
-
-require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
-require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
-
-/**
- *    CourseManager Class
- *    @package chamilo.library
- */
 class CourseManager
 {
     const MAX_COURSE_LENGTH_CODE = 40;
@@ -112,10 +107,12 @@ class CourseManager
                         $cr->set_file_option();
                         $cr->restore($course_info['id']); //course_info[id] is the course.code value (I know...)
                     }
+
                     return $course_info;
                 }
             }
         }
+
         return false;
     }
 
@@ -140,7 +137,8 @@ class CourseManager
      * @return an array with all the fields of the course table
      * @assert ('') === false
      */
-    public static function get_course_information_by_id($course_id) {
+    public static function get_course_information_by_id($course_id)
+    {
         return Database::select('*, id as real_id', Database::get_main_table(TABLE_MAIN_COURSE), array('where'=>array('id = ?' =>intval($course_id))),'first');
     }
 
@@ -572,7 +570,8 @@ class CourseManager
      * @return int Course id
      * @assert ('', '') === false
      */
-    public static function get_course_code_from_original_id($original_course_id_value, $original_course_id_name) {
+    public static function get_course_code_from_original_id($original_course_id_value, $original_course_id_name)
+    {
         $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
         $table_field = Database::get_main_table(TABLE_MAIN_COURSE_FIELD);
         $sql = "SELECT course_code FROM $table_field cf INNER JOIN $t_cfv cfv ON cfv.field_id=cf.id
@@ -622,9 +621,9 @@ class CourseManager
     public static function add_user_to_course($user_id, $course_code, $status = STUDENT)
     {
         $debug = false;
-        $user_table         = Database::get_main_table(TABLE_MAIN_USER);
-        $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
-        $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $user_table = Database::get_main_table(TABLE_MAIN_USER);
+        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
+        $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
 
         $status = ($status == STUDENT || $status == COURSEMANAGER) ? $status : STUDENT;
         if (empty($user_id) || empty($course_code) || ($user_id != strval(intval($user_id)))) {
@@ -674,7 +673,8 @@ class CourseManager
      *    @return true if parameter is set and not empty, false otherwise
      *    @todo move function to better place, main_api ?
      */
-    public static function check_parameter($parameter, $error_message) {
+    public static function check_parameter($parameter, $error_message)
+    {
         if (empty($parameter)) {
             Display::display_normal_message($error_message);
             return false;
@@ -686,7 +686,8 @@ class CourseManager
      *    Lets the script die when a parameter check fails.
      *    @todo move function to better place, main_api ?
      */
-    public static function check_parameter_or_fail($parameter, $error_message) {
+    public static function check_parameter_or_fail($parameter, $error_message)
+    {
         if (!self::check_parameter($parameter, $error_message)) {
             die();
         }
@@ -696,9 +697,11 @@ class CourseManager
      *    @return true if there already are one or more courses
      *    with the same code OR visual_code (visualcode), false otherwise
      */
-    public static function course_code_exists($wanted_course_code) {
+    public static function course_code_exists($wanted_course_code)
+    {
         $wanted_course_code = Database::escape_string($wanted_course_code);
-        $sql = "SELECT COUNT(*) as number FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE code = '$wanted_course_code' OR visual_code = '$wanted_course_code'";
+        $sql = "SELECT COUNT(*) as number FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
+                WHERE code = '$wanted_course_code' OR visual_code = '$wanted_course_code'";
         $result = Database::fetch_array(Database::query($sql));
         return $result['number'] > 0;
     }
@@ -707,7 +710,8 @@ class CourseManager
      *    @return an array with the course info of all real courses on the platform
      */
     public static function get_real_course_list() {
-        $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)." WHERE target_course_code IS NULL");
+        $sql_result = Database::query("SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE)."
+                        WHERE target_course_code IS NULL");
         $real_course_list = array();
         while ($result = Database::fetch_array($sql_result)) {
             $real_course_list[$result['code']] = $result;
@@ -734,7 +738,8 @@ class CourseManager
      * the current user is course admin
      * @return array   A list of courses details for courses to which the user is subscribed as course admin (status = 1)
      */
-    public static function get_real_course_list_of_user_as_course_admin($user_id) {
+    public static function get_real_course_list_of_user_as_course_admin($user_id)
+    {
         $result_array = array();
         if ($user_id != strval(intval($user_id))) {
             return $result_array;
@@ -846,7 +851,7 @@ class CourseManager
 
     /**
      * @param int $user_id
-     * @return an array with the course info of all the courses (real and virtual)
+     * @return array An array with the course info of all the courses (real and virtual)
      * of which the current user is course admin.
      */
     public static function get_course_list_of_user_as_course_admin($user_id)
@@ -912,15 +917,15 @@ class CourseManager
      * (I'm not sure about the last case, but this seems not too bad)
      *
      * @author Roan Embrechts
-     * @param $user_id, the id of the user
-     * @param $course_info, an array with course info that you get using Database::get_course_info($course_system_code);
-     * @return an array with indices
+     * @param int $user_id, the id of the user
+     * @param array $course_info, an array with course info that you get using Database::get_course_info($course_system_code);
+     * @return array An array with indices
      *    $return_result['title'] - the course title of the combined courses
      *    $return_result['code']  - the course code of the combined courses
      * @deprecated use api_get_course_info()
      */
-    public static function determine_course_title_from_course_info($user_id, $course_info) {
-
+    public static function determine_course_title_from_course_info($user_id, $course_info)
+    {
         if ($user_id != strval(intval($user_id))) {
             return array();
         }
@@ -970,7 +975,6 @@ class CourseManager
      */
     public static function create_combined_name($user_is_registered_in_real_course, $real_course_name, $virtual_course_list)
     {
-
         $complete_course_name = array();
 
         if ($user_is_registered_in_real_course) {
@@ -992,7 +996,6 @@ class CourseManager
      */
     public static function create_combined_code($user_is_registered_in_real_course, $real_course_code, $virtual_course_list)
     {
-
         $complete_course_code = array();
 
         if ($user_is_registered_in_real_course) {
@@ -1187,8 +1190,8 @@ class CourseManager
     *
     *    @return true if the user is registered in the real course or linked courses, false otherwise
     */
-    public static function is_user_subscribed_in_real_or_linked_course($user_id, $course_code, $session_id = '') {
-
+    public static function is_user_subscribed_in_real_or_linked_course($user_id, $course_code, $session_id = '')
+    {
         if ($user_id != strval(intval($user_id))) {
             return false;
         }
@@ -1211,7 +1214,6 @@ class CourseManager
         $session_id = intval($session_id);
 
         // From here we trust session id.
-
         // Is he/she subscribed to the session's course?
 
         // A user?
@@ -1547,7 +1549,8 @@ class CourseManager
      * @param   int       $session_id
      * @return  int
      */
-    public static function get_users_count_in_course($course_code, $session_id = 0) {
+    public static function get_users_count_in_course($course_code, $session_id = 0)
+    {
         // variable initialisation
         $session_id     = intval($session_id);
         $course_code    = Database::escape_string($course_code);
@@ -1594,8 +1597,8 @@ class CourseManager
      * @param   int     Session ID
      * @return  array   List of users
      */
-    public static function get_coach_list_from_course_code($course_code, $session_id) {
-
+    public static function get_coach_list_from_course_code($course_code, $session_id)
+    {
         if ($session_id != strval(intval($session_id))) {
             return array();
         }
@@ -1625,6 +1628,7 @@ class CourseManager
         $user_info['tutor_id'] = $user['tutor_id'];
         $user_info['email'] = $user['email'];
         $users[$session_id_coach] = $user_info;
+
         return $users;
     }
 
@@ -1755,8 +1759,8 @@ class CourseManager
      * @return array    - array containing user_id, lastname, firstname, username
      *
      */
-    public static function get_coachs_from_course($session_id=0, $course_code='') {
-
+    public static function get_coachs_from_course($session_id=0, $course_code='')
+    {
         if (!empty($session_id)) {
             $session_id = intval($session_id);
         } else {
@@ -1787,7 +1791,12 @@ class CourseManager
         }
     }
 
-    public static function get_coachs_from_course_to_string($session_id = 0, $course_code = null, $separator = self::USER_SEPARATOR, $add_link_to_profile = false) {
+    public static function get_coachs_from_course_to_string(
+        $session_id = 0,
+        $course_code = null,
+        $separator = self::USER_SEPARATOR,
+        $add_link_to_profile = false
+    ) {
         $coachs_course = self::get_coachs_from_course($session_id, $course_code);
         $course_coachs = array();
 
@@ -1808,7 +1817,8 @@ class CourseManager
         return $coaches_to_string;
     }
 
-    public static function get_coach_list_from_course_code_to_string($course_code, $session_id) {
+    public static function get_coach_list_from_course_code_to_string($course_code, $session_id)
+    {
         $tutor_data = '';
         if ($session_id != 0) {
             $coaches = self::get_email_of_tutor_to_session($session_id, $course_code);
@@ -1823,7 +1833,6 @@ class CourseManager
         return $tutor_data;
     }
 
-
     /**
      *    Return user info array of all users registered in the specified course
      *    this includes the users of the course itsel and the users of all linked courses.
@@ -1831,7 +1840,8 @@ class CourseManager
      *    @param array $course_info
      *    @return array with user info
      */
-    public static function get_real_and_linked_user_list($course_code, $with_sessions = true, $session_id = 0) {
+    public static function get_real_and_linked_user_list($course_code, $with_sessions = true, $session_id = 0)
+    {
         //get list of virtual courses
         $virtual_course_list = self::get_virtual_courses_linked_to_real_course($course_code);
         $complete_user_list = array();
@@ -1864,7 +1874,8 @@ class CourseManager
      *    @return array of course info arrays
      *  @deprecated virtual course feature is not supported
      */
-    public static function get_list_of_virtual_courses_for_specific_user_and_real_course($user_id, $course_code) {
+    public static function get_list_of_virtual_courses_for_specific_user_and_real_course($user_id, $course_code)
+    {
         $result_array = array();
 
         if ($user_id != strval(intval($user_id))) {
@@ -3972,27 +3983,37 @@ class CourseManager
         return $wanted_code;
     }
 
-
     /**
      * Gets the status of the users agreement in a course course-session
      *
-     * @param int user id
-     * @param string course code
-     * @param int session id
+     * @param int $user_id
+     * @param string $course_code
+     * @param int $session_id
      * @return boolean
      */
-    public static function is_user_accepted_legal($user_id, $course_code, $session_id = null) {
-        $user_id    = intval($user_id);
+    public static function is_user_accepted_legal($user_id, $course_code, $session_id = null)
+    {
+        $user_id = intval($user_id);
         $course_code = Database::escape_string($course_code);
         $session_id = intval($session_id);
+
+        // Course legal
+        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
+
+        if ($enabled == 'true') {
+            require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
+            $plugin = CourseLegalPlugin::create();
+            return $plugin->isUserAcceptedLegal($user_id, $course_code, $session_id);
+        }
+
         if (empty($session_id)) {
             $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
             $sql = "SELECT legal_agreement FROM $table
-                    WHERE user_id =  $user_id AND course_code  ='$course_code' ";
+                    WHERE user_id = $user_id AND course_code ='$course_code' ";
             $result = Database::query($sql);
             if (Database::num_rows($result) > 0 ) {
                 $result = Database::fetch_array($result);
-                if ($result['legal_agreement'] == 1 ) {
+                if ($result['legal_agreement'] == 1) {
                     return true;
                 }
             }
@@ -4000,11 +4021,11 @@ class CourseManager
         } else {
             $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
             $sql = "SELECT legal_agreement FROM $table
-                    WHERE id_user =  $user_id AND course_code  ='$course_code' AND id_session = $session_id";
+                    WHERE id_user = $user_id AND course_code ='$course_code' AND id_session = $session_id";
             $result = Database::query($sql);
             if (Database::num_rows($result) > 0 ) {
                 $result = Database::fetch_array($result);
-                if ($result['legal_agreement'] == 1 ) {
+                if ($result['legal_agreement'] == 1) {
                     return true;
                 }
             }
@@ -4019,25 +4040,43 @@ class CourseManager
      * @param   string course code
      * @param   int session id
      */
-    function save_user_legal($user_id, $course_code, $session_id = null) {
+    public static function save_user_legal($user_id, $course_code, $session_id = null)
+    {
+        // Course plugin legal
+        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
+
+        if ($enabled == 'true') {
+            require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
+            $plugin = CourseLegalPlugin::create();
+            return $plugin->saveUserLegal($user_id, $course_code, $session_id);
+        }
 
-        $user_id    = intval($user_id);
+        $user_id = intval($user_id);
         $course_code = Database::escape_string($course_code);
         $session_id = intval($session_id);
+
         if (empty($session_id)) {
             $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
             $sql = "UPDATE $table SET legal_agreement = '1'
                     WHERE user_id =  $user_id AND course_code  ='$course_code' ";
-            $result = Database::query($sql);
+            Database::query($sql);
         } else {
             $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
             $sql = "UPDATE  $table SET legal_agreement = '1'
                     WHERE id_user =  $user_id AND course_code  = '$course_code' AND id_session = $session_id";
-            $result = Database::query($sql);
+            Database::query($sql);
         }
     }
 
-    public static function get_user_course_vote($user_id, $course_id, $session_id = null, $url_id = null) {
+    /**
+     * @param int $user_id
+     * @param int $course_id
+     * @param int $session_id
+     * @param int $url_id
+     * @return bool
+     */
+    public static function get_user_course_vote($user_id, $course_id, $session_id = null, $url_id = null)
+    {
         $table_user_course_vote     = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
 
         $session_id = !isset($session_id)   ? api_get_session_id()                : intval($session_id);
@@ -4069,8 +4108,9 @@ class CourseManager
      * @param int $url_id
      * @return array
      */
-    public static function get_course_ranking($course_id, $session_id = null, $url_id = null) {
-        $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
+    public static function get_course_ranking($course_id, $session_id = null, $url_id = null)
+    {
+        $table_course_ranking = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
 
         $session_id = !isset($session_id)   ? api_get_session_id() : intval($session_id);
         $url_id     = empty($url_id)        ? api_get_current_access_url_id() : intval($url_id);
@@ -4121,8 +4161,15 @@ class CourseManager
      * @param id    url id
      *
      **/
-    public static function update_course_ranking($course_id = null, $session_id = null, $url_id = null, $points_to_add = null, $add_access = true, $add_user = true) {
-        //Course catalog stats modifications see #4191
+    public static function update_course_ranking(
+        $course_id = null,
+        $session_id = null,
+        $url_id = null,
+        $points_to_add = null,
+        $add_access = true,
+        $add_user = true
+    ) {
+        // Course catalog stats modifications see #4191
         $table_course_ranking       = Database::get_main_table(TABLE_STATISTIC_TRACK_COURSE_RANKING);
 
         $now = api_get_utc_datetime();
@@ -4138,7 +4185,12 @@ class CourseManager
             'creation_date' => $now,
         );
 
-        $result = Database::select('id, accesses, total_score, users', $table_course_ranking, array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)), 'first');
+        $result = Database::select(
+            'id, accesses, total_score, users',
+            $table_course_ranking,
+            array('where' => array('c_id = ? AND session_id = ? AND url_id = ?' => $params)),
+            'first'
+        );
 
         // Problem here every time we load the courses/XXXX/index.php course home page we update the access
 
@@ -4168,13 +4220,17 @@ class CourseManager
             }
 
             if (!empty($my_params)) {
-                $result = Database::update($table_course_ranking, $my_params, array('c_id = ? AND session_id = ? AND url_id = ?' => $params));
+                $result = Database::update(
+                    $table_course_ranking,
+                    $my_params,
+                    array('c_id = ? AND session_id = ? AND url_id = ?' => $params)
+                );
             }
         }
+
         return $result;
     }
 
-
     /**
      * Add user vote to a course
      *
@@ -4184,10 +4240,9 @@ class CourseManager
      * @param   int session id
      * @param   int url id (access_url_id)
      * @return    mixed 'added', 'updated' or 'nothing'
-     *
      */
-
-    public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null) {
+    public static function add_course_vote($user_id, $vote, $course_id, $session_id = null, $url_id = null)
+    {
         $table_user_course_vote     = Database::get_main_table(TABLE_MAIN_USER_REL_COURSE_VOTE);
         $course_id  = empty($course_id) ? api_get_course_int_id() : intval($course_id);
 

+ 0 - 1
main/inc/lib/course_home.lib.php

@@ -751,7 +751,6 @@ class CourseHome
 
                 // Including Courses Plugins
                 // Creating title and the link
-
                 if (isset($tool['category']) && $tool['category'] == 'plugin') {
                     $plugin_info = $app_plugin->get_plugin_info($tool['name']);
                     if (isset($plugin_info) && isset($plugin_info['title'])) {

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

@@ -1150,7 +1150,7 @@ class Database {
             	var_dump($sql);
             }
             return self::insert_id();
-        }        
+        }
         return false;
     }
 

+ 12 - 3
main/inc/lib/fileUpload.lib.php

@@ -185,7 +185,8 @@ function handle_uploaded_document(
     $to_user_id = null,
     $unzip = 0,
     $what_if_file_exists = '',
-    $output = true
+    $output = true,
+    $onlyUploadFile = false
 ) {
 	if (!$user_id) {
         die('Not a valid user.');
@@ -263,9 +264,17 @@ function handle_uploaded_document(
 			$document_name = get_document_title($uploaded_file['name']);
 			// Size of the uploaded file (in bytes)
 			$file_size = $uploaded_file['size'];
-
 			$files_perm = api_get_permissions_for_new_files();
-            //$doc_path = '/'.$clean_name;
+
+            if ($onlyUploadFile) {
+                $errorResult = moveUploadedFile($uploaded_file, $store_path);
+                if ($errorResult) {
+                    return $store_path;
+                } else {
+                    return $errorResult;
+                }
+            }
+
             $docId = DocumentManager::get_document_id($_course, $file_path, $current_session_id);
 
             // What to do if the target file exists

+ 70 - 48
main/inc/lib/legal.lib.php

@@ -1,29 +1,28 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
- * Legal class
+ * Class LegalManager
  *
- * @version 1.0
- * @package chamilo.legal
- *
-*/
-/**
- * Class
  * @package chamilo.legal
  */
-class LegalManager {
-	private function __construct () {
-		//void
+class LegalManager
+{
+	private function __construct ()
+    {
+
 	}
+
 	/**
 	 * Add a new Term and Condition
-	 * @param int language id
-	 * @param string the content
-	 * @param int term and condition type (0 or 1)
-	 * @param string explain changes
-	 * @return boolean sucess
+	 * @param int $language language id
+	 * @param string $content content
+	 * @param int $type term and condition type (0 or 1)
+	 * @param string $changes explain changes
+	 * @return boolean success
 	 */
-	public static function add ($language, $content, $type, $changes) {
+	public static function add($language, $content, $type, $changes)
+    {
 		$legal_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$last = self::get_last_condition($language);
 		$language = Database::escape_string($language);
@@ -35,31 +34,34 @@ class LegalManager {
 		if ($last['content'] != $content) {
 			$version = intval(LegalManager::get_last_condition_version($language));
 			$version++;
-			 $sql = "INSERT INTO $legal_table
-						SET language_id = '".Database::escape_string($language)."',
-							content = '".$content."',
-							changes= '".$changes."',
-							type = '".$type."',
-							version = '".Database::escape_string($version)."',
-							date = '".$time."'";
-			$result = Database::query($sql);
+			 $sql = "INSERT INTO $legal_table SET
+			            language_id = '".Database::escape_string($language)."',
+                        content = '".$content."',
+                        changes= '".$changes."',
+                        type = '".$type."',
+                        version = '".Database::escape_string($version)."',
+                        date = '".$time."'";
+			Database::query($sql);
+
 			return true;
 		} elseif($last['type'] != $type && $language==$last['language_id']) {
 			//update
 			$id = $last['legal_id'];
-			$sql = "UPDATE $legal_table
-					SET  changes= '".$changes."',
-					type = '".$type."',
-					date = '".$time."'
+			$sql = "UPDATE $legal_table SET
+                        changes= '".$changes."',
+                        type = '".$type."',
+                        date = '".$time."'
 					WHERE legal_id= $id  ";
-			$result = Database::query($sql);
+			Database::query($sql);
+
 			return true;
 		} else {
 			return false;
 		}
 	}
 
-	public static function delete ($id) {
+	public static function delete($id)
+    {
 		/*
 		$legal_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$id = intval($id);
@@ -69,50 +71,64 @@ class LegalManager {
 
 	/**
 	 * Gets the last version of a Term and condition by language
-	 * @param int the language id
+	 * @param int $language language id
 	 * @return array all the info of a Term and condition
 	 */
-
-	public static function get_last_condition_version ($language) {
+	public static function get_last_condition_version($language)
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$language= Database::escape_string($language);
-		$sql = "SELECT version FROM $legal_conditions_table WHERE language_id = '".$language."' ORDER BY legal_id DESC LIMIT 1 ";
+		$sql = "SELECT version FROM $legal_conditions_table
+		        WHERE language_id = '".$language."'
+		        ORDER BY legal_id DESC LIMIT 1 ";
 		$result = Database::query($sql);
 		$row = Database::fetch_array($result);
-		if (Database::num_rows($result)>0) {
+        if (Database::num_rows($result) > 0) {
+
 			return $row['version'];
 		} else {
+
 			return 0;
 		}
 	}
+
 	/**
 	 * Gets the data of a Term and condition by language
-	 * @param int the language id
+	 * @param int $language language id
 	 * @return array all the info of a Term and condition
 	 */
-	public static function get_last_condition ($language) {
+	public static function get_last_condition ($language)
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$language= Database::escape_string($language);
-		$sql = "SELECT * FROM $legal_conditions_table WHERE language_id = '".$language."' ORDER BY version DESC LIMIT 1 ";
+		$sql = "SELECT * FROM $legal_conditions_table
+                WHERE language_id = '".$language."'
+                ORDER BY version DESC LIMIT 1 ";
 		$result = Database::query($sql);
+
 		return Database::fetch_array($result);
 	}
 
 	/**
 	 * Gets the last version of a Term and condition by language
-	 * @param int the language id
+	 * @param int $language language id
 	 * @return boolean | int the version or false if does not exist
 	 */
-	public static function get_last_version ($language) {
+	public static function get_last_version($language)
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$language= Database::escape_string($language);
-		$sql = "SELECT version FROM $legal_conditions_table WHERE language_id = '".$language."' ORDER BY version DESC LIMIT 1 ";
+		$sql = "SELECT version FROM $legal_conditions_table
+		        WHERE language_id = '".$language."'
+		        ORDER BY version DESC LIMIT 1 ";
 		$result = Database::query($sql);
 		if (Database::num_rows($result)>0){
 			$version = Database::fetch_array($result);
 			$version = explode(':',$version[0]);
+
 			return $version[0];
 		} else {
+
 			return false;
 		}
 	}
@@ -120,9 +136,11 @@ class LegalManager {
 	/**
 	 * Show the last condition
 	 * @param array with type and content i.e array('type'=>'1', 'content'=>'hola');
+     *
 	 * @return string html preview
 	 */
-	public static function show_last_condition($term_preview) {
+	public static function show_last_condition($term_preview)
+    {
 		$preview = '';
 		switch ($term_preview['type']) {
 			/*// scroll box
@@ -175,7 +193,6 @@ class LegalManager {
 		return 	$preview;
 	}
 
-
 	/**
 	 * Get the terms and condition table (only for maintenance)
 	 * @param int offset
@@ -183,7 +200,8 @@ class LegalManager {
 	 * @param int column
 	 * @return array
 	 */
-	public static function get_legal_data ($from, $number_of_items, $column) {
+	public static function get_legal_data($from, $number_of_items, $column)
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$lang_table = Database::get_main_table(TABLE_MAIN_LANGUAGE);
 		$from = intval($from);
@@ -218,12 +236,14 @@ class LegalManager {
 	 * Gets the number of terms and conditions available
 	 * @return int
 	 */
-	public static function count() {
+	public static function count()
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$sql = "SELECT count(*) as count_result FROM $legal_conditions_table ORDER BY legal_id DESC ";
 		$result = Database::query($sql);
 		$url = Database::fetch_array($result,'ASSOC');
 		$result = $url['count_result'];
+
 		return $result;
 	}
 
@@ -233,12 +253,14 @@ class LegalManager {
 	 * @param int The language id
 	 * @return int The current type of terms and conditions
 	 */
-	public static function get_type_of_terms_and_conditions ($legal_id,$language_id) {
+	public static function get_type_of_terms_and_conditions($legal_id,$language_id)
+    {
 		$legal_conditions_table = Database::get_main_table(TABLE_MAIN_LEGAL);
 		$legal_id=Database::escape_string($legal_id);
 		$language_id=Database::escape_string($language_id);
-		$sql='SELECT type FROM '.$legal_conditions_table.' WHERE legal_id="'.$legal_id.'" AND language_id="'.$language_id.'"';
-		$rs=Database::query($sql);
+		$sql = 'SELECT type FROM '.$legal_conditions_table.' WHERE legal_id="'.$legal_id.'" AND language_id="'.$language_id.'"';
+		$rs = Database::query($sql);
+
 		return Database::result($rs,0,'type');
 	}
 }

+ 2 - 1
main/inc/lib/plugin.class.php

@@ -292,6 +292,7 @@ class Plugin
     {
         // Check whether the language strings for the plugin have already been
         // loaded. If so, no need to load them again.
+
         if (is_null($this->strings)) {
             global $language_interface;
             $root = api_get_path(SYS_PLUGIN_PATH);
@@ -455,7 +456,7 @@ class Plugin
      */
     public function install_course_fields_in_all_courses($add_tool_link = true)
     {
-        // Update existing courses to add conference settings
+        // Update existing courses to add plugin settings
         $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
         $sql = "SELECT id FROM $t_courses ORDER BY id";
         $res = Database::query($sql);

+ 23 - 16
main/inc/local.inc.php

@@ -175,16 +175,22 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
         unset($_user['user_id']);
     }
 
-    //Platform legal terms and conditions
+    // Platform legal terms and conditions
     if (api_get_setting('allow_terms_conditions') == 'true') {
-        if (isset($_POST['login']) && isset($_POST['password']) && isset($_SESSION['term_and_condition']['user_id'])) {
-            $user_id = $_SESSION['term_and_condition']['user_id'];    // user id
+        if (isset($_POST['login']) && isset($_POST['password']) &&
+            isset($_SESSION['term_and_condition']['user_id'])
+        ) {
+            // user id
+            $user_id = $_SESSION['term_and_condition']['user_id'];
             // Update the terms & conditions
             $legal_type = null;
             //verify type of terms and conditions
             if (isset($_POST['legal_info'])) {
                 $info_legal = explode(':', $_POST['legal_info']);
-                $legal_type = LegalManager::get_type_of_terms_and_conditions($info_legal[0], $info_legal[1]);
+                $legal_type = LegalManager::get_type_of_terms_and_conditions(
+                    $info_legal[0],
+                    $info_legal[1]
+                );
             }
 
             //is necessary verify check
@@ -622,9 +628,9 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) {
                 //lookup the user in the main database
                 $user_table = Database::get_main_table(TABLE_MAIN_USER);
                 $sql = "SELECT user_id, username, password, auth_source, active, expiration_date
-                    FROM $user_table
-                    WHERE openid = '$id1'
-                    OR openid = '$id2' ";
+                        FROM $user_table
+                        WHERE openid = '$id1'
+                        OR openid = '$id2' ";
                 $result = Database::query($sql);
                 if ($result !== false) {
                     if (Database::num_rows($result)>0) {
@@ -717,7 +723,9 @@ if (!empty($cDir)) {
 
 // if the requested course is different from the course in session
 
-if (!empty($cidReq) && (!isset($_SESSION['_cid']) or (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))) {
+if (!empty($cidReq) && (!isset($_SESSION['_cid']) or
+    (isset($_SESSION['_cid']) && $cidReq != $_SESSION['_cid']))
+) {
     $cidReset = true;
     $gidReset = true;    // As groups depend from courses, group id is reset
 }
@@ -796,8 +804,8 @@ if (isset($cidReset) && $cidReset) {
         if (!empty($_course)) {
 
             //@TODO real_cid should be cid, for working with numeric course id
-            $_real_cid                      = $_course['real_id'];
-            $_cid                           = $_course['code'];
+            $_real_cid = $_course['real_id'];
+            $_cid = $_course['code'];
 
             Session::write('_real_cid', $_real_cid);
             Session::write('_cid', $_cid);
@@ -853,7 +861,7 @@ if (isset($cidReset) && $cidReset) {
             }
         }
 
-        //Deleting session info
+        // Deleting session info.
         if (api_get_session_id()) {
             Session::erase('id_session');
             Session::erase('session_name');
@@ -880,12 +888,12 @@ if (isset($cidReset) && $cidReset) {
     }
 
     if (empty($_SESSION['_course']) or empty($_SESSION['_cid'])) { //no previous values...
-        $_cid         = -1;        //set default values that will be caracteristic of being unset
-        $_course      = -1;
+        $_cid = -1; // Set default values
+        $_course = -1;
     } else {
 
-        $_cid      = $_SESSION['_cid'   ];
-        $_course   = $_SESSION['_course'];
+        $_cid = $_SESSION['_cid'];
+        $_course = $_SESSION['_course'];
 
         // these lines are usefull for tracking. Indeed we can have lost the id_session and not the cid.
         // Moreover, if we want to track a course with another session it can be usefull
@@ -1154,7 +1162,6 @@ if ((isset($uidReset) && $uidReset) || (isset($cidReset) && $cidReset)) {
                         }
                     }
                 }
-
             }
 
             //If I'm the admin platform i'm a teacher of the course

+ 408 - 0
plugin/courselegal/CourseLegalPlugin.php

@@ -0,0 +1,408 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ * Class CourseLegalPlugin
+ */
+class CourseLegalPlugin extends Plugin
+{
+    public $isCoursePlugin = true;
+
+    // When creating a new course this settings are added to the course
+    public $course_settings = array(
+        array(
+            'name' => 'courselegal',
+            'type' => 'text'
+        )
+    );
+
+    /**
+     * @return CourseLegalPlugin
+     */
+    static function create()
+    {
+        static $result = null;
+        return $result ? $result : $result = new self();
+    }
+
+    /**
+     *
+     */
+    protected function __construct()
+    {
+        parent::__construct(
+            '0.1',
+            'Julio Montoya',
+            array(
+                'tool_enable' => 'boolean'
+            )
+        );
+    }
+
+    /**
+     * @return string
+     */
+    public function getTeacherLink()
+    {
+        $link = null;
+        if (api_is_allowed_to_edit()) {
+            $url = api_get_path(WEB_PLUGIN_PATH).'courselegal/start.php?'.api_get_cidreq();
+            $link = Display::url(
+                get_lang('Legal'),
+                $url,
+                array('class' => 'btn')
+            );
+        }
+
+        return $link;
+    }
+
+    /**
+     * @param int $userId
+     * @param int $courseId
+     * @param int $sessionId
+     *
+     * @return array
+     */
+    public function getUserAcceptedLegal($userId, $courseId, $sessionId)
+    {
+        $userId = intval($userId);
+        $courseId = intval($courseId);
+        $sessionId = intval($sessionId);
+
+        $table = Database::get_main_table('session_rel_course_rel_user_legal');
+        $sql = "SELECT *
+                FROM $table
+                WHERE user_id = $userId AND c_id = $courseId AND session_id = $sessionId";
+        $result = Database::query($sql);
+        $data = array();
+        if (Database::num_rows($result) > 0 ) {
+            $data = Database::fetch_array($result, 'ASSOC');
+        }
+
+        return $data;
+    }
+
+    /**
+     * @param int $userId
+     * @param string $courseCode
+     * @param int $sessionId
+     *
+     * @return bool
+     */
+    public function isUserAcceptedLegal($userId, $courseCode, $sessionId)
+    {
+        $courseInfo = api_get_course_info($courseCode);
+        $courseId = $courseInfo['real_id'];
+        $result = $this->getUserAcceptedLegal($userId, $courseId, $sessionId);
+
+        if (!empty($result)) {
+            if ($result['mail_agreement'] == 1 &&
+                $result['web_agreement'] == 1
+            ) {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    /**
+ * @param int $userId
+ * @param int $courseCode
+ * @param int $sessionId
+ *
+ * @return bool
+ */
+    public function saveUserLegal($userId, $courseCode, $sessionId)
+    {
+        $courseInfo = api_get_course_info($courseCode);
+        $courseId = $courseInfo['real_id'];
+        $data = $this->getUserAcceptedLegal($userId, $courseId, $sessionId);
+
+        $id = false;
+        if (empty($data)) {
+            $table = Database::get_main_table(
+                'session_rel_course_rel_user_legal'
+            );
+            $uniqueId = api_get_unique_id();
+            $values = array(
+                'user_id' => $userId,
+                'c_id' => $courseId,
+                'session_id' => $sessionId,
+                'web_agreement' => 1,
+                'web_agreement_date' => api_get_utc_datetime(),
+                'mail_agreement_link' => $uniqueId
+            );
+            $id = Database::insert($table, $values);
+
+            $url = api_get_path(WEB_CODE_PATH).'course_info/legal.php?web_agreement_link='.$uniqueId.'&course_code='.Security::remove_XSS($courseCode).'&session_id='.$sessionId;
+            $courseUrl = Display::url($url, $url);
+
+            $subject = get_lang("MailAgreement");
+            $message = sprintf(get_lang("MailAgreementWasSentWithClickX"), $courseUrl);
+            MessageManager::send_message_simple($userId, $subject, $message);
+        }
+
+        return $id;
+    }
+
+    /**
+     * @param string $link
+     * @param int $userId
+     * @param int $courseId
+     * @param int $sessionId
+     *
+     * @return bool
+     */
+    public function saveUserMailLegal($link, $userId, $courseId, $sessionId)
+    {
+        $data = $this->getUserAcceptedLegal($userId, $courseId, $sessionId);
+
+        if (empty($data)) {
+            return null;
+        }
+
+        if ($data['mail_agreement_link'] == $link) {
+            $table = Database::get_main_table('session_rel_course_rel_user_legal');
+            $id = $data['id'];
+            $values = array(
+                'mail_agreement' => 1,
+                'mail_agreement_date' => api_get_utc_datetime()
+            );
+            Database::update($table, $values, array('id = ?' => array($id)));
+        }
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     */
+    public function warnUsersByEmail($courseId, $sessionId)
+    {
+        $courseInfo = api_get_course_info_by_id($courseId);
+        $courseCode = $courseInfo['code'];
+
+        if (empty($sessionId)) {
+            $students = CourseManager::get_student_list_from_course_code($courseCode, false);
+        } else {
+            $students = CourseManager::get_student_list_from_course_code($courseCode, true, $sessionId);
+        }
+
+        $url = api_get_course_url($courseCode, $sessionId);
+        $url = Display::url($url, $url);
+
+        $subject = get_lang("AgreementUpdated");
+        $message = sprintf(get_lang("AgreementWasUpdatedClickHere"), $url);
+
+        if (!empty($students)) {
+            foreach ($students as $student) {
+                $userId = $student['user_id'];
+                MessageManager::send_message_simple($userId, $subject, $message);
+            }
+        }
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     */
+    public function removePreviousAgreements($courseId, $sessionId)
+    {
+        $table = Database::get_main_table('session_rel_course_rel_user_legal');
+        $sessionId = intval($sessionId);
+        $courseId = intval($courseId);
+        $sql = "DELETE FROM $table
+                WHERE c_id = '$courseId' AND session_id = $sessionId ";
+        Database::query($sql);
+    }
+
+    /**
+     * @param array $values
+     * @param array  $file $_FILES['uploaded_file']
+     */
+    public function save($values, $file = array(), $deleteFile = false)
+    {
+        $table = Database::get_main_table('session_rel_course_legal');
+
+        $courseId = $values['c_id'];
+        $sessionId = $values['session_id'];
+
+        $conditions = array(
+            'c_id' => $courseId,
+            'session_id' => $sessionId,
+        );
+
+        $legalData = $this->getData($courseId, $sessionId);
+
+        $conditions['content'] = $values['content'];
+
+        $course = api_get_course_info();
+        $coursePath = api_get_path(SYS_COURSE_PATH).$course['directory'].'/courselegal';
+
+        if (!is_dir($coursePath)) {
+            mkdir($coursePath, api_get_permissions_for_new_directories());
+        }
+
+        require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php';
+        $uploadOk = process_uploaded_file($file, false);
+
+        $fileName = null;
+        if ($uploadOk) {
+            $uploadResult = handle_uploaded_document(
+                $course,
+                $file,
+                $coursePath,
+                '/',
+                api_get_user_id(),
+                api_get_group_id(),
+                null,
+                false,
+                false,
+                false,
+                true
+            );
+
+            if ($uploadResult) {
+                $fileName = basename($uploadResult);
+                // Delete old one if exists.
+                if ($legalData) {
+                    if (!empty($legalData['filename'])) {
+                        $fileToDelete = $coursePath.'/'.$legalData['filename'];
+                        if (file_exists($fileToDelete)) {
+                            unlink($fileToDelete);
+                        }
+                    }
+                }
+            }
+        }
+        $conditions['filename'] = $fileName;
+
+        if (empty($legalData)) {
+            $id = Database::insert($table, $conditions);
+        } else {
+            $id = $legalData['id'];
+            Database::update(
+                $table,
+                array(
+                    'content' => $values['content'],
+                    'filename' => $fileName
+                ),
+                array('id = ? ' => $id)
+            );
+        }
+
+        if ($deleteFile) {
+            Database::update(
+                $table,
+                array('filename' => ''),
+                array('id = ? ' => $id)
+            );
+            if (!empty($legalData['filename'])) {
+                $fileToDelete = $coursePath . '/' . $legalData['filename'];
+                if (file_exists($fileToDelete)) {
+                    unlink($fileToDelete);
+                }
+            }
+        }
+
+        if (isset($values['remove_previous_agreements']) && !empty($values['remove_previous_agreements'])) {
+            $this->removePreviousAgreements($courseId, $sessionId);
+        }
+
+        if (isset($values['warn_users_by_email']) && !empty($values['warn_users_by_email'])) {
+            $this->warnUsersByEmail($courseId, $sessionId);
+        }
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     * @return array|mixed
+     */
+    public function getData($courseId, $sessionId)
+    {
+        $table = Database::get_main_table('session_rel_course_legal');
+        $conditions = array(
+            'c_id  = ? AND session_id = ? ' => array(
+                $courseId,
+                $sessionId
+            )
+        );
+
+        $result = Database::select('*', $table, array('where' => $conditions));
+        $legalData = isset($result) && !empty($result) ? current($result) : array();
+
+        return $legalData;
+    }
+
+    /**
+     * @param int $courseId
+     * @param int $sessionId
+     *
+     * @return string
+     */
+    public function getCurrentFile($courseId, $sessionId)
+    {
+        $data = $this->getData($courseId, $sessionId);
+
+        if (isset($data['filename']) && !empty($data['filename'])) {
+            $course = api_get_course_info_by_id($courseId);
+
+            $coursePath = api_get_path(SYS_COURSE_PATH).$course['directory'].'/courselegal';
+            $file = $coursePath.'/'.$data['filename'];
+
+            if (file_exists($file)) {
+                return Display::url(
+                    $data['filename'],
+                    api_get_path(WEB_COURSE_PATH).$course['directory'].'/courselegal/'.$data['filename']
+                );
+            }
+        }
+    }
+
+    public function install()
+    {
+        $table = Database::get_main_table('session_rel_course_legal');
+        $sql = "CREATE TABLE IF NOT EXISTS $table (
+                    id int PRIMARY KEY AUTO_INCREMENT,
+                    c_id int,
+                    session_id int,
+                    content text,
+                    filename varchar(255)
+                )";
+        Database::query($sql);
+
+        $table = Database::get_main_table('session_rel_course_rel_user_legal');
+
+        $sql = "CREATE TABLE IF NOT EXISTS $table (
+                    id int PRIMARY KEY AUTO_INCREMENT,
+                    user_id int,
+                    c_id int,
+                    session_id int,
+                    web_agreement varchar(255),
+                    web_agreement_date datetime,
+                    mail_agreement varchar(255),
+                    mail_agreement_date datetime,
+                    mail_agreement_link varchar(255)
+                )";
+        Database::query($sql);
+
+        // Installing course settings
+        $this->install_course_fields_in_all_courses(false);
+    }
+
+    public function uninstall()
+    {
+        $table = Database::get_main_table('session_rel_course_legal');
+        $sql = "DROP TABLE $table ";
+        Database::query($sql);
+
+        $table = Database::get_main_table('session_rel_course_rel_user_legal');
+        $sql = "DROP TABLE $table ";
+        Database::query($sql);
+
+        // Deleting course settings
+        $this->uninstall_course_fields_in_all_courses($this->course_settings);
+    }
+}

+ 6 - 0
plugin/courselegal/config.php

@@ -0,0 +1,6 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+require_once __DIR__ . '/../../main/inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'plugin.class.php';
+require_once __DIR__.'/CourseLegalPlugin.php';

+ 1 - 0
plugin/courselegal/index.php

@@ -0,0 +1 @@
+<?php

+ 9 - 0
plugin/courselegal/install.php

@@ -0,0 +1,9 @@
+<?php
+/* For license terms, see /license.txt */
+
+require_once dirname(__FILE__) . '/config.php';
+
+if (!api_is_platform_admin()) {
+    die ('You must have admin permissions to install plugins');
+}
+CourseLegalPlugin::create()->install();

+ 4 - 0
plugin/courselegal/lang/english.php

@@ -0,0 +1,4 @@
+<?php
+
+$strings['plugin_title'] = "Course agreements";
+$strings['plugin_comment'] = "Course agreements";

+ 4 - 0
plugin/courselegal/lang/spanish.php

@@ -0,0 +1,4 @@
+<?php
+
+$strings['plugin_title'] = "Course agreements";
+$strings['plugin_comment'] = "Course agreements";

+ 5 - 0
plugin/courselegal/plugin.php

@@ -0,0 +1,5 @@
+<?php
+
+require_once dirname(__FILE__) . '/config.php';
+
+$plugin_info = CourseLegalPlugin::create()->get_info();

+ 24 - 0
plugin/courselegal/readme.txt

@@ -0,0 +1,24 @@
+README
+
+1. Enabled the plugin from the list of plugins.
+2. Click "Configure" once the plugin was enabled.
+3. Select tool_enable = Yes and save.
+4. Go into a *course* (not course session) and enter the Settings tool.
+5. In the "Course access" section select "Enable legal terms" and
+   change the course visibility to "Private" and save.
+6. Go to a course or a course in a session a new button "Legal" will appear
+   in the course home.
+7. Click the button "Legal". Fill the form with the content and a file you want
+to be shown to the students. There are other options in the form, like:
+ - Send an email to all users.
+ - Delete all previous agreements
+ - Delete the file.
+
+ The file are saved in courses/XX/courselegal/
+
+8. Once the form was saved, a new form will appear for the registered users.
+   The student has to accept the form.
+   When the form is accepted an email will be sent to the user via email and
+   then Chamilo message tool
+9. The user has to click in the URL. Once the user clicked to the URL the user
+   will have access to the course.

+ 51 - 0
plugin/courselegal/start.php

@@ -0,0 +1,51 @@
+<?php
+/* For license terms, see /license.txt */
+$language_file = array('document','gradebook');
+
+require_once dirname(__FILE__) . '/config.php';
+
+// Course legal
+$enabled = api_get_plugin_setting('courselegal', 'tool_enable');
+
+if ($enabled != 'true') {
+    api_not_allowed(true);
+}
+
+if (!api_is_allowed_to_edit()) {
+    api_not_allowed(true);
+}
+
+$legal = CourseLegalPlugin::create();
+$url = api_get_self().'?'.api_get_cidreq();
+$courseId = api_get_course_int_id();
+$sessionId = api_get_session_id();
+
+$form = new FormValidator('plugin', 'post', $url );
+$form->addElement('header', get_lang('CourseLegal'));
+$form->addElement('hidden', 'session_id', $sessionId);
+$form->addElement('hidden', 'c_id', $courseId);
+$form->addElement('textarea', 'content', get_lang('Text'));
+$form->addElement('file', 'uploaded_file', get_lang('File'));
+$file = $legal->getCurrentFile($courseId, $sessionId);
+
+if (!empty($file)) {
+    $form->addElement('label', get_lang('File'), $file);
+}
+
+$form->addElement('checkbox', 'delete_file', null, get_lang('DeleteFile'));
+$form->addElement('checkbox', 'remove_previous_agreements', null, get_lang('RemoveAllUserAgreements'));
+$form->addElement('checkbox', 'warn_users_by_email', null, get_lang('WarnAllUsersByEmail'));
+$form->addElement('button', 'submit', get_lang('Send'));
+
+$form->setDefaults($legal->getData($courseId, $sessionId));
+
+if ($form->validate()) {
+    $values = $form->getSubmitValues();
+    $file = isset($_FILES['uploaded_file']) ? $_FILES['uploaded_file'] : array();
+    $deleteFile = isset($values['delete_file']) ? $values['delete_file'] : false;
+    $legal->save($values, $file, $deleteFile);
+    header('Location: '.$url);
+    exit;
+}
+Display::display_header(get_lang('CourseLegal'));
+$form->display();