Browse Source

Merge branch 'AngelFQC-BT9461' into 1.10.x

Yannick Warnier 10 years ago
parent
commit
b12bb8f241

+ 70 - 15
plugin/advanced_subscription/ajax/advanced_subscription.ajax.php

@@ -5,7 +5,6 @@
  * @author Daniel Alejandro Barreto Alva <daniel.barreto@beeznest.com>
  * @package chamilo.plugin.advanced_subscription
  */
-
 /**
  * Init
  */
@@ -32,7 +31,7 @@ $result = array('error' => true, 'errorMessage' => get_lang('ThereWasAnError'));
 // Check if data is valid or is for start subscription
 $verified = $plugin->checkHash($data, $hash) || $data['action'] == 'subscribe';
 if ($verified) {
-    switch($data['action']) {
+    switch ($data['action']) {
         case 'check': // Check minimum requirements
             try {
                 $res = AdvancedSubscriptionPlugin::create()->isAllowedToDoRequest($data['studentUserId'], $data);
@@ -50,18 +49,33 @@ if ($verified) {
             break;
         case 'subscribe': // Subscription
             // Start subscription to queue
-            $res = AdvancedSubscriptionPlugin::create()->startSubscription($data['studentUserId'], $data['sessionId'], $data);
+            $res = AdvancedSubscriptionPlugin::create()->startSubscription(
+                $data['studentUserId'],
+                $data['sessionId'],
+                $data
+            );
             // Check if queue subscription was successful
             if ($res === true) {
                 $legalEnabled = api_get_plugin_setting('courselegal', 'tool_enable');
                 if ($legalEnabled) {
                     // Save terms confirmation
-                    CourseLegalPlugin::create()->saveUserLegal($data['studentUserId'], $data['courseId'], $data['sessionId']);
+                    CourseLegalPlugin::create()->saveUserLegal(
+                        $data['studentUserId'],
+                        $data['courseId'],
+                        $data['sessionId'],
+                        false
+                    );
                 }
                 // Prepare data
                 // Get session data
                 // Assign variables
-                $fieldsArray = array('description', 'target', 'mode', 'publication_end_date', 'recommended_number_of_participants');
+                $fieldsArray = array(
+                    'description',
+                    'target',
+                    'mode',
+                    'publication_end_date',
+                    'recommended_number_of_participants'
+                );
                 $sessionArray = api_get_session_info($data['sessionId']);
                 $extraSession = new ExtraFieldValue('session');
                 $extraField = new ExtraField('session');
@@ -75,7 +89,11 @@ if ($verified) {
                 }
 
                 $mergedArray = array_merge(array($data['sessionId']), array_keys($fields));
-                $sessionFieldValueList = $extraSession->get_all(array('session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray));
+                $sessionFieldValueList = $extraSession->get_all(
+                    array(
+                        'session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray
+                    )
+                );
                 foreach ($sessionFieldValueList as $sessionFieldValue) {
                     // Check if session field value is set in session field list
                     if (isset($fields[$sessionFieldValue['field_id']])) {
@@ -87,8 +105,18 @@ if ($verified) {
                 }
                 // Get student data
                 $studentArray = api_get_user_info($data['studentUserId']);
-                $studentArray['picture'] = UserManager::get_user_picture_path_by_id($studentArray['user_id'], 'web', false, true);
-                $studentArray['picture'] = UserManager::get_picture_user($studentArray['user_id'], $studentArray['picture']['file'], 22, USER_IMAGE_SIZE_MEDIUM);
+                $studentArray['picture'] = UserManager::get_user_picture_path_by_id(
+                    $studentArray['user_id'],
+                    'web',
+                    false,
+                    true
+                );
+                $studentArray['picture'] = UserManager::get_picture_user(
+                    $studentArray['user_id'],
+                    $studentArray['picture']['file'],
+                    22,
+                    USER_IMAGE_SIZE_MEDIUM
+                );
                 // Get superior data if exist
                 $superiorId = UserManager::getStudentBoss($data['studentUserId']);
                 if (!empty($superiorId)) {
@@ -124,7 +152,10 @@ if ($verified) {
                         $data['admin_view_url'] = api_get_path(WEB_PLUGIN_PATH) .
                             'advanced_subscription/src/admin_view.php?s=' . $data['sessionId'];
                         // Send mails
-                        $result['mailIds'] = $plugin->sendMail($data, ADVANCED_SUBSCRIPTION_ACTION_STUDENT_REQUEST_NO_BOSS);
+                        $result['mailIds'] = $plugin->sendMail(
+                            $data,
+                            ADVANCED_SUBSCRIPTION_ACTION_STUDENT_REQUEST_NO_BOSS
+                        );
                         // Check if mails were sent
                         if (!empty($result['mailIds'])) {
                             $result['error'] = false;
@@ -189,7 +220,13 @@ if ($verified) {
                 if ($res === true) {
                     // Prepare data
                     // Prepare session data
-                    $fieldsArray = array('description', 'target', 'mode', 'publication_end_date', 'recommended_number_of_participants');
+                    $fieldsArray = array(
+                        'description',
+                        'target',
+                        'mode',
+                        'publication_end_date',
+                        'recommended_number_of_participants'
+                    );
                     $sessionArray = api_get_session_info($data['sessionId']);
                     $extraSession = new ExtraFieldValue('session');
                     $extraField = new ExtraField('session');
@@ -203,7 +240,9 @@ if ($verified) {
                     }
 
                     $mergedArray = array_merge(array($data['sessionId']), array_keys($fields));
-                    $sessionFieldValueList = $extraSession->get_all(array('session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray));
+                    $sessionFieldValueList = $extraSession->get_all(
+                        array('session_id = ? field_id IN ( ?, ?, ?, ?, ?, ?, ? )' => $mergedArray)
+                    );
                     foreach ($sessionFieldValueList as $sessionFieldValue) {
                         // Check if session field value is set in session field list
                         if (isset($fields[$sessionFieldValue['field_id']])) {
@@ -215,8 +254,18 @@ if ($verified) {
                     }
                     // Prepare student data
                     $studentArray = api_get_user_info($data['studentUserId']);
-                    $studentArray['picture'] = UserManager::get_user_picture_path_by_id($studentArray['user_id'], 'web', false, true);
-                    $studentArray['picture'] = UserManager::get_picture_user($studentArray['user_id'], $studentArray['picture']['file'], 22, USER_IMAGE_SIZE_MEDIUM);
+                    $studentArray['picture'] = UserManager::get_user_picture_path_by_id(
+                        $studentArray['user_id'],
+                        'web',
+                        false,
+                        true
+                    );
+                    $studentArray['picture'] = UserManager::get_picture_user(
+                        $studentArray['user_id'],
+                        $studentArray['picture']['file'],
+                        22,
+                        USER_IMAGE_SIZE_MEDIUM
+                    );
                     // Prepare superior data
                     $superiorId = UserManager::getStudentBoss($data['studentUserId']);
                     if (!empty($superiorId)) {
@@ -240,7 +289,8 @@ if ($verified) {
                     $data['admins'] = $adminsArray;
                     $data['session'] = $sessionArray;
                     $data['signature'] = api_get_setting('Institution');
-                    $data['admin_view_url'] = api_get_path(WEB_PLUGIN_PATH) . 'advanced_subscription/src/admin_view.php?s=' . $data['sessionId'];
+                    $data['admin_view_url'] = api_get_path(WEB_PLUGIN_PATH)
+                        . 'advanced_subscription/src/admin_view.php?s=' . $data['sessionId'];
                     // Check if exist and action in data
                     if (empty($data['mailAction'])) {
                         // set action in data by new status
@@ -264,7 +314,12 @@ if ($verified) {
 
                     // Student Session inscription
                     if ($data['newStatus'] == ADVANCED_SUBSCRIPTION_QUEUE_STATUS_ADMIN_APPROVED) {
-                        SessionManager::suscribe_users_to_session($data['sessionId'], array($data['studentUserId']), null, false);
+                        SessionManager::suscribe_users_to_session(
+                            $data['sessionId'],
+                            array($data['studentUserId']),
+                            null,
+                            false
+                        );
                     }
 
                     // Send mails

+ 1 - 2
plugin/advanced_subscription/lang/english.php

@@ -22,7 +22,7 @@ $strings['min_profile_percentage_help'] = "Percentage number( > 0.00 y < 100.00)
 
 /* String for error message about requirements */
 $strings['AdvancedSubscriptionNotConnected'] = "You are not connected to platform. Please login first";
-$strings['AdvancedSubscriptionProfileIncomplete'] = "Your percentage completed profile require to exceed minimum percentage. Please complete percentage";
+$strings['AdvancedSubscriptionProfileIncomplete'] = "You must complete at least <strong>%d percent</strong> of your profile. You have only completed <strong>%d percent</strong> at this point";
 $strings['AdvancedSubscriptionIncompleteInduction'] = "You have not yet completed induction course. Please complete it first";
 $strings['AdvancedSubscriptionCostXLimitReached'] = "We are sorry, you have already reached yearly limit %s TUV cost for courses ";
 $strings['AdvancedSubscriptionTimeXLimitReached'] = "We are sorry, you have already reached yearly limit %s hours for courses";
@@ -138,4 +138,3 @@ $strings['MailContentReminderMaxSuperior'] = 'We kindly remind you that we have
 $strings['MailContentReminderMaxSuperiorSecond'] = 'This course have limited vacancies and has received a high subscription request rate, So we recommend all areas to accept at most <strong>%s</strong> candidates. We invite you to accept or reject the inscription request by clicking the corresponding button for each collaborator.';
 
 $strings['YouMustAcceptTermsAndConditions'] = 'To subscribe to course <strong>%s</strong>, you must accept these terms and conditions.';
-$strings['YouMustFillXPercentOfYourProfileAtLeast'] = "You must fill the <strong>%d percent</strong> of your profile at least. For now you has filled the <strong>%d percent</strong>";

+ 1 - 2
plugin/advanced_subscription/lang/spanish.php

@@ -22,7 +22,7 @@ $strings['min_profile_percentage_help'] = 'Número porcentage ( > 0.00 y < 100.0
 
 /* String for error message about requirements */
 $strings['AdvancedSubscriptionNotConnected'] = "Usted no está conectado en la plataforma. Por favor ingrese su usuario / constraseña para poder inscribirse";
-$strings['AdvancedSubscriptionProfileIncomplete'] = "Su perfil no es lo suficientemente completo para poder inscribirse al curso. Por favor complete su perfil";
+$strings['AdvancedSubscriptionProfileIncomplete'] = "Debe llenar el <strong>%d porciento</strong> de tu perfil como mínimo. Por ahora has llenado el <strong>%d porciento</strong>";
 $strings['AdvancedSubscriptionIncompleteInduction'] = "Usted aún no ha completado el curso de inducción. Por favor complete el curso inducción";
 $strings['AdvancedSubscriptionCostXLimitReached'] = "Lo sentimos, usted ya ha alcanzado el límite anual de %s UIT para los cursos que ha seguido este año";
 $strings['AdvancedSubscriptionTimeXLimitReached'] = "Lo sentimos, usted ya ha alcanzado el límite anual de %s horas para los cursos que ha seguido este año";
@@ -138,4 +138,3 @@ $strings['MailContentReminderMaxSuperior'] = 'Le recordamos que hemos recibido l
 $strings['MailContentReminderMaxSuperiorSecond'] = 'Este curso tiene una cantidad de cupos limitados y ha recibido una alta tasa de solicitudes de inscripción, por lo que recomendamos que cada área apruebe un máximo de <strong>%s</strong> candidatos. Le invitamos a aprobar o desaprobar las suscripciones, dando clic en el botón correspondiente a continuación para cada colaborador.';
 
 $strings['YouMustAcceptTermsAndConditions'] = 'Para inscribirse al curso <strong>%s</strong>, debe aceptar estos términos y condiciones.';
-$strings['YouMustFillXPercentOfYourProfileAtLeast'] = "Debes llenar el <strong>%d porciento</strong> de tu perfil como mínimo. Por ahora has llenado el <strong>%d porciento</strong>";

+ 153 - 89
plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php

@@ -10,6 +10,8 @@
 class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
 {
     protected $strings;
+    private $errorMessages;
+
     /**
      * Constructor
      */
@@ -29,6 +31,8 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
         );
 
         parent::__construct('1.0', 'Imanol Losada, Daniel Barreto', $parameters);
+
+        $this->errorMessages = array();
     }
 
     /**
@@ -136,115 +140,175 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
         Database::query("DELETE FROM $settingsTable WHERE subkey = 'advanced_subscription'");
     }
 
+    /**
+     * Get the error messages list
+     * @return array The message list
+     */
+    public function getErrorMessages()
+    {
+        return $this->errorMessages;
+    }
+
     /**
      * Return true if user is allowed to be added to queue for session subscription
      * @param int $userId
      * @param array $params MUST have keys:
      * "is_connected" Indicate if the user is online on external web
      * "profile_completed" Percentage of completed profile, given by WS
+     * @param boolean $collectErrors Optional. Default is false. Whether collect all errors or throw exeptions
      * @throws Exception
      * @return bool
      */
-    public function isAllowedToDoRequest($userId, $params = array())
+    public function isAllowedToDoRequest($userId, $params = array(), $collectErrors = false)
     {
-        $isAllowed = null;
         $plugin = self::create();
         $wsUrl = $plugin->get('ws_url');
         // Student always is connected
         $isConnected = true;
-        if ($isConnected) {
-            $profileCompletedMin = (float) $plugin->get('min_profile_percentage');
-            if (is_string($wsUrl) && !empty($wsUrl)) {
-                $options = array(
-                    'location' => $wsUrl,
-                    'uri' => $wsUrl
-                );
-                $client = new SoapClient(null, $options);
-                $userInfo = UserManager::get_user_info_by_id($userId);
-                try {
-                    $profileCompleted = $client->__soapCall('getProfileCompletionPercentage', $userInfo['extra']['drupal_user_id']);
-                } catch (\Exception $e) {
-                    $profileCompleted = 0;
-                }
-            } elseif (isset($params['profile_completed'])) {
-                $profileCompleted = (float) $params['profile_completed'];
-            } else {
-                $profileCompleted = 0;
+
+        if (!$isConnected) {
+            $this->errorMessages[] = $this->get_lang('AdvancedSubscriptionNotConnected');
+
+            if (!$collectErrors) {
+                throw new \Exception($this->get_lang('AdvancedSubscriptionNotConnected'));
             }
-            if ($profileCompleted >= $profileCompletedMin) {
-                $checkInduction = $plugin->get('check_induction');
-                // @TODO: check if user have completed at least one induction session
-                $completedInduction = true;
-                if (!$checkInduction || $completedInduction) {
-                    $uitMax = $plugin->get('yearly_cost_unit_converter');
-                    $uitMax *= $plugin->get('yearly_cost_limit');
-                    $uitUser = 0;
-                    $now = new DateTime(api_get_utc_datetime());
-                    $newYearDate = $plugin->get('course_session_credit_year_start_date');
-                    $newYearDate = !empty($newYearDate) ?
-                        new \DateTime($newYearDate . $now->format('/Y')) :
-                        $now;
-                    $extra = new ExtraFieldValue('session');
-                    $joinSessionTable = Database::get_main_table(TABLE_MAIN_SESSION_USER) . ' su INNER JOIN ' .
-                        Database::get_main_table(TABLE_MAIN_SESSION) . ' s ON s.id = su.id_session';
-                    $whereSessionParams = 'su.relation_type = ? AND s.date_start >= ? AND su.id_user = ?';
-                    $whereSessionParamsValues = array(
-                        0,
-                        $newYearDate->format('Y-m-d'),
-                        $userId
-                    );
-                    $whereSession = array(
-                        'where' => array(
-                            $whereSessionParams => $whereSessionParamsValues
-                        )
-                    );
-                    $selectSession = 's.id AS id';
-                    $sessions = Database::select(
-                        $selectSession,
-                        $joinSessionTable,
-                        $whereSession
-                    );
+        }
 
-                    if (is_array($sessions) && count($sessions) > 0) {
-                        foreach ($sessions as $session) {
-                            $var = $extra->get_values_by_handler_and_field_variable($session['id'], 'cost');
-                            $uitUser += $var['field_value'];
-                        }
-                    }
-                    if ($uitMax >= $uitUser) {
-                        $expendedTimeMax = $plugin->get('yearly_hours_limit');
-                        $expendedTime = 0;
-                        if (is_array($sessions) && count($sessions) > 0) {
-                            foreach ($sessions as $session) {
-                                $var = $extra->get_values_by_handler_and_field_variable($session['id'], 'teaching_hours');
-                                $expendedTime += $var['field_value'];
-                            }
-                        }
-                        if ($expendedTimeMax >= $expendedTime) {
-                            $expendedNumMax = $plugin->get('courses_count_limit');
-                            $expendedNum = count($sessions);
-                            if ($expendedNumMax >= $expendedNum) {
-                                $isAllowed = true;
-                            } else {
-                                throw new \Exception($this->get_lang('AdvancedSubscriptionCourseXLimitReached'));
-                            }
-                        } else {
-                            throw new \Exception($this->get_lang('AdvancedSubscriptionTimeXLimitReached'));
-                        }
-                    } else {
-                        throw new \Exception($this->get_lang('AdvancedSubscriptionCostXLimitReached'));
-                    }
-                } else {
-                    throw new \Exception($this->get_lang('AdvancedSubscriptionIncompleteInduction'));
-                }
-            } else {
-                throw new \Exception($this->get_lang('AdvancedSubscriptionProfileIncomplete'));
+        $profileCompletedMin = (float) $plugin->get('min_profile_percentage');
+
+        if (is_string($wsUrl) && !empty($wsUrl)) {
+            $options = array(
+                'location' => $wsUrl,
+                'uri' => $wsUrl
+            );
+            $client = new SoapClient(null, $options);
+            $userInfo = UserManager::get_user_info_by_id($userId);
+            try {
+                $profileCompleted = $client->__soapCall('getProfileCompletionPercentage', $userInfo['extra']['drupal_user_id']);
+            } catch (\Exception $e) {
+                $profileCompleted = 0;
             }
+        } elseif (isset($params['profile_completed'])) {
+            $profileCompleted = (float) $params['profile_completed'];
         } else {
-            throw new \Exception($this->get_lang('AdvancedSubscriptionNotConnected'));
+            $profileCompleted = 0;
+        }
+
+        if ($profileCompleted < $profileCompletedMin) {
+            $errorMessage = sprintf(
+                $this->get_lang('AdvancedSubscriptionProfileIncomplete'),
+                $profileCompletedMin,
+                $profileCompleted
+            );
+
+            $this->errorMessages[] = $errorMessage;
+
+            if (!$collectErrors) {
+                throw new \Exception($errorMessage);
+            }
+        }
+
+        $checkInduction = $plugin->get('check_induction');
+        // @TODO: check if user have completed at least one induction session
+        $completedInduction = true;
+
+        if ($checkInduction && !$completedInduction) {
+            $this->errorMessages[] = $this->get_lang('AdvancedSubscriptionIncompleteInduction');
+
+            if (!$collectErrors) {
+                throw new \Exception($this->get_lang('AdvancedSubscriptionIncompleteInduction'));
+            }
+        }
+
+        $uitMax = $plugin->get('yearly_cost_unit_converter');
+        $uitMax *= $plugin->get('yearly_cost_limit');
+        $uitUser = 0;
+        $now = new DateTime(api_get_utc_datetime());
+        $newYearDate = $plugin->get('course_session_credit_year_start_date');
+        $newYearDate = !empty($newYearDate) ?
+            new \DateTime($newYearDate . $now->format('/Y')) :
+            $now;
+        $extra = new ExtraFieldValue('session');
+        $joinSessionTable = Database::get_main_table(TABLE_MAIN_SESSION_USER) . ' su INNER JOIN ' .
+            Database::get_main_table(TABLE_MAIN_SESSION) . ' s ON s.id = su.id_session';
+        $whereSessionParams = 'su.relation_type = ? AND s.date_start >= ? AND su.id_user = ?';
+        $whereSessionParamsValues = array(
+            0,
+            $newYearDate->format('Y-m-d'),
+            $userId
+        );
+        $whereSession = array(
+            'where' => array(
+                $whereSessionParams => $whereSessionParamsValues
+            )
+        );
+        $selectSession = 's.id AS id';
+        $sessions = Database::select(
+            $selectSession,
+            $joinSessionTable,
+            $whereSession
+        );
+
+        if (is_array($sessions) && count($sessions) > 0) {
+            foreach ($sessions as $session) {
+                $var = $extra->get_values_by_handler_and_field_variable($session['id'], 'cost');
+                $uitUser += $var['field_value'];
+            }
+        }
+
+        if ($uitMax < $uitUser) {
+            $errorMessage = sprintf(
+                $this->get_lang('AdvancedSubscriptionCostXLimitReached'),
+                $uitMax
+            );
+
+            $this->errorMessages[] = $errorMessage;
+
+            if (!$collectErrors) {
+                throw new \Exception($errorMessage);
+            }
+        }
+
+        $expendedTimeMax = $plugin->get('yearly_hours_limit');
+        $expendedTime = 0;
+
+        if (is_array($sessions) && count($sessions) > 0) {
+            foreach ($sessions as $session) {
+                $var = $extra->get_values_by_handler_and_field_variable($session['id'], 'teaching_hours');
+                $expendedTime += $var['field_value'];
+            }
+        }
+
+        if ($expendedTimeMax < $expendedTime) {
+            $errorMessage = sprintf(
+                $this->get_lang('AdvancedSubscriptionTimeXLimitReached'),
+                $expendedTimeMax
+            );
+
+            $this->errorMessages[] = $errorMessage;
+
+            if (!$collectErrors) {
+                throw new \Exception($errorMessage);
+            }
+        }
+
+        $expendedNumMax = $plugin->get('courses_count_limit');
+        $expendedNum = count($sessions);
+
+        if ($expendedNumMax < $expendedNum) {
+            $errorMessage = sprintf(
+                $this->get_lang('AdvancedSubscriptionCourseXLimitReached'),
+                $expendedNumMax
+            );
+
+            $this->errorMessages[] = $errorMessage;
+
+            if (!$collectErrors) {
+                throw new \Exception($errorMessage);
+            }
         }
 
-        return $isAllowed;
+        return empty($this->errorMessages);
     }
 
     /**

+ 13 - 3
plugin/advanced_subscription/src/terms_and_conditions.php

@@ -24,7 +24,18 @@ $data['termsRejected'] = isset($_REQUEST['r']) ? intval($_REQUEST['r']) : 0;
 // Init template
 $tpl = new Template($plugin->get_lang('plugin_title'));
 
-$requiredMinimun = $plugin->get('min_profile_percentage');
+$isAllowToDoRequest = $plugin->isAllowedToDoRequest(
+    $data['studentUserId'],
+    array(
+        'is_connected' => $data['is_connected'],
+        'profile_completed' => $data['profile_completed']
+    ),
+    true
+);
+
+if (!$isAllowToDoRequest) {
+    $tpl->assign('errorMessages', $plugin->getErrorMessages());
+}
 
 if (
     !empty($data['sessionId']) &&
@@ -76,7 +87,6 @@ $tpl->assign('student', $data['student']);
 $tpl->assign('sessionId', $data['sessionId']);
 $tpl->assign('termsContent', $termsContent);
 $tpl->assign('termsFiles', $termFiles);
-$tpl->assign('profileCompleted', $data['profile_completed']);
-$tpl->assign('percentMinimun', $requiredMinimun);
+
 $content = $tpl->fetch('/advanced_subscription/views/terms_and_conditions.tpl');
 echo $content;

+ 8 - 2
plugin/advanced_subscription/views/terms_and_conditions.tpl

@@ -25,11 +25,17 @@
     {{ "YouMustAcceptTermsAndConditions"  | get_plugin_lang("AdvancedSubscriptionPlugin") | format(session.name) }}
 </div>
 {% endif %}
-{% if percentMinimun > profileCompleted %}
+
+{% if errorMessages is defined %}
     <div class="alert alert-warning legal-terms-popup">
-        {{ "YouMustFillXPercentOfYourProfileAtLeast"  | get_plugin_lang("AdvancedSubscriptionPlugin") | format(percentMinimun, profileCompleted) }}
+        <ul>
+            {% for errorMessage in errorMessages %}
+                <li>{{ errorMessage }}</li>
+            {% endfor %}
+        </ul>
     </div>
 {% endif %}
+
 <div class="legal-terms legal-terms-popup">
     {{ termsContent }}
 </div>

+ 5 - 3
plugin/courselegal/CourseLegalPlugin.php

@@ -111,10 +111,10 @@ class CourseLegalPlugin extends Plugin
     * @param int $userId
     * @param int $courseCode
     * @param int $sessionId
-    *
+    * @param boolean $sendEmail Optional. Indicate whether the mail must be sent. Default is true
     * @return bool
     */
-    public function saveUserLegal($userId, $courseCode, $sessionId)
+    public function saveUserLegal($userId, $courseCode, $sessionId, $sendEmail = true)
     {
         $courseInfo = api_get_course_info($courseCode);
         $courseId = $courseInfo['real_id'];
@@ -136,7 +136,9 @@ class CourseLegalPlugin extends Plugin
             );
             $id = Database::insert($table, $values);
 
-            $this->sendMailLink($uniqueId, $userId, $courseId, $sessionId);
+            if ($sendEmail) {
+                $this->sendMailLink($uniqueId, $userId, $courseId, $sessionId);
+            }
         }
 
         return $id;