From 7bf47ed59c8dfd83acae5baeeeb2c4e176261351 Mon Sep 17 00:00:00 2001 From: Julio Montoya Date: Wed, 18 Feb 2015 09:14:14 +0100 Subject: [PATCH] Adding Event and ExerciseLib classes. --- index.php | 6 +- main/admin/configure_homepage.php | 20 +- main/admin/event_type.php | 4 +- main/admin/settings.lib.php | 10 +- main/admin/settings.php | 6 +- main/admin/special_exports.php | 2 +- main/admin/sub_language.class.php | 2 +- main/announcements/download.php | 2 +- main/attendance/layout.php | 2 +- main/auth/external_login/login.ldap.php | 3 +- main/auth/external_login/login.ws.php | 3 +- main/auth/external_login/newUser.ldap.php | 32 +- main/auth/external_login/newUser.php | 2 +- main/auth/inscription.php | 2 +- main/auth/ldap/login.php | 2 +- .../lib/shibboleth_session.class.php | 6 +- main/auth/sso/sso.Drupal.class.php | 42 +- main/auth/sso/sso.class.php | 36 +- main/blog/download.php | 2 +- main/calendar/agenda.php | 2 +- main/calendar/download.php | 2 +- main/chat/chat.php | 2 +- .../ajax_controller.class.php | 34 +- main/course_description/controller.class.php | 54 +- main/course_description/layout.php | 6 +- main/course_home/course_home.php | 2 +- main/course_progress/layout.php | 6 +- main/course_progress/layout_no_header.php | 2 +- main/document/create_audio.php | 2 +- main/document/create_document.php | 2 +- main/document/create_draw.php | 2 +- main/document/create_paint.php | 2 +- main/document/document.php | 6 +- main/document/document_lite.php | 4 +- main/document/download.php | 2 +- main/document/download_scorm.php | 10 +- main/document/downloadfolder.inc.php | 2 +- main/document/edit_document.php | 2 +- main/document/edit_draw.php | 2 +- main/document/edit_paint.php | 2 +- main/document/file.php | 4 +- main/document/record_audio.php | 3 +- main/document/record_audio_wami.php | 2 +- main/document/webcam_clip.php | 3 +- main/dropbox/index.php | 2 +- main/exercice/Hpdownload.php | 4 +- main/exercice/admin.php | 7 +- main/exercice/exercice.php | 16 +- main/exercice/exercise.class.php | 49 +- main/exercice/exercise.lib.php | 2990 -------------- main/exercice/exercise_reminder.php | 4 +- main/exercice/exercise_report.php | 2 +- main/exercice/exercise_result.php | 12 +- main/exercice/exercise_show.php | 10 +- main/exercice/exercise_submit.php | 20 +- main/exercice/overview.php | 8 +- main/exercice/question_list_admin.inc.php | 2 +- main/exercice/question_pool.php | 4 +- main/exercice/result.php | 2 +- main/exercice/stats.php | 14 +- main/exercice/testcategory.class.php | 12 +- main/forum/download.php | 2 +- main/forum/forumsearch.php | 2 +- main/forum/index.php | 2 +- main/glossary/ajax_controller.class.php | 16 +- main/glossary/controller.class.php | 36 +- main/glossary/index.php | 2 +- main/gradebook/lib/be/category.class.php | 2 +- main/inc/ajax/course.ajax.php | 2 +- main/inc/ajax/events.ajax.php | 4 +- main/inc/ajax/exercise.ajax.php | 10 +- main/inc/ajax/model.ajax.php | 12 +- main/inc/ajax/user_manager.ajax.php | 4 +- main/inc/global.inc.php | 4 +- main/inc/lib/add_course.lib.inc.php | 2 +- main/inc/lib/career.lib.php | 4 +- main/inc/lib/course.lib.php | 10 +- main/inc/lib/events.lib.inc.php | 3175 ++++++++------- main/inc/lib/exercise.lib.php | 3620 +++++++++++++++++ main/inc/lib/exercise_show_functions.lib.php | 14 +- main/inc/lib/group_portal_manager.lib.php | 12 +- main/inc/lib/login.lib.php | 2 +- main/inc/lib/promotion.lib.php | 4 +- main/inc/lib/sessionmanager.lib.php | 10 +- main/inc/lib/tracking.lib.php | 64 +- main/inc/lib/usermanager.lib.php | 16 +- main/inc/lib/userportal.lib.php | 3 +- main/inc/local.inc.php | 14 +- main/link/ajax_controller.class.php | 36 +- main/link/controller.class.php | 48 +- main/link/link.php | 2 +- main/link/link_goto.php | 2 +- main/messages/download.php | 2 +- main/mySpace/myStudents.php | 2 +- main/newscorm/download.php | 2 +- main/newscorm/learnpath_functions.inc.php | 3 +- main/newscorm/lp_edit.php | 2 +- main/newscorm/lp_list.php | 2 +- main/newscorm/lp_list_search.php | 2 +- main/notebook/ajax_controller.class.php | 18 +- main/notebook/controller.class.php | 38 +- main/notebook/index.php | 2 +- main/session/index.php | 14 +- main/survey/survey_list.php | 2 +- main/tracking/course_session_report.php | 4 +- main/tracking/lp_results_by_user.php | 4 +- main/tracking/question_course_report.php | 4 +- main/upload/index.php | 2 +- main/upload/upload_ppt.php | 2 +- main/upload/upload_word.php | 2 +- main/user/user.php | 2 +- main/wiki/index.php | 2 +- main/wiki/wiki.inc.php | 2 +- main/work/downloadfolder.inc.php | 2 +- main/work/file.php | 6 +- main/work/work.lib.php | 6 +- main/work/work.php | 2 +- tests/main/exercice/exercise.lib.test.php | 24 +- tests/main/inc/lib/events.lib.inc.test.php | 22 +- tests/main/inc/lib/social.lib.test.php | 4 +- .../AccessurleditcoursestourlTest.lib.php | 2 +- .../AccessurledituserstourlTest.lib.php | 2 +- tests/test_manager.inc.php | 7 +- 123 files changed, 5803 insertions(+), 5025 deletions(-) delete mode 100755 main/exercice/exercise.lib.php create mode 100644 main/inc/lib/exercise.lib.php diff --git a/index.php b/index.php index 0cd9122780..43b8ae071e 100755 --- a/index.php +++ b/index.php @@ -66,7 +66,7 @@ $_setting['display_courses_to_anonymous_users'] = 'true'; */ if (isset($_GET['submitAuth']) && $_GET['submitAuth'] == 1) { $i = api_get_anonymous_id(); - event_system(LOG_ATTEMPTED_FORCED_LOGIN, 'tried_hacking_get', $_SERVER['REMOTE_ADDR'].(empty($_POST['login'])?'':'/'.$_POST['login']),null,$i); + Event::addEvent(LOG_ATTEMPTED_FORCED_LOGIN, 'tried_hacking_get', $_SERVER['REMOTE_ADDR'].(empty($_POST['login'])?'':'/'.$_POST['login']),null,$i); echo 'Attempted breakin - sysadmins notified.'; session_destroy(); die(); @@ -110,7 +110,7 @@ if (!empty($_POST['submitAuth'])) { } Database::free_result($result_last_login); - //event_login(); + //Event::event_login(); if (api_is_platform_admin()) { // decode all open event informations and fill the track_c_* tables include api_get_path(LIBRARY_PATH).'stats.lib.inc.php'; @@ -120,7 +120,7 @@ if (!empty($_POST['submitAuth'])) { // End login -- if ($_POST['submitAuth']) } else { // Only if login form was not sent because if the form is sent the user was already on the page. - event_open(); + Event::event_open(); } if (api_get_setting('display_categories_on_homepage') == 'true') { diff --git a/main/admin/configure_homepage.php b/main/admin/configure_homepage.php index 1c89c91d0c..17045625e1 100755 --- a/main/admin/configure_homepage.php +++ b/main/admin/configure_homepage.php @@ -272,7 +272,7 @@ if (!empty($action)) { if (EventsMail::check_if_using_class('portal_homepage_edited')) { EventsDispatcher::events('portal_homepage_edited',array('about_user' => api_get_user_id())); } - event_system( + Event::addEvent( LOG_HOMEPAGE_CHANGED, 'edit_top', cut(strip_tags($home_top), 254), @@ -330,7 +330,7 @@ if (!empty($action)) { fputs($fp, "$notice_title
\n$notice_text"); fclose($fp); } - event_system(LOG_HOMEPAGE_CHANGED, 'edit_notice', cut(strip_tags($notice_title), 254), api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_HOMEPAGE_CHANGED, 'edit_notice', cut(strip_tags($notice_title), 254), api_get_utc_datetime(), api_get_user_id()); break; case 'edit_news': //Filter @@ -376,7 +376,7 @@ if (!empty($action)) { } } } - event_system(LOG_HOMEPAGE_CHANGED, 'edit_news', strip_tags(cut($home_news, 254)), api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_HOMEPAGE_CHANGED, 'edit_news', strip_tags(cut($home_news, 254)), api_get_utc_datetime(), api_get_user_id()); break; case 'insert_tabs': case 'edit_tabs': @@ -541,13 +541,13 @@ if (!empty($action)) { } } } - event_system( - LOG_HOMEPAGE_CHANGED, - $action, - cut($link_name . ':' . $link_url, 254), - api_get_utc_datetime(), - api_get_user_id() - ); + Event::addEvent( + LOG_HOMEPAGE_CHANGED, + $action, + cut($link_name . ':' . $link_url, 254), + api_get_utc_datetime(), + api_get_user_id() + ); break; } //end of switch($action) diff --git a/main/admin/event_type.php b/main/admin/event_type.php index 24197f833d..2938e9fcc9 100755 --- a/main/admin/event_type.php +++ b/main/admin/event_type.php @@ -38,12 +38,12 @@ if ($action == 'modEventType') { if (!empty($event_name)) { $eventName = $event_name; } - save_event_type_message($eventName, $users, $eventMessage, $eventSubject, $eventMessageLanguage, $activated); + Event::save_event_type_message($eventName, $users, $eventMessage, $eventSubject, $eventMessageLanguage, $activated); header('location: event_controller.php'); exit; } -$ets = get_all_event_types(); +$ets = Event::get_all_event_types(); $languages = api_get_languages(); diff --git a/main/admin/settings.lib.php b/main/admin/settings.lib.php index 22dbe5b456..2657e001cf 100755 --- a/main/admin/settings.lib.php +++ b/main/admin/settings.lib.php @@ -22,7 +22,7 @@ function handle_regions() // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, @@ -116,7 +116,7 @@ function handle_plugins() // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, @@ -255,7 +255,7 @@ function handle_stylesheets() // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, @@ -755,7 +755,7 @@ function handle_templates() { // Add event to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; - event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); + Event::addEvent(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); } else { if ($action == 'delete' && is_numeric($_GET['id'])) { delete_template($_GET['id']); @@ -763,7 +763,7 @@ function handle_templates() { // Add event to the system log $user_id = api_get_user_id(); $category = $_GET['category']; - event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); + Event::addEvent(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id); } display_templates(); } diff --git a/main/admin/settings.php b/main/admin/settings.php index f933fe5fcb..057fc8b135 100755 --- a/main/admin/settings.php +++ b/main/admin/settings.php @@ -330,7 +330,7 @@ if (!empty($_GET['category']) && // Add event configuration settings category to the system log. $user_id = api_get_user_id(); $category = $_GET['category']; - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, @@ -342,7 +342,7 @@ if (!empty($_GET['category']) && if (is_array($keys) && count($keys) > 0) { foreach ($keys as $variable) { if (in_array($key, $settings_to_avoid)) { continue; } - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_VARIABLE, $variable, @@ -482,7 +482,7 @@ if (!empty($_GET['category'])) { // add event to system log $user_id = api_get_user_id(); $category = $_GET['category']; - event_system( + Event::addEvent( LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, diff --git a/main/admin/special_exports.php b/main/admin/special_exports.php index 54b2ebce83..5f6a754374 100755 --- a/main/admin/special_exports.php +++ b/main/admin/special_exports.php @@ -190,7 +190,7 @@ function create_zip(){ } function rename_zip($FileZip) { - event_download(($FileZip['PATH'] == '/')?'full_export_'.date('Ymd').'.zip (folder)': basename($FileZip['PATH']).'.zip (folder)'); + Event::event_download(($FileZip['PATH'] == '/')?'full_export_'.date('Ymd').'.zip (folder)': basename($FileZip['PATH']).'.zip (folder)'); $name = ($FileZip['PATH']=='/')? 'full_export_'.date('Ymd').'.zip':basename($FileZip['PATH']).'.zip'; if(file_exists($FileZip['PATH_TEMP_ARCHIVE'].'/'.$name)){ unlink($FileZip['PATH_TEMP_ARCHIVE'].'/'.$name); } if(file_exists($FileZip['TEMP_FILE_ZIP'])) { diff --git a/main/admin/sub_language.class.php b/main/admin/sub_language.class.php index aaad14e786..1f55dcbfd5 100755 --- a/main/admin/sub_language.class.php +++ b/main/admin/sub_language.class.php @@ -355,7 +355,7 @@ class SubLanguageManager $lang = Database::fetch_array($result); $sql_update_2 = "UPDATE " . $tbl_settings_current . " SET selected_value='" . $lang['english_name'] . "' WHERE variable='platformLanguage'"; $result_2 = Database::query($sql_update_2); - event_system(LOG_PLATFORM_LANGUAGE_CHANGE, LOG_PLATFORM_LANGUAGE, $lang['english_name']); + Event::addEvent(LOG_PLATFORM_LANGUAGE_CHANGE, LOG_PLATFORM_LANGUAGE, $lang['english_name']); return $result_2 !== false; } diff --git a/main/announcements/download.php b/main/announcements/download.php index d68fe2811a..7f558c8285 100755 --- a/main/announcements/download.php +++ b/main/announcements/download.php @@ -53,7 +53,7 @@ if (is_dir($full_file_name)) { $tbl_announcement_attachment = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT); // launch event -event_download($doc_url); +Event::event_download($doc_url); $course_id = api_get_course_int_id(); diff --git a/main/attendance/layout.php b/main/attendance/layout.php index dbc7537e24..ce84eb845f 100755 --- a/main/attendance/layout.php +++ b/main/attendance/layout.php @@ -18,7 +18,7 @@ Display :: display_header(''); Display::display_introduction_section($tool); // Tracking -event_access_tool($tool); +Event::event_access_tool($tool); // Display echo $content; diff --git a/main/auth/external_login/login.ldap.php b/main/auth/external_login/login.ldap.php index d94c9eb392..e130db5efc 100755 --- a/main/auth/external_login/login.ldap.php +++ b/main/auth/external_login/login.ldap.php @@ -65,8 +65,7 @@ if ($ldap_user !== false) { Session::write('_user', $_user); $uidReset = true; $logging_in = true; - event_login(); - error_log("Calling event_login"); + Event::event_login(); } else { error_log('extldap_authenticate error'); $loginFailed = true; diff --git a/main/auth/external_login/login.ws.php b/main/auth/external_login/login.ws.php index a801c772f5..748c145159 100755 --- a/main/auth/external_login/login.ws.php +++ b/main/auth/external_login/login.ws.php @@ -27,8 +27,7 @@ if ($isValid === 1) { Session::write('_user', $_user); $uidReset = true; $logging_in = true; - event_login(); - //error_log('Calling event_login'); + Event::event_login(); } else { //error_log('WS authentication error - user not approved by external WS'); $loginFailed = true; diff --git a/main/auth/external_login/newUser.ldap.php b/main/auth/external_login/newUser.ldap.php index d59137805e..f422fbd366 100755 --- a/main/auth/external_login/newUser.ldap.php +++ b/main/auth/external_login/newUser.ldap.php @@ -2,38 +2,38 @@ // External login module : LDAP /** - * This file is included by main/inc/local.inc.php when extldap is activated, a user try to login + * This file is included by main/inc/local.inc.php when extldap is activated, a user try to login * and chamilo does not find his user - * Variables that can be used : + * Variables that can be used : * - $login : string containing the username posted by the user * - $password : string containing the password posted by the user * * Please configure the exldap module in main/auth/external_login/ldap.conf.php - * - * If login succeeds, we have to add the user in the chamilo database and then - * we have 2 choices : - * 1. - set $loginFailed to false, - * - set $_SESSION['_user']['user_id'] with the dokeos user_id + * + * If login succeeds, we have to add the user in the chamilo database and then + * we have 2 choices : + * 1. - set $loginFailed to false, + * - set $_SESSION['_user']['user_id'] with the dokeos user_id * - set $uidReset to true * - let the script local.inc.php continue * - * 2. - set $_SESSION['_user']['user_id'] with the dokeos user_id + * 2. - set $_SESSION['_user']['user_id'] with the dokeos user_id * - set $_SESSION['_user']['uidReset'] to true * - upgrade user info in dokeos database if needeed * - redirect to any page and let local.inc.php do the magic - * + * * If login fails we have also 2 choices : - * 1. - unset $_user['user_id'] - * - set $loginFailed=true + * 1. - unset $_user['user_id'] + * - set $loginFailed=true * - set $uidReset = false * User wil then have the user password incorrect message * - * 2. We redirect the user to index.php with appropriate message : - * Possible messages are : + * 2. We redirect the user to index.php with appropriate message : + * Possible messages are : * - index.php?loginFailed=1&error=access_url_inactive * - index.php?loginFailed=1&error=account_expired * - index.php?loginFailed=1&error=account_inactive - * - index.php?loginFailed=1&error=user_password_incorrect + * - index.php?loginFailed=1&error=user_password_incorrect * - index.php?loginFailed=1&error=unrecognize_sso_origin'); * */ @@ -55,13 +55,13 @@ if ($ldap_user !== false) { $_user['uidReset'] = true; Session::write('_user', $_user); $uidReset = true; - // Is user admin? + // Is user admin? if ($chamilo_user['admin'] === true) { $is_platformAdmin = true; Database::query("INSERT INTO admin values ('$chamilo_uid')"); } } - event_login(); + Event::event_login(); } else { $loginFailed = true; $uidReset = false; diff --git a/main/auth/external_login/newUser.php b/main/auth/external_login/newUser.php index cd4a825ca7..71a8ab8903 100755 --- a/main/auth/external_login/newUser.php +++ b/main/auth/external_login/newUser.php @@ -46,7 +46,7 @@ if ($user !== false && ($chamilo_uid = external_add_user($user)) !== false) { // Can user create course $is_allowedCreateCourse = (bool) (($user['status'] == COURSEMANAGER) or (api_get_setting('drhCourseManagerRights') and $user['status'] == SESSIONADMIN)); - event_login(); + Event::event_login(); } else { $loginFailed = true; unset($_user['user_id']); diff --git a/main/auth/inscription.php b/main/auth/inscription.php index 937e95981b..787dda0abd 100755 --- a/main/auth/inscription.php +++ b/main/auth/inscription.php @@ -601,7 +601,7 @@ if ($form->validate()) { Session::write('is_allowedCreateCourse', $is_allowedCreateCourse); // Stats - event_login(); + Event::event_login(); // last user login date is now $user_last_login_datetime = 0; // used as a unix timestamp it will correspond to : 1 1 1970 diff --git a/main/auth/ldap/login.php b/main/auth/ldap/login.php index 5906a37243..5df705e0c9 100755 --- a/main/auth/ldap/login.php +++ b/main/auth/ldap/login.php @@ -34,7 +34,7 @@ if ($loginLdapSucces) $_user['user_id'] = $uData['user_id']; Session::write('_uid',$_uid); // Jand: copied from event_login in events.lib.php to enable login statistics: - event_login(); + Event::event_login(); } else { diff --git a/main/auth/shibboleth/lib/shibboleth_session.class.php b/main/auth/shibboleth/lib/shibboleth_session.class.php index 849da6a27e..4dcfdf35f8 100755 --- a/main/auth/shibboleth/lib/shibboleth_session.class.php +++ b/main/auth/shibboleth/lib/shibboleth_session.class.php @@ -80,14 +80,14 @@ class ShibbolethSession $_SESSION['noredirection'] = true; //must be called before 'init_local.inc.php' - event_login(); + Event::event_login(); //used in 'init_local.inc.php' this is BAD but and should be changed $loginFailed = false; $uidReset = true; $gidReset = true; - $cidReset = false; //FALSE !! + $cidReset = false; //FALSE !! $mainDbName = Database :: get_main_database(); $includePath = api_get_path(INCLUDE_PATH); @@ -98,4 +98,4 @@ class ShibbolethSession return $_user; } -} \ No newline at end of file +} diff --git a/main/auth/sso/sso.Drupal.class.php b/main/auth/sso/sso.Drupal.class.php index d2214f0802..2da1869caf 100755 --- a/main/auth/sso/sso.Drupal.class.php +++ b/main/auth/sso/sso.Drupal.class.php @@ -4,7 +4,7 @@ use \ChamiloSession as Session; /* For licensing terms, see /license.txt */ /** - * This file contains the necessary elements to implement a Single Sign On + * This file contains the necessary elements to implement a Single Sign On * mechanism with an external Drupal application (on which the Chamilo module * 7.x-1.0-alpha3 or above must be implemented) * @@ -16,7 +16,7 @@ use \ChamiloSession as Session; * * @package chamilo.auth.sso */ - + /** * The SSO class allows for management of remote Single Sign On resources */ @@ -44,9 +44,9 @@ class ssoDrupal { $this->master_url = $this->protocol.$this->domain.$this->auth_uri; $this->target = api_get_path(WEB_PATH); } - + /** - * Unlogs the user from the remote server + * Unlogs the user from the remote server */ public function logout() { header('Location: '.$this->deauth_url); @@ -69,7 +69,7 @@ class ssoDrupal { header('Location: '.$this->master_url.$params); exit; } - + /** * Validates the received active connection data with the database * @return bool Return the loginFailed variable value to local.inc.php @@ -100,29 +100,29 @@ class ssoDrupal { //Check the user's password if ($uData['auth_source'] == PLATFORM_AUTH_SOURCE) { - if ($sso['secret'] === sha1($uData['username'].$sso_challenge.api_get_security_key()) + if ($sso['secret'] === sha1($uData['username'].$sso_challenge.api_get_security_key()) && ($sso['username'] == $uData['username'])) { //Check if the account is active (not locked) if ($uData['active']=='1') { // check if the expiration date has not been reached - if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') { - + if ($uData['expiration_date'] > date('Y-m-d H:i:s') OR $uData['expiration_date']=='0000-00-00 00:00:00') { + //If Multiple URL is enabled if (api_get_multiple_access_url()) { //Check the access_url configuration setting if the user is registered in the access_url_rel_user table //Getting the current access_url_id of the platform $current_access_url_id = api_get_current_access_url_id(); - // my user is subscribed in these + // my user is subscribed in these //sites: $my_url_list $my_url_list = api_get_access_url_from_user($uData['user_id']); } else { $current_access_url_id = 1; $my_url_list = array(1); } - + $my_user_is_admin = UserManager::is_admin($uData['user_id']); - + if ($my_user_is_admin === false) { if (is_array($my_url_list) && count($my_url_list) > 0 ) { if (in_array($current_access_url_id, $my_url_list)) { @@ -130,7 +130,7 @@ class ssoDrupal { $_user['user_id'] = $uData['user_id']; $_user = api_get_user_info($_user['user_id']); Session::write('_user', $_user); - event_login(); + Event::event_login(); // Redirect to homepage $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) .'.index.php'; header('Location: '. $sso_target); @@ -143,7 +143,7 @@ class ssoDrupal { exit; } } else { - // there is no URL in the multiple + // there is no URL in the multiple // urls list for this user $loginFailed = true; Session::erase('_uid'); @@ -153,23 +153,23 @@ class ssoDrupal { } else { //Only admins of the "main" (first) Chamilo // portal can login wherever they want - if (in_array(1, $my_url_list)) { - //Check if this admin is admin on the + if (in_array(1, $my_url_list)) { + //Check if this admin is admin on the // principal portal $_user['user_id'] = $uData['user_id']; $_user = api_get_user_info($_user['user_id']); $is_platformAdmin = $uData['status'] == COURSEMANAGER; Session::write('is_platformAdmin', $is_platformAdmin); Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { - //Secondary URL admin wants to login + //Secondary URL admin wants to login // so we check as a normal user if (in_array($current_access_url_id, $my_url_list)) { $_user['user_id'] = $uData['user_id']; $_user = api_get_user_info($_user['user_id']); Session::write('_user',$_user); - event_login(); + Event::event_login(); } else { $loginFailed = true; Session::erase('_uid'); @@ -177,7 +177,7 @@ class ssoDrupal { exit; } } - } + } } else { // user account expired $loginFailed = true; @@ -215,7 +215,7 @@ class ssoDrupal { } return $loginFailed; } - + /** * Decode the cookie (this function may vary depending on the * Single Sign On implementation @@ -230,7 +230,7 @@ class ssoDrupal { * Generate the URL for profile editing for a any user or the current user * @param int $userId Optional. The user id * @param boolean $asAdmin Optional. Whether get the URL for the platform admin - * @return string If the URL is obtained return the drupal_user_id. Otherwise return false + * @return string If the URL is obtained return the drupal_user_id. Otherwise return false */ public function generateProfileEditingURL($userId = 0, $asAdmin = false) { diff --git a/main/auth/sso/sso.class.php b/main/auth/sso/sso.class.php index ab827d00cd..f70e037e59 100755 --- a/main/auth/sso/sso.class.php +++ b/main/auth/sso/sso.class.php @@ -4,11 +4,11 @@ use \ChamiloSession as Session; /* For licensing terms, see /license.txt */ /** - * This file contains the necessary elements to implement a Single Sign On - * mechanism with an arbitrary external web application (given some light + * This file contains the necessary elements to implement a Single Sign On + * mechanism with an arbitrary external web application (given some light * development there) and is based on the Drupal-Chamilo module implementation. * To develop a new authentication mechanism, please extend this class and - * overwrite its method, then modify the corresponding calling code in + * overwrite its method, then modify the corresponding calling code in * main/inc/local.inc.php * @package chamilo.auth.sso */ @@ -40,16 +40,16 @@ class sso { $this->master_url = $this->protocol.$this->domain.$this->auth_uri; $this->target = api_get_path(WEB_PATH); } - + /** - * Unlogs the user from the remote server + * Unlogs the user from the remote server */ public function logout() { header('Location: '.$this->deauth_url); exit; } - + /** * Sends the user to the master URL for a check of active connection */ @@ -68,7 +68,7 @@ class sso { header('Location: '.$this->master_url.$params); exit; } - + /** * Validates the received active connection data with the database * @return bool Return the loginFailed variable value to local.inc.php @@ -79,10 +79,10 @@ class sso { $loginFailed = false; //change the way we recover the cookie depending on how it is formed $sso = $this->decode_cookie($_GET['sso_cookie']); - + //error_log('check_user'); //error_log('sso decode cookie: '.print_r($sso,1)); - + //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, status @@ -97,7 +97,7 @@ class sso { //This user's authentification is managed by Chamilo itself // check the user's password // password hash comes already parsed in sha1, md5 or none - + /* error_log($sso['secret']); error_log($uData['password']); @@ -125,7 +125,7 @@ class sso { // check if the expiration date has not been reached if ($uData['expiration_date'] > date('Y-m-d H:i:s') or $uData['expiration_date']=='0000-00-00 00:00:00') { - + //If Multiple URL is enabled if (api_get_multiple_access_url()) { //Check the access_url configuration setting if @@ -139,9 +139,9 @@ class sso { $current_access_url_id = 1; $my_url_list = array(1); } - + $my_user_is_admin = UserManager::is_admin($uData['user_id']); - + if ($my_user_is_admin === false) { if (is_array($my_url_list) && count($my_url_list) > 0) { if (in_array($current_access_url_id, $my_url_list)) { @@ -149,7 +149,7 @@ class sso { $_user['user_id'] = $uData['user_id']; $_user = api_get_user_info($_user['user_id']); Session::write('_user', $_user); - event_login(); + Event::event_login(); // Redirect to homepage $sso_target = isset($sso['target']) ? $sso['target'] : api_get_path(WEB_PATH) .'.index.php'; header('Location: '. $sso_target); @@ -180,7 +180,7 @@ class sso { $is_platformAdmin = $uData['status'] == COURSEMANAGER; Session::write('is_platformAdmin', $is_platformAdmin); Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { //Secondary URL admin wants to login // so we check as a normal user @@ -188,7 +188,7 @@ class sso { $_user['user_id'] = $uData['user_id']; $_user = api_get_user_info($_user['user_id']); Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { $loginFailed = true; Session::erase('_uid'); @@ -243,7 +243,7 @@ class sso { } return $loginFailed; } - + /** * Decode the cookie (this function may vary depending on the * Single Sign On implementation @@ -259,7 +259,7 @@ class sso { * Generate the URL for profile editing for a any user or the current user * @param int $userId Optional. The user id * @param boolean $asAdmin Optional. Whether get the URL for the platform admin - * @return string The SSO URL + * @return string The SSO URL */ public function generateProfileEditingURL($userId = 0, $asAdmin = false) { diff --git a/main/blog/download.php b/main/blog/download.php index 722642f867..821fb68573 100755 --- a/main/blog/download.php +++ b/main/blog/download.php @@ -51,7 +51,7 @@ $tbl_blogs_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT); $course_id = api_get_course_int_id(); // launch event -event_download($doc_url); +Event::event_download($doc_url); $sql = 'SELECT filename FROM '.$tbl_blogs_attachment.' WHERE c_id = '.$course_id.' AND path LIKE BINARY "'.Database::escape_string($doc_url).'"'; diff --git a/main/calendar/agenda.php b/main/calendar/agenda.php index f7ea78924d..67f9750b8e 100755 --- a/main/calendar/agenda.php +++ b/main/calendar/agenda.php @@ -63,7 +63,7 @@ function plus_repeated_event() { // setting the name of the tool $nameTools = get_lang('Agenda'); -event_access_tool(TOOL_CALENDAR_EVENT); +Event::event_access_tool(TOOL_CALENDAR_EVENT); // permission stuff - also used by loading from global in agenda.inc.php $is_allowed_to_edit = api_is_allowed_to_edit(false, true) OR (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()); diff --git a/main/calendar/download.php b/main/calendar/download.php index 459c573f04..b5722adc1e 100755 --- a/main/calendar/download.php +++ b/main/calendar/download.php @@ -67,7 +67,7 @@ if (is_dir($full_file_name)) { $tbl_agenda_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT); // launch event -event_download($doc_url); +Event::event_download($doc_url); $sql='SELECT filename FROM '.$tbl_agenda_attachment.' WHERE c_id = '.$course_id.' AND path LIKE BINARY "'.Database::escape_string($doc_url).'"'; diff --git a/main/chat/chat.php b/main/chat/chat.php index 347d0d8f0a..f3d248b61e 100755 --- a/main/chat/chat.php +++ b/main/chat/chat.php @@ -26,7 +26,7 @@ if ($origin != 'whoisonline') { /* TRACKING */ -event_access_tool(TOOL_CHAT); +Event::event_access_tool(TOOL_CHAT); header('Content-Type: text/html; charset='.api_get_system_encoding()); /* diff --git a/main/course_description/ajax_controller.class.php b/main/course_description/ajax_controller.class.php index 38fb17e197..f64a9ffd4a 100755 --- a/main/course_description/ajax_controller.class.php +++ b/main/course_description/ajax_controller.class.php @@ -19,14 +19,14 @@ use Header; /** * Ajax controller. Dispatch request and perform required action. - * - * - delete category/link - * + * + * - delete category/link + * * Usage: - * + * * $controller = AjaxController::instance(); * $controller->run(); - * + * * @author Laurent Opprecht for the Univesity of Genevas * @license /license.txt */ @@ -38,7 +38,7 @@ class AjaxController extends \Controller /** * Return the instance of the controller. - * + * * @return \CourseDescription\AjaxController */ public static function instance() @@ -52,15 +52,15 @@ class AjaxController extends \Controller protected function __construct() { - + } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { - event_access_tool(TOOL_COURSE_DESCRIPTION); + Event::event_access_tool(TOOL_COURSE_DESCRIPTION); } public function is_allowed_to_edit() @@ -79,7 +79,7 @@ class AjaxController extends \Controller } return true; } - + public function authorize() { $authorize = api_protect_course_script(); @@ -102,7 +102,7 @@ class AjaxController extends \Controller } /** - * + * */ public function delete() { @@ -120,7 +120,7 @@ class AjaxController extends \Controller $this->response($success); } /** - * + * */ public function delete_by_course() { @@ -128,11 +128,11 @@ class AjaxController extends \Controller $this->forbidden(); return; } - + $course = (object) array(); $course->c_id = Request::get_c_id(); $course->session_id = Request::get_session_id(); - + $success = CourseDescription::repository()->remove_by_course($course); $this->response($success); @@ -149,7 +149,7 @@ class AjaxController extends \Controller } /** - * Action exists but implementation is missing. + * Action exists but implementation is missing. */ public function missing() { @@ -158,9 +158,9 @@ class AjaxController extends \Controller /** * Display a standard json responce. - * + * * @param bool $success - * @param string $message + * @param string $message * @param object $data */ public function response($success = false, $message = '', $data = null) diff --git a/main/course_description/controller.class.php b/main/course_description/controller.class.php index f646f34f6c..b200e9570e 100755 --- a/main/course_description/controller.class.php +++ b/main/course_description/controller.class.php @@ -13,18 +13,18 @@ use Javascript; /** * Controller for course description. Dispatch request and peform required action. - * + * * - list course description for course * - add a new course description to a course/session * - edit a course session * - delete a course session - * + * * Usage: - * + * * $controller = CourseDescriptionController::instance(); * $controller->run(); - * - * @package chamilo.course_description + * + * @package chamilo.course_description * @author Christian Fasanando * @author Laurent Opprecht for the Univesity of Genevas * @license see /license.txt @@ -42,8 +42,8 @@ class Controller extends \Controller /** * Return the instance of the controller. - * - * @return CourseDescriptionController + * + * @return CourseDescriptionController */ public static function instance() { @@ -56,13 +56,13 @@ class Controller extends \Controller protected function __construct() { - + } /** - * Action to perform. + * Action to perform. * Returns the request parameter. - * + * * @return string */ public function get_action() @@ -95,8 +95,8 @@ class Controller extends \Controller /** * Whether the call is authorized or not. - * - * @return boolean + * + * @return boolean */ public function authorize() { @@ -114,7 +114,7 @@ class Controller extends \Controller } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { @@ -135,12 +135,12 @@ class Controller extends \Controller $current_course_tool = TOOL_COURSE_DESCRIPTION; // Tracking - event_access_tool(TOOL_COURSE_DESCRIPTION); + Event::event_access_tool(TOOL_COURSE_DESCRIPTION); } /** * Javascript used by the controller - * + * * @return string */ public function javascript() @@ -156,10 +156,10 @@ class Controller extends \Controller /** * Returns a url for an action that the controller can process - * + * * @param string $action * @param array $params - * @return string + * @return string */ public function url($action = '', $params = array()) { @@ -185,8 +185,8 @@ class Controller extends \Controller /** * List course descriptions. - * - * @param array messages + * + * @param array messages */ public function listing() { @@ -203,7 +203,7 @@ class Controller extends \Controller } /** - * Performs the edit action. + * Performs the edit action. */ public function edit() { @@ -211,7 +211,7 @@ class Controller extends \Controller $this->forbidden(); return; } - + $id = Request::get_id(); $c_id = Request::get_c_id(); @@ -223,13 +223,13 @@ class Controller extends \Controller if ($form->validate()) { $success = $repo->save($description); - + $message = $success ? get_lang('DescriptionUpdated') : get_lang('Error'); $home = $this->url(self::ACTION_DEFAULT); Redirect::go($home); } - + $data = (object) array(); $data->form = $form; $this->render('edit', $data); @@ -285,7 +285,7 @@ class Controller extends \Controller /** * Performs the delete action. - * + * * @todo: could be worth to require a security token in the url and check it. Currently confirmation is done through javascript confirmation only. */ public function delete() @@ -344,7 +344,7 @@ class Controller extends \Controller $path = $file->tmp_name; $reader = new CsvReader($path); $descriptions = $reader->get_items(); - + $c_id = Request::get_c_id(); $session_id = Request::get_session_id(); $course = (object) array(); @@ -364,10 +364,10 @@ class Controller extends \Controller /** * Render a template using data. Adds a few common parameters to the data array. - * + * * @see /main/template/default/course_description/ * @param string $template - * @param array $data + * @param array $data */ protected function render($template, $data) { diff --git a/main/course_description/layout.php b/main/course_description/layout.php index 66bbadba8c..44c484a293 100755 --- a/main/course_description/layout.php +++ b/main/course_description/layout.php @@ -2,7 +2,7 @@ /* For licensing terms, see /license.txt */ /** -* Layout (principal view) used for structuring other views +* Layout (principal view) used for structuring other views * @author Christian Fasanando * @package chamilo.course_description */ @@ -17,10 +17,10 @@ Display :: display_header(''); Display::display_introduction_section(TOOL_COURSE_DESCRIPTION); // Tracking -event_access_tool(TOOL_COURSE_DESCRIPTION); +Event::event_access_tool(TOOL_COURSE_DESCRIPTION); // Display echo $content; // Footer -Display :: display_footer(); \ No newline at end of file +Display :: display_footer(); diff --git a/main/course_home/course_home.php b/main/course_home/course_home.php index 9ede3a0b6c..3a7269fd2b 100755 --- a/main/course_home/course_home.php +++ b/main/course_home/course_home.php @@ -183,7 +183,7 @@ api_protect_course_script(true); /* STATISTICS */ if (!isset($coursesAlreadyVisited[$course_code])) { - event_access_course(); + Event::accessCourse(); $coursesAlreadyVisited[$course_code] = 1; Session::write('coursesAlreadyVisited', $coursesAlreadyVisited); } diff --git a/main/course_progress/layout.php b/main/course_progress/layout.php index d63d8d4380..277763460b 100755 --- a/main/course_progress/layout.php +++ b/main/course_progress/layout.php @@ -2,7 +2,7 @@ /* For licensing terms, see /license.txt */ /** -* Layout (principal view) used for structuring other views +* Layout (principal view) used for structuring other views * @author Christian Fasanando * @package chamilo.course_progress */ @@ -18,10 +18,10 @@ Display :: display_header(''); Display::display_introduction_section($tool); // Tracking -event_access_tool($tool); +Event::event_access_tool($tool); // Display echo $content; // Footer -Display :: display_footer(); \ No newline at end of file +Display :: display_footer(); diff --git a/main/course_progress/layout_no_header.php b/main/course_progress/layout_no_header.php index a9d36c3a08..2309c5d35b 100755 --- a/main/course_progress/layout_no_header.php +++ b/main/course_progress/layout_no_header.php @@ -7,7 +7,7 @@ api_protect_course_script(true); Display :: display_reduced_header(); // Tracking -event_access_tool($tool); +Event::event_access_tool($tool); // Display diff --git a/main/document/create_audio.php b/main/document/create_audio.php index ac0727dd72..f656be7620 100755 --- a/main/document/create_audio.php +++ b/main/document/create_audio.php @@ -93,7 +93,7 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { diff --git a/main/document/create_document.php b/main/document/create_document.php index 4c4750255c..b339d91979 100755 --- a/main/document/create_document.php +++ b/main/document/create_document.php @@ -307,7 +307,7 @@ if (!($is_allowed_to_edit || /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset($group_properties)) { diff --git a/main/document/create_draw.php b/main/document/create_draw.php index c46f0b5ee5..00df18e726 100755 --- a/main/document/create_draw.php +++ b/main/document/create_draw.php @@ -97,7 +97,7 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { $display_dir = explode('/', $dir); diff --git a/main/document/create_paint.php b/main/document/create_paint.php index 944ff70b05..55db05a05c 100755 --- a/main/document/create_paint.php +++ b/main/document/create_paint.php @@ -97,7 +97,7 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || } /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { $display_dir = explode('/', $dir); diff --git a/main/document/document.php b/main/document/document.php index 53efbaac66..e957d8da17 100755 --- a/main/document/document.php +++ b/main/document/document.php @@ -268,7 +268,7 @@ switch ($action) { api_not_allowed(); } // Launch event - event_download($document_data['url']); + Event::event_download($document_data['url']); // Check visibility of document and paths if (!($is_allowed_to_edit || $group_member_with_upload_rights) && !DocumentManager::is_visible_by_id($document_id, $courseInfo, $sessionId, api_get_user_id())) { @@ -314,7 +314,7 @@ switch ($action) { require 'downloadfolder.inc.php'; } // Launch event - event_download($document_data['url']); + Event::event_download($document_data['url']); exit; } break; @@ -927,7 +927,7 @@ $(document).ready( function() { '; // Lib for event log, stats & tracking & record of the access -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); /* DISPLAY */ if ($groupId != 0) { // Add group name after for group documents diff --git a/main/document/document_lite.php b/main/document/document_lite.php index c6c67d092b..60fc2d4590 100755 --- a/main/document/document_lite.php +++ b/main/document/document_lite.php @@ -71,7 +71,7 @@ switch ($action) { exit; } // Launch event - event_download($document_data['url']); + Event::event_download($document_data['url']); // Check visibility of document and paths if (!($is_allowed_to_edit || $group_member_with_upload_rights) && !DocumentManager::is_visible_by_id($document_id, $course_info, api_get_session_id(), api_get_user_id())) { api_not_allowed(true); @@ -294,7 +294,7 @@ $(document).ready( function() { // Lib for event log, stats & tracking & record of the access -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); /* DISPLAY */ if ($to_group_id != 0) { // Add group name after for group documents diff --git a/main/document/download.php b/main/document/download.php index 927fca03ee..84217e0533 100755 --- a/main/document/download.php +++ b/main/document/download.php @@ -96,7 +96,7 @@ if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) { exit; // You shouldn't be here anyway. } // Launch event - event_download($doc_url); + Event::event_download($doc_url); DocumentManager::file_send_for_download($full_file_name); } exit; diff --git a/main/document/download_scorm.php b/main/document/download_scorm.php index 4049cef767..dabed20051 100755 --- a/main/document/download_scorm.php +++ b/main/document/download_scorm.php @@ -6,7 +6,7 @@ * @package chamilo.document */ /** - * Code + * Code */ session_cache_limiter('none'); @@ -53,12 +53,12 @@ $sys_course_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/scorm'; if (is_dir($sys_course_path.$doc_url)) { api_not_allowed(); } - + if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) { $full_file_name = $sys_course_path.$doc_url; // Launch event - event_download($doc_url); - + Event::event_download($doc_url); + DocumentManager::file_send_for_download($full_file_name); } -exit; \ No newline at end of file +exit; diff --git a/main/document/downloadfolder.inc.php b/main/document/downloadfolder.inc.php index 23d82d008f..080435518e 100755 --- a/main/document/downloadfolder.inc.php +++ b/main/document/downloadfolder.inc.php @@ -279,7 +279,7 @@ if (api_is_allowed_to_edit()) { } // Launch event -event_download(($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip (folder)'); +Event::event_download(($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip (folder)'); // Start download of created file $name = ($path == '/') ? 'documents.zip' : $documentInfo['title'].'.zip'; diff --git a/main/document/edit_document.php b/main/document/edit_document.php index 497ef8fed3..7da1ee2880 100755 --- a/main/document/edit_document.php +++ b/main/document/edit_document.php @@ -178,7 +178,7 @@ if (!api_is_allowed_to_edit()) { api_not_allowed(true); } -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); //TODO:check the below code and his funcionality if (!is_allowed_to_edit()) { diff --git a/main/document/edit_draw.php b/main/document/edit_draw.php index 38a6f48d1d..c835f07696 100755 --- a/main/document/edit_draw.php +++ b/main/document/edit_draw.php @@ -115,7 +115,7 @@ if (!$is_allowedToEdit) { api_not_allowed(true); } -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); Display :: display_header($nameTools, 'Doc'); echo '
'; diff --git a/main/document/edit_paint.php b/main/document/edit_paint.php index 5a6be5d6f0..bb01b519a3 100755 --- a/main/document/edit_paint.php +++ b/main/document/edit_paint.php @@ -120,7 +120,7 @@ if (!$is_allowedToEdit) { api_not_allowed(true); } -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); Display :: display_header($nameTools, 'Doc'); echo '
'; diff --git a/main/document/file.php b/main/document/file.php index cb9cc7101a..34247e94e5 100755 --- a/main/document/file.php +++ b/main/document/file.php @@ -69,7 +69,7 @@ if (count($ids) == 1) { Response::not_found(); } - event_download(Uri::here()); + Event::event_download(Uri::here()); DocumentManager::file_send_for_download($doc); exit; } @@ -156,5 +156,5 @@ foreach ($files as $file) { /** * Send file for download */ -event_download(Uri::here()); +Event::event_download(Uri::here()); DocumentManager::file_send_for_download($temp_zip_path, false, get_lang('Documents') . '.zip'); diff --git a/main/document/record_audio.php b/main/document/record_audio.php index 191f2d82dc..76558ba0af 100755 --- a/main/document/record_audio.php +++ b/main/document/record_audio.php @@ -86,9 +86,8 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || api_not_allowed(true); } - /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { diff --git a/main/document/record_audio_wami.php b/main/document/record_audio_wami.php index ebe66ea63a..21d448a359 100755 --- a/main/document/record_audio_wami.php +++ b/main/document/record_audio_wami.php @@ -94,7 +94,7 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || } /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { diff --git a/main/document/webcam_clip.php b/main/document/webcam_clip.php index 88fc2b151b..4ab42e15d8 100755 --- a/main/document/webcam_clip.php +++ b/main/document/webcam_clip.php @@ -92,9 +92,8 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || api_not_allowed(true); } - /* Header */ -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset ($group)) { diff --git a/main/dropbox/index.php b/main/dropbox/index.php index 69753584ac..0a78a21a41 100755 --- a/main/dropbox/index.php +++ b/main/dropbox/index.php @@ -18,7 +18,7 @@ $viewReceivedCategory = isset($_GET['view_received_category']) ? Security::remov $viewSentCategory = isset($_GET['view_sent_category']) ? Security::remove_XSS($_GET['view_sent_category']) : null; // Do the tracking -event_access_tool(TOOL_DROPBOX); +Event::event_access_tool(TOOL_DROPBOX); // This var is used to give a unique value to every page request. This is to prevent resubmiting data $dropbox_unid = md5(uniqid(rand(), true)); diff --git a/main/exercice/Hpdownload.php b/main/exercice/Hpdownload.php index ace2022863..76bcbea78a 100755 --- a/main/exercice/Hpdownload.php +++ b/main/exercice/Hpdownload.php @@ -20,7 +20,7 @@ $doc_url=str_replace(array('../','\\..','\\0','..\\'),array('','','',''),urldeco $filename=basename($doc_url); // launch event -//event_download($doc_url); +//Event::event_download($doc_url); if (isset($_course['path'])) { $course_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'; $full_file_name = $course_path.Security::remove_XSS($doc_url); @@ -34,7 +34,7 @@ if(!is_file($full_file_name)) { } if (!Security::check_abs_path($full_file_name, $course_path.'/')) { - exit; + exit; } $extension=explode('.',$filename); diff --git a/main/exercice/admin.php b/main/exercice/admin.php index c3099d3bf0..229f60f255 100755 --- a/main/exercice/admin.php +++ b/main/exercice/admin.php @@ -113,7 +113,12 @@ $cancelQuestion = isset($cancelQuestion) ? $cancelQuestion : null; /* Cleaning all incomplete attempts of the admin/teacher to avoid weird problems when changing the exercise settings, number of questions, etc */ -delete_all_incomplete_attempts(api_get_user_id(), $exerciseId, api_get_course_id(), api_get_session_id()); +Event::delete_all_incomplete_attempts( + api_get_user_id(), + $exerciseId, + api_get_course_id(), + api_get_session_id() +); // get from session $objExercise = isset($_SESSION['objExercise']) ? $_SESSION['objExercise'] : null; diff --git a/main/exercice/exercice.php b/main/exercice/exercice.php index 735ddc3b00..7642e611eb 100755 --- a/main/exercice/exercice.php +++ b/main/exercice/exercice.php @@ -162,7 +162,7 @@ if ($origin != 'learnpath') { Display :: display_reduced_header(); } -event_access_tool(TOOL_QUIZ); +Event::event_access_tool(TOOL_QUIZ); // Tool introduction Display :: display_introduction_section(TOOL_QUIZ); @@ -183,7 +183,7 @@ if ($is_allowedToEdit) { if ($check) { // list des exercices dans un test // we got variable $courseId $courseInfo session api_get_session_id() - $exerciseList = get_all_exercises_for_course_id( + $exerciseList = ExerciseLib::get_all_exercises_for_course_id( $courseInfo, api_get_session_id(), $courseId, @@ -623,7 +623,7 @@ if (!empty($exercise_list)) { $title = $cut_title; } - $count_exercise_not_validated = intval(count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id)); + $count_exercise_not_validated = intval(Event::count_exercise_result_not_validated($my_exercise_id, $course_code, $session_id)); $move = Display::return_icon('all_directions.png',get_lang('Move'), array('class'=>'moved', 'style'=>'margin-bottom:-0.5em;')); $move = null; @@ -744,7 +744,7 @@ if (!empty($exercise_list)) { } //Attempts - //$attempts = get_count_exam_results($row['id']).' '.get_lang('Attempts'); + //$attempts = ExerciseLib::get_count_exam_results($row['id']).' '.get_lang('Attempts'); //$item .= Display::tag('td',$attempts); $item .= Display::tag('td', $number_of_questions); } else { @@ -803,7 +803,7 @@ if (!empty($exercise_list)) { if ($num > 0) { $row_track = Database :: fetch_array($qryres); $attempt_text = get_lang('LatestAttempt').' : '; - $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']); + $attempt_text .= ExerciseLib::show_score($row_track['exe_result'], $row_track['exe_weighting']); } else { //No attempts $attempt_text = get_lang('NotAttempted'); @@ -843,7 +843,7 @@ if (!empty($exercise_list)) { if ($num > 0) { $row_track = Database :: fetch_array($qryres); $attempt_text = get_lang('LatestAttempt').' : '; - $attempt_text .= show_score($row_track['exe_result'], $row_track['exe_weighting']); + $attempt_text .= ExerciseLib::show_score($row_track['exe_result'], $row_track['exe_weighting']); } else { $attempt_text = get_lang('NotAttempted'); } @@ -986,7 +986,7 @@ if (isset($attribute['path']) && is_array($attribute['path'])) { } else { // Student only if ($active == 1) { - $attempt = getLatestHotPotatoResult( + $attempt = ExerciseLib::getLatestHotPotatoResult( $path, $userId, api_get_course_int_id(), @@ -999,7 +999,7 @@ if (isset($attribute['path']) && is_array($attribute['path'])) { if (!empty($attempt)) { $actions = ''.Display :: return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).''; $attemptText = get_lang('LatestAttempt').' : '; - $attemptText .= show_score($attempt['exe_result'], $attempt['exe_weighting']).' '; + $attemptText .= ExerciseLib::show_score($attempt['exe_result'], $attempt['exe_weighting']).' '; $attemptText .= $actions; } else { // No attempts. diff --git a/main/exercice/exercise.class.php b/main/exercice/exercise.class.php index 235cad7ad6..ba6f61da10 100755 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -1625,7 +1625,7 @@ class Exercise AND session_id = ".$session_id.""; Database::query($sql); - event_system( + Event::addEvent( LOG_EXERCISE_RESULT_DELETE, LOG_EXERCISE_ID, $this->id, @@ -2192,7 +2192,7 @@ class Exercise $nano = null; if ($answerType == ORAL_EXPRESSION) { - $exe_info = get_exercise_results_by_attempt($exeId); + $exe_info = Event::get_exercise_results_by_attempt($exeId); $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null; $params = array(); @@ -3461,24 +3461,24 @@ class Exercise if ($final_answer == 0) { $questionScore = 0; } - exercise_attempt($questionScore, 1, $quesId, $exeId, 0); // we always insert the answer_id 1 = delineation + Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0); // we always insert the answer_id 1 = delineation //in delineation mode, get the answer from $hotspot_delineation_result[1] - exercise_attempt_hotspot($exeId,$quesId,1, $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId]); + Event::saveExerciseAttemptHotspot($exeId,$quesId,1, $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId]); } else { if ($final_answer==0) { $questionScore = 0; $answer=0; - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0); if (is_array($exerciseResultCoordinates[$quesId])) { foreach($exerciseResultCoordinates[$quesId] as $idx => $val) { - exercise_attempt_hotspot($exeId,$quesId,$idx,0,$val); + Event::saveExerciseAttemptHotspot($exeId,$quesId,$idx,0,$val); } } } else { - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0); if (is_array($exerciseResultCoordinates[$quesId])) { foreach($exerciseResultCoordinates[$quesId] as $idx => $val) { - exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val); + Event::saveExerciseAttemptHotspot($exeId,$quesId,$idx,$choice[$idx],$val); } } } @@ -3531,11 +3531,11 @@ class Exercise $reply = array_keys($choice); for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; - exercise_attempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id); + Event::saveQuestionAttempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id); if ($debug) error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]); } } else { - exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) { if ($choice != 0) { @@ -3544,47 +3544,47 @@ class Exercise if ($debug) error_log("reply ".print_r($reply, 1).""); for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; - exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); + Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); } } else { - exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) { if ($choice != 0) { $reply = array_keys($choice); for ($i = 0; $i < sizeof($reply); $i++) { $ans = $reply[$i]; - exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); + Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id); } } else { - exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id); } } elseif ($answerType == MATCHING) { if (isset($matching)) { foreach ($matching as $j => $val) { - exercise_attempt($questionScore, $val, $quesId, $exeId, $j, $this->id); + Event::saveQuestionAttempt($questionScore, $val, $quesId, $exeId, $j, $this->id); } } } elseif ($answerType == FREE_ANSWER) { $answer = $choice; - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); } elseif ($answerType == ORAL_EXPRESSION) { $answer = $choice; - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $nano); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $nano); } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) { $answer = $choice; - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) { } elseif ($answerType == HOT_SPOT) { - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id); if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) { foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) { - exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val,$this->id); + Event::saveExerciseAttemptHotspot($exeId,$quesId,$idx,$choice[$idx],$val,$this->id); } } } else { - exercise_attempt($questionScore, $answer, $quesId, $exeId, 0,$this->id); + Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0,$this->id); } } @@ -3962,9 +3962,10 @@ class Exercise * @param int attempt id * @return float exercise result */ - public function get_exercise_result($exe_id) { + public function get_exercise_result($exe_id) + { $result = array(); - $track_exercise_info = get_exercise_track_exercise_info($exe_id); + $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id); if (!empty($track_exercise_info)) { $totalScore = 0; @@ -4091,7 +4092,7 @@ class Exercise if ($is_visible) { if ($exerciseAttempts > 0) { - $attempt_count = get_attempt_count_not_finished( + $attempt_count = Event::get_attempt_count_not_finished( api_get_user_id(), $this->id, $lp_id, diff --git a/main/exercice/exercise.lib.php b/main/exercice/exercise.lib.php deleted file mode 100755 index 7a65dd0263..0000000000 --- a/main/exercice/exercise.lib.php +++ /dev/null @@ -1,2990 +0,0 @@ - - * @version $Id: exercise.lib.php 22247 2009-07-20 15:57:25Z ivantcholakov $ - * Modified by Hubert Borderiou 2011-10-21 Question Category - */ - -/** - * Shows a question - * - * @param int $questionId question id - * @param bool $only_questions if true only show the questions, no exercise title - * @param bool $origin i.e = learnpath - * @param string $current_item current item from the list of questions - * @param bool $show_title - * @param bool $freeze - * @param array $user_choice - * @param bool $show_comment - * @param bool $exercise_feedback - * @param bool $show_answers - * */ -function showQuestion( - $questionId, - $only_questions = false, - $origin = false, - $current_item = '', - $show_title = true, - $freeze = false, - $user_choice = array(), - $show_comment = false, - $exercise_feedback = null, - $show_answers = false -) { - - // Text direction for the current language - $is_ltr_text_direction = api_get_text_direction() != 'rtl'; - - // Change false to true in the following line to enable answer hinting - $debug_mark_answer = $show_answers; //api_is_allowed_to_edit() && false; - - // Reads question information - if (!$objQuestionTmp = Question::read($questionId)) { - // Question not found - return false; - } - - if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) { - $show_comment = false; - } - - $answerType = $objQuestionTmp->selectType(); - $pictureName = $objQuestionTmp->selectPicture(); - $s = ''; - - if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) { - // Question is not a hotspot - - if (!$only_questions) { - $questionDescription = $objQuestionTmp->selectDescription(); - if ($show_title) { - Testcategory::displayCategoryAndTitle($objQuestionTmp->id); - echo Display::div( - $current_item.'. '.$objQuestionTmp->selectTitle(), - array('class'=>'question_title') - ); - } - if (!empty($questionDescription)) { - echo Display::div($questionDescription, array('class'=>'question_description')); - } - } - - if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) { - return ''; - } - - echo '
'; - // construction of the Answer object (also gets all answers details) - $objAnswerTmp = new Answer($questionId); - - $nbrAnswers = $objAnswerTmp->selectNbrAnswers(); - $course_id = api_get_course_int_id(); - $quiz_question_options = Question::readQuestionOption($questionId, $course_id); - - // For "matching" type here, we need something a little bit special - // because the match between the suggestions and the answers cannot be - // done easily (suggestions and answers are in the same table), so we - // have to go through answers first (elems with "correct" value to 0). - $select_items = array(); - //This will contain the number of answers on the left side. We call them - // suggestions here, for the sake of comprehensions, while the ones - // on the right side are called answers - $num_suggestions = 0; - - if ($answerType == MATCHING) { - $s .= ''; - // Iterate through answers - $x = 1; - //mark letters for each answer - $letter = 'A'; - $answer_matching = array(); - $cpt1 = array(); - for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) { - $answerCorrect = $objAnswerTmp->isCorrect($answerId); - $numAnswer = $objAnswerTmp->selectAutoId($answerId); - - $answer = $objAnswerTmp->selectAnswer($answerId); - if ($answerCorrect == 0) { - // options (A, B, C, ...) that will be put into the list-box - // have the "correct" field set to 0 because they are answer - $cpt1[$x] = $letter; - $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer); - $x++; - $letter++; - } - } - - $i = 1; - - $select_items[0]['id'] = 0; - $select_items[0]['letter'] = '--'; - $select_items[0]['answer'] = ''; - foreach ($answer_matching as $id => $value) { - $select_items[$i]['id'] = $value['id']; - $select_items[$i]['letter'] = $cpt1[$id]; - $select_items[$i]['answer'] = $value['answer']; - $i++; - } - - $user_choice_array_position = array(); - if (!empty($user_choice)) { - foreach ($user_choice as $item) { - $user_choice_array_position[$item['position']] = $item['answer']; - } - } - $num_suggestions = ($nbrAnswers - $x) + 1; - - } elseif ($answerType == FREE_ANSWER) { - $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer']:null; - - $oFCKeditor = new CKeditor(); - $oFCKeditor->ToolbarSet = 'Test_Free_Answer'; - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '200'; - $oFCKeditor->Value = $fck_content; - $s .= $oFCKeditor->editor("choice[".$questionId."]", $oFCKeditor->Value); - } elseif ($answerType == ORAL_EXPRESSION) { - //Add nanog - if (api_get_setting('enable_nanogong') == 'true') { - //@todo pass this as a parameter - global $exercise_stat_info, $exerciseId, $exe_id; - - if (!empty($exercise_stat_info)) { - $params = array( - 'exercise_id' => $exercise_stat_info['exe_exo_id'], - 'exe_id' => $exercise_stat_info['exe_id'], - 'question_id' => $questionId - ); - } else { - $params = array( - 'exercise_id' => $exerciseId, - 'exe_id' => 'temp_exe', - 'question_id' => $questionId - ); - } - $nano = new Nanogong($params); - echo $nano->show_button(); - } - - $oFCKeditor = new CKeditor(); - $oFCKeditor->ToolbarSet = 'TestFreeAnswer'; - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '150'; - $oFCKeditor->ToolbarStartExpanded = false; - $oFCKeditor->Value = '' ; - $s .= $oFCKeditor->editor("choice[".$questionId."]", $oFCKeditor->Value); - } - - // Now navigate through the possible answers, using the max number of - // answers for the question as a limiter - $lines_count = 1; // a counter for matching-type answers - - if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || - $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE - ) { - $header = Display::tag('th', get_lang('Options')); - foreach ($objQuestionTmp->options as $item) { - if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) { - if (in_array($item, $objQuestionTmp->options)) { - $header .= Display::tag('th', get_lang($item)); - } else { - $header .= Display::tag('th', $item); - } - } else { - $header .= Display::tag('th', $item); - } - - } - if ($show_comment) { - $header .= Display::tag('th', get_lang('Feedback')); - } - $s .= '
'; - $s .= Display::tag('tr', $header, array('style'=>'text-align:left;')); - } - - if ($show_comment) { - if (in_array( - $answerType, - array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER)) - ) { - $header = Display::tag('th', get_lang('Options')); - if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) { - $header .= Display::tag('th', get_lang('Feedback')); - } - $s .= '
'; - $s .= Display::tag('tr',$header, array('style'=>'text-align:left;')); - } - } - - $matching_correct_answer = 0; - $user_choice_array = array(); - if (!empty($user_choice)) { - foreach($user_choice as $item) { - $user_choice_array[] = $item['answer']; - } - } - - for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) { - $answer = $objAnswerTmp->selectAnswer($answerId); - $answerCorrect = $objAnswerTmp->isCorrect($answerId); - $numAnswer = $objAnswerTmp->selectAutoId($answerId); - $comment = $objAnswerTmp->selectComment($answerId); - - $attributes = array(); - - // Unique answer - if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) { - $input_id = 'choice-'.$questionId.'-'.$answerId; - if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer ) { - $attributes = array('id' =>$input_id, 'checked'=>1, 'selected'=>1); - } else { - $attributes = array('id' =>$input_id); - } - - if ($debug_mark_answer) { - if ($answerCorrect) { - $attributes['checked'] = 1; - $attributes['selected'] = 1; - } - } - - $answer = Security::remove_XSS($answer, STUDENT); - $s .= Display::input('hidden', 'choice2['.$questionId.']','0'); - - $answer_input = ''; - - if ($show_comment) { - $s .= ''; - $s .= ''; - $s .= ''; - } else { - $s .= $answer_input; - } - - } elseif ($answerType == MULTIPLE_ANSWER || - $answerType == MULTIPLE_ANSWER_TRUE_FALSE || - $answerType == GLOBAL_MULTIPLE_ANSWER - ) { - $input_id = 'choice-'.$questionId.'-'.$answerId; - $answer = Security::remove_XSS($answer, STUDENT); - - if (in_array($numAnswer, $user_choice_array)) { - $attributes = array('id' =>$input_id, 'checked'=>1, 'selected'=>1); - } else { - $attributes = array('id' =>$input_id); - } - - if ($debug_mark_answer) { - if ($answerCorrect) { - $attributes['checked'] = 1; - $attributes['selected'] = 1; - } - } - - if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) { - $s .= ''; - - $answer_input = ''; - - if ($show_comment) { - $s .= ''; - $s .= ''; - $s .=''; - } else { - $s .= $answer_input; - } - } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) { - - $my_choice = array(); - if (!empty($user_choice_array)) { - foreach ($user_choice_array as $item) { - $item = explode(':', $item); - $my_choice[$item[0]] = $item[1]; - } - } - - $s .= ''; - $s .= Display::tag('td', $answer); - - if (!empty($quiz_question_options)) { - foreach ($quiz_question_options as $id => $item) { - - if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) { - $attributes = array('checked'=>1, 'selected'=>1); - } else { - $attributes = array(); - } - - if ($debug_mark_answer) { - if ($id == $answerCorrect) { - $attributes['checked'] = 1; - $attributes['selected'] = 1; - } - } - $s .= Display::tag('td', Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $id, $attributes), array('style'=>'')); - } - } - - if ($show_comment) { - $s .= ''; - } - $s.=''; - } - } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) { - // multiple answers - $input_id = 'choice-'.$questionId.'-'.$answerId; - - if (in_array($numAnswer, $user_choice_array)) { - $attributes = array('id'=>$input_id, 'checked'=>1, 'selected'=>1); - } else { - $attributes = array('id'=>$input_id); - } - - if ($debug_mark_answer) { - if ($answerCorrect) { - $attributes['checked'] = 1; - $attributes['selected'] = 1; - } - } - - $answer = Security::remove_XSS($answer, STUDENT); - $answer_input = ''; - $answer_input .= ''; - - if ($show_comment) { - $s .= ''; - $s .= ''; - $s .= ''; - $s .= ''; - } else { - $s .= $answer_input; - } - - } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { - $s .= ''; - - $my_choice = array(); - if (!empty($user_choice_array)) { - foreach ($user_choice_array as $item) { - $item = explode(':', $item); - $my_choice[$item[0]] = $item[1]; - } - } - $answer = Security::remove_XSS($answer, STUDENT); - $s .=''; - $s .= Display::tag('td', $answer); - - foreach ($objQuestionTmp->options as $key => $item) { - if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) { - $attributes = array('checked' => 1, 'selected' => 1); - } else { - $attributes = array(); - } - - if ($debug_mark_answer) { - if ($key == $answerCorrect) { - $attributes['checked'] = 1; - $attributes['selected'] = 1; - } - } - $s .= Display::tag( - 'td', - Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $key, $attributes) - ); - } - - if ($show_comment) { - $s .= ''; - } - $s .=''; - - } elseif ($answerType == FILL_IN_BLANKS) { - /* - * In the FILL_IN_BLANKS test - * you mustn't have [ and ] in the textarea - * you mustn't have :: in the textarea - * the text to find mustn't be empty or contains only spaces - * the text to find mustn't contains HTML tags - * the text to find mustn't contains char " - */ - - list($answer) = explode('::', $answer); - - // $correct_answer_list array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]] - api_preg_match_all('/\[[^]]+\]/', $answer, $correct_answer_list); - - // get student answer to display it if student go back to previous fillBlank answer question in a test - if (isset($user_choice[0]['answer'])) { - api_preg_match_all('/\[[^]]+\]/', $user_choice[0]['answer'], $student_answer_list); - $student_answer_list_tobecleaned = $student_answer_list[0]; - $student_answer_list = array(); - // here we got the student answer in a test - // let's clean up the results - /* - Array - ( - [0] => Array - ( - [0] => [yer / ici] - [1] => [plop / /p] - ) - ) - */ - for ($i=0; $i < count($student_answer_list_tobecleaned); $i++) { - $answer_corrected = $student_answer_list_tobecleaned[$i]; - /* - * we got if student answer is wrong - * [rrr / /p] - * or if student answer is good - * [plop / plop] - * or if student didn't answer [] - */ - $answer_corrected = api_preg_replace('| / .*$|', '', $answer_corrected); - /* - * we got [rrr or [plop or [ - */ - $answer_corrected = api_preg_replace('/^\[/', '', $answer_corrected); - /* - * we got rrr or plop - * non breakable spaces     from /main/exercice/exercise.class.php have been removed l 2391 and l 2370 - */ - $answer_corrected = api_preg_replace('|^|', '', $answer_corrected); - $answer_corrected = api_preg_replace('|$|', '', $answer_corrected); - $answer_corrected = '['.$answer_corrected.']'; - /* - * we got [rrr] or [plop] or [] - */ - $student_answer_list[] = $answer_corrected; - } - } - - // If display preview of answer in test view for exemple, set the student answer to the correct answers - if ($debug_mark_answer) { - // contain the rights answers surronded with brackets - $student_answer_list = $correct_answer_list[0]; - } - - /* - Split the response by bracket - tab_comments is an array with text surrounding the text to find - we add a space before and after the answer_question to be sure to - have a block of text before and after [xxx] patterns - so we have n text to find ([xxx]) and n+1 block of texts before, - between and after the text to find - */ - $tab_comments = api_preg_split('/\[[^]]+\]/', ' '.$answer.' '); - - if (!empty($correct_answer_list) && !empty($student_answer_list)) { - $answer = ""; - $i = 0; - foreach ($student_answer_list as $student_item) { - // remove surronding brackets - $student_response = api_substr($student_item, 1, api_strlen($student_item) - 2); - - $size = strlen($student_item); - $attributes['class'] = detectInputAppropriateClass($size); - - $answer .= $tab_comments[$i]. - Display::input( - 'text', - "choice[$questionId][]", - $student_response, - $attributes - ); - $i++; - } - $answer .= $tab_comments[$i]; - } else { - // display exercise with empty input fields - // every [xxx] are replaced with an empty input field - foreach ($correct_answer_list[0] as $item) { - $size = strlen($item); - $attributes['class'] = detectInputAppropriateClass($size); - $answer = str_replace( - $item, - Display::input('text', "choice[$questionId][]", '', $attributes), - $answer - ); - } - /*$answer = api_preg_replace( - '/\[[^]]+\]/', - Display::input( - 'text', - "choice[$questionId][]", - '', - $attributes - ), $answer);*/ - } - $s .= $answer; - - } elseif ($answerType == CALCULATED_ANSWER) { - /* - * In the CALCULATED_ANSWER test - * you mustn't have [ and ] in the textarea - * you mustn't have @@ in the textarea - * the text to find mustn't be empty or contains only spaces - * the text to find mustn't contains HTML tags - * the text to find mustn't contains char " - */ - if ($origin !== null) { - global $exe_id; - $trackAttempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $sqlTrackAttempt = 'SELECT answer FROM '.$trackAttempts.' WHERE exe_id='.$exe_id.' AND question_id='.$questionId; - $rsLastAttempt = Database::query($sqlTrackAttempt); - $rowLastAttempt = Database::fetch_array($rsLastAttempt); - $answer = $rowLastAttempt['answer']; - if (empty($answer)) { - $_SESSION['calculatedAnswerId'][$questionId] = mt_rand(1, $nbrAnswers); - $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]); - } - } - list($answer) = explode('@@', $answer); - // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]] - api_preg_match_all('/\[[^]]+\]/', $answer, $correctAnswerList); - // get student answer to display it if student go back to previous calculated answer question in a test - if (isset($user_choice[0]['answer'])) { - api_preg_match_all('/\[[^]]+\]/', $answer, $studentAnswerList); - $studentAnswerListTobecleaned = $studentAnswerList[0]; - $studentAnswerList = array(); - - for ($i=0; $i < count($studentAnswerListTobecleaned); $i++) { - $answerCorrected = $studentAnswerListTobecleaned[$i]; - $answerCorrected = api_preg_replace('| / .*$|', '', $answerCorrected); - $answerCorrected = api_preg_replace('/^\[/', '', $answerCorrected); - $answerCorrected = api_preg_replace('|^|', '', $answerCorrected); - $answerCorrected = api_preg_replace('|$|', '', $answerCorrected); - $answerCorrected = '['.$answerCorrected.']'; - $studentAnswerList[] = $answerCorrected; - } - } - // If display preview of answer in test view for exemple, set the student answer to the correct answers - if ($debug_mark_answer) { - // contain the rights answers surronded with brackets - $studentAnswerList = $correctAnswerList[0]; - } - /* - Split the response by bracket - tabComments is an array with text surrounding the text to find - we add a space before and after the answerQuestion to be sure to - have a block of text before and after [xxx] patterns - so we have n text to find ([xxx]) and n+1 block of texts before, - between and after the text to find - */ - $tabComments = api_preg_split('/\[[^]]+\]/', ' '.$answer.' '); - if (!empty($correctAnswerList) && !empty($studentAnswerList)) { - $answer = ""; - $i = 0; - foreach ($studentAnswerList as $studentItem) { - // remove surronding brackets - $studentResponse = api_substr($studentItem, 1, api_strlen($studentItem) - 2); - $size = strlen($studentItem); - $attributes['class'] = detectInputAppropriateClass($size); - - $answer .= $tabComments[$i]. - Display::input( - 'text', - "choice[$questionId][]", - $studentResponse, - $attributes - ); - $i++; - } - $answer .= $tabComments[$i]; - } else { - // display exercise with empty input fields - // every [xxx] are replaced with an empty input field - foreach ($correctAnswerList[0] as $item) { - $size = strlen($item); - $attributes['class'] = detectInputAppropriateClass($size); - $answer = str_replace( - $item, - Display::input('text', "choice[$questionId][]", '', $attributes), - $answer - ); - } - } - if ($origin !== null) { - $s = $answer; - break; - } else { - $s .= $answer; - } - } elseif ($answerType == MATCHING) { - // matching type, showing suggestions and answers - // TODO: replace $answerId by $numAnswer - - if ($answerCorrect != 0) { - // only show elements to be answered (not the contents of - // the select boxes, who are corrrect = 0) - $s .= ''; - //middle part (matches selects) - - $s .= ''; - $s .=''; - $s .= ''; - $lines_count++; - //if the left side of the "matching" has been completely - // shown but the right side still has values to show... - if (($lines_count -1) == $num_suggestions) { - // if it remains answers to shown at the right side - while (isset($select_items[$lines_count])) { - $s .= ' - - - "; - $lines_count++; - } // end while() - } // end if() - $matching_correct_answer++; - } - } - } // end for() - - if ($show_comment) { - $s .= '
'; - $s .= $answer_input; - $s .= ''; - $s .= $comment; - $s .= '
'; - $s .= $answer_input; - $s .= ''; - $s .= $comment; - $s .= '
'; - $s .= $comment; - $s .= '
'; - $s .= $answer_input; - $s .= ''; - $s .= $comment; - $s .= '
'; - $s .= $comment; - $s .= '
'; - $parsed_answer = $answer; - //left part questions - $s .= ' '.$lines_count.' - '.$parsed_answer.'   - '; - if (isset($select_items[$lines_count])) { - $s.=''.$select_items[$lines_count]['letter'].'.'. - ''.$select_items[$lines_count]['answer'].''; - } else { - $s.=' '; - } - $s .= '
'; - $s .=''.$select_items[$lines_count]['letter'].'. '.$select_items[$lines_count]['answer']; - $s .="
'; - } else { - if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || - $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { - $s .= ''; - } - } - - $s .= '
'; - - // destruction of the Answer object - unset($objAnswerTmp); - - // destruction of the Question object - unset($objQuestionTmp); - - if ($origin != 'export') { - echo $s; - } else { - return $s; - } - } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) { - // Question is a HOT_SPOT - //checking document/images visibility - if (api_is_platform_admin() || api_is_course_admin()) { - $course = api_get_course_info(); - $doc_id = DocumentManager::get_document_id($course, '/images/'.$pictureName); - if (is_numeric($doc_id)) { - $images_folder_visibility = api_get_item_visibility($course,'document', $doc_id, api_get_session_id()); - if (!$images_folder_visibility) { - //This message is shown only to the course/platform admin if the image is set to visibility = false - Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage')); - } - } - } - $questionName = $objQuestionTmp->selectTitle(); - $questionDescription = $objQuestionTmp->selectDescription(); - - if ($freeze) { - echo Display::img($objQuestionTmp->selectPicturePath()); - return; - } - - // Get the answers, make a list - $objAnswerTmp = new Answer($questionId); - $nbrAnswers = $objAnswerTmp->selectNbrAnswers(); - - // get answers of hotpost - $answers_hotspot = array(); - for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) { - $answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId)); - $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId); - } - - // display answers of hotpost order by id - $answer_list = '
'.get_lang('HotspotZones').'
'; - if (!empty($answers_hotspot)) { - ksort($answers_hotspot); - foreach ($answers_hotspot as $key => $value) { - $answer_list .= '
'.$key.'.- '.$value.'

'; - } - } - $answer_list .= '
'; - - if ($answerType == HOT_SPOT_DELINEATION) { - $answer_list=''; - $swf_file = 'hotspot_delineation_user'; - $swf_height = 405; - } else { - $swf_file = 'hotspot_user'; - $swf_height = 436; - } - - if (!$only_questions) { - if ($show_title) { - Testcategory::displayCategoryAndTitle($objQuestionTmp->id); - echo '
'.$current_item.'. '.$questionName.'
'; - } - //@todo I need to the get the feedback type - echo ''; - echo ' - - '; - } - - $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1'); - - $s .= ' - - - - - '; - $s .= ''; - echo $s; - echo '
'; - echo $questionDescription; - echo '
- -
- - '.$answer_list.'
-
'; - } - - return $nbrAnswers; -} - -/** - * @param int $exe_id - * @return array - */ -function get_exercise_track_exercise_info($exe_id) -{ - $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); - $TBL_TRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE); - $exe_id = intval($exe_id); - $result = array(); - if (!empty($exe_id)) { - $sql = " SELECT q.*, tee.* - FROM $TBL_EXERCICES as q - INNER JOIN $TBL_TRACK_EXERCICES as tee - ON q.id=tee.exe_exo_id - INNER JOIN $TBL_COURSE c - ON c.code = tee.exe_cours_id - WHERE tee.exe_id=$exe_id - AND q.c_id=c.id"; - - $res_fb_type = Database::query($sql); - $result = Database::fetch_array($res_fb_type, 'ASSOC'); - } - - return $result; -} - -/** - * Validates the time control key - */ -function exercise_time_control_is_valid($exercise_id, $lp_id = 0 , $lp_item_id = 0) -{ - $course_id = api_get_course_int_id(); - $exercise_id = intval($exercise_id); - $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); - $sql = "SELECT expired_time FROM $TBL_EXERCICES - WHERE c_id = $course_id AND id = $exercise_id"; - $result = Database::query($sql); - $row = Database::fetch_array($result, 'ASSOC'); - if (!empty($row['expired_time'])) { - $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id); - if (isset($_SESSION['expired_time'][$current_expired_time_key])) { - $current_time = time(); - $expired_time = api_strtotime($_SESSION['expired_time'][$current_expired_time_key], 'UTC'); - $total_time_allowed = $expired_time + 30; - if ($total_time_allowed < $current_time) { - return false; - } - return true; - } else { - return false; - } - } else { - return true; - } -} - -/** -Deletes the time control token - */ -function exercise_time_control_delete($exercise_id, $lp_id = 0 , $lp_item_id = 0) -{ - $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id); - unset($_SESSION['expired_time'][$current_expired_time_key]); -} - -/** -Generates the time control key - */ -function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) -{ - $exercise_id = intval($exercise_id); - $lp_id = intval($lp_id); - $lp_item_id = intval($lp_item_id); - return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id().'_'.$lp_id.'_'.$lp_item_id; -} - -/** - * Get session time control - */ -function get_session_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) -{ - $return_value = 0; - $time_control_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id); - if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) { - $return_value = $_SESSION['expired_time'][$time_control_key]; - } - return $return_value; -} - -/** - * Gets count of exam results - * @todo this function should be moved in a library + no global calls - */ -function get_count_exam_results($exercise_id, $extra_where_conditions) -{ - $count = get_exam_results_data(null, null, null, null, $exercise_id, $extra_where_conditions, true); - return $count; -} - -/** - * @param string $in_hotpot_path - * @return int - */ -function get_count_exam_hotpotatoes_results($in_hotpot_path) -{ - return get_exam_results_hotpotatoes_data(0, 0, '', '', $in_hotpot_path, true, ''); -} - -/** - * @param int $in_from - * @param int $in_number_of_items - * @param int $in_column - * @param int $in_direction - * @param string $in_hotpot_path - * @param bool $in_get_count - * @param null $where_condition - * @return array|int - */ -function get_exam_results_hotpotatoes_data( - $in_from, - $in_number_of_items, - $in_column, - $in_direction, - $in_hotpot_path, - $in_get_count = false, - $where_condition = null -) { - $course_code = api_get_course_id(); - /* by default in_column = 1 If parameters given, - it is the name of the column witch is the bdd field name*/ - if ($in_column == 1) { - $in_column = 'firstname'; - } - $in_hotpot_path = Database::escape_string($in_hotpot_path); - $in_direction = Database::escape_string($in_direction); - $in_column = Database::escape_string($in_column); - $in_number_of_items = intval($in_number_of_items); - $in_from = intval($in_from); - - $TBL_TRACK_HOTPOTATOES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES); - $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER); - - $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp - JOIN $TBL_USER u ON thp.exe_user_id = u.user_id - WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'"; - - // just count how many answers - if ($in_get_count) { - $res = Database::query($sql); - return Database::num_rows($res); - } - // get a number of sorted results - $sql .= " $where_condition - ORDER BY $in_column $in_direction - LIMIT $in_from, $in_number_of_items"; - - $res = Database::query($sql); - $result = array(); - $apiIsAllowedToEdit = api_is_allowed_to_edit(); - $urlBase = api_get_path(WEB_CODE_PATH).'exercice/hotpotatoes_exercise_report.php?action=delete&'.api_get_cidreq().'&id='; - while ($data = Database::fetch_array($res)) { - $actions = null; - - if ($apiIsAllowedToEdit) { - $url = $urlBase.$data['id'].'&path='.$data['exe_name']; - $actions = Display::url( - Display::return_icon('delete.png', get_lang('Delete')), - $url - ); - } - - $result[] = array( - 'firstname' => $data['firstname'], - 'lastname' => $data['lastname'], - 'username' => $data['username'], - 'group_name' => implode("
", GroupManager::get_user_group_name($data['user_id'])), - 'exe_date' => $data['exe_date'], - 'score' => $data['exe_result'].' / '.$data['exe_weighting'], - 'actions' => $actions, - ); - } - - return $result; -} - -/** - * @param string $exercisePath - * @param int $userId - * @param int $courseId - * @param int $sessionId - * - * @return array - */ -function getLatestHotPotatoResult( - $exercisePath, - $userId, - $courseId, - $sessionId -) { - $table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES); - - $courseInfo = api_get_course_info_by_id($courseId); - $courseCode = $courseInfo['code']; - $exercisePath = Database::escape_string($exercisePath); - $userId = intval($userId); - - $sql = "SELECT * FROM $table - WHERE - exe_cours_id = '$courseCode' AND - exe_name LIKE '$exercisePath%' AND - exe_user_id = $userId - ORDER BY id - LIMIT 1"; - $result = Database::query($sql); - $attempt = array(); - if (Database::num_rows($result)) { - $attempt = Database::fetch_array($result, 'ASSOC'); - } - return $attempt; -} - -/** - * Gets the exam'data results - * @todo this function should be moved in a library + no global calls - * @param int $from - * @param int $number_of_items - * @param int $column - * @param string $direction - * @param int $exercise_id - * @param null $extra_where_conditions - * @param bool $get_count - * @return array - */ -function get_exam_results_data( - $from, - $number_of_items, - $column, - $direction, - $exercise_id, - $extra_where_conditions = null, - $get_count = false -) { - //@todo replace all this globals - global $documentPath, $filter; - - $course_id = api_get_course_int_id(); - $course_code = api_get_course_id(); - $sessionId = api_get_session_id(); - - $is_allowedToEdit = api_is_allowed_to_edit(null,true) || api_is_allowed_to_edit(true) || api_is_drh() || api_is_student_boss(); - - $TBL_USER = Database :: get_main_table(TABLE_MAIN_USER); - $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST); - $TBL_GROUP_REL_USER = Database :: get_course_table(TABLE_GROUP_USER); - $TBL_GROUP = Database :: get_course_table(TABLE_GROUP); - $TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $TBL_TRACK_HOTPOTATOES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES); - $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - - $session_id_and = ' AND te.session_id = '.$sessionId.' '; - $exercise_id = intval($exercise_id); - - $exercise_where = ''; - if (!empty($exercise_id)) { - $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.' '; - } - - $hotpotatoe_where = ''; - if (!empty($_GET['path'])) { - $hotpotatoe_path = Database::escape_string($_GET['path']); - $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'" '; - } - - // sql for chamilo-type tests for teacher / tutor view - $sql_inner_join_tbl_track_exercices = " ( - SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised - FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr - ON (ttte.exe_id = tr.exe_id) - WHERE - exe_cours_id = '$course_code' AND - exe_exo_id = $exercise_id AND - ttte.session_id = ".$sessionId." - )"; - if ($is_allowedToEdit) { - //Teacher view - if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') { - //$exercise_where_query = ' te.exe_exo_id = ce.id AND '; - } - - $sqlFromOption = ""; - $sqlWhereOption = ""; // for hpsql - - //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries - - //Hack in order to filter groups - $sql_inner_join_tbl_user = ''; - - if (strpos($extra_where_conditions, 'group_id')) { - $sql_inner_join_tbl_user = " - ( - SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id - FROM $TBL_USER u - INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id.") - INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=".$course_id.") - )"; - } - - if (strpos($extra_where_conditions, 'group_all')) { - - $extra_where_conditions = str_replace("AND ( group_id = 'group_all' )", '', $extra_where_conditions); - $extra_where_conditions = str_replace("AND group_id = 'group_all'", '', $extra_where_conditions); - $extra_where_conditions = str_replace("group_id = 'group_all' AND", '', $extra_where_conditions); - - $sql_inner_join_tbl_user = " - ( - SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id - FROM $TBL_USER u - )"; - $sql_inner_join_tbl_user = null; - } - - if (strpos($extra_where_conditions, 'group_none')) { - $extra_where_conditions = str_replace("AND ( group_id = 'group_none' )", "AND ( group_id is null )", $extra_where_conditions); - $extra_where_conditions = str_replace("AND group_id = 'group_none'", "AND ( group_id is null )", $extra_where_conditions); - $sql_inner_join_tbl_user = " - ( - SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id - FROM $TBL_USER u - LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id." ) - LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = ".$course_id.") - )"; - } - - // All - $is_empty_sql_inner_join_tbl_user = false; - - if (empty($sql_inner_join_tbl_user)) { - $is_empty_sql_inner_join_tbl_user = true; - $sql_inner_join_tbl_user = " - ( - SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id, official_code - FROM $TBL_USER u - WHERE u.status NOT IN(" . api_get_users_status_ignored_in_reports('string') . ") - )"; - } - - $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru "; - $sqlWhereOption = " AND gru.c_id = ".api_get_course_int_id()." AND gru.user_id = user.user_id "; - - $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname"; - - if ($get_count) { - $sql_select = "SELECT count(te.exe_id) "; - } else { - $sql_select = "SELECT DISTINCT - user_id, - $first_and_last_name, - official_code, - ce.title, - username, - te.exe_result, - te.exe_weighting, - te.exe_date, - te.exe_id, - email as exemail, - te.start_date, - steps_counter, - exe_user_id, - te.exe_duration, - propagate_neg, - revised, - group_name, - group_id, - orig_lp_id"; - } - - $sql = " $sql_select - FROM $TBL_EXERCICES AS ce - INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id) - INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id) - WHERE - te.status != 'incomplete' AND - te.exe_cours_id='" . api_get_course_id() . "' $session_id_and AND - ce.active <>-1 AND ce.c_id=".api_get_course_int_id()." - $exercise_where - $extra_where_conditions - "; - - // sql for hotpotatoes tests for teacher / tutor view - - if ($get_count) { - $hpsql_select = "SELECT count(username)"; - } else { - $hpsql_select = "SELECT - $first_and_last_name , - username, - official_code, - tth.exe_name, - tth.exe_result , - tth.exe_weighting, - tth.exe_date"; - } - - $hpsql = " $hpsql_select - FROM - $TBL_TRACK_HOTPOTATOES tth, - $TBL_USER user - $sqlFromOption - WHERE - user.user_id=tth.exe_user_id - AND tth.exe_cours_id = '" . api_get_course_id()."' - $hotpotatoe_where - $sqlWhereOption - AND user.status NOT IN(" . api_get_users_status_ignored_in_reports('string') . ") - ORDER BY - tth.exe_cours_id ASC, - tth.exe_date DESC"; - } - - if ($get_count) { - $resx = Database::query($sql); - $rowx = Database::fetch_row($resx,'ASSOC'); - - return $rowx[0]; - } - - $teacher_list = CourseManager::get_teacher_list_from_course_code(api_get_course_id()); - $teacher_id_list = array(); - foreach ($teacher_list as $teacher) { - $teacher_id_list[] = $teacher['user_id']; - } - - $list_info = array(); - - // Simple exercises - if (empty($hotpotatoe_where)) { - $column = !empty($column) ? Database::escape_string($column) : null; - $from = intval($from); - $number_of_items = intval($number_of_items); - - if (!empty($column)) { - $sql .= " ORDER BY $column $direction "; - } - $sql .= " LIMIT $from, $number_of_items"; - - $results = array(); - $resx = Database::query($sql); - while ($rowx = Database::fetch_array($resx, 'ASSOC')) { - $results[] = $rowx; - } - - $group_list = GroupManager::get_group_list(); - $clean_group_list = array(); - - if (!empty($group_list)) { - foreach ($group_list as $group) { - $clean_group_list[$group['id']] = $group['name']; - } - } - - $lp_list_obj = new LearnpathList(api_get_user_id()); - $lp_list = $lp_list_obj->get_flat_list(); - - if (is_array($results)) { - - $users_array_id = array(); - $from_gradebook = false; - if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') { - $from_gradebook = true; - } - $sizeof = count($results); - - $user_list_id = array(); - $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE); - - // Looping results - for ($i = 0; $i < $sizeof; $i++) { - $revised = $results[$i]['revised']; - - if ($from_gradebook && ($is_allowedToEdit)) { - if (in_array($results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], $users_array_id)) { - continue; - } - $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname']; - } - - $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null; - $lp_name = null; - - if ($lp_obj) { - $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$results[$i]['orig_lp_id']; - $lp_name = Display::url($lp_obj['lp_name'], $url, array('target' => '_blank')); - } - - //Add all groups by user - $group_name_list = null; - - if ($is_empty_sql_inner_join_tbl_user) { - $group_list = GroupManager::get_group_ids( - api_get_course_int_id(), - $results[$i]['user_id'] - ); - - foreach ($group_list as $id) { - $group_name_list .= $clean_group_list[$id].'
'; - } - $results[$i]['group_name'] = $group_name_list; - } - - $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0; - - $user_list_id[] = $results[$i]['exe_user_id']; - $id = $results[$i]['exe_id']; - - $dt = api_convert_and_format_date($results[$i]['exe_weighting']); - - // we filter the results if we have the permission to - if (isset($results[$i]['results_disabled'])) { - $result_disabled = intval($results[$i]['results_disabled']); - } else { - $result_disabled = 0; - } - - if ($result_disabled == 0) { - $my_res = $results[$i]['exe_result']; - $my_total = $results[$i]['exe_weighting']; - - $results[$i]['start_date'] = api_get_local_time($results[$i]['start_date']); - $results[$i]['exe_date'] = api_get_local_time($results[$i]['exe_date']); - - if (!$results[$i]['propagate_neg'] && $my_res < 0) { - $my_res = 0; - } - - $score = show_score($my_res, $my_total); - - $actions = ''; - if ($is_allowedToEdit) { - if (isset($teacher_id_list)) { - if (in_array($results[$i]['exe_user_id'], $teacher_id_list)) { - $actions .= Display::return_icon('teachers.gif', get_lang('Teacher')); - } - } - if ($revised) { - $actions .= "". - Display :: return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL); - $actions .= ' '; - } else { - $actions .="". - Display :: return_icon('quiz.gif', get_lang('Qualify')); - $actions .=' '; - } - $actions .=""; - - if ($filter == 2) { - $actions .=' ' . - Display :: return_icon('history.gif', get_lang('ViewHistoryChange')).''; - } - - //Admin can always delete the attempt - if (($locked == false || api_is_platform_admin()) && !api_is_student_boss()) { - $ip = TrackingUserLog::get_ip_from_user_event($results[$i]['exe_user_id'], date('Y-m-d h:i:s'), false); - $actions .= ''; - - $delete_link = ''.Display :: return_icon('delete.png', get_lang('Delete')).''; - $delete_link = utf8_encode($delete_link); - - if (api_is_drh() && !api_is_platform_admin()) { - $delete_link = null; - } - $actions .= $delete_link.' '; - } - - } else { - $attempt_url = api_get_path(WEB_CODE_PATH).'exercice/result.php?'.api_get_cidreq().'&id='.$results[$i]['exe_id'].'&id_session='.$sessionId.'&height=500&width=750'; - $attempt_link = Display::url(get_lang('Show'), $attempt_url, array('class'=>'ajax btn')); - $actions .= $attempt_link; - } - - if ($revised) { - $revised = Display::label(get_lang('Validated'), 'success'); - } else { - $revised = Display::label(get_lang('NotValidated'), 'info'); - } - - if ($is_allowedToEdit) { - $results[$i]['status'] = $revised; - $results[$i]['score'] = $score; - $results[$i]['lp'] = $lp_name; - $results[$i]['actions'] = $actions; - $list_info[] = $results[$i]; - } else { - $results[$i]['status'] = $revised; - $results[$i]['score'] = $score; - $results[$i]['actions'] = $actions; - $list_info[] = $results[$i]; - } - } - } - } - } else { - $hpresults = getManyResultsXCol($hpsql, 6); - // Print HotPotatoes test results. - if (is_array($hpresults)) { - for ($i = 0; $i < sizeof($hpresults); $i++) { - $hp_title = GetQuizName($hpresults[$i][3], $documentPath); - if ($hp_title == '') { - $hp_title = basename($hpresults[$i][3]); - } - - $hp_date = api_get_local_time($hpresults[$i][6], null, date_default_timezone_get()); - $hp_result = round(($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, 2).'% ('.$hpresults[$i][4].' / '.$hpresults[$i][5].')'; - if ($is_allowedToEdit) { - $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hpresults[$i][2], '', $hp_title, '-', $hp_date , $hp_result , '-'); - } else { - $list_info[] = array($hp_title, '-', $hp_date , $hp_result , '-'); - } - } - } - } - - return $list_info; -} - -/** - * Converts the score with the exercise_max_note and exercise_min_score - * the platform settings + formats the results using the float_format function - * - * @param float $score - * @param float $weight - * @param bool $show_percentage show percentage or not - * @param bool $use_platform_settings use or not the platform settings - * @param bool $show_only_percentage - * @return string an html with the score modified - */ -function show_score($score, $weight, $show_percentage = true, $use_platform_settings = true, $show_only_percentage = false) -{ - if (is_null($score) && is_null($weight)) { - return '-'; - } - - $max_note = api_get_setting('exercise_max_score'); - $min_note = api_get_setting('exercise_min_score'); - - if ($use_platform_settings) { - if ($max_note != '' && $min_note != '') { - if (!empty($weight) && intval($weight) != 0) { - $score = $min_note + ($max_note - $min_note) * $score / $weight; - } else { - $score = $min_note; - } - $weight = $max_note; - } - } - $percentage = (100 * $score) / ($weight != 0 ? $weight : 1); - - // Formats values - $percentage = float_format($percentage, 1); - $score = float_format($score, 1); - $weight = float_format($weight, 1); - - $html = null; - if ($show_percentage) { - $parent = '(' . $score . ' / ' . $weight . ')'; - $html = $percentage."% $parent"; - if ($show_only_percentage) { - $html = $percentage."% "; - } - } else { - $html = $score . ' / ' . $weight; - } - $html = Display::span($html, array('class' => 'score_exercise')); - - return $html; -} - -/** - * @param float $score - * @param float $weight - * @param string $pass_percentage - * @return bool - */ -function is_success_exercise_result($score, $weight, $pass_percentage) -{ - $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1); - if (isset($pass_percentage) && !empty($pass_percentage)) { - if ($percentage >= $pass_percentage) { - return true; - } - } - return false; -} - -/** - * @param float $score - * @param float $weight - * @param string $pass_percentage - * @return string - */ -function show_success_message($score, $weight, $pass_percentage) -{ - $res = ""; - if (is_pass_pourcentage_enabled($pass_percentage)) { - $is_success = is_success_exercise_result($score, $weight, $pass_percentage); - - if ($is_success) { - $html = get_lang('CongratulationsYouPassedTheTest'); - $icon = Display::return_icon('completed.png', get_lang('Correct'), array(), ICON_SIZE_MEDIUM); - } else { - //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning'); - $html = get_lang('YouDidNotReachTheMinimumScore'); - $icon = Display::return_icon('warning.png', get_lang('Wrong'), array(), ICON_SIZE_MEDIUM); - } - $html = Display::tag('h4', $html); - $html .= Display::tag('h5', $icon, array('style' => 'width:40px; padding:2px 10px 0px 0px')); - $res = $html; - } - return $res; -} - -/** - * Return true if pass_pourcentage activated (we use the pass pourcentage feature - * return false if pass_percentage = 0 (we don't use the pass pourcentage feature - * @param $in_pass_pourcentage - * @return boolean - * In this version, pass_percentage and show_success_message are disabled if - * pass_percentage is set to 0 - */ -function is_pass_pourcentage_enabled($in_pass_pourcentage) -{ - return $in_pass_pourcentage > 0; -} - -/** - * Converts a numeric value in a percentage example 0.66666 to 66.67 % - * @param $value - * @return float Converted number - */ -function convert_to_percentage($value) -{ - $return = '-'; - if ($value != '') { - $return = float_format($value * 100, 1).' %'; - } - return $return; -} - -/** - * Converts a score/weight values to the platform scale - * @param float $score - * @param float $weight - * - * @return float the score rounded converted to the new range - */ -function convert_score($score, $weight) -{ - $max_note = api_get_setting('exercise_max_score'); - $min_note = api_get_setting('exercise_min_score'); - - if ($score != '' && $weight != '') { - if ($max_note != '' && $min_note != '') { - if (!empty($weight)) { - $score = $min_note + ($max_note - $min_note) * $score / $weight; - } else { - $score = $min_note; - } - } - } - $score_rounded = float_format($score, 1); - return $score_rounded; -} - -/** - * Getting all active exercises from a course from a session - * (if a session_id is provided we will show all the exercises in the course + - * all exercises in the session) - * @param array $course_info - * @param int $session_id - * @param boolean $check_publication_dates - * @param string $search Search exercise name - * @param boolean $search_all_sessions Search exercises in all sessions - * @param int 0 = only inactive exercises - * 1 = only active exercises, - * 2 = all exercises - * 3 = active <> -1 - * @return array array with exercise data - */ -function get_all_exercises( - $course_info = null, - $session_id = 0, - $check_publication_dates = false, - $search = '', - $search_all_sessions = false, - $active = 2 -) { - $course_id = api_get_course_int_id(); - - if (!empty($course_info) && !empty($course_info['real_id'])) { - $course_id = $course_info['real_id']; - } - - if ($session_id == -1) { - $session_id = 0; - } - - $now = api_get_utc_datetime(); - $time_conditions = ''; - - if ($check_publication_dates) { - //start and end are set - $time_conditions = " AND ((start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now' ) OR "; - // only start is set - $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time = '0000-00-00 00:00:00') OR "; - // only end is set - $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now') OR "; - // nothing is set - $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) "; - } - - $needle_where = !empty($search) ? " AND title LIKE '?' " : ''; - $needle = !empty($search) ? "%" . $search . "%" : ''; - - // Show courses by active status - $active_sql = ''; - if ($active == 3) { - $active_sql = ' active <> -1 AND'; - } else if ($active != 2) { - $active_sql = sprintf(' active = %d AND', $active); - } - - if ($search_all_sessions == true) { - $conditions = array( - 'where' => array($active_sql . ' c_id = ? '. $needle_where . $time_conditions => array($course_id, $needle)), - 'order' => 'title' - ); - } else { - if ($session_id == 0) { - $conditions = array( - 'where' => array($active_sql . ' session_id = ? AND c_id = ? '. $needle_where . $time_conditions => array($session_id, $course_id, $needle)), - 'order' =>'title' - ); - } else { - $conditions = array( - 'where' => array($active_sql . ' (session_id = 0 OR session_id = ? ) AND c_id = ? ' . $needle_where . $time_conditions => array($session_id, $course_id, $needle)), - 'order' => 'title' - ); - } - } - - $table = Database :: get_course_table(TABLE_QUIZ_TEST); - - return Database::select('*', $table, $conditions); -} - -/** - * Get exercise information by id - * @param int $exerciseId Exercise Id - * @param int $courseId The course ID (necessary as c_quiz.id is not unique) - * @return array Exercise info - */ -function get_exercise_by_id($exerciseId = 0, $courseId = null) -{ - $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST); - if (empty($courseId)) { - $courseId = api_get_course_int_id(); - } else { - $courseId = intval($courseId); - } - $conditions = array('where' => array('id = ?' => array($exerciseId), ' AND c_id = ? ' => $courseId)); - return Database::select('*', $TBL_EXERCICES, $conditions); -} -/** - * Getting all exercises (active only or all) - * from a course from a session - * (if a session_id is provided we will show all the exercises in the - * course + all exercises in the session) - * @param array course data - * @param int session id - * @param int course c_id - * @param boolean $only_active_exercises - * @return array array with exercise data - * modified by Hubert Borderiou - */ -function get_all_exercises_for_course_id($course_info = null, $session_id = 0, $course_id = 0, $only_active_exercises = true) -{ - $TBL_EXERCISES = Database :: get_course_table(TABLE_QUIZ_TEST); - - if ($only_active_exercises) { - // Only active exercises. - $sql_active_exercises = "active = 1 AND "; - } else { - // Not only active means visible and invisible NOT deleted (-2) - $sql_active_exercises = "active IN (1, 0) AND "; - } - - if ($session_id == -1) { - $session_id = 0; - } - - $params = array( - $session_id, - $course_id - ); - - if ($session_id == 0) { - $conditions = array( - 'where' => array("$sql_active_exercises session_id = ? AND c_id = ?" => $params), - 'order'=>'title' - ); - } else { - // All exercises - $conditions = array( - 'where' => array("$sql_active_exercises (session_id = 0 OR session_id = ? ) AND c_id=?" => $params), - 'order'=>'title' - ); - } - - return Database::select('*', $TBL_EXERCISES, $conditions); -} - -/** - * Gets the position of the score based in a given score (result/weight) - * and the exe_id based in the user list - * (NO Exercises in LPs ) - * @param float $my_score user score to be compared *attention* - * $my_score = score/weight and not just the score - * @param int $my_exe_id exe id of the exercise - * (this is necessary because if 2 students have the same score the one - * with the minor exe_id will have a best position, just to be fair and FIFO) - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @param array $user_list - * @param bool $return_string - * - * @return int the position of the user between his friends in a course - * (or course within a session) - */ -function get_exercise_result_ranking( - $my_score, - $my_exe_id, - $exercise_id, - $course_code, - $session_id = 0, - $user_list = array(), - $return_string = true -) { - //No score given we return - if (is_null($my_score)) { - return '-'; - } - if (empty($user_list)) { - return '-'; - } - - $best_attempts = array(); - foreach ($user_list as $user_data) { - $user_id = $user_data['user_id']; - $best_attempts[$user_id]= get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id); - } - - if (empty($best_attempts)) { - return 1; - } else { - $position = 1; - $my_ranking = array(); - foreach($best_attempts as $user_id => $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $my_ranking[$user_id] = $result['exe_result']/$result['exe_weighting']; - } else { - $my_ranking[$user_id] = 0; - } - } - //if (!empty($my_ranking)) { - asort($my_ranking); - $position = count($my_ranking); - if (!empty($my_ranking)) { - foreach ($my_ranking as $user_id => $ranking) { - if ($my_score >= $ranking) { - if ($my_score == $ranking) { - $exe_id = $best_attempts[$user_id]['exe_id']; - if ($my_exe_id < $exe_id) { - $position--; - } - } else { - $position--; - } - } - } - } - //} - $return_value = array( - 'position' => $position, - 'count' => count($my_ranking) - ); - - if ($return_string) { - if (!empty($position) && !empty($my_ranking)) { - $return_value = $position.'/'.count($my_ranking); - } else { - $return_value = '-'; - } - } - return $return_value; - } -} - -/** - * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts - * (NO Exercises in LPs ) old functionality by attempt - * @param float user score to be compared attention => score/weight - * @param int exe id of the exercise (this is necesary because if 2 students have the same score the one with the minor exe_id will have a best position, just to be fair and FIFO) - * @param int exercise id - * @param string course code - * @param int session id - * @return int the position of the user between his friends in a course (or course within a session) - */ -function get_exercise_result_ranking_by_attempt($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) { - if (empty($session_id)) { - $session_id = 0; - } - if (is_null($my_score)) { - return '-'; - } - $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false); - $position_data = array(); - if (empty($user_results)) { - return 1; - } else { - $position = 1; - $my_ranking = array(); - foreach($user_results as $result) { - //print_r($result); - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $my_ranking[$result['exe_id']] = $result['exe_result']/$result['exe_weighting']; - } else { - $my_ranking[$result['exe_id']] = 0; - } - } - asort($my_ranking); - $position = count($my_ranking); - if (!empty($my_ranking)) { - foreach($my_ranking as $exe_id=>$ranking) { - if ($my_score >= $ranking) { - if ($my_score == $ranking) { - if ($my_exe_id < $exe_id) { - $position--; - } - } else { - $position--; - } - } - } - } - $return_value = array( - 'position' => $position, - 'count' => count($my_ranking) - ); - - if ($return_string) { - if (!empty($position) && !empty($my_ranking)) { - return $position.'/'.count($my_ranking); - } - } - return $return_value; - } -} - -/** - * Get the best attempt in a exercise (NO Exercises in LPs ) - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * - * @return array - */ -function get_best_attempt_in_course($exercise_id, $course_code, $session_id) -{ - $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false); - $best_score_data = array(); - $best_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - if ($score >= $best_score) { - $best_score = $score; - $best_score_data = $result; - } - } - } - } - return $best_score_data; -} - -/** - * Get the best score in a exercise (NO Exercises in LPs ) - * @param int $user_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * - * @return array - */ -function get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id) -{ - $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false, $user_id); - $best_score_data = array(); - $best_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - if ($score >= $best_score) { - $best_score = $score; - $best_score_data = $result; - } - } - } - } - return $best_score_data; -} - -/** - * Get average score (NO Exercises in LPs ) - * @param int exercise id - * @param string course code - * @param int session id - * @return float Average score - */ -function get_average_score($exercise_id, $course_code, $session_id) -{ - $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id); - $avg_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - $avg_score +=$score; - } - } - $avg_score = float_format($avg_score / count($user_results), 1); - } - - return $avg_score; -} - -/** - * Get average score by score (NO Exercises in LPs ) - * @param int exercise id - * @param string course code - * @param int session id - * @return float Average score - */ -function get_average_score_by_course($course_code, $session_id) -{ - $user_results = get_all_exercise_results_by_course($course_code, $session_id, false); - //echo $course_code.' - '.$session_id.'
'; - $avg_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - $avg_score +=$score; - } - } - //We asume that all exe_weighting - //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); - $avg_score = ($avg_score / count($user_results)); - } - - return $avg_score; -} - -/** - * @param int $user_id - * @param string $course_code - * @param int $session_id - * - * @return float|int - */ -function get_average_score_by_course_by_user($user_id, $course_code, $session_id) -{ - $user_results = get_all_exercise_results_by_user($user_id, $course_code, $session_id); - $avg_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - $avg_score +=$score; - } - } - //We asume that all exe_weighting - //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); - $avg_score = ($avg_score / count($user_results)); - } - return $avg_score; -} - -/** - * Get average score by score (NO Exercises in LPs ) - * @param int exercise id - * @param string course code - * @param int session id - * @return float Best average score - */ -function get_best_average_score_by_exercise($exercise_id, $course_code, $session_id, $user_count) -{ - $user_results = get_best_exercise_results_by_user($exercise_id, $course_code, $session_id); - $avg_score = 0; - if (!empty($user_results)) { - foreach($user_results as $result) { - if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { - $score = $result['exe_result']/$result['exe_weighting']; - $avg_score +=$score; - } - } - //We asume that all exe_weighting - //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); - //$avg_score = ($avg_score / count($user_results)); - if(!empty($user_count)) { - $avg_score = float_format($avg_score / $user_count, 1) * 100; - } else { - $avg_score = 0; - } - } - return $avg_score; -} - -/** - * @param string $course_code - * @param int $session_id - * - * @return array - */ -function get_exercises_to_be_taken($course_code, $session_id) -{ - $course_info = api_get_course_info($course_code); - $exercises = get_all_exercises($course_info, $session_id); - $result = array(); - $now = time() + 15*24*60*60; - foreach($exercises as $exercise_item) { - if (isset($exercise_item['end_time']) && - !empty($exercise_item['end_time']) && - $exercise_item['end_time'] != '0000-00-00 00:00:00' && - api_strtotime($exercise_item['end_time'], 'UTC') < $now - ) { - $result[] = $exercise_item; - } - } - return $result; -} - -/** - * Get student results (only in completed exercises) stats by question - * @param int $question_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * - **/ -function get_student_stats_by_question($question_id, $exercise_id, $course_code, $session_id) -{ - $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - - $question_id = intval($question_id); - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - $sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average - FROM $track_exercises e - INNER JOIN $track_attempt a - ON ( - a.exe_id = e.exe_id AND - e.exe_cours_id = a.course_code AND - e.session_id = a.session_id - ) - WHERE - exe_exo_id = $exercise_id AND - course_code = '$course_code' AND - e.session_id = $session_id AND - question_id = $question_id AND - status = '' - LIMIT 1"; - $result = Database::query($sql); - $return = array(); - if ($result) { - $return = Database::fetch_array($result, 'ASSOC'); - } - - return $return; -} - -/** - * @param int $question_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @return int - */ -function get_number_students_question_with_answer_count($question_id, $exercise_id, $course_code, $session_id) -{ - $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); - $courseUserSession = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - - $question_id = intval($question_id); - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - if (empty($session_id)) { - $courseCondition = " - INNER JOIN $courseUser cu - ON cu.course_code = a.course_code AND cu.user_id = exe_user_id"; - $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT; - } else { - $courseCondition = " - INNER JOIN $courseUserSession cu - ON cu.course_code = a.course_code AND cu.id_user = exe_user_id"; - $courseConditionWhere = " AND cu.status = 0 "; - } - - $sql = "SELECT DISTINCT exe_user_id - FROM $track_exercises e - INNER JOIN $track_attempt a - ON ( - a.exe_id = e.exe_id AND - e.exe_cours_id = a.course_code AND - e.session_id = a.session_id - ) - $courseCondition - WHERE - exe_exo_id = $exercise_id AND - a.course_code = '$course_code' AND - e.session_id = $session_id AND - question_id = $question_id AND - answer <> '0' AND - e.status = '' - $courseConditionWhere - "; - $result = Database::query($sql); - $return = 0; - if ($result) { - $return = Database::num_rows($result); - } - return $return; -} - -/** - * @param int $answer_id - * @param int $question_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * - * @return int - */ -function get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, $course_code, $session_id) -{ - $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); - $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); - $courseUserSession = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - - $question_id = intval($question_id); - $answer_id = intval($answer_id); - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - if (empty($session_id)) { - $courseCondition = " - INNER JOIN $courseUser cu - ON cu.course_code = a.hotspot_course_code AND cu.user_id = exe_user_id"; - $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT; - } else { - $courseCondition = " - INNER JOIN $courseUserSession cu - ON cu.course_code = a.hotspot_course_code AND cu.id_user = exe_user_id"; - $courseConditionWhere = " AND cu.status = 0 "; - } - - $sql = "SELECT DISTINCT exe_user_id - FROM $track_exercises e - INNER JOIN $track_hotspot a - ON (a.hotspot_exe_id = e.exe_id) - $courseCondition - WHERE - exe_exo_id = $exercise_id AND - a.hotspot_course_code = '$course_code' AND - e.session_id = $session_id AND - hotspot_answer_id = $answer_id AND - hotspot_question_id = $question_id AND - hotspot_correct = 1 AND - e.status = '' - $courseConditionWhere - "; - - $result = Database::query($sql); - $return = 0; - if ($result) { - $return = Database::num_rows($result); - } - return $return; -} - -/** - * @param int $answer_id - * @param int $question_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @param string $question_type - * @param string $correct_answer - * @param string $current_answer - * @return int - */ -function get_number_students_answer_count( - $answer_id, - $question_id, - $exercise_id, - $course_code, - $session_id, - $question_type = null, - $correct_answer = null, - $current_answer = null -) { - $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); - $courseUserSession = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER); - - $question_id = intval($question_id); - $answer_id = intval($answer_id); - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - switch ($question_type) { - case FILL_IN_BLANKS: - $answer_condition = ""; - $select_condition = " e.exe_id, answer "; - break; - case MATCHING: - default: - $answer_condition = " answer = $answer_id AND "; - $select_condition = " DISTINCT exe_user_id "; - } - - if (empty($session_id)) { - $courseCondition = " - INNER JOIN $courseUser cu - ON cu.course_code = a.course_code AND cu.user_id = exe_user_id"; - $courseConditionWhere = " AND relation_type <> 2 AND cu.status = ".STUDENT; - } else { - $courseCondition = " - INNER JOIN $courseUserSession cu - ON cu.course_code = a.course_code AND cu.id_user = exe_user_id"; - $courseConditionWhere = " AND cu.status = 0 "; - } - - $sql = "SELECT $select_condition - FROM $track_exercises e - INNER JOIN $track_attempt a - ON ( - a.exe_id = e.exe_id AND - e.exe_cours_id = a.course_code AND - e.session_id = a.session_id - ) - $courseCondition - WHERE - exe_exo_id = $exercise_id AND - a.course_code = '$course_code' AND - e.session_id = $session_id AND - $answer_condition - question_id = $question_id AND - e.status = '' - $courseConditionWhere - "; - $result = Database::query($sql); - $return = 0; - if ($result) { - $good_answers = 0; - switch ($question_type) { - case FILL_IN_BLANKS: - while ($row = Database::fetch_array($result, 'ASSOC')) { - $fill_blank = check_fill_in_blanks($correct_answer, $row['answer']); - if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1 ) { - $good_answers++; - } - } - return $good_answers; - break; - case MATCHING: - default: - $return = Database::num_rows($result); - } - } - - return $return; -} - -/** - * @param array $answer - * @param string $user_answer - * @return array - */ -function check_fill_in_blanks($answer, $user_answer) -{ - // the question is encoded like this - // [A] B [C] D [E] F::10,10,10@1 - // number 1 before the "@" means that is a switchable fill in blank question - // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10 - // means that is a normal fill blank question - // first we explode the "::" - $pre_array = explode('::', $answer); - // is switchable fill blank or not - $last = count($pre_array) - 1; - $is_set_switchable = explode('@', $pre_array[$last]); - $switchable_answer_set = false; - if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) { - $switchable_answer_set = true; - } - $answer = ''; - for ($k = 0; $k < $last; $k++) { - $answer .= $pre_array[$k]; - } - // splits weightings that are joined with a comma - $answerWeighting = explode(',', $is_set_switchable[0]); - - // we save the answer because it will be modified - //$temp = $answer; - $temp = $answer; - - $answer = ''; - $j = 0; - //initialise answer tags - $user_tags = $correct_tags = $real_text = array (); - // the loop will stop at the end of the text - while (1) { - // quits the loop if there are no more blanks (detect '[') - if (($pos = api_strpos($temp, '[')) === false) { - // adds the end of the text - $answer = $temp; - /* // Deprecated code - // TeX parsing - replacement of texcode tags - $texstring = api_parse_tex($texstring); - $answer = str_replace("{texcode}", $texstring, $answer); - */ - $real_text[] = $answer; - break; //no more "blanks", quit the loop - } - // adds the piece of text that is before the blank - //and ends with '[' into a general storage array - $real_text[] = api_substr($temp, 0, $pos +1); - $answer .= api_substr($temp, 0, $pos +1); - //take the string remaining (after the last "[" we found) - $temp = api_substr($temp, $pos +1); - // quit the loop if there are no more blanks, and update $pos to the position of next ']' - if (($pos = api_strpos($temp, ']')) === false) { - // adds the end of the text - $answer .= $temp; - break; - } - - $str = $user_answer; - - preg_match_all('#\[([^[]*)\]#', $str, $arr); - $str = str_replace('\r\n', '', $str); - $choice = $arr[1]; - - $tmp = api_strrpos($choice[$j],' / '); - $choice[$j] = api_substr($choice[$j],0,$tmp); - $choice[$j] = trim($choice[$j]); - - //Needed to let characters ' and " to work as part of an answer - $choice[$j] = stripslashes($choice[$j]); - - $user_tags[] = api_strtolower($choice[$j]); - //put the contents of the [] answer tag into correct_tags[] - $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos)); - $j++; - $temp = api_substr($temp, $pos +1); - } - - $answer = ''; - $real_correct_tags = $correct_tags; - $chosen_list = array(); - $good_answer = array(); - - for ($i = 0; $i < count($real_correct_tags); $i++) { - if (!$switchable_answer_set) { - //needed to parse ' and " characters - $user_tags[$i] = stripslashes($user_tags[$i]); - if ($correct_tags[$i] == $user_tags[$i]) { - $good_answer[$correct_tags[$i]] = 1; - } elseif (!empty ($user_tags[$i])) { - $good_answer[$correct_tags[$i]] = 0; - } else { - $good_answer[$correct_tags[$i]] = 0; - } - } else { - // switchable fill in the blanks - if (in_array($user_tags[$i], $correct_tags)) { - $correct_tags = array_diff($correct_tags, $chosen_list); - $good_answer[$correct_tags[$i]] = 1; - } elseif (!empty ($user_tags[$i])) { - $good_answer[$correct_tags[$i]] = 0; - } else { - $good_answer[$correct_tags[$i]] = 0; - } - } - // adds the correct word, followed by ] to close the blank - $answer .= ' / ' . $real_correct_tags[$i] . ']'; - if (isset ($real_text[$i +1])) { - $answer .= $real_text[$i +1]; - } - } - - return $good_answer; -} - -/** - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @return int - */ -function get_number_students_finish_exercise($exercise_id, $course_code, $session_id) -{ - $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - $sql = "SELECT DISTINCT exe_user_id - FROM $track_exercises e - INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) - WHERE - exe_exo_id = $exercise_id AND - course_code = '$course_code' AND - e.session_id = $session_id AND - status = ''"; - $result = Database::query($sql); - $return = 0; - if ($result) { - $return = Database::num_rows($result); - - } - return $return; -} - -/** - * @param string $in_name is the name and the id of the - */ -function displayGroupMenu($in_name, $in_default, $in_onchange = "") -{ - // check the default value of option - $tabSelected = array($in_default => " selected='selected' "); - $res = ""; - $res .= ""; - return $res; -} - - -/** - * Return a list of group for user with user_id=in_userid separated with in_separator - * @deprecated ? - */ -function displayGroupsForUser($in_separator, $in_userid) -{ - $res = implode($in_separator, GroupManager::get_user_group_name($in_userid)); - if ($res == "") { - $res = "
-
"; - } - return $res; -} - -function create_chat_exercise_session($exe_id) -{ - if (!isset($_SESSION['current_exercises'])) { - $_SESSION['current_exercises'] = array(); - } - $_SESSION['current_exercises'][$exe_id] = true; -} - -function delete_chat_exercise_session($exe_id) -{ - if (isset($_SESSION['current_exercises'])) { - $_SESSION['current_exercises'][$exe_id] = false; - } -} - -/** - * Display the exercise results - * @param Exercise $objExercise - * @param int $exe_id - * @param bool $save_user_result save users results (true) or just show the results (false) - */ -function display_question_list_by_attempt($objExercise, $exe_id, $save_user_result = false) -{ - global $origin; - - // Getting attempt info - $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id); - - // Getting question list - $question_list = array(); - if (!empty($exercise_stat_info['data_tracking'])) { - $question_list = explode(',', $exercise_stat_info['data_tracking']); - } else { - // Try getting the question list only if save result is off - if ($save_user_result == false) { - $question_list = $objExercise->get_validated_question_list(); - } - } - - $counter = 1; - $total_score = $total_weight = 0; - - $exercise_content = null; - - // Hide results - $show_results = false; - $show_only_score = false; - - if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) { - $show_results = true; - } - - if (in_array($objExercise->results_disabled, - array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES)) - ) { - $show_only_score = true; - } - - // Not display expected answer, but score, and feedback - $show_all_but_expected_answer = false; - if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY && - $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END - ) { - $show_all_but_expected_answer = true; - $show_results = true; - $show_only_score = false; - } - - if ($show_results || $show_only_score) { - $user_info = api_get_user_info($exercise_stat_info['exe_user_id']); - //Shows exercise header - echo $objExercise->show_exercise_result_header( - $user_info, - api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), - $exercise_stat_info['duration'] - ); - } - - // Display text when test is finished #4074 and for LP #4227 - $end_of_message = $objExercise->selectTextWhenFinished(); - if (!empty($end_of_message)) { - Display::display_normal_message($end_of_message, false); - echo "
 
"; - } - - $question_list_answers = array(); - $media_list = array(); - $category_list = array(); - - // Loop over all question to show results for each of them, one by one - if (!empty($question_list)) { - foreach ($question_list as $questionId) { - - // creates a temporary Question object - $objQuestionTmp = Question::read($questionId); - - // This variable came from exercise_submit_modal.php - ob_start(); - - // We're inside *one* question. Go through each possible answer for this question - $result = $objExercise->manage_answer( - $exercise_stat_info['exe_id'], - $questionId, - null, - 'exercise_result', - array(), - $save_user_result, - true, - $show_results, - $objExercise->selectPropagateNeg(), - array() - ); - - if (empty($result)) { - continue; - } - - // In case of global score, make sure the calculated total score is integer - /*if (!is_int($result['score'])) { - $result['score'] = round($result['score']); - }*/ - - $total_score += $result['score']; - $total_weight += $result['weight']; - - $question_list_answers[] = array( - 'question' => $result['open_question'], - 'answer' => $result['open_answer'], - 'answer_type' => $result['answer_type'] - ); - - $my_total_score = $result['score']; - $my_total_weight = $result['weight']; - - // Category report - $category_was_added_for_this_test = false; - - if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) { - $category_list[$objQuestionTmp->category]['score'] += $my_total_score; - $category_list[$objQuestionTmp->category]['total'] += $my_total_weight; - $category_was_added_for_this_test = true; - } - - if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) { - foreach($objQuestionTmp->category_list as $category_id) { - $category_list[$category_id]['score'] += $my_total_score; - $category_list[$category_id]['total'] += $my_total_weight; - $category_was_added_for_this_test = true; - } - } - - // No category for this question! - if ($category_was_added_for_this_test == false) { - if (!isset($category_list['none']['score'])) { - $category_list['none']['score'] = 0; - } - if (!isset($category_list['none']['total'])) { - $category_list['none']['total'] = 0; - } - - $category_list['none']['score'] += $my_total_score; - $category_list['none']['total'] += $my_total_weight; - } - - if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) { - $my_total_score = 0; - } - - $comnt = null; - if ($show_results) { - $comnt = get_comments($exe_id, $questionId); - if (!empty($comnt)) { - echo ''.get_lang('Feedback').''; - echo '
'.$comnt.'
'; - } - } - - if ($show_results) { - $score = array( - 'result' => get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, true), - 'pass' => $my_total_score >= $my_total_weight ? true : false, - 'score' => $my_total_score, - 'weight' => $my_total_weight, - 'comments' => $comnt, - ); - } else { - $score = array(); - } - - $contents = ob_get_clean(); - $question_content = '
'; - - if ($show_results) { - $show_media = false; - /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) { - $show_media = true; - $media_list[] = $objQuestionTmp->parent_id; - }*/ - //Shows question title an description - $question_content .= $objQuestionTmp->return_header(null, $counter, $score); - } - $counter++; - - $question_content .= $contents; - $question_content .= '
'; - - $exercise_content .= $question_content; - - } // end foreach() block that loops over all questions - } - - $total_score_text = null; - - if ($origin != 'learnpath') { - if ($show_results || $show_only_score) { - $total_score_text .= '
'; - $total_score_text .= get_question_ribbon($objExercise, $total_score, $total_weight, true); - $total_score_text .= '
'; - } - } - - if (!empty($category_list) && ($show_results || $show_only_score) ) { - //Adding total - $category_list['total'] = array('score' => $total_score, 'total' => $total_weight); - echo Testcategory::get_stats_table_by_attempt($objExercise->id, $category_list); - } - - if ($show_all_but_expected_answer) { - $exercise_content .= "
".get_lang("ExerciseWithFeedbackWithoutCorrectionComment")."
"; - } - // Remove audio auto play from questions on results page - refs BT#7939 - $exercise_content = preg_replace('/autoplay[\=\".+\"]+/','',$exercise_content); - - echo $total_score_text; - echo $exercise_content; - - if (!$show_only_score) { - echo $total_score_text; - } - - if ($save_user_result) { - - // Tracking of results - $learnpath_id = $exercise_stat_info['orig_lp_id']; - $learnpath_item_id = $exercise_stat_info['orig_lp_item_id']; - $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id']; - - if (api_is_allowed_to_session_edit()) { - update_event_exercice( - $exercise_stat_info['exe_id'], - $objExercise->selectId(), - $total_score, - $total_weight, - api_get_session_id(), - $learnpath_id, - $learnpath_item_id, - $learnpath_item_view_id, - $exercise_stat_info['exe_duration'], - $question_list, - '', - array() - ); - } - - // Send notification .. - if (!api_is_allowed_to_edit(null,true) && !apiIsExcludedUserType()) { - if (api_get_course_setting('email_alert_manager_on_new_quiz') == 1 ) { - $objExercise->send_mail_notification_for_exam($question_list_answers, $origin, $exe_id); - } - $objExercise->send_notification_for_open_questions($question_list_answers, $origin, $exe_id); - $objExercise->send_notification_for_oral_questions($question_list_answers, $origin, $exe_id); - } - } -} - -/** - * @param Exercise $objExercise - * @param float $score - * @param float $weight - * @param bool $check_pass_percentage - * @return string - */ -function get_question_ribbon($objExercise, $score, $weight, $check_pass_percentage = false) -{ - $ribbon = '
'; - if ($check_pass_percentage) { - $is_success = is_success_exercise_result( - $score, - $weight, - $objExercise->selectPassPercentage() - ); - // Color the final test score if pass_percentage activated - $ribbon_total_success_or_error = ""; - if (is_pass_pourcentage_enabled($objExercise->selectPassPercentage())) { - if ($is_success) { - $ribbon_total_success_or_error = ' ribbon-total-success'; - } else { - $ribbon_total_success_or_error = ' ribbon-total-error'; - } - } - $ribbon .= '
'; - } else { - $ribbon .= '
'; - } - $ribbon .= '

'.get_lang('YourTotalScore').": "; - $ribbon .= show_score($score, $weight, false, true); - $ribbon .= '

'; - $ribbon .= '
'; - if ($check_pass_percentage) { - $ribbon .= show_success_message( - $score, - $weight, - $objExercise->selectPassPercentage() - ); - } - $ribbon .= '
'; - - return $ribbon; -} - -/** - * @param int $countLetter - * @return mixed - */ -function detectInputAppropriateClass($countLetter) -{ - $limits = array( - 0 => 'input-mini', - 10 => 'input-mini', - 15 => 'input-medium', - 20 => 'input-xlarge', - 40 => 'input-xlarge', - 60 => 'input-xxlarge', - 100 => 'input-xxlarge', - 200 => 'input-xxlarge', - ); - - foreach ($limits as $size => $item) { - if ($countLetter <= $size) { - return $item; - } - } - return $limits[0]; -} diff --git a/main/exercice/exercise_reminder.php b/main/exercice/exercise_reminder.php index 34b2edb660..525936c836 100755 --- a/main/exercice/exercise_reminder.php +++ b/main/exercice/exercise_reminder.php @@ -36,7 +36,7 @@ if (!$objExercise) { } $time_control = false; -$clock_expired_time = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); +$clock_expired_time = ExerciseLib::get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); if ($objExercise->expired_time != 0 && !empty($clock_expired_time)) { $time_control = true; @@ -133,7 +133,7 @@ echo ''; -$attempt_list = get_all_exercise_event_by_exe_id($exe_id); +$attempt_list = Event::getAllExerciseEventByExeId($exe_id); $remind_list = $exercise_stat_info['questions_to_check']; $remind_list = explode(',', $remind_list); diff --git a/main/exercice/exercise_report.php b/main/exercice/exercise_report.php index c3143d22ce..0159f1cbd6 100755 --- a/main/exercice/exercise_report.php +++ b/main/exercice/exercise_report.php @@ -130,7 +130,7 @@ if (isset($_REQUEST['comments']) && $_REQUEST['comments'] == 'update' && ($is_allowedToEdit || $is_tutor) && $_GET['exeid'] == strval(intval($_GET['exeid']))) { $id = intval($_GET['exeid']); //filtered by post-condition - $track_exercise_info = get_exercise_track_exercise_info($id); + $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id); if (empty($track_exercise_info)) { api_not_allowed(); } diff --git a/main/exercice/exercise_result.php b/main/exercice/exercise_result.php index 8bc3a9eb29..6f97374fd6 100755 --- a/main/exercice/exercise_result.php +++ b/main/exercice/exercise_result.php @@ -110,7 +110,7 @@ $i = $total_score = $total_weight = 0; //We check if the user attempts before sending to the exercise_result.php if ($objExercise->selectAttempts() > 0) { - $attempt_count = get_attempt_count( + $attempt_count = Event::get_attempt_count( api_get_user_id(), $objExercise->id, $learnpath_id, @@ -133,21 +133,21 @@ if ($objExercise->selectAttempts() > 0) { Display :: display_normal_message(get_lang('Saved').'
',false); // Display and save questions -display_question_list_by_attempt($objExercise, $exe_id, true); +ExerciseLib::display_question_list_by_attempt($objExercise, $exe_id, true); //If is not valid /* -$session_control_key = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); -if (isset($session_control_key) && !exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) { +$session_control_key = ExerciseLib::get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); +if (isset($session_control_key) && !ExerciseLib::exercise_time_control_is_valid($objExercise->id, $learnpath_id, $learnpath_item_id)) { $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); $sql_fraud = "UPDATE $TBL_TRACK_ATTEMPT SET answer = 0, marks = 0, position = 0 WHERE exe_id = $exe_id "; Database::query($sql_fraud); }*/ //Unset session for clock time -exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id); -delete_chat_exercise_session($exe_id); +ExerciseLib::exercise_time_control_delete($objExercise->id, $learnpath_id, $learnpath_item_id); +ExerciseLib::delete_chat_exercise_session($exe_id); if ($origin != 'learnpath') { echo '
'; diff --git a/main/exercice/exercise_show.php b/main/exercice/exercise_show.php index 78ee744fd9..4fba205722 100755 --- a/main/exercice/exercise_show.php +++ b/main/exercice/exercise_show.php @@ -70,7 +70,7 @@ $maxEditors = isset($_configuration['exercise_max_fckeditors_in_page']) ? $_conf $is_allowedToEdit = api_is_allowed_to_edit(null, true) || $is_courseTutor || api_is_session_admin() || api_is_drh() || api_is_student_boss(); //Getting results from the exe_id. This variable also contain all the information about the exercise -$track_exercise_info = get_exercise_track_exercise_info($id); +$track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id); //No track info if (empty($track_exercise_info)) { @@ -527,7 +527,7 @@ foreach ($questionList as $questionId) { echo '
'; echo '
'; - $comnt = trim(get_comments($id, $questionId)); + $comnt = trim(Event::get_comments($id, $questionId)); if (empty($comnt)) { echo '
'; } else { @@ -542,7 +542,7 @@ foreach ($questionList as $questionId) { $renderer =& $feedback_form->defaultRenderer(); $renderer->setFormTemplate('
{content}
'); $renderer->setElementTemplate('
{element}
'); - $comnt = get_comments($id, $questionId); + $comnt = Event::get_comments($id, $questionId); $default = array('comments_'.$questionId => $comnt); if ($useAdvancedEditor) { $feedback_form->addElement( @@ -565,7 +565,7 @@ foreach ($questionList as $questionId) { echo '
'; } else { - $comnt = get_comments($id, $questionId); + $comnt = Event::get_comments($id, $questionId); echo '
'; if (!empty($comnt)) { echo ''.get_lang('Feedback').''; @@ -650,7 +650,7 @@ foreach ($questionList as $questionId) { $score = array(); if ($show_results) { - $score['result'] = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, false); + $score['result'] = get_lang('Score')." : ".ExerciseLib::show_score($my_total_score, $my_total_weight, false, false); $score['pass'] = $my_total_score >= $my_total_weight ? true : false; $score['type'] = $answerType; $score['score'] = $my_total_score; diff --git a/main/exercice/exercise_submit.php b/main/exercice/exercise_submit.php index 7b91d2e0df..240cb1843f 100755 --- a/main/exercice/exercise_submit.php +++ b/main/exercice/exercise_submit.php @@ -148,7 +148,7 @@ if ($objExercise->expired_time != 0) { } // Generating the time control key for the user -$current_expired_time_key = get_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); +$current_expired_time_key = ExerciseLib::get_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); $_SESSION['duration_time'][$current_expired_time_key] = $current_timestamp; @@ -161,7 +161,7 @@ $show_clock = true; $user_id = api_get_user_id(); if ($objExercise->selectAttempts() > 0) { $attempt_html = ''; - $attempt_count = get_attempt_count( + $attempt_count = Event::get_attempt_count( $user_id, $exerciseId, $learnpath_id, @@ -175,7 +175,7 @@ if ($objExercise->selectAttempts() > 0) { if ($objExercise->results_disabled == 0 && $origin != 'learnpath') { // Showing latest attempt according with task BT#1628 - $exercise_stat_info = get_exercise_results_by_user( + $exercise_stat_info = Event::getExerciseResultsByUser( $user_id, $exerciseId, api_get_course_id(), @@ -199,7 +199,7 @@ if ($objExercise->selectAttempts() > 0) { $attempt_html .= Display::div(get_lang('Score').' '.$marks, array('id'=>'question_score')); } } - $score = show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']); + $score = ExerciseLib::show_score($last_attempt_info['exe_result'], $last_attempt_info['exe_weighting']); $attempt_html .= Display::div(get_lang('YourTotalScore').' '.$score, array('id'=>'question_score')); } else { $attempt_html .= Display::return_message(sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()), 'warning', false); @@ -281,7 +281,7 @@ if (empty($exercise_stat_info)) { // Remember last question id position. $isFirstTime = Session::read('firstTime'); if ($isFirstTime && $objExercise->type == ONE_PER_PAGE) { - $resolvedQuestions = get_all_exercise_event_by_exe_id($exe_id); + $resolvedQuestions = Event::getAllExerciseEventByExeId($exe_id); if (!empty($resolvedQuestions) && !empty($exercise_stat_info['data_tracking']) ) { @@ -337,7 +337,7 @@ if ($time_control) { $expired_time_of_this_attempt = $exercise_stat_info['expired_time_control']; if ($debug) {error_log('7.5 $expired_time_of_this_attempt: '.$expired_time_of_this_attempt); } // Get the last attempt of an exercise - $last_attempt_date = get_last_attempt_date_of_exercise($exercise_stat_info['exe_id']); + $last_attempt_date = Event::getLastAttemptDateOfExercise($exercise_stat_info['exe_id']); /* This means that the user enters the exam but do not answer the first question we get the date from the track_e_exercises not from @@ -504,7 +504,7 @@ if ($formSent && isset($_POST)) { //We check if the user attempts before sending to the exercise_result.php if ($objExercise->selectAttempts() > 0) { - $attempt_count = get_attempt_count( + $attempt_count = Event::get_attempt_count( api_get_user_id(), $exerciseId, $learnpath_id, @@ -563,7 +563,7 @@ if ($question_count != 0) { //We check if the user attempts before sending to the exercise_result.php if ($objExercise->selectAttempts() > 0) { - $attempt_count = get_attempt_count( + $attempt_count = Event::get_attempt_count( api_get_user_id(), $exerciseId, $learnpath_id, @@ -1028,7 +1028,7 @@ if (!empty($error)) { $attempt_list = array(); if (isset($exe_id)) { - $attempt_list = get_all_exercise_event_by_exe_id($exe_id); + $attempt_list = Event::getAllExerciseEventByExeId($exe_id); } $remind_list = array(); @@ -1086,7 +1086,7 @@ if (!empty($error)) { echo '
'; // Shows the question and its answers - showQuestion($questionId, false, $origin, $i, true, false, $user_choice, false); + ExerciseLib::showQuestion($questionId, false, $origin, $i, true, false, $user_choice, false); // Button save and continue switch ($objExercise->type) { diff --git a/main/exercice/overview.php b/main/exercice/overview.php index ea88b17880..88c50f69e3 100755 --- a/main/exercice/overview.php +++ b/main/exercice/overview.php @@ -42,7 +42,7 @@ $interbreadcrumb[] = array("url" => "exercice.php?gradebook=$gradebook", "name" $interbreadcrumb[] = array("url" => "#", "name" => $objExercise->name); $time_control = false; -$clock_expired_time = get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); +$clock_expired_time = ExerciseLib::get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id); if ($objExercise->expired_time != 0 && !empty($clock_expired_time)) { $time_control = true; @@ -94,7 +94,7 @@ if (isset($_GET['preview'])) { $exercise_stat_info = $objExercise->get_stat_track_exercise_info($learnpath_id, $learnpath_item_id, 0); $attempt_list = null; if (isset($exercise_stat_info['exe_id'])) { - $attempt_list = get_all_exercise_event_by_exe_id($exercise_stat_info['exe_id']); + $attempt_list = Event::getAllExerciseEventByExeId($exercise_stat_info['exe_id']); } //1. Check if this is a new attempt or a previous @@ -130,7 +130,7 @@ if ($visible_return['value'] == false) { } } -$attempts = get_exercise_results_by_user( +$attempts = Event::getExerciseResultsByUser( api_get_user_id(), $objExercise->id, api_get_course_id(), @@ -160,7 +160,7 @@ if (!empty($attempts) && $visible_return['value'] == true) { $i = $counter; foreach ($attempts as $attempt_result) { - $score = show_score( + $score = ExerciseLib::show_score( $attempt_result['exe_result'], $attempt_result['exe_weighting'] ); diff --git a/main/exercice/question_list_admin.inc.php b/main/exercice/question_list_admin.inc.php index cfa0de831e..21d24bab88 100755 --- a/main/exercice/question_list_admin.inc.php +++ b/main/exercice/question_list_admin.inc.php @@ -247,7 +247,7 @@ if (!$inATest) { echo '
'; //echo get_lang('Level').': '.$objQuestionTmp->selectLevel(); echo '
'; - showQuestion($id, false, null, null, false, true, false, true, $objExercise->feedback_type, true); + ExerciseLib::showQuestion($id, false, null, null, false, true, false, true, $objExercise->feedback_type, true); echo '

'; echo '
'; echo '
'; diff --git a/main/exercice/question_pool.php b/main/exercice/question_pool.php index f02d3c6672..f49f782f36 100755 --- a/main/exercice/question_pool.php +++ b/main/exercice/question_pool.php @@ -337,7 +337,7 @@ echo Display::form_row(get_lang("QuestionCategory"), $selectCourseCategory); // Get exercise list for this course -$exercise_list = get_all_exercises_for_course_id( +$exercise_list = ExerciseLib::get_all_exercises_for_course_id( $course_info, $session_id, $selected_course, @@ -558,7 +558,7 @@ if ($exerciseId > 0) { } } - $exerciseList = get_all_exercises($course_item, $session_id); + $exerciseList = ExerciseLib::get_all_exercises($course_item, $session_id); if (!empty($exerciseList)) { foreach ($exerciseList as $exercise) { diff --git a/main/exercice/result.php b/main/exercice/result.php index d979047f43..1e0ce8e5b6 100755 --- a/main/exercice/result.php +++ b/main/exercice/result.php @@ -32,7 +32,7 @@ if (empty($id)) { $is_allowedToEdit = api_is_allowed_to_edit(null,true) || $is_courseTutor; //Getting results from the exe_id. This variable also contain all the information about the exercise -$track_exercise_info = get_exercise_track_exercise_info($id); +$track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id); //No track info if (empty($track_exercise_info)) { diff --git a/main/exercice/stats.php b/main/exercice/stats.php index 0d19ead5b2..883a823b0e 100755 --- a/main/exercice/stats.php +++ b/main/exercice/stats.php @@ -42,14 +42,14 @@ if (!empty($question_list)) { foreach ($question_list as $question_id) { $question_obj = Question::read($question_id); - $exercise_stats = get_student_stats_by_question( + $exercise_stats = ExerciseLib::get_student_stats_by_question( $question_id, $exercise_id, $courseCode, $sessionId ); - $count_users = get_number_students_question_with_answer_count( + $count_users = ExerciseLib::get_number_students_question_with_answer_count( $question_id, $exercise_id, $courseCode, @@ -111,7 +111,7 @@ if (!empty($question_list)) { $id = 0; foreach ($question_list as $question_id) { $question_obj = Question::read($question_id); - $exercise_stats = get_student_stats_by_question( + $exercise_stats = ExerciseLib::get_student_stats_by_question( $question_id, $exercise_id, $courseCode, @@ -148,7 +148,7 @@ if (!empty($question_list)) { $data[$id]['correct'] = '-'; - $count = get_number_students_answer_count( + $count = ExerciseLib::get_number_students_answer_count( $real_answer_id, $question_id, $exercise_id, @@ -188,7 +188,7 @@ if (!empty($question_list)) { $data[$id]['answer'] = $correct; $data[$id]['correct'] = $answer_info; - $count = get_number_students_answer_count( + $count = ExerciseLib::get_number_students_answer_count( $answer_id, $question_id, $exercise_id, @@ -212,7 +212,7 @@ if (!empty($question_list)) { $data[$id]['answer'] = $answer_info; $data[$id]['correct'] = '-'; - $count = get_number_students_answer_hotspot_count( + $count = ExerciseLib::get_number_students_answer_hotspot_count( $answer_id, $question_id, $exercise_id, @@ -234,7 +234,7 @@ if (!empty($question_list)) { $data[$id]['answer'] = $answer_info; $data[$id]['correct'] = $correct_answer; - $count = get_number_students_answer_count( + $count = ExerciseLib::get_number_students_answer_count( $real_answer_id, $question_id, $exercise_id, diff --git a/main/exercice/testcategory.class.php b/main/exercice/testcategory.class.php index 37e05bb300..5349f58be3 100755 --- a/main/exercice/testcategory.class.php +++ b/main/exercice/testcategory.class.php @@ -572,21 +572,21 @@ class Testcategory if (count($category_list) > 1) { foreach ($category_list as $category_id => $category_item) { $table->setCellContents($row, 0, $category_name_list[$category_id]); - $table->setCellContents($row, 1, show_score($category_item['score'], $category_item['total'], false)); - $table->setCellContents($row, 2, show_score($category_item['score'], $category_item['total'], true, false, true)); + $table->setCellContents($row, 1, ExerciseLib::show_score($category_item['score'], $category_item['total'], false)); + $table->setCellContents($row, 2, ExerciseLib::show_score($category_item['score'], $category_item['total'], true, false, true)); $row++; } if (!empty($none_category)) { $table->setCellContents($row, 0, get_lang('None')); - $table->setCellContents($row, 1, show_score($none_category['score'], $none_category['total'], false)); - $table->setCellContents($row, 2, show_score($none_category['score'], $none_category['total'], true, false, true)); + $table->setCellContents($row, 1, ExerciseLib::show_score($none_category['score'], $none_category['total'], false)); + $table->setCellContents($row, 2, ExerciseLib::show_score($none_category['score'], $none_category['total'], true, false, true)); $row++; } if (!empty($total)) { $table->setCellContents($row, 0, get_lang('Total')); - $table->setCellContents($row, 1, show_score($total['score'], $total['total'], false)); - $table->setCellContents($row, 2, show_score($total['score'], $total['total'], true, false, true)); + $table->setCellContents($row, 1, ExerciseLib::show_score($total['score'], $total['total'], false)); + $table->setCellContents($row, 2, ExerciseLib::show_score($total['score'], $total['total'], true, false, true)); } return $table->toHtml(); } diff --git a/main/forum/download.php b/main/forum/download.php index 8670e100ba..c62d874e45 100755 --- a/main/forum/download.php +++ b/main/forum/download.php @@ -56,7 +56,7 @@ $tbl_forum_post = Database::get_course_table(TABLE_FORUM_POST); $course_id = api_get_course_int_id(); // launch event -event_download($doc_url); +Event::event_download($doc_url); $sql = 'SELECT thread_id, forum_id,filename FROM '.$tbl_forum_post.' f diff --git a/main/forum/forumsearch.php b/main/forum/forumsearch.php index c4abea1080..98fa166af8 100755 --- a/main/forum/forumsearch.php +++ b/main/forum/forumsearch.php @@ -91,7 +91,7 @@ if ($origin == 'learnpath') { Display::display_introduction_section(TOOL_FORUM); // Tracking -event_access_tool(TOOL_FORUM); +Event::event_access_tool(TOOL_FORUM); // Forum search forum_search(); diff --git a/main/forum/index.php b/main/forum/index.php index d34b0c1bc8..223779f25b 100755 --- a/main/forum/index.php +++ b/main/forum/index.php @@ -131,7 +131,7 @@ $whatsnew_post_info = Session::read('whatsnew_post_info'); /* TRACKING */ -event_access_tool(TOOL_FORUM); +Event::event_access_tool(TOOL_FORUM); /* RETRIEVING ALL THE FORUM CATEGORIES AND FORUMS diff --git a/main/glossary/ajax_controller.class.php b/main/glossary/ajax_controller.class.php index 0b3c054936..259b6e1f47 100755 --- a/main/glossary/ajax_controller.class.php +++ b/main/glossary/ajax_controller.class.php @@ -18,16 +18,16 @@ use Header; /** * Ajax controller. Dispatch request and perform required action. - * + * * - delete one glossary entry * - delete all glossary entried in a course/session * - returns a glossary entry from its id - * + * * Usage: - * + * * $controller = AjaxController::instance(); * $controller->run(); - * + * * @author Laurent Opprecht for the Univesity of Genevas * @license /license.txt */ @@ -40,7 +40,7 @@ class AjaxController extends \AjaxController /** * Return the instance of the controller. - * + * * @return \Glossary\AjaxController */ public static function instance() @@ -53,12 +53,12 @@ class AjaxController extends \AjaxController } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { - event_access_tool(TOOL_GLOSSARY); - } + Event::event_access_tool(TOOL_GLOSSARY); + } public function is_allowed_to_edit() { diff --git a/main/glossary/controller.class.php b/main/glossary/controller.class.php index 94afd27c6d..b8631e10ab 100755 --- a/main/glossary/controller.class.php +++ b/main/glossary/controller.class.php @@ -21,17 +21,17 @@ use Javascript; /** * Controller for glossary. Dispatch request and peform required action. - * + * * - list glossary entries for course * - add/edit glossary entry * - change view from table to details - * + * * Usage: - * + * * $controller = Controller::instance(); * $controller->run(); - * - * @package chamilo.course_description + * + * @package chamilo.course_description * @author Christian Fasanando * @author Laurent Opprecht for the Univesity of Genevas * @license see /license.txt @@ -49,7 +49,7 @@ class Controller extends \Controller /** * Return the instance of the controller. - * + * * @return \Glossary\Controller */ public static function instance() @@ -62,9 +62,9 @@ class Controller extends \Controller } /** - * Action to perform. + * Action to perform. * Returns the request parameter. - * + * * @return string */ public function get_action() @@ -84,7 +84,7 @@ class Controller extends \Controller } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { @@ -100,15 +100,15 @@ class Controller extends \Controller $current_course_tool = TOOL_GLOSSARY; // Tracking - event_access_tool(TOOL_GLOSSARY); + Event::event_access_tool(TOOL_GLOSSARY); } /** * Returns a url for an action that the controller can process - * + * * @param string $action * @param array $params - * @return string + * @return string */ public function url($action = '', $params = array()) { @@ -136,8 +136,8 @@ class Controller extends \Controller /** * List course descriptions. - * - * @param array messages + * + * @param array messages */ public function index() { @@ -156,7 +156,7 @@ class Controller extends \Controller } /** - * Performs the edit action. + * Performs the edit action. */ public function edit() { @@ -226,7 +226,7 @@ class Controller extends \Controller /** * Performs the delete action. - * + * * @see AjaxController */ public function delete() @@ -288,10 +288,10 @@ class Controller extends \Controller /** * Render a template using data. Adds a few common parameters to the data array. - * + * * @see /main/template/default/course_description/ * @param string $template - * @param array $data + * @param array $data */ protected function render($template, $data) { diff --git a/main/glossary/index.php b/main/glossary/index.php index 52e8b20fb2..07ef37ab15 100755 --- a/main/glossary/index.php +++ b/main/glossary/index.php @@ -34,7 +34,7 @@ $(document).ready(function () { $tool = TOOL_GLOSSARY; // Tracking -event_access_tool(TOOL_GLOSSARY); +Event::event_access_tool(TOOL_GLOSSARY); function sorter($item1, $item2) { if ($item1[2] == $item2[2]) diff --git a/main/gradebook/lib/be/category.class.php b/main/gradebook/lib/be/category.class.php index 93a0bca64b..db939d8fbb 100755 --- a/main/gradebook/lib/be/category.class.php +++ b/main/gradebook/lib/be/category.class.php @@ -1600,7 +1600,7 @@ class Category implements GradebookItem if ($locked == 1) { $event_type = LOG_GRADEBOOK_LOCKED; } - event_system($event_type, LOG_GRADEBOOK_ID, $this->id); + Event::addEvent($event_type, LOG_GRADEBOOK_ID, $this->id); } } diff --git a/main/inc/ajax/course.ajax.php b/main/inc/ajax/course.ajax.php index 0201abbd38..48bf786475 100755 --- a/main/inc/ajax/course.ajax.php +++ b/main/inc/ajax/course.ajax.php @@ -180,7 +180,7 @@ switch ($action) { if (api_is_platform_admin()) { $course = api_get_course_info_by_id($_GET['course_id']); $session_id = (!empty($_GET['session_id'])) ? intval($_GET['session_id']) : 0 ; - $exercises = get_all_exercises($course, $session_id, false, $_GET['q'], true, 3); + $exercises = ExerciseLib::get_all_exercises($course, $session_id, false, $_GET['q'], true, 3); foreach ($exercises as $exercise) { $data[] = array('id' => $exercise['id'], 'text' => html_entity_decode($exercise['title']) ); diff --git a/main/inc/ajax/events.ajax.php b/main/inc/ajax/events.ajax.php index 8a8da8687d..d6ff5454d5 100755 --- a/main/inc/ajax/events.ajax.php +++ b/main/inc/ajax/events.ajax.php @@ -10,7 +10,7 @@ api_protect_admin_script(); switch ($action) { case 'getEventTypes': - $events = get_all_event_types(); + $events = Event::get_all_event_types(); print json_encode($events); break; case 'getUsers': @@ -18,7 +18,7 @@ switch ($action) { print json_encode($users); break; case 'get_event_users': - $users = get_event_users($event_name); + $users = Event::get_event_users($event_name); print json_encode($users); break; } diff --git a/main/inc/ajax/exercise.ajax.php b/main/inc/ajax/exercise.ajax.php index 4648961606..b3ea6a1817 100755 --- a/main/inc/ajax/exercise.ajax.php +++ b/main/inc/ajax/exercise.ajax.php @@ -290,7 +290,7 @@ switch ($action) { $total_score = $exercise_stat_info['exe_result']; //Getting the list of attempts - $attempt_list = get_all_exercise_event_by_exe_id($exe_id); + $attempt_list = Event::getAllExerciseEventByExeId($exe_id); } // Updating Reminder algorythm. @@ -399,9 +399,9 @@ switch ($action) { if ($debug) { error_log("delete_attempt exe_id : $exe_id, my_question_id: $my_question_id"); } - delete_attempt($exe_id, api_get_user_id(), $course_code, $session_id, $my_question_id); + Event::delete_attempt($exe_id, api_get_user_id(), $course_code, $session_id, $my_question_id); if ($objQuestionTmp->type == HOT_SPOT) { - delete_attempt_hotspot($exe_id, api_get_user_id(), $course_code, $session_id, $my_question_id); + Event::delete_attempt_hotspot($exe_id, api_get_user_id(), $course_code, $session_id, $my_question_id); } if (isset($attempt_list[$my_question_id]) && isset($attempt_list[$my_question_id]['marks'])) { @@ -438,7 +438,7 @@ switch ($action) { $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id); } - $key = get_time_control_key($exercise_id, $exercise_stat_info['orig_lp_id'], $exercise_stat_info['orig_lp_item_id']); + $key = ExerciseLib::get_time_control_key($exercise_id, $exercise_stat_info['orig_lp_id'], $exercise_stat_info['orig_lp_item_id']); if (isset($_SESSION['duration_time'][$key]) && !empty($_SESSION['duration_time'][$key])) { $duration = $now - $_SESSION['duration_time'][$key]; @@ -454,7 +454,7 @@ switch ($action) { $_SESSION['duration_time'][$key] = time(); - update_event_exercice( + Event::update_event_exercice( $exe_id, $objExercise->selectId(), $total_score, diff --git a/main/inc/ajax/model.ajax.php b/main/inc/ajax/model.ajax.php index 00b1825fb4..85eae006d2 100755 --- a/main/inc/ajax/model.ajax.php +++ b/main/inc/ajax/model.ajax.php @@ -280,11 +280,11 @@ switch ($action) { $filter_user = intval($_GET['filter_by_user']); $whereCondition .= " AND te.exe_user_id = '$filter_user'"; } - $count = get_count_exam_results($exercise_id, $whereCondition); + $count = ExerciseLib::get_count_exam_results($exercise_id, $whereCondition); break; case 'get_hotpotatoes_exercise_results': $hotpot_path = $_REQUEST['path']; - $count = get_count_exam_hotpotatoes_results($hotpot_path); + $count = ExerciseLib::get_count_exam_hotpotatoes_results($hotpot_path); break; case 'get_sessions_tracking': $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : null; @@ -654,7 +654,7 @@ switch ($action) { break; case 'get_exercise_results': $course = api_get_course_info(); - // Used inside get_exam_results_data() + // Used inside ExerciseLib::get_exam_results_data() $documentPath = api_get_path(SYS_COURSE_PATH) . $course['path'] . "/document"; if ($is_allowedToEdit || api_is_student_boss()) { $columns = array( @@ -665,7 +665,7 @@ switch ($action) { $columns = array_merge(array('official_code'), $columns); } } - $result = get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $whereCondition); + $result = ExerciseLib::get_exam_results_data($start, $limit, $sidx, $sord, $exercise_id, $whereCondition); break; case 'get_hotpotatoes_exercise_results': $course = api_get_course_info(); @@ -675,7 +675,7 @@ switch ($action) { } else { $columns = array('exe_date', 'score', 'actions'); } - $result = get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $whereCondition); + $result = ExerciseLib::get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $whereCondition); break; case 'get_work_student_list_overview': if (!(api_is_allowed_to_edit() || api_is_coach())) { @@ -706,7 +706,7 @@ switch ($action) { } else { $columns = array('exe_date', 'score', 'actions'); } - $result = get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $whereCondition); + $result = ExerciseLib::get_exam_results_hotpotatoes_data($start, $limit, $sidx, $sord, $hotpot_path, $whereCondition); break; case 'get_sessions_tracking': if (api_is_drh()) { diff --git a/main/inc/ajax/user_manager.ajax.php b/main/inc/ajax/user_manager.ajax.php index 1c82b160db..7bdb33a23c 100755 --- a/main/inc/ajax/user_manager.ajax.php +++ b/main/inc/ajax/user_manager.ajax.php @@ -112,9 +112,9 @@ switch ($action) { null, $additionalParameters ); - event_system(LOG_USER_ENABLE, LOG_USER_ID, $user_id); + Event::addEvent(LOG_USER_ENABLE, LOG_USER_ID, $user_id); } else { - event_system(LOG_USER_DISABLE, LOG_USER_ID, $user_id); + Event::addEvent(LOG_USER_DISABLE, LOG_USER_ID, $user_id); } echo $status; } diff --git a/main/inc/global.inc.php b/main/inc/global.inc.php index 92881b805b..67b13cfacf 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -102,14 +102,12 @@ require_once dirname(__FILE__).'/../../vendor/autoload.php'; require_once $lib_path.'database.lib.php'; require_once $lib_path.'text.lib.php'; require_once $lib_path.'array.lib.php'; -require_once $lib_path.'events.lib.inc.php'; require_once $lib_path.'course.lib.php'; require_once $lib_path.'online.inc.php'; require_once $lib_path.'banner.lib.php'; require_once $lib_path.'fileManage.lib.php'; require_once $lib_path.'fileUpload.lib.php'; require_once $lib_path.'fileDisplay.lib.php'; -require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php'; require_once $lib_path.'course_category.lib.php'; define('_MPDF_TEMP_PATH', api_get_path(SYS_ARCHIVE_PATH).'mpdf/'); @@ -622,7 +620,7 @@ if (!isset($_SESSION['login_as']) && isset($_user)) { if ($res_logout_date < time() - $_configuration['session_lifetime']) { // it isn't, we should create a fresh entry - event_login(); + Event::event_login(); // now that it's created, we can get its ID and carry on $q_last_connection = Database::query($sql_last_connection); $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id'); diff --git a/main/inc/lib/add_course.lib.inc.php b/main/inc/lib/add_course.lib.inc.php index 88a195be54..c116600342 100755 --- a/main/inc/lib/add_course.lib.inc.php +++ b/main/inc/lib/add_course.lib.inc.php @@ -3168,7 +3168,7 @@ class AddCourse // Add event to the system log. $user_id = api_get_user_id(); - event_system( + Event::addEvent( LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, diff --git a/main/inc/lib/career.lib.php b/main/inc/lib/career.lib.php index d9f4a37793..d7a665dffb 100755 --- a/main/inc/lib/career.lib.php +++ b/main/inc/lib/career.lib.php @@ -213,7 +213,7 @@ class Career extends Model { $id = parent::save($params); if (!empty($id)) { - event_system(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_CAREER_CREATE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id()); } return $id; @@ -226,6 +226,6 @@ class Career extends Model public function delete($id) { parent::delete($id); - event_system(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_CAREER_DELETE, LOG_CAREER_ID, $id, api_get_utc_datetime(), api_get_user_id()); } } diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 0778e1f7d7..d545e35a76 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -464,7 +464,7 @@ class CourseManager // add event to system log $user_id = api_get_user_id(); - event_system( + Event::addEvent( LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_COURSE_CODE, $course_code, @@ -474,7 +474,7 @@ class CourseManager foreach ($user_list as $userId) { $userInfo = api_get_user_info($userId); - event_system( + Event::addEvent( LOG_UNSUBSCRIBE_USER_FROM_COURSE, LOG_USER_OBJECT, $userInfo, @@ -592,7 +592,7 @@ class CourseManager $result = @Database::query($sql); // Add event to the system log - event_system( + Event::addEvent( LOG_SUBSCRIBE_USER_TO_COURSE, LOG_COURSE_CODE, $course_code, @@ -601,7 +601,7 @@ class CourseManager ); $user_info = api_get_user_info($user_id); - event_system( + Event::addEvent( LOG_SUBSCRIBE_USER_TO_COURSE, LOG_USER_OBJECT, $user_info, @@ -2405,7 +2405,7 @@ class CourseManager // Add event to system log $user_id = api_get_user_id(); - event_system( + Event::addEvent( LOG_COURSE_DELETE, LOG_COURSE_CODE, $code, diff --git a/main/inc/lib/events.lib.inc.php b/main/inc/lib/events.lib.inc.php index a89d570cb0..1bac520e10 100755 --- a/main/inc/lib/events.lib.inc.php +++ b/main/inc/lib/events.lib.inc.php @@ -1,56 +1,43 @@ - * @desc Record information for open event (when homepage is opened) + * Class Event + * Functions of this library are used to record informations when some kind + * of event occur. Each event has his own types of informations then each event + * use its own function. */ -function event_open() +class Event { - global $_configuration; - global $TABLETRACK_OPEN; - - // @getHostByAddr($_SERVER['REMOTE_ADDR']) : will provide host and country information - // $_SERVER['HTTP_USER_AGENT'] : will provide browser and os information - // $_SERVER['HTTP_REFERER'] : provide information about refering url - if (isset($_SERVER['HTT_REFERER'])) { - $referer = Database::escape_string($_SERVER['HTTP_REFERER']); - } else { - $referer = ''; - } - // record informations only if user comes from another site - //if(!eregi($_configuration['root_web'],$referer)) - $pos = strpos($referer, $_configuration['root_web']); - if ($pos === false && $referer != '') { - $ip = api_get_real_ip(); - $remhost = @ getHostByAddr($ip); - if ($remhost == $ip) - $remhost = "Unknown"; // don't change this - $reallyNow = api_get_utc_datetime(); - $sql = "INSERT INTO ".$TABLETRACK_OPEN." + /** + * @author Sebastien Piraux + * @desc Record information for open event (when homepage is opened) + */ + public static function event_open() + { + global $_configuration; + global $TABLETRACK_OPEN; + + // @getHostByAddr($_SERVER['REMOTE_ADDR']) : will provide host and country information + // $_SERVER['HTTP_USER_AGENT'] : will provide browser and os information + // $_SERVER['HTTP_REFERER'] : provide information about refering url + if (isset($_SERVER['HTT_REFERER'])) { + $referer = Database::escape_string($_SERVER['HTTP_REFERER']); + } else { + $referer = ''; + } + // record informations only if user comes from another site + //if(!eregi($_configuration['root_web'],$referer)) + $pos = strpos($referer, $_configuration['root_web']); + if ($pos === false && $referer != '') { + $ip = api_get_real_ip(); + $remhost = @ getHostByAddr($ip); + if ($remhost == $ip) + $remhost = "Unknown"; // don't change this + $reallyNow = api_get_utc_datetime(); + $sql = "INSERT INTO ".$TABLETRACK_OPEN." (open_remote_host, open_agent, open_referer, @@ -58,291 +45,326 @@ function event_open() VALUES ('".$remhost."', '".Database::escape_string($_SERVER['HTTP_USER_AGENT'])."', '".Database::escape_string($referer)."', '$reallyNow')"; - $res = Database::query($sql); + $res = Database::query($sql); + } + return 1; } - return 1; -} -/** - * @author Sebastien Piraux - * @desc Record information for login event - * (when an user identifies himself with username & password) - */ -function event_login() -{ - global $TABLETRACK_LOGIN; - global $_user; - // @todo use api_get_user_info(); - //$userInfo = api_get_user_info(); - $userInfo = $_user; - if (empty($userInfo)) { - return false; - } + /** + * @author Sebastien Piraux old code + * @author Julio Montoya 2013 + * @desc Record information for login event when an user identifies himself with username & password + */ + public static function event_login() + { + $userInfo = api_get_user_info(); + if (empty($userInfo)) { + return false; + } - $userId = api_get_user_id(); - - $reallyNow = api_get_utc_datetime(); - $sql = "INSERT INTO ".$TABLETRACK_LOGIN." (login_user_id, login_ip, login_date, logout_date) VALUES - ('".$userId."', - '".Database::escape_string(api_get_real_ip())."', - '".$reallyNow."', - '".$reallyNow."' - )"; - Database::query($sql); - - // Auto subscribe - $user_status = $userInfo['status'] == SESSIONADMIN ? 'sessionadmin' : - $userInfo['status'] == COURSEMANAGER ? 'teacher' : - $userInfo['status'] == DRH ? 'DRH' : 'student'; - $autoSubscribe = api_get_setting($user_status.'_autosubscribe'); - if ($autoSubscribe) { - $autoSubscribe = explode('|', $autoSubscribe); - foreach ($autoSubscribe as $code) { - if (CourseManager::course_exists($code)) { - CourseManager::subscribe_user($userId, $code); + $userId = api_get_user_id(); + + $TABLETRACK_LOGIN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN); + + $reallyNow = api_get_utc_datetime(); + + $sql = "INSERT INTO ".$TABLETRACK_LOGIN." (login_user_id, login_ip, login_date, logout_date) VALUES + ('".$userId."', + '".Database::escape_string(api_get_real_ip())."', + '".$reallyNow."', + '".$reallyNow."' + )"; + Database::query($sql); + + // Auto subscribe + $user_status = $userInfo['status'] == SESSIONADMIN ? 'sessionadmin' : + $userInfo['status'] == COURSEMANAGER ? 'teacher' : + $userInfo['status'] == DRH ? 'DRH' : 'student'; + $autoSubscribe = api_get_setting($user_status.'_autosubscribe'); + if ($autoSubscribe) { + $autoSubscribe = explode('|', $autoSubscribe); + foreach ($autoSubscribe as $code) { + if (CourseManager::course_exists($code)) { + CourseManager::subscribe_user($userId, $code); + } } } } -} -/** - * @author Sebastien Piraux - * @desc Record information for access event for courses - */ -function event_access_course() { - global $TABLETRACK_ACCESS, $TABLETRACK_LASTACCESS; - - $id_session = api_get_session_id(); - $now = api_get_utc_datetime(); - $_cid = api_get_course_id(); - $user_id = api_get_user_id(); - - if ($user_id) { - $user_id = "'".$user_id."'"; - } else { - $user_id = "0"; // no one - } - $sql = "INSERT INTO ".$TABLETRACK_ACCESS." (access_user_id, access_cours_code, access_date, access_session_id) VALUES - (".$user_id.", '".$_cid."', '".$now."','".$id_session."')"; - Database::query($sql); - - // added for "what's new" notification - $sql = "UPDATE $TABLETRACK_LASTACCESS SET access_date = '$now' - WHERE access_user_id = $user_id AND access_cours_code = '$_cid' AND access_tool IS NULL AND access_session_id=".$id_session; - Database::query($sql); - - if (Database::affected_rows() == 0) { - $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, access_cours_code, access_date, access_session_id) - VALUES (".$user_id.", '".$_cid."', '$now', '".$id_session."')"; + /** + * @param tool name of the tool (name in mainDb.accueil table) + * @author Sebastien Piraux + * @desc Record information for access event for courses + */ + public static function accessCourse() + { + $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS); + //for "what's new" notification + $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); + + $id_session = api_get_session_id(); + $now = api_get_utc_datetime(); + $courseId = api_get_course_int_id(); + $user_id = api_get_user_id(); + + if ($user_id) { + $user_id = "'".$user_id."'"; + } else { + $user_id = "0"; // no one + } + $sql = "INSERT INTO ".$TABLETRACK_ACCESS." (access_user_id, c_id, access_date, access_session_id) VALUES + (".$user_id.", '".$courseId."', '".$now."','".$id_session."')"; Database::query($sql); + + // added for "what's new" notification + $sql = "UPDATE $TABLETRACK_LASTACCESS SET access_date = '$now' + WHERE access_user_id = $user_id AND c_id = '$courseId' AND access_tool IS NULL AND access_session_id=".$id_session; + $result = Database::query($sql); + + if (Database::affected_rows($result) == 0) { + $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_date, access_session_id) + VALUES (".$user_id.", '".$courseId."', '$now', '".$id_session."')"; + Database::query($sql); + } + + return 1; } - // end "what's new" notification - return 1; -} -/** - * @param string $tool tool name of the tool (name in mainDb.accueil table) - * @author Sebastien Piraux - * @desc Record information for access event for tools - * - * $tool can take this values : - * Links, Calendar, Document, Announcements, - * Group, Video, Works, Users, Exercices, Course Desc - * ... - * Values can be added if new modules are created (15char max) - * I encourage to use $nameTool as $tool when calling this function - * - * Functionality for "what's new" notification is added by Toon Van Hoecke - */ -function event_access_tool($tool, $id_session = 0) -{ - global $_configuration; - global $_cid; - global $TABLETRACK_ACCESS; - global $_course; - global $TABLETRACK_LASTACCESS; //for "what's new" notification - - $id_session = api_get_session_id(); - $tool = Database::escape_string($tool); - $reallyNow = api_get_utc_datetime(); - $user_id = api_get_user_id(); - // record information - // only if user comes from the course $_cid - //if( eregi($_configuration['root_web'].$_cid,$_SERVER['HTTP_REFERER'] ) ) - //$pos = strpos($_SERVER['HTTP_REFERER'],$_configuration['root_web'].$_cid); - $coursePath = isset($_course['path']) ? $_course['path'] : null; - - $pos = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower(api_get_path(WEB_COURSE_PATH).$coursePath)) : false; - // added for "what's new" notification - $pos2 = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower($_configuration['root_web']."index")) : false; - // end "what's new" notification - if ($pos !== false || $pos2 !== false) { - $sql = "INSERT INTO ".$TABLETRACK_ACCESS." - (access_user_id, - access_cours_code, - access_tool, - access_date, - access_session_id - ) - VALUES - (".$user_id.",".// Don't add ' ' around value, it's already done. - "'".$_cid."' , - '".$tool."', - '".$reallyNow."', - '".$id_session."')"; - Database::query($sql); + /** + * @param tool name of the tool (name in mainDb.accueil table) + * @author Sebastien Piraux + * @desc Record information for access event for tools + * + * $tool can take this values : + * Links, Calendar, Document, Announcements, + * Group, Video, Works, Users, Exercices, Course Desc + * ... + * Values can be added if new modules are created (15char max) + * I encourage to use $nameTool as $tool when calling this function + * + * Functionality for "what's new" notification is added by Toon Van Hoecke + */ + public static function event_access_tool($tool, $id_session = 0) + { + $TABLETRACK_ACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS); + $TABLETRACK_LASTACCESS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS); //for "what's new" notification + + $_course = api_get_course_info(); + $courseId = api_get_course_int_id(); + $id_session = api_get_session_id(); + $tool = Database::escape_string($tool); + $reallyNow = api_get_utc_datetime(); + $user_id = api_get_user_id(); + + // record information + // only if user comes from the course $_cid + //if( eregi($_configuration['root_web'].$_cid,$_SERVER['HTTP_REFERER'] ) ) + //$pos = strpos($_SERVER['HTTP_REFERER'],$_configuration['root_web'].$_cid); + $coursePath = isset($_course['path']) ? $_course['path'] : null; + + $pos = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower(api_get_path(WEB_COURSE_PATH).$coursePath)) : false; + // added for "what's new" notification + $pos2 = isset($_SERVER['HTTP_REFERER']) ? strpos(strtolower($_SERVER['HTTP_REFERER']), strtolower(api_get_path(WEB_PATH)."index")) : false; + // end "what's new" notification + if ($pos !== false || $pos2 !== false) { + $sql = "INSERT INTO ".$TABLETRACK_ACCESS." + (access_user_id, + c_id, + access_tool, + access_date, + access_session_id + ) + VALUES + (".$user_id.",".// Don't add ' ' around value, it's already done. + "'".$courseId."' , + '".$tool."', + '".$reallyNow."', + '".$id_session."')"; + Database::query($sql); + } + // "what's new" notification + $sql = "UPDATE $TABLETRACK_LASTACCESS + SET access_date = '$reallyNow' + WHERE access_user_id = ".$user_id." AND c_id = '".$courseId."' AND access_tool = '".$tool."' AND access_session_id=".$id_session; + $result = Database::query($sql); + if (Database::affected_rows($result) == 0) { + $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id, c_id, access_tool, access_date, access_session_id) + VALUES (".$user_id.", '".$courseId."' , '$tool', '$reallyNow', $id_session)"; + Database::query($sql); + } + return 1; } - // "what's new" notification - $sql = "UPDATE $TABLETRACK_LASTACCESS - SET access_date = '$reallyNow' - WHERE access_user_id = ".$user_id." AND access_cours_code = '".$_cid."' AND access_tool = '".$tool."' AND access_session_id=".$id_session; - Database::query($sql); - if (Database::affected_rows() == 0) { - $sql = "INSERT INTO $TABLETRACK_LASTACCESS (access_user_id,access_cours_code,access_tool, access_date, access_session_id) - VALUES (".$user_id.", '".$_cid."' , '$tool', '$reallyNow', $id_session)"; + + /** + * @param doc_id id of document (id in mainDb.document table) + * @author Sebastien Piraux + * @desc Record information for download event + * (when an user click to d/l a document) + * it will be used in a redirection page + * bug fixed: Roan Embrechts + * Roan: + * The user id is put in single quotes, + * (why? perhaps to prevent sql insertion hacks?) + * and later again. + * Doing this twice causes an error, I remove one of them. + */ + public static function event_download($doc_url) + { + $tbl_stats_downloads = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS); + $doc_url = Database::escape_string($doc_url); + + $reallyNow = api_get_utc_datetime(); + $user_id = "'".api_get_user_id()."'"; + $_cid = api_get_course_int_id(); + + $sql = "INSERT INTO $tbl_stats_downloads ( + down_user_id, + c_id, + down_doc_path, + down_date, + down_session_id + ) + VALUES ( + ".$user_id.", + '".$_cid."', + '".$doc_url."', + '".$reallyNow."', + '".api_get_session_id()."' + )"; Database::query($sql); + return 1; } - return 1; -} -/** - * @param doc_id id of document (id in mainDb.document table) - * @author Sebastien Piraux - * @desc Record information for download event - * (when an user click to d/l a document) - * it will be used in a redirection page - * bug fixed: Roan Embrechts - * Roan: - * The user id is put in single quotes, - * (why? perhaps to prevent sql insertion hacks?) - * and later again. - * Doing this twice causes an error, I remove one of them. - */ -function event_download($doc_url) -{ - $tbl_stats_downloads = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS); - $doc_url = Database::escape_string($doc_url); - - $reallyNow = api_get_utc_datetime(); - $user_id = "'".api_get_user_id()."'"; - $_cid = api_get_course_id(); - - $sql = "INSERT INTO $tbl_stats_downloads ( - down_user_id, - down_cours_id, - down_doc_path, - down_date, - down_session_id - ) - VALUES ( - ".$user_id.", - '".$_cid."', - '".$doc_url."', - '".$reallyNow."', - '".api_get_session_id()."' - )"; - Database::query($sql); - return 1; -} + /** + * @param doc_id id of document (id in mainDb.document table) + * @author Sebastien Piraux + * @desc Record information for upload event + * used in the works tool to record informations when + * an user upload 1 work + */ + public static function event_upload($doc_id) + { + $TABLETRACK_UPLOADS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS); + $courseCode = api_get_course_id(); + $reallyNow = api_get_utc_datetime(); + $user_id = api_get_user_id(); -/** - * @param link_id (id in coursDb liens table) - * @author Sebastien Piraux - * @desc Record information for link event (when an user click on an added link) - * it will be used in a redirection page -*/ -function event_link($link_id) -{ - global $TABLETRACK_LINKS; - $reallyNow = api_get_utc_datetime(); - $user_id = api_get_user_id(); - $sql = "INSERT INTO ".$TABLETRACK_LINKS." - ( links_user_id, - links_cours_id, - links_link_id, - links_date, - links_session_id - ) VALUES ( - ".$user_id.", - '".api_get_course_id()."', - '".Database::escape_string($link_id)."', - '".$reallyNow."', - '".api_get_session_id()."' - )"; - Database::query($sql); - return 1; -} + $sql = "INSERT INTO ".$TABLETRACK_UPLOADS." + ( upload_user_id, + upload_cours_id, + upload_work_id, + upload_date, + upload_session_id + ) + VALUES ( + ".$user_id.", + '".$courseCode."', + '".$doc_id."', + '".$reallyNow."', + '".api_get_session_id()."' + )"; + Database::query($sql); + return 1; + } -/** - * Update the TRACK_E_EXERCICES exercises - * - * @param int exeid id of the attempt - * @param int exo_id exercise id - * @param mixed result score - * @param int weighting ( higher score ) - * @param int duration ( duration of the attempt in seconds ) - * @param int session_id - * @param int learnpath_id (id of the learnpath) - * @param int learnpath_item_id (id of the learnpath_item) - * - * @author Sebastien Piraux - * @author Julio Montoya Armas Reworked 2010 - * @desc Record result of user when an exercice was done -*/ -function update_event_exercice( - $exeid, - $exo_id, - $score, - $weighting, - $session_id, - $learnpath_id = 0, - $learnpath_item_id = 0, - $learnpath_item_view_id = 0, - $duration = 0, - $question_list = array(), - $status = '', - $remind_list = array(), - $end_date = null -) { - global $debug; - - if ($debug) error_log('Called to update_event_exercice'); - if ($debug) error_log('duration:' . $duration); - - if ($exeid != '') { - /* - * Code commented due BT#8423 do not change the score to 0. - * - * Validation in case of fraud with actived control time - if (!exercise_time_control_is_valid($exo_id, $learnpath_id, $learnpath_item_id)) { - $score = 0; - } - */ - if (!isset($status) || empty($status)) { - $status = ''; - } else { - $status = Database::escape_string($status); - } + /** + * @param link_id (id in coursDb liens table) + * @author Sebastien Piraux + * @desc Record information for link event (when an user click on an added link) + * it will be used in a redirection page + */ + public static function event_link($link_id) + { + $TABLETRACK_LINKS = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LINKS); + $reallyNow = api_get_utc_datetime(); + $user_id = api_get_user_id(); + $sql = "INSERT INTO ".$TABLETRACK_LINKS." + ( links_user_id, + c_id, + links_link_id, + links_date, + links_session_id + ) VALUES ( + ".$user_id.", + '".api_get_course_int_id()."', + '".Database::escape_string($link_id)."', + '".$reallyNow."', + '".api_get_session_id()."' + )"; + Database::query($sql); + return 1; + } - $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + /** + * Update the TRACK_E_EXERCICES exercises + * + * @param int exeid id of the attempt + * @param int exo_id exercise id + * @param mixed result score + * @param int weighting ( higher score ) + * @param int duration ( duration of the attempt in seconds ) + * @param int session_id + * @param int learnpath_id (id of the learnpath) + * @param int learnpath_item_id (id of the learnpath_item) + * + * @author Sebastien Piraux + * @author Julio Montoya Armas Reworked 2010 + * @desc Record result of user when an exercice was done + */ + public static function update_event_exercice( + $exeid, + $exo_id, + $score, + $weighting, + $session_id, + $learnpath_id = 0, + $learnpath_item_id = 0, + $learnpath_item_view_id = 0, + $duration = 0, + $question_list = array(), + $status = '', + $remind_list = array(), + $end_date = null + ) { + global $debug; + + if ($debug) error_log('Called to update_event_exercice'); + if ($debug) error_log('duration:' . $duration); + + if ($exeid != '') { + /* + * Code commented due BT#8423 do not change the score to 0. + * + * Validation in case of fraud with actived control time + if (!ExerciseLib::exercise_time_control_is_valid($exo_id, $learnpath_id, $learnpath_item_id)) { + $score = 0; + } + */ + if (!isset($status) || empty($status)) { + $status = ''; + } else { + $status = Database::escape_string($status); + } - if (!empty($question_list)) { - $question_list = array_map('intval', $question_list); - } + $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - if (!empty($remind_list)) { - $remind_list = array_map('intval', $remind_list); - $remind_list = array_filter($remind_list); - $remind_list = implode(",", $remind_list); - } else { - $remind_list = ''; - } + if (!empty($question_list)) { + $question_list = array_map('intval', $question_list); + } - if (empty($end_date)) { - $end_date = api_get_utc_datetime(); - } + if (!empty($remind_list)) { + $remind_list = array_map('intval', $remind_list); + $remind_list = array_filter($remind_list); + $remind_list = implode(",", $remind_list); + } else { + $remind_list = ''; + } - $sql = "UPDATE $TABLETRACK_EXERCICES SET + if (empty($end_date)) { + $end_date = api_get_utc_datetime(); + } + + $sql = "UPDATE $TABLETRACK_EXERCICES SET exe_exo_id = '".Database::escape_string($exo_id)."', exe_result = '".Database::escape_string($score)."', exe_weighting = '".Database::escape_string($weighting)."', @@ -356,1338 +378,1469 @@ function update_event_exercice( questions_to_check = '".$remind_list."', data_tracking = '".implode(',', $question_list)."' WHERE exe_id = '".Database::escape_string($exeid)."'"; - $res = Database::query($sql); - - if ($debug) error_log('update_event_exercice called'); - if ($debug) error_log("$sql"); - - //Deleting control time session track - //exercise_time_control_delete($exo_id); - return $res; - } else { - return false; - } -} - -/** - * This function creates an empty Exercise in STATISTIC_TRACK_E_EXERCICES table. - * After that in exercise_result.php we call the update_event_exercice() to update the exercise - * @return $id the last id registered, or false on error - * @author Julio Montoya - * @desc Record result of user when an exercice was done - * @deprecated this function seems to be deprecated -*/ -function create_event_exercice($exo_id) -{ - if (empty($exo_id) or (intval($exo_id)!=$exo_id)) { - return false; - } - $tbl_track_exe = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $tbl_exe = Database::get_course_table(TABLE_QUIZ_TEST); - $uid = api_get_user_id(); - $course_id = api_get_course_int_id(); - - // First, check the exercise exists - $sql_exe_id="SELECT exercises.id FROM $tbl_exe as exercises WHERE c_id = $course_id AND exercises.id=$exo_id"; - $res_exe_id=Database::query($sql_exe_id); - if ($res_exe_id === false) { return false; } //sql error - if (Database::num_rows($res_exe_id)<1) { return false;} //exe not found - $row_exe_id=Database::fetch_row($res_exe_id); - $exercise_id = intval($row_exe_id[0]); - // Second, check if the record exists in the database (looking for incomplete records) - $sql = "SELECT exe_id FROM $tbl_track_exe WHERE exe_exo_id = $exo_id AND " . - "exe_user_id = $uid AND " . - "exe_cours_id = '".api_get_course_id()."' AND " . - "status = 'incomplete' AND ". - "session_id = ".api_get_session_id(); - $res = Database::query($sql); - if ($res === false) {return false;} - if (Database::num_rows($res) > 0) { - $row = Database::fetch_array($res); - return $row['exe_id']; - } + $res = Database::query($sql); - // No record was found, so create one - // get expire time to insert into the tracking record - $current_expired_time_key = get_time_control_key($exercise_id); - if (isset($_SESSION['expired_time'][$current_expired_time_key])) { //Only for exercice of type "One page" - $expired_date = $_SESSION['expired_time'][$current_expired_time_key]; - } else { - $expired_date = '0000-00-00 00:00:00'; - } - $sql = "INSERT INTO $tbl_track_exe ( exe_user_id, exe_cours_id, expired_time_control, exe_exo_id, session_id) - VALUES ( $uid, '".api_get_course_id()."' ,'$expired_date','$exo_id','".api_get_session_id()."')"; - Database::query($sql); - $id= Database::insert_id(); - return $id; -} - -/** - * Record an event for this attempt at answering an exercise - * @param float Score achieved - * @param string Answer given - * @param integer Question ID - * @param integer Exercise ID - * @param integer Position - * @return boolean Result of the insert query - */ -function exercise_attempt($score, $answer, $question_id, $exe_id, $position, $exercise_id = 0, $nano = null) -{ - global $debug, $learnpath_id, $learnpath_item_id; - $score = Database::escape_string($score); - $answer = Database::escape_string($answer); - $question_id = Database::escape_string($question_id); - $exe_id = Database::escape_string($exe_id); - $position = Database::escape_string($position); - $now = api_get_utc_datetime(); - $user_id = api_get_user_id(); - - $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - - if ($debug) error_log("----- entering exercise_attempt() function ------"); - if ($debug) error_log("answer: $answer"); - if ($debug) error_log("score: $score"); - if ($debug) error_log("question_id : $question_id"); - if ($debug) error_log("position: $position"); - - //Validation in case of fraud with actived control time - if (!exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id)) { - if ($debug) error_log("exercise_time_control_is_valid is false"); - $score = 0; - $answer = 0; - } + if ($debug) error_log('update_event_exercice called'); + if ($debug) error_log("$sql"); - if (!empty($user_id)) { - $user_id = "'".$user_id."'"; - } else { - // anonymous - $user_id = api_get_anonymous_id(); + //Deleting control time session track + //ExerciseLib::exercise_time_control_delete($exo_id); + return $res; + } else { + return false; + } } - $file = ''; - if (isset($nano)) { - $file = Database::escape_string(basename($nano->load_filename_if_exists(false))); - } + /** + * Record an event for this attempt at answering an exercise + * @param float Score achieved + * @param string Answer given + * @param integer Question ID + * @param integer Exercise attempt ID a.k.a exe_id (from track_e_exercise) + * @param integer Position + * @param integer Exercise ID (from c_quiz) + * @param bool update results? + * @param string Filename (for audio answers - using nanogong) + * @param integer User ID The user who's going to get this score. Default value of null means "get from context". + * @param integer Course ID (from the "id" column of course table). Default value of null means "get from context". + * @param integer Session ID (from the session table). Default value of null means "get from context". + * @param integer Learnpath ID (from c_lp table). Default value of null means "get from context". + * @param integer Learnpath item ID (from the c_lp_item table). Default value of null means "get from context". + * @return boolean Result of the insert query + */ + public static function saveQuestionAttempt( + $score, + $answer, + $question_id, + $exe_id, + $position, + $exercise_id = 0, + $updateResults = false, + $nano = null, + $user_id = null, + $course_id = null, + $session_id = null, + $learnpath_id = null, + $learnpath_item_id = null + ) { + global $debug; + + //$score = Database::escape_string($score); + // $answer = Database::escape_string($answer); + $question_id = Database::escape_string($question_id); + $exe_id = Database::escape_string($exe_id); + $position = Database::escape_string($position); + $now = api_get_utc_datetime(); + + // check user_id or get from context + if (empty($user_id) or intval($user_id) != $user_id) { + $user_id = api_get_user_id(); + // anonymous + if (empty($user_id)) { + $user_id = api_get_anonymous_id(); + } + } + // check course_id or get from context + if (empty($course_id) or intval($course_id) != $course_id) { + $course_id = api_get_course_int_id(); + } + // check session_id or get from context + if (empty($session_id) or intval($session_id) != $session_id) { + $session_id = api_get_session_id(); + } + // check learnpath_id or get from context + if (empty($learnpath_id)) { + global $learnpath_id; + } + // check learnpath_item_id or get from context + if (empty($learnpath_item_id)) { + global $learnpath_item_id; + } - $course_code = api_get_course_id(); - $session_id = api_get_session_id(); + $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) { + if ($debug) { + error_log("----- entering saveQuestionAttempt() function ------"); + error_log("answer: $answer"); + error_log("score: $score"); + error_log("question_id : $question_id"); + error_log("position: $position"); + } - // Check if attempt exists - $sql = "SELECT exe_id FROM $TBL_TRACK_ATTEMPT - WHERE - course_code = '$course_code' AND - session_id = $session_id AND - exe_id = $exe_id AND - user_id = $user_id AND - question_id = $question_id AND - position = $position"; - $result = Database::query($sql); - if (Database::num_rows($result)) { - if ($debug) error_log("Attempt already exist: exe_id: $exe_id - user_id:$user_id - question_id:$question_id"); - //The attempt already exist do not update use update_event_exercice() instead - return false; + //Validation in case of fraud with active control time + if (!ExerciseLib::exercise_time_control_is_valid($exercise_id, $learnpath_id, $learnpath_item_id)) { + if ($debug) { + error_log("exercise_time_control_is_valid is false"); + } + $score = 0; + $answer = 0; } - $sql = "INSERT INTO $TBL_TRACK_ATTEMPT (exe_id, user_id, question_id, answer, marks, course_code, session_id, position, tms, filename) - VALUES ( - ".$exe_id.", - ".$user_id.", - '".$question_id."', - '".$answer."', - '".$score."', - '".$course_code."', - '".$session_id."', - '".$position."', - '".$now."', - '".$file."' - )"; - - if ($debug) error_log("Saving question attempt: "); - if ($debug) error_log($sql); + if (!empty($user_id)) { + $user_id = "'".$user_id."'"; + } else { + // anonymous + $user_id = api_get_anonymous_id(); + } - $res = Database::query($sql); - if (defined('ENABLED_LIVE_EXERCISE_TRACKING')){ - $recording_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - if ($debug) error_log("Saving e attempt recording "); - $recording_changes = "INSERT INTO $recording_table (exe_id, question_id, marks, insert_date, author, session_id) - VALUES ('$exe_id','$question_id','$score','".api_get_utc_datetime()."','', '".api_get_session_id()."') "; - Database::query($recording_changes); + $file = ''; + if (isset($nano)) { + $file = Database::escape_string(basename($nano->load_filename_if_exists(false))); } - return $res; - } else { - return false; - } -} -/** - * Record an hotspot spot for this attempt at answering an hotspot question - * @param int Exercise ID - * @param int Question ID - * @param int Answer ID - * @param int Whether this answer is correct (1) or not (0) - * @param string Coordinates of this point (e.g. 123;324) - * @return boolean Result of the insert query - * @uses Course code and user_id from global scope $_cid and $_user - */ -function exercise_attempt_hotspot($exe_id, $question_id, $answer_id, $correct, $coords, $exerciseId = 0) -{ - global $safe_lp_id, $safe_lp_item_id; - //Validation in case of fraud with actived control time - if (!exercise_time_control_is_valid($exerciseId, $safe_lp_id, $safe_lp_item_id)) { - $correct = 0; - } + $session_id = api_get_session_id(); + + if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) { + $attempt = array( + 'user_id' => $user_id, + 'question_id' => $question_id, + 'answer' => $answer, + 'marks' => $score, + 'c_id' => $course_id, + 'session_id' => $session_id, + 'position' => $position, + 'tms' => $now, + 'filename' => $file, + ); + + + // Check if attempt exists. + + $sql = "SELECT exe_id FROM $TBL_TRACK_ATTEMPT + WHERE c_id = $course_id AND + session_id = $session_id AND + exe_id = $exe_id AND + user_id = $user_id AND + question_id = $question_id AND + position = $position"; + $result = Database::query($sql); + if (Database::num_rows($result)) { + if ($debug) { + error_log("Attempt already exist: exe_id: $exe_id - user_id:$user_id - question_id:$question_id"); + } + if ($updateResults == false) { + //The attempt already exist do not update use update_event_exercise() instead + return false; + } + } else { + $attempt['exe_id'] = $exe_id; + } - $tbl_track_e_hotspot = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); - $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate)". - " VALUES ('" . api_get_user_id() . "'," . - " '" . api_get_course_id() . "', " . - " '" . Database :: escape_string($exe_id) . "', " . - " '" . Database :: escape_string($question_id) . "'," . - " '" . Database :: escape_string($answer_id) . "'," . - " '" . Database :: escape_string($correct) . "'," . - " '" . Database :: escape_string($coords) . "')"; - return $result = Database::query($sql); -} + if ($debug) { + error_log("updateResults : $updateResults"); + error_log("Saving question attempt: "); + error_log($sql); + } -/** - * Records information for common (or admin) events (in the track_e_default table) - * @author Yannick Warnier - * @param string Type of event - * @param string Type of value - * @param string Value - * @param string Timestamp (defaults to null) - * @param integer User ID (defaults to null) - * @param string Course code (defaults to null) - * @param integer Session ID (defaults to null - only stored from 1.10 onwards) - * @assert ('','','') === false - */ -function event_system( - $event_type, - $event_value_type, - $event_value, - $datetime = null, - $user_id = null, - $course_code = null, - $session_id = null -) { - global $TABLETRACK_DEFAULT; - if (empty($event_type)) { - return false; - } - $event_type = Database::escape_string($event_type); - $event_value_type = Database::escape_string($event_value_type); - - // Clean the user_info. - if ($event_value_type == LOG_USER_OBJECT) { - if (is_array($event_value)) { - unset($event_value['complete_name']); - unset($event_value['firstName']); - unset($event_value['lastName']); - unset($event_value['avatar_small']); - unset($event_value['avatar']); - unset($event_value['password']); - unset($event_value['lastLogin']); - unset($event_value['picture_uri']); + $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); + + if ($updateResults == false) { + $attempt_id = Database::insert($TBL_TRACK_ATTEMPT, $attempt); + + if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) { + if ($debug) { + error_log("Saving e attempt recording "); + } + $attempt_recording = array( + 'exe_id' => $attempt_id, + 'question_id' => $question_id, + 'marks' => $score, + 'insert_date' => $now, + 'author' => '', + 'session_id' => $session_id, + ); + Database::insert($recording_table, $attempt_recording); + } + } else { + Database::update($TBL_TRACK_ATTEMPT, $attempt, + array('exe_id = ? AND question_id = ? AND user_id = ? ' => array($exe_id, $question_id, $user_id))); + + if (defined('ENABLED_LIVE_EXERCISE_TRACKING')) { + + $attempt_recording = array( + 'exe_id' => $exe_id, + 'question_id' => $question_id, + 'marks' => $score, + 'insert_date' => $now, + 'author' => '', + 'session_id' => $session_id, + ); + + Database::update($recording_table, $attempt_recording, + array('exe_id = ? AND question_id = ? AND session_id = ? ' => array($exe_id, $question_id, $session_id)) + ); + } + $attempt_id = $exe_id; + } + return $attempt_id; + } else { + return false; } } - if (is_array($event_value)) { - $event_value = serialize($event_value); - } - - $event_value = Database::escape_string($event_value); - $course_info = api_get_course_info($course_code); + /** + * Record an hotspot spot for this attempt at answering an hotspot question + * @param int Exercise ID + * @param int Question ID + * @param int Answer ID + * @param int Whether this answer is correct (1) or not (0) + * @param string Coordinates of this point (e.g. 123;324) + * @param bool update results? + * @return boolean Result of the insert query + * @uses Course code and user_id from global scope $_cid and $_user + */ + public static function saveExerciseAttemptHotspot($exe_id, $question_id, $answer_id, $correct, $coords, $updateResults = false, $exerciseId = 0) + { + global $safe_lp_id, $safe_lp_item_id; + + if ($updateResults == false) { + // Validation in case of fraud with activated control time + if (!ExerciseLib::exercise_time_control_is_valid($exerciseId, $safe_lp_id, $safe_lp_item_id)) { + $correct = 0; + } + } + $tbl_track_e_hotspot = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); + if ($updateResults) { + $params = array( + 'hotspot_correct' => $correct, + 'hotspot_coordinate' => $coords + ); + Database::update($tbl_track_e_hotspot, $params, + array('hotspot_user_id = ? AND hotspot_exe_id = ? AND hotspot_question_id = ? AND hotspot_answer_id = ? ' => array( + api_get_user_id(), + $exe_id, + $question_id, + $answer_id, + $answer_id + + ))); - if (!empty($course_info)) { - $course_id = $course_info['real_id']; - $course_code = $course_info['code']; - $course_code = Database::escape_string($course_code); - } else { - $course_id = null; - $course_code = null; + } else { + $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, c_id, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate)". + " VALUES ('".api_get_user_id()."',". + " '".api_get_course_int_id()."', ". + " '".Database :: escape_string($exe_id)."', ". + " '".Database :: escape_string($question_id)."',". + " '".Database :: escape_string($answer_id)."',". + " '".Database :: escape_string($correct)."',". + " '".Database :: escape_string($coords)."')"; + return $result = Database::query($sql); + } } - if (!isset($datetime)) { - $datetime = api_get_utc_datetime(); - } + /** + * Records information for common (or admin) events (in the track_e_default table) + * @author Yannick Warnier + * @param string Type of event + * @param string Type of value + * @param string Value + * @param string Timestamp (defaults to null) + * @param integer User ID (defaults to null) + * @param string Course code (defaults to null) + * @assert ('','','') === false + */ + public static function addEvent( + $event_type, + $event_value_type, + $event_value, + $datetime = null, + $user_id = null, + $course_code = null + ) { + $TABLETRACK_DEFAULT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT); + + if (empty($event_type)) { + return false; + } + $event_type = Database::escape_string($event_type); + $event_value_type = Database::escape_string($event_value_type); + + //Clean the user_info + if ($event_value_type == LOG_USER_OBJECT) { + if (is_array($event_value)) { + unset($event_value['complete_name']); + unset($event_value['complete_name_with_username']); + unset($event_value['firstName']); + unset($event_value['lastName']); + unset($event_value['avatar_small']); + unset($event_value['avatar_sys_path']); + unset($event_value['avatar']); + unset($event_value['mail']); + unset($event_value['password']); + unset($event_value['lastLogin']); + unset($event_value['picture_uri']); + $event_value = serialize($event_value); + } + } - $datetime = Database::escape_string($datetime); + $event_value = Database::escape_string($event_value); + $course_info = api_get_course_info($course_code); - if (!isset($user_id)) { - $user_id = api_get_user_id(); - } + if (!empty($course_info)) { + $course_id = $course_info['real_id']; + $course_code = $course_info['code']; + $course_code = Database::escape_string($course_code); + } else { + $course_id = null; + $course_code = null; + } - $user_id = intval($user_id); + if (!isset($datetime)) { + $datetime = api_get_utc_datetime(); + } - $sql = "INSERT INTO $TABLETRACK_DEFAULT (default_user_id, default_cours_code, c_id, default_date, default_event_type, default_value_type, default_value) - VALUES ('$user_id', '$course_code', '$course_id', '$datetime', '$event_type', '$event_value_type', '$event_value')"; - Database::query($sql); - return true; -} + $datetime = Database::escape_string($datetime); -/** - * Get every email stored in the database - * - * @param int $etId - * @return array - * @assert () !== false - */ -function get_all_event_types() { - global $event_config; + if (!isset($user_id)) { + $user_id = api_get_user_id(); + } - $sql = 'SELECT etm.id, event_type_name, activated, language_id, message, subject, dokeos_folder - FROM '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' etm - INNER JOIN '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' l - ON etm.language_id = l.id'; + $user_id = intval($user_id); - $events_types = Database::store_result(Database::query($sql), 'ASSOC'); + $sql = "INSERT INTO $TABLETRACK_DEFAULT + (default_user_id, + default_cours_code, + c_id, + default_date, + default_event_type, + default_value_type, + default_value + ) + VALUES('$user_id.', + '$course_code', + '$course_id', + '$datetime', + '$event_type', + '$event_value_type', + '$event_value')"; + Database::query($sql); + return true; + } - $to_return = array(); - foreach ($events_types as $et) { - $et['nameLangVar'] = $event_config[$et["event_type_name"]]["name_lang_var"]; - $et['descLangVar'] = $event_config[$et["event_type_name"]]["desc_lang_var"]; - $to_return[] = $et; + /** + * Get every email stored in the database + * + * @param int $etId + * @return type + * @assert () !== false + */ + public static function get_all_event_types() + { + global $event_config; + + $sql = 'SELECT etm.id, event_type_name, activated, language_id, message, subject, dokeos_folder + FROM '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' etm + INNER JOIN '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' l + ON etm.language_id = l.id'; + + $events_types = Database::store_result(Database::query($sql), 'ASSOC'); + + $to_return = array(); + foreach ($events_types as $et) { + $et['nameLangVar'] = $event_config[$et["event_type_name"]]["name_lang_var"]; + $et['descLangVar'] = $event_config[$et["event_type_name"]]["desc_lang_var"]; + $to_return[] = $et; + } + return $to_return; } - return $to_return; -} -/** - * Get users linked to an event - * - * @param string $event_name - * - * @return string - */ -function get_users_subscribed_to_event($event_name) { - $event_name = Database::escape_string($event_name); - $sql = 'SELECT u.* - FROM '.Database::get_main_table(TABLE_MAIN_USER).' u,' - .Database::get_main_table(TABLE_MAIN_EVENT_TYPE).' e,' - .Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' ue - WHERE ue.user_id = u.user_id - AND e.name = "'.$event_name.'" - AND e.id = ue.event_type_id'; - $return = Database::store_result(Database::query($sql),'ASSOC'); - return json_encode($return); -} + /** + * Get the users related to one event + * + * @param string $event_name + */ + public static function get_event_users($event_name) + { + $event_name = Database::escape_string($event_name); + $sql = 'SELECT user.user_id, user.firstname, user.lastname + FROM '.Database::get_main_table(TABLE_MAIN_USER).' user + JOIN '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' relUser + ON relUser.user_id = user.user_id + WHERE user.status <> '.ANONYMOUS.' AND relUser.event_type_name = "'.$event_name.'"'; + $user_list = Database::store_result(Database::query($sql), 'ASSOC'); + return json_encode($user_list); + } -/** - * Get the users related to one event - * - * @param string $event_name - */ -function get_event_users($event_name) -{ - $event_name = Database::escape_string($event_name); - $sql = 'SELECT user.user_id, user.firstname, user.lastname - FROM '.Database::get_main_table(TABLE_MAIN_USER).' user - JOIN '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' relUser - ON relUser.user_id = user.user_id - WHERE user.status <> '.ANONYMOUS.' AND relUser.event_type_name = "'.$event_name.'"'; - $user_list = Database::store_result(Database::query($sql), 'ASSOC'); - return json_encode($user_list); -} + /** + * @param int $user_id + * @param string $event_type + * @return array|bool + */ + public static function get_events_by_user_and_type($user_id, $event_type) + { + $TABLETRACK_DEFAULT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT); + $user_id = intval($user_id); + $event_type = Database::escape_string($event_type); -/** - * @param int $user_id - * @param string $event_type - * @return array|bool - */ -function get_events_by_user_and_type($user_id, $event_type) { - global $TABLETRACK_DEFAULT; - $user_id = intval($user_id); - $event_type = Database::escape_string($event_type); - - $sql = "SELECT * FROM $TABLETRACK_DEFAULT - WHERE default_value_type = 'user_id' AND - default_value = $user_id AND - default_event_type = '$event_type' - ORDER BY default_date "; - $result = Database::query($sql); - if ($result) { - return Database::store_result($result, 'ASSOC'); + $sql = "SELECT * FROM $TABLETRACK_DEFAULT + WHERE default_value_type = 'user_id' AND + default_value = $user_id AND + default_event_type = '$event_type' + ORDER BY default_date "; + $result = Database::query($sql); + if ($result) { + return Database::store_result($result, 'ASSOC'); + } + return false; } - return false; -} -/** - * @param int $user_id - * @param string $event_type - * @return mixed - */ -function get_latest_event_by_user_and_type($user_id, $event_type) { - $result = get_events_by_user_and_type($user_id, $event_type); - if ($result && !empty($result)) { - return $result[0]; + /** + * @deprecated seems not to be use. + * @param $user_id + * @param $event_type + * @return mixed + */ + function get_latest_event_by_user_and_type($user_id, $event_type) + { + $result = self::get_events_by_user_and_type($user_id, $event_type); + if ($result && !empty($result)) { + return $result[0]; + } } -} -/** - * Save the new message for one event and for one language - * - * @param string $eventName - * @param array $users - * @param string $message - * @param string $subject - * @param string $eventMessageLanguage - * @param int $activated - */ -function save_event_type_message($event_name, $users, $message, $subject, $event_message_language, $activated) -{ - $event_name = Database::escape_string($event_name); - $activated = intval($activated); - $event_message_language = Database::escape_string($event_message_language); + /** + * Save the new message for one event and for one language + * + * @param string $eventName + * @param array $users + * @param string $message + * @param string $subject + * @param string $eventMessageLanguage + * @param int $activated + */ + public static function save_event_type_message($event_name, $users, $message, $subject, $event_message_language, $activated) + { + $event_name = Database::escape_string($event_name); + $activated = intval($activated); + $event_message_language = Database::escape_string($event_message_language); + + // Deletes then re-adds the users linked to the event + $sql = 'DELETE FROM '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' WHERE event_type_name = "'.$event_name.'" '; + Database::query($sql); - // Deletes then re-adds the users linked to the event - $sql = 'DELETE FROM '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' WHERE event_type_name = "'.$event_name.'" '; - Database::query($sql); + foreach ($users as $user) { + $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' (user_id,event_type_name) VALUES('.intval($user).',"'.$event_name.'")'; + Database::query($sql); + } + $language_id = api_get_language_id($event_message_language); + // check if this template in this language already exists or not + $sql = 'SELECT COUNT(id) as total FROM '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' + WHERE event_type_name = "'.$event_name.'" AND language_id = '.$language_id; + + $sql = Database::store_result(Database::query($sql), 'ASSOC'); + + // if already exists, we update + if ($sql[0]["total"] > 0) { + $sql = 'UPDATE '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' + SET message = "'.Database::escape_string($message).'", + subject = "'.Database::escape_string($subject).'", + activated = '.$activated.' + WHERE event_type_name = "'.$event_name.'" AND language_id = (SELECT id FROM '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' + WHERE dokeos_folder = "'.$event_message_language.'")'; + Database::query($sql); + } else { // else we create a new record + // gets the language_-_id + $lang_id = '(SELECT id FROM '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' + WHERE dokeos_folder = "'.$event_message_language.'")'; + $lang_id = Database::store_result(Database::query($lang_id), 'ASSOC'); + + if (!empty($lang_id[0]["id"])) { + $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' (event_type_name, language_id, message, subject, activated) + VALUES("'.$event_name.'", '.$lang_id[0]["id"].', "'.Database::escape_string($message).'", "'.Database::escape_string($subject).'", '.$activated.')'; + Database::query($sql); + } + } - foreach ($users as $user) { - $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' (user_id,event_type_name) VALUES('.intval($user).',"'. $event_name.'")'; + // set activated at every save + $sql = 'UPDATE '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' + SET activated = '.$activated.' + WHERE event_type_name = "'.$event_name.'"'; Database::query($sql); } - $language_id = api_get_language_id($event_message_language); - // check if this template in this language already exists or not - $sql = 'SELECT COUNT(id) as total FROM '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' - WHERE event_type_name = "'.$event_name.'" AND language_id = '.$language_id; - $sql = Database::store_result(Database::query($sql),'ASSOC'); - - // if already exists, we update - if ($sql[0]["total"] > 0) { - $sql = 'UPDATE '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' - SET message = "'.Database::escape_string($message).'", - subject = "'.Database::escape_string($subject).'", - activated = '.$activated.' - WHERE event_type_name = "'.$event_name.'" AND language_id = (SELECT id FROM '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' - WHERE dokeos_folder = "'.$event_message_language.'")'; + /** + * @param $etId + * @param $users + * @param $message + * @param $subject + * @deprecated seem not to be use + */ + public static function eventTypeMod($etId, $users, $message, $subject) { + $etId = intval($etId); + + $sql = 'DELETE FROM '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' WHERE event_type_id = '.$etId.' '; Database::query($sql); - } else { // else we create a new record - // gets the language_-_id - $lang_id = '(SELECT id FROM '.Database::get_main_table(TABLE_MAIN_LANGUAGE).' - WHERE dokeos_folder = "'.$event_message_language.'")'; - $lang_id = Database::store_result(Database::query($lang_id),'ASSOC'); - if (!empty($lang_id[0]["id"])) { - $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' (event_type_name, language_id, message, subject, activated) - VALUES("'.$event_name.'", '.$lang_id[0]["id"].', "'.Database::escape_string($message).'", "'.Database::escape_string($subject).'", '.$activated.')'; + foreach ($users as $user) { + $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' (user_id,event_type_id) + VALUES('.intval($user).','.$etId.') '; Database::query($sql); } - } - // set activated at every save - $sql = 'UPDATE '.Database::get_main_table(TABLE_EVENT_EMAIL_TEMPLATE).' - SET activated = '.$activated.' - WHERE event_type_name = "'.$event_name.'"'; - Database::query($sql); -} - -/** - * @param $etId - * @param $users - * @param $message - * @param $subject - */ -function eventType_mod($etId, $users, $message, $subject) { - $etId = intval($etId); - - $sql = 'DELETE FROM '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' WHERE event_type_id = '.$etId.' '; - Database::query($sql); - - foreach ($users as $user) { - $sql = 'INSERT INTO '.Database::get_main_table(TABLE_EVENT_TYPE_REL_USER).' (user_id,event_type_id) - VALUES('.intval($user).','.$etId.') '; + $sql = 'UPDATE '.Database::get_main_table(TABLE_MAIN_EVENT_TYPE_MESSAGE).' + SET message = "'.Database::escape_string($message).'", + subject = "'.Database::escape_string($subject).'" + WHERE event_type_id = '.$etId.''; Database::query($sql); } - $sql = 'UPDATE '.Database::get_main_table(TABLE_MAIN_EVENT_TYPE_MESSAGE).' - SET message = "'.Database::escape_string($message).'", - subject = "'.Database::escape_string($subject).'" - WHERE event_type_id = '.$etId.''; - Database::query($sql); -} + /** + * Gets the last attempt of an exercise based in the exe_id + * @param int $exe_id + * @return mixed + */ + public static function getLastAttemptDateOfExercise($exe_id) + { + $exe_id = intval($exe_id); + $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $sql_track_attempt = 'SELECT max(tms) as last_attempt_date FROM '.$track_attempts.' WHERE exe_id='.$exe_id; + $rs_last_attempt = Database::query($sql_track_attempt); + $row_last_attempt = Database::fetch_array($rs_last_attempt); + $last_attempt_date = $row_last_attempt['last_attempt_date']; //Get the date of last attempt + return $last_attempt_date; + } -/** - * Gets the last attempt of an exercise based in the exe_id - * - * @param $exe_id - * @return mixed - */ -function get_last_attempt_date_of_exercise($exe_id) -{ - $exe_id = intval($exe_id); - $track_attempts = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $sql = 'SELECT max(tms) as last_attempt_date FROM '.$track_attempts.' - WHERE exe_id='.$exe_id; - $rs_last_attempt = Database::query($sql); - $row_last_attempt = Database::fetch_array($rs_last_attempt); - //Get the date of last attempt - $last_attempt_date = $row_last_attempt['last_attempt_date']; - return $last_attempt_date; -} + /** + * Gets the last attempt of an exercise based in the exe_id + * @param int $exe_id + * @return mixed + */ + public static function getLatestQuestionIdFromAttempt($exe_id) + { + $exe_id = intval($exe_id); + $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $sql = 'SELECT question_id FROM '.$track_attempts.' + WHERE exe_id='.$exe_id.' + ORDER BY tms DESC + LIMIT 1'; + $result = Database::query($sql); + if (Database::num_rows($result)) { + $row = Database::fetch_array($result); + return $row['question_id']; + } else { + return false; + } + } -/** - * Gets how many attempts exists by user, exercise, learning path - * @param int user id - * @param int exercise id - * @param int lp id - * @param int lp item id - * @param int lp item view id - */ -function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id,$lp_item_view_id) { - $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $user_id = intval($user_id); - $exerciseId = intval($exerciseId); - $lp_id = intval($lp_id); - $lp_item_id = intval($lp_item_id); - $lp_item_view_id= intval($lp_item_view_id); - - $sql = "SELECT count(*) as count FROM $stat_table WHERE - exe_exo_id = $exerciseId AND - exe_user_id = $user_id AND - status != 'incomplete' AND - orig_lp_id = $lp_id AND - orig_lp_item_id = $lp_item_id AND - orig_lp_item_view_id = $lp_item_view_id AND - exe_cours_id = '".api_get_course_id()."' AND - session_id = '" . api_get_session_id() . "'"; - - $query = Database::query($sql); - if (Database::num_rows($query) > 0 ) { - $attempt = Database :: fetch_array($query,'ASSOC'); - return $attempt['count']; - } else { - return 0; + /** + * Gets how many attempts exists by user, exercise, learning path + * @param int user id + * @param int exercise id + * @param int lp id + * @param int lp item id + * @param int lp item view id + */ + public static function get_attempt_count($user_id, $exerciseId, $lp_id, $lp_item_id, $lp_item_view_id) + { + $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $user_id = intval($user_id); + $exerciseId = intval($exerciseId); + $lp_id = intval($lp_id); + $lp_item_id = intval($lp_item_id); + $lp_item_view_id = intval($lp_item_view_id); + + $sql = "SELECT count(*) as count FROM $stat_table WHERE + exe_exo_id = $exerciseId AND + exe_user_id = $user_id AND + status != 'incomplete' AND + orig_lp_id = $lp_id AND + orig_lp_item_id = $lp_item_id AND + orig_lp_item_view_id = $lp_item_view_id AND + c_id = '".api_get_course_int_id()."' AND + session_id = '".api_get_session_id()."'"; + + $query = Database::query($sql); + if (Database::num_rows($query) > 0) { + $attempt = Database :: fetch_array($query, 'ASSOC'); + return $attempt['count']; + } else { + return 0; + } } -} -/** - * @param int $user_id - * @param int $exerciseId - * @param int $lp_id - * @param int $lp_item_id - * @return int - */ -function get_attempt_count_not_finished($user_id, $exerciseId, $lp_id, $lp_item_id) -{ - $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $user_id = intval($user_id); - $exerciseId = intval($exerciseId); - $lp_id = intval($lp_id); - $lp_item_id = intval($lp_item_id); - //$lp_item_view_id= intval($lp_item_view_id); - - $sql = "SELECT count(*) as count FROM $stat_table WHERE - exe_exo_id = $exerciseId AND - exe_user_id = $user_id AND - status != 'incomplete' AND - orig_lp_id = $lp_id AND - orig_lp_item_id = $lp_item_id AND - exe_cours_id = '".api_get_course_id()."' AND - session_id = '" . api_get_session_id() . "'"; - - $query = Database::query($sql); - if (Database::num_rows($query) > 0 ) { - $attempt = Database :: fetch_array($query,'ASSOC'); - return $attempt['count']; - } else { - return 0; + /** + * @param $user_id + * @param $exerciseId + * @param $lp_id + * @param $lp_item_id + * @return int + */ + public static function get_attempt_count_not_finished($user_id, $exerciseId, $lp_id, $lp_item_id) + { + $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $user_id = intval($user_id); + $exerciseId = intval($exerciseId); + $lp_id = intval($lp_id); + $lp_item_id = intval($lp_item_id); + //$lp_item_view_id = intval($lp_item_view_id); + + $sql = "SELECT count(*) as count FROM $stat_table WHERE + exe_exo_id = $exerciseId AND + exe_user_id = $user_id AND + status != 'incomplete' AND + orig_lp_id = $lp_id AND + orig_lp_item_id = $lp_item_id AND + c_id = '".api_get_course_int_id()."' AND + session_id = '".api_get_session_id()."'"; + + $query = Database::query($sql); + if (Database::num_rows($query) > 0) { + $attempt = Database :: fetch_array($query, 'ASSOC'); + return $attempt['count']; + } else { + return 0; + } } -} -/** - * Deletes a learning path view for a student - * @param int $user_id - * @param int $lp_id - * @param array $course - * @param int $session_id - */ -function delete_student_lp_events($user_id, $lp_id, $course, $session_id) -{ - $lp_view_table = Database::get_course_table(TABLE_LP_VIEW); - $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW); - $lpInteraction = Database::get_course_table(TABLE_LP_IV_INTERACTION); - $lpObjective = Database::get_course_table(TABLE_LP_IV_OBJECTIVE); + /** + * @param int $user_id + * @param int $lp_id + * @param array $course + * @param int $session_id + */ + public static function delete_student_lp_events($user_id, $lp_id, $course, $session_id) + { + $lp_view_table = Database::get_course_table(TABLE_LP_VIEW); + $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW); + $lpInteraction = Database::get_course_table(TABLE_LP_IV_INTERACTION); + $lpObjective = Database::get_course_table(TABLE_LP_IV_OBJECTIVE); + + $course_id = $course['real_id']; + + if (empty($course_id)) { + $course_id = api_get_course_int_id(); + } - $course_id = $course['real_id']; + $track_e_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_attempts = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + $recording_table = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING + ); - if (empty($course_id)) { - $course_id = api_get_course_int_id(); - } + $user_id = intval($user_id); + $lp_id = intval($lp_id); + $session_id = intval($session_id); - $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempts = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $recording_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - $user_id = intval($user_id); - $lp_id = intval($lp_id); - $session_id = intval($session_id); + //Make sure we have the exact lp_view_id + $sql = "SELECT id FROM $lp_view_table + WHERE + c_id = $course_id AND + user_id = $user_id AND + lp_id = $lp_id AND + session_id = $session_id "; + $result = Database::query($sql); - //Make sure we have the exact lp_view_id - $sql = "SELECT id FROM $lp_view_table - WHERE - c_id = $course_id AND - user_id = $user_id AND - lp_id = $lp_id AND - session_id = $session_id "; - $result = Database::query($sql); - - if (Database::num_rows($result)) { - $view = Database::fetch_array($result, 'ASSOC'); - $lp_view_id = $view['id']; - $sql = "DELETE FROM $lp_item_view_table - WHERE c_id = $course_id AND lp_view_id = $lp_view_id "; - Database::query($sql); + if (Database::num_rows($result)) { + $view = Database::fetch_array($result, 'ASSOC'); + $lp_view_id = $view['id']; - $sql = "DELETE FROM $lpInteraction - WHERE c_id = $course_id AND lp_iv_id = $lp_view_id "; - Database::query($sql); + $sql = "DELETE FROM $lp_item_view_table WHERE c_id = $course_id AND lp_view_id = $lp_view_id "; + Database::query($sql); - $sql = "DELETE FROM $lpObjective - WHERE c_id = $course_id AND lp_iv_id = $lp_view_id "; - Database::query($sql); - } + $sql = "DELETE FROM $lpInteraction + WHERE c_id = $course_id AND lp_iv_id = $lp_view_id "; + Database::query($sql); + + $sql = "DELETE FROM $lpObjective + WHERE c_id = $course_id AND lp_iv_id = $lp_view_id "; + Database::query($sql); + } - $sql = "DELETE FROM $lp_view_table + $sql = "DELETE FROM $lp_view_table WHERE c_id = $course_id AND user_id = $user_id AND lp_id= $lp_id AND session_id = $session_id "; - Database::query($sql); - - $sql = "SELECT exe_id FROM $track_e_exercises - WHERE - exe_user_id = $user_id AND - session_id = $session_id AND - exe_cours_id = '{$course['code']}' AND - orig_lp_id = $lp_id - "; + Database::query($sql); - $result = Database::query($sql); - $exe_list = array(); - while ($row = Database::fetch_array($result, 'ASSOC')) { - $exe_list[] = $row['exe_id']; - } + $sql = "SELECT exe_id FROM $track_e_exercises + WHERE exe_user_id = $user_id AND + session_id = $session_id AND + c_id = $course_id AND + orig_lp_id = $lp_id"; + $result = Database::query($sql); + $exe_list = array(); + while ($row = Database::fetch_array($result, 'ASSOC')) { + $exe_list[] = $row['exe_id']; + } - if (!empty($exe_list) && is_array($exe_list) && count($exe_list) > 0) { - $sql = "DELETE FROM $track_e_exercises WHERE exe_id IN (".implode(',',$exe_list).")"; - Database::query($sql); + if (!empty($exe_list) && is_array($exe_list) && count($exe_list) > 0) { + $sql = "DELETE FROM $track_e_exercises WHERE exe_id IN (" . implode( + ',', + $exe_list + ) . ")"; + Database::query($sql); - $sql = "DELETE FROM $track_attempts WHERE exe_id IN (".implode(',',$exe_list).")"; - Database::query($sql); + $sql = "DELETE FROM $track_attempts WHERE exe_id IN (" . implode( + ',', + $exe_list + ) . ")"; + Database::query($sql); - $sql = "DELETE FROM $recording_table WHERE exe_id IN (".implode(',',$exe_list).")"; - Database::query($sql); - } - event_system( - LOG_LP_ATTEMPT_DELETE, - LOG_LP_ID, - $lp_id, - null, - null, - $course['code'], - $session_id - ); -} + $sql = "DELETE FROM $recording_table WHERE exe_id IN (" . implode( + ',', + $exe_list + ) . ")"; + Database::query($sql); + } -/** - * Delete all exercise attempts (included in LP or not) - * - * @param int user id - * @param int exercise id - * @param string course code - * @param int session id - */ -function delete_all_incomplete_attempts($user_id, $exercise_id, $course_code, $session_id = 0) -{ - $track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $user_id = intval($user_id); - $exercise_id = intval($exercise_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - if (!empty($user_id) && !empty($exercise_id) && !empty($course_code)) { - $sql = "DELETE FROM $track_e_exercises - WHERE exe_user_id = $user_id AND exe_exo_id = $exercise_id AND exe_cours_id = '$course_code' AND session_id = $session_id AND status = 'incomplete' "; - Database::query($sql); + Event::addEvent( + LOG_LP_ATTEMPT_DELETE, + LOG_LP_ID, + $lp_id, + null, + null, + $course['code'], + $session_id + ); } - event_system(LOG_EXERCISE_RESULT_DELETE, LOG_EXERCISE_AND_USER_ID, $exercise_id.'-'.$user_id, null, null, $course_code, $session_id); -} -/** - * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session - * @param int exercise id - * @param string course code - * @param int session id - * @return array with the results - */ -function get_all_exercise_results($exercise_id, $course_code, $session_id = 0, $load_question_list = true, $user_id = null) { - $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - - $user_condition = null; - if (!empty($user_id)) { + /** + * Delete all exercise attempts (included in LP or not) + * + * @param int user id + * @param int exercise id + * @param string course code + * @param int session id + */ + public static function delete_all_incomplete_attempts($user_id, $exercise_id, $course_id, $session_id = 0) + { + $track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); $user_id = intval($user_id); - $user_condition = "AND exe_user_id = $user_id "; - } - $sql = "SELECT * FROM $TABLETRACK_EXERCICES - WHERE - status = '' AND - exe_cours_id = '$course_code' AND - exe_exo_id = '$exercise_id' AND - session_id = $session_id AND - orig_lp_id =0 AND - orig_lp_item_id = 0 - $user_condition - ORDER BY exe_id"; - $res = Database::query($sql); - $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - if ($load_question_list) { - $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; - } + $exercise_id = intval($exercise_id); + $course_id = intval($course_id); + $session_id = intval($session_id); + if (!empty($user_id) && !empty($exercise_id) && !empty($course_code)) { + $sql = "DELETE FROM $track_e_exercises + WHERE exe_user_id = $user_id AND + exe_exo_id = $exercise_id AND + c_id = '$course_id' AND + session_id = $session_id AND + status = 'incomplete' "; + Database::query($sql); + Event::addEvent(LOG_EXERCISE_RESULT_DELETE, LOG_EXERCISE_AND_USER_ID, $exercise_id.'-'.$user_id, null, null, $course_code, $session_id); } } - return $list; -} -/** - * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session - * @param string course code - * @param int session id - * @return array with the results - * - */ -function get_all_exercise_results_by_course($course_code, $session_id = 0, $get_count = true) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_code = Database::escape_string($course_code); - - $session_id = intval($session_id); - $select = '*'; - if ($get_count) { - $select = 'count(*) as count'; - } - $sql = "SELECT $select FROM $table_track_exercises - WHERE status = '' AND exe_cours_id = '$course_code' AND session_id = $session_id AND orig_lp_id = 0 AND orig_lp_item_id = 0 - ORDER BY exe_id"; - $res = Database::query($sql); - if ($get_count) { - $row = Database::fetch_array($res,'ASSOC'); - return $row['count']; - } else { + /** + * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session + * @param int exercise id + * @param string course code + * @param int session id + * @return array with the results + * + */ + public static function get_all_exercise_results($exercise_id, $courseId, $session_id = 0, $load_question_list = true, $user_id = null) + { + $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + + $user_condition = null; + if (!empty($user_id)) { + $user_id = intval($user_id); + $user_condition = "AND exe_user_id = $user_id "; + } + $sql = "SELECT * FROM $TABLETRACK_EXERCICES + WHERE status = '' AND + c_id = '$courseId' AND + exe_exo_id = '$exercise_id' AND + session_id = $session_id AND + orig_lp_id =0 AND + orig_lp_item_id = 0 + $user_condition + ORDER BY exe_id"; + $res = Database::query($sql); $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; - } + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; + if ($load_question_list) { + $sql = "SELECT * FROM $TBL_TRACK_ATTEMPT WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } + } } return $list; } -} -/** -* Gets all exercise results (NO Exercises in LPs) from a given exercise id, course, session -* @param int exercise id -* @param string course code -* @param int session id -* @return array with the results -* -*/ -function get_all_exercise_results_by_user($user_id, $course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_code = Database::escape_string($course_code); - //$exercise_id = intval($exercise_id); - $session_id = intval($session_id); - $user_id = intval($user_id); - - $sql = "SELECT * FROM $table_track_exercises - WHERE - status = '' AND - exe_user_id = $user_id AND - exe_cours_id = '$course_code' AND - session_id = $session_id AND - orig_lp_id = 0 AND - orig_lp_item_id = 0 - ORDER by exe_id"; - - $res = Database::query($sql); - $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + /** + * Gets all exercise results (NO Exercises in LPs ) from a given exercise id, course, session + * @param string course code + * @param int session id + * @return array with the results + * + */ + public static function get_all_exercise_results_by_course($courseId, $session_id = 0, $get_count = true) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $courseId = intval($courseId); + $session_id = intval($session_id); + + $select = '*'; + if ($get_count) { + $select = 'count(*) as count'; + } + $sql = "SELECT $select FROM $table_track_exercises + WHERE status = '' AND + c_id = '$courseId' AND + session_id = $session_id AND + orig_lp_id = 0 AND + orig_lp_item_id = 0 + ORDER BY exe_id"; + $res = Database::query($sql); + if ($get_count) { + $row = Database::fetch_array($res, 'ASSOC'); + return $row['count']; + } else { + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } + } + return $list; } } - return $list; -} -/** -* Gets exercise results (NO Exercises in LPs) from a given exercise id, course, session -* @param int exercise id -* @param string course code -* @param int session id -* @return array with the results -* -*/ -function get_exercise_results_by_attempt($exe_id) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $table_track_attempt_recording = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - $exe_id = intval($exe_id); - - $sql = "SELECT * FROM $table_track_exercises WHERE status = '' AND exe_id = $exe_id"; - $res = Database::query($sql); - $list = array(); - if (Database::num_rows($res)) { - $row = Database::fetch_array($res,'ASSOC'); - - // Checking if this attempt was revised by a teacher - $sql_revised = 'SELECT exe_id FROM ' . $table_track_attempt_recording . ' - WHERE author != "" AND exe_id = '.$exe_id.' LIMIT 1'; - $res_revised = Database::query($sql_revised); - $row['attempt_revised'] = 0; - if (Database::num_rows($res_revised) > 0) { - $row['attempt_revised'] = 1; - } - $list[$exe_id] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = $exe_id ORDER BY tms ASC"; - $res_question = Database::query($sql); - while ($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$exe_id]['question_list'][$row_q['question_id']] = $row_q; + /** + * Gets all exercise results (NO Exercises in LPs) from a given exercise id, course, session + * @param int exercise id + * @param string course code + * @param int session id + * @return array with the results + * + */ + public static function get_all_exercise_results_by_user($user_id, $courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $courseId = intval($courseId); + $session_id = intval($session_id); + $user_id = intval($user_id); + + $sql = "SELECT * FROM $table_track_exercises + WHERE status = '' AND + exe_user_id = $user_id AND + c_id = '$courseId' AND + session_id = $session_id AND + orig_lp_id = 0 AND + orig_lp_item_id = 0 + ORDER by exe_id"; + + $res = Database::query($sql); + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } } + //echo '
'; print_r($list);
+        return $list;
     }
-    // echo '
'; print_r($list); echo "
"; - return $list; -} -/** - * Gets exercise results (NO Exercises in LPs) from a given user, - * exercise id, course, session, lp_id, lp_item_id - * @param int user id - * @param int exercise id - * @param string course code - * @param int session id - * @param int lp id - * @param int lp item id - * @param string order asc or desc - * @return array with the results - * - */ -function get_exercise_results_by_user( - $user_id, - $exercise_id, - $course_code, - $session_id = 0, - $lp_id = 0, - $lp_item_id = 0, - $order = null -) { - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $table_track_attempt_recording = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - $user_id = intval($user_id); - $lp_id = intval($lp_id); - $lp_item_id = intval($lp_item_id); - - if (!in_array(strtolower($order), array('asc', 'desc'))) { - $order = 'asc'; + /** + * Gets exercise results (NO Exercises in LPs) from a given exercise id, course, session + * @param int exercise id + * @param string course code + * @param int session id + * @return array with the results + * + */ + public static function get_exercise_results_by_attempt($exe_id, $status = null) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); + $exe_id = intval($exe_id); + + $status = Database::escape_string($status); + + $sql = "SELECT * FROM $table_track_exercises WHERE status = '".$status."' AND exe_id = $exe_id"; + + $res = Database::query($sql); + $list = array(); + if (Database::num_rows($res)) { + $row = Database::fetch_array($res, 'ASSOC'); + + //Checking if this attempt was revised by a teacher + $sql_revised = 'SELECT exe_id FROM '.$table_track_attempt_recording.' WHERE author != "" AND exe_id = '.$exe_id.' LIMIT 1'; + $res_revised = Database::query($sql_revised); + $row['attempt_revised'] = 0; + if (Database::num_rows($res_revised) > 0) { + $row['attempt_revised'] = 1; + } + $list[$exe_id] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = $exe_id ORDER BY tms ASC"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$exe_id]['question_list'][$row_q['question_id']] = $row_q; + } + } + return $list; } - $sql = "SELECT * FROM $table_track_exercises - WHERE status = '' AND - exe_user_id = $user_id AND - exe_cours_id = '$course_code' AND - exe_exo_id = $exercise_id AND - session_id = $session_id AND - orig_lp_id = $lp_id AND - orig_lp_item_id = $lp_item_id - ORDER by exe_id $order "; - - $res = Database::query($sql); - $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - //Checking if this attempt was revised by a teacher - $sql_revised = 'SELECT exe_id FROM ' . $table_track_attempt_recording . ' - WHERE author != "" AND exe_id = '.$row['exe_id'].' LIMIT 1'; - $res_revised = Database::query($sql_revised); - $row['attempt_revised'] = 0; - if (Database::num_rows($res_revised) > 0) { - $row['attempt_revised'] = 1; + /** + * Gets exercise results (NO Exercises in LPs) from a given user, exercise id, course, session, lp_id, lp_item_id + * @param int user id + * @param int exercise id + * @param string course code + * @param int session id + * @param int lp id + * @param int lp item id + * @param string order asc or desc + * @return array with the results + * + */ + public static function getExerciseResultsByUser($user_id, $exercise_id, $courseId, $session_id = 0, $lp_id = 0, $lp_item_id = 0, $order = null) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $table_track_attempt_recording = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + $user_id = intval($user_id); + $lp_id = intval($lp_id); + $lp_item_id = intval($lp_item_id); + + if (!in_array(strtolower($order), array('asc', 'desc'))) { + $order = 'asc'; } - $list[$row['exe_id']] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while ($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + + $sql = "SELECT * FROM $table_track_exercises + WHERE status = '' AND + exe_user_id = $user_id AND + c_id = $courseId AND + exe_exo_id = $exercise_id AND + session_id = $session_id AND + orig_lp_id = $lp_id AND + orig_lp_item_id = $lp_item_id + ORDER by exe_id $order "; + + $res = Database::query($sql); + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + //Checking if this attempt was revised by a teacher + $sql_revised = 'SELECT exe_id FROM '.$table_track_attempt_recording.' WHERE author != "" AND exe_id = '.$row['exe_id'].' LIMIT 1'; + $res_revised = Database::query($sql_revised); + $row['attempt_revised'] = 0; + if (Database::num_rows($res_revised) > 0) { + $row['attempt_revised'] = 1; + } + $list[$row['exe_id']] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } } + return $list; } - return $list; -} -/** - * Count exercise attempts (NO Exercises in LPs ) from a given exercise id, course, session - * @param int exercise id - * @param string course code - * @param int session id - * @return array with the results - * - */ -function count_exercise_attempts_by_user($user_id, $exercise_id, $course_code, $session_id = 0) -{ - $TABLETRACK_EXERCICES = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - $user_id = intval($user_id); - - $sql = "SELECT count(*) as count FROM $TABLETRACK_EXERCICES - WHERE status = '' AND exe_user_id = '$user_id' AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id AND orig_lp_id =0 AND orig_lp_item_id = 0 ORDER BY exe_id"; - $res = Database::query($sql); - $result = 0; - if (Database::num_rows($res) > 0 ) { - $row = Database::fetch_array($res,'ASSOC'); - $result = $row['count']; - } - return $result; -} + /** + * Count exercise attempts (NO Exercises in LPs ) from a given exercise id, course, session + * @param int exercise id + * @param int course id + * @param int session id + * @return array with the results + * + */ + public static function count_exercise_attempts_by_user($user_id, $exercise_id, $courseId, $session_id = 0) + { + $TABLETRACK_EXERCICES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + $user_id = intval($user_id); -/** - * Gets all exercise BEST results attempts (NO Exercises in LPs ) from a given exercise id, course, session per user - * @param int exercise id - * @param string course code - * @param int session id - * @return array with the results - * @todo rename this function - * - */ -function get_best_exercise_results_by_user($exercise_id, $course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - - $sql = "SELECT * FROM $table_track_exercises - WHERE status = '' AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id AND orig_lp_id =0 AND orig_lp_item_id = 0 ORDER BY exe_id"; - - $res = Database::query($sql); - $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + $sql = "SELECT count(*) as count FROM $TABLETRACK_EXERCICES + WHERE status = '' AND + exe_user_id = '$user_id' AND + c_id = '$courseId' AND + exe_exo_id = '$exercise_id' AND + session_id = $session_id AND + orig_lp_id =0 AND + orig_lp_item_id = 0 + ORDER BY exe_id"; + $res = Database::query($sql); + $result = 0; + if (Database::num_rows($res) > 0) { + $row = Database::fetch_array($res, 'ASSOC'); + $result = $row['count']; } + return $result; } - //Getting the best results of every student - $best_score_return = array(); - - foreach ($list as $student_result) { - $user_id = $student_result['exe_user_id']; - $current_best_score[$user_id] = $student_result['exe_result']; - //echo $current_best_score[$user_id].' - '.$best_score_return[$user_id]['exe_result'].'
'; - if (isset($current_best_score[$user_id]) && - isset($best_score_return[$user_id]['exe_result']) && - $current_best_score[$user_id] > $best_score_return[$user_id]['exe_result'] - ) { - $best_score_return[$user_id] = $student_result; + + /** + * Gets all exercise BEST results attempts (NO Exercises in LPs ) from a given exercise id, course, session per user + * @param int exercise id + * @param int course id + * @param int session id + * @return array with the results + * @todo rename this function + * + */ + public static function get_best_exercise_results_by_user($exercise_id, $courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + + $sql = "SELECT * FROM $table_track_exercises + WHERE status = '' AND + c_id = $courseId AND + exe_exo_id = '$exercise_id' AND + session_id = $session_id AND + orig_lp_id = 0 AND + orig_lp_item_id = 0 + ORDER BY exe_id"; + + $res = Database::query($sql); + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } } - } - return $best_score_return; -} -/** - * @param int $user_id - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @return array - */ -function get_best_attempt_exercise_results_per_user($user_id, $exercise_id, $course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - $user_id = intval($user_id); + //Getting the best results of every student + $best_score_return = array(); - $sql = "SELECT * FROM $table_track_exercises - WHERE - status = '' AND - exe_cours_id = '$course_code' AND - exe_exo_id = '$exercise_id' AND - session_id = $session_id AND - exe_user_id = $user_id AND - orig_lp_id =0 AND - orig_lp_item_id = 0 - ORDER BY exe_id"; - - $res = Database::query($sql); - $list = array(); - while ($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - } - //Getting the best results of every student - $best_score_return = array(); - $best_score_return['exe_result'] = 0; - - foreach ($list as $result) { - $current_best_score = $result; - if ($current_best_score['exe_result'] > $best_score_return['exe_result']) { - $best_score_return = $result; + foreach ($list as $student_result) { + $user_id = $student_result['exe_user_id']; + $current_best_score[$user_id] = $student_result['exe_result']; + + if (isset($current_best_score[$user_id]) && isset($best_score_return[$user_id]) && $current_best_score[$user_id] > $best_score_return[$user_id]['exe_result']) { + $best_score_return[$user_id] = $student_result; + } } + return $best_score_return; } - if (!isset($best_score_return['exe_weighting'])) { + /** + * @param int $user_id + * @param int $exercise_id + * @param int $courseId + * @param int $session_id + * @return array + */ + public static function get_best_attempt_exercise_results_per_user($user_id, $exercise_id, $courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + $user_id = intval($user_id); + + $sql = "SELECT * FROM $table_track_exercises + WHERE status = '' AND + c_id = '$courseId' AND + exe_exo_id = '$exercise_id' AND + session_id = $session_id AND + exe_user_id = $user_id AND + orig_lp_id =0 AND + orig_lp_item_id = 0 + ORDER BY exe_id"; + + $res = Database::query($sql); + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; /* + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while($row_q = Database::fetch_array($res_question,'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } */ + } + //Getting the best results of every student $best_score_return = array(); - } + $best_score_return['exe_result'] = 0; - return $best_score_return; -} + foreach ($list as $result) { + $current_best_score = $result; + if ($current_best_score['exe_result'] > $best_score_return['exe_result']) { + $best_score_return = $result; + } + } + if (!isset($best_score_return['exe_weighting'])) { + $best_score_return = array(); + } + return $best_score_return; + } -/** - * @param int $exercise_id - * @param string $course_code - * @param int $session_id - * @return mixed - */ -function count_exercise_result_not_validated($exercise_id, $course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - $exercise_id = intval($exercise_id); - - $sql = "SELECT count(e.exe_id) as count FROM $table_track_exercises e - LEFT JOIN $table_track_attempt a ON e.exe_id = a.exe_id - WHERE exe_exo_id = $exercise_id AND - exe_cours_id = '$course_code' AND - e.session_id = $session_id AND - orig_lp_id = 0 AND - marks IS NULL AND - status = '' AND - orig_lp_item_id = 0 ORDER BY e.exe_id"; - $res = Database::query($sql); - $row = Database::fetch_array($res,'ASSOC'); - return $row['count']; -} + /** + * @param int $exercise_id + * @param int $courseId + * @param int $session_id + * @return mixed + */ + public static function count_exercise_result_not_validated($exercise_id, $courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); + $courseId = intval($courseId); + $session_id = intval($session_id); + $exercise_id = intval($exercise_id); + + $sql = "SELECT count(e.exe_id) as count + FROM $table_track_exercises e LEFT JOIN $table_track_attempt a ON e.exe_id = a.exe_id + WHERE exe_exo_id = $exercise_id AND + c_id = '$courseId' AND + e.session_id = $session_id AND + orig_lp_id = 0 AND + marks IS NULL AND + status = '' AND + orig_lp_item_id = 0 ORDER BY e.exe_id"; + $res = Database::query($sql); + $row = Database::fetch_array($res, 'ASSOC'); -/** - * Gets all exercise BEST results attempts (NO Exercises in LPs ) - * from a given exercise id, course, session per user - * @param string course code - * @param int session id - * @return array with the results - * - */ -function get_count_exercises_attempted_by_course($course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - - $sql = "SELECT DISTINCT exe_exo_id, exe_user_id - FROM $table_track_exercises - WHERE status = '' AND exe_cours_id = '$course_code' AND session_id = $session_id AND orig_lp_id =0 AND orig_lp_item_id = 0 - ORDER BY exe_id"; - $res = Database::query($sql); - $count = 0; - if (Database::num_rows($res) > 0) { - $count = Database::num_rows($res); + return $row['count']; } - return $count; -} -/** - * Gets all exercise events from a Learning Path within a Course nd Session - * @param int exercise id - * @param string course_code - * @param int session id - * @return array - */ -function get_all_exercise_event_from_lp($exercise_id, $course_code, $session_id = 0) -{ - $table_track_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_code = Database::escape_string($course_code); - $exercise_id = intval($exercise_id); - $session_id = intval($session_id); - - $sql = "SELECT * FROM $table_track_exercises - WHERE status = '' AND exe_cours_id = '$course_code' AND exe_exo_id = '$exercise_id' AND session_id = $session_id AND orig_lp_id !=0 AND orig_lp_item_id != 0"; - - $res = Database::query($sql); - $list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - $list[$row['exe_id']] = $row; - $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; - $res_question = Database::query($sql); - while($row_q = Database::fetch_array($res_question,'ASSOC')) { - $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + /** + * Gets all exercise BEST results attempts (NO Exercises in LPs ) from a given exercise id, course, session per user + * @param int exercise id + * @param int course id + * @param int session id + * @return array with the results + * + */ + public static function get_count_exercises_attempted_by_course($courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $courseId = intval($courseId); + $session_id = intval($session_id); + + $sql = "SELECT DISTINCT exe_exo_id, exe_user_id + FROM $table_track_exercises + WHERE status = '' AND + c_id = '$courseId' AND + session_id = $session_id AND + orig_lp_id =0 AND + orig_lp_item_id = 0 + ORDER BY exe_id"; + $res = Database::query($sql); + $count = 0; + if (Database::num_rows($res) > 0) { + $count = Database::num_rows($res); } + return $count; } - return $list; -} -/** - * @param int $lp_id - * @param int $course_id - * @return array - */ -function get_all_exercises_from_lp($lp_id, $course_id) -{ - $lp_item_table = Database :: get_course_table(TABLE_LP_ITEM); - $course_id = intval($course_id); - $lp_id = intval($lp_id); - $sql = "SELECT * FROM $lp_item_table - WHERE c_id = $course_id AND lp_id = '".$lp_id."' - ORDER BY parent_item_id, display_order"; - $res = Database::query($sql); - $my_exercise_list = array(); - while($row = Database::fetch_array($res,'ASSOC')) { - if ($row['item_type'] == 'quiz') { - $my_exercise_list[] = $row; + /** + * Gets all exercise events from a Learning Path within a Course nd Session + * @param int exercise id + * @param string course_code + * @param int session id + * @return array + */ + public static function get_all_exercise_event_from_lp($exercise_id, $courseId, $session_id = 0) + { + $table_track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $courseId = intval($courseId); + $exercise_id = intval($exercise_id); + $session_id = intval($session_id); + + $sql = "SELECT * FROM $table_track_exercises + WHERE status = '' AND + c_id = $courseId AND + exe_exo_id = '$exercise_id' AND + session_id = $session_id AND + orig_lp_id !=0 AND + orig_lp_item_id != 0"; + + $res = Database::query($sql); + $list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + $list[$row['exe_id']] = $row; + $sql = "SELECT * FROM $table_track_attempt WHERE exe_id = {$row['exe_id']}"; + $res_question = Database::query($sql); + while ($row_q = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['exe_id']]['question_list'][$row_q['question_id']] = $row_q; + } } + return $list; } - return $my_exercise_list; -} - -/** - * This function gets the comments of an exercise - * - * @param int $id - * @param int $question_id - * @return str the comment - */ -function get_comments($exe_id, $question_id) -{ - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $sql = "SELECT teacher_comment - FROM ".$table_track_attempt." - WHERE exe_id='".Database::escape_string($exe_id)."' AND question_id = '".Database::escape_string($question_id)."' - ORDER by question_id"; - $sqlres = Database::query($sql); - $comm = Database::result($sqlres, 0, "teacher_comment"); - return $comm; -} -/** - * @param int $exe_id - * @return array - */ -function get_all_exercise_event_by_exe_id($exe_id) -{ - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $exe_id = intval($exe_id); - $sql = "SELECT * FROM $table_track_attempt - WHERE exe_id = $exe_id - ORDER BY position"; - $res_question = Database::query($sql); - $list = array(); - if (Database::num_rows($res_question)) { - while ($row = Database::fetch_array($res_question, 'ASSOC')) { - $list[$row['question_id']][] = $row; + /** + * @param int $lp_id + * @param $course_id + * @return array + */ + public static function get_all_exercises_from_lp($lp_id, $course_id) + { + $lp_item_table = Database :: get_course_table(TABLE_LP_ITEM); + $course_id = intval($course_id); + $lp_id = intval($lp_id); + $sql = "SELECT * FROM $lp_item_table + WHERE c_id = $course_id AND lp_id = '".$lp_id."' + ORDER BY parent_item_id, display_order"; + $res = Database::query($sql); + $my_exercise_list = array(); + while ($row = Database::fetch_array($res, 'ASSOC')) { + if ($row['item_type'] == 'quiz') { + $my_exercise_list[] = $row; + } } + return $my_exercise_list; } - return $list; -} -/** - * @param int $exe_id - * @param int $user_id - * @param string $course_code - * @param int $session_id - * @param int $question_id - */ -function delete_attempt($exe_id, $user_id, $course_code, $session_id, $question_id) -{ - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - - $exe_id = intval($exe_id); - $user_id = intval($user_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - $question_id = intval($question_id); - - $sql = "DELETE FROM $table_track_attempt - WHERE exe_id = $exe_id AND user_id = $user_id AND course_code = '$course_code' AND session_id = $session_id AND question_id = $question_id "; - Database::query($sql); - event_system( - LOG_QUESTION_RESULT_DELETE, - LOG_EXERCISE_ATTEMPT_QUESTION_ID, - $exe_id . '-' . $question_id, - null, - null, - $course_code, - $session_id - ); -} + /** + * This function gets the comments of an exercise + * + * @param int $id + * @param int $question_id + * @return string the comment + */ + public static function get_comments($exe_id, $question_id) + { + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $sql = "SELECT teacher_comment FROM ".$table_track_attempt." + WHERE exe_id='".Database::escape_string($exe_id)."' AND question_id = '".Database::escape_string($question_id)."' + ORDER by question_id"; + $sqlres = Database::query($sql); + $comm = Database::result($sqlres, 0, "teacher_comment"); + return $comm; + } -/** - * @param int $exe_id - * @param int $user_id - * @param string $course_code - * @param int $question_id - * @todo add session_id for 10 - */ -function delete_attempt_hotspot($exe_id, $user_id, $course_code, $session_id = 0, $question_id) { - $table_track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); - - $exe_id = intval($exe_id); - $user_id = intval($user_id); - $course_code = Database::escape_string($course_code); - $session_id = intval($session_id); - $question_id = intval($question_id); - - $sql = "DELETE FROM $table_track_attempt - WHERE hotspot_exe_id = $exe_id AND hotspot_user_id = $user_id AND hotspot_course_code = '$course_code' AND hotspot_question_id = $question_id "; - Database::query($sql); - event_system( - LOG_QUESTION_RESULT_DELETE, - LOG_EXERCISE_ATTEMPT_QUESTION_ID, - $exe_id . '-' . $question_id, - null, - null, - $course_code, - $session_id - ); -} + /** + * @param int $exe_id + * @return array + */ + public static function getAllExerciseEventByExeId($exe_id) + { + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $exe_id = intval($exe_id); + $list = array(); -/** - * User logs in for the first time to a course - * @param string $course_code - * @param int $user_id - * @param int $session_id - */ -function event_course_login($course_code, $user_id, $session_id) -{ - $course_tracking_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); + $sql = "SELECT * FROM $table_track_attempt + WHERE exe_id = $exe_id ORDER BY position"; + $res_question = Database::query($sql); + if (Database::num_rows($res_question)) { + while ($row = Database::fetch_array($res_question, 'ASSOC')) { + $list[$row['question_id']][] = $row; + } + } + return $list; + } - //@todo use api_get_utc_datetime - $time = api_get_utc_datetime(); + /** + * + * @param int $exe_id + * @param int $user_id + * @param int $courseId + * @param int $session_id + * @param int $question_id + */ + public static function delete_attempt($exe_id, $user_id, $courseId, $session_id, $question_id) + { + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + + $exe_id = intval($exe_id); + $user_id = intval($user_id); + $courseId = intval($courseId); + $session_id = intval($session_id); + $question_id = intval($question_id); + + $sql = "DELETE FROM $table_track_attempt + WHERE exe_id = $exe_id AND + user_id = $user_id AND + c_id = $courseId AND + session_id = $session_id AND + question_id = $question_id "; + Database::query($sql); - $course_code = Database::escape_string($course_code); - $user_id = intval($user_id); - $session_id = intval($session_id); - $session_lifetime = 3600; + Event::addEvent( + LOG_QUESTION_RESULT_DELETE, + LOG_EXERCISE_ATTEMPT_QUESTION_ID, + $exe_id . '-' . $question_id, + null, + null, + $course_code, + $session_id + ); + } - //We select the last record for the current course in the course tracking table - $sql = "SELECT course_access_id - FROM $course_tracking_table - WHERE - user_id = $user_id AND - course_code = '$course_code' AND - session_id = $session_id AND - login_course_date > '$time' - INTERVAL $session_lifetime SECOND - ORDER BY login_course_date DESC LIMIT 0,1"; - $result = Database::query($sql); - - if (Database::num_rows($result) > 0) { - $i_course_access_id = Database::result($result,0,0); - //We update the course tracking table - $sql = "UPDATE $course_tracking_table SET logout_course_date = '$time', counter = counter+1 - WHERE course_access_id = ".intval($i_course_access_id)." AND session_id = ".$session_id; + /** + * @param $exe_id + * @param $user_id + * @param int $courseId + * @param $question_id + */ + public static function delete_attempt_hotspot($exe_id, $user_id, $courseId, $question_id) + { + $table_track_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); + + $exe_id = intval($exe_id); + $user_id = intval($user_id); + $courseId = intval($courseId); + $question_id = intval($question_id); + + $sql = "DELETE FROM $table_track_attempt + WHERE hotspot_exe_id = $exe_id AND + hotspot_user_id = $user_id AND + c_id = $courseId AND + hotspot_question_id = $question_id "; Database::query($sql); - } else { - $sql="INSERT INTO $course_tracking_table (course_code, user_id, login_course_date, logout_course_date, counter, session_id)" . - "VALUES('".$course_code."', '".$user_id."', '$time', '$time', '1','".$session_id."')"; + Event::addEvent( + LOG_QUESTION_RESULT_DELETE, + LOG_EXERCISE_ATTEMPT_QUESTION_ID, + $exe_id . '-' . $question_id, + null, + null, + $course_code, + $session_id + ); + } + + /** + * @param $exe_id + * @param $objExercise + * @return array + */ + public static function getAnsweredQuestionsFromAttempt($exe_id, $objExercise) + { + $attempt_list = self::getAllExerciseEventByExeId($exe_id); + $exercise_result = array(); + if (!empty($attempt_list)) { + foreach ($attempt_list as $question_id => $options) { + foreach ($options as $item) { + $question_obj = Question::read($item['question_id']); + switch ($question_obj->type) { + case FILL_IN_BLANKS: + $item['answer'] = $objExercise->fill_in_blank_answer_to_string($item['answer']); + break; + case HOT_SPOT: + //var_dump($item['answer']); + break; + } + + if ($item['answer'] != '0' && !empty($item['answer'])) { + $exercise_result[] = $question_id; + break; + } + } + } + } + return $exercise_result; + } + + /** + * User logs in for the first time to a course + * @param $course_code + * @param $user_id + * @param $session_id + */ + public static function event_course_login($courseId, $user_id, $session_id) + { + $course_tracking_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); + $time = api_get_datetime(); + + $courseId = Database::escape_string($courseId); + $user_id = Database::escape_string($user_id); + $session_id = Database::escape_string($session_id); + + $sql = "INSERT INTO $course_tracking_table(c_id, user_id, login_course_date, logout_course_date, counter, session_id) + VALUES('".$courseId."', '".$user_id."', '$time', '$time', '1', '".$session_id."')"; Database::query($sql); + + //Course catalog stats modifications see #4191 + CourseManager::update_course_ranking(null, null, null, null, true, false); } - // Course catalog stats modifications see #4191 - CourseManager::update_course_ranking(null, null, null, null, true, false); -} -/** - * For the sake of genericity, this function is a switch. - * It's called by EventsDispatcher and fires the good function - * with the good require_once. - * - * @param string $event_name - * @param array $params - */ -function event_send_mail($event_name, $params) -{ - EventsMail::send_mail($event_name, $params); -} + /** + * For the sake of genericity, this function is a switch. + * It's called by EventsDispatcher and fires the good function + * with the good require_once. + * + * @param string $event_name + * @param array $params + */ + public static function event_send_mail($event_name, $params) + { + EventsMail::send_mail($event_name, $params); + } -/** - * Internal function checking if the mail was already sent from that user to that user - * @param string $event_name - * @param int $user_from - * @param int $user_to - * @return boolean - */ -function check_if_mail_already_sent($event_name, $user_from, $user_to = null) { - $event_name = Database::escape_string($event_name); - $user_to = intval($user_to); - $user_from = intval($user_from); - if ($user_to == null) { - $sql = 'SELECT COUNT(*) as total FROM ' . Database::get_main_table(TABLE_EVENT_SENT) . ' - WHERE user_from = '.$user_from.' AND event_type_name = "'.$event_name.'"'; - } else { - $sql = 'SELECT COUNT(*) as total FROM ' . Database::get_main_table(TABLE_EVENT_SENT) . ' - WHERE user_from = '.$user_from.' AND user_to = '.$user_to.' AND event_type_name = "'.$event_name.'"'; + /** + * Internal function checking if the mail was already sent from that user to that user + * @param string $event_name + * @param int $user_from + * @param int $user_to + * @return boolean + */ + public static function check_if_mail_already_sent($event_name, $user_from, $user_to = null) + { + if ($user_to == null) { + $sql = 'SELECT COUNT(*) as total FROM '.Database::get_main_table(TABLE_EVENT_SENT).' + WHERE user_from = '.$user_from.' AND event_type_name = "'.$event_name.'"'; + } else { + $sql = 'SELECT COUNT(*) as total FROM '.Database::get_main_table(TABLE_EVENT_SENT).' + WHERE user_from = '.$user_from.' AND user_to = '.$user_to.' AND event_type_name = "'.$event_name.'"'; + } + $result = Database::store_result(Database::query($sql), 'ASSOC'); + return $result[0]["total"]; } - $result = Database::store_result(Database::query($sql), 'ASSOC'); - return $result[0]["total"]; -} -/* - * Filter EventEmailTemplate Filters see the main/inc/conf/events.conf.dist.php - */ + /** + * + * Filter EventEmailTemplate Filters see the main/inc/conf/events.conf.dist.php + * + */ + + /** + * Basic template event message filter (to be used by other filters as default) + * @param array $values (passing by reference) + * @return boolean True if everything is OK, false otherwise + */ + function event_send_mail_filter_func(&$values) + { + return true; + } -/** - * Basic template event message filter (to be used by other filters as default) - * @param array $values (passing by reference) - * @return boolean True if everything is OK, false otherwise - */ -function _event_send_mail_filter_func(&$values) { - return true; -} -/** - * user_registration - send_mail filter - * @param array $values (passing by reference) - * @return boolean True if everything is OK, false otherwise - */ -function user_registration_event_send_mail_filter_func(&$values) { - $res = _event_send_mail_filter_func($values); - // proper logic for this filter - return $res; -} -/** - * portal_homepage_edited - send_mail filter - * @param array $values (passing by reference) - * @return boolean True if everything is OK, false otherwise - */ -function portal_homepage_edited_event_send_mail_filter_func(&$values) { - $res = _event_send_mail_filter_func($values); - // proper logic for this filter - return $res; -} + /** + * user_registration - send_mail filter + * @param array $values (passing by reference) + * @return boolean True if everything is OK, false otherwise + */ + function user_registration_event_send_mail_filter_func(&$values) + { + $res = _event_send_mail_filter_func($values); + // proper logic for this filter + return $res; + } -/* End of filters */ + /** + * portal_homepage_edited - send_mail filter + * @param array $values (passing by reference) + * @return boolean True if everything is OK, false otherwise + */ + function portal_homepage_edited_event_send_mail_filter_func(&$values) + { + $res = self::event_send_mail_filter_func($values); + // proper logic for this filter + return $res; + } +} diff --git a/main/inc/lib/exercise.lib.php b/main/inc/lib/exercise.lib.php new file mode 100644 index 0000000000..28984c1fce --- /dev/null +++ b/main/inc/lib/exercise.lib.php @@ -0,0 +1,3620 @@ + + * @author Hubert Borderiou 2011-10-21 + * @author ivantcholakov2009-07-20 + * + */ +class ExerciseLib +{ + /** + * Shows a question + * + * @param int $questionId question id + * @param bool $only_questions if true only show the questions, no exercise title + * @param bool $origin i.e = learnpath + * @param string $current_item current item from the list of questions + * @param bool $show_title + * @param bool $freeze + * @param array $user_choice + * @param bool $show_comment + * @param bool $exercise_feedback + * @param bool $show_answers + * */ + public static function showQuestion( + $questionId, + $only_questions = false, + $origin = false, + $current_item = '', + $show_title = true, + $freeze = false, + $user_choice = array(), + $show_comment = false, + $exercise_feedback = null, + $show_answers = false + ) + { + // Change false to true in the following line to enable answer hinting + $debug_mark_answer = $show_answers; + + // Reads question information + if (!$objQuestionTmp = Question::read($questionId)) { + // Question not found + return false; + } + + if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) { + $show_comment = false; + } + + $answerType = $objQuestionTmp->selectType(); + $pictureName = $objQuestionTmp->selectPicture(); + $s = ''; + + if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) { + // Question is not a hotspot + + if (!$only_questions) { + $questionDescription = $objQuestionTmp->selectDescription(); + if ($show_title) { + Testcategory::displayCategoryAndTitle($objQuestionTmp->id); + echo Display::div( + $current_item . '. ' . $objQuestionTmp->selectTitle(), + array('class' => 'question_title') + ); + } + if (!empty($questionDescription)) { + echo Display::div( + $questionDescription, + array('class' => 'question_description') + ); + } + } + + if (in_array( + $answerType, + array(FREE_ANSWER, ORAL_EXPRESSION) + ) && $freeze + ) { + return ''; + } + + echo '
'; + // construction of the Answer object (also gets all answers details) + $objAnswerTmp = new Answer($questionId); + + $nbrAnswers = $objAnswerTmp->selectNbrAnswers(); + $course_id = api_get_course_int_id(); + $quiz_question_options = Question::readQuestionOption( + $questionId, + $course_id + ); + + // For "matching" type here, we need something a little bit special + // because the match between the suggestions and the answers cannot be + // done easily (suggestions and answers are in the same table), so we + // have to go through answers first (elems with "correct" value to 0). + $select_items = array(); + //This will contain the number of answers on the left side. We call them + // suggestions here, for the sake of comprehensions, while the ones + // on the right side are called answers + $num_suggestions = 0; + + if ($answerType == MATCHING) { + $s .= ''; + // Iterate through answers + $x = 1; + //mark letters for each answer + $letter = 'A'; + $answer_matching = array(); + $cpt1 = array(); + for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) { + $answerCorrect = $objAnswerTmp->isCorrect($answerId); + $numAnswer = $objAnswerTmp->selectAutoId($answerId); + + $answer = $objAnswerTmp->selectAnswer($answerId); + if ($answerCorrect == 0) { + // options (A, B, C, ...) that will be put into the list-box + // have the "correct" field set to 0 because they are answer + $cpt1[$x] = $letter; + $answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId( + $numAnswer + ); + $x++; + $letter++; + } + } + + $i = 1; + + $select_items[0]['id'] = 0; + $select_items[0]['letter'] = '--'; + $select_items[0]['answer'] = ''; + foreach ($answer_matching as $id => $value) { + $select_items[$i]['id'] = $value['id']; + $select_items[$i]['letter'] = $cpt1[$id]; + $select_items[$i]['answer'] = $value['answer']; + $i++; + } + + $user_choice_array_position = array(); + if (!empty($user_choice)) { + foreach ($user_choice as $item) { + $user_choice_array_position[$item['position']] = $item['answer']; + } + } + $num_suggestions = ($nbrAnswers - $x) + 1; + + } elseif ($answerType == FREE_ANSWER) { + $fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer'] : null; + + $oFCKeditor = new CKeditor(); + $oFCKeditor->ToolbarSet = 'Test_Free_Answer'; + $oFCKeditor->Width = '100%'; + $oFCKeditor->Height = '200'; + $oFCKeditor->Value = $fck_content; + $s .= $oFCKeditor->editor( + "choice[" . $questionId . "]", + $oFCKeditor->Value + ); + } elseif ($answerType == ORAL_EXPRESSION) { + //Add nanog + if (api_get_setting('enable_nanogong') == 'true') { + //@todo pass this as a parameter + global $exercise_stat_info, $exerciseId, $exe_id; + + if (!empty($exercise_stat_info)) { + $params = array( + 'exercise_id' => $exercise_stat_info['exe_exo_id'], + 'exe_id' => $exercise_stat_info['exe_id'], + 'question_id' => $questionId + ); + } else { + $params = array( + 'exercise_id' => $exerciseId, + 'exe_id' => 'temp_exe', + 'question_id' => $questionId + ); + } + $nano = new Nanogong($params); + echo $nano->show_button(); + } + + $oFCKeditor = new CKeditor(); + $oFCKeditor->ToolbarSet = 'TestFreeAnswer'; + $oFCKeditor->Width = '100%'; + $oFCKeditor->Height = '150'; + $oFCKeditor->ToolbarStartExpanded = false; + $oFCKeditor->Value = ''; + $s .= $oFCKeditor->editor( + "choice[" . $questionId . "]", + $oFCKeditor->Value + ); + } + + // Now navigate through the possible answers, using the max number of + // answers for the question as a limiter + $lines_count = 1; // a counter for matching-type answers + + if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || + $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE + ) { + $header = Display::tag('th', get_lang('Options')); + foreach ($objQuestionTmp->options as $item) { + if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) { + if (in_array($item, $objQuestionTmp->options)) { + $header .= Display::tag('th', get_lang($item)); + } else { + $header .= Display::tag('th', $item); + } + } else { + $header .= Display::tag('th', $item); + } + + } + if ($show_comment) { + $header .= Display::tag('th', get_lang('Feedback')); + } + $s .= '
'; + $s .= Display::tag( + 'tr', + $header, + array('style' => 'text-align:left;') + ); + } + + if ($show_comment) { + if (in_array( + $answerType, + array( + MULTIPLE_ANSWER, + MULTIPLE_ANSWER_COMBINATION, + UNIQUE_ANSWER, + UNIQUE_ANSWER_NO_OPTION, + GLOBAL_MULTIPLE_ANSWER + ) + ) + ) { + $header = Display::tag('th', get_lang('Options')); + if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) { + $header .= Display::tag('th', get_lang('Feedback')); + } + $s .= '
'; + $s .= Display::tag( + 'tr', + $header, + array('style' => 'text-align:left;') + ); + } + } + + $matching_correct_answer = 0; + $user_choice_array = array(); + if (!empty($user_choice)) { + foreach ($user_choice as $item) { + $user_choice_array[] = $item['answer']; + } + } + + for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) { + $answer = $objAnswerTmp->selectAnswer($answerId); + $answerCorrect = $objAnswerTmp->isCorrect($answerId); + $numAnswer = $objAnswerTmp->selectAutoId($answerId); + $comment = $objAnswerTmp->selectComment($answerId); + + $attributes = array(); + + // Unique answer + if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) { + $input_id = 'choice-' . $questionId . '-' . $answerId; + if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer) { + $attributes = array( + 'id' => $input_id, + 'checked' => 1, + 'selected' => 1 + ); + } else { + $attributes = array('id' => $input_id); + } + + if ($debug_mark_answer) { + if ($answerCorrect) { + $attributes['checked'] = 1; + $attributes['selected'] = 1; + } + } + + $answer = Security::remove_XSS($answer, STUDENT); + $s .= Display::input( + 'hidden', + 'choice2[' . $questionId . ']', + '0' + ); + + $answer_input = ''; + + if ($show_comment) { + $s .= ''; + $s .= ''; + $s .= ''; + } else { + $s .= $answer_input; + } + + } elseif ($answerType == MULTIPLE_ANSWER || + $answerType == MULTIPLE_ANSWER_TRUE_FALSE || + $answerType == GLOBAL_MULTIPLE_ANSWER + ) { + $input_id = 'choice-' . $questionId . '-' . $answerId; + $answer = Security::remove_XSS($answer, STUDENT); + + if (in_array($numAnswer, $user_choice_array)) { + $attributes = array( + 'id' => $input_id, + 'checked' => 1, + 'selected' => 1 + ); + } else { + $attributes = array('id' => $input_id); + } + + if ($debug_mark_answer) { + if ($answerCorrect) { + $attributes['checked'] = 1; + $attributes['selected'] = 1; + } + } + + if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) { + $s .= ''; + + $answer_input = ''; + + if ($show_comment) { + $s .= ''; + $s .= ''; + $s .= ''; + } else { + $s .= $answer_input; + } + } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) { + + $my_choice = array(); + if (!empty($user_choice_array)) { + foreach ($user_choice_array as $item) { + $item = explode(':', $item); + $my_choice[$item[0]] = $item[1]; + } + } + + $s .= ''; + $s .= Display::tag('td', $answer); + + if (!empty($quiz_question_options)) { + foreach ($quiz_question_options as $id => $item) { + + if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) { + $attributes = array( + 'checked' => 1, + 'selected' => 1 + ); + } else { + $attributes = array(); + } + + if ($debug_mark_answer) { + if ($id == $answerCorrect) { + $attributes['checked'] = 1; + $attributes['selected'] = 1; + } + } + $s .= Display::tag( + 'td', + Display::input( + 'radio', + 'choice[' . $questionId . '][' . $numAnswer . ']', + $id, + $attributes + ), + array('style' => '') + ); + } + } + + if ($show_comment) { + $s .= ''; + } + $s .= ''; + } + } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) { + // multiple answers + $input_id = 'choice-' . $questionId . '-' . $answerId; + + if (in_array($numAnswer, $user_choice_array)) { + $attributes = array( + 'id' => $input_id, + 'checked' => 1, + 'selected' => 1 + ); + } else { + $attributes = array('id' => $input_id); + } + + if ($debug_mark_answer) { + if ($answerCorrect) { + $attributes['checked'] = 1; + $attributes['selected'] = 1; + } + } + + $answer = Security::remove_XSS($answer, STUDENT); + $answer_input = ''; + $answer_input .= ''; + + if ($show_comment) { + $s .= ''; + $s .= ''; + $s .= ''; + $s .= ''; + } else { + $s .= $answer_input; + } + + } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) { + $s .= ''; + + $my_choice = array(); + if (!empty($user_choice_array)) { + foreach ($user_choice_array as $item) { + $item = explode(':', $item); + $my_choice[$item[0]] = $item[1]; + } + } + $answer = Security::remove_XSS($answer, STUDENT); + $s .= ''; + $s .= Display::tag('td', $answer); + + foreach ($objQuestionTmp->options as $key => $item) { + if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) { + $attributes = array( + 'checked' => 1, + 'selected' => 1 + ); + } else { + $attributes = array(); + } + + if ($debug_mark_answer) { + if ($key == $answerCorrect) { + $attributes['checked'] = 1; + $attributes['selected'] = 1; + } + } + $s .= Display::tag( + 'td', + Display::input( + 'radio', + 'choice[' . $questionId . '][' . $numAnswer . ']', + $key, + $attributes + ) + ); + } + + if ($show_comment) { + $s .= ''; + } + $s .= ''; + + } elseif ($answerType == FILL_IN_BLANKS) { + /* + * In the FILL_IN_BLANKS test + * you mustn't have [ and ] in the textarea + * you mustn't have :: in the textarea + * the text to find mustn't be empty or contains only spaces + * the text to find mustn't contains HTML tags + * the text to find mustn't contains char " + */ + + list($answer) = explode('::', $answer); + + // $correct_answer_list array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]] + api_preg_match_all( + '/\[[^]]+\]/', + $answer, + $correct_answer_list + ); + + // get student answer to display it if student go back to previous fillBlank answer question in a test + if (isset($user_choice[0]['answer'])) { + api_preg_match_all( + '/\[[^]]+\]/', + $user_choice[0]['answer'], + $student_answer_list + ); + $student_answer_list_tobecleaned = $student_answer_list[0]; + $student_answer_list = array(); + // here we got the student answer in a test + // let's clean up the results + /* + Array + ( + [0] => Array + ( + [0] => [yer / ici] + [1] => [plop / /p] + ) + ) + */ + for ($i = 0; $i < count( + $student_answer_list_tobecleaned + ); $i++) { + $answer_corrected = $student_answer_list_tobecleaned[$i]; + /* + * we got if student answer is wrong + * [rrr / /p] + * or if student answer is good + * [plop / plop] + * or if student didn't answer [] + */ + $answer_corrected = api_preg_replace( + '| / .*$|', + '', + $answer_corrected + ); + /* + * we got [rrr or [plop or [ + */ + $answer_corrected = api_preg_replace( + '/^\[/', + '', + $answer_corrected + ); + /* + * we got rrr or plop + * non breakable spaces     from /main/exercice/exercise.class.php have been removed l 2391 and l 2370 + */ + $answer_corrected = api_preg_replace( + '|^|', + '', + $answer_corrected + ); + $answer_corrected = api_preg_replace( + '|$|', + '', + $answer_corrected + ); + $answer_corrected = '[' . $answer_corrected . ']'; + /* + * we got [rrr] or [plop] or [] + */ + $student_answer_list[] = $answer_corrected; + } + } + + // If display preview of answer in test view for exemple, set the student answer to the correct answers + if ($debug_mark_answer) { + // contain the rights answers surronded with brackets + $student_answer_list = $correct_answer_list[0]; + } + + /* + Split the response by bracket + tab_comments is an array with text surrounding the text to find + we add a space before and after the answer_question to be sure to + have a block of text before and after [xxx] patterns + so we have n text to find ([xxx]) and n+1 block of texts before, + between and after the text to find + */ + $tab_comments = api_preg_split( + '/\[[^]]+\]/', + ' ' . $answer . ' ' + ); + + if (!empty($correct_answer_list) && !empty($student_answer_list)) { + $answer = ""; + $i = 0; + foreach ($student_answer_list as $student_item) { + // remove surronding brackets + $student_response = api_substr( + $student_item, + 1, + api_strlen($student_item) - 2 + ); + + $size = strlen($student_item); + $attributes['class'] = detectInputAppropriateClass( + $size + ); + + $answer .= $tab_comments[$i] . + Display::input( + 'text', + "choice[$questionId][]", + $student_response, + $attributes + ); + $i++; + } + $answer .= $tab_comments[$i]; + } else { + // display exercise with empty input fields + // every [xxx] are replaced with an empty input field + foreach ($correct_answer_list[0] as $item) { + $size = strlen($item); + $attributes['class'] = detectInputAppropriateClass( + $size + ); + $answer = str_replace( + $item, + Display::input( + 'text', + "choice[$questionId][]", + '', + $attributes + ), + $answer + ); + } + /*$answer = api_preg_replace( + '/\[[^]]+\]/', + Display::input( + 'text', + "choice[$questionId][]", + '', + $attributes + ), $answer);*/ + } + $s .= $answer; + + } elseif ($answerType == CALCULATED_ANSWER) { + /* + * In the CALCULATED_ANSWER test + * you mustn't have [ and ] in the textarea + * you mustn't have @@ in the textarea + * the text to find mustn't be empty or contains only spaces + * the text to find mustn't contains HTML tags + * the text to find mustn't contains char " + */ + if ($origin !== null) { + global $exe_id; + $trackAttempts = Database::get_statistic_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + $sqlTrackAttempt = 'SELECT answer FROM ' . $trackAttempts . ' WHERE exe_id=' . $exe_id . ' AND question_id=' . $questionId; + $rsLastAttempt = Database::query($sqlTrackAttempt); + $rowLastAttempt = Database::fetch_array($rsLastAttempt); + $answer = $rowLastAttempt['answer']; + if (empty($answer)) { + $_SESSION['calculatedAnswerId'][$questionId] = mt_rand( + 1, + $nbrAnswers + ); + $answer = $objAnswerTmp->selectAnswer( + $_SESSION['calculatedAnswerId'][$questionId] + ); + } + } + list($answer) = explode('@@', $answer); + // $correctAnswerList array of array with correct anwsers 0=> [0=>[\p] 1=>[plop]] + api_preg_match_all( + '/\[[^]]+\]/', + $answer, + $correctAnswerList + ); + // get student answer to display it if student go back to previous calculated answer question in a test + if (isset($user_choice[0]['answer'])) { + api_preg_match_all( + '/\[[^]]+\]/', + $answer, + $studentAnswerList + ); + $studentAnswerListTobecleaned = $studentAnswerList[0]; + $studentAnswerList = array(); + + for ($i = 0; $i < count( + $studentAnswerListTobecleaned + ); $i++) { + $answerCorrected = $studentAnswerListTobecleaned[$i]; + $answerCorrected = api_preg_replace( + '| / .*$|', + '', + $answerCorrected + ); + $answerCorrected = api_preg_replace( + '/^\[/', + '', + $answerCorrected + ); + $answerCorrected = api_preg_replace( + '|^|', + '', + $answerCorrected + ); + $answerCorrected = api_preg_replace( + '|$|', + '', + $answerCorrected + ); + $answerCorrected = '[' . $answerCorrected . ']'; + $studentAnswerList[] = $answerCorrected; + } + } + // If display preview of answer in test view for exemple, set the student answer to the correct answers + if ($debug_mark_answer) { + // contain the rights answers surronded with brackets + $studentAnswerList = $correctAnswerList[0]; + } + /* + Split the response by bracket + tabComments is an array with text surrounding the text to find + we add a space before and after the answerQuestion to be sure to + have a block of text before and after [xxx] patterns + so we have n text to find ([xxx]) and n+1 block of texts before, + between and after the text to find + */ + $tabComments = api_preg_split( + '/\[[^]]+\]/', + ' ' . $answer . ' ' + ); + if (!empty($correctAnswerList) && !empty($studentAnswerList)) { + $answer = ""; + $i = 0; + foreach ($studentAnswerList as $studentItem) { + // remove surronding brackets + $studentResponse = api_substr( + $studentItem, + 1, + api_strlen($studentItem) - 2 + ); + $size = strlen($studentItem); + $attributes['class'] = detectInputAppropriateClass( + $size + ); + + $answer .= $tabComments[$i] . + Display::input( + 'text', + "choice[$questionId][]", + $studentResponse, + $attributes + ); + $i++; + } + $answer .= $tabComments[$i]; + } else { + // display exercise with empty input fields + // every [xxx] are replaced with an empty input field + foreach ($correctAnswerList[0] as $item) { + $size = strlen($item); + $attributes['class'] = detectInputAppropriateClass( + $size + ); + $answer = str_replace( + $item, + Display::input( + 'text', + "choice[$questionId][]", + '', + $attributes + ), + $answer + ); + } + } + if ($origin !== null) { + $s = $answer; + break; + } else { + $s .= $answer; + } + } elseif ($answerType == MATCHING) { + // matching type, showing suggestions and answers + // TODO: replace $answerId by $numAnswer + + if ($answerCorrect != 0) { + // only show elements to be answered (not the contents of + // the select boxes, who are corrrect = 0) + $s .= ''; + //middle part (matches selects) + + $s .= ''; + $s .= ''; + $s .= ''; + $lines_count++; + //if the left side of the "matching" has been completely + // shown but the right side still has values to show... + if (($lines_count - 1) == $num_suggestions) { + // if it remains answers to shown at the right side + while (isset($select_items[$lines_count])) { + $s .= ' + + + "; + $lines_count++; + } // end while() + } // end if() + $matching_correct_answer++; + } + } + } // end for() + + if ($show_comment) { + $s .= '
'; + $s .= $answer_input; + $s .= ''; + $s .= $comment; + $s .= '
'; + $s .= $answer_input; + $s .= ''; + $s .= $comment; + $s .= '
'; + $s .= $comment; + $s .= '
'; + $s .= $answer_input; + $s .= ''; + $s .= $comment; + $s .= '
'; + $s .= $comment; + $s .= '
'; + $parsed_answer = $answer; + //left part questions + $s .= ' ' . $lines_count . ' + ' . $parsed_answer . '   + '; + if (isset($select_items[$lines_count])) { + $s .= '' . $select_items[$lines_count]['letter'] . '.' . + '' . $select_items[$lines_count]['answer'] . ''; + } else { + $s .= ' '; + } + $s .= '
'; + $s .= '' . $select_items[$lines_count]['letter'] . '. ' . $select_items[$lines_count]['answer']; + $s .= "
'; + } else { + if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || + $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE + ) { + $s .= ''; + } + } + + $s .= '
'; + + // destruction of the Answer object + unset($objAnswerTmp); + + // destruction of the Question object + unset($objQuestionTmp); + + if ($origin != 'export') { + echo $s; + } else { + return $s; + } + } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) { + // Question is a HOT_SPOT + //checking document/images visibility + if (api_is_platform_admin() || api_is_course_admin()) { + $course = api_get_course_info(); + $doc_id = DocumentManager::get_document_id( + $course, + '/images/' . $pictureName + ); + if (is_numeric($doc_id)) { + $images_folder_visibility = api_get_item_visibility( + $course, + 'document', + $doc_id, + api_get_session_id() + ); + if (!$images_folder_visibility) { + //This message is shown only to the course/platform admin if the image is set to visibility = false + Display::display_warning_message( + get_lang('ChangeTheVisibilityOfTheCurrentImage') + ); + } + } + } + $questionName = $objQuestionTmp->selectTitle(); + $questionDescription = $objQuestionTmp->selectDescription(); + + if ($freeze) { + echo Display::img($objQuestionTmp->selectPicturePath()); + return; + } + + // Get the answers, make a list + $objAnswerTmp = new Answer($questionId); + $nbrAnswers = $objAnswerTmp->selectNbrAnswers(); + + // get answers of hotpost + $answers_hotspot = array(); + for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) { + $answers = $objAnswerTmp->selectAnswerByAutoId( + $objAnswerTmp->selectAutoId($answerId) + ); + $answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer( + $answerId + ); + } + + // display answers of hotpost order by id + $answer_list = '
' . get_lang( + 'HotspotZones' + ) . '
'; + if (!empty($answers_hotspot)) { + ksort($answers_hotspot); + foreach ($answers_hotspot as $key => $value) { + $answer_list .= '
' . $key . '.- ' . $value . '

'; + } + } + $answer_list .= '
'; + + if ($answerType == HOT_SPOT_DELINEATION) { + $answer_list = ''; + $swf_file = 'hotspot_delineation_user'; + $swf_height = 405; + } else { + $swf_file = 'hotspot_user'; + $swf_height = 436; + } + + if (!$only_questions) { + if ($show_title) { + Testcategory::displayCategoryAndTitle($objQuestionTmp->id); + echo '
' . $current_item . '. ' . $questionName . '
'; + } + //@todo I need to the get the feedback type + echo ''; + echo ' + + '; + } + + $canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1'); + + $s .= ' + + + + + '; + $s .= ''; + echo $s; + echo '
'; + echo $questionDescription; + echo '
+ +
+ + ' . $answer_list . '
+
'; + } + return $nbrAnswers; + } + + /** + * @param int $exe_id + * @return array + */ + public static function get_exercise_track_exercise_info($exe_id) + { + $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); + $TBL_TRACK_EXERCICES = Database::get_statistic_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $TBL_COURSE = Database::get_main_table(TABLE_MAIN_COURSE); + $exe_id = intval($exe_id); + $result = array(); + if (!empty($exe_id)) { + $sql = " SELECT q.*, tee.* + FROM $TBL_EXERCICES as q + INNER JOIN $TBL_TRACK_EXERCICES as tee + ON q.id=tee.exe_exo_id + INNER JOIN $TBL_COURSE c + ON c.code = tee.exe_cours_id + WHERE tee.exe_id=$exe_id + AND q.c_id=c.id"; + + $res_fb_type = Database::query($sql); + $result = Database::fetch_array($res_fb_type, 'ASSOC'); + } + + return $result; + } + + /** + * Validates the time control key + */ + public static function exercise_time_control_is_valid( + $exercise_id, + $lp_id = 0, + $lp_item_id = 0 + ) { + $course_id = api_get_course_int_id(); + $exercise_id = intval($exercise_id); + $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST); + $sql = "SELECT expired_time FROM $TBL_EXERCICES + WHERE c_id = $course_id AND id = $exercise_id"; + $result = Database::query($sql); + $row = Database::fetch_array($result, 'ASSOC'); + if (!empty($row['expired_time'])) { + $current_expired_time_key = ExerciseLib::get_time_control_key( + $exercise_id, + $lp_id, + $lp_item_id + ); + if (isset($_SESSION['expired_time'][$current_expired_time_key])) { + $current_time = time(); + $expired_time = api_strtotime( + $_SESSION['expired_time'][$current_expired_time_key], + 'UTC' + ); + $total_time_allowed = $expired_time + 30; + if ($total_time_allowed < $current_time) { + return false; + } + return true; + } else { + return false; + } + } else { + return true; + } + } + + /** + * Deletes the time control token + */ + public static function exercise_time_control_delete( + $exercise_id, + $lp_id = 0, + $lp_item_id = 0 + ) { + $current_expired_time_key = self::get_time_control_key( + $exercise_id, + $lp_id, + $lp_item_id + ); + unset($_SESSION['expired_time'][$current_expired_time_key]); + } + + /** + * Generates the time control key + */ + public static function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) + { + $exercise_id = intval($exercise_id); + $lp_id = intval($lp_id); + $lp_item_id = intval($lp_item_id); + return api_get_course_int_id() . '_' . api_get_session_id() . '_' . $exercise_id . '_' . api_get_user_id() . '_' . $lp_id . '_' . $lp_item_id; + } + + /** + * Get session time control + */ + public static function get_session_time_control_key( + $exercise_id, + $lp_id = 0, + $lp_item_id = 0 + ) { + $return_value = 0; + $time_control_key = self::get_time_control_key( + $exercise_id, + $lp_id, + $lp_item_id + ); + if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) { + $return_value = $_SESSION['expired_time'][$time_control_key]; + } + return $return_value; + } + + /** + * Gets count of exam results + * @todo this function should be moved in a library + no global calls + */ + public static function get_count_exam_results($exercise_id, $extra_where_conditions) + { + $count = self::get_exam_results_data( + null, + null, + null, + null, + $exercise_id, + $extra_where_conditions, + true + ); + return $count; + } + + /** + * @param string $in_hotpot_path + * @return int + */ + public static function get_count_exam_hotpotatoes_results($in_hotpot_path) + { + return self::get_exam_results_hotpotatoes_data( + 0, + 0, + '', + '', + $in_hotpot_path, + true, + '' + ); + } + + /** + * @param int $in_from + * @param int $in_number_of_items + * @param int $in_column + * @param int $in_direction + * @param string $in_hotpot_path + * @param bool $in_get_count + * @param null $where_condition + * @return array|int + */ + public static function get_exam_results_hotpotatoes_data( + $in_from, + $in_number_of_items, + $in_column, + $in_direction, + $in_hotpot_path, + $in_get_count = false, + $where_condition = null + ) { + $course_code = api_get_course_id(); + /* by default in_column = 1 If parameters given, + it is the name of the column witch is the bdd field name*/ + if ($in_column == 1) { + $in_column = 'firstname'; + } + $in_hotpot_path = Database::escape_string($in_hotpot_path); + $in_direction = Database::escape_string($in_direction); + $in_column = Database::escape_string($in_column); + $in_number_of_items = intval($in_number_of_items); + $in_from = intval($in_from); + + $TBL_TRACK_HOTPOTATOES = Database:: get_statistic_table( + TABLE_STATISTIC_TRACK_E_HOTPOTATOES + ); + $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER); + + $sql = "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp + JOIN $TBL_USER u ON thp.exe_user_id = u.user_id + WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'"; + + // just count how many answers + if ($in_get_count) { + $res = Database::query($sql); + return Database::num_rows($res); + } + // get a number of sorted results + $sql .= " $where_condition + ORDER BY $in_column $in_direction + LIMIT $in_from, $in_number_of_items"; + + $res = Database::query($sql); + $result = array(); + $apiIsAllowedToEdit = api_is_allowed_to_edit(); + $urlBase = api_get_path( + WEB_CODE_PATH + ) . 'exercice/hotpotatoes_exercise_report.php?action=delete&' . api_get_cidreq( + ) . '&id='; + while ($data = Database::fetch_array($res)) { + $actions = null; + + if ($apiIsAllowedToEdit) { + $url = $urlBase . $data['id'] . '&path=' . $data['exe_name']; + $actions = Display::url( + Display::return_icon('delete.png', get_lang('Delete')), + $url + ); + } + + $result[] = array( + 'firstname' => $data['firstname'], + 'lastname' => $data['lastname'], + 'username' => $data['username'], + 'group_name' => implode( + "
", + GroupManager::get_user_group_name($data['user_id']) + ), + 'exe_date' => $data['exe_date'], + 'score' => $data['exe_result'] . ' / ' . $data['exe_weighting'], + 'actions' => $actions, + ); + } + + return $result; + } + + /** + * @param string $exercisePath + * @param int $userId + * @param int $courseId + * @param int $sessionId + * + * @return array + */ + public static function getLatestHotPotatoResult( + $exercisePath, + $userId, + $courseId, + $sessionId + ) { + $table = Database:: get_statistic_table( + TABLE_STATISTIC_TRACK_E_HOTPOTATOES + ); + + $courseInfo = api_get_course_info_by_id($courseId); + $courseCode = $courseInfo['code']; + $exercisePath = Database::escape_string($exercisePath); + $userId = intval($userId); + + $sql = "SELECT * FROM $table + WHERE + exe_cours_id = '$courseCode' AND + exe_name LIKE '$exercisePath%' AND + exe_user_id = $userId + ORDER BY id + LIMIT 1"; + $result = Database::query($sql); + $attempt = array(); + if (Database::num_rows($result)) { + $attempt = Database::fetch_array($result, 'ASSOC'); + } + return $attempt; + } + + /** + * Gets the exam'data results + * @todo this function should be moved in a library + no global calls + * @param int $from + * @param int $number_of_items + * @param int $column + * @param string $direction + * @param int $exercise_id + * @param null $extra_where_conditions + * @param bool $get_count + * @return array + */ + public static function get_exam_results_data( + $from, + $number_of_items, + $column, + $direction, + $exercise_id, + $extra_where_conditions = null, + $get_count = false + ) { + //@todo replace all this globals + global $documentPath, $filter; + + $course_id = api_get_course_int_id(); + $course_code = api_get_course_id(); + $sessionId = api_get_session_id(); + + $is_allowedToEdit = api_is_allowed_to_edit( + null, + true + ) || api_is_allowed_to_edit(true) || api_is_drh( + ) || api_is_student_boss(); + + $TBL_USER = Database:: get_main_table(TABLE_MAIN_USER); + $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST); + $TBL_GROUP_REL_USER = Database:: get_course_table(TABLE_GROUP_USER); + $TBL_GROUP = Database:: get_course_table(TABLE_GROUP); + $TBL_TRACK_EXERCICES = Database:: get_statistic_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $TBL_TRACK_HOTPOTATOES = Database:: get_statistic_table( + TABLE_STATISTIC_TRACK_E_HOTPOTATOES + ); + $TBL_TRACK_ATTEMPT_RECORDING = Database:: get_statistic_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING + ); + + $session_id_and = ' AND te.session_id = ' . $sessionId . ' '; + $exercise_id = intval($exercise_id); + + $exercise_where = ''; + if (!empty($exercise_id)) { + $exercise_where .= ' AND te.exe_exo_id = ' . $exercise_id . ' '; + } + + $hotpotatoe_where = ''; + if (!empty($_GET['path'])) { + $hotpotatoe_path = Database::escape_string($_GET['path']); + $hotpotatoe_where .= ' AND exe_name = "' . $hotpotatoe_path . '" '; + } + + // sql for chamilo-type tests for teacher / tutor view + $sql_inner_join_tbl_track_exercices = " ( + SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised + FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr + ON (ttte.exe_id = tr.exe_id) + WHERE + exe_cours_id = '$course_code' AND + exe_exo_id = $exercise_id AND + ttte.session_id = " . $sessionId . " + )"; + if ($is_allowedToEdit) { + //Teacher view + if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') { + //$exercise_where_query = ' te.exe_exo_id = ce.id AND '; + } + + $sqlFromOption = ""; + $sqlWhereOption = ""; // for hpsql + + //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries + + //Hack in order to filter groups + $sql_inner_join_tbl_user = ''; + + if (strpos($extra_where_conditions, 'group_id')) { + $sql_inner_join_tbl_user = " + ( + SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id + FROM $TBL_USER u + INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . ") + INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=" . $course_id . ") + )"; + } + + if (strpos($extra_where_conditions, 'group_all')) { + + $extra_where_conditions = str_replace( + "AND ( group_id = 'group_all' )", + '', + $extra_where_conditions + ); + $extra_where_conditions = str_replace( + "AND group_id = 'group_all'", + '', + $extra_where_conditions + ); + $extra_where_conditions = str_replace( + "group_id = 'group_all' AND", + '', + $extra_where_conditions + ); + + $sql_inner_join_tbl_user = " + ( + SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id + FROM $TBL_USER u + )"; + $sql_inner_join_tbl_user = null; + } + + if (strpos($extra_where_conditions, 'group_none')) { + $extra_where_conditions = str_replace( + "AND ( group_id = 'group_none' )", + "AND ( group_id is null )", + $extra_where_conditions + ); + $extra_where_conditions = str_replace( + "AND group_id = 'group_none'", + "AND ( group_id is null )", + $extra_where_conditions + ); + $sql_inner_join_tbl_user = " + ( + SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id + FROM $TBL_USER u + LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=" . $course_id . " ) + LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = " . $course_id . ") + )"; + } + + // All + $is_empty_sql_inner_join_tbl_user = false; + + if (empty($sql_inner_join_tbl_user)) { + $is_empty_sql_inner_join_tbl_user = true; + $sql_inner_join_tbl_user = " + ( + SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id, official_code + FROM $TBL_USER u + WHERE u.status NOT IN(" . api_get_users_status_ignored_in_reports( + 'string' + ) . ") + )"; + } + + $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru "; + $sqlWhereOption = " AND gru.c_id = " . api_get_course_int_id( + ) . " AND gru.user_id = user.user_id "; + + $first_and_last_name = api_is_western_name_order( + ) ? "firstname, lastname" : "lastname, firstname"; + + if ($get_count) { + $sql_select = "SELECT count(te.exe_id) "; + } else { + $sql_select = "SELECT DISTINCT + user_id, + $first_and_last_name, + official_code, + ce.title, + username, + te.exe_result, + te.exe_weighting, + te.exe_date, + te.exe_id, + email as exemail, + te.start_date, + steps_counter, + exe_user_id, + te.exe_duration, + propagate_neg, + revised, + group_name, + group_id, + orig_lp_id"; + } + + $sql = " $sql_select + FROM $TBL_EXERCICES AS ce + INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id) + INNER JOIN $sql_inner_join_tbl_user AS user ON (user.user_id = exe_user_id) + WHERE + te.status != 'incomplete' AND + te.exe_cours_id='" . api_get_course_id() . "' $session_id_and AND + ce.active <>-1 AND ce.c_id=" . api_get_course_int_id() . " + $exercise_where + $extra_where_conditions + "; + + // sql for hotpotatoes tests for teacher / tutor view + + if ($get_count) { + $hpsql_select = "SELECT count(username)"; + } else { + $hpsql_select = "SELECT + $first_and_last_name , + username, + official_code, + tth.exe_name, + tth.exe_result , + tth.exe_weighting, + tth.exe_date"; + } + + $hpsql = " $hpsql_select + FROM + $TBL_TRACK_HOTPOTATOES tth, + $TBL_USER user + $sqlFromOption + WHERE + user.user_id=tth.exe_user_id + AND tth.exe_cours_id = '" . api_get_course_id() . "' + $hotpotatoe_where + $sqlWhereOption + AND user.status NOT IN(" . api_get_users_status_ignored_in_reports( + 'string' + ) . ") + ORDER BY + tth.exe_cours_id ASC, + tth.exe_date DESC"; + } + + if ($get_count) { + $resx = Database::query($sql); + $rowx = Database::fetch_row($resx, 'ASSOC'); + + return $rowx[0]; + } + + $teacher_list = CourseManager::get_teacher_list_from_course_code( + api_get_course_id() + ); + $teacher_id_list = array(); + foreach ($teacher_list as $teacher) { + $teacher_id_list[] = $teacher['user_id']; + } + + $list_info = array(); + + // Simple exercises + if (empty($hotpotatoe_where)) { + $column = !empty($column) ? Database::escape_string($column) : null; + $from = intval($from); + $number_of_items = intval($number_of_items); + + if (!empty($column)) { + $sql .= " ORDER BY $column $direction "; + } + $sql .= " LIMIT $from, $number_of_items"; + + $results = array(); + $resx = Database::query($sql); + while ($rowx = Database::fetch_array($resx, 'ASSOC')) { + $results[] = $rowx; + } + + $group_list = GroupManager::get_group_list(); + $clean_group_list = array(); + + if (!empty($group_list)) { + foreach ($group_list as $group) { + $clean_group_list[$group['id']] = $group['name']; + } + } + + $lp_list_obj = new LearnpathList(api_get_user_id()); + $lp_list = $lp_list_obj->get_flat_list(); + + if (is_array($results)) { + + $users_array_id = array(); + $from_gradebook = false; + if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') { + $from_gradebook = true; + } + $sizeof = count($results); + + $user_list_id = array(); + $locked = api_resource_is_locked_by_gradebook( + $exercise_id, + LINK_EXERCISE + ); + + // Looping results + for ($i = 0; $i < $sizeof; $i++) { + $revised = $results[$i]['revised']; + + if ($from_gradebook && ($is_allowedToEdit)) { + if (in_array( + $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], + $users_array_id + )) { + continue; + } + $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname']; + } + + $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null; + $lp_name = null; + + if ($lp_obj) { + $url = api_get_path( + WEB_CODE_PATH + ) . 'newscorm/lp_controller.php?' . api_get_cidreq( + ) . '&action=view&lp_id=' . $results[$i]['orig_lp_id']; + $lp_name = Display::url( + $lp_obj['lp_name'], + $url, + array('target' => '_blank') + ); + } + + //Add all groups by user + $group_name_list = null; + + if ($is_empty_sql_inner_join_tbl_user) { + $group_list = GroupManager::get_group_ids( + api_get_course_int_id(), + $results[$i]['user_id'] + ); + + foreach ($group_list as $id) { + $group_name_list .= $clean_group_list[$id] . '
'; + } + $results[$i]['group_name'] = $group_name_list; + } + + $results[$i]['exe_duration'] = !empty($results[$i]['exe_duration']) ? round( + $results[$i]['exe_duration'] / 60 + ) : 0; + + $user_list_id[] = $results[$i]['exe_user_id']; + $id = $results[$i]['exe_id']; + + $dt = api_convert_and_format_date( + $results[$i]['exe_weighting'] + ); + + // we filter the results if we have the permission to + if (isset($results[$i]['results_disabled'])) { + $result_disabled = intval( + $results[$i]['results_disabled'] + ); + } else { + $result_disabled = 0; + } + + if ($result_disabled == 0) { + $my_res = $results[$i]['exe_result']; + $my_total = $results[$i]['exe_weighting']; + + $results[$i]['start_date'] = api_get_local_time( + $results[$i]['start_date'] + ); + $results[$i]['exe_date'] = api_get_local_time( + $results[$i]['exe_date'] + ); + + if (!$results[$i]['propagate_neg'] && $my_res < 0) { + $my_res = 0; + } + + $score = self::show_score($my_res, $my_total); + + $actions = ''; + if ($is_allowedToEdit) { + if (isset($teacher_id_list)) { + if (in_array( + $results[$i]['exe_user_id'], + $teacher_id_list + )) { + $actions .= Display::return_icon( + 'teachers.gif', + get_lang('Teacher') + ); + } + } + if ($revised) { + $actions .= "" . + Display:: return_icon( + 'edit.png', + get_lang('Edit'), + array(), + ICON_SIZE_SMALL + ); + $actions .= ' '; + } else { + $actions .= "" . + Display:: return_icon( + 'quiz.gif', + get_lang('Qualify') + ); + $actions .= ' '; + } + $actions .= ""; + + if ($filter == 2) { + $actions .= ' ' . + Display:: return_icon( + 'history.gif', + get_lang('ViewHistoryChange') + ) . ''; + } + + //Admin can always delete the attempt + if (($locked == false || api_is_platform_admin( + )) && !api_is_student_boss() + ) { + $ip = TrackingUserLog::get_ip_from_user_event( + $results[$i]['exe_user_id'], + date('Y-m-d h:i:s'), + false + ); + $actions .= ''; + + $delete_link = '' . Display:: return_icon( + 'delete.png', + get_lang('Delete') + ) . ''; + $delete_link = utf8_encode($delete_link); + + if (api_is_drh() && !api_is_platform_admin()) { + $delete_link = null; + } + $actions .= $delete_link . ' '; + } + + } else { + $attempt_url = api_get_path( + WEB_CODE_PATH + ) . 'exercice/result.php?' . api_get_cidreq( + ) . '&id=' . $results[$i]['exe_id'] . '&id_session=' . $sessionId . '&height=500&width=750'; + $attempt_link = Display::url( + get_lang('Show'), + $attempt_url, + array('class' => 'ajax btn') + ); + $actions .= $attempt_link; + } + + if ($revised) { + $revised = Display::label( + get_lang('Validated'), + 'success' + ); + } else { + $revised = Display::label( + get_lang('NotValidated'), + 'info' + ); + } + + if ($is_allowedToEdit) { + $results[$i]['status'] = $revised; + $results[$i]['score'] = $score; + $results[$i]['lp'] = $lp_name; + $results[$i]['actions'] = $actions; + $list_info[] = $results[$i]; + } else { + $results[$i]['status'] = $revised; + $results[$i]['score'] = $score; + $results[$i]['actions'] = $actions; + $list_info[] = $results[$i]; + } + } + } + } + } else { + $hpresults = getManyResultsXCol($hpsql, 6); + // Print HotPotatoes test results. + if (is_array($hpresults)) { + for ($i = 0; $i < sizeof($hpresults); $i++) { + $hp_title = GetQuizName($hpresults[$i][3], $documentPath); + if ($hp_title == '') { + $hp_title = basename($hpresults[$i][3]); + } + + $hp_date = api_get_local_time( + $hpresults[$i][6], + null, + date_default_timezone_get() + ); + $hp_result = round( + ($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, + 2 + ) . '% (' . $hpresults[$i][4] . ' / ' . $hpresults[$i][5] . ')'; + if ($is_allowedToEdit) { + $list_info[] = array( + $hpresults[$i][0], + $hpresults[$i][1], + $hpresults[$i][2], + '', + $hp_title, + '-', + $hp_date, + $hp_result, + '-' + ); + } else { + $list_info[] = array( + $hp_title, + '-', + $hp_date, + $hp_result, + '-' + ); + } + } + } + } + + return $list_info; + } + + /** + * Converts the score with the exercise_max_note and exercise_min_score + * the platform settings + formats the results using the float_format function + * + * @param float $score + * @param float $weight + * @param bool $show_percentage show percentage or not + * @param bool $use_platform_settings use or not the platform settings + * @param bool $show_only_percentage + * @return string an html with the score modified + */ + public static function show_score( + $score, + $weight, + $show_percentage = true, + $use_platform_settings = true, + $show_only_percentage = false + ) { + if (is_null($score) && is_null($weight)) { + return '-'; + } + + $max_note = api_get_setting('exercise_max_score'); + $min_note = api_get_setting('exercise_min_score'); + + if ($use_platform_settings) { + if ($max_note != '' && $min_note != '') { + if (!empty($weight) && intval($weight) != 0) { + $score = $min_note + ($max_note - $min_note) * $score / $weight; + } else { + $score = $min_note; + } + $weight = $max_note; + } + } + $percentage = (100 * $score) / ($weight != 0 ? $weight : 1); + + // Formats values + $percentage = float_format($percentage, 1); + $score = float_format($score, 1); + $weight = float_format($weight, 1); + + $html = null; + if ($show_percentage) { + $parent = '(' . $score . ' / ' . $weight . ')'; + $html = $percentage . "% $parent"; + if ($show_only_percentage) { + $html = $percentage . "% "; + } + } else { + $html = $score . ' / ' . $weight; + } + $html = Display::span($html, array('class' => 'score_exercise')); + + return $html; + } + + /** + * @param float $score + * @param float $weight + * @param string $pass_percentage + * @return bool + */ + public static function is_success_exercise_result($score, $weight, $pass_percentage) + { + $percentage = float_format( + ($score / ($weight != 0 ? $weight : 1)) * 100, + 1 + ); + if (isset($pass_percentage) && !empty($pass_percentage)) { + if ($percentage >= $pass_percentage) { + return true; + } + } + return false; + } + + /** + * @param float $score + * @param float $weight + * @param string $pass_percentage + * @return string + */ + public static function show_success_message($score, $weight, $pass_percentage) + { + $res = ""; + if (self::is_pass_pourcentage_enabled($pass_percentage)) { + $is_success = self::is_success_exercise_result( + $score, + $weight, + $pass_percentage + ); + + if ($is_success) { + $html = get_lang('CongratulationsYouPassedTheTest'); + $icon = Display::return_icon( + 'completed.png', + get_lang('Correct'), + array(), + ICON_SIZE_MEDIUM + ); + } else { + //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning'); + $html = get_lang('YouDidNotReachTheMinimumScore'); + $icon = Display::return_icon( + 'warning.png', + get_lang('Wrong'), + array(), + ICON_SIZE_MEDIUM + ); + } + $html = Display::tag('h4', $html); + $html .= Display::tag( + 'h5', + $icon, + array('style' => 'width:40px; padding:2px 10px 0px 0px') + ); + $res = $html; + } + return $res; + } + + /** + * Return true if pass_pourcentage activated (we use the pass pourcentage feature + * return false if pass_percentage = 0 (we don't use the pass pourcentage feature + * @param $in_pass_pourcentage + * @return boolean + * In this version, pass_percentage and show_success_message are disabled if + * pass_percentage is set to 0 + */ + public static function is_pass_pourcentage_enabled($in_pass_pourcentage) + { + return $in_pass_pourcentage > 0; + } + + /** + * Converts a numeric value in a percentage example 0.66666 to 66.67 % + * @param $value + * @return float Converted number + */ + public static function convert_to_percentage($value) + { + $return = '-'; + if ($value != '') { + $return = float_format($value * 100, 1) . ' %'; + } + return $return; + } + + /** + * Converts a score/weight values to the platform scale + * @param float $score + * @param float $weight + * @deprecated seem not to be used + * @return float the score rounded converted to the new range + */ + public static function convert_score($score, $weight) + { + $max_note = api_get_setting('exercise_max_score'); + $min_note = api_get_setting('exercise_min_score'); + + if ($score != '' && $weight != '') { + if ($max_note != '' && $min_note != '') { + if (!empty($weight)) { + $score = $min_note + ($max_note - $min_note) * $score / $weight; + } else { + $score = $min_note; + } + } + } + $score_rounded = float_format($score, 1); + return $score_rounded; + } + + /** + * Getting all active exercises from a course from a session + * (if a session_id is provided we will show all the exercises in the course + + * all exercises in the session) + * @param array $course_info + * @param int $session_id + * @param boolean $check_publication_dates + * @param string $search Search exercise name + * @param boolean $search_all_sessions Search exercises in all sessions + * @param int 0 = only inactive exercises + * 1 = only active exercises, + * 2 = all exercises + * 3 = active <> -1 + * @return array array with exercise data + */ + public static function get_all_exercises( + $course_info = null, + $session_id = 0, + $check_publication_dates = false, + $search = '', + $search_all_sessions = false, + $active = 2 + ) { + $course_id = api_get_course_int_id(); + + if (!empty($course_info) && !empty($course_info['real_id'])) { + $course_id = $course_info['real_id']; + } + + if ($session_id == -1) { + $session_id = 0; + } + + $now = api_get_utc_datetime(); + $time_conditions = ''; + + if ($check_publication_dates) { + //start and end are set + $time_conditions = " AND ((start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now' ) OR "; + // only start is set + $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now' AND end_time = '0000-00-00 00:00:00') OR "; + // only end is set + $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now') OR "; + // nothing is set + $time_conditions .= " (start_time = '0000-00-00 00:00:00' AND end_time = '0000-00-00 00:00:00')) "; + } + + $needle_where = !empty($search) ? " AND title LIKE '?' " : ''; + $needle = !empty($search) ? "%" . $search . "%" : ''; + + // Show courses by active status + $active_sql = ''; + if ($active == 3) { + $active_sql = ' active <> -1 AND'; + } else { + if ($active != 2) { + $active_sql = sprintf(' active = %d AND', $active); + } + } + + if ($search_all_sessions == true) { + $conditions = array( + 'where' => array( + $active_sql . ' c_id = ? ' . $needle_where . $time_conditions => array( + $course_id, + $needle + ) + ), + 'order' => 'title' + ); + } else { + if ($session_id == 0) { + $conditions = array( + 'where' => array( + $active_sql . ' session_id = ? AND c_id = ? ' . $needle_where . $time_conditions => array( + $session_id, + $course_id, + $needle + ) + ), + 'order' => 'title' + ); + } else { + $conditions = array( + 'where' => array( + $active_sql . ' (session_id = 0 OR session_id = ? ) AND c_id = ? ' . $needle_where . $time_conditions => array( + $session_id, + $course_id, + $needle + ) + ), + 'order' => 'title' + ); + } + } + + $table = Database:: get_course_table(TABLE_QUIZ_TEST); + + return Database::select('*', $table, $conditions); + } + + /** + * Get exercise information by id + * @param int $exerciseId Exercise Id + * @param int $courseId The course ID (necessary as c_quiz.id is not unique) + * @return array Exercise info + */ + public static function get_exercise_by_id($exerciseId = 0, $courseId = null) + { + $TBL_EXERCICES = Database:: get_course_table(TABLE_QUIZ_TEST); + if (empty($courseId)) { + $courseId = api_get_course_int_id(); + } else { + $courseId = intval($courseId); + } + $conditions = array( + 'where' => array( + 'id = ?' => array($exerciseId), + ' AND c_id = ? ' => $courseId + ) + ); + + return Database::select('*', $TBL_EXERCICES, $conditions); + } + + /** + * Getting all exercises (active only or all) + * from a course from a session + * (if a session_id is provided we will show all the exercises in the + * course + all exercises in the session) + * @param array course data + * @param int session id + * @param int course c_id + * @param boolean $only_active_exercises + * @return array array with exercise data + * modified by Hubert Borderiou + */ + public static function get_all_exercises_for_course_id( + $course_info = null, + $session_id = 0, + $course_id = 0, + $only_active_exercises = true + ) { + $TBL_EXERCISES = Database:: get_course_table(TABLE_QUIZ_TEST); + + if ($only_active_exercises) { + // Only active exercises. + $sql_active_exercises = "active = 1 AND "; + } else { + // Not only active means visible and invisible NOT deleted (-2) + $sql_active_exercises = "active IN (1, 0) AND "; + } + + if ($session_id == -1) { + $session_id = 0; + } + + $params = array( + $session_id, + $course_id + ); + + if ($session_id == 0) { + $conditions = array( + 'where' => array("$sql_active_exercises session_id = ? AND c_id = ?" => $params), + 'order' => 'title' + ); + } else { + // All exercises + $conditions = array( + 'where' => array("$sql_active_exercises (session_id = 0 OR session_id = ? ) AND c_id=?" => $params), + 'order' => 'title' + ); + } + + return Database::select('*', $TBL_EXERCISES, $conditions); + } + + /** + * Gets the position of the score based in a given score (result/weight) + * and the exe_id based in the user list + * (NO Exercises in LPs ) + * @param float $my_score user score to be compared *attention* + * $my_score = score/weight and not just the score + * @param int $my_exe_id exe id of the exercise + * (this is necessary because if 2 students have the same score the one + * with the minor exe_id will have a best position, just to be fair and FIFO) + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * @param array $user_list + * @param bool $return_string + * + * @return int the position of the user between his friends in a course + * (or course within a session) + */ + public static function get_exercise_result_ranking( + $my_score, + $my_exe_id, + $exercise_id, + $course_code, + $session_id = 0, + $user_list = array(), + $return_string = true + ) { + //No score given we return + if (is_null($my_score)) { + return '-'; + } + if (empty($user_list)) { + return '-'; + } + + $best_attempts = array(); + foreach ($user_list as $user_data) { + $user_id = $user_data['user_id']; + $best_attempts[$user_id] = self::get_best_attempt_by_user( + $user_id, + $exercise_id, + $course_code, + $session_id + ); + } + + if (empty($best_attempts)) { + return 1; + } else { + $position = 1; + $my_ranking = array(); + foreach ($best_attempts as $user_id => $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $my_ranking[$user_id] = $result['exe_result'] / $result['exe_weighting']; + } else { + $my_ranking[$user_id] = 0; + } + } + //if (!empty($my_ranking)) { + asort($my_ranking); + $position = count($my_ranking); + if (!empty($my_ranking)) { + foreach ($my_ranking as $user_id => $ranking) { + if ($my_score >= $ranking) { + if ($my_score == $ranking) { + $exe_id = $best_attempts[$user_id]['exe_id']; + if ($my_exe_id < $exe_id) { + $position--; + } + } else { + $position--; + } + } + } + } + //} + $return_value = array( + 'position' => $position, + 'count' => count($my_ranking) + ); + + if ($return_string) { + if (!empty($position) && !empty($my_ranking)) { + $return_value = $position . '/' . count($my_ranking); + } else { + $return_value = '-'; + } + } + return $return_value; + } + } + + /** + * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts + * (NO Exercises in LPs ) old functionality by attempt + * @param float user score to be compared attention => score/weight + * @param int exe id of the exercise + * (this is necessary because if 2 students have the same score the one + * with the minor exe_id will have a best position, just to be fair and FIFO) + * @param int exercise id + * @param string course code + * @param int session id + * @return int the position of the user between his friends in a course (or course within a session) + */ + public static function get_exercise_result_ranking_by_attempt( + $my_score, + $my_exe_id, + $exercise_id, + $course_code, + $session_id = 0, + $return_string = true + ) { + if (empty($session_id)) { + $session_id = 0; + } + if (is_null($my_score)) { + return '-'; + } + $user_results = Event::get_all_exercise_results( + $exercise_id, + $course_code, + $session_id, + false + ); + $position_data = array(); + if (empty($user_results)) { + return 1; + } else { + $position = 1; + $my_ranking = array(); + foreach ($user_results as $result) { + //print_r($result); + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $my_ranking[$result['exe_id']] = $result['exe_result'] / $result['exe_weighting']; + } else { + $my_ranking[$result['exe_id']] = 0; + } + } + asort($my_ranking); + $position = count($my_ranking); + if (!empty($my_ranking)) { + foreach ($my_ranking as $exe_id => $ranking) { + if ($my_score >= $ranking) { + if ($my_score == $ranking) { + if ($my_exe_id < $exe_id) { + $position--; + } + } else { + $position--; + } + } + } + } + $return_value = array( + 'position' => $position, + 'count' => count($my_ranking) + ); + + if ($return_string) { + if (!empty($position) && !empty($my_ranking)) { + return $position . '/' . count($my_ranking); + } + } + return $return_value; + } + } + + /** + * Get the best attempt in a exercise (NO Exercises in LPs ) + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * + * @return array + */ + public static function get_best_attempt_in_course($exercise_id, $course_code, $session_id) + { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $course_code, + $session_id, + false + ); + $best_score_data = array(); + $best_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $score = $result['exe_result'] / $result['exe_weighting']; + if ($score >= $best_score) { + $best_score = $score; + $best_score_data = $result; + } + } + } + } + return $best_score_data; + } + + /** + * Get the best score in a exercise (NO Exercises in LPs ) + * @param int $user_id + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * + * @return array + */ + public static function get_best_attempt_by_user( + $user_id, + $exercise_id, + $course_code, + $session_id + ) { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $course_code, + $session_id, + false, + $user_id + ); + $best_score_data = array(); + $best_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) { + $score = $result['exe_result'] / $result['exe_weighting']; + if ($score >= $best_score) { + $best_score = $score; + $best_score_data = $result; + } + } + } + } + + return $best_score_data; + } + + /** + * Get average score (NO Exercises in LPs ) + * @param int exercise id + * @param string course code + * @param int session id + * @return float Average score + */ + public static function get_average_score($exercise_id, $course_code, $session_id) + { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $course_code, + $session_id + ); + $avg_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $score = $result['exe_result'] / $result['exe_weighting']; + $avg_score += $score; + } + } + $avg_score = float_format($avg_score / count($user_results), 1); + } + + return $avg_score; + } + + /** + * Get average score by score (NO Exercises in LPs ) + * @param int exercise id + * @param string course code + * @param int session id + * @return float Average score + */ + public static function get_average_score_by_course($course_code, $session_id) + { + $user_results = Event::get_all_exercise_results_by_course( + $course_code, + $session_id, + false + ); + //echo $course_code.' - '.$session_id.'
'; + $avg_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $score = $result['exe_result'] / $result['exe_weighting']; + $avg_score += $score; + } + } + //We asume that all exe_weighting + //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); + $avg_score = ($avg_score / count($user_results)); + } + + return $avg_score; + } + + /** + * @param int $user_id + * @param string $course_code + * @param int $session_id + * + * @return float|int + */ + public static function get_average_score_by_course_by_user( + $user_id, + $course_code, + $session_id + ) { + $user_results = Event::get_all_exercise_results_by_user( + $user_id, + $course_code, + $session_id + ); + $avg_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $score = $result['exe_result'] / $result['exe_weighting']; + $avg_score += $score; + } + } + //We asume that all exe_weighting + //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); + $avg_score = ($avg_score / count($user_results)); + } + + return $avg_score; + } + + /** + * Get average score by score (NO Exercises in LPs ) + * @param int exercise id + * @param string course code + * @param int session id + * @return float Best average score + */ + public static function get_best_average_score_by_exercise( + $exercise_id, + $course_code, + $session_id, + $user_count + ) { + $user_results = Event::get_best_exercise_results_by_user( + $exercise_id, + $course_code, + $session_id + ); + $avg_score = 0; + if (!empty($user_results)) { + foreach ($user_results as $result) { + if (!empty($result['exe_weighting']) && intval( + $result['exe_weighting'] + ) != 0 + ) { + $score = $result['exe_result'] / $result['exe_weighting']; + $avg_score += $score; + } + } + //We asume that all exe_weighting + //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']); + //$avg_score = ($avg_score / count($user_results)); + if (!empty($user_count)) { + $avg_score = float_format($avg_score / $user_count, 1) * 100; + } else { + $avg_score = 0; + } + } + return $avg_score; + } + + /** + * @param string $course_code + * @param int $session_id + * + * @return array + */ + public static function get_exercises_to_be_taken($course_code, $session_id) + { + $course_info = api_get_course_info($course_code); + $exercises = self::get_all_exercises($course_info, $session_id); + $result = array(); + $now = time() + 15 * 24 * 60 * 60; + foreach ($exercises as $exercise_item) { + if (isset($exercise_item['end_time']) && + !empty($exercise_item['end_time']) && + $exercise_item['end_time'] != '0000-00-00 00:00:00' && + api_strtotime($exercise_item['end_time'], 'UTC') < $now + ) { + $result[] = $exercise_item; + } + } + return $result; + } + + /** + * Get student results (only in completed exercises) stats by question + * @param int $question_id + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * + **/ + public static function get_student_stats_by_question( + $question_id, + $exercise_id, + $course_code, + $session_id + ) { + $track_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_attempt = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + + $question_id = intval($question_id); + $exercise_id = intval($exercise_id); + $course_code = Database::escape_string($course_code); + $session_id = intval($session_id); + + $sql = "SELECT MAX(marks) as max, MIN(marks) as min, AVG(marks) as average + FROM $track_exercises e + INNER JOIN $track_attempt a + ON ( + a.exe_id = e.exe_id AND + e.exe_cours_id = a.course_code AND + e.session_id = a.session_id + ) + WHERE + exe_exo_id = $exercise_id AND + course_code = '$course_code' AND + e.session_id = $session_id AND + question_id = $question_id AND + status = '' + LIMIT 1"; + $result = Database::query($sql); + $return = array(); + if ($result) { + $return = Database::fetch_array($result, 'ASSOC'); + } + + return $return; + } + + /** + * @param int $question_id + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * @return int + */ + public static function get_number_students_question_with_answer_count( + $question_id, + $exercise_id, + $course_code, + $session_id + ) { + $track_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_attempt = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); + $courseUserSession = Database::get_main_table( + TABLE_MAIN_SESSION_COURSE_USER + ); + + $question_id = intval($question_id); + $exercise_id = intval($exercise_id); + $course_code = Database::escape_string($course_code); + $session_id = intval($session_id); + + if (empty($session_id)) { + $courseCondition = " + INNER JOIN $courseUser cu + ON cu.course_code = a.course_code AND cu.user_id = exe_user_id"; + $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT; + } else { + $courseCondition = " + INNER JOIN $courseUserSession cu + ON cu.course_code = a.course_code AND cu.id_user = exe_user_id"; + $courseConditionWhere = " AND cu.status = 0 "; + } + + $sql = "SELECT DISTINCT exe_user_id + FROM $track_exercises e + INNER JOIN $track_attempt a + ON ( + a.exe_id = e.exe_id AND + e.exe_cours_id = a.course_code AND + e.session_id = a.session_id + ) + $courseCondition + WHERE + exe_exo_id = $exercise_id AND + a.course_code = '$course_code' AND + e.session_id = $session_id AND + question_id = $question_id AND + answer <> '0' AND + e.status = '' + $courseConditionWhere + "; + $result = Database::query($sql); + $return = 0; + if ($result) { + $return = Database::num_rows($result); + } + return $return; + } + + /** + * @param int $answer_id + * @param int $question_id + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * + * @return int + */ + public static function get_number_students_answer_hotspot_count( + $answer_id, + $question_id, + $exercise_id, + $course_code, + $session_id + ) { + $track_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_hotspot = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_HOTSPOT + ); + $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); + $courseUserSession = Database::get_main_table( + TABLE_MAIN_SESSION_COURSE_USER + ); + + $question_id = intval($question_id); + $answer_id = intval($answer_id); + $exercise_id = intval($exercise_id); + $course_code = Database::escape_string($course_code); + $session_id = intval($session_id); + + if (empty($session_id)) { + $courseCondition = " + INNER JOIN $courseUser cu + ON cu.course_code = a.hotspot_course_code AND cu.user_id = exe_user_id"; + $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT; + } else { + $courseCondition = " + INNER JOIN $courseUserSession cu + ON cu.course_code = a.hotspot_course_code AND cu.id_user = exe_user_id"; + $courseConditionWhere = " AND cu.status = 0 "; + } + + $sql = "SELECT DISTINCT exe_user_id + FROM $track_exercises e + INNER JOIN $track_hotspot a + ON (a.hotspot_exe_id = e.exe_id) + $courseCondition + WHERE + exe_exo_id = $exercise_id AND + a.hotspot_course_code = '$course_code' AND + e.session_id = $session_id AND + hotspot_answer_id = $answer_id AND + hotspot_question_id = $question_id AND + hotspot_correct = 1 AND + e.status = '' + $courseConditionWhere + "; + + $result = Database::query($sql); + $return = 0; + if ($result) { + $return = Database::num_rows($result); + } + return $return; + } + + /** + * @param int $answer_id + * @param int $question_id + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * @param string $question_type + * @param string $correct_answer + * @param string $current_answer + * @return int + */ + public static function get_number_students_answer_count( + $answer_id, + $question_id, + $exercise_id, + $course_code, + $session_id, + $question_type = null, + $correct_answer = null, + $current_answer = null + ) { + $track_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_attempt = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + $courseUser = Database::get_main_table(TABLE_MAIN_COURSE_USER); + $courseUserSession = Database::get_main_table( + TABLE_MAIN_SESSION_COURSE_USER + ); + + $question_id = intval($question_id); + $answer_id = intval($answer_id); + $exercise_id = intval($exercise_id); + $course_code = Database::escape_string($course_code); + $session_id = intval($session_id); + + switch ($question_type) { + case FILL_IN_BLANKS: + $answer_condition = ""; + $select_condition = " e.exe_id, answer "; + break; + case MATCHING: + default: + $answer_condition = " answer = $answer_id AND "; + $select_condition = " DISTINCT exe_user_id "; + } + + if (empty($session_id)) { + $courseCondition = " + INNER JOIN $courseUser cu + ON cu.course_code = a.course_code AND cu.user_id = exe_user_id"; + $courseConditionWhere = " AND relation_type <> 2 AND cu.status = " . STUDENT; + } else { + $courseCondition = " + INNER JOIN $courseUserSession cu + ON cu.course_code = a.course_code AND cu.id_user = exe_user_id"; + $courseConditionWhere = " AND cu.status = 0 "; + } + + $sql = "SELECT $select_condition + FROM $track_exercises e + INNER JOIN $track_attempt a + ON ( + a.exe_id = e.exe_id AND + e.exe_cours_id = a.course_code AND + e.session_id = a.session_id + ) + $courseCondition + WHERE + exe_exo_id = $exercise_id AND + a.course_code = '$course_code' AND + e.session_id = $session_id AND + $answer_condition + question_id = $question_id AND + e.status = '' + $courseConditionWhere + "; + $result = Database::query($sql); + $return = 0; + if ($result) { + $good_answers = 0; + switch ($question_type) { + case FILL_IN_BLANKS: + while ($row = Database::fetch_array($result, 'ASSOC')) { + $fill_blank = self::check_fill_in_blanks( + $correct_answer, + $row['answer'] + ); + if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1) { + $good_answers++; + } + } + return $good_answers; + break; + case MATCHING: + default: + $return = Database::num_rows($result); + } + } + + return $return; + } + + /** + * @param array $answer + * @param string $user_answer + * @return array + */ + public static function check_fill_in_blanks($answer, $user_answer) + { + // the question is encoded like this + // [A] B [C] D [E] F::10,10,10@1 + // number 1 before the "@" means that is a switchable fill in blank question + // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10 + // means that is a normal fill blank question + // first we explode the "::" + $pre_array = explode('::', $answer); + // is switchable fill blank or not + $last = count($pre_array) - 1; + $is_set_switchable = explode('@', $pre_array[$last]); + $switchable_answer_set = false; + if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) { + $switchable_answer_set = true; + } + $answer = ''; + for ($k = 0; $k < $last; $k++) { + $answer .= $pre_array[$k]; + } + // splits weightings that are joined with a comma + $answerWeighting = explode(',', $is_set_switchable[0]); + + // we save the answer because it will be modified + //$temp = $answer; + $temp = $answer; + + $answer = ''; + $j = 0; + //initialise answer tags + $user_tags = $correct_tags = $real_text = array(); + // the loop will stop at the end of the text + while (1) { + // quits the loop if there are no more blanks (detect '[') + if (($pos = api_strpos($temp, '[')) === false) { + // adds the end of the text + $answer = $temp; + /* // Deprecated code + // TeX parsing - replacement of texcode tags + $texstring = api_parse_tex($texstring); + $answer = str_replace("{texcode}", $texstring, $answer); + */ + $real_text[] = $answer; + break; //no more "blanks", quit the loop + } + // adds the piece of text that is before the blank + //and ends with '[' into a general storage array + $real_text[] = api_substr($temp, 0, $pos + 1); + $answer .= api_substr($temp, 0, $pos + 1); + //take the string remaining (after the last "[" we found) + $temp = api_substr($temp, $pos + 1); + // quit the loop if there are no more blanks, and update $pos to the position of next ']' + if (($pos = api_strpos($temp, ']')) === false) { + // adds the end of the text + $answer .= $temp; + break; + } + + $str = $user_answer; + + preg_match_all('#\[([^[]*)\]#', $str, $arr); + $str = str_replace('\r\n', '', $str); + $choice = $arr[1]; + + $tmp = api_strrpos($choice[$j], ' / '); + $choice[$j] = api_substr($choice[$j], 0, $tmp); + $choice[$j] = trim($choice[$j]); + + //Needed to let characters ' and " to work as part of an answer + $choice[$j] = stripslashes($choice[$j]); + + $user_tags[] = api_strtolower($choice[$j]); + //put the contents of the [] answer tag into correct_tags[] + $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos)); + $j++; + $temp = api_substr($temp, $pos + 1); + } + + $answer = ''; + $real_correct_tags = $correct_tags; + $chosen_list = array(); + $good_answer = array(); + + for ($i = 0; $i < count($real_correct_tags); $i++) { + if (!$switchable_answer_set) { + //needed to parse ' and " characters + $user_tags[$i] = stripslashes($user_tags[$i]); + if ($correct_tags[$i] == $user_tags[$i]) { + $good_answer[$correct_tags[$i]] = 1; + } elseif (!empty ($user_tags[$i])) { + $good_answer[$correct_tags[$i]] = 0; + } else { + $good_answer[$correct_tags[$i]] = 0; + } + } else { + // switchable fill in the blanks + if (in_array($user_tags[$i], $correct_tags)) { + $correct_tags = array_diff($correct_tags, $chosen_list); + $good_answer[$correct_tags[$i]] = 1; + } elseif (!empty ($user_tags[$i])) { + $good_answer[$correct_tags[$i]] = 0; + } else { + $good_answer[$correct_tags[$i]] = 0; + } + } + // adds the correct word, followed by ] to close the blank + $answer .= ' / ' . $real_correct_tags[$i] . ']'; + if (isset ($real_text[$i + 1])) { + $answer .= $real_text[$i + 1]; + } + } + + return $good_answer; + } + + /** + * @param int $exercise_id + * @param string $course_code + * @param int $session_id + * @return int + */ + public static function get_number_students_finish_exercise( + $exercise_id, + $course_code, + $session_id + ) { + $track_exercises = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $track_attempt = Database::get_main_table( + TABLE_STATISTIC_TRACK_E_ATTEMPT + ); + + $exercise_id = intval($exercise_id); + $course_code = Database::escape_string($course_code); + $session_id = intval($session_id); + + $sql = "SELECT DISTINCT exe_user_id + FROM $track_exercises e + INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) + WHERE + exe_exo_id = $exercise_id AND + course_code = '$course_code' AND + e.session_id = $session_id AND + status = ''"; + $result = Database::query($sql); + $return = 0; + if ($result) { + $return = Database::num_rows($result); + + } + return $return; + } + + /** + * @param string $in_name is the name and the id of the + */ + public static function displayGroupMenu($in_name, $in_default, $in_onchange = "") + { + // check the default value of option + $tabSelected = array($in_default => " selected='selected' "); + $res = ""; + $res .= ""; + return $res; + } + + + /** + * Return a list of group for user with user_id=in_userid separated with in_separator + * @deprecated ? + */ + public static function displayGroupsForUser($in_separator, $in_userid) + { + $res = implode( + $in_separator, + GroupManager::get_user_group_name($in_userid) + ); + if ($res == "") { + $res = "
-
"; + } + return $res; + } + + public static function create_chat_exercise_session($exe_id) + { + if (!isset($_SESSION['current_exercises'])) { + $_SESSION['current_exercises'] = array(); + } + $_SESSION['current_exercises'][$exe_id] = true; + } + + public static function delete_chat_exercise_session($exe_id) + { + if (isset($_SESSION['current_exercises'])) { + $_SESSION['current_exercises'][$exe_id] = false; + } + } + + /** + * Display the exercise results + * @param Exercise $objExercise + * @param int $exe_id + * @param bool $save_user_result save users results (true) or just show the results (false) + */ + public static function display_question_list_by_attempt( + $objExercise, + $exe_id, + $save_user_result = false + ) { + global $origin; + + // Getting attempt info + $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id( + $exe_id + ); + + // Getting question list + $question_list = array(); + if (!empty($exercise_stat_info['data_tracking'])) { + $question_list = explode(',', $exercise_stat_info['data_tracking']); + } else { + // Try getting the question list only if save result is off + if ($save_user_result == false) { + $question_list = $objExercise->get_validated_question_list(); + } + } + + $counter = 1; + $total_score = $total_weight = 0; + + $exercise_content = null; + + // Hide results + $show_results = false; + $show_only_score = false; + + if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) { + $show_results = true; + } + + if (in_array( + $objExercise->results_disabled, + array( + RESULT_DISABLE_SHOW_SCORE_ONLY, + RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES + ) + ) + ) { + $show_only_score = true; + } + + // Not display expected answer, but score, and feedback + $show_all_but_expected_answer = false; + if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY && + $objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END + ) { + $show_all_but_expected_answer = true; + $show_results = true; + $show_only_score = false; + } + + if ($show_results || $show_only_score) { + $user_info = api_get_user_info($exercise_stat_info['exe_user_id']); + //Shows exercise header + echo $objExercise->show_exercise_result_header( + $user_info, + api_convert_and_format_date( + $exercise_stat_info['start_date'], + DATE_TIME_FORMAT_LONG + ), + $exercise_stat_info['duration'] + ); + } + + // Display text when test is finished #4074 and for LP #4227 + $end_of_message = $objExercise->selectTextWhenFinished(); + if (!empty($end_of_message)) { + Display::display_normal_message($end_of_message, false); + echo "
 
"; + } + + $question_list_answers = array(); + $media_list = array(); + $category_list = array(); + + // Loop over all question to show results for each of them, one by one + if (!empty($question_list)) { + foreach ($question_list as $questionId) { + + // creates a temporary Question object + $objQuestionTmp = Question::read($questionId); + + // This variable came from exercise_submit_modal.php + ob_start(); + + // We're inside *one* question. Go through each possible answer for this question + $result = $objExercise->manage_answer( + $exercise_stat_info['exe_id'], + $questionId, + null, + 'exercise_result', + array(), + $save_user_result, + true, + $show_results, + $objExercise->selectPropagateNeg(), + array() + ); + + if (empty($result)) { + continue; + } + + // In case of global score, make sure the calculated total score is integer + /*if (!is_int($result['score'])) { + $result['score'] = round($result['score']); + }*/ + + $total_score += $result['score']; + $total_weight += $result['weight']; + + $question_list_answers[] = array( + 'question' => $result['open_question'], + 'answer' => $result['open_answer'], + 'answer_type' => $result['answer_type'] + ); + + $my_total_score = $result['score']; + $my_total_weight = $result['weight']; + + // Category report + $category_was_added_for_this_test = false; + + if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) { + $category_list[$objQuestionTmp->category]['score'] += $my_total_score; + $category_list[$objQuestionTmp->category]['total'] += $my_total_weight; + $category_was_added_for_this_test = true; + } + + if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) { + foreach ($objQuestionTmp->category_list as $category_id) { + $category_list[$category_id]['score'] += $my_total_score; + $category_list[$category_id]['total'] += $my_total_weight; + $category_was_added_for_this_test = true; + } + } + + // No category for this question! + if ($category_was_added_for_this_test == false) { + if (!isset($category_list['none']['score'])) { + $category_list['none']['score'] = 0; + } + if (!isset($category_list['none']['total'])) { + $category_list['none']['total'] = 0; + } + + $category_list['none']['score'] += $my_total_score; + $category_list['none']['total'] += $my_total_weight; + } + + if ($objExercise->selectPropagateNeg( + ) == 0 && $my_total_score < 0 + ) { + $my_total_score = 0; + } + + $comnt = null; + if ($show_results) { + $comnt = Event::get_comments($exe_id, $questionId); + if (!empty($comnt)) { + echo '' . get_lang('Feedback') . ''; + echo '
' . $comnt . '
'; + } + } + + if ($show_results) { + $score = array( + 'result' => get_lang('Score') . " : " . self::show_score( + $my_total_score, + $my_total_weight, + false, + true + ), + 'pass' => $my_total_score >= $my_total_weight ? true : false, + 'score' => $my_total_score, + 'weight' => $my_total_weight, + 'comments' => $comnt, + ); + } else { + $score = array(); + } + + $contents = ob_get_clean(); + $question_content = '
'; + + if ($show_results) { + $show_media = false; + /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) { + $show_media = true; + $media_list[] = $objQuestionTmp->parent_id; + }*/ + //Shows question title an description + $question_content .= $objQuestionTmp->return_header( + null, + $counter, + $score + ); + } + $counter++; + + $question_content .= $contents; + $question_content .= '
'; + + $exercise_content .= $question_content; + + } // end foreach() block that loops over all questions + } + + $total_score_text = null; + + if ($origin != 'learnpath') { + if ($show_results || $show_only_score) { + $total_score_text .= '
'; + $total_score_text .= get_question_ribbon( + $objExercise, + $total_score, + $total_weight, + true + ); + $total_score_text .= '
'; + } + } + + if (!empty($category_list) && ($show_results || $show_only_score)) { + //Adding total + $category_list['total'] = array( + 'score' => $total_score, + 'total' => $total_weight + ); + echo Testcategory::get_stats_table_by_attempt( + $objExercise->id, + $category_list + ); + } + + if ($show_all_but_expected_answer) { + $exercise_content .= "
" . get_lang( + "ExerciseWithFeedbackWithoutCorrectionComment" + ) . "
"; + } + // Remove audio auto play from questions on results page - refs BT#7939 + $exercise_content = preg_replace( + '/autoplay[\=\".+\"]+/', + '', + $exercise_content + ); + + echo $total_score_text; + echo $exercise_content; + + if (!$show_only_score) { + echo $total_score_text; + } + + if ($save_user_result) { + + // Tracking of results + $learnpath_id = $exercise_stat_info['orig_lp_id']; + $learnpath_item_id = $exercise_stat_info['orig_lp_item_id']; + $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id']; + + if (api_is_allowed_to_session_edit()) { + Event::update_event_exercice( + $exercise_stat_info['exe_id'], + $objExercise->selectId(), + $total_score, + $total_weight, + api_get_session_id(), + $learnpath_id, + $learnpath_item_id, + $learnpath_item_view_id, + $exercise_stat_info['exe_duration'], + $question_list, + '', + array() + ); + } + + // Send notification .. + if (!api_is_allowed_to_edit(null, true) && !apiIsExcludedUserType() + ) { + if (api_get_course_setting( + 'email_alert_manager_on_new_quiz' + ) == 1 + ) { + $objExercise->send_mail_notification_for_exam( + $question_list_answers, + $origin, + $exe_id + ); + } + $objExercise->send_notification_for_open_questions( + $question_list_answers, + $origin, + $exe_id + ); + $objExercise->send_notification_for_oral_questions( + $question_list_answers, + $origin, + $exe_id + ); + } + } + } + + /** + * @param Exercise $objExercise + * @param float $score + * @param float $weight + * @param bool $check_pass_percentage + * @return string + */ + public static function get_question_ribbon( + $objExercise, + $score, + $weight, + $check_pass_percentage = false + ) { + $ribbon = '
'; + if ($check_pass_percentage) { + $is_success = self::is_success_exercise_result( + $score, + $weight, + $objExercise->selectPassPercentage() + ); + // Color the final test score if pass_percentage activated + $ribbon_total_success_or_error = ""; + if (self::is_pass_pourcentage_enabled( + $objExercise->selectPassPercentage() + )) { + if ($is_success) { + $ribbon_total_success_or_error = ' ribbon-total-success'; + } else { + $ribbon_total_success_or_error = ' ribbon-total-error'; + } + } + $ribbon .= '
'; + } else { + $ribbon .= '
'; + } + $ribbon .= '

' . get_lang('YourTotalScore') . ": "; + $ribbon .= self::show_score($score, $weight, false, true); + $ribbon .= '

'; + $ribbon .= '
'; + if ($check_pass_percentage) { + $ribbon .= self::show_success_message( + $score, + $weight, + $objExercise->selectPassPercentage() + ); + } + $ribbon .= '
'; + + return $ribbon; + } + + /** + * @param int $countLetter + * @return mixed + */ + public static function detectInputAppropriateClass($countLetter) + { + $limits = array( + 0 => 'input-mini', + 10 => 'input-mini', + 15 => 'input-medium', + 20 => 'input-xlarge', + 40 => 'input-xlarge', + 60 => 'input-xxlarge', + 100 => 'input-xxlarge', + 200 => 'input-xxlarge', + ); + + foreach ($limits as $size => $item) { + if ($countLetter <= $size) { + return $item; + } + } + return $limits[0]; + } +} diff --git a/main/inc/lib/exercise_show_functions.lib.php b/main/inc/lib/exercise_show_functions.lib.php index a83d7178e0..b3d99035c7 100755 --- a/main/inc/lib/exercise_show_functions.lib.php +++ b/main/inc/lib/exercise_show_functions.lib.php @@ -41,7 +41,7 @@ class ExerciseShowFunctions if (!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?> @@ -74,7 +74,7 @@ class ExerciseShowFunctions if (!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?> @@ -92,7 +92,7 @@ class ExerciseShowFunctions */ static function display_free_answer($feedback_type, $answer, $exe_id, $questionId, $questionScore = null) { - $comments = get_comments($exe_id, $questionId); + $comments = Event::get_comments($exe_id, $questionId); if (!empty($answer)) { echo ''; @@ -137,7 +137,7 @@ class ExerciseShowFunctions if (!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { echo ''; - $comm = get_comments($id,$questionId); + $comm = Event::get_comments($id,$questionId); echo ''; } echo ''; @@ -281,7 +281,7 @@ class ExerciseShowFunctions @@ -371,7 +371,7 @@ class ExerciseShowFunctions @@ -469,7 +469,7 @@ class ExerciseShowFunctions diff --git a/main/inc/lib/group_portal_manager.lib.php b/main/inc/lib/group_portal_manager.lib.php index 43aff69e8d..f527f86291 100755 --- a/main/inc/lib/group_portal_manager.lib.php +++ b/main/inc/lib/group_portal_manager.lib.php @@ -38,7 +38,7 @@ class GroupPortalManager Database::query($sql); $id = Database::insert_id(); if ($id) { - event_system(LOG_GROUP_PORTAL_CREATED, LOG_GROUP_PORTAL_ID, $id); + Event::addEvent(LOG_GROUP_PORTAL_CREATED, LOG_GROUP_PORTAL_ID, $id); return $id; } @@ -99,7 +99,7 @@ class GroupPortalManager self::delete_users($id); // Delete group image self::delete_group_picture($id); - event_system(LOG_GROUP_PORTAL_DELETED, LOG_GROUP_PORTAL_ID, $id); + Event::addEvent(LOG_GROUP_PORTAL_DELETED, LOG_GROUP_PORTAL_ID, $id); return $result; } @@ -594,7 +594,7 @@ class GroupPortalManager $sql = "INSERT INTO $table_url_rel_group SET user_id = ".intval($user_id).", group_id = ".intval($group_id).", relation_type = ".intval($relation_type); $result = Database::query($sql); - event_system( + Event::addEvent( LOG_GROUP_PORTAL_USER_SUBSCRIBED, LOG_GROUP_PORTAL_REL_USER_ARRAY, array('user_id' => $user_id, 'group_id' => $group_id, 'relation_type' => $relation_type) @@ -653,7 +653,7 @@ class GroupPortalManager $sql = "DELETE FROM $table_ WHERE group_id = ".intval($group_id).$condition_relation; $result = Database::query($sql); - event_system( + Event::addEvent( LOG_GROUP_PORTAL_USER_DELETE_ALL, LOG_GROUP_PORTAL_REL_USER_ARRAY, array('group_id' => $group_id, 'relation_type' => $relation_type) @@ -675,7 +675,7 @@ class GroupPortalManager $sql = "DELETE FROM $table WHERE user_id = ".intval($user_id)." AND group_id=".intval($group_id); $result = Database::query($sql); - event_system( + Event::addEvent( LOG_GROUP_PORTAL_USER_UNSUBSCRIBED, LOG_GROUP_PORTAL_REL_USER_ARRAY, array('user_id' => $user_id, 'group_id' => $group_id) @@ -710,7 +710,7 @@ class GroupPortalManager "; Database::query($sql); - event_system( + Event::addEvent( LOG_GROUP_PORTAL_USER_UPDATE_ROLE, LOG_GROUP_PORTAL_REL_USER_ARRAY, array('user_id' => $user_id, 'group_id' => $group_id, 'relation_type' => $relation_type) diff --git a/main/inc/lib/login.lib.php b/main/inc/lib/login.lib.php index 67dcb12ac4..15a8dbcafe 100755 --- a/main/inc/lib/login.lib.php +++ b/main/inc/lib/login.lib.php @@ -396,7 +396,7 @@ class Login if (!isset($_SESSION['login_as'])) { //Course login if (isset($_user['user_id'])) { - event_course_login($_course['sysCode'], $_user['user_id'], api_get_session_id()); + Event::event_course_login($_course['sysCode'], $_user['user_id'], api_get_session_id()); } } } else { diff --git a/main/inc/lib/promotion.lib.php b/main/inc/lib/promotion.lib.php index b098317c26..0b1f11271c 100755 --- a/main/inc/lib/promotion.lib.php +++ b/main/inc/lib/promotion.lib.php @@ -211,7 +211,7 @@ class Promotion extends Model { $id = parent::save($params, $show_query); if (!empty($id)) { - event_system(LOG_PROMOTION_CREATE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_PROMOTION_CREATE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id()); } return $id; } @@ -220,7 +220,7 @@ class Promotion extends Model { if (parent::delete($id)) { SessionManager::clear_session_ref_promotion($id); - event_system(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id()); + Event::addEvent(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id()); } else { return false; } diff --git a/main/inc/lib/sessionmanager.lib.php b/main/inc/lib/sessionmanager.lib.php index 91d6506438..28bf02d06c 100755 --- a/main/inc/lib/sessionmanager.lib.php +++ b/main/inc/lib/sessionmanager.lib.php @@ -228,7 +228,7 @@ class SessionManager // add event to system log $user_id = api_get_user_id(); - event_system(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id); + Event::addEvent(LOG_SESSION_CREATE, LOG_SESSION_ID, $session_id, api_get_utc_datetime(), $user_id); } return $session_id; } @@ -902,7 +902,7 @@ class SessionManager /** * Exercises */ - $exercises = get_all_exercises($course, $sessionId, false, '', $getAllSessions); + $exercises = ExerciseLib::get_all_exercises($course, $sessionId, false, '', $getAllSessions); $exercises_total = count($exercises); /** @@ -1496,7 +1496,7 @@ class SessionManager Database::query($sql_delete_sfv); // Add event to system log - event_system(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId); + Event::addEvent(LOG_SESSION_DELETE, LOG_SESSION_ID, $id_checked, api_get_utc_datetime(), $userId); } /** @@ -2334,7 +2334,7 @@ class SessionManager $id_session = Database::insert_id(); // Add event to system log $user_id = api_get_user_id(); - event_system(LOG_SESSION_CATEGORY_CREATE, LOG_SESSION_CATEGORY_ID, $id_session, api_get_utc_datetime(), $user_id); + Event::addEvent(LOG_SESSION_CATEGORY_CREATE, LOG_SESSION_CATEGORY_ID, $id_session, api_get_utc_datetime(), $user_id); return $id_session; } @@ -2433,7 +2433,7 @@ class SessionManager // Add event to system log $user_id = api_get_user_id(); - event_system( + Event::addEvent( LOG_SESSION_CATEGORY_DELETE, LOG_SESSION_CATEGORY_ID, $id_checked, diff --git a/main/inc/lib/tracking.lib.php b/main/inc/lib/tracking.lib.php index 62ceb20c0d..667d7d47a0 100755 --- a/main/inc/lib/tracking.lib.php +++ b/main/inc/lib/tracking.lib.php @@ -346,14 +346,14 @@ class Tracking if ($maxscore == 0) { $view_score = $score; } else { - $view_score = show_score($score, $maxscore, false); + $view_score = ExerciseLib::show_score($score, $maxscore, false); } break; case 'document': - $view_score = ($score == 0 ? '/' : show_score($score, $maxscore, false)); + $view_score = ($score == 0 ? '/' : ExerciseLib::show_score($score, $maxscore, false)); break; default: - $view_score = show_score($score, $maxscore, false); + $view_score = ExerciseLib::show_score($score, $maxscore, false); break; } } @@ -717,7 +717,7 @@ class Tracking get_lang('ResultsHiddenByExerciseSetting') ); } else { - $scoreItem .= show_score($score, $maxscore, false); + $scoreItem .= ExerciseLib::show_score($score, $maxscore, false); } } else { $scoreItem .= $score == 0 ? '/' : ($maxscore == 0 ? $score : $score . '/' . $maxscore); @@ -857,12 +857,12 @@ class Tracking } else { // Show only float when need it if ($my_score == 0) { - $view_score = show_score(0, $my_maxscore, false); + $view_score = ExerciseLib::show_score(0, $my_maxscore, false); } else { if ($my_maxscore == 0) { $view_score = $my_score; } else { - $view_score = show_score($my_score, $my_maxscore, false); + $view_score = ExerciseLib::show_score($my_score, $my_maxscore, false); } } } @@ -1832,7 +1832,7 @@ class Tracking if (!empty($exercise_list)) { foreach ($exercise_list as $exercise_data) { $exercise_id = $exercise_data['id']; - $best_attempt = get_best_attempt_exercise_results_per_user( + $best_attempt = Event::get_best_attempt_exercise_results_per_user( $user_id, $exercise_id, $course_code, @@ -4075,7 +4075,7 @@ class Tracking $exercise_graph_list = array(); foreach ($course_list as $course_data) { - $exercise_list = get_all_exercises( + $exercise_list = ExerciseLib::get_all_exercises( $course_data, $my_session_id, false, @@ -4092,7 +4092,7 @@ class Tracking if ($exercise_data['results_disabled'] == 0 || $exercise_data['results_disabled'] == 2) { $best_average = intval( - get_best_average_score_by_exercise( + ExerciseLib::get_best_average_score_by_exercise( $exercise_data['id'], $course_data['code'], $my_session_id, @@ -4102,7 +4102,7 @@ class Tracking $exercise_graph_list[] = $best_average; $all_exercise_graph_list[] = $best_average; - $user_result_data = get_best_attempt_by_user( + $user_result_data = ExerciseLib::get_best_attempt_by_user( api_get_user_id(), $exercise_data['id'], $course_data['code'], @@ -4187,20 +4187,20 @@ class Tracking foreach($course_list as $course_data) { //All exercises in the course @todo change for a real count - $exercises = get_all_exercises($course_data, $my_session_id); + $exercises = ExerciseLib::get_all_exercises($course_data, $my_session_id); $count_exercises = 0; if (is_array($exercises) && !empty($exercises)) { $count_exercises = count($exercises); } //Count of user results - //$done_exercises = get_count_exercises_attempted_by_course($course_data['code'], $my_session_id); + //$done_exercises = Event::get_count_exercises_attempted_by_course($course_data['code'], $my_session_id); $done_exercises = null; $answered_exercises = 0; if (!empty($exercises)) { foreach($exercises as $exercise_item) { - $attempts = count_exercise_attempts_by_user(api_get_user_id(), $exercise_item['id'], $course_data['code'], $my_session_id); + $attempts = Event::count_exercise_attempts_by_user(api_get_user_id(), $exercise_item['id'], $course_data['code'], $my_session_id); if ($attempts > 1) { $answered_exercises++; } @@ -4208,7 +4208,7 @@ class Tracking } // Average - $average = get_average_score_by_course($course_data['code'], $my_session_id); + $average = ExerciseLib::get_average_score_by_course($course_data['code'], $my_session_id); $all_exercises += $count_exercises; @@ -4232,7 +4232,7 @@ class Tracking $html .= Display::tag('td', $all_unanswered_exercises_by_user); //$html .= Display::tag('td', $all_done_exercise); - $html .= Display::tag('td', convert_to_percentage($all_average)); + $html .= Display::tag('td', ExerciseLib::convert_to_percentage($all_average)); if (isset($_GET['session_id']) && $my_session_id == $_GET['session_id']) { $icon = Display::url(Display::return_icon('2rightarrow_na.gif', get_lang('Details')), '?session_id='.$my_session_id); @@ -4276,7 +4276,7 @@ class Tracking $course_title = $course_data['title']; //All exercises in the course @todo change for a real count - $exercises = get_all_exercises($course_data, $session_id_from_get); + $exercises = ExerciseLib::get_all_exercises($course_data, $session_id_from_get); $count_exercises = 0; if (!empty($exercises)) { $count_exercises = count($exercises); @@ -4285,10 +4285,10 @@ class Tracking //$done_exercises = get_best_exercise_results_by_course($course_code, $session_id_from_get); //From course exercises NOT from LP exercises!!! - //$done_exercises = get_count_exercises_attempted_by_course($course_code, $session_id_from_get); + //$done_exercises = Event::get_count_exercises_attempted_by_course($course_code, $session_id_from_get); $answered_exercises = 0; foreach($exercises as $exercise_item) { - $attempts = count_exercise_attempts_by_user(api_get_user_id(), $exercise_item['id'], $course_code, $session_id_from_get); + $attempts = Event::count_exercise_attempts_by_user(api_get_user_id(), $exercise_item['id'], $course_code, $session_id_from_get); if ($attempts > 1) { $answered_exercises++; } @@ -4297,8 +4297,8 @@ class Tracking $unanswered_exercises = $count_exercises - $answered_exercises; // Average - $average = get_average_score_by_course($course_code, $session_id_from_get); - $my_average = get_average_score_by_course_by_user(api_get_user_id(), $course_code, $session_id_from_get); + $average = ExerciseLib::get_average_score_by_course($course_code, $session_id_from_get); + $my_average = ExerciseLib::get_average_score_by_course_by_user(api_get_user_id(), $course_code, $session_id_from_get); $stats_array[$course_code] = array( 'exercises' => $count_exercises, @@ -4329,9 +4329,9 @@ class Tracking $html .= Display::tag('td', $stats_array[$course_code]['exercises']); $html .= Display::tag('td', $stats_array[$course_code]['unanswered_exercises_by_user']); //$html .= Display::tag('td', $stats_array[$course_code]['done_exercises']); - $html .= Display::tag('td', convert_to_percentage($stats_array[$course_code]['my_average'])); + $html .= Display::tag('td', ExerciseLib::convert_to_percentage($stats_array[$course_code]['my_average'])); - $html .= Display::tag('td', $stats_array[$course_code]['average'] == 0 ? '-' : '('.convert_to_percentage($stats_array[$course_code]['average']).')'); + $html .= Display::tag('td', $stats_array[$course_code]['average'] == 0 ? '-' : '('.ExerciseLib::convert_to_percentage($stats_array[$course_code]['average']).')'); $html .= Display::tag('td', $time, array('align'=>'center')); if (is_numeric($progress)) { @@ -4412,9 +4412,9 @@ class Tracking $user_list = CourseManager::get_user_list_from_course_code($course, $session_id, null, null, 0); } - //$exercise_list = get_all_exercises($course_info, $session_id, true); + //$exercise_list = ExerciseLib::get_all_exercises($course_info, $session_id, true); // Show exercise results of invisible exercises? see BT#4091 - $exercise_list = get_all_exercises( + $exercise_list = ExerciseLib::get_all_exercises( $course_info, $session_id, false, @@ -4436,7 +4436,7 @@ class Tracking $score = $weighting = $attempts = 0; //Getting count of attempts by user - $attempts = count_exercise_attempts_by_user(api_get_user_id(), $exercices['id'], $course_info['code'], $session_id); + $attempts = Event::count_exercise_attempts_by_user(api_get_user_id(), $exercices['id'], $course_info['code'], $session_id); $html .= ''; $url = api_get_path(WEB_CODE_PATH)."exercice/overview.php?cidReq={$course_info['code']}&id_session=$session_id&exerciseId={$exercices['id']}"; @@ -4450,7 +4450,7 @@ class Tracking //Exercise configuration show results or show only score if ($exercices['results_disabled'] == 0 || $exercices['results_disabled'] == 2) { //For graphics - $best_exercise_stats = get_best_exercise_results_by_user($exercices['id'], $course_info['code'], $session_id); + $best_exercise_stats = Event::get_best_exercise_results_by_user($exercices['id'], $course_info['code'], $session_id); $to_graph_exercise_result[$exercices['id']] = array('title'=>$exercices['title'], 'data'=>$best_exercise_stats); $latest_attempt_url = ''; @@ -4458,11 +4458,11 @@ class Tracking $graph = $normal_graph = null; //Getting best results - $best_score_data = get_best_attempt_in_course($exercices['id'], $course_info['code'], $session_id); - $best_score = show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']); + $best_score_data = ExerciseLib::get_best_attempt_in_course($exercices['id'], $course_info['code'], $session_id); + $best_score = ExerciseLib::show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']); if ($attempts > 0) { - $exercise_stat = get_best_attempt_by_user(api_get_user_id(), $exercices['id'], $course_info['code'], $session_id); + $exercise_stat = ExerciseLib::get_best_attempt_by_user(api_get_user_id(), $exercices['id'], $course_info['code'], $session_id); if (!empty($exercise_stat)) { //Always getting the BEST attempt @@ -4471,13 +4471,13 @@ class Tracking $exe_id = $exercise_stat['exe_id']; $latest_attempt_url .= api_get_path(WEB_CODE_PATH).'exercice/result.php?id='.$exe_id.'&cidReq='.$course_info['code'].'&show_headers=1&id_session='.$session_id; - $percentage_score_result = Display::url(show_score($score, $weighting), $latest_attempt_url); + $percentage_score_result = Display::url(ExerciseLib::show_score($score, $weighting), $latest_attempt_url); $my_score = 0; if (!empty($weighting) && intval($weighting) != 0) { $my_score = $score/$weighting; } //@todo this function slows the page - $position = get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list); + $position = ExerciseLib::get_exercise_result_ranking($my_score, $exe_id, $exercices['id'], $course_info['code'], $session_id, $user_list); $graph = self::generate_exercise_result_thumbnail_graph($to_graph_exercise_result[$exercices['id']]); $normal_graph = self::generate_exercise_result_graph($to_graph_exercise_result[$exercices['id']]); @@ -5944,7 +5944,7 @@ class TrackingCourseLog $course_info = api_get_course_info($course_code); $total_surveys = 0; - $total_exercises = get_all_exercises( + $total_exercises = ExerciseLib::get_all_exercises( $course_info, $session_id, false, diff --git a/main/inc/lib/usermanager.lib.php b/main/inc/lib/usermanager.lib.php index 1dfdbbb764..3a87765aa7 100755 --- a/main/inc/lib/usermanager.lib.php +++ b/main/inc/lib/usermanager.lib.php @@ -234,7 +234,7 @@ class UserManager } /* ENDS MANAGE EVENT WITH MAIL */ } - event_system(LOG_USER_CREATE, LOG_USER_ID, $return); + Event::addEvent(LOG_USER_CREATE, LOG_USER_ID, $return); } else { return api_set_failure('error inserting in Database'); } @@ -438,8 +438,8 @@ class UserManager // Add event to system log $user_id_manager = api_get_user_id(); - event_system(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info); - event_system(LOG_USER_DELETE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager, null, $user_info); + Event::addEvent(LOG_USER_DELETE, LOG_USER_ID, $user_id, api_get_utc_datetime(), $user_id_manager, null, $user_info); + Event::addEvent(LOG_USER_DELETE, LOG_USER_OBJECT, $user_info, api_get_utc_datetime(), $user_id_manager, null, $user_info); return true; } @@ -494,7 +494,7 @@ class UserManager $sql = "UPDATE $table_user SET active = 0 WHERE user_id IN ($ids)"; $r = Database::query($sql); if ($r !== false) { - event_system(LOG_USER_DISABLE,LOG_USER_ID,$ids); + Event::addEvent(LOG_USER_DISABLE,LOG_USER_ID,$ids); } return $r; } @@ -524,7 +524,7 @@ class UserManager $sql = "UPDATE $table_user SET active = 1 WHERE user_id IN ($ids)"; $r = Database::query($sql); if ($r !== false) { - event_system(LOG_USER_ENABLE,LOG_USER_ID,$ids); + Event::addEvent(LOG_USER_ENABLE,LOG_USER_ID,$ids); } return $r; } @@ -676,7 +676,7 @@ class UserManager } else { $event_title = LOG_USER_DISABLE; } - event_system($event_title, LOG_USER_ID, $user_id); + Event::addEvent($event_title, LOG_USER_ID, $user_id); } if (is_array($extra) && count($extra) > 0) { $res = true; @@ -735,7 +735,7 @@ class UserManager $ev = LOG_USER_ENABLE; } if ($r !== false) { - event_system($ev,LOG_USER_ID,$user_id); + Event::addEvent($ev,LOG_USER_ID,$user_id); } return $r; } @@ -1924,7 +1924,7 @@ class UserManager if ($result) { //echo "id returned"; $return = Database::insert_id(); - event_system(LOG_USER_FIELD_CREATE, LOG_USER_FIELD_VARIABLE, Database::escape_string($fieldvarname)); + Event::addEvent(LOG_USER_FIELD_CREATE, LOG_USER_FIELD_VARIABLE, Database::escape_string($fieldvarname)); } else { //echo "false - failed" ; return false; diff --git a/main/inc/lib/userportal.lib.php b/main/inc/lib/userportal.lib.php index b4d56fcf18..b252e0b829 100755 --- a/main/inc/lib/userportal.lib.php +++ b/main/inc/lib/userportal.lib.php @@ -67,14 +67,13 @@ class IndexManager function return_exercise_block($personal_course_list) { - require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php'; $exercise_list = array(); if (!empty($personal_course_list)) { foreach($personal_course_list as $course_item) { $course_code = $course_item['c']; $session_id = $course_item['id_session']; - $exercises = get_exercises_to_be_taken($course_code, $session_id); + $exercises = ExerciseLib::get_exercises_to_be_taken($course_code, $session_id); foreach($exercises as $exercise_item) { $exercise_item['course_code'] = $course_code; diff --git a/main/inc/local.inc.php b/main/inc/local.inc.php index 662beb67cb..1d0af91b71 100755 --- a/main/inc/local.inc.php +++ b/main/inc/local.inc.php @@ -128,7 +128,7 @@ if (isset($_SESSION['conditional_login']['uid']) && $_SESSION['conditional_login Session::write('_user', $_user); Session::erase('conditional_login'); $uidReset=true; - event_login(); + Event::event_login(); } // parameters passed via GET @@ -351,7 +351,7 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) { $_user['user_id'] = $uData['user_id']; $_user['status'] = $uData['status']; Session::write('_user', $_user); - event_login(); + Event::event_login(); $logging_in = true; } else { $loginFailed = true; @@ -377,14 +377,14 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) { $_user['user_id'] = $uData['user_id']; $_user['status'] = $uData['status']; Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { //This means a secondary admin wants to login so we check as he's a normal user if (in_array($current_access_url_id, $my_url_list)) { $_user['user_id'] = $uData['user_id']; $_user['status'] = $uData['status']; Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { $loginFailed = true; Session::erase('_uid'); @@ -403,7 +403,7 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) { $_user['status'] = $uData['status']; Session::write('_user', $_user); - event_login(); + Event::event_login(); $logging_in = true; } } else { @@ -650,7 +650,7 @@ if (!empty($_SESSION['_user']['user_id']) && !($login || $logout)) { $_user['status'] = $uData['status']; Session::write('_user', $_user); - event_login(); + Event::event_login(); } else { $loginFailed = true; Session::erase('_uid'); @@ -837,7 +837,7 @@ if (isset($cidReset) && $cidReset) { if (!isset($_SESSION['login_as'])) { //Course login if (isset($_user['user_id'])) { - event_course_login($_course['code'], $_user['user_id'], api_get_session_id()); + Event::event_course_login($_course['code'], $_user['user_id'], api_get_session_id()); } } } else { diff --git a/main/link/ajax_controller.class.php b/main/link/ajax_controller.class.php index bcd1fd10e5..9e9018948d 100755 --- a/main/link/ajax_controller.class.php +++ b/main/link/ajax_controller.class.php @@ -21,16 +21,16 @@ use Header; /** * Ajax controller. Dispatch request and perform required action. - * - * - delete category/link + * + * - delete category/link * - hide/show link * - sort links/categories - * + * * Usage: - * + * * $controller = AjaxController::instance(); * $controller->run(); - * + * * @author Laurent Opprecht for the Univesity of Genevas * @license /license.txt */ @@ -48,7 +48,7 @@ class AjaxController extends \Controller /** * Return the instance of the controller. - * + * * @return \Link\AjaxController */ public static function instance() @@ -62,15 +62,15 @@ class AjaxController extends \Controller protected function __construct() { - + } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { - event_access_tool(TOOL_LINK); + Event::event_access_tool(TOOL_LINK); } public function authorize() @@ -113,7 +113,7 @@ class AjaxController extends \Controller } /** - * + * */ public function hide_link() { @@ -131,7 +131,7 @@ class AjaxController extends \Controller } /** - * + * */ public function show_link() { @@ -149,7 +149,7 @@ class AjaxController extends \Controller } /** - * + * */ public function delete_link() { @@ -168,7 +168,7 @@ class AjaxController extends \Controller } /** - * + * */ public function delete_category() { @@ -186,7 +186,7 @@ class AjaxController extends \Controller $this->response($success); } /** - * + * */ public function delete_by_course() { @@ -250,7 +250,7 @@ class AjaxController extends \Controller $repo = LinkRepository::instance(); $link = $repo->find_one_by_id($c_id, $id); $success = $link ? $link->validate() : false; - + $this->response($success); } @@ -265,7 +265,7 @@ class AjaxController extends \Controller } /** - * Action exists but implementation is missing. + * Action exists but implementation is missing. */ public function missing() { @@ -274,9 +274,9 @@ class AjaxController extends \Controller /** * Display a standard json responce. - * + * * @param bool $success - * @param string $message + * @param string $message * @param object $data */ public function response($success = false, $message = '', $data = null) diff --git a/main/link/controller.class.php b/main/link/controller.class.php index d57657f8a2..c0c641a00b 100755 --- a/main/link/controller.class.php +++ b/main/link/controller.class.php @@ -18,16 +18,16 @@ use Header; /** * Html controller. Dispatch request and perform required action: - * + * * - list * - add/edit/delete link * - add/edit/delete category * - make visible/invisible link * - go to link target - * + * * Note: * Currently some actions are only implemented in the Ajax controller. - * + * * @author Laurent Opprecht for the Univesity of Genevas * @license /license.txt */ @@ -50,7 +50,7 @@ class Controller extends \Controller const ACTION_DEFAULT = 'listing'; /** - * + * * @return \Link\Controller */ public static function instance() @@ -82,9 +82,9 @@ class Controller extends \Controller } /** - * Action to perform. + * Action to perform. * Returns the request parameter. - * + * * @return string */ public function get_action() @@ -101,7 +101,7 @@ class Controller extends \Controller public function prolog() { - event_access_tool(TOOL_LINK); + Event::event_access_tool(TOOL_LINK); //legacy global $interbreadcrumb; @@ -118,8 +118,8 @@ class Controller extends \Controller /** * Whether the call is authorized or not. - * - * @return boolean + * + * @return boolean */ public function authorize() { @@ -138,7 +138,7 @@ class Controller extends \Controller /** * Javascript used by the controller - * + * * @return string */ public function javascript() @@ -153,10 +153,10 @@ class Controller extends \Controller /** * Returns a url for an action that the controller can process - * + * * @param string $action * @param array $params - * @return string + * @return string */ public function url($action, $params = array()) { @@ -213,7 +213,7 @@ class Controller extends \Controller $link->c_id = Request::get_c_id(); $link->session_id = Request::get_session_id(); /** - * @todo: ensure session_id is correctly defaulted + * @todo: ensure session_id is correctly defaulted */ $action = $this->url(self::ACTION_ADD_LINK); $form = new LinkForm('link', 'post', $action); @@ -242,13 +242,13 @@ class Controller extends \Controller if (!$this->is_allowed_to_edit()) { $this->forbidden(); return; - } - + } + $action = $this->url(self::ACTION_IMPORT_CSV); $form = new UploadFileForm('import_csv', 'post', $action); $form->init(); if ($form->validate()) { - $file = $form->get_file(); + $file = $form->get_file(); $path = $file['tmp_name']; $c_id = Request::get_c_id(); $session_id = Request::get_session_id(); @@ -310,7 +310,7 @@ class Controller extends \Controller $writer->put($data); } } - + \DocumentManager :: file_send_for_download($temp, true, get_lang('Links').'.csv'); } @@ -322,7 +322,7 @@ class Controller extends \Controller } /** - * See AjaxController + * See AjaxController */ $this->missing(); } @@ -369,7 +369,7 @@ class Controller extends \Controller } /** - * See AjaxController + * See AjaxController */ $this->missing(); } @@ -382,7 +382,7 @@ class Controller extends \Controller } /** - * See AjaxController + * See AjaxController */ $this->missing(); } @@ -486,7 +486,7 @@ class Controller extends \Controller $link = $repo->find_one_by_id($c_id, $id); $url = $link->url; - event_link($id); + Event::event_link($id); Header::cache_control('no-store, no-cache, must-revalidate'); Header::pragma('no-cache'); @@ -495,15 +495,15 @@ class Controller extends \Controller /** * Render a template using data. Adds a few common parameters to the data array. - * + * * @see /main/template/default/course_description/ * @param string $template - * @param array $data + * @param array $data */ protected function render($template, $data) { $data = $data ? $data : (object) array(); - + $_user = api_get_user_info(); $session_id = Request::get_session_id(); $data->session_image = api_get_session_image($session_id, $_user); diff --git a/main/link/link.php b/main/link/link.php index e4000f06d8..c7e254bcfa 100755 --- a/main/link/link.php +++ b/main/link/link.php @@ -99,7 +99,7 @@ $tbl_link = Database::get_course_table(TABLE_LINK); $tbl_categories = Database::get_course_table(TABLE_LINK_CATEGORY); // Statistics -event_access_tool(TOOL_LINK); +Event::event_access_tool(TOOL_LINK); Display::display_header($nameTools, 'Links'); diff --git a/main/link/link_goto.php b/main/link/link_goto.php index 75163bbd76..71d859413e 100755 --- a/main/link/link_goto.php +++ b/main/link/link_goto.php @@ -25,7 +25,7 @@ $link_url = html_entity_decode(Security::remove_XSS($_GET['link_url'])); $link_id = intval($_GET['link_id']); // Launch event -event_link($link_id); +Event::event_link($link_id); header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 header("Cache-Control: post-check=0, pre-check=0", false); diff --git a/main/messages/download.php b/main/messages/download.php index 9f0b98b0ad..b3b60933f0 100755 --- a/main/messages/download.php +++ b/main/messages/download.php @@ -85,7 +85,7 @@ $full_file_name = $path_user_info['dir'].'message_attachments/'.$file_url; if (Security::check_abs_path($full_file_name, $path_user_info['dir'].'message_attachments/')) { // launch event - event_download($file_url); + Event::event_download($file_url); DocumentManager::file_send_for_download($full_file_name,TRUE, $title); } exit; diff --git a/main/mySpace/myStudents.php b/main/mySpace/myStudents.php index a8cf7533ff..02b0a8f40a 100755 --- a/main/mySpace/myStudents.php +++ b/main/mySpace/myStudents.php @@ -194,7 +194,7 @@ if ($check) { !empty($student_id) ) { $course_info = api_get_course_info($course); - delete_student_lp_events( + Event::delete_student_lp_events( $student_id, $lp_id, $course_info, diff --git a/main/newscorm/download.php b/main/newscorm/download.php index c8410ccbb1..d2543b4498 100755 --- a/main/newscorm/download.php +++ b/main/newscorm/download.php @@ -39,7 +39,7 @@ if ($_SESSION['oLP']) { $visible = learnpath::is_lp_visible_for_student($lp_id, $user_id); if ($visible) { - event_download($doc_url); + Event::event_download($doc_url); if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) { $full_file_name = $sys_course_path.$doc_url; DocumentManager::file_send_for_download($full_file_name); diff --git a/main/newscorm/learnpath_functions.inc.php b/main/newscorm/learnpath_functions.inc.php index 991a9f0b11..2d522927f6 100755 --- a/main/newscorm/learnpath_functions.inc.php +++ b/main/newscorm/learnpath_functions.inc.php @@ -1250,8 +1250,7 @@ function export_exercise($item_id) { $i ++; echo $s = "".get_lang('Question')." "; - // Call the showQuestion() function from exercise.lib.php. This basically displays the question in a table. - $test .= showQuestion($questionId, false, 'export', $i); + $test .= ExerciseLib::showQuestion($questionId, false, 'export', $i); } // end foreach() diff --git a/main/newscorm/lp_edit.php b/main/newscorm/lp_edit.php index b3d1ae2635..a16321079a 100755 --- a/main/newscorm/lp_edit.php +++ b/main/newscorm/lp_edit.php @@ -13,7 +13,7 @@ global $charset; $show_description_field = false; //for now $nameTools = get_lang('Doc'); $this_section = SECTION_COURSES; -event_access_tool(TOOL_LEARNPATH); +Event::event_access_tool(TOOL_LEARNPATH); api_protect_course_script(); diff --git a/main/newscorm/lp_list.php b/main/newscorm/lp_list.php index afcbf813b6..6e8734b029 100755 --- a/main/newscorm/lp_list.php +++ b/main/newscorm/lp_list.php @@ -36,7 +36,7 @@ function confirmation(name) { } "; $nameTools = get_lang('LearningPaths'); -event_access_tool(TOOL_LEARNPATH); +Event::event_access_tool(TOOL_LEARNPATH); api_protect_course_script(); //if (!$is_allowed_in_course) api_not_allowed(); diff --git a/main/newscorm/lp_list_search.php b/main/newscorm/lp_list_search.php index 787da09ebb..a48c87604a 100755 --- a/main/newscorm/lp_list_search.php +++ b/main/newscorm/lp_list_search.php @@ -18,7 +18,7 @@ require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php'; require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php'; $htmlHeadXtra[] = ''; -event_access_tool(TOOL_SEARCH); +Event::event_access_tool(TOOL_SEARCH); if (isset($_SESSION['gradebook'])){ $gradebook = $_SESSION['gradebook']; diff --git a/main/notebook/ajax_controller.class.php b/main/notebook/ajax_controller.class.php index 5f63ffdba7..9a818b5de0 100755 --- a/main/notebook/ajax_controller.class.php +++ b/main/notebook/ajax_controller.class.php @@ -11,16 +11,16 @@ use Header; /** * Ajax controller. Dispatch request and perform required action. - * + * * - delete one note * - delete all notes in a course/session * - returns a note from its id - * + * * Usage: - * + * * $controller = AjaxController::instance(); * $controller->run(); - * + * * @author Laurent Opprecht for the Univesity of Genevas * @license /license.txt */ @@ -33,7 +33,7 @@ class AjaxController extends \AjaxController /** * Return the instance of the controller. - * + * * @return \Notebook\AjaxController */ public static function instance() @@ -46,12 +46,12 @@ class AjaxController extends \AjaxController } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { - event_access_tool(TOOL_NOTEBOOK); - } + Event::event_access_tool(TOOL_NOTEBOOK); + } public function is_allowed_to_edit() { @@ -105,4 +105,4 @@ class AjaxController extends \AjaxController $this->response($success, '', $data); } -} \ No newline at end of file +} diff --git a/main/notebook/controller.class.php b/main/notebook/controller.class.php index 17aafaee7f..efdd777ef6 100755 --- a/main/notebook/controller.class.php +++ b/main/notebook/controller.class.php @@ -14,17 +14,17 @@ use Javascript; /** * Controller for notebook. Dispatch request and peform required action. - * + * * - list notes for course * - add/edit notes entry * - change view from table to details - * + * * Usage: - * + * * $controller = Controller::instance(); * $controller->run(); - * - * @package chamilo.course_description + * + * @package chamilo.course_description * @author Christian Fasanando * @author Laurent Opprecht for the Univesity of Genevas * @license see /license.txt @@ -42,7 +42,7 @@ class Controller extends \Controller /** * Return the instance of the controller. - * + * * @return \Noteboook\Controller */ public static function instance() @@ -55,9 +55,9 @@ class Controller extends \Controller } /** - * Action to perform. + * Action to perform. * Returns the request parameter. - * + * * @return string */ public function get_action() @@ -77,7 +77,7 @@ class Controller extends \Controller } /** - * Prepare the environment. Set up breadcrumps and raise tracking event. + * Prepare the environment. Set up breadcrumps and raise tracking event. */ protected function prolog() { @@ -93,15 +93,15 @@ class Controller extends \Controller $current_course_tool = TOOL_NOTEBOOK; // Tracking - event_access_tool(TOOL_NOTEBOOK); + Event::event_access_tool(TOOL_NOTEBOOK); } /** * Returns a url for an action that the controller can process - * + * * @param string $action * @param array $params - * @return string + * @return string */ public function url($action = '', $params = array()) { @@ -129,8 +129,8 @@ class Controller extends \Controller /** * List course descriptions. - * - * @param array messages + * + * @param array messages */ public function index() { @@ -154,7 +154,7 @@ class Controller extends \Controller } /** - * Performs the edit action. + * Performs the edit action. */ public function edit() { @@ -224,7 +224,7 @@ class Controller extends \Controller /** * Performs the delete action. - * + * * @see AjaxController */ public function delete() @@ -286,10 +286,10 @@ class Controller extends \Controller /** * Render a template using data. Adds a few common parameters to the data array. - * + * * @see /main/template/default/course_description/ * @param string $template - * @param array $data + * @param array $data */ protected function render($template, $data) { @@ -309,4 +309,4 @@ class Controller extends \Controller parent::render("notebook/$template.tpl", $data); } -} \ No newline at end of file +} diff --git a/main/notebook/index.php b/main/notebook/index.php index 14f635a30c..2da224da75 100755 --- a/main/notebook/index.php +++ b/main/notebook/index.php @@ -37,7 +37,7 @@ $(document).ready(function () { $tool = TOOL_NOTEBOOK; // Tracking -event_access_tool(TOOL_NOTEBOOK); +Event::event_access_tool(TOOL_NOTEBOOK); // Tool name if (isset($_GET['action']) && $_GET['action'] == 'addnote') { diff --git a/main/session/index.php b/main/session/index.php index 847cd135c0..217c3a43ae 100755 --- a/main/session/index.php +++ b/main/session/index.php @@ -77,7 +77,7 @@ if (!empty($new_session_list)) { $course_info = api_get_course_info($my_course['code']); // Getting all visible exercises from the current course - $exercise_list = get_all_exercises( + $exercise_list = ExerciseLib::get_all_exercises( $course_info, $my_session_id, true, @@ -96,7 +96,7 @@ if (!empty($new_session_list)) { $visible_return = $exercise->is_visible(); if ($visible_return['value'] != false) { // Reading all Exercise results by user, exercise_id, code, and session. - $user_results = get_exercise_results_by_user( + $user_results = Event::getExerciseResultsByUser( api_get_user_id(), $exercise_item['id'], $my_course['code'], @@ -147,7 +147,7 @@ if (!empty($course_list)) { $course_info = api_get_course_info($course_data['code']); $exercise_count = count( - get_all_exercises( + ExerciseLib::get_all_exercises( $course_info, $session_id, true, @@ -253,11 +253,11 @@ foreach ($final_array as $session_data) { if (!empty($course_data['exercises'])) { // Exercises foreach ($course_data['exercises'] as $my_exercise_id => $exercise_data) { - $best_score_data = get_best_attempt_in_course($my_exercise_id, $my_course_code, $session_id); + $best_score_data = ExerciseLib::get_best_attempt_in_course($my_exercise_id, $my_course_code, $session_id); $best_score = ''; if (!empty($best_score_data)) { - $best_score = show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']); + $best_score = ExerciseLib::show_score($best_score_data['exe_result'], $best_score_data['exe_weighting']); } // Exercise results $counter = 1; @@ -272,12 +272,12 @@ foreach ($final_array as $session_data) { } if (!empty($result_list)) { foreach ($result_list as $exercise_result) { - $platform_score = show_score($exercise_result['exe_result'], $exercise_result['exe_weighting']); + $platform_score = ExerciseLib::show_score($exercise_result['exe_result'], $exercise_result['exe_weighting']); $my_score = 0; if(!empty($exercise_result['exe_weighting']) && intval($exercise_result['exe_weighting']) != 0) { $my_score = $exercise_result['exe_result']/$exercise_result['exe_weighting']; } - $position = get_exercise_result_ranking( + $position = ExerciseLib::get_exercise_result_ranking( $my_score, $exercise_result['exe_id'], $my_exercise_id, diff --git a/main/survey/survey_list.php b/main/survey/survey_list.php index cadefddf22..059e740c73 100755 --- a/main/survey/survey_list.php +++ b/main/survey/survey_list.php @@ -31,7 +31,7 @@ $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null; require_once 'survey.lib.php'; // Tracking -event_access_tool(TOOL_SURVEY); +Event::event_access_tool(TOOL_SURVEY); /** @todo * This has to be moved to a more appropriate place (after the display_header diff --git a/main/tracking/course_session_report.php b/main/tracking/course_session_report.php index 88fee5d638..3ea98e552a 100755 --- a/main/tracking/course_session_report.php +++ b/main/tracking/course_session_report.php @@ -99,10 +99,10 @@ foreach ($course_list as $current_course ) { // Looping LPs foreach ($lp_list as $lp_id =>$lp) { - $exercise_list = get_all_exercises_from_lp($lp_id, $course_info['real_id']); + $exercise_list = Event::get_all_exercises_from_lp($lp_id, $course_info['real_id']); // Looping Chamilo Exercises in LP foreach ($exercise_list as $exercise) { - $exercise_stats = get_all_exercise_event_from_lp($exercise['path'], $course_info['id'], $session_id); + $exercise_stats = Event::get_all_exercise_event_from_lp($exercise['path'], $course_info['id'], $session_id); // Looping Exercise Attempts foreach ($exercise_stats as $stats) { $attempt_result[$stats['exe_user_id']]['result'] += $stats['exe_result'] / $stats['exe_weighting']; diff --git a/main/tracking/lp_results_by_user.php b/main/tracking/lp_results_by_user.php index 8f87981864..eba73965e2 100755 --- a/main/tracking/lp_results_by_user.php +++ b/main/tracking/lp_results_by_user.php @@ -136,11 +136,11 @@ foreach($course_list as $current_course ) { // Looping LPs $lps = array(); foreach ($lp_list as $lp_id =>$lp) { - $exercise_list = get_all_exercises_from_lp($lp_id, $course_info['real_id']); + $exercise_list = Event::get_all_exercises_from_lp($lp_id, $course_info['real_id']); $attempt_result = array(); //Looping Chamilo Exercises in LP foreach ($exercise_list as $exercise) { - $exercise_stats = get_all_exercise_event_from_lp($exercise['path'], $course_info['id'], $session_id); + $exercise_stats = Event::get_all_exercise_event_from_lp($exercise['path'], $course_info['id'], $session_id); //Looping Exercise Attempts foreach($exercise_stats as $stats) { //$attempt_result[$exercise['id']]['users'][$stats['exe_user_id']][$stats['exe_id']] = array('exe_result' =>$stats['exe_result'],'exe_weighting' =>$stats['exe_weighting']); diff --git a/main/tracking/question_course_report.php b/main/tracking/question_course_report.php index bafa852b7c..c3af55cc3a 100755 --- a/main/tracking/question_course_report.php +++ b/main/tracking/question_course_report.php @@ -91,13 +91,13 @@ if (!empty($course_info)) { $_course = $course_info; $main_question_list = array(); foreach ($lp_list as $lp_id =>$lp) { - $exercise_list = get_all_exercises_from_lp($lp_id, $course_info['real_id']); + $exercise_list = Event:: get_all_exercises_from_lp($lp_id, $course_info['real_id']); foreach ($exercise_list as $exercise) { $my_exercise = new Exercise(); $my_exercise->read($exercise['path']); $question_list = $my_exercise->selectQuestionList(); - $exercise_stats = get_all_exercise_event_from_lp( + $exercise_stats = Event::get_all_exercise_event_from_lp( $exercise['path'], $course_info['id'], $session_id diff --git a/main/upload/index.php b/main/upload/index.php index 30def04084..515d7cdab0 100755 --- a/main/upload/index.php +++ b/main/upload/index.php @@ -80,7 +80,7 @@ if (isset($_REQUEST['tool'])) { /** * Process */ -event_access_tool(TOOL_UPLOAD); +Event::event_access_tool(TOOL_UPLOAD); /** * Prepare the header diff --git a/main/upload/upload_ppt.php b/main/upload/upload_ppt.php index 9237c078aa..d997779cac 100755 --- a/main/upload/upload_ppt.php +++ b/main/upload/upload_ppt.php @@ -59,7 +59,7 @@ if (isset($_POST['convert'])) { } } -event_access_tool(TOOL_UPLOAD); +Event::event_access_tool(TOOL_UPLOAD); // check access permissions (edit permission is needed to add a document or a LP) $is_allowed_to_edit = api_is_allowed_to_edit(); diff --git a/main/upload/upload_word.php b/main/upload/upload_word.php index e0407b1605..96a350e0fd 100755 --- a/main/upload/upload_word.php +++ b/main/upload/upload_word.php @@ -79,7 +79,7 @@ if (isset($_POST['convert'])) { } } -event_access_tool(TOOL_UPLOAD); +Event::event_access_tool(TOOL_UPLOAD); // check access permissions (edit permission is needed to add a document or a LP) $is_allowed_to_edit = api_is_allowed_to_edit(); if (!$is_allowed_to_edit) { diff --git a/main/user/user.php b/main/user/user.php index b34fe04173..237d8d3927 100755 --- a/main/user/user.php +++ b/main/user/user.php @@ -457,7 +457,7 @@ if ($origin != 'learnpath') { } // Statistics -event_access_tool(TOOL_USER); +Event::event_access_tool(TOOL_USER); /* Setting the permissions for this page */ $is_allowed_to_track = ($is_courseAdmin || $is_courseTutor); diff --git a/main/wiki/index.php b/main/wiki/index.php index 355ee86c32..b3afb1a7c2 100755 --- a/main/wiki/index.php +++ b/main/wiki/index.php @@ -69,7 +69,7 @@ api_protect_course_script(); api_block_anonymous_users(); /* TRACKING */ -event_access_tool(TOOL_WIKI); +Event::event_access_tool(TOOL_WIKI); if ($groupId) { $group_properties = GroupManager::get_group_properties($groupId); diff --git a/main/wiki/wiki.inc.php b/main/wiki/wiki.inc.php index 882c5b5900..5440ed8a77 100755 --- a/main/wiki/wiki.inc.php +++ b/main/wiki/wiki.inc.php @@ -767,7 +767,7 @@ class Wiki //log users access to wiki (page_id) if (!empty($row['page_id'])) { - event_system(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']); + Event::addEvent(LOG_WIKI_ACCESS, LOG_WIKI_PAGE_ID, $row['page_id']); } //update visits if ($row['id']) { diff --git a/main/work/downloadfolder.inc.php b/main/work/downloadfolder.inc.php index 8a72e29839..0f0dd25915 100755 --- a/main/work/downloadfolder.inc.php +++ b/main/work/downloadfolder.inc.php @@ -180,7 +180,7 @@ while ($not_deleted_file = Database::fetch_assoc($query)) { if (!empty($files)) { $fileName = replace_dangerous_char($work_data['title']); // Logging - event_download($fileName .'.zip (folder)'); + Event::event_download($fileName .'.zip (folder)'); //start download of created file $name = $fileName .'.zip'; diff --git a/main/work/file.php b/main/work/file.php index 2a7edf3ead..527cd8eafb 100755 --- a/main/work/file.php +++ b/main/work/file.php @@ -63,7 +63,7 @@ if (count($ids) == 1) { } if ($pub->is_file()) { - event_download(Uri::here()); + Event::event_download(Uri::here()); DocumentManager::file_send_for_download($pub->get_absolute_path(), false, $pub->get_title()); exit; } @@ -88,7 +88,7 @@ if (count($ids) == 1) { $title = $item->get_title(); $zip->add($path, $title); } - event_download(Uri::here()); + Event::event_download(Uri::here()); DocumentManager::file_send_for_download($zip->get_path(), false, $pub->get_title() . '.zip'); } @@ -129,5 +129,5 @@ foreach ($items as $item) { /** * Send file for download */ -event_download(Uri::here()); +Event::event_download(Uri::here()); DocumentManager::file_send_for_download($zip->get_path(), false, get_lang('StudentPublications') . '.zip'); diff --git a/main/work/work.lib.php b/main/work/work.lib.php index 5cd591d18a..a8558f21f6 100755 --- a/main/work/work.lib.php +++ b/main/work/work.lib.php @@ -4007,7 +4007,7 @@ function processWorkForm($workInfo, $values, $courseInfo, $sessionId, $groupId, $groupId ); sendAlertToTeacher($workId, $courseInfo, $sessionId); - event_upload($workId, $userId, $courseInfo['code'], $sessionId); + Event::event_upload($workId, $userId, $courseInfo['code'], $sessionId); $message = Display::return_message(get_lang('DocAdd')); } } else { @@ -4920,7 +4920,7 @@ function getFileContents($id, $course_info, $sessionId = 0) $title = $row['filename']; } $title = str_replace(' ', '_', $title); - event_download($title); + Event::event_download($title); if (Security::check_abs_path( $full_file_name, api_get_path(SYS_COURSE_PATH).api_get_course_path().'/') @@ -5178,7 +5178,7 @@ function downloadAllFilesPerUser($userId, $courseInfo) // Start download of created file $name = basename(replace_dangerous_char($userInfo['complete_name'])).'.zip'; - event_download($name.'.zip (folder)'); + Event::event_download($name.'.zip (folder)'); if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) { DocumentManager::file_send_for_download($tempZipFile, true, $name); @unlink($tempZipFile); diff --git a/main/work/work.php b/main/work/work.php index bb5ab7a136..33f94e647f 100755 --- a/main/work/work.php +++ b/main/work/work.php @@ -134,7 +134,7 @@ if (!empty($group_id)) { } // Stats -event_access_tool(TOOL_STUDENTPUBLICATION); +Event::event_access_tool(TOOL_STUDENTPUBLICATION); $is_allowed_to_edit = api_is_allowed_to_edit(); $student_can_edit_in_session = api_is_allowed_to_session_edit(false, true); diff --git a/tests/main/exercice/exercise.lib.test.php b/tests/main/exercice/exercise.lib.test.php index 769fde0cb7..72291eba48 100755 --- a/tests/main/exercice/exercise.lib.test.php +++ b/tests/main/exercice/exercise.lib.test.php @@ -3,17 +3,17 @@ require_once api_get_path(SYS_CODE_PATH).'exercice/question.class.php'; class TestExerciseLib extends UnitTestCase { /*public $eQuestion; - + public function TestExerciseLib() { $this->UnitTestCase(''); } - + public function setUp() { - $this->eQuestion = new Question(); + $this->eQuestion = new Question(); } - - public function tearDown() { + + public function tearDown() { $this->eQuestion = null; }*/ /** @@ -23,20 +23,20 @@ class TestExerciseLib extends UnitTestCase { * @param int current item from the list of questions * @param int number of total questions */ - + function testshowQuestion() { global $_course; $questionId = 1; $current_item = 1 ; $total_item = 1; //$objQuestionTmp = $question->read($questionId); - $res = showQuestion($questionId, $onlyAnswers=false, $origin=false,$current_item, $total_item); + $res = ExerciseLib::showQuestion($questionId, $onlyAnswers=false, $origin=false,$current_item, $total_item); $this->assertTrue(is_null($res)); var_dump($res); } - - - - -} + + + + +} ?> diff --git a/tests/main/inc/lib/events.lib.inc.test.php b/tests/main/inc/lib/events.lib.inc.test.php index c621e641fc..1e31ad97a9 100755 --- a/tests/main/inc/lib/events.lib.inc.test.php +++ b/tests/main/inc/lib/events.lib.inc.test.php @@ -29,7 +29,7 @@ class TestEvents extends UnitTestCase { global $_cid; global $TABLETRACK_ACCESS; global $TABLETRACK_LASTACCESS; - $res=event_access_course(); + $res=Event::accessCourse(); $this->assertTrue(is_numeric($res)); //var_dump($res); } @@ -43,7 +43,7 @@ class TestEvents extends UnitTestCase { global $TABLETRACK_LASTACCESS; $tool = ''; $id_session = 0; - $res=event_access_tool($tool, $id_session); + $res=Event::event_access_tool($tool, $id_session); $this->assertTrue(is_numeric($res)); //var_dump($res); } @@ -54,7 +54,7 @@ class TestEvents extends UnitTestCase { global $_cid; global $TABLETRACK_DOWNLOADS; $doc_url= ''; - $res=event_download($doc_url); + $res=Event::event_download($doc_url); $this->assertTrue(is_numeric($res)); //var_dump($res); } @@ -65,7 +65,7 @@ class TestEvents extends UnitTestCase { global $_cid; global $TABLETRACK_LINKS; $link_id=''; - $res=event_link($link_id); + $res=Event::event_link($link_id); $this->assertTrue(is_numeric($res)); //var_dump($res); } @@ -74,7 +74,7 @@ class TestEvents extends UnitTestCase { global $_configuration; global $_user; global $TABLETRACK_LOGIN; - $res=event_login(); + $res=Event::event_login(); $this->assertNull($res); //var_dump($res); } @@ -94,7 +94,7 @@ class TestEvents extends UnitTestCase { $event_type = Database::escape_string($event_type); $event_value_type = Database::escape_string($event_value_type); $event_value = Database::escape_string($event_value); - $res=event_system($event_type, $event_value_type,$event_value); + $res=Event::addEvent($event_type, $event_value_type,$event_value); $this->assertTrue(is_bool($res)); //var_dump($res); } @@ -106,7 +106,7 @@ class TestEvents extends UnitTestCase { global $_cid; global $TABLETRACK_UPLOADS; $doc_id=''; - $res=event_upload($doc_id); + $res=Event::event_upload($doc_id); $this->assertTrue(is_numeric($res)); //var_dump($res); } @@ -118,7 +118,7 @@ class TestEvents extends UnitTestCase { $exeId = Database::escape_string($exeId); $j = Database::escape_string($j); global $_configuration, $_user, $_cid; - $res=exercise_attempt($score,$answer,$quesId,$exeId,$j); + $res=Event::exercise_attempt($score,$answer,$quesId,$exeId,$j); $this->assertTrue(is_bool($res)); //var_dump($res); } @@ -130,7 +130,7 @@ class TestEvents extends UnitTestCase { $answer_id=''; $correct=''; $coords=''; - $res=exercise_attempt_hotspot($exe_id, $question_id, $answer_id, $correct, $coords); + $res=Event::exercise_attempt_hotspot($exe_id, $question_id, $answer_id, $correct, $coords); $this->assertTrue(is_bool($res)); //var_dump($res); } @@ -143,8 +143,8 @@ class TestEvents extends UnitTestCase { $session_id=''; $duration=''; $question_list = array(); - $res=update_event_exercice($exeid,$exo_id, $score, $weighting,$session_id,$learnpath_id=0,$learnpath_item_id=0, $duration, $question_list); + $res=Event::update_event_exercice($exeid,$exo_id, $score, $weighting,$session_id,$learnpath_id=0,$learnpath_item_id=0, $duration, $question_list); $this->assertTrue(is_bool($res)); //var_dump($res); } -} \ No newline at end of file +} diff --git a/tests/main/inc/lib/social.lib.test.php b/tests/main/inc/lib/social.lib.test.php index 822da0654c..3294c4654a 100755 --- a/tests/main/inc/lib/social.lib.test.php +++ b/tests/main/inc/lib/social.lib.test.php @@ -1,7 +1,7 @@ \ No newline at end of file +?> diff --git a/tests/phpunit/classes/AccessurleditcoursestourlTest.lib.php b/tests/phpunit/classes/AccessurleditcoursestourlTest.lib.php index 857cc4ae59..3937dd6b43 100755 --- a/tests/phpunit/classes/AccessurleditcoursestourlTest.lib.php +++ b/tests/phpunit/classes/AccessurleditcoursestourlTest.lib.php @@ -17,7 +17,7 @@ class AccessurleditcoursestourlTest extends PHPUnit_Framework_TestCase { ob_start(); require_once dirname(__FILE__).'/../../../main/inc/lib/access_url_edit_courses_to_url_functions.lib.php'; - require_once dirname(__FILE__).'/../../../main/inc/lib/main_api.lib.php'; + require_once dirname(__FILE__).'/../../../main/inc/lib/api.lib.php'; $this->object = new Accessurleditcoursestourl; } diff --git a/tests/phpunit/classes/AccessurledituserstourlTest.lib.php b/tests/phpunit/classes/AccessurledituserstourlTest.lib.php index ba5372dd68..9f7c3c64d7 100755 --- a/tests/phpunit/classes/AccessurledituserstourlTest.lib.php +++ b/tests/phpunit/classes/AccessurledituserstourlTest.lib.php @@ -17,7 +17,7 @@ class AccessurledituserstourlTest extends PHPUnit_Framework_TestCase { ob_start(); require_once dirname(__FILE__).'/../../../main/inc/lib/access_url_edit_users_to_url_functions.lib.php'; - require_once dirname(__FILE__).'/../../../main/inc/lib/main_api.lib.php'; + require_once dirname(__FILE__).'/../../../main/inc/lib/api.lib.php'; $this->object = new Accessurledituserstourl; } diff --git a/tests/test_manager.inc.php b/tests/test_manager.inc.php index 64fbb14960..f72a6fbdf6 100755 --- a/tests/test_manager.inc.php +++ b/tests/test_manager.inc.php @@ -81,16 +81,13 @@ require_once $libdir.'notebook.lib.php'; /**This files need be inside a buffering to clean the objects*/ ob_start(); -require_once $libdir.'main_api.lib.php'; require_once $libdir.'course_document.lib.php'; require_once $libdir.'add_course.lib.inc.php'; require_once $libdir.'geometry.lib.php'; ob_end_clean(); -/**Problem with this file to test objects*/ -//require_once $maindir.'exercice/exercise.lib.php'; - -class TestManager { +class TestManager +{ /* MAIN CODE */