diff --git a/index.php b/index.php index 0cd9122780..ff809ab52e 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(); @@ -95,7 +95,7 @@ if (!api_get_user_id() && CustomPages::enabled()) { if (!empty($_POST['submitAuth'])) { // The user has been already authenticated, we are now to find the last login of the user. if (isset ($_user['user_id'])) { - $track_login_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN); + $track_login_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN); $sql_last_login = "SELECT UNIX_TIMESTAMP(login_date) FROM $track_login_table WHERE login_user_id = '".$_user['user_id']."' @@ -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/access_url_add_courses_to_url.php b/main/admin/access_url_add_courses_to_url.php index 1fb3a0cc43..741ed379df 100755 --- a/main/admin/access_url_add_courses_to_url.php +++ b/main/admin/access_url_add_courses_to_url.php @@ -28,10 +28,10 @@ $courses = array (); $url_list = array(); $users = array(); -$tbl_access_url_rel_course = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); -$tbl_access_url = Database :: get_main_table(TABLE_MAIN_ACCESS_URL); -$tbl_user = Database :: get_main_table(TABLE_MAIN_USER); -$tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE); +$tbl_access_url_rel_course = Database:: get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); +$tbl_access_url = Database:: get_main_table(TABLE_MAIN_ACCESS_URL); +$tbl_user = Database:: get_main_table(TABLE_MAIN_USER); +$tbl_course = Database:: get_main_table(TABLE_MAIN_COURSE); /* Header */ $tool_name = get_lang('AddCoursesToURL'); diff --git a/main/admin/add_courses_to_usergroup.php b/main/admin/add_courses_to_usergroup.php index 23d7f07229..d31b38ef63 100755 --- a/main/admin/add_courses_to_usergroup.php +++ b/main/admin/add_courses_to_usergroup.php @@ -100,7 +100,7 @@ $filters = array( ); $searchForm = new FormValidator('search', 'get', api_get_self().'?id='.$id); -$searchForm->add_header(get_lang('AdvancedSearch')); +$searchForm->addHeader(get_lang('AdvancedSearch')); $renderer =& $searchForm->defaultRenderer(); $searchForm->addElement('hidden', 'id', $id); foreach ($filters as $param) { diff --git a/main/admin/add_users_to_usergroup.php b/main/admin/add_users_to_usergroup.php index 020c7cf8ce..e53599c2d7 100755 --- a/main/admin/add_users_to_usergroup.php +++ b/main/admin/add_users_to_usergroup.php @@ -184,7 +184,7 @@ $filters = array( ); $searchForm = new FormValidator('search', 'get', api_get_self().'?id='.$id); -$searchForm->add_header(get_lang('AdvancedSearch')); +$searchForm->addHeader(get_lang('AdvancedSearch')); $renderer =& $searchForm->defaultRenderer(); $searchForm->addElement('hidden', 'id', $id); diff --git a/main/admin/configure_homepage.php b/main/admin/configure_homepage.php index 1c89c91d0c..c8a80d5737 100755 --- a/main/admin/configure_homepage.php +++ b/main/admin/configure_homepage.php @@ -46,7 +46,7 @@ function home_tabs($file_logged_in) } } -$language_file = array('index', 'admin', 'accessibility'); +$language_file = array('index', 'admin'); $cidReset = true; require_once '../inc/global.inc.php'; @@ -200,9 +200,6 @@ if (api_is_multiple_url_enabled()) { // Check WCAG settings and prepare edition using WCAG $errorMsg = ''; -if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - $errorMsg = WCAG_Rendering::request_validation(); -} // Filter link param $link = ''; @@ -224,12 +221,7 @@ if (!empty($action)) { switch ($action) { case 'edit_top': // Filter - $home_top = ''; - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - $home_top = WCAG_Rendering::prepareXHTML(); - } else { - $home_top = trim(stripslashes($_POST['home_top'])); - } + $home_top = trim(stripslashes($_POST['home_top'])); // Write if (is_writable($homep)) { @@ -272,7 +264,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,16 +322,12 @@ 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 - //$s_languages_news=$_POST["news_languages"]; // TODO: Why this line has been disabled? - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - $home_news = WCAG_rendering::prepareXHTML(); - } else { - $home_news = trim(stripslashes($_POST['home_news'])); - } + $home_news = trim(stripslashes($_POST['home_news'])); + //Write if ($s_languages_news != 'all') { if (file_exists($homep.$newsf.'_'.$s_languages_news.$ext)) { @@ -376,7 +364,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': @@ -387,14 +375,7 @@ if (!empty($action)) { $link_name = trim(stripslashes($_POST['link_name'])); $link_url = trim(stripslashes($_POST['link_url'])); $add_in_tab = intval($_POST['add_in_tab']); - - // WCAG - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - $link_html = WCAG_Rendering::prepareXHTML(); - } else { - $link_html = trim(stripslashes($_POST['link_html'])); - } - + $link_html = trim(stripslashes($_POST['link_html'])); $filename = trim(stripslashes($_POST['filename'])); $target_blank = $_POST['target_blank'] ? true : false; @@ -541,13 +522,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) @@ -882,22 +863,13 @@ switch ($action) { if (!empty($target_blank)) { $target_blank_checkbox->setChecked(true); } if ($action == 'edit_link' && (empty($link_url) || $link_url == 'http://' || $link_url == 'https://')) { - if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - $form->addElement('html', WCAG_Rendering::create_xhtml(isset($_POST['link_html'])?$_POST['link_html']:$link_html)); - } else { - $default['link_html'] = isset($_POST['link_html']) ? $_POST['link_html'] : $link_html; - $form->add_html_editor('link_html', get_lang('Content'), false, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); - } + $default['link_html'] = isset($_POST['link_html']) ? $_POST['link_html'] : $link_html; + $form->add_html_editor('link_html', get_lang('Content'), false, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"'); } else { if (in_array($action, array('edit_tabs','insert_tabs'))) { - if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - $form->addElement('html', get_lang('Content').' ('.get_lang('Optional').')'); - $form->addElement('html', WCAG_Rendering::create_xhtml(isset($_POST['link_html'])?$_POST['link_html']:(!empty($link_html) ? $link_html : ''))); - } else { - $default['link_html'] = isset($_POST['link_html']) ? $_POST['link_html'] : (!empty($link_html) ? $link_html : ''); - $form->add_html_editor('link_html', get_lang('Content'), false, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); - } + $default['link_html'] = isset($_POST['link_html']) ? $_POST['link_html'] : (!empty($link_html) ? $link_html : ''); + $form->add_html_editor('link_html', get_lang('Content'), false, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); } $form->addElement('checkbox', 'all_langs', null, get_lang('ApplyAllLanguages'), array('id' => 'all_langs')); $form->addElement('html',''); @@ -968,17 +940,8 @@ switch ($action) { $form->addElement('html', $html); } - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - //TODO: review these lines - // Print WCAG-specific HTML editor - $html = ''; - $form->addElement('html', $html); - } else { - $default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open); - $form->add_html_editor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); - } + $default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open); + $form->add_html_editor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); $form->addElement('checkbox', 'all_langs', null, get_lang('ApplyAllLanguages'),array('id' => 'all_langs')); $form->addElement('html','
'; - $html .= WCAG_Rendering::create_xhtml($open); - $html .= '
'); diff --git a/main/admin/configure_inscription.php b/main/admin/configure_inscription.php index d74c230b1e..95682d7a6a 100755 --- a/main/admin/configure_inscription.php +++ b/main/admin/configure_inscription.php @@ -115,14 +115,8 @@ if (!empty($action)) { switch ($action) { case 'edit_top': // Filter - $home_top = ''; - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - $home_top = WCAG_Rendering::prepareXHTML(); - } else { - $home_top = trim(stripslashes($_POST['register_top'])); - } + $home_top = trim(stripslashes($_POST['register_top'])); // Write - if (file_exists($homep.$topf.'_'.$lang.$ext)) { if (is_writable($homep.$topf.'_'.$lang.$ext)) { $fp = fopen($homep.$topf.'_'.$lang.$ext, 'w'); @@ -361,17 +355,8 @@ switch ($action){ $renderer->setElementTemplate(''); $renderer->setRequiredNoteTemplate(''); $form->addElement('hidden', 'formSent', '1'); - if (api_get_setting('wcag_anysurfer_public_pages') == 'true') { - //TODO: review these lines - // Print WCAG-specific HTML editor - $html = ''; - $form->addElement('html', $html); - } else { - $default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open); - $form->add_html_editor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); - } + $default[$name] = str_replace('{rel_path}', api_get_path(REL_PATH), $open); + $form->add_html_editor($name, '', true, false, array('ToolbarSet' => 'PortalHomePage', 'Width' => '100%', 'Height' => '400')); $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"'); $form->setDefaults($default); $form->display(); diff --git a/main/admin/course_category.php b/main/admin/course_category.php index 1bfdd179a4..7bc6149e4d 100755 --- a/main/admin/course_category.php +++ b/main/admin/course_category.php @@ -3,9 +3,7 @@ /** * @package chamilo.admin */ -/** - * Code - */ + // name of the language file that needs to be included $language_file = 'admin'; $cidReset = true; @@ -82,10 +80,11 @@ if ($action == 'add' || $action == 'edit') { if (!empty($category)) { $form_title .= ' ' . get_lang('Into') . ' ' . Security::remove_XSS($category); } - $url = api_get_self().'?action='.Security::remove_XSS($action).'&category='.Security::remove_XSS($category).'&id='.$categoryId; + $url = api_get_self().'?action='.Security::remove_XSS($action).'&category='.Security::remove_XSS($category).'&id='.$category; $form = new FormValidator('course_category', 'post', $url); $form->addElement('header', '', $form_title); $form->addElement('hidden', 'formSent', 1); + $form->addElement('text', 'code', get_lang("CategoryCode")); $form->addElement('text', 'name', get_lang("CategoryName")); $form->addRule('name', get_lang('PleaseEnterCategoryInfo'), 'required'); diff --git a/main/admin/course_edit.php b/main/admin/course_edit.php index 89a3a04fcf..9840260733 100755 --- a/main/admin/course_edit.php +++ b/main/admin/course_edit.php @@ -298,7 +298,7 @@ if ($form->validate()) { $course_code = $course['code']; $visual_code = $course['visual_code']; - $visual_code = generate_course_code($visual_code); + $visual_code = CourseManager::generate_course_code($visual_code); // Check if the visual code is already used by *another* course $visual_code_is_used = false; diff --git a/main/admin/course_import.php b/main/admin/course_import.php index 397175575f..413411ed3c 100755 --- a/main/admin/course_import.php +++ b/main/admin/course_import.php @@ -210,7 +210,7 @@ if (isset($errors) && count($errors) != 0) { } $form = new FormValidator('import', 'post', api_get_self(), null, array('enctype' => 'multipart/form-data')); -$form->add_header($tool_name); +$form->addHeader($tool_name); $form->addElement('file', 'import_file', get_lang('ImportCSVFileLocation')); $form->addElement('checkbox', 'add_me_as_teacher', null, get_lang('AddMeAsTeacherInCourses')); $form->addElement('button', 'save', get_lang('Import')); diff --git a/main/admin/course_request_accepted.php b/main/admin/course_request_accepted.php index 9426074d8b..6a74a702b3 100755 --- a/main/admin/course_request_accepted.php +++ b/main/admin/course_request_accepted.php @@ -22,12 +22,6 @@ $this_section = SECTION_PLATFORM_ADMIN; api_protect_admin_script(); -require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; -require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php'; - -// Including a configuration file. -require api_get_path(CONFIGURATION_PATH).'add_course.conf.php'; - // A check whether the course validation feature is enabled. $course_validation_feature = api_get_setting('course_validation') == 'true'; diff --git a/main/admin/course_request_edit.php b/main/admin/course_request_edit.php index cdbde5435b..33f2a73b80 100755 --- a/main/admin/course_request_edit.php +++ b/main/admin/course_request_edit.php @@ -17,12 +17,6 @@ $tool_name = get_lang('CourseRequestEdit'); api_protect_admin_script(); -require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; -require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php'; - -// Including a configuration file. -require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php'; - // A check whether the course validation feature is enabled. $course_validation_feature = api_get_setting('course_validation') == 'true'; diff --git a/main/admin/course_request_rejected.php b/main/admin/course_request_rejected.php index ad620b7b5c..d431e317ac 100755 --- a/main/admin/course_request_rejected.php +++ b/main/admin/course_request_rejected.php @@ -22,12 +22,6 @@ $this_section = SECTION_PLATFORM_ADMIN; api_protect_admin_script(); -require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; -require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php'; - -// Including a configuration file. -require api_get_path(CONFIGURATION_PATH).'add_course.conf.php'; - // A check whether the course validation feature is enabled. $course_validation_feature = api_get_setting('course_validation') == 'true'; diff --git a/main/admin/course_request_review.php b/main/admin/course_request_review.php index 229719b9f8..fb6cf44dc1 100755 --- a/main/admin/course_request_review.php +++ b/main/admin/course_request_review.php @@ -19,12 +19,6 @@ $this_section = SECTION_PLATFORM_ADMIN; api_protect_admin_script(); -require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; -require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php'; - -// Including a configuration file. -require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php'; - // The delete action should be deactivated in this page. // Better reject the target request, after that you can delete it. // see DELETE_ACTION_ENABLED constant in main_api.lib.php diff --git a/main/admin/dashboard_add_users_to_user.php b/main/admin/dashboard_add_users_to_user.php index 6b5fdba811..d280b322a1 100755 --- a/main/admin/dashboard_add_users_to_user.php +++ b/main/admin/dashboard_add_users_to_user.php @@ -259,7 +259,7 @@ $filters = array( ); $searchForm = new FormValidator('search', 'get', api_get_self().'?user='.$user_id); -$searchForm->add_header(get_lang('AdvancedSearch')); +$searchForm->addHeader(get_lang('AdvancedSearch')); $renderer =& $searchForm->defaultRenderer(); $searchForm->addElement('hidden', 'user', $user_id); diff --git a/main/admin/event_type.php b/main/admin/event_type.php index 94314499c9..2938e9fcc9 100755 --- a/main/admin/event_type.php +++ b/main/admin/event_type.php @@ -12,7 +12,6 @@ $language_file = array('admin'); $cidReset = true; require_once '../inc/global.inc.php'; -require_once '../inc/conf/events.conf.php'; $this_section = SECTION_PLATFORM_ADMIN; api_protect_admin_script(); @@ -35,16 +34,16 @@ if ($action == 'modEventType') { $users = explode(';', $eventUsers); } else { $users = array(); - } + } 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(); @@ -64,7 +63,7 @@ foreach ($users as $user) { /** * Header definition - */ + */ $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin')); $interbreadcrumb[] = array('url' => 'event_controller.php', 'name' => get_lang('Events')); $tool_name = get_lang('EventMessageManagement'); @@ -84,16 +83,16 @@ echo Display::actions($action_array); var eventsConfig = ; var currentLanguage = ; var flagContentHasChanged = false; - var key_lang = ""; + var key_lang = ""; var event_type_name = ""; - - $(document).ready(function() { + + $(document).ready(function() { confirmMessage("eventList"); if (event_type_name != 0) { $("#event_list_group").hide(); } }); - + function ajax(params,func) { $.ajax({ url: "", @@ -103,27 +102,27 @@ echo Display::actions($action_array); }); } - function refreshUsersList() { + function refreshUsersList() { removeAllOption($('#usersList')); - $.each(usersList, function(ind,item) { + $.each(usersList, function(ind,item) { addOption($('#usersList'), item.user_id, item.firstname + ' '+item.lastname); - }); + }); } function getCurrentEventTypeName() { var name = false; - + if (event_type_name != 0) { return event_type_name; } else { return $('#eventList option:selected').first().attr('value'); } - + } - + function self_sent_lock(self_sent) { if (self_sent == true) { - $(".registration_case").show(); + $(".registration_case").show(); $("#usersList").attr('disabled', 'true'); $("#usersSubList").attr('disabled', 'true'); removeAllOption($('#usersSubList')); @@ -135,17 +134,17 @@ echo Display::actions($action_array); } function showEventType() { - cleanInput(); + cleanInput(); currentEventName = getCurrentEventTypeName(); - + $("span#activated_checkbox").css("display", "inline"); // make checkbox visible $('input[name=activated]').attr('checked', false); - - var self_sent = false; + + var self_sent = false; if (typeof(eventsConfig[currentEventName])!='undefined') { // if registration, only sent to self_user - if (eventsConfig[currentEventName].self_sent == true) { + if (eventsConfig[currentEventName].self_sent == true) { self_sent = true; } } @@ -180,9 +179,9 @@ echo Display::actions($action_array); $('#keys').append('
  • '+key+'
  • '); }); } - + if (self_sent == false ) { - + $.ajax({ url: '?action=get_event_users&eventName=' +currentEventName, dataType: 'json', @@ -190,8 +189,8 @@ echo Display::actions($action_array); removeAllOption($('#usersSubList')); refreshUsersList(); usersIds = new Array(); - var json = jQuery.parseJSON(data); - $.each(json, function(ind,item) { + var json = jQuery.parseJSON(data); + $.each(json, function(ind,item) { addOption($('#usersSubList'),item.user_id, item.firstname + ' '+item.lastname); usersIds[ind] = item.value; removeOption($('#usersList'),item.user_id); @@ -224,7 +223,7 @@ echo Display::actions($action_array); select.find('option[value='+value+']').remove(); } - function removeAllOption(select) { + function removeAllOption(select) { select.find('option').remove(); } @@ -267,8 +266,8 @@ echo Display::actions($action_array); /** * Asks if user want to abandon the changes he's done */ - function confirmMessage(sender) { - + function confirmMessage(sender) { + if (flagContentHasChanged == true) { if (confirm(key_lang)) { flagContentHasChanged = false; @@ -308,23 +307,23 @@ echo Display::actions($action_array);
    - +
    -

    +

    +
    - +

    -
    +

    @@ -336,13 +335,13 @@ echo Display::actions($action_array);

    -
    +

    - +
    '.get_lang('SendToUsersInSessions').''; - echo '
    '; - } - - if (!isset($announcement_to_modify) ) $announcement_to_modify =''; - - ($email_ann=='1')?$checked='checked':$checked=''; - echo '
    -
    - -
    -
    '; - - - } else { - if (!isset($announcement_to_modify) ) { - $announcement_to_modify =""; - } - - ($email_ann=='1' || !empty($surveyid))?$checked='checked':$checked=''; - echo '
    -
    - - '.get_lang('EmailOption').': '.get_lang('MyGroup').' - '.get_lang('ModifyRecipientList').''; - AnnouncementManager::show_to_form_group($group_id); - echo '
    '; - } - - // the announcement title - echo '
    - - -
    - -
    -
    '; - - unset($title_to_modify); - $title_to_modify = null; - - if (!isset($announcement_to_modify) ) $announcement_to_modify =""; - if (!isset($content_to_modify) ) $content_to_modify =""; - if (!isset($title_to_modify)) $title_to_modify = ""; - - echo ''; - // @todo use formvalidator - $oFCKeditor = new Editor(); - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '300'; - - if(!api_is_allowed_to_edit()) { - $oFCKeditor->ToolbarSet = "AnnouncementsStudent"; - } else { - $oFCKeditor->ToolbarSet = "Announcements"; - } - - $oFCKeditor->Value = $content_to_modify; - - echo '
    '; - - echo Display::display_normal_message(get_lang('Tags').'

    '.implode('
    ', AnnouncementManager::get_tags()), false); - - - //echo $oFCKeditor->CreateHtml(); - echo $oFCKeditor->editor('newContent', $oFCKeditor->Value); - echo '
    '; - - - //File attachment - echo '
    -
    -  '.get_lang('AddAnAttachment').' -
    -
    {element}
    '; - $html .= WCAG_Rendering::create_xhtml($open); - $html .= '
    - - - - - - - - - '; - - echo'
    '; - echo '
    '; - - if (empty($group_id)) { - echo ''; - echo ''; - echo '

    '; - } else { - echo ''; - echo ''; - echo '

    '; - } - echo '
    '; - echo '
    '; - - if ((isset($_GET['action']) && isset($_GET['id']) && is_array($to))||isset($_GET['remindallinactives'])||isset($_GET['remind_inactive'])) { - echo ''; - } - -} // end of displayform for announcement creation/edition - -/** - * Announcements list display - */ -$course_id = api_get_course_int_id(); - -//if ($display_announcement_list && !$surveyid) { -if ($display_announcement_list) { - // by default we use the id of the current user. The course administrator can see the announcement of other users by using the user / group filter - //$user_id=$_user['user_id']; - if (isset($_SESSION['user'])) { - //$user_id=$_SESSION['user']; - } - $user_id = api_get_user_id(); - - if (isset($_SESSION['group'])) { - //$group_id=$_SESSION['group']; - } - $group_id = api_get_group_id(); - - $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id()); - - //$is_group_member = GroupManager :: is_tutor(api_get_user_id()); - - if (api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - // A.1. you are a course admin with a USER filter - // => see only the messages of this specific user + the messages of the group (s)he is member of. - if (!empty($_SESSION['user'])) { - - if (is_array($group_memberships) && count($group_memberships) > 0 ) { - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref AND - ip.tool = 'announcement' AND - (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) - $condition_session - - ORDER BY display_order DESC"; - - } else { - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref AND - ip.tool ='announcement' AND - (ip.to_user_id = $user_id OR ip.to_group_id='0') AND - ip.visibility='1' - $condition_session - ORDER BY display_order DESC"; - - } - } elseif (api_get_group_id() != 0 ) { - // A.2. you are a course admin with a GROUP filter - // => see only the messages of this specific group - $sql="SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - AND ip.visibility<>'2' - AND (ip.to_group_id=$group_id OR ip.to_group_id='0') - $condition_session - GROUP BY ip.ref - ORDER BY display_order DESC"; - } else { - - // A.3 you are a course admin without any group or user filter - // A.3.a you are a course admin without user or group filter but WITH studentview - // => see all the messages of all the users and groups without editing possibilities - - if (isset($isStudentView) and $isStudentView=="true") { - $sql="SELECT - announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - AND ip.visibility='1' - $condition_session - GROUP BY ip.ref - ORDER BY display_order DESC"; - } else { - // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view) - // => see all the messages of all the users and groups with editing possibilities - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - AND (ip.visibility='0' or ip.visibility='1') - $condition_session - GROUP BY ip.ref - ORDER BY display_order DESC"; - } - } - } else { - //STUDENT - - if (is_array($group_memberships) && count($group_memberships)>0) { - if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - if (api_get_group_id() == 0) { - //No group - $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ( ip.to_user_id='".$_user['user_id']."'" . - " OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))) "; - } else { - $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' - OR ip.to_group_id IN (0, ".api_get_group_id()."))"; - } - //$cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") )) "; - - } else { - if (api_get_group_id() == 0) { - $cond_user_id = " AND (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) "; - } else { - $cond_user_id = " AND (ip.to_user_id=$user_id OR ip.to_group_id IN (0, ".api_get_group_id()."))"; - } - } - - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - $cond_user_id - $condition_session - AND ip.visibility='1' - ORDER BY display_order DESC"; - } else { - if ($_user['user_id']) { - if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR (ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0')) "; - } else { - $cond_user_id = " AND (ip.to_user_id='".$_user['user_id']."' OR ip.to_group_id='0') "; - } - - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE - announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref AND - ip.tool='announcement' - $cond_user_id - $condition_session - AND ip.visibility='1' - AND announcement.session_id IN(0,".api_get_session_id().") - ORDER BY display_order DESC"; - } else { - - if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' ) "; - } else { - $cond_user_id = " AND ip.to_group_id='0' "; - } - - $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date - FROM $tbl_announcement announcement, $tbl_item_property ip - WHERE - announcement.c_id = $course_id AND - ip.c_id = $course_id AND - announcement.id = ip.ref - AND ip.tool='announcement' - $cond_user_id - $condition_session - AND ip.visibility='1' - AND announcement.session_id IN(0,".api_get_session_id().")"; - } - } - } - - $result = Database::query($sql); - $num_rows = Database::num_rows($result); - - // DISPLAY: NO ITEMS - - if (!isset($_GET['action']) || !in_array($_GET['action'], array('add', 'modify','view'))) - if ($num_rows == 0) { - if ((api_is_allowed_to_edit(false,true) OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) and (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath')) { - echo '
    '; - echo '

    '.get_lang('Announcements').'

    '; - echo Display::return_icon('valves.png', '', array(), 64); - echo '
    '; - echo Display::url(get_lang('AddAnnouncement'), api_get_self()."?".api_get_cidreq()."&action=add&origin=".$origin, array('class' => 'btn')); - echo '
    '; - echo '
    '; - } else { - //echo "".Display::return_icon('new_announce.png',get_lang('AddAnnouncement'),'',ICON_SIZE_MEDIUM).""; - Display::display_warning_message(get_lang('NoAnnouncements')); - } - - } else { - $iterator = 1; - $bottomAnnouncement = $announcement_number; - - echo ''; - $ths = Display::tag('th', get_lang('Title')); - $ths .= Display::tag('th', get_lang('By') ); - $ths .= Display::tag('th', get_lang('LastUpdateDate') ); - if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT,$myrow['id'])) - OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - $ths .= Display::tag('th', get_lang('Modify')); - } - - echo Display::tag('tr', $ths); - $displayed = array(); - - while ($myrow = Database::fetch_array($result, 'ASSOC')) { - if (!in_array($myrow['id'], $displayed)) { - $sent_to_icon = ''; - // the email icon - if ($myrow['email_sent'] == '1') { - $sent_to_icon = ' '.Display::return_icon('email.gif', get_lang('AnnounceSentByEmail')); - } - - $title = $myrow['title'].$sent_to_icon; - - /* DATE */ - $last_post_datetime = $myrow['end_date']; - - $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id); - $myrow['visibility'] = $item_visibility; - - // the styles - if ($myrow['visibility'] == '0') { - $style='invisible'; - } else { - $style = ''; - } - - echo ''; - - // show attachment list - $attachment_list = array(); - $attachment_list = AnnouncementManager::get_attachment($myrow['id']); - - $attachment_icon = ''; - if (count($attachment_list)>0) { - $attachment_icon = ' '.Display::return_icon('attachment.gif',get_lang('Attachment')); - } - - /* TITLE */ - $title = Display::url($title.$attachment_icon, api_get_self().'?'.api_get_cidreq().'&action=view&id='.$myrow['id']); - echo Display::tag('td', Security::remove_XSS($title), array('class' => 'announcements-list-line-title '.$style)); - - $user_info = api_get_user_info($myrow['insert_user_id']); - $username = sprintf(get_lang("LoginX"), $user_info['username']); - $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title'=>$username)); - echo Display::tag('td', $username_span, array('class' => 'announcements-list-line-by-user')); - echo Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), array('class' => 'announcements-list-line-datetime')); - - // we can edit if : we are the teacher OR the element belongs to the session we are coaching OR the option to allow users to edit is on - $modify_icons = ''; - if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id'])) - OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - - $modify_icons = "".Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).""; - if ($myrow['visibility']==1) { - $image_visibility="visible"; - $alt_visibility=get_lang('Hide'); - } else { - $image_visibility="invisible"; - $alt_visibility=get_lang('Visible'); - } - $modify_icons .= "". - Display::return_icon($image_visibility.'.png', $alt_visibility,'',ICON_SIZE_SMALL).""; - - // DISPLAY MOVE UP COMMAND only if it is not the top announcement - if ($iterator != 1) { - $modify_icons .= "".Display::return_icon('up.gif', get_lang('Up')).""; - } else { - $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up')); - } - if ($iterator < $bottomAnnouncement) { - $modify_icons .= "".Display::return_icon('down.gif', get_lang('Down')).""; - } else { - $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down')); - } - if (api_is_allowed_to_edit(false,true)) { - $modify_icons .= "". - Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL). - ""; - } - $iterator ++; - echo Display::tag('td', $modify_icons, array('class' => 'announcements-list-line-actions')); - } - echo ""; - } - $displayed[]=$myrow['id']; - } // end while - echo "
    "; - } -} // end: if ($displayAnnoucementList) - - -if (isset($_GET['action']) && $_GET['action'] == 'view') { - AnnouncementManager::display_announcement($announcement_id); -} /* FOOTER */ if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') { 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/announcements/resources/js/main.js b/main/announcements/resources/js/main.js index 3e056d61de..78ca6b89e3 100755 --- a/main/announcements/resources/js/main.js +++ b/main/announcements/resources/js/main.js @@ -34,8 +34,6 @@ $(function() { } } }); - - }); }); diff --git a/main/attendance/attendance_controller.php b/main/attendance/attendance_controller.php index 0e111238e7..777a7013cb 100755 --- a/main/attendance/attendance_controller.php +++ b/main/attendance/attendance_controller.php @@ -565,7 +565,7 @@ class AttendanceController ) . '&action=calendar_logins' ); $form->addDateRangePicker('range', get_lang('Range')); - $form->add_button('submit', get_lang('submit')); + $form->addButton('submit', get_lang('submit')); if ($form->validate()) { $values = $form->getSubmitValues(); diff --git a/main/attendance/attendance_sheet.php b/main/attendance/attendance_sheet.php index d74b70ae5b..7678e0cc0e 100755 --- a/main/attendance/attendance_sheet.php +++ b/main/attendance/attendance_sheet.php @@ -345,7 +345,11 @@ if (api_is_allowed_to_edit(null, true) || echo ''; } } else { - echo ''; + $calendarClass = null; + if (isset($calendar)) { + $calendarClass = "checkboxes_col_".$calendar['id']; + } + echo ''; echo '
    '; echo '
     
    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/ldap.inc.php b/main/auth/external_login/ldap.inc.php index d504a0a921..9b3f6e9f63 100755 --- a/main/auth/external_login/ldap.inc.php +++ b/main/auth/external_login/ldap.inc.php @@ -48,7 +48,7 @@ function extldap_connect() $ds = ldap_connect($host); } if (!$ds) { - $port = isset($extldap_config['port']) ? $ldap_config['port'] : 389; + $port = isset($extldap_config['port']) ? $extldap_config['port'] : 389; error_log('EXTLDAP ERROR : cannot connect to '.$extldap_config['host'].':'.$port); } else { break; 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/authldap.php b/main/auth/ldap/authldap.php index b8fd83c6d7..31d15a2224 100755 --- a/main/auth/ldap/authldap.php +++ b/main/auth/ldap/authldap.php @@ -62,6 +62,7 @@ use \ChamiloSession as Session; /** * Code */ +require_once api_get_path(SYS_CODE_PATH).'auth/external_login/ldap.inc.php'; require 'ldap_var.inc.php'; /** * Check login and password with LDAP @@ -325,7 +326,9 @@ function ldap_set_version(&$resource) { */ function ldap_handle_bind(&$ldap_handler,&$ldap_bind) { //error_log('Entering ldap_handle_bind(&$ldap_handler,&$ldap_bind)',0); - global $ldap_rdn,$ldap_pass; + global $ldap_rdn,$ldap_pass, $extldap_config; + $ldap_rdn = $extldap_config['admin_dn']; + $ldap_pass = $extldap_config['admin_password']; if (!empty($ldap_rdn) and !empty($ldap_pass)) { //error_log('Trying authenticated login :'.$ldap_rdn.'/'.$ldap_pass,0); $ldap_bind = ldap_bind($ldap_handler,$ldap_rdn,$ldap_pass); @@ -352,21 +355,23 @@ function ldap_handle_bind(&$ldap_handler,&$ldap_bind) { */ function ldap_get_users() { - global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass; + global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass, $ldap_search_dn, $extldap_user_correspondance; - $keyword_firstname = trim(Database::escape_string($_GET['keyword_firstname'])); - $keyword_lastname = trim(Database::escape_string($_GET['keyword_lastname'])); - $keyword_username = trim(Database::escape_string($_GET['keyword_username'])); - $keyword_type = Database::escape_string($_GET['keyword_type']); + $keyword_firstname = isset($_GET['keyword_firstname']) ? trim(Database::escape_string($_GET['keyword_firstname'])): ''; + $keyword_lastname = isset($_GET['keyword_lastname']) ? trim(Database::escape_string($_GET['keyword_lastname'])) : ''; + $keyword_username = isset($_GET['keyword_username']) ? trim(Database::escape_string($_GET['keyword_username'])) : ''; + $keyword_type = isset($_GET['keyword_type']) ? Database::escape_string($_GET['keyword_type']) : ''; $ldap_query=array(); if ($keyword_username != "") { - $ldap_query[]="(uid=".$keyword_username."*)"; - } else if ($keyword_lastname!=""){ - $ldap_query[]="(sn=".$keyword_lastname."*)"; + $ldap_query[] = str_replace('%username%', $keyword_username, $ldap_search_dn); + } else { + if ($keyword_lastname!=""){ + $ldap_query[]="(".$extldap_user_correspondance['lastname']."=".$keyword_lastname."*)"; + } if ($keyword_firstname!="") { - $ldap_query[]="(givenName=".$keyword_firstname."*)"; + $ldap_query[]="(".$extldap_user_correspondance['firstname']."=".$keyword_firstname."*)"; } } if ($keyword_type !="" && $keyword_type !="all") { @@ -380,7 +385,7 @@ function ldap_get_users() { } $str_query.=" )"; } else { - $str_query=$ldap_query[0]; + $str_query= count($ldap_query) > 0 ? $ldap_query[0] : null; } $ds = ldap_connect($ldap_host, $ldap_port); @@ -421,6 +426,9 @@ function ldap_get_number_of_users() { * @author Mustapha Alouani */ function ldap_get_user_data($from, $number_of_items, $column, $direction) { + + global $extldap_user_correspondance; + $users = array(); $is_western_name_order = api_is_western_name_order(); if (isset($_GET['submit'])) { @@ -434,17 +442,17 @@ function ldap_get_user_data($from, $number_of_items, $column, $direction) { //$dn_array=ldap_explode_dn($info[$key]["dn"],1); //$user[] = $dn_array[0]; // uid is first key //$user[] = $dn_array[0]; // uid is first key - $user[] = $info[$key]['uid'][0]; - $user[] = $info[$key]['uid'][0]; + $user[] = $info[$key][$extldap_user_correspondance['username']][0]; + $user[] = $info[$key][$extldap_user_correspondance['username']][0]; if ($is_western_name_order) { - $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8'); - $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8'); + $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8'); + $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8'); } else { - $user[] = api_convert_encoding($info[$key]['sn'][0], api_get_system_encoding(), 'UTF-8'); - $user[] = api_convert_encoding($info[$key]['cn'][0], api_get_system_encoding(), 'UTF-8'); + $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['firstname']][0], api_get_system_encoding(), 'UTF-8'); + $user[] = api_convert_encoding($info[$key][$extldap_user_correspondance['lastname']][0], api_get_system_encoding(), 'UTF-8'); } $user[] = $info[$key]['mail'][0]; - $outab[] = $info[$key]['eduPersonPrimaryAffiliation'][0]; // Ici "student" + $user[] = $info[$key][$extldap_user_correspondance['username']][0]; $users[] = $user; } } else { @@ -462,9 +470,12 @@ function ldap_get_user_data($from, $number_of_items, $column, $direction) { * @author Mustapha Alouani */ function modify_filter($user_id,$url_params, $row) { - $url_params_id="id[]=".$row[0]; + $query_string="id[]=".$row[0]; + if (!empty($_GET['id_session'])){ + $query_string .= '&id_session='.Security::remove_XSS($_GET['id_session']); + } //$url_params_id="id=".$row[0]; - $result .= ''.Display::return_icon('add_user.gif', get_lang('AddUsers')).''; + $result = ''.Display::return_icon('add_user.gif', get_lang('AddUsers')).''; return $result; } @@ -474,26 +485,9 @@ function modify_filter($user_id,$url_params, $row) { * @author Mustapha Alouani */ function ldap_add_user($login) { - global $ldap_basedn, $ldap_host, $ldap_port, $ldap_rdn, $ldap_pass; - $ds = ldap_connect($ldap_host, $ldap_port); - ldap_set_version($ds); - $user_id = 0; - if ($ds) { - $str_query="(uid=".$login.")"; - $r = false; - $res = ldap_handle_bind($ds, $r); - $sr = ldap_search($ds, $ldap_basedn, $str_query); - //echo "Number of results is : ".ldap_count_entries($ds,$sr)."

    "; - $info = ldap_get_entries($ds, $sr); - - for ($key = 0; $key < $info['count']; $key ++) { - $user_id = ldap_add_user_by_array($info[$key]); - } - - } else { - Display :: display_error_message(get_lang('LDAPConnectionError')); + if ($ldap_user = extldap_authenticate($login, 'nopass', true)) { + return extldap_add_user_by_array($ldap_user); } - return $user_id; } function ldap_add_user_by_array($data, $update_if_exists = true) { diff --git a/main/auth/ldap/ldap_var.inc.php b/main/auth/ldap/ldap_var.inc.php index 5ff295e59f..60f39b637d 100755 --- a/main/auth/ldap/ldap_var.inc.php +++ b/main/auth/ldap/ldap_var.inc.php @@ -23,24 +23,24 @@ * Configuration settings */ // your ldap server -$ldap_host = api_get_setting('ldap_main_server_address'); +$ldap_host = $extldap_config['host'][0]; // your ldap server's port number -$ldap_port = api_get_setting('ldap_main_server_port'); +$ldap_port = @$extldap_config['port'] ?: null; //domain -$ldap_basedn = api_get_setting('ldap_domain'); +$ldap_basedn = $extldap_config['base_dn']; //search term for students -$ldap_search_dn = api_get_setting('ldap_search_string'); +$ldap_search_dn = $extldap_config['user_search']; //additional server params for use of replica in case of problems -$ldap_host2 = api_get_setting('ldap_replicate_server_address'); -$ldap_port2 = api_get_setting('ldap_replicate_server_port'); +$ldap_host2 = count($extldap_config['host']) > 1 ? $extldap_config['host'][1] : null; +$ldap_port2 = $extldap_config['port']; //protocol version - set to 3 for LDAP 3 -$ldap_version = api_get_setting('ldap_version'); +$ldap_version = $extldap_config['protocol_version']; //non-anonymous LDAP mode -$ldap_rdn = api_get_setting('ldap_authentication_login'); -$ldap_pass = api_get_setting('ldap_authentication_password'); +$ldap_rdn = $extldap_config['admin_dn']; +$ldap_pass = $extldap_config['admin_password']; $ldap_pass_placeholder = "PLACEHOLDER"; 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/my_progress.php b/main/auth/my_progress.php index abfd81aa05..5963053df2 100755 --- a/main/auth/my_progress.php +++ b/main/auth/my_progress.php @@ -65,7 +65,7 @@ if (!empty($course_user_list)) { if ($count == $last_item) { $last = ''.get_lang('Last').''; } - $course_info = api_get_course_info($result['course_code']); + $course_info = api_get_course_info_by_id($result['c_id']); $course_image = ''; $dates .= '

  • '.api_get_utc_datetime($login).'
  • '; $issues .= '
  • 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..e5c8d51cf1 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) { @@ -243,18 +243,19 @@ class ssoDrupal { $userExtraFieldValue = new ExtraFieldValue('user'); $drupalUserIdData = $userExtraFieldValue->get_values_by_handler_and_field_variable($userId, 'drupal_user_id'); + // If this is an administrator, allow him to make some changes in + // the Chamilo profile + if ($asAdmin && api_is_platform_admin(true)) { + return api_get_path(WEB_CODE_PATH) . "admin/user_edit.php?user_id=$userId"; + } + // If the user doesn't match a Drupal user, give the normal profile + // link if ($drupalUserIdData === false) { - if ($asAdmin && api_is_platform_admin(true)) { - return api_get_path(WEB_CODE_PATH) . "admin/user_edit.php?user_id=$userId"; - } - return api_get_path(WEB_CODE_PATH) . 'auth/profile.php'; } - + // In all other cases, generate a link to the Drupal profile edition $drupalUserId = $drupalUserIdData['field_value']; - $url = "{$this->protocol}{$this->domain}/user/{$drupalUserId}/edit"; - return $url; } 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/blog.php b/main/blog/blog.php index 28da6c62ce..ff11b8ed26 100755 --- a/main/blog/blog.php +++ b/main/blog/blog.php @@ -6,9 +6,6 @@ * @package chamilo.blogs */ -/** - * INIT - */ // name of the language file that needs to be included $language_file = "blog"; require_once '../inc/global.inc.php'; @@ -22,18 +19,11 @@ if (empty($blog_id)) { $this_section = SECTION_COURSES; $current_course_tool = TOOL_BLOGS; - /* ACCESS RIGHTS */ // notice for unauthorized people. api_protect_course_script(true); -//session -if(isset($_GET['id_session'])) { - $_SESSION['id_session'] = intval($_GET['id_session']); -} - $lib_path = api_get_path(LIBRARY_PATH); - $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT); $nameTools = get_lang('Blogs'); @@ -41,95 +31,146 @@ $DaysShort = api_get_week_days_short(); $DaysLong = api_get_week_days_long(); $MonthsLong = api_get_months_long(); -$current_page = $_GET['action']; +$action = isset($_GET['action']) ? $_GET['action'] : null; /* PROCESSING */ -$safe_post_title = Security::remove_XSS($_POST['post_title']); -$safe_post_file_comment = Security::remove_XSS($_POST['post_file_comment']); -$safe_post_full_text = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['post_full_text'])), COURSEMANAGERLOWSECURITY); -$safe_comment_text = Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['comment_text'])), COURSEMANAGERLOWSECURITY); -$safe_comment_title = Security::remove_XSS($_POST['comment_title']); -$safe_task_name = Security::remove_XSS($_POST['task_name']); -$safe_task_description = Security::remove_XSS($_POST['task_description']); - -if (!empty($_POST['new_post_submit']) AND !empty($_POST['post_title'])) { - Blog :: create_post($safe_post_title, $safe_post_full_text, $safe_post_file_comment,$blog_id); +$safe_post_file_comment = isset($_GET['post_file_comment']) ? Security::remove_XSS($_POST['post_file_comment']) : null; +$safe_comment_text = isset($_GET['comment_text']) ? Security::remove_XSS(stripslashes(api_html_entity_decode($_POST['comment_text'])), COURSEMANAGERLOWSECURITY) : null; +$safe_comment_title = isset($_GET['comment_title']) ? Security::remove_XSS($_POST['comment_title']) : null; +$safe_task_name = isset($_GET['task_name']) ? Security::remove_XSS($_POST['task_name']) : null; +$safe_task_description = isset($_GET['task_description']) ? Security::remove_XSS($_POST['task_description']) : null; + +if (!empty($_POST['new_post_submit'])) { + Blog:: create_post( + $_POST['title'], + $_POST['full_text'], + $_POST['post_file_comment'], + $blog_id + ); $return_message = array('type' => 'confirmation', 'message' => get_lang('BlogAdded')); } -if (!empty($_POST['edit_post_submit'])) -{ - $safe_post_title = Security::remove_XSS($_POST['post_title']); - Blog :: edit_post($_POST['post_id'], $safe_post_title, $safe_post_full_text, $blog_id); +if (!empty($_POST['edit_post_submit'])) { + Blog:: edit_post( + $_POST['post_id'], + $_POST['title'], + $_POST['full_text'], + $blog_id + ); $return_message = array('type' => 'confirmation', 'message' => get_lang('BlogEdited')); } -if (!empty($_POST['new_comment_submit'])) -{ - Blog :: create_comment($safe_comment_title, $safe_comment_text, $safe_post_file_comment,$blog_id, (int)$_GET['post_id'], $_POST['comment_parent_id']); + +if (!empty($_POST['new_comment_submit'])) { + Blog:: create_comment( + $_POST['title'], + $_POST['comment'], + $_POST['post_file_comment'], + $blog_id, + $_GET['post_id'], + $_POST['comment_parent_id'] + ); $return_message = array('type' => 'confirmation', 'message' => get_lang('CommentAdded')); } -if (!empty($_POST['new_task_submit'])) -{ - Blog :: create_task($blog_id, $safe_task_name, $safe_task_description, $_POST['chkArticleDelete'], $_POST['chkArticleEdit'], $_POST['chkCommentsDelete'], $_POST['task_color']); +if (!empty($_POST['new_task_submit'])) { + Blog:: create_task( + $blog_id, + $safe_task_name, + $safe_task_description, + $_POST['chkArticleDelete'], + $_POST['chkArticleEdit'], + $_POST['chkCommentsDelete'], + $_POST['task_color'] + ); $return_message = array('type' => 'confirmation', 'message' => get_lang('TaskCreated')); } -if (isset($_POST['edit_task_submit'])) -{ - Blog :: edit_task($_POST['blog_id'], $_POST['task_id'], $safe_task_name, $safe_task_description, $_POST['chkArticleDelete'], $_POST['chkArticleEdit'],$_POST['chkCommentsDelete'], $_POST['task_color']); - $return_message = array('type' => 'confirmation', 'message' => get_lang('TaskEdited')); +if (isset($_POST['edit_task_submit'])) { + Blog:: edit_task( + $_POST['blog_id'], + $_POST['task_id'], + $safe_task_name, + $safe_task_description, + $_POST['chkArticleDelete'], + $_POST['chkArticleEdit'], + $_POST['chkCommentsDelete'], + $_POST['task_color'] + ); + $return_message = array( + 'type' => 'confirmation', + 'message' => get_lang('TaskEdited') + ); } -if (!empty($_POST['assign_task_submit'])) -{ - Blog :: assign_task($blog_id, $_POST['task_user_id'], $_POST['task_task_id'], $_POST['task_year']."-".$_POST['task_month']."-".$_POST['task_day']); - $return_message = array('type' => 'confirmation', 'message' => get_lang('TaskAssigned')); + +if (!empty($_POST['assign_task_submit'])) { + Blog:: assign_task( + $blog_id, + $_POST['task_user_id'], + $_POST['task_task_id'], + $_POST['task_year'] . "-" . $_POST['task_month'] . "-" . $_POST['task_day'] + ); + $return_message = array( + 'type' => 'confirmation', + 'message' => get_lang('TaskAssigned') + ); } -if (isset($_POST['assign_task_edit_submit'])) -{ - Blog :: edit_assigned_task($blog_id, $_POST['task_user_id'], $_POST['task_task_id'], $_POST['task_year']."-".$_POST['task_month']."-".$_POST['task_day'], $_POST['old_user_id'], $_POST['old_task_id'], $_POST['old_target_date']); - $return_message = array('type' => 'confirmation', 'message' => get_lang('AssignedTaskEdited')); +if (isset($_POST['assign_task_edit_submit'])) { + Blog:: edit_assigned_task( + $blog_id, + $_POST['task_user_id'], + $_POST['task_task_id'], + $_POST['task_year'] . "-" . $_POST['task_month'] . "-" . $_POST['task_day'], + $_POST['old_user_id'], + $_POST['old_task_id'], + $_POST['old_target_date'] + ); + $return_message = array( + 'type' => 'confirmation', + 'message' => get_lang('AssignedTaskEdited') + ); } -if (!empty($_POST['new_task_execution_submit'])) -{ - Blog :: create_comment($safe_comment_title, $safe_comment_text, $blog_id, (int)$_GET['post_id'], $_POST['comment_parent_id'], $_POST['task_id']); - $return_message = array('type' => 'confirmation', 'message' => get_lang('CommentCreated')); +if (!empty($_POST['new_task_execution_submit'])) { + Blog:: create_comment( + $safe_comment_title, + $safe_comment_text, + $blog_id, + (int)$_GET['post_id'], + $_POST['comment_parent_id'], + $_POST['task_id'] + ); + $return_message = array( + 'type' => 'confirmation', + 'message' => get_lang('CommentCreated') + ); } -if (!empty($_POST['register'])) -{ +if (!empty($_POST['register'])) { if (is_array($_POST['user'])) { - foreach ($_POST['user'] as $index => $user_id) - { + foreach ($_POST['user'] as $index => $user_id) { Blog :: set_user_subscribed((int)$_GET['blog_id'], $user_id); } } } -if (!empty($_POST['unregister'])) -{ +if (!empty($_POST['unregister'])) { if (is_array($_POST['user'])) { - foreach ($_POST['user'] as $index => $user_id) - { + foreach ($_POST['user'] as $index => $user_id) { Blog :: set_user_unsubscribed((int)$_GET['blog_id'], $user_id); } } } -if (!empty($_GET['register'])) -{ +if (!empty($_GET['register'])) { Blog :: set_user_subscribed((int)$_GET['blog_id'], (int)$_GET['user_id']); $return_message = array('type' => 'confirmation', 'message' => get_lang('UserRegistered')); $flag = 1; } -if (!empty($_GET['unregister'])) -{ +if (!empty($_GET['unregister'])) { Blog :: set_user_unsubscribed((int)$_GET['blog_id'], (int)$_GET['user_id']); } if (isset($_GET['action']) && $_GET['action'] == 'manage_tasks') { - if (isset($_GET['do']) && $_GET['do'] == 'delete') - { + if (isset($_GET['do']) && $_GET['do'] == 'delete') { Blog :: delete_task($blog_id, (int)$_GET['task_id']); $return_message = array('type' => 'confirmation', 'message' => get_lang('TaskDeleted')); } @@ -138,54 +179,40 @@ if (isset($_GET['action']) && $_GET['action'] == 'manage_tasks') { Blog :: delete_assigned_task($blog_id, intval($_GET['task_id']), intval($_GET['user_id'])); $return_message = array('type' => 'confirmation', 'message' => get_lang('TaskAssignmentDeleted')); } - } if (isset($_GET['action']) && $_GET['action'] == 'view_post') { $task_id = (isset ($_GET['task_id']) && is_numeric($_GET['task_id'])) ? $_GET['task_id'] : 0; - if (isset($_GET['do']) && $_GET['do'] == 'delete_comment') - { - if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) - { + if (isset($_GET['do']) && $_GET['do'] == 'delete_comment') { + if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_delete', $task_id)) { Blog :: delete_comment($blog_id, (int)$_GET['post_id'],(int)$_GET['comment_id']); $return_message = array('type' => 'confirmation', 'message' => get_lang('CommentDeleted')); - } - else - { + } else { $error = true; $message = get_lang('ActionNotAllowed'); } } - if (isset($_GET['do']) && $_GET['do'] == 'delete_article') - { - if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) - { + if (isset($_GET['do']) && $_GET['do'] == 'delete_article') { + if (api_is_allowed('BLOG_'.$blog_id, 'article_delete', $task_id)) { Blog :: delete_post($blog_id, (int)$_GET['article_id']); - $current_page = ''; // Article is gone, go to blog home + $action = ''; // Article is gone, go to blog home $return_message = array('type' => 'confirmation', 'message' => get_lang('BlogDeleted')); - } - else - { + } else { $error = true; $message = get_lang('ActionNotAllowed'); } } - if (isset($_GET['do']) && $_GET['do'] == 'rate') - { - if (isset($_GET['type']) && $_GET['type'] == 'post') - { - if (api_is_allowed('BLOG_'.$blog_id, 'article_rate')) - { + if (isset($_GET['do']) && $_GET['do'] == 'rate') { + if (isset($_GET['type']) && $_GET['type'] == 'post') { + if (api_is_allowed('BLOG_'.$blog_id, 'article_rate')) { Blog :: add_rating('post', $blog_id, (int)$_GET['post_id'], (int)$_GET['rating']); $return_message = array('type' => 'confirmation', 'message' => get_lang('RatingAdded')); } } - if (isset($_GET['type']) && $_GET['type'] == 'comment') - { - if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) - { + if (isset($_GET['type']) && $_GET['type'] == 'comment') { + if (api_is_allowed('BLOG_'.$blog_id, 'article_comments_add')) { Blog :: add_rating('comment', $blog_id, (int)$_GET['comment_id'], (int)$_GET['rating']); $return_message = array('type' => 'confirmation', 'message' => get_lang('RatingAdded')); } @@ -198,7 +225,7 @@ if (isset($_GET['action']) && $_GET['action'] == 'view_post') { $htmlHeadXtra[] = ''; // Set bredcrumb -switch ($current_page) { +switch ($action) { case 'new_post' : $nameTools = get_lang('NewPost'); $interbreadcrumb[] = array ('url' => "blog.php?blog_id=$blog_id", "name" => Blog :: get_blog_title($blog_id)); @@ -244,7 +271,6 @@ if (!empty($return_message)) { } } - // actions echo '
    '; ?> @@ -256,9 +282,8 @@ echo '
    '; echo '
    '; // Tool introduction -Display::display_introduction_section(TOOL_BLOG); +Display::display_introduction_section(TOOL_BLOGS); -//Display::display_header($nameTools,'Blogs'); ?>
    @@ -309,7 +334,7 @@ if (isset($error)) { } if (isset($flag) && $flag == '1') { - $current_page = "manage_tasks"; + $action = "manage_tasks"; Blog :: display_assign_task_form($blog_id); } @@ -338,13 +363,13 @@ if (isset ($_GET['task_id']) && is_numeric($_GET['task_id'])) { $user_task = true; } -switch ($current_page) { - case 'new_post' : +switch ($action) { + case 'new_post': if (api_is_allowed('BLOG_'.$blog_id, 'article_add', $user_task ? $task_id : 0)) { // we show the form if // 1. no post data // 2. there is post data and the required field is empty - if (!$_POST OR (!empty($_POST) AND empty($_POST['post_title']))) { + if (!$_POST OR (!empty($_POST) AND empty($_POST['title']))) { // if there is post data there is certainly an error in the form if ($_POST) { Display::display_error_message(get_lang('FormHasErrorsPleaseComplete')); diff --git a/main/blog/blog_admin.php b/main/blog/blog_admin.php index 5853833dcf..337d800c9e 100755 --- a/main/blog/blog_admin.php +++ b/main/blog/blog_admin.php @@ -1,13 +1,12 @@ 'blog_admin.php?'.$my_url, - 'name' => $current_section - ); + /*$interbreadcrumb[] = array( + 'url' => 'blog_admin.php?' . $my_url, + 'name' => $current_section + );*/ Display::display_header(''); - } else { } echo ''; - /* - PROCESSING.. - */ - $get_blog_name = Security::remove_XSS($_POST['blog_name']); - $get_blog_subtitle = Security::remove_XSS($_POST['blog_subtitle']); - $get_blog_id = Security::remove_XSS($_POST['blog_id']); - if (!empty($_POST['new_blog_submit']) AND !empty($_POST['blog_name'])) { - if (strlen(trim($_POST['blog_name']))>0) { - Blog::create_blog($get_blog_name,$get_blog_subtitle); + if (isset($_POST['blog_name'])) { + Blog::create_blog($_POST['blog_name'], $_POST['blog_subtitle']); Display::display_confirmation_message(get_lang('BlogStored')); } } if (!empty($_POST['edit_blog_submit']) AND !empty($_POST['blog_name'])) { if (strlen(trim($_POST['blog_name']))>0) { - Blog::edit_blog($get_blog_id,$get_blog_name,$get_blog_subtitle); + Blog::edit_blog($_POST['blog_id'], $_POST['blog_name'], $_POST['blog_subtitle']); Display::display_confirmation_message(get_lang('BlogEdited')); } } @@ -96,11 +88,11 @@ if (api_is_allowed_to_edit()) { /*if ($_POST){ Display::display_error_message(get_lang('FormHasErrorsPleaseComplete')); }*/ - if (strlen($_POST['blog_name'])==0) { + /*if (strlen($_POST['blog_name'])==0) { if (count($_POST)>0) { Display::display_error_message(get_lang('FormHasErrorsPleaseComplete')); } - } + }*/ Blog::display_new_blog_form(); } } 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..b99a9135b1 100755 --- a/main/chat/chat.php +++ b/main/chat/chat.php @@ -6,7 +6,6 @@ * @package chamilo.chat */ -$language_file = array('chat'); require_once '../inc/global.inc.php'; $current_course_tool = TOOL_CHAT; $this_section = SECTION_COURSES; @@ -26,7 +25,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/chat/chat_chat.php b/main/chat/chat_chat.php index d01589593d..4e46ed1f31 100755 --- a/main/chat/chat_chat.php +++ b/main/chat/chat_chat.php @@ -10,7 +10,6 @@ define('FRAME', 'chat'); -$language_file = array('chat'); require_once '../inc/global.inc.php'; $course = $_GET['cidReq']; diff --git a/main/chat/chat_hidden.php b/main/chat/chat_hidden.php index e0eb4ddaf4..28e9779970 100755 --- a/main/chat/chat_hidden.php +++ b/main/chat/chat_hidden.php @@ -10,8 +10,6 @@ define('FRAME', 'hidden'); -$language_file = array('chat'); - require_once '../inc/global.inc.php'; require_once 'chat_functions.lib.php'; diff --git a/main/chat/chat_message.php b/main/chat/chat_message.php index 1f0a1274e3..c78356aefc 100755 --- a/main/chat/chat_message.php +++ b/main/chat/chat_message.php @@ -10,7 +10,6 @@ */ define('FRAME', 'message'); -$language_file = array('chat'); require_once '../inc/global.inc.php'; require_once api_get_path(SYS_CODE_PATH).'chat/chat_functions.lib.php'; diff --git a/main/chat/chat_whoisonline.php b/main/chat/chat_whoisonline.php index 73f134c8d4..319f46847e 100755 --- a/main/chat/chat_whoisonline.php +++ b/main/chat/chat_whoisonline.php @@ -8,7 +8,6 @@ */ define('FRAME', 'online'); -$language_file = array('chat'); require_once '../inc/global.inc.php'; diff --git a/main/course_description/add.php b/main/course_description/add.php index 98b5b2c03f..12a7acb49d 100755 --- a/main/course_description/add.php +++ b/main/course_description/add.php @@ -54,12 +54,7 @@ $form->addElement('hidden', 'description_type',$description_type); $form->addElement('hidden', 'sec_token',$token); $form->add_textfield('title', get_lang('Title'), true, array('size'=>'width: 350px;')); $form->applyFilter('title','html_filter'); - -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - WCAG_rendering::prepare_admin_form($description_content, $form); -} else { - $form->add_html_editor('contentDescription', get_lang('Content'), true, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); -} +$form->add_html_editor('contentDescription', get_lang('Content'), true, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"'); // display default questions @@ -68,10 +63,4 @@ if (isset ($question[$description_type])) { $message .= $question[$description_type]; Display::display_normal_message($message, false); } -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - echo (WCAG_Rendering::editor_header()); -} $form->display(); -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - echo (WCAG_Rendering::editor_footer()); -} 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..f25b71c621 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'); + + $message = $success ? get_lang('CourseDescriptionUpdated') : 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/course_description_controller.php b/main/course_description/course_description_controller.php index e642204b15..323d6c87e8 100755 --- a/main/course_description/course_description_controller.php +++ b/main/course_description/course_description_controller.php @@ -45,7 +45,7 @@ class CourseDescriptionController $data['descriptions'] = array($data['descriptions']); } foreach ($data['descriptions'] as $description) { - if (strpos($description, '= ADD_BLOCK) { $course_description->set_description_type($description_type); diff --git a/main/course_description/course_description_form.class.php b/main/course_description/course_description_form.class.php index a3b09f670e..2546b778e1 100755 --- a/main/course_description/course_description_form.class.php +++ b/main/course_description/course_description_form.class.php @@ -70,14 +70,14 @@ class CourseDescriptionForm extends \FormValidator $defaults['title'] = $description->title; $defaults['content'] = $description->content; - $this->add_header($description->get_title()); - $this->add_hidden('description_type', $description->get_description_type()); - $this->add_hidden('c_id', $description->c_id); - $this->add_hidden('id', $description->id); + $this->addHeader($description->get_title()); + $this->addHidden('description_type', $description->get_description_type()); + $this->addHidden('c_id', $description->c_id); + $this->addHidden('id', $description->id); $this->add_textfield('title', get_lang('Title'), true, array('size' => 'width: 350px;')); $this->applyFilter('title', 'html_filter'); $this->add_html_editor('content', get_lang('Content'), true, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); - $this->add_button('save', get_lang('Save'), 'class="save"'); + $this->addButton('save', get_lang('Save'), 'class="save"'); $this->setDefaults($defaults); } diff --git a/main/course_description/edit.php b/main/course_description/edit.php index 07addda21d..707c29f8d1 100755 --- a/main/course_description/edit.php +++ b/main/course_description/edit.php @@ -11,7 +11,7 @@ api_protect_course_script(true); $original_id = $id; -if (!$error) { +if (empty($error)) { $token = Security::get_token(); } // display categories @@ -58,17 +58,16 @@ $form->addElement('hidden', 'description_type',$description_type); $form->addElement('hidden', 'sec_token',$token); $form->add_textfield('title', get_lang('Title'), true, array('size'=>'50')); $form->applyFilter('title','html_filter'); - -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - WCAG_rendering::prepare_admin_form($description_content, $form); -} else { - $form->add_html_editor('contentDescription', get_lang('Content'), true, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); -} +$form->add_html_editor('contentDescription', get_lang('Content'), true, false, array('ToolbarSet' => 'TrainingDescription', 'Width' => '100%', 'Height' => '200')); $form->addElement('style_submit_button', null, get_lang('Save'), 'class="save"'); // Set some default values -$default['title'] = Security::remove_XSS($description_title); -$default['contentDescription'] = Security::remove_XSS($description_content,COURSEMANAGERLOWSECURITY); +if (!empty($description_title)) { + $default['title'] = Security::remove_XSS($description_title); +} +if (!empty($description_content)) { + $default['contentDescription'] = Security::remove_XSS($description_content,COURSEMANAGERLOWSECURITY); +} $default['description_type'] = $description_type; $form->setDefaults($default); @@ -78,12 +77,4 @@ if (isset ($question[$description_type])) { $message .= $question[$description_type]; Display::display_normal_message($message, false); } - -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - echo (WCAG_Rendering::editor_header()); -} - $form->display(); -if (api_get_setting('wcag_anysurfer_public_pages')=='true') { - echo (WCAG_Rendering::editor_footer()); -} diff --git a/main/course_description/index.php b/main/course_description/index.php index af445e2b6e..ec2816f848 100755 --- a/main/course_description/index.php +++ b/main/course_description/index.php @@ -7,9 +7,6 @@ * @package chamilo.course_description */ -// name of the language file that needs to be included -$language_file = array ('course_description', 'accessibility'); - // including files require_once '../inc/global.inc.php'; $current_course_tool = TOOL_COURSE_DESCRIPTION; 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_description/listing.php b/main/course_description/listing.php index fb114839a8..226a5b0fcb 100755 --- a/main/course_description/listing.php +++ b/main/course_description/listing.php @@ -60,7 +60,7 @@ if (isset($descriptions) && count($descriptions) > 0) { $description['title'] = $description['title'].' '.api_get_session_image(api_get_session_id(), $user_info['status']); //delete - echo ''; + echo ''; echo Display::return_icon('delete.png', get_lang('Delete'), array('style' => 'vertical-align:middle;float:right;'),ICON_SIZE_SMALL); echo ' '; diff --git a/main/course_description/upload_file_form.class.php b/main/course_description/upload_file_form.class.php index 63cc3fb25f..f0021715e0 100755 --- a/main/course_description/upload_file_form.class.php +++ b/main/course_description/upload_file_form.class.php @@ -14,7 +14,7 @@ use Chamilo; /** * Form to upload a file. - * + * * @license /licence.txt * @author Laurent Opprecht */ @@ -28,19 +28,19 @@ class UploadFileForm extends \FormValidator /** * - * + * */ function init() { $form_name = get_lang('UploadFile'); - $this->add_header($form_name); + $this->addHeader($form_name); $label = get_lang('File'); $this->add_file('file', $label); $this->addRule('file', get_lang('ThisFieldIsRequired'), 'required'); //$this->add_checkbox('replace', '', get_lang('ReplaceExistingEntries')); - $this->add_button('save', get_lang('Save'), array('class' => 'btn save')); + $this->addButton('save', get_lang('Save'), array('class' => 'btn save')); // $label = get_lang('CSVMustLookLike'); // $label = "

    $label

    "; 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_info/infocours.php b/main/course_info/infocours.php index 3d988d7731..d250704491 100755 --- a/main/course_info/infocours.php +++ b/main/course_info/infocours.php @@ -22,9 +22,6 @@ $this_section = SECTION_COURSES; $nameTools = get_lang('ModifInfo'); -/* Libraries */ -require_once api_get_path(INCLUDE_PATH).'conf/course_info.conf.php'; - api_protect_course_script(true); api_block_anonymous_users(); $_course = api_get_course_info(); diff --git a/main/course_info/start.php b/main/course_info/start.php index b5413f0d47..3a374c2deb 100644 --- a/main/course_info/start.php +++ b/main/course_info/start.php @@ -3,7 +3,7 @@ use \ChamiloSession as Session; -$language_file = array('create_course', 'registration','admin','exercice', 'course_description', 'course_info'); +$language_file = array('create_course', 'registration','admin','exercice', 'course_info'); require_once '../inc/global.inc.php'; diff --git a/main/course_progress/index.php b/main/course_progress/index.php index 9747361014..6f678a8f42 100755 --- a/main/course_progress/index.php +++ b/main/course_progress/index.php @@ -8,7 +8,7 @@ */ // name of the language file that needs to be included -$language_file = array('course_description', 'userInfo', 'admin'); +$language_file = array('userInfo', 'admin'); // including files require_once '../inc/global.inc.php'; @@ -94,72 +94,7 @@ $default_thematic_plan_title = $thematic->get_default_thematic_plan_title(); $htmlHeadXtra[] = ''; 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/course_progress/thematic.php b/main/course_progress/thematic.php index fad5f7fa88..e32a81cb23 100755 --- a/main/course_progress/thematic.php +++ b/main/course_progress/thematic.php @@ -13,6 +13,8 @@ api_protect_course_script(true); $token = Security::get_token(); $url_token = "&sec_token=".$token; +$user_info = api_get_user_info(); +$param_gradebook = '&'.api_get_cidreq(); if (api_is_allowed_to_edit(null, true)) { echo '
    '; @@ -20,27 +22,37 @@ if (api_is_allowed_to_edit(null, true)) { switch ($action) { case 'thematic_add' : case 'thematic_import_select' : - echo ''.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ThematicDetails'),'',ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ThematicDetails'),'',ICON_SIZE_MEDIUM).''; break; case 'thematic_list' : - echo ''.Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; break; case 'thematic_details' : - echo ''.Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; - echo ''.Display::return_icon('import_csv.png',get_lang('ImportThematic'),'',ICON_SIZE_MEDIUM).''; - echo ''.Display::return_icon('export_csv.png',get_lang('ExportThematic'),'', ICON_SIZE_MEDIUM).''; - echo ''.Display::return_icon('pdf.png',get_lang('ExportToPDF'),'', ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('import_csv.png',get_lang('ImportThematic'),'',ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('export_csv.png',get_lang('ExportThematic'),'', ICON_SIZE_MEDIUM).''; + echo ''. + Display::return_icon('pdf.png',get_lang('ExportToPDF'),'', ICON_SIZE_MEDIUM).''; break; default : - echo ''.Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; - + echo ''. + Display::return_icon('new_course_progress.png',get_lang('NewThematicSection'),'',ICON_SIZE_MEDIUM).''; } echo '
    '; } if ($action == 'thematic_list') { - $table = new SortableTable('thematic_list', array('Thematic', 'get_number_of_thematics'), array('Thematic', 'get_thematic_data')); + $table = new SortableTable( + 'thematic_list', + array('Thematic', 'get_number_of_thematics'), + array('Thematic', 'get_thematic_data') + ); $parameters['action'] = $action; $table->set_additional_parameters($parameters); @@ -59,9 +71,14 @@ if ($action == 'thematic_list') { } if (isset($last_id) && $last_id) { - $link_to_thematic_plan = ''.Display::return_icon('lesson_plan.png', get_lang('ThematicPlan'), array('style'=>'vertical-align:middle;float:none;'),ICON_SIZE_SMALL).''; - $link_to_thematic_advance = ''.Display::return_icon('lesson_plan_calendar.png', get_lang('ThematicAdvance'), array('style'=>'vertical-align:middle;float:none;'),ICON_SIZE_SMALL).''; - Display::display_confirmation_message(get_lang('ThematicSectionHasBeenCreatedSuccessfull').'
    '.sprintf(get_lang('NowYouShouldAddThematicPlanXAndThematicAdvanceX'),$link_to_thematic_plan, $link_to_thematic_advance), false); + $link_to_thematic_plan = ''. + Display::return_icon('lesson_plan.png', get_lang('ThematicPlan'), array('style'=>'vertical-align:middle;float:none;'),ICON_SIZE_SMALL).''; + $link_to_thematic_advance = ''. + Display::return_icon('lesson_plan_calendar.png', get_lang('ThematicAdvance'), array('style'=>'vertical-align:middle;float:none;'),ICON_SIZE_SMALL).''; + Display::display_confirmation_message( + get_lang('ThematicSectionHasBeenCreatedSuccessfull').'
    '.sprintf(get_lang('NowYouShouldAddThematicPlanXAndThematicAdvanceX'),$link_to_thematic_plan, $link_to_thematic_advance), + false + ); } // display title @@ -74,13 +91,11 @@ if ($action == 'thematic_list') { echo '
    '; } - // display thematic data - + // Display thematic data if (!empty($thematic_data)) { // display progress echo '

    '.get_lang('Progress').': '.$total_average_of_advances.' %

    '; - echo ''; echo ''; foreach ($thematic_data as $thematic) { @@ -94,17 +109,14 @@ if ($action == 'thematic_list') { } //@todo add a validation in order to load or not course thematics in the session thematic - /* - if (api_get_session_id() == $thematic['session_id']) { - $session_star = api_get_session_image(api_get_session_id(), $user_info['status']); - } else { - continue; - } */ echo ''; $actions_first_col = ''; if (api_is_allowed_to_edit(null, true)) { // Thematic title - $actions_first_col = Display::url(Display::return_icon('cd.gif', get_lang('Copy')), 'index.php?'.api_get_cidreq().'&action=thematic_copy&thematic_id='.$my_thematic_id.$param_gradebook.$url_token); + $actions_first_col = Display::url( + Display::return_icon('cd.gif', get_lang('Copy')), + 'index.php?'.api_get_cidreq().'&action=thematic_copy&thematic_id='.$my_thematic_id.$param_gradebook.$url_token + ); if (api_get_session_id() == 0 ) { if ($thematic['display_order'] > 1) { @@ -112,7 +124,7 @@ if ($action == 'thematic_list') { } else { $actions_first_col .= ' '.Display::return_icon('up_na.png',' ','',ICON_SIZE_SMALL); } - if ($thematic['display_order'] < $thematic['max_thematic_item']) { + if (isset($thematic['max_thematic_item']) && $thematic['display_order'] < $thematic['max_thematic_item']) { $actions_first_col .= ' '.Display::return_icon('down.png',get_lang('Down'),'',ICON_SIZE_SMALL).''; } else { $actions_first_col .= ' '.Display::return_icon('down_na.png',' ','',ICON_SIZE_SMALL); @@ -152,7 +164,8 @@ if ($action == 'thematic_list') { //if (api_is_allowed_to_edit(null, true) && api_get_session_id() == $thematic['session_id']) { if (api_is_allowed_to_edit(null, true)) { - echo ''; + echo ''; } //if (api_is_allowed_to_edit(null, true) && api_get_session_id() == $thematic['session_id']) { @@ -172,7 +185,10 @@ if ($action == 'thematic_list') { Display::return_icon('delete.png',get_lang('Delete'),'',ICON_SIZE_SMALL).''; //Links - $edit_link = Display::div(Display::div($edit_link , array('id'=>'thematic_advance_tools_'.$thematic_advance['id'], 'class'=>'thematic_advance_actions')), array('style'=>'height:20px;')); + $edit_link = Display::div( + Display::div($edit_link , array('id'=>'thematic_advance_tools_'.$thematic_advance['id'], 'class'=>'thematic_advance_actions')), + array('style'=>'height:20px;') + ); } $thematic_advance_item = isset($thematic_advance_div[$thematic['id']][$thematic_advance['id']]) ? $thematic_advance_div[$thematic['id']][$thematic_advance['id']] : null; @@ -256,7 +272,7 @@ if ($action == 'thematic_list') { } // error messages - if ($error) { + if (isset($error)) { Display::display_error_message(get_lang('FormHasErrorsPleaseComplete'),false); } if ($show_form) diff --git a/main/course_progress/thematic_advance.php b/main/course_progress/thematic_advance.php index 3a47139c97..6c352340d2 100755 --- a/main/course_progress/thematic_advance.php +++ b/main/course_progress/thematic_advance.php @@ -47,7 +47,7 @@ if ($action == 'thematic_advance_add' || $action == 'thematic_advance_edit') { $form->addElement('html', ''); if (isset($thematic_advance_data['attendance_id']) && $thematic_advance_data['attendance_id'] == 0) { diff --git a/main/coursecopy/classes/CourseRestorer.class.php b/main/coursecopy/classes/CourseRestorer.class.php index ded898c1bc..c7bf87b65e 100755 --- a/main/coursecopy/classes/CourseRestorer.class.php +++ b/main/coursecopy/classes/CourseRestorer.class.php @@ -1132,7 +1132,13 @@ class CourseRestorer $resources = $this->course->resources; foreach ($resources[RESOURCE_EVENT] as $id => $event) { // check resources inside html from fckeditor tool and copy correct urls into recipient course - $event->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($event->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $event->content = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $event->content, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $sql = "INSERT INTO ".$table." SET c_id = ".$this->destination_course_id." , @@ -1203,7 +1209,13 @@ class CourseRestorer } // check resources inside html from fckeditor tool and copy correct urls into recipient course - $description_content = DocumentManager::replace_urls_inside_content_html_from_copy_course($cd->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $description_content = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $cd->content, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $condition_session = ""; if (!empty($session_id)) { @@ -1229,7 +1241,13 @@ class CourseRestorer foreach ($resources[RESOURCE_ANNOUNCEMENT] as $id => $announcement) { // check resources inside html from fckeditor tool and copy correct urls into recipient course - $announcement->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($announcement->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $announcement->content = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $announcement->content, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $sql = "INSERT INTO ".$table." " ."SET c_id = ".$this->destination_course_id." , @@ -2359,7 +2377,13 @@ class CourseRestorer } // check resources inside html from fckeditor tool and copy correct urls into recipient course - $glossary->description = DocumentManager::replace_urls_inside_content_html_from_copy_course($glossary->description, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $glossary->description = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $glossary->description, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $sql = "INSERT INTO " . $table_glossary . " SET c_id = " . $this->destination_course_id . " , @@ -2403,24 +2427,29 @@ class CourseRestorer $resources = $this->course->resources; foreach ($resources[RESOURCE_WIKI] as $id => $wiki) { - //$wiki = new Wiki($obj->page_id, $obj->reflink, $obj->title, $obj->content, $obj->user_id, $obj->group_id, $obj->dtime); // the sql statement to insert the groups from the old course to the new course // check resources inside html from fckeditor tool and copy correct urls into recipient course - $wiki->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($wiki->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $wiki->content = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $wiki->content, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $sql = "INSERT INTO $table_wiki (c_id, page_id, reflink, title, content, user_id, group_id, dtime, progress, version, session_id) VALUES ( - ".$this->destination_course_id." , - '".self::DBUTF8escapestring($wiki->page_id)."', - '".self::DBUTF8escapestring($wiki->reflink)."', - '".self::DBUTF8escapestring($wiki->title)."', - '".self::DBUTF8escapestring($wiki->content)."', - '".intval($wiki->user_id)."', - '".intval($wiki->group_id)."', - '".self::DBUTF8escapestring($wiki->dtime)."', - '".self::DBUTF8escapestring($wiki->progress)."', - '".intval($wiki->version)."', - '".(!empty($session_id)?intval($session_id):0)."')"; + ".$this->destination_course_id." , + '".self::DBUTF8escapestring($wiki->page_id)."', + '".self::DBUTF8escapestring($wiki->reflink)."', + '".self::DBUTF8escapestring($wiki->title)."', + '".self::DBUTF8escapestring($wiki->content)."', + '".intval($wiki->user_id)."', + '".intval($wiki->group_id)."', + '".self::DBUTF8escapestring($wiki->dtime)."', + '".self::DBUTF8escapestring($wiki->progress)."', + '".intval($wiki->version)."', + '".(!empty($session_id)?intval($session_id):0)."')"; Database::query($sql); $new_id = Database::insert_id(); $this->course->resources[RESOURCE_WIKI][$id]->destination_id = $new_id; @@ -2450,7 +2479,13 @@ class CourseRestorer foreach ($resources[RESOURCE_THEMATIC] as $id => $thematic) { // check resources inside html from fckeditor tool and copy correct urls into recipient course - $thematic->content = DocumentManager::replace_urls_inside_content_html_from_copy_course($thematic->content, $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $thematic->content = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $thematic->content, + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $thematic->params['c_id'] = $this->destination_course_id; $thematic->params['id'] = null; $last_id = Database::insert($table_thematic, $thematic->params, false); @@ -2499,7 +2534,13 @@ class CourseRestorer foreach ($resources[RESOURCE_ATTENDANCE] as $id => $obj) { // check resources inside html from fckeditor tool and copy correct urls into recipient course - $obj->params['description'] = DocumentManager::replace_urls_inside_content_html_from_copy_course($obj->params['description'], $this->course->code, $this->course->destination_path, $this->course->backup_path, $this->course->info['path']); + $obj->params['description'] = DocumentManager::replace_urls_inside_content_html_from_copy_course( + $obj->params['description'], + $this->course->code, + $this->course->destination_path, + $this->course->backup_path, + $this->course->info['path'] + ); $obj->params['id'] = null; $obj->params['c_id'] = $this->destination_course_id; diff --git a/main/create_course/add_course.php b/main/create_course/add_course.php index 95b419178f..b9ccb4a850 100755 --- a/main/create_course/add_course.php +++ b/main/create_course/add_course.php @@ -14,7 +14,7 @@ use \ChamiloSession as Session; // Name of the language file that needs to be included. -$language_file = array('create_course', 'registration','admin','exercice', 'course_description', 'course_info'); +$language_file = array('create_course', 'registration','admin','exercice', 'course_info'); // Flag forcing the "current course" reset. $cidReset = true; @@ -33,9 +33,6 @@ if (api_get_setting('course_validation') == 'true' && !api_is_platform_admin()) $course_validation_feature = true; } -// Require additional libraries. -require_once api_get_path(CONFIGURATION_PATH).'course_info.conf.php'; - $htmlHeadXtra[] = ''; //I'm in the certification module? @@ -183,9 +96,9 @@ if (!empty($sessionId) && empty($document_data)) { if (empty($document_data)) { if (api_is_in_group()) { - $group_properties = GroupManager::get_group_properties($groupId); - $document_id = DocumentManager::get_document_id($_course, $group_properties['directory']); - $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id()); + $group_properties = GroupManager::get_group_properties($groupId); + $document_id = DocumentManager::get_document_id($_course, $group_properties['directory']); + $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id()); $dir = $document_data['path']; $folder_id = $document_data['id']; } else { @@ -240,9 +153,6 @@ for ($i = 0; $i < ($count_dir); $i++) { $relative_url .= '../'; } -/* We do this in order to avoid the condition in html_editor.php ==> if - ($this -> fck_editor->Config['CreateDocumentWebDir']=='' || $this -> fck_editor->Config['CreateDocumentDir']== '')* -*/ if ($relative_url== '') { $relative_url = '/'; } @@ -281,7 +191,7 @@ if (!$is_certificate_mode) { $req_gid = null; if (api_is_in_group()) { $req_gid = '&gidReq='.api_get_group_id(); - $interbreadcrumb[] = array ("url" => "../group/group_space.php?gidReq=".api_get_group_id(), "name" => get_lang('GroupSpace')); + $interbreadcrumb[] = array ("url" => "../group/group_space.php?".api_get_cidreq(), "name" => get_lang('GroupSpace')); $noPHP_SELF = true; $to_group_id = api_get_group_id(); $path = explode('/', $dir); @@ -300,14 +210,13 @@ if (!$is_allowed_in_course) { if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || - is_my_shared_folder($userId, $dir, api_get_session_id())) + DocumentManager::is_my_shared_folder($userId, $dir, api_get_session_id())) ) { api_not_allowed(true); } /* Header */ - -event_access_tool(TOOL_DOCUMENT); +Event::event_access_tool(TOOL_DOCUMENT); $display_dir = $dir; if (isset($group_properties)) { @@ -363,11 +272,6 @@ function document_exists($filename) { api_get_session_id(), api_get_group_id() ); - /*$filename = addslashes(trim($filename)); - $filename = Security::remove_XSS($filename); - $filename = replace_dangerous_char($filename); - $filename = disable_dangerous_file($filename); - return !file_exists($filepath.$filename.'.html');*/ } // Add group to the form @@ -393,7 +297,7 @@ $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is // If we are not in the certificates creation, display a folder chooser for the // new document created -if (!$is_certificate_mode && !is_my_shared_folder($userId, $dir, $current_session_id)) { +if (!$is_certificate_mode && !DocumentManager::is_my_shared_folder($userId, $dir, $current_session_id)) { $folders = DocumentManager::get_all_document_folders($_course, $to_group_id, $is_allowed_to_edit); $parent_select = $form->addElement('select', 'curdirpath', array(null, get_lang('DestinationDirectory'))); @@ -404,19 +308,19 @@ if (!$is_certificate_mode && !is_my_shared_folder($userId, $dir, $current_sessio if (is_array($folders)) { $escaped_folders = array(); foreach ($folders as $key => & $val) { - //Hide some folders + // Hide some folders if ($val=='/HotPotatoes_files' || $val=='/certificates' || basename($val)=='css'){ continue; } - //Admin setting for Hide/Show the folders of all users + // Admin setting for Hide/Show the folders of all users if (api_get_setting('show_users_folders') == 'false' && (strstr($val, '/shared_folder') || strstr($val, 'shared_folder_session_'))){ continue; } - //Admin setting for Hide/Show Default folders to all users + // Admin setting for Hide/Show Default folders to all users if (api_get_setting('show_default_folders') == 'false' && ($val=='/images' || $val=='/flash' || $val=='/audio' || $val=='/video' || strstr($val, '/images/gallery') || $val=='/video/flv')){ continue; } - //Admin setting for Hide/Show chat history folder + // Admin setting for Hide/Show chat history folder if (api_get_setting('show_chat_folder') == 'false' && $val=='/chat_files'){ continue; } 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 f1b9e0ce64..7695ffcc03 100755 --- a/main/document/document.php +++ b/main/document/document.php @@ -29,7 +29,7 @@ use \ChamiloSession as Session; // Language files that need to be included -$language_file = array('document', 'slideshow', 'gradebook', 'create_course'); +$language_file = array('document', 'gradebook', 'create_course'); require_once '../inc/global.inc.php'; $current_course_tool = TOOL_DOCUMENT; $this_section = SECTION_COURSES; @@ -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 @@ -1285,15 +1285,14 @@ if ($is_allowed_to_edit || // Show them the form for the directory name if (isset($_GET['createdir'])) { - $dirForm = create_dir_form($document_id); + $dirForm = DocumentManager::create_dir_form($document_id); } } /* VISIBILITY COMMANDS */ if ($is_allowed_to_edit) { if ((isset($_GET['set_invisible']) && !empty($_GET['set_invisible'])) || - (isset($_GET['set_visible']) && !empty($_GET['set_visible'])) && - $_GET['set_visible'] != '*' && $_GET['set_invisible'] != '*' + (isset($_GET['set_visible']) && !empty($_GET['set_visible'])) ) { // Make visible or invisible? if (isset($_GET['set_visible'])) { @@ -1328,7 +1327,6 @@ if ($is_allowed_to_edit) { null, $sessionId) ) { - //don't use ViMod because firt is load ViMdod (Gradebook). VisibilityChanged (trad4all) $message = Display::return_message(get_lang('VisibilityChanged'), 'confirmation'); } else { $message = Display::return_message(get_lang('ViModProb'), 'error'); diff --git a/main/document/document_lite.php b/main/document/document_lite.php index 1117a2b3e0..1534e6abb5 100755 --- a/main/document/document_lite.php +++ b/main/document/document_lite.php @@ -12,7 +12,7 @@ exit; // Language files that need to be included -$language_file = array('document', 'slideshow', 'gradebook', 'create_course'); +$language_file = array('document', 'gradebook', 'create_course'); require_once '../inc/global.inc.php'; $this_section = SECTION_COURSES; @@ -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 @@ -590,7 +590,7 @@ if ($is_allowed_to_edit) { /* TEMPLATE ACTION */ //Only teacher and all users into their group -if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)){ +if ($is_allowed_to_edit || $group_member_with_upload_rights || DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)){ if (isset($_GET['add_as_template']) && !isset($_POST['create_template'])) { $document_id_for_template = intval($_GET['add_as_template']); 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 0933f572d6..080435518e 100755 --- a/main/document/downloadfolder.inc.php +++ b/main/document/downloadfolder.inc.php @@ -93,6 +93,11 @@ function fixDocumentNameCallback($p_event, &$p_header) $documentData['to_group_id'] ); + // Changes file.phps to file.php + $basename = basename($documentNameFixed); + $basenamePHPFixed = str_replace('.phps', '.php', $basename); + $documentNameFixed = str_replace($basename, $basenamePHPFixed, $basenamePHPFixed); + $p_header['stored_filename'] = $documentNameFixed; return 1; @@ -274,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/save_pixlr.php b/main/document/save_pixlr.php index f836a2850c..9fe49df5a8 100755 --- a/main/document/save_pixlr.php +++ b/main/document/save_pixlr.php @@ -12,7 +12,6 @@ * Code */ require_once '../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; api_protect_course_script(); api_block_anonymous_users(); diff --git a/main/document/showinframesmin.php b/main/document/showinframesmin.php index a52723afc6..70fdac007e 100755 --- a/main/document/showinframesmin.php +++ b/main/document/showinframesmin.php @@ -12,9 +12,6 @@ $language_file[] = 'document'; require_once '../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'document.lib.php'; -require_once api_get_path(LIBRARY_PATH).'glossary.lib.php'; -require_once api_get_path(LIBRARY_PATH).'groupmanager.lib.php'; // Protection api_protect_course_script(); diff --git a/main/document/slideshow.php b/main/document/slideshow.php index 37e3309e66..9683a2e58d 100755 --- a/main/document/slideshow.php +++ b/main/document/slideshow.php @@ -8,7 +8,7 @@ */ // Language files that need to be included -$language_file = array('slideshow', 'document'); +$language_file = array('document'); require_once '../inc/global.inc.php'; api_protect_course_script(); diff --git a/main/document/slideshowoptions.php b/main/document/slideshowoptions.php index 5aa1c34e01..e340149224 100755 --- a/main/document/slideshowoptions.php +++ b/main/document/slideshowoptions.php @@ -22,7 +22,7 @@ */ // Language files that need to be included -$language_file = array('slideshow', 'document'); +$language_file = array('document'); require_once '../inc/global.inc.php'; api_protect_course_script(); 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/dropbox_functions.inc.php b/main/dropbox/dropbox_functions.inc.php index cd4170081e..ffd9fd38d6 100755 --- a/main/dropbox/dropbox_functions.inc.php +++ b/main/dropbox/dropbox_functions.inc.php @@ -1241,7 +1241,7 @@ function check_number_feedback($key, $array) { /** * Get the last access to a given tool of a given user * @param $tool string the tool constant - * @param $course_code the course_id + * @param $courseId the course_id * @param $user_id the id of the user * @return string last tool access date * @@ -1250,11 +1250,11 @@ function check_number_feedback($key, $array) { * * @todo consider moving this function to a more appropriate place. */ -function get_last_tool_access($tool, $course_code = '', $user_id='') +function get_last_tool_access($tool, $courseId = null, $user_id = null) { // The default values of the parameters - if (empty($course_code)) { - $course_code = api_get_course_id(); + if (empty($courseId)) { + $courseId = api_get_course_int_id(); } if (empty($user_id)) { $user_id = api_get_user_id(); @@ -1266,7 +1266,7 @@ function get_last_tool_access($tool, $course_code = '', $user_id='') $sql = "SELECT access_date FROM $table_last_access WHERE access_user_id = ".intval($user_id)." AND - access_cours_code='".Database::escape_string($course_code)."' AND + c_id='".intval($courseId)."' AND access_tool='".Database::escape_string($tool)."' ORDER BY access_date DESC LIMIT 1"; diff --git a/main/dropbox/dropbox_submit.php b/main/dropbox/dropbox_submit.php index c53823cf92..534e157420 100755 --- a/main/dropbox/dropbox_submit.php +++ b/main/dropbox/dropbox_submit.php @@ -16,7 +16,6 @@ * - UPLOAD NEW FILE */ if (isset($_POST['submitWork'])) { - require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'; $error = false; $errormsg = ''; /** 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 c645981b62..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); @@ -68,7 +68,6 @@ header('Last-Modified: '.gmdate('D, d M Y H:i:s',time()+10).' GMT'); */ if ($content_type == 'text/html') { - require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; $directory_name = dirname($full_file_name); $dir=str_replace(array('\\',$_configuration['root_sys']."courses/".$_course['path'].'/document'),array('/',''),$directory_name); diff --git a/main/exercice/admin.php b/main/exercice/admin.php index 602aab1b26..d6be2de610 100755 --- a/main/exercice/admin.php +++ b/main/exercice/admin.php @@ -64,8 +64,6 @@ if (!$is_allowedToEdit) { api_not_allowed(true); } -require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; -require_once api_get_path(LIBRARY_PATH).'document.lib.php'; /* stripslashes POST data */ if($_SERVER['REQUEST_METHOD'] == 'POST') { foreach($_POST as $key=>$val) { @@ -111,11 +109,17 @@ $cancelExercise = isset($cancelExercise) ? $cancelExercise : null; $cancelAnswers = isset($cancelAnswers) ? $cancelAnswers : null; $modifyIn = isset($modifyIn) ? $modifyIn : null; $cancelQuestion = isset($cancelQuestion) ? $cancelQuestion : null; +$_course = api_get_course_info(); /* 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_int_id(), + api_get_session_id() +); // get from session $objExercise = isset($_SESSION['objExercise']) ? $_SESSION['objExercise'] : null; @@ -183,8 +187,6 @@ if (!is_object($objExercise)) { // Exercise can be edited in their course. if ($objExercise->sessionId != $sessionId) { api_not_allowed(true); - /*header('Location: '.api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq()); - exit;*/ } // doesn't select the exercise ID if we come from the question pool @@ -213,7 +215,7 @@ if ($editQuestion || $newQuestion || $modifyQuestion || $modifyAnswers) { } // checks if the object exists - if(is_object($objQuestion)) { + if (is_object($objQuestion)) { // gets the question ID $questionId = $objQuestion->selectId(); } @@ -222,7 +224,7 @@ if ($editQuestion || $newQuestion || $modifyQuestion || $modifyAnswers) { // if cancelling an exercise if ($cancelExercise) { // existing exercise - if($exerciseId) { + if ($exerciseId) { unset($modifyExercise); } else { // new exercise @@ -235,14 +237,14 @@ if ($cancelExercise) { // if cancelling question creation/modification if ($cancelQuestion) { // if we are creating a new question from the question pool - if(!$exerciseId && !$questionId) { + if (!$exerciseId && !$questionId) { // goes back to the question pool header('Location: question_pool.php'); exit(); } else { // goes back to the question viewing - $editQuestion=$modifyQuestion; - unset($newQuestion,$modifyQuestion); + $editQuestion = $modifyQuestion; + unset($newQuestion, $modifyQuestion); } } @@ -272,6 +274,7 @@ if ($cancelAnswers) { $editQuestion=$modifyAnswers; unset($modifyAnswers); } + $nameTools = null; // modifies the query string that is used in the link of tool name if ($editQuestion || $modifyQuestion || $newQuestion || $modifyAnswers) { @@ -289,16 +292,16 @@ if (!empty($gradebook) && $gradebook=='view') { ); } -$interbreadcrumb[] = array("url" => "exercice.php","name" => get_lang('Exercices')); +$interbreadcrumb[] = array("url" => "exercice.php?".api_get_cidreq(),"name" => get_lang('Exercices')); if (isset($_GET['newQuestion']) || isset($_GET['editQuestion']) ) { - $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$objExercise->id, "name" => $objExercise->name); + $interbreadcrumb[] = array("url" => "admin.php?exerciseId=".$objExercise->id.'&'.api_get_cidreq(), "name" => $objExercise->name); } else { $interbreadcrumb[] = array("url" => "#", "name" => $objExercise->name); } // shows a link to go back to the question pool if (!$exerciseId && $nameTools != get_lang('ExerciseManagement')){ - $interbreadcrumb[]=array( + $interbreadcrumb[] = array( "url" => api_get_path(WEB_CODE_PATH)."exercice/question_pool.php?fromExercise=$fromExercise&".api_get_cidreq(), "name" => get_lang('QuestionPool') ); @@ -306,7 +309,7 @@ if (!$exerciseId && $nameTools != get_lang('ExerciseManagement')){ // if the question is duplicated, disable the link of tool name if ($modifyIn == 'thisExercise') { - if($buttonBack) { + if ($buttonBack) { $modifyIn='allExercises'; } else { $noPHP_SELF=true; @@ -329,8 +332,6 @@ function multiple_answer_true_false_onchange(variable) { } document.getElementById(weight_id).value = array_result[result]; } - - '; $htmlHeadXtra[] = " @@ -520,7 +521,6 @@ if ($newQuestion || $editQuestion) { if ($newQuestion == 'yes') { $objExercise->edit_exercise_in_lp = true; } - require 'question_admin.inc.php'; } diff --git a/main/exercice/calculated_answer.class.php b/main/exercice/calculated_answer.class.php index e0d9881024..404b0db958 100644 --- a/main/exercice/calculated_answer.class.php +++ b/main/exercice/calculated_answer.class.php @@ -73,14 +73,6 @@ class CalculatedAnswer extends Question document.getElementById("randomValue"+index).innerHTML = "'.get_lang("ExampleValue").': " + result; } - /*function FCKeditor_OnComplete(editorInstance) { - if (window.attachEvent) { - editorInstance.EditorDocument.attachEvent("onkeyup", updateBlanks) ; - } else { - editorInstance.EditorDocument.addEventListener("keyup", updateBlanks, true); - } - }*/ - CKEDITOR.on("instanceCreated", function(e) { if (e.editor.name === "answer") { e.editor.on("change", updateBlanks); diff --git a/main/exercice/exercice.php b/main/exercice/exercice.php index 735ddc3b00..0aad704027 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, @@ -476,7 +476,6 @@ $offline_icon = Display::return_icon('offline.png', get_lang('Invisible'), array $exercise_list = array(); $exercise_obj = new Exercise(); -//$list_ordered = $exercise_obj->get_exercise_list_ordered(); $list_ordered = null; while ($row = Database :: fetch_array($result, 'ASSOC')) { @@ -623,7 +622,13 @@ 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, + $courseId, + $session_id + ) + ); $move = Display::return_icon('all_directions.png',get_lang('Move'), array('class'=>'moved', 'style'=>'margin-bottom:-0.5em;')); $move = null; @@ -744,7 +749,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 +808,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 +848,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 +991,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 +1004,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..648c6686e6 100755 --- a/main/exercice/exercise.class.php +++ b/main/exercice/exercise.class.php @@ -1018,7 +1018,7 @@ class Exercise $editor_config = array_merge($editor_config, $type); } - $form->addElement ('html','
    '); + $form->addElement ('html',''); @@ -1571,8 +1571,8 @@ class Exercise */ public function clean_results($cleanLpTests = false, $cleanResultBeforeDate = null) { - $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); $sql_where = ' AND orig_lp_id = 0 AND @@ -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, @@ -1710,7 +1710,7 @@ class Exercise $lp_item_view_id = 0, $status = 'incomplete' ) { - $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); if (empty($lp_id)) { $lp_id = 0; } @@ -1758,7 +1758,7 @@ class Exercise $questionList = array(), $weight = 0 ) { - $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); $safe_lp_id = intval($safe_lp_id); $safe_lp_item_id = intval($safe_lp_item_id); $safe_lp_item_view_id = intval($safe_lp_item_view_id); @@ -1772,20 +1772,30 @@ class Exercise if (empty($clock_expired_time)) { $clock_expired_time = 0; } + + $questionList = array_map('intval', $questionList); + + $params = array( + 'exe_exo_id' => $this->id , + 'exe_user_id' => api_get_user_id(), + 'exe_cours_id' => api_get_course_id(), + 'c_id' => api_get_course_int_id(), + 'status' => 'incomplete', + 'session_id' => api_get_session_id(), + 'data_tracking' => implode(',', $questionList) , + 'start_date' => api_get_utc_datetime(), + 'orig_lp_id' => $safe_lp_id, + 'orig_lp_item_id' => $safe_lp_item_id, + 'orig_lp_item_view_id' => $safe_lp_item_view_id, + 'exe_weighting'=> $weight, + ); + if ($this->expired_time != 0) { - $sql_fields = "expired_time_control, "; - $sql_fields_values = "'"."$clock_expired_time"."',"; - } else { - $sql_fields = ""; - $sql_fields_values = ""; + $params['expired_time_control'] = $clock_expired_time; } - $questionList = array_map('intval', $questionList); - $weight = Database::escape_string($weight); - $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, exe_cours_id, status,session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, orig_lp_item_view_id, exe_weighting) - VALUES($sql_fields_values '".$this->id."','" . api_get_user_id() . "','" . api_get_course_id() . "','incomplete','" . api_get_session_id() . "','" . implode(',', $questionList) . "', '" . api_get_utc_datetime() . "', '$safe_lp_id', '$safe_lp_item_id', '$safe_lp_item_view_id', '$weight')"; - Database::query($sql); - $id = Database::insert_id(); + $id = Database::insert($track_exercises, $params); + return $id; } @@ -2141,7 +2151,7 @@ class Exercise $questionId = intval($questionId); $exeId = intval($exeId); - $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); + $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER); // Creates a temporary Question object @@ -2192,7 +2202,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(); @@ -2682,7 +2692,8 @@ class Exercise // for free answer case FREE_ANSWER: if ($from_database) { - $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'"; + $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." + WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'"; $resq = Database::query($query); $choice = Database::result($resq,0,'answer'); $choice = str_replace('\r\n', '', $choice); @@ -2709,7 +2720,8 @@ class Exercise break; case ORAL_EXPRESSION: if ($from_database) { - $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'"; + $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." + WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'"; $resq = Database::query($query); $choice = Database::result($resq,0,'answer'); $choice = str_replace('\r\n', '', $choice); @@ -2809,7 +2821,7 @@ class Exercise } case HOT_SPOT : if ($from_database) { - $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); + $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); $sql = "SELECT hotspot_correct FROM $TBL_TRACK_HOTSPOT WHERE @@ -2847,7 +2859,7 @@ class Exercise case HOT_SPOT_DELINEATION : if ($from_database) { // getting the user answer - $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); + $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); $query = "SELECT hotspot_correct, hotspot_coordinate FROM $TBL_TRACK_HOTSPOT WHERE @@ -2949,11 +2961,7 @@ class Exercise $user_array = substr($user_array,0,-1); if ($next) { - //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); - // Save into db - /* $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 ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')"; - $result = api_sql_query($sql,__FILE__,__LINE__);*/ + $user_answer = $user_array; // we compare only the delineation not the other points @@ -3144,7 +3152,7 @@ class Exercise case HOT_SPOT_DELINEATION: $user_answer = $user_array; if ($next) { - //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); + //$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); // Save into db /* $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 ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')"; @@ -3461,24 +3469,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 +3539,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 +3552,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); } } @@ -3593,7 +3601,7 @@ class Exercise } if ($saved_results) { - $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); $sql = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . floatval($questionScore) . ' WHERE exe_id = ' . $exeId; @@ -3962,9 +3970,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 +4100,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, @@ -4274,7 +4283,7 @@ class Exercise public function get_stat_track_exercise_info_by_exe_id($exe_id) { - $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); $exe_id = intval($exe_id); $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id "; $result = Database::query($sql_track); @@ -4308,7 +4317,7 @@ class Exercise $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id); $question_id = intval($question_id); $exe_id = intval($exe_id); - $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); if ($exercise_info) { if (empty($exercise_info['questions_to_check'])) { @@ -4546,7 +4555,7 @@ class Exercise $ids = is_array($quizId) ? $quizId : array($quizId); $ids = array_map('intval', $ids); $ids = implode(',', $ids); - $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); + $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); if ($sessionId != 0) { $sql = "SELECT * FROM $track_exercises te " . "INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id " diff --git a/main/exercice/exercise.lib.php b/main/exercice/exercise.lib.php deleted file mode 100755 index a05ecf1597..0000000000 --- a/main/exercice/exercise.lib.php +++ /dev/null @@ -1,2939 +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 .= '
    '.get_lang('Thematic').''.get_lang('ThematicPlan').''.get_lang('ThematicAdvance').'
    '; - // 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()) { - require_once api_get_path(LIBRARY_PATH).'document.lib.php'; - $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_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_statistic_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) - 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_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); - $course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); - - $question_id = intval($question_id); - $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) - INNER JOIN $course_user cu - ON cu.course_code = a.course_code AND cu.user_id = exe_user_id - 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 - cu.status = ".STUDENT." AND - relation_type <> 2 AND - e.status = ''"; - $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_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); - $course_user = Database::get_main_table(TABLE_MAIN_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); - - $sql = "SELECT DISTINCT exe_user_id - FROM $track_exercises e - INNER JOIN $track_hotspot a - ON (a.hotspot_exe_id = e.exe_id) - INNER JOIN $course_user cu - ON cu.course_code = a.hotspot_course_code AND cu.user_id = exe_user_id - 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 - cu.status = ".STUDENT." AND - hotspot_correct = 1 AND - relation_type <> 2 AND - e.status = ''"; - - $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); - $course_user = Database::get_main_table(TABLE_MAIN_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 "; - } - - $sql = "SELECT $select_condition - FROM $track_exercises e - INNER JOIN $track_attempt a - ON (a.exe_id = e.exe_id) - INNER JOIN $course_user cu - ON cu.course_code = a.course_code AND cu.user_id = exe_user_id - 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 - cu.status = ".STUDENT." AND - relation_type <> 2 AND - e.status = ''"; - $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_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); - $track_attempt = Database::get_statistic_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_admin.php b/main/exercice/exercise_admin.php index ec6766d614..103793b225 100755 --- a/main/exercice/exercise_admin.php +++ b/main/exercice/exercise_admin.php @@ -33,18 +33,6 @@ $htmlHeadXtra[] = ''; -$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..a61bb90001 100755 --- a/main/exercice/exercise_report.php +++ b/main/exercice/exercise_report.php @@ -28,8 +28,7 @@ api_protect_course_script(true, false, true); // including additional libraries require_once 'hotpotatoes.lib.php'; -// need functions of statsutils lib to display previous exercices scores -require_once api_get_path(LIBRARY_PATH).'statsUtils.lib.inc.php'; +$_course = api_get_course_info(); // document path $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document"; @@ -42,9 +41,9 @@ $is_allowedToEdit = api_is_allowed_to_edit(null, true) || api_is_drh() || api_is $is_tutor = api_is_allowed_to_edit(true); $TBL_QUESTIONS = Database :: get_course_table(TABLE_QUIZ_QUESTION); -$TBL_TRACK_EXERCICES = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES); -$TBL_TRACK_ATTEMPT = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); -$TBL_TRACK_ATTEMPT_RECORDING = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); +$TBL_TRACK_EXERCICES = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES); +$TBL_TRACK_ATTEMPT = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); +$TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING); $TBL_LP_ITEM_VIEW = Database :: get_course_table(TABLE_LP_ITEM_VIEW); $course_id = api_get_course_int_id(); @@ -128,9 +127,11 @@ if (!empty($_REQUEST['export_report']) && $_REQUEST['export_report'] == '1') { //Send student email @todo move this code in a class, library 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); + ($is_allowedToEdit || $is_tutor) +) { + //filtered by post-condition + $id = intval($_GET['exeid']); + $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($id); if (empty($track_exercise_info)) { api_not_allowed(); } @@ -165,8 +166,7 @@ if (isset($_REQUEST['comments']) && } } - $loop_in_track = ($comments_exist === true) ? (count($_POST) / 2) : count($_POST); - + $loop_in_track = $comments_exist === true ? (count($_POST) / 2) : count($_POST); $array_content_id_exe = array(); if ($comments_exist === true) { @@ -184,14 +184,10 @@ if (isset($_REQUEST['comments']) && $my_comments = ''; } $my_questionid = intval($array_content_id_exe[$i]); - $sql = "SELECT question from $TBL_QUESTIONS WHERE c_id = $course_id AND id = '$my_questionid'"; - - $result = Database::query($sql); - Database::result($result, 0, "question"); - $query = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks', teacher_comment = '$my_comments' - WHERE question_id = ".$my_questionid." AND exe_id=".$id; - Database::query($query); + $sql = "UPDATE $TBL_TRACK_ATTEMPT SET marks = '$my_marks', teacher_comment = '$my_comments' + WHERE question_id = ".$my_questionid." AND exe_id=".$id; + Database::query($sql); //Saving results in the track recording table $sql = 'INSERT INTO '.$TBL_TRACK_ATTEMPT_RECORDING.' (exe_id, question_id, marks, insert_date, author, teacher_comment) @@ -229,7 +225,12 @@ if (isset($_REQUEST['comments']) && $message .= $from_name; $message = str_replace("#test#", Security::remove_XSS($test), $message); $message = str_replace("#url#", $url, $message); - MessageManager::send_message_simple($student_id, $subject, $message, api_get_user_id()); + MessageManager::send_message_simple( + $student_id, + $subject, + $message, + api_get_user_id() + ); } //Updating LP score here diff --git a/main/exercice/exercise_result.php b/main/exercice/exercise_result.php index 8bc3a9eb29..7ba03f48ec 100755 --- a/main/exercice/exercise_result.php +++ b/main/exercice/exercise_result.php @@ -19,7 +19,7 @@ use \ChamiloSession as Session; // Name of the language file that needs to be included $language_file = 'exercice'; - +$debug = false; require_once '../inc/global.inc.php'; $this_section = SECTION_COURSES; @@ -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..0cb821dfcc 100755 --- a/main/exercice/exercise_show.php +++ b/main/exercice/exercise_show.php @@ -19,7 +19,7 @@ use \ChamiloSession as Session; $language_file = array('exercice'); require_once '../inc/global.inc.php'; - +$debug = false; if (empty($origin) ) { $origin = isset($_REQUEST['origin']) ? $_REQUEST['origin'] : null; } @@ -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)) { @@ -155,8 +155,7 @@ function getFCK(vals,marksid) { oHidden.type = "hidden"; oHidden.name = "comments_"+ids[k]; if (maxEditors == 0) { - oEditor = FCKeditorAPI.GetInstance(oHidden.name) ; - oHidden.value = oEditor.GetXHTML(true); + oHidden.value = CKEDITOR.instances[oHidden.name].getData(); } else { oHidden.value = $("textarea[name='" + oHidden.name + "']").val(); } @@ -289,7 +288,8 @@ $exercise_content = null; $category_list = array(); $useAdvancedEditor = true; -if (count($questionList) > $maxEditors) { + +if (!empty($maxEditors) && count($questionList) > $maxEditors) { $useAdvancedEditor = false; } @@ -462,9 +462,8 @@ foreach ($questionList as $questionId) { $url=$url_hotspot; } else { //show if no error - //echo 'no error'; - $comment=$answerComment=$objAnswerTmp->selectComment($nbrAnswers); - $answerDestination=$objAnswerTmp->selectDestination($nbrAnswers); + $comment=$answerComment = $objAnswerTmp->selectComment($nbrAnswers); + $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers); } } @@ -527,7 +526,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,8 +541,9 @@ 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( 'html_editor', @@ -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; @@ -685,13 +685,18 @@ if ($origin!='learnpath' || ($origin == 'learnpath' && isset($_GET['fb_type']))) if ($objExercise->selectPropagateNeg() == 0 && $my_total_score_temp < 0) { $my_total_score_temp = 0; } - $total_score_text .= get_question_ribbon($objExercise, $my_total_score_temp, $totalWeighting, true); + $total_score_text .= ExerciseLib::get_question_ribbon( + $objExercise, + $my_total_score_temp, + $totalWeighting, + true + ); $total_score_text .= '
    '; } } if (!empty($category_list) && ($show_results || $show_only_total_score)) { - //Adding total + // Adding total $category_list['total'] = array( 'score' => $my_total_score_temp, 'total' => $totalWeighting @@ -710,20 +715,19 @@ if (is_array($arrid) && is_array($arrmarks)) { if ($is_allowedToEdit && $locked == false && !api_is_drh() && !api_is_student_boss()) { if (in_array($origin, array('tracking_course','user_course','correct_exercise_in_lp'))) { - echo '
    '; + echo ''; echo ''; echo ''; echo ''; echo ' '; echo ' '; } else { - echo ' '; + echo ' '; } if ($origin !='learnpath' && $origin!='student_progress') { - echo ''; ?> -
    diff --git a/main/exercice/exercise_submit.php b/main/exercice/exercise_submit.php index 7b91d2e0df..335b4b3a46 100755 --- a/main/exercice/exercise_submit.php +++ b/main/exercice/exercise_submit.php @@ -33,13 +33,8 @@ $language_file = 'exercice'; require_once '../inc/global.inc.php'; $current_course_tool = TOOL_QUIZ; - $this_section = SECTION_COURSES; - -if ($debug) { - error_log('--- Enter to the exercise_submit.php ---- '); - error_log('0. POST variables : ' . print_r($_POST, 1)); -} +$debug = false; // Notice for unauthorized people. api_protect_course_script(true); @@ -148,7 +143,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 +156,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 +170,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 +194,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 +276,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']) ) { @@ -302,7 +297,7 @@ if (empty($exercise_stat_info)) { } // Array to check in order to block the chat -create_chat_exercise_session($exe_id); +ExerciseLib::create_chat_exercise_session($exe_id); if ($debug) { error_log('6. $objExercise->get_stat_track_exercise_info function called:: '.print_r($exercise_stat_info, 1)); }; @@ -337,7 +332,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 +499,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 +558,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, @@ -893,17 +888,12 @@ if (!empty($error)) { //3. Hotspots var hotspot = $(\'*[name*="hotspot[\'+question_id+\']"]\').serialize(); - //Checking FCK - if (typeof(FCKeditorAPI) !== "undefined") { - var oEditor = FCKeditorAPI.GetInstance("choice["+question_id+"]") ; - var fck_content = ""; - - if (oEditor) { - fck_content = oEditor.GetHTML(); - my_choice = {}; - my_choice["choice["+question_id+"]"] = fck_content; - my_choice = $.param(my_choice); - } + // Checking FCK + if (CKEDITOR.instances["choice["+question_id+"]"]) { + fck_content = CKEDITOR.instances["choice["+question_id+"]"].getData(); + my_choice = {}; + my_choice["choice["+question_id+"]"] = fck_content; + my_choice = $.param(my_choice); } if ($(\'input[name="remind_list[\'+question_id+\']"]\').is(\':checked\')) { @@ -967,19 +957,13 @@ if (!empty($error)) { var free_answers = {}; $.each(question_list, function(index, my_question_id) { - //Checking FCK - if (typeof(FCKeditorAPI) !== "undefined") { - var oEditor = FCKeditorAPI.GetInstance("choice["+my_question_id+"]") ; - var fck_content = ""; - if (oEditor) { - fck_content = oEditor.GetHTML(); - //alert(index + " " +my_question_id + " " +fck_content); - free_answers["free_choice["+my_question_id+"]"] = fck_content; - } + // Checking FCK + if (CKEDITOR.instances["choice["+question_id+"]"]) { + fck_content = CKEDITOR.instances["choice["+question_id+"]"].getData(); + free_answers["free_choice["+my_question_id+"]"] = fck_content; } }); - // lok+(fgt)= data base free_answers = $.param(free_answers); $("#save_all_reponse").html("'.addslashes(Display::return_icon('loading1.gif')).'"); @@ -1028,7 +1012,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 +1070,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/hotpotatoes_exercise_report.php b/main/exercice/hotpotatoes_exercise_report.php index 01e272144d..3dda44e5db 100755 --- a/main/exercice/hotpotatoes_exercise_report.php +++ b/main/exercice/hotpotatoes_exercise_report.php @@ -26,8 +26,6 @@ api_protect_course_script(true, false, true); // including additional libraries require_once 'hotpotatoes.lib.php'; -// need functions of statsutils lib to display previous exercices scores -require_once api_get_path(LIBRARY_PATH) . 'statsUtils.lib.inc.php'; // document path $documentPath = api_get_path(SYS_COURSE_PATH).$_course['path']."/document"; diff --git a/main/exercice/hotspot.class.php b/main/exercice/hotspot.class.php index f99c3af02b..16e1486e5b 100755 --- a/main/exercice/hotspot.class.php +++ b/main/exercice/hotspot.class.php @@ -15,19 +15,22 @@ class HotSpot extends Question static $typePicture = 'hotspot.png'; static $explanationLangVar = 'HotSpot'; - function HotSpot() { + public function HotSpot() + { parent::question(); $this -> type = HOT_SPOT; } - function display() { + public function display() + { } - function createForm (&$form, $fck_config=0) { - parent::createForm ($form, $fck_config); + function createForm (&$form, $fck_config=0) + { + parent::createForm($form, $fck_config); global $text, $class; - if(!isset($_GET['editQuestion'])) { - $renderer = $form->defaultRenderer(); + + if (!isset($_GET['editQuestion'])) { $form->addElement('file','imageUpload',array('', get_lang('UploadJpgPicture')) ); // setting the save button here and not in the question class.php @@ -40,10 +43,10 @@ class HotSpot extends Question // Editing a question $form->addElement('style_submit_button','submitQuestion',get_lang('ModifyExercise'), 'class="'.$class.'"'); } - } - function processCreation ($form, $objExercise = null) { + public function processCreation($form, $objExercise = null) + { $file_info = $form -> getSubmitValue('imageUpload'); parent::processCreation ($form, $objExercise); if(!empty($file_info['tmp_name'])) { @@ -65,7 +68,7 @@ class HotSpot extends Question } function createAnswersForm ($form) { - // nothing + // nothing } function processAnswersCreation ($form) { @@ -78,30 +81,34 @@ class HotSpot extends Question */ class HotSpotDelineation extends HotSpot { - static $typePicture = 'hotspot_delineation.gif'; static $explanationLangVar = 'HotspotDelineation'; - function HotSpotDelineation(){ + function HotSpotDelineation() + { parent::question(); $this -> type = HOT_SPOT_DELINEATION; } - function createForm (&$form, $fck_config=0) { + function createForm (&$form, $fck_config=0) + { parent::createForm ($form, $fck_config); } - function processCreation ($form, $objExercise = null) { + function processCreation ($form, $objExercise = null) + { $file_info = $form -> getSubmitValue('imageUpload'); parent::processCreation ($form, $objExercise); } - function createAnswersForm ($form) { + function createAnswersForm ($form) + { parent::createAnswersForm ($form); } - function processAnswersCreation ($form) { + function processAnswersCreation ($form) + { parent::processAnswersCreation ($form); } } diff --git a/main/exercice/hotspot_admin.inc.php b/main/exercice/hotspot_admin.inc.php index 379269df7e..e2fa718c29 100755 --- a/main/exercice/hotspot_admin.inc.php +++ b/main/exercice/hotspot_admin.inc.php @@ -1,14 +1,13 @@ selectTitle(); $answerType = $objQuestion->selectType(); $pictureName = $objQuestion->selectPicture(); $debug = 0; // debug variable to get where we are - $okPicture = empty($pictureName) ? false : true; -// if we come from the warning box "this question is used in serveral exercises" +// if we come from the warning box "this question is used in several exercises" + if ($modifyIn) { if ($debug > 0) { echo '$modifyIn was set' . "
    \n"; } - // if the user has chosed to modify the question only in the current exercise + // if the user has chosen to modify the question only in the current exercise if ($modifyIn == 'thisExercise') { // duplicates the question $questionId = $objQuestion->duplicate(); @@ -53,7 +52,6 @@ if ($modifyIn) { $objAnswer->duplicate($questionId); // construction of the duplicated Answers - $objAnswer = new Answer($questionId); } $color = unserialize($color); @@ -69,17 +67,16 @@ if ($modifyIn) { $hotspot_admin_url = api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidreq() . '&exerciseId=' . $exerciseId; // the answer form has been submitted +$submitAnswers = isset($_POST['submitAnswers']) ? true : false; +$buttonBack = isset($_POST['buttonBack']) ? true : false; +$nbrAnswers = isset($_POST['nbrAnswers']) ? intval($_POST['nbrAnswers']) : 0; -$submitAnswers = isset($submitAnswers) ? $submitAnswers : false; -$buttonBack = isset($buttonBack) ? $buttonBack : false; -$nbrAnswers = isset($nbrAnswers) ? $nbrAnswers : 0; if ($submitAnswers || $buttonBack) { - if ($answerType == HOT_SPOT) { - if ($debug > 0) { echo '$submitAnswers or $buttonBack was set' . "
    \n"; } + $questionWeighting = $nbrGoodAnswers = 0; for ($i = 1; $i <= $nbrAnswers; $i++) { if ($debug > 0) { @@ -88,6 +85,7 @@ if ($submitAnswers || $buttonBack) { $reponse[$i] = trim($reponse[$i]); $comment[$i] = trim($comment[$i]); $weighting[$i] = $weighting[$i]; // it can be float + // checks if field is empty if (empty($reponse[$i]) && $reponse[$i] != '0') { $msgErr = get_lang('HotspotGiveAnswers'); @@ -124,7 +122,15 @@ if ($submitAnswers || $buttonBack) { $questionWeighting+=$weighting[$i]; } // creates answer - $objAnswer->createAnswer($reponse[$i], '', $comment[$i], $weighting[$i], $i, $hotspot_coordinates[$i], $hotspot_type[$i]); + $objAnswer->createAnswer( + $reponse[$i], + '', + $comment[$i], + $weighting[$i], + $i, + $hotspot_coordinates[$i], + $hotspot_type[$i] + ); } // end for() // saves the answers into the data base $objAnswer->save(); @@ -141,7 +147,6 @@ if ($submitAnswers || $buttonBack) { echo '$modifyIn was set - end' . "
    \n"; } } else { - if ($debug > 0) { echo '$submitAnswers or $buttonBack was set' . "
    \n"; } @@ -164,23 +169,25 @@ if ($submitAnswers || $buttonBack) { $comment[$i] = trim($comment[$i]); $weighting[$i] = $weighting[$i]; - if (empty($threadhold1[$i])) + if (empty($threadhold1[$i])) { $threadhold1_str = 0; - else + } else { $threadhold1_str = intval($threadhold1[$i]); + } - if (empty($threadhold2[$i])) + if (empty($threadhold2[$i])) { $threadhold2_str = 0; - else + } else { $threadhold2_str = intval($threadhold2[$i]); + } - if (empty($threadhold3[$i])) + if (empty($threadhold3[$i])) { $threadhold3_str = 0; - else + } else { $threadhold3_str = intval($threadhold3[$i]); + } $threadhold_total = $threadhold1_str . ';' . $threadhold2_str . ';' . $threadhold3_str; - //echo '
    ';print_r($_POST);echo '
    '; if ($try[$i] == 'on') { $try_str = 1; @@ -207,9 +214,6 @@ if ($submitAnswers || $buttonBack) { } $destination[$i] = $threadhold_total . '@@' . $try_str . '@@' . $lp_str . '@@' . $question_str . '@@' . $url_str; - // the last answer is the IF NO ERROR section witch has not have the reponse, weight and coordinates values - //if ($i!=$nbrAnswers && !($answerType==HOT_SPOT_DELINEATION)) - // { // checks if field is empty if (empty($reponse[$i]) && $reponse[$i] != '0') { $msgErr = get_lang('HotspotGiveAnswers'); @@ -281,11 +285,29 @@ if ($submitAnswers || $buttonBack) { $questionWeighting+=$weighting[$i]; } // creates answer - $objAnswer->createAnswer($reponse[$i], '', $comment[$i], $weighting[$i], $i, $hotspot_coordinates[$i], $hotspot_type[$i], $destination[$i]); + $objAnswer->createAnswer( + $reponse[$i], + '', + $comment[$i], + $weighting[$i], + $i, + $hotspot_coordinates[$i], + $hotspot_type[$i], + $destination[$i] + ); } // end for() // saves the answers into the data base - $objAnswer->createAnswer('noerror', '', $comment_noerror, '0', $nbrAnswers + 1, null, 'noerror', $destination_noerror); + $objAnswer->createAnswer( + 'noerror', + '', + $comment_noerror, + '0', + $nbrAnswers + 1, + null, + 'noerror', + $destination_noerror + ); $objAnswer->save(); // sets the total weighting of the question @@ -301,7 +323,6 @@ if ($submitAnswers || $buttonBack) { } if ($modifyAnswers) { - if ($debug > 0) { echo str_repeat(' ', 0) . '$modifyAnswers is set' . "
    \n"; } @@ -315,7 +336,6 @@ if ($modifyAnswers) { if ($answerType == HOT_SPOT_DELINEATION) { $try = $_POST['try']; - for ($i = 1; $i <= $nbrAnswers; $i++) { if ($try[$i] == 'on') { $try[$i] = 1; @@ -347,7 +367,6 @@ if ($modifyAnswers) { $destination_items = array(); $destination = array(); - for ($i = 1; $i <= $nbrAnswers; $i++) { $reponse[$i] = $objAnswer->selectAnswer($i); if ($objExercise->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_EXAM) { @@ -400,7 +419,7 @@ if ($modifyAnswers) { $_SESSION['tmp_answers']['destination'] = $destination; } - $lessAnswers = isset($lessAnswers) ? $lessAnswers : false; + $lessAnswers = isset($_POST['lessAnswers']) ? true : false; if ($lessAnswers) { if ($answerType == HOT_SPOT_DELINEATION) { $lest_answer = 1; @@ -438,7 +457,8 @@ if ($modifyAnswers) { } } - $moreAnswers = isset($moreAnswers) ? $moreAnswers : false; + $moreAnswers = isset($_POST['moreAnswers']) ? true : false; + if ($moreAnswers) { if ($nbrAnswers < 12) { $nbrAnswers++; @@ -457,7 +477,9 @@ if ($modifyAnswers) { } } - $moreOARAnswers = isset($moreOARAnswers) ? $moreOARAnswers : false; + + $moreOARAnswers = isset($_POST['moreOARAnswers']) ? true : false; + if ($moreOARAnswers) { if ($nbrAnswers < 12) { // Add a new answer @@ -481,9 +503,24 @@ if ($modifyAnswers) { echo str_repeat(' ', 4) . '$answerType is HOT_SPOT' . "
    \n"; } if ($answerType == HOT_SPOT_DELINEATION) { - $hotspot_colors = array("", "#4271B5", "#FE8E16", "#45C7F0", "#BCD631", "#D63173", "#D7D7D7", "#90AFDD", "#AF8640", "#4F9242", "#F4EB24", "#ED2024", "#3B3B3B"); + $hotspot_colors = array( + "", + "#4271B5", + "#FE8E16", + "#45C7F0", + "#BCD631", + "#D63173", + "#D7D7D7", + "#90AFDD", + "#AF8640", + "#4F9242", + "#F4EB24", + "#ED2024", + "#3B3B3B" + ); } else { - $hotspot_colors = array("", // $i starts from 1 on next loop (ugly fix) + $hotspot_colors = array( + "", // $i starts from 1 on next loop (ugly fix) "#4271B5", "#FE8E16", "#45C7F0", @@ -496,7 +533,8 @@ if ($modifyAnswers) { "#F4EB24", "#ED2024", "#3B3B3B", - "#F7BDE2"); + "#F7BDE2" + ); } Display::tag('h3', get_lang('Question') . ": " . $questionName . ' ' . strip_tags(get_lang('HotspotChoose')) . ''); @@ -504,503 +542,450 @@ if ($modifyAnswers) { Display::display_normal_message($msgErr); //main API } - $hotspot_admin_url = api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidreq() . '&hotspotadmin=' . $modifyAnswers . '&exerciseId=' . $exerciseId; + $hotspot_admin_url = api_get_path(WEB_CODE_PATH) . 'exercice/admin.php?' . api_get_cidreq() . '&hotspotadmin=' . $modifyAnswers . '&exerciseId=' . $exerciseId.'&'.api_get_cidreq(); ?> -
    - - - - - -
    - - - - - - - - - - - - - - - - - - -
    - - - - - - - - ' . get_lang('Thresholds') . ''; ?> + + + + + + + 'TestProposedAnswer' + ); + $form->add_html_editor('comment['.$i.']', null, false, false, $config); + $renderer = $form->defaultRenderer(); + $form_template = '{content}'; + $renderer->setFormTemplate($form_template); + $element_template = ' + {label} + {element} + '; + $renderer->setElementTemplate($element_template); + + $form->setDefaults(array('comment['.$i.']' => $commentValue)); + $return = $form->return_form(); + ?> + + + + + + get_flat_list(); + $select_lp_id = array(); + $option_lp = ''; + $isSelected = false; + foreach ($flat_list as $id => $details) { + $selected = ''; + $select_lp_id[$id] = $details['lp_name']; + if (isset($lp_noerror) && $id == $lp_noerror) { + $selected = 'selected="selected"'; + $isSelected = true; + } + $option_lp.=''; + } + + if ($isSelected) { + $option_lp = '' . $option_lp; + } else { + $option_lp = '' . $option_lp; + } + + // Feedback SELECT + $question_list = $objExercise->selectQuestionList(); + $option_feed = ''; + $option_feed.=''; + $details = isset($details) ? $details : null; + $id = isset($id) ? $id : 0; + $selectQuestionNoError = isset($selectQuestionNoError) ? $selectQuestionNoError : null; + foreach ($question_list as $key => $questionid) { + $selected = ''; + $question = Question::read($questionid); + $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL); + $select_lp_id[$id] = $details['lp_name']; + if ($questionid == $selectQuestionNoError) { + $selected = 'selected="selected"'; + } + $option_feed.=''; + } + if ($selectQuestionNoError == -1) + $option_feed.=''; + else + $option_feed.=''; + + if ($answerType == HOT_SPOT_DELINEATION) { ?> + + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + + + + + + + + + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + + + + + + +
      *
    + + + + + + + + +
    + + + + + + + ' . get_lang('Thresholds') . ''; ?> selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> - - ' . get_lang('Scenario') . ''; ?> + + + ' . get_lang('Scenario') . ''; ?> - + + + + * - - - get_flat_list(); //loading list of LPs - - for ($i = 1; $i <= $nbrAnswers; $i++) { - // is an delineation - if ($answerType == HOT_SPOT_DELINEATION) { + $list = new LearnpathList(api_get_user_id()); + // Loading list of LPs + $flat_list = $list->get_flat_list(); - $select_lp_id = array(); - $option_lp = ''; - - // setting the LP - $isSelected = false; - foreach ($flat_list as $id => $details) { - $select_lp_id[$id] = $details['lp_name']; - $selected = ''; - if ($id == $lp[$i]) { - $isSelected = true; - $selected = 'selected="selected"'; - } - $option_lp.=''; - } - if ($isSelected) { - $option_lp = '' . $option_lp; - } else { - $option_lp = '' . $option_lp; + for ($i = 1; $i <= $nbrAnswers; $i++) { + // is an delineation + if ($answerType == HOT_SPOT_DELINEATION) { + $select_lp_id = array(); + $option_lp = ''; + + // setting the LP + $isSelected = false; + foreach ($flat_list as $id => $details) { + $select_lp_id[$id] = $details['lp_name']; + $selected = ''; + if ($id == $lp[$i]) { + $isSelected = true; + $selected = 'selected="selected"'; } + $option_lp.=''; + } + if ($isSelected) { + $option_lp = '' . $option_lp; + } else { + $option_lp = '' . $option_lp; + } - //Feedback SELECT - $question_list = $objExercise->selectQuestionList(); - $option_feed = ''; - $option_feed.=''; - - foreach ($question_list as $key => $questionid) { - $selected = ''; - $question = Question::read($questionid); - $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL); - $select_lp_id[$id] = $details['lp_name']; - if ($questionid == $select_question[$i]) { - $selected = 'selected="selected"'; - } - $option_feed.=''; + // Feedback SELECT + $question_list = $objExercise->selectQuestionList(); + $option_feed = ''; + $option_feed.=''; + + foreach ($question_list as $key => $questionid) { + $selected = ''; + $question = Question::read($questionid); + $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL); + $select_lp_id[$id] = $details['lp_name']; + if ($questionid == $select_question[$i]) { + $selected = 'selected="selected"'; } - if ($select_question[$i] == -1) - $option_feed.=''; - else - $option_feed.=''; - - //-------- IF it is a delineation - - if ($_SESSION['tmp_answers']['hotspot_type'][$i] == 'delineation') { - for ($k = 1; $k <= 100; $k++) { - $selected1 = $selected2 = $selected3 = ''; - if ($k == $threadhold1[$i]) - $selected1 = 'selected="selected"'; - if ($k == $threadhold2[$i]) - $selected2 = 'selected="selected"'; - if ($k == $threadhold3[$i]) - $selected3 = 'selected="selected"'; - $option1.=''; - $option2.=''; - $option3.=''; - } - ?> - - - - - - - - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> - - - - - - - - - - - - - + $option_feed.=''; + } + if ($select_question[$i] == -1) { + $option_feed .= ''; + } else { + $option_feed .= ''; + } - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + //-------- IF it is a delineation + + if ($_SESSION['tmp_answers']['hotspot_type'][$i] == 'delineation') { + for ($k = 1; $k <= 100; $k++) { + $selected1 = $selected2 = $selected3 = ''; + if ($k == $threadhold1[$i]) + $selected1 = 'selected="selected"'; + if ($k == $threadhold2[$i]) + $selected2 = 'selected="selected"'; + if ($k == $threadhold3[$i]) + $selected3 = 'selected="selected"'; + $option1.=''; + $option2.=''; + $option3.=''; + } + ?> + + + + + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + + + + } elseif (false) { + ?> + + + + + + + + + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + + + + + + + + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + + + + + + + + - ToolbarSet = 'TestProposedAnswer'; - $oFCKeditor->Config['ToolbarStartExpanded'] = 'false'; - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '100'; - $oFCKeditor->Value = $content; - //$return = $oFCKeditor->CreateHtml(); - $return = $oFCKeditor->editor("comment[$i]", $oFCKeditor->Value);*/ - /* */ - ?> - - - - - - get_flat_list(); - $select_lp_id = array(); - $option_lp = ''; - $isSelected = false; - foreach ($flat_list as $id => $details) { - $selected = ''; - $select_lp_id[$id] = $details['lp_name']; - if ($id == $lp_noerror) { - $selected = 'selected="selected"'; - $isSelected = true; - } - $option_lp.=''; - } - - if ($isSelected) { - $option_lp = '' . $option_lp; - } else { - $option_lp = '' . $option_lp; - } - - //Feedback SELECT - - $question_list = $objExercise->selectQuestionList(); - $option_feed = ''; - $option_feed.=''; - $details = isset($details) ? $details : null; - $id = isset($id) ? $id : 0; - $selectQuestionNoError = isset($selectQuestionNoError) ? $selectQuestionNoError : null; - foreach ($question_list as $key => $questionid) { - $selected = ''; - $question = Question::read($questionid); - $val = 'Q' . $key . ' :' . substrwords($question->selectTitle(), ICON_SIZE_SMALL); - $select_lp_id[$id] = $details['lp_name']; - if ($questionid == $selectQuestionNoError) { - $selected = 'selected="selected"'; - } - $option_feed.=''; - } - if ($selectQuestionNoError == -1) - $option_feed.=''; - else - $option_feed.=''; - - if ($answerType == HOT_SPOT_DELINEATION) { - ?> - - - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> - - - - - - - - - - - - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + + selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> + - - - - - -
      * *
    -
    - -
    -

    -

    -

    -

    -
    -

    - % -

    - % -

    - % -
    -
    -
    - - - -
    - -
    - - - - - -
    - /> - -

    - -
    - - - -

    -
    - -

    -
    - - - -
    -
     
    - - - - - - - -
    +
    + +
    +

    +

    +

    +

    +
    +

    + % +

    + % +

    + % +
    +
    +
    + + + +
    + +
    + + - - - - - - +
    - - - - -
    - /> - -

    - -
    - -

    - -
    - -

    -
    - -
    + /> + +

    +
    + +

    +
    + +

    +
    +
     
    +
     
    + + + + + + + + + - - - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> - - - - - - - - - - - - - - - - - selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) { ?> - - - - - +
     * 
    -
    -
    - - - - - - - - - - -
    - /> - -

    - -
    - -

    -
    - -

    -
    - - -
    + /> + +

    + +
    + +

    +
    + +

    +
    +
     
    +
     
     * 
    - +   - - - - - - + + + - - -
     
    - - - -
    - /> - + /> +

    -
    - +

    - -
    - +
    +

    -
    - +
      
    + +
    +
    +
    + +   + + + + + + + + + +
     
    + + + + + + + + +
    + /> + +

    +
    + +

    +
    + +

    +
    + +
    +
      
    - +
    diff --git a/main/exercice/hotspot_save.inc.php b/main/exercice/hotspot_save.inc.php index 44f9decbcf..5bd499c353 100755 --- a/main/exercice/hotspot_save.inc.php +++ b/main/exercice/hotspot_save.inc.php @@ -8,7 +8,7 @@ * @version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $ */ -include('../inc/global.inc.php'); +require_once '../inc/global.inc.php'; $TBL_ANSWER = Database::get_course_table(TABLE_QUIZ_ANSWER); $questionId = intval($_GET['questionId']); diff --git a/main/exercice/hotspot_savescore.inc.php b/main/exercice/hotspot_savescore.inc.php index 79d4cd1ca8..9e58f151d1 100755 --- a/main/exercice/hotspot_savescore.inc.php +++ b/main/exercice/hotspot_savescore.inc.php @@ -7,7 +7,7 @@ * @author Toon Keppens * @version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $ */ -include('../inc/global.inc.php'); +require_once '../inc/global.inc.php'; $courseCode = $_GET['coursecode']; $questionId = $_GET['questionId']; $coordinates = $_GET['coord']; @@ -36,7 +36,7 @@ foreach ($coords as $coord) { } $coordinates = substr($coordinates,0,-1); -$TBL_TRACK_E_HOTSPOT = Database::get_statistic_table(STATISTIC_TRACK_E_HOTSPOTS); +$TBL_TRACK_E_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); // Save into db $sql = "INSERT INTO $TBL_TRACK_E_HOTSPOT (user_id , course_id , quiz_id , question_id , answer_id , correct , coordinate ) VALUES ( ".intval($_user['user_id']).", diff --git a/main/exercice/hotspot_updatescore.inc.php b/main/exercice/hotspot_updatescore.inc.php index 94d6c2a72a..a4dab2e46d 100755 --- a/main/exercice/hotspot_updatescore.inc.php +++ b/main/exercice/hotspot_updatescore.inc.php @@ -8,7 +8,7 @@ * @version $Id: admin.php 10680 2007-01-11 21:26:23Z pcool $ */ -include '../inc/global.inc.php'; +require_once '../inc/global.inc.php'; $courseCode = $_GET['coursecode']; $questionId = $_GET['questionId']; @@ -47,7 +47,7 @@ foreach ($coords as $coord) { } $coordinates = substr($coordinates,0,-1); -$TBL_TRACK_E_HOTSPOT = Database::get_statistic_table(STATISTIC_TRACK_E_HOTSPOTS); +$TBL_TRACK_E_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT); // update db $update_id = $_SESSION['exerciseResult'][$questionId]['ids'][$answerId]; diff --git a/main/exercice/overview.php b/main/exercice/overview.php index ea88b17880..648f2a7e25 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(), @@ -146,7 +146,7 @@ $table_content = ''; /* Make a special case for IE, which doesn't seem to be able to handle the * results popup -> send it to the full results page */ -require_once api_get_path(LIBRARY_PATH).'browser/Browser.php'; + $browser = new Browser(); $current_browser = $browser->getBrowser(); $url_suffix = ''; @@ -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.class.php b/main/exercice/question.class.php index 39d4590eb5..5958c40a9b 100755 --- a/main/exercice/question.class.php +++ b/main/exercice/question.class.php @@ -683,22 +683,22 @@ abstract class Question * @author Olivier Brouckaert * @param integer $exerciseId - exercise ID if saving in an exercise */ - function save($exerciseId=0) { + public function save($exerciseId=0) + { $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION); $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION); - $id = $this->id; - $question = $this->question; - $description = $this->description; - $weighting = $this->weighting; - $position = $this->position; - $type = $this->type; - $picture = $this->picture; - $level = $this->level; - $extra = $this->extra; - $c_id = $this->course['real_id']; - $category = $this->category; - + $id = $this->id; + $question = $this->question; + $description = $this->description; + $weighting = $this->weighting; + $position = $this->position; + $type = $this->type; + $picture = $this->picture; + $level = $this->level; + $extra = $this->extra; + $c_id = $this->course['real_id']; + $category = $this->category; // question already exists if(!empty($id)) { @@ -1143,28 +1143,17 @@ abstract class Question * A subclass can redifine this function to add fields... * @param FormValidator $form the formvalidator instance (by reference) */ - function createForm (&$form, $fck_config=0) { + function createForm (&$form, $fck_config=0) + { echo ''; - echo ''; + echo ''; } else { //New question - echo ''; + echo ''; } } else { - echo ''; + echo ''; } } else { if (isset($questionName)) { 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..1a7829ff5c 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)) { @@ -65,7 +65,7 @@ if ($show_headers) { Display::display_reduced_header(); } -display_question_list_by_attempt($objExercise, $id, false); +ExerciseLib::display_question_list_by_attempt($objExercise, $id, false); if ($show_headers) { Display::display_footer(); diff --git a/main/exercice/stats.php b/main/exercice/stats.php index 86ff374084..883a823b0e 100755 --- a/main/exercice/stats.php +++ b/main/exercice/stats.php @@ -5,7 +5,7 @@ $language_file = array('exercice', 'tracking'); require_once '../inc/global.inc.php'; $this_section = SECTION_COURSES; -$exercise_id = (isset($_GET['exerciseId']) && !empty($_GET['exerciseId'])) ? intval($_GET['exerciseId']) : 0; +$exercise_id = isset($_GET['exerciseId']) && !empty($_GET['exerciseId']) ? intval($_GET['exerciseId']) : 0; $gradebook = isset($gradebook) ? $gradebook : null; $objExercise = new Exercise(); @@ -15,23 +15,22 @@ if (!$result) { api_not_allowed(true); } -$session_id = api_get_session_id(); +$sessionId = api_get_session_id(); +$courseCode = api_get_course_id(); -if (empty($session_id)) { - $students = CourseManager :: get_student_list_from_course_code(api_get_course_id(), false); +if (empty($sessionId)) { + $students = CourseManager :: get_student_list_from_course_code($courseCode, false); } else { - $students = CourseManager :: get_student_list_from_course_code(api_get_course_id(), true, $session_id); + $students = CourseManager :: get_student_list_from_course_code($courseCode, true, $sessionId); } $count_students = count($students); - $question_list = $objExercise->get_validated_question_list(); $data = array(); -//Question title # of students who tool it Lowest score Average Highest score Maximum score +// Question title # of students who tool it Lowest score Average Highest score Maximum score $headers = array( get_lang('Question'), get_lang('QuestionType'), - //get_lang('NumberOfStudentsWhoTryTheExercise'), get_lang('NumberStudentWhoSelectedIt'), get_lang('LowestScore'), get_lang('AverageScore'), @@ -41,28 +40,42 @@ $headers = array( if (!empty($question_list)) { foreach ($question_list as $question_id) { - $question_obj = Question::read($question_id); - $exercise_stats = get_student_stats_by_question($question_id, $exercise_id, api_get_course_id(), api_get_session_id()); - $count_users = get_number_students_question_with_answer_count($question_id, $exercise_id, api_get_course_id(), api_get_session_id()); - - $data[$question_id]['name'] = cut($question_obj->question, 100); - $data[$question_id]['type'] = $question_obj->get_question_type_name(); - //$data[$question_id]['students_who_try_exercise'] = $exercise_stats['users']; + $question_obj = Question::read($question_id); + + $exercise_stats = ExerciseLib::get_student_stats_by_question( + $question_id, + $exercise_id, + $courseCode, + $sessionId + ); + + $count_users = ExerciseLib::get_number_students_question_with_answer_count( + $question_id, + $exercise_id, + $courseCode, + $sessionId + ); + + $data[$question_id]['name'] = cut($question_obj->question, 100); + $data[$question_id]['type'] = $question_obj->get_question_type_name(); $percentange = 0; if ($count_students) { - $percentange = $count_users/$count_students*100; + $percentange = $count_users / $count_students*100; } - $data[$question_id]['students_who_try_exercise'] = Display::bar_progress($percentange, false, $count_users .' / '.$count_students); - - $data[$question_id]['lowest_score'] = round($exercise_stats['min'], 2); - $data[$question_id]['average_score'] = round($exercise_stats['average'], 2); - $data[$question_id]['highest_score'] = round($exercise_stats['max'], 2); - $data[$question_id]['max_score'] = round($question_obj->weighting, 2); + $data[$question_id]['students_who_try_exercise'] = Display::bar_progress( + $percentange, + false, + $count_users .' / '.$count_students + ); + $data[$question_id]['lowest_score'] = round($exercise_stats['min'], 2); + $data[$question_id]['average_score'] = round($exercise_stats['average'], 2); + $data[$question_id]['highest_score'] = round($exercise_stats['max'], 2); + $data[$question_id]['max_score'] = round($question_obj->weighting, 2); } } -//Format A table +// Format A table $table = new HTML_Table(array('class' => 'data_table')); $row = 0; $column = 0; @@ -83,7 +96,7 @@ foreach ($data as $row_table) { } $content = $table->toHtml(); -//Format B +// Format B $headers = array( get_lang('Question'), @@ -98,19 +111,23 @@ 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($question_id, $exercise_id, api_get_course_id(), api_get_session_id()); + $exercise_stats = ExerciseLib::get_student_stats_by_question( + $question_id, + $exercise_id, + $courseCode, + $sessionId + ); $answer = new Answer($question_id); $answer_count = $answer->selectNbrAnswers(); for ($answer_id = 1; $answer_id <= $answer_count; $answer_id++) { - $answer_info = $answer->selectAnswer($answer_id); - $is_correct = $answer->isCorrect($answer_id); + $answer_info = $answer->selectAnswer($answer_id); + $is_correct = $answer->isCorrect($answer_id); $correct_answer = $is_correct == 1 ? get_lang('Yes') : get_lang('No'); $real_answer_id = $answer->selectAutoId($answer_id); - //$data[$id]['name'] .=$answer_count; - //Overwriting values depending of the question + // Overwriting values depending of the question switch ($question_obj->type) { case FILL_IN_BLANKS : $answer_info_db = $answer_info; @@ -120,9 +137,9 @@ if (!empty($question_list)) { $counter = 0; foreach ($answers as $answer_item) { if ($counter == 0) { - $data[$id]['name'] = cut($question_obj->question, 100); + $data[$id]['name'] = cut($question_obj->question, 100); } else { - $data[$id]['name'] = '-'; + $data[$id]['name'] = '-'; } $data[$id]['answer'] = $answer_item; @@ -131,13 +148,22 @@ if (!empty($question_list)) { $data[$id]['correct'] = '-'; - $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), FILL_IN_BLANKS, $answer_info_db, $answer_item); + $count = ExerciseLib::get_number_students_answer_count( + $real_answer_id, + $question_id, + $exercise_id, + $courseCode, + $sessionId, + FILL_IN_BLANKS, + $answer_info_db, + $answer_item + ); $percentange = 0; if (!empty($count_students)) { $percentange = $count/$count_students*100; } - $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); + $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); $id++; $counter++; @@ -146,9 +172,9 @@ if (!empty($question_list)) { case MATCHING: if ($is_correct == 0) { if ($answer_id == 1) { - $data[$id]['name'] = cut($question_obj->question, 100); + $data[$id]['name'] = cut($question_obj->question, 100); } else { - $data[$id]['name'] = '-'; + $data[$id]['name'] = '-'; } $correct = ''; @@ -159,48 +185,67 @@ if (!empty($question_list)) { break; } } - $data[$id]['answer'] = $correct; - $data[$id]['correct'] = $answer_info; - - $count = get_number_students_answer_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id(), MATCHING); + $data[$id]['answer'] = $correct; + $data[$id]['correct'] = $answer_info; + + $count = ExerciseLib::get_number_students_answer_count( + $answer_id, + $question_id, + $exercise_id, + $courseCode, + $sessionId, + MATCHING + ); $percentange = 0; if (!empty($count_students)) { $percentange = $count/$count_students*100; } - $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); + $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); } break; case HOT_SPOT: if ($answer_id == 1) { - $data[$id]['name'] = cut($question_obj->question, 100); + $data[$id]['name'] = cut($question_obj->question, 100); } else { - $data[$id]['name'] = '-'; + $data[$id]['name'] = '-'; } - $data[$id]['answer'] = $answer_info; - $data[$id]['correct'] = '-'; - - $count = get_number_students_answer_hotspot_count($answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id()); + $data[$id]['answer'] = $answer_info; + $data[$id]['correct'] = '-'; + + $count = ExerciseLib::get_number_students_answer_hotspot_count( + $answer_id, + $question_id, + $exercise_id, + $courseCode, + $sessionId + ); $percentange = 0; if (!empty($count_students)) { $percentange = $count/$count_students*100; } - $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); + $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); break; default: if ($answer_id == 1) { - $data[$id]['name'] = cut($question_obj->question, 100); + $data[$id]['name'] = cut($question_obj->question, 100); } else { - $data[$id]['name'] = '-'; + $data[$id]['name'] = '-'; } - $data[$id]['answer'] = $answer_info; - $data[$id]['correct'] = $correct_answer; - - $count = get_number_students_answer_count($real_answer_id, $question_id, $exercise_id, api_get_course_id(), api_get_session_id()); + $data[$id]['answer'] = $answer_info; + $data[$id]['correct'] = $correct_answer; + + $count = ExerciseLib::get_number_students_answer_count( + $real_answer_id, + $question_id, + $exercise_id, + $courseCode, + $sessionId + ); $percentange = 0; if (!empty($count_students)) { $percentange = $count/$count_students*100; } - $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); + $data[$id]['attempts'] = Display::bar_progress($percentange, false, $count .' / '.$count_students); } $id++; } @@ -208,7 +253,7 @@ if (!empty($question_list)) { } } -//Format A table +// Format A table $table = new HTML_Table(array('class' => 'data_table')); $row = 0; $column = 0; @@ -239,7 +284,8 @@ $tpl = new Template(get_lang('ReportByQuestion')); //$actions[]= array(get_lang('Back'), Display::return_icon('back.png', get_lang('Back'), 'exercise_report.php?'.$exercise_id)); //$tpl->set_actions($actions); -$actions = '' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).''; +$actions = '' . + Display :: return_icon('back.png', get_lang('GoBackToQuestionList'),'',ICON_SIZE_MEDIUM).''; $actions = Display::div($actions, array('class'=> 'actions')); $content = $actions.$content; $tpl->assign('content', $content); 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/forumfunction.inc.php b/main/forum/forumfunction.inc.php index 05590b70d8..42ef77dcec 100755 --- a/main/forum/forumfunction.inc.php +++ b/main/forum/forumfunction.inc.php @@ -3154,7 +3154,7 @@ function get_whats_new() $sql = "SELECT * FROM ".$tracking_last_tool_access." WHERE access_user_id='".Database::escape_string($_user['user_id'])."' AND - access_cours_code='".Database::escape_string($_course['sysCode'])."' AND + c_id ='".$course_id."' AND access_tool='".Database::escape_string($tool)."'"; $result = Database::query($sql); $row = Database::fetch_array($result); @@ -3936,7 +3936,6 @@ function search_link() */ function add_forum_attachment_file($file_comment, $last_id) { - require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'; $_course = api_get_course_info(); $agenda_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT); 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/glossary_ajax_request.php b/main/glossary/glossary_ajax_request.php index 35459eea2d..f47e722a2a 100755 --- a/main/glossary/glossary_ajax_request.php +++ b/main/glossary/glossary_ajax_request.php @@ -11,9 +11,6 @@ // Including the global initialization file. require_once '../inc/global.inc.php'; -// Including additional libraries. -require_once api_get_path(LIBRARY_PATH).'glossary.lib.php'; - /** * Search a term and return description from a glossary. */ diff --git a/main/glossary/glossary_form.class.php b/main/glossary/glossary_form.class.php index b3fbc4b1e2..ed7973b0c2 100755 --- a/main/glossary/glossary_form.class.php +++ b/main/glossary/glossary_form.class.php @@ -13,7 +13,7 @@ use Chamilo; /** * Form to edit/Create glossary entries. - * + * * @license /licence.txt * @author Laurent Opprecht */ @@ -24,7 +24,7 @@ class GlossaryForm extends \FormValidator * * @param string $action * @param \Glossary\Glossary $item - * @return \Glossary\GlossaryForm + * @return \Glossary\GlossaryForm */ static function create($action, $item = null) { @@ -34,7 +34,7 @@ class GlossaryForm extends \FormValidator } return $result; } - + protected $glossary; function __construct($form_name = 'glossary', $method = 'post', $action = '', $target = '', $attributes = null, $track_submit = true) @@ -68,17 +68,17 @@ class GlossaryForm extends \FormValidator $defaults['name'] = $glossary->name; $defaults['description'] = $glossary->description; - $this->add_hidden('c_id', $glossary->c_id); - $this->add_hidden('id', $glossary->id); - $this->add_hidden('session_id', $glossary->session_id); - $this->add_hidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token()); + $this->addHidden('c_id', $glossary->c_id); + $this->addHidden('id', $glossary->id); + $this->addHidden('session_id', $glossary->session_id); + $this->addHidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token()); $form_name = $glossary->id ? get_lang('TermEdit') : get_lang('TermAddNew'); - $this->add_header($form_name); + $this->addHeader($form_name); $this->add_textfield('name', get_lang('TermName'), $required = true, array('class' => 'span3')); $this->add_html_editor('description', get_lang('TermDefinition'), true, array('ToolbarSet' => 'Glossary', 'Width' => '90%', 'Height' => '300')); - $this->add_button('save', get_lang('Save'), array('class' => 'btn save')); + $this->addButton('save', get_lang('Save'), array('class' => 'btn save')); $this->setDefaults($defaults); } diff --git a/main/glossary/index.php b/main/glossary/index.php index e61ca3c9b7..07ef37ab15 100755 --- a/main/glossary/index.php +++ b/main/glossary/index.php @@ -11,9 +11,6 @@ $language_file = array('glossary', 'admin'); // Including the global initialization file. require_once '../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'glossary.lib.php'; -require_once api_get_path(LIBRARY_PATH).'export.lib.inc.php'; -require_once api_get_path(LIBRARY_PATH).'import.lib.php'; $current_course_tool = TOOL_GLOSSARY; @@ -37,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/glossary/upload_file_form.class.php b/main/glossary/upload_file_form.class.php index d787c2016d..fe9c7f3fd1 100755 --- a/main/glossary/upload_file_form.class.php +++ b/main/glossary/upload_file_form.class.php @@ -13,7 +13,7 @@ use Chamilo; /** * Form to upload a CSV file. - * + * * @license /licence.txt * @author Laurent Opprecht */ @@ -23,7 +23,7 @@ class UploadFileForm extends \FormValidator /** * * @param string $action - * @return \Glossary\UploadFileForm + * @return \Glossary\UploadFileForm */ public static function create($action) { @@ -37,20 +37,19 @@ class UploadFileForm extends \FormValidator /** * - * + * */ function init() { $form_name = get_lang('ImportGlossary'); - $this->add_header($form_name); + $this->addHeader($form_name); - $this->add_hidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token()); + $this->addHidden(Request::PARAM_SEC_TOKEN, Access::instance()->get_token()); $label = get_lang('ImportCSVFileLocation'); $this->add_file('file', $label); $this->addRule('file', get_lang('ThisFieldIsRequired'), 'required'); - $this->add_checkbox('deleteall', '', get_lang('DeleteAllGlossaryTerms')); - - $this->add_button('save', get_lang('Save'), array('class' => 'btn save')); + $this->addCheckBox('deleteall', '', get_lang('DeleteAllGlossaryTerms')); + $this->addButton('save', get_lang('Save'), array('class' => 'btn save')); $label = get_lang('CSVMustLookLike'); $label = "$label"; diff --git a/main/gradebook/gradebook_display_certificate.php b/main/gradebook/gradebook_display_certificate.php index a3ed929052..b8fd694cf4 100755 --- a/main/gradebook/gradebook_display_certificate.php +++ b/main/gradebook/gradebook_display_certificate.php @@ -111,7 +111,12 @@ if (!empty($cats)) { $total_resource_weight = 0; if (!empty($datagen)) { - $data_array = $datagen->get_data(GradebookDataGenerator :: GDG_SORT_NAME,0,null,true); + $data_array = $datagen->get_data( + GradebookDataGenerator :: GDG_SORT_NAME, + 0, + null, + true + ); if (!empty($data_array)) { $newarray = array(); @@ -144,7 +149,7 @@ if ($filter) { api_get_self().'?'.api_get_cidreq().'&cat_id='.$cat_id ); $form->addElement('select', 'filter', get_lang('OfficialCode'), $options); - $form->add_button('submit', get_lang('Submit')); + $form->addButton('submit', get_lang('Submit')); $filterForm = '
    '.$form->return_form(); if ($form->validate()) { diff --git a/main/gradebook/gradebook_result.class.php b/main/gradebook/gradebook_result.class.php index 29a4baba40..c9b5d7bd91 100755 --- a/main/gradebook/gradebook_result.class.php +++ b/main/gradebook/gradebook_result.class.php @@ -125,8 +125,8 @@ class GradeBookResult ORDER BY exe_cours_id ASC, exe_date ASC"; } - $results=getManyResultsXCol($sql,8); - $hpresults=getManyResultsXCol($hpsql,7); + $results=StatsUtils::getManyResultsXCol($sql,8); + $hpresults=StatsUtils::getManyResultsXCol($hpsql,7); $NoTestRes = 0; $NoHPTestRes = 0; diff --git a/main/gradebook/lib/be/category.class.php b/main/gradebook/lib/be/category.class.php index 030e68b96d..26a6bfc0d9 100755 --- a/main/gradebook/lib/be/category.class.php +++ b/main/gradebook/lib/be/category.class.php @@ -365,7 +365,7 @@ class Category implements GradebookItem $cat->set_parent_id(null); $cat->set_weight(0); $cat->set_visible(1); - $cat->setGenerateCertificates(false); + $cat->setGenerateCertificates(0); return $cat; } @@ -376,7 +376,7 @@ class Category implements GradebookItem */ private static function create_category_objects_from_sql_result($result) { - $allcat = array(); + $categories = array(); while ($data = Database::fetch_array($result)) { $cat = new Category(); $cat->set_id($data['id']); @@ -392,10 +392,10 @@ class Category implements GradebookItem $cat->set_grade_model_id($data['grade_model_id']); $cat->set_locked($data['locked']); $cat->setGenerateCertificates($data['generate_certificates']); - $allcat[] = $cat; + $categories[] = $cat; } - return $allcat; + return $categories; } /** @@ -722,14 +722,20 @@ class Category implements GradebookItem /** * Checks if the certificate is available for the given user in this category - * @param integer User ID - * @return boolean True if conditions match, false if fails + * @param integer $user_id User ID + * @return boolean True if conditions match, false if fails */ public function is_certificate_available($user_id) { $score = $this->calc_score($user_id, $this->course_code); - if (isset($score)) { - $certification_score = ($score[0]/$score[1])*100; //get a percentage score to compare to minimum certificate score + + if (isset($score) && isset($score[0])) { + // Get a percentage score to compare to minimum certificate score + //$certification_score = $score[0] / $score[1] * 100; + + // Get real score not a percentage. + $certification_score = $score[0]; + if ($certification_score >= $this->certificate_min_score) { return true; } @@ -1594,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); } } @@ -1619,11 +1625,19 @@ class Category implements GradebookItem $category = $cats_course[0]; if (!$category->getGenerateCetificates()) { + $skill = new Skill(); + $skill->add_skill_to_user( + $user_id, + $category_id, + api_get_course_int_id(), + api_get_session_id() + ); + return false; } - $alleval_course = $category->get_evaluations($user_id, true); - $alllink_course = $category->get_links($user_id, true); + $alleval_course = $category->get_evaluations($user_id, true); + $alllink_course = $category->get_links($user_id, true); $evals_links = array_merge($alleval_course, $alllink_course); //@todo move these in a function @@ -1686,6 +1700,7 @@ class Category implements GradebookItem if (!empty($my_certificate)) { $certificate_obj = new Certificate($my_certificate['id']); $fileWasGenerated = $certificate_obj->html_file_is_generated(); + if (!empty($fileWasGenerated)) { $url = api_get_path(WEB_PATH) . 'certificates/index.php?id=' . $my_certificate['id']; $certificates = Display::url( diff --git a/main/gradebook/lib/fe/evalform.class.php b/main/gradebook/lib/fe/evalform.class.php index d071c9f099..3c3f2dc384 100755 --- a/main/gradebook/lib/fe/evalform.class.php +++ b/main/gradebook/lib/fe/evalform.class.php @@ -271,12 +271,18 @@ class EvalForm extends FormValidator ); } + $firstUser = true; foreach ($tblusers as $user) { $element_name = 'score[' . $user[0] . ']'; - + + $scoreColumnProperties = array('class' => 'span1', 'maxlength' => 5); + if ($firstUser) { + $scoreColumnProperties['autofocus'] = ''; + $firstUser = false; + } //user_id, user.username, lastname, firstname - $this->add_textfield($element_name, $this->build_stud_label($user[0], $user[1], $user[2], $user[3]), false, array('class' => 'span1', 'maxlength' => 5)); + $this->add_textfield($element_name, $this->build_stud_label($user[0], $user[1], $user[2], $user[3]), false, $scoreColumnProperties); $this->addRule($element_name, get_lang('OnlyNumbers'), 'numeric'); $this->addRule(array($element_name, 'maxvalue'), get_lang('OverMax'), 'compare', '<='); diff --git a/main/gradebook/lib/fe/flatviewtable.class.php b/main/gradebook/lib/fe/flatviewtable.class.php index d7476c127a..70120fd8d7 100755 --- a/main/gradebook/lib/fe/flatviewtable.class.php +++ b/main/gradebook/lib/fe/flatviewtable.class.php @@ -369,12 +369,9 @@ class FlatViewTable extends SortableTable // retrieve sorting type if ($is_western_name_order) { - //$users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME : FlatViewDataGenerator :: FVDG_SORT_LASTNAME); - $users_sorting = FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME; - + $users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME : FlatViewDataGenerator :: FVDG_SORT_LASTNAME); } else { - //$users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_LASTNAME : FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME); - $users_sorting = FlatViewDataGenerator :: FVDG_SORT_LASTNAME; + $users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_LASTNAME : FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME); } if ($this->direction == 'DESC') { @@ -382,17 +379,12 @@ class FlatViewTable extends SortableTable } else { $users_sorting |= FlatViewDataGenerator :: FVDG_SORT_ASC; } - // step 1: generate columns: evaluations and links + // step 1: generate columns: evaluations and links $header_names = $this->datagen->get_header_names($this->offset, $selectlimit); - if ($is_western_name_order) { - $this->set_header(0, $header_names[1]); - $this->set_header(1, $header_names[0]); - } else { - $this->set_header(0, $header_names[0]); - $this->set_header(1, $header_names[1]); - } + $this->set_header(0, $header_names[0]); + $this->set_header(1, $header_names[1]); $column = 2; while ($column < count($header_names)) { @@ -410,22 +402,19 @@ class FlatViewTable extends SortableTable $table_data = array(); foreach ($data_array as $user_row) { - $table_row = array(); - $count = 0; - $user_id = $user_row[$count++]; - $lastname = $user_row[$count++]; - $firstname = $user_row[$count++]; + $user_id = $user_row[0]; + unset($user_row[0]); + $userInfo = api_get_user_info($user_id); if ($is_western_name_order) { - $table_row[] = $this->build_name_link($user_id, $firstname); - $table_row[] = $this->build_name_link($user_id, $lastname); + $user_row[1] = $this->build_name_link($user_id, $userInfo['firstname']); + $user_row[2] = $this->build_name_link($user_id, $userInfo['lastname']); } else { - $table_row[] = $this->build_name_link($user_id, $lastname); - $table_row[] = $this->build_name_link($user_id, $firstname); + $user_row[1] = $this->build_name_link($user_id, $userInfo['lastname']); + $user_row[2] = $this->build_name_link($user_id, $userInfo['firstname']); } - while ($count < count($user_row)) { - $table_row[] = $user_row[$count++]; - } - $table_data[] = $table_row; + $user_row = array_values($user_row); + + $table_data[] = $user_row; } return $table_data; } diff --git a/main/gradebook/lib/flatview_data_generator.class.php b/main/gradebook/lib/flatview_data_generator.class.php index 405d518b65..710cc6c3b2 100755 --- a/main/gradebook/lib/flatview_data_generator.class.php +++ b/main/gradebook/lib/flatview_data_generator.class.php @@ -87,6 +87,7 @@ class FlatViewDataGenerator if (isset($this->params['show_official_code']) && $this->params['show_official_code']) { $headers[] = get_lang('OfficialCode'); } + if (isset($this->params['join_firstname_lastname']) && $this->params['join_firstname_lastname']) { if (api_is_western_name_order()) { $headers[] = get_lang('FirstnameAndLastname'); @@ -167,7 +168,7 @@ class FlatViewDataGenerator $add_weight = " $sub_cat_weight %"; $headers[] = Display::url( $sub_cat->get_name(), - api_get_self().'?selectcat='.$sub_cat->get_id() + api_get_self().'?selectcat='.$sub_cat->get_id().'&'.api_get_cidreq() ).$add_weight; } } else { @@ -358,7 +359,9 @@ class FlatViewDataGenerator } // Last name - if (isset($this->params['join_firstname_lastname']) && $this->params['join_firstname_lastname']) { + if (isset($this->params['join_firstname_lastname']) && + $this->params['join_firstname_lastname'] + ) { if ($export_to_pdf) { $row['name'] = api_get_person_name($user[3], $user[2]); } else { diff --git a/main/help/allowed_html_tags.php b/main/help/allowed_html_tags.php index 4cd419448d..b77051ecfb 100755 --- a/main/help/allowed_html_tags.php +++ b/main/help/allowed_html_tags.php @@ -15,8 +15,6 @@ $language_file = 'help'; require '../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php'; -require_once api_get_path(LIBRARY_PATH).'formvalidator/Rule/HTML.php'; header('Content-Type: text/html; charset='.api_get_system_encoding()); ?> diff --git a/main/img/icons/22/award_red.png b/main/img/icons/22/award_red.png index 478b69129b..2930e8a820 100644 Binary files a/main/img/icons/22/award_red.png and b/main/img/icons/22/award_red.png differ 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/course_home.ajax.php b/main/inc/ajax/course_home.ajax.php index c92535f1ac..f43be6637c 100755 --- a/main/inc/ajax/course_home.ajax.php +++ b/main/inc/ajax/course_home.ajax.php @@ -66,7 +66,6 @@ switch ($action) { } break; case 'show_course_information' : - $language_file = array('course_description'); require_once '../global.inc.php'; // Get the name of the database course. @@ -149,7 +148,7 @@ switch ($action) { $last_date = Tracking::get_last_connection_date_on_the_course( api_get_user_id(), - $item['code'], + $item['id'], $session_id, false ); @@ -279,7 +278,12 @@ switch ($action) { $temp[$count]['id']= $lp_id; $lp_url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?cidReq='.$item['code'].'&id_session='.$session_id.'&lp_id='.$lp_id.'&action=view'; - $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(),$item['code'], $session_id, false); + $last_date = Tracking::get_last_connection_date_on_the_course( + api_get_user_id(), + $item['id'], + $session_id, + false + ); if ($lp_item['modified_on'] == '0000-00-00 00:00:00' || empty($lp_item['modified_on'])) { $lp_date = api_get_local_time($lp_item['created_on']); $image = 'new.gif'; @@ -402,7 +406,12 @@ switch ($action) { foreach($flat_list as $lp_id => $lp_item) { $temp[$count]['id']= $lp_id; $lp_url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?cidReq='.$item['code'].'&id_session='.$session_id.'&lp_id='.$lp_id.'&action=view'; - $last_date = Tracking::get_last_connection_date_on_the_course(api_get_user_id(),$item['code'], $session_id, false); + $last_date = Tracking::get_last_connection_date_on_the_course( + api_get_user_id(), + $item['id'], + $session_id, + false + ); if ($lp_item['modified_on'] == '0000-00-00 00:00:00' || empty($lp_item['modified_on'])) { $lp_date = api_get_local_time($lp_item['created_on']); $image = 'new.gif'; 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..81abfcac45 100755 --- a/main/inc/ajax/exercise.ajax.php +++ b/main/inc/ajax/exercise.ajax.php @@ -6,7 +6,7 @@ */ require_once '../global.inc.php'; - +$debug = false; api_protect_course_script(true); $action = $_REQUEST['a']; @@ -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,12 +399,26 @@ 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_id, + $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_id, + $session_id, + $my_question_id + ); } - if (isset($attempt_list[$my_question_id]) && isset($attempt_list[$my_question_id]['marks'])) { + if (isset($attempt_list[$my_question_id]) && + isset($attempt_list[$my_question_id]['marks']) + ) { $total_score -= $attempt_list[$my_question_id]['marks']; } } @@ -438,7 +452,11 @@ 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 +472,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/forum.ajax.php b/main/inc/ajax/forum.ajax.php index 02211887b2..2c50ba3d96 100644 --- a/main/inc/ajax/forum.ajax.php +++ b/main/inc/ajax/forum.ajax.php @@ -8,7 +8,6 @@ */ require_once '../global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'document.lib.php'; require_once api_get_path(SYS_CODE_PATH) . 'forum/forumfunction.inc.php'; // First, protect this script 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/myspace.ajax.php b/main/inc/ajax/myspace.ajax.php index b19ad502d5..6a9bc74b85 100755 --- a/main/inc/ajax/myspace.ajax.php +++ b/main/inc/ajax/myspace.ajax.php @@ -17,19 +17,22 @@ switch ($action) { $type = Security::remove_XSS($_REQUEST['type']); $range = Security::remove_XSS($_REQUEST['range']); + $courseInfo = api_get_course_info($course_code); + $courseId = $courseInfo['real_id']; + if ($range == 1) { $start_date = Security::remove_XSS($_REQUEST['sd']); $end_date = Security::remove_XSS($_REQUEST['ed']); $sql_result = get_connections_to_course_by_date( $user_id, - $course_code, + $courseId, $start_date, $end_date ); } else { $sql_result = MySpace::get_connections_to_course( $user_id, - $course_code + $courseId ); } $foo_print = grapher($sql_result, $start_date, $end_date, $type); @@ -44,10 +47,12 @@ switch ($action) { $user_id = isset($_REQUEST['student']) ? $_REQUEST['student'] : ""; $course_code = isset($_REQUEST['course']) ? $_REQUEST['course'] : ""; $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : ""; + $courseInfo = api_get_course_info($course_code); + $courseId = $courseInfo['real_id']; $sql_result = get_connections_to_course_by_date( $user_id, - $course_code, + $courseId, $start_date, $end_date ); diff --git a/main/inc/ajax/skill.ajax.php b/main/inc/ajax/skill.ajax.php index 31b0d4d876..c87197271e 100755 --- a/main/inc/ajax/skill.ajax.php +++ b/main/inc/ajax/skill.ajax.php @@ -74,8 +74,7 @@ switch ($action) { break; case 'get_course_info_popup': $course_info = api_get_course_info($_REQUEST['code']); - $course_info['course_code'] = $course_info['code']; - $courses = CourseManager::process_hot_course_item(array($course_info)); + $courses = CourseManager::process_hot_course_item(array($course_info['real_id'])); Display::display_no_header(); Display::$global_template->assign('hot_courses', $courses); echo Display::$global_template->fetch('default/layout/hot_course_item_popup.tpl'); diff --git a/main/inc/ajax/timeline.ajax.php b/main/inc/ajax/timeline.ajax.php index bbeb9b6160..b174c3e0ef 100755 --- a/main/inc/ajax/timeline.ajax.php +++ b/main/inc/ajax/timeline.ajax.php @@ -1,7 +1,7 @@ '; var_dump($items);*/ break; -} \ No newline at end of file +} diff --git a/main/inc/ajax/user_manager.ajax.php b/main/inc/ajax/user_manager.ajax.php index f7f22a7e18..7bdb33a23c 100755 --- a/main/inc/ajax/user_manager.ajax.php +++ b/main/inc/ajax/user_manager.ajax.php @@ -101,19 +101,20 @@ switch ($action) { 'userId' => $user_id ); - $result = api_mail( + $result = api_mail_html( $recipient_name, $user_info['mail'], $emailsubject, $emailbody, $sender_name, $email_admin, - '', + null, + 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 f7759e2370..4b8a96f891 100755 --- a/main/inc/global.inc.php +++ b/main/inc/global.inc.php @@ -25,8 +25,8 @@ define('SHOW_ERROR_CODES', false); // Determine the directory path where this current file lies. -// This path will be useful to include the other intialisation files. -$includePath = dirname(__FILE__); +// This path will be useful to include the other initialisation files. +$includePath = __DIR__; // @todo Isn't this file renamed to configuration.inc.php yet? // Include the main Chamilo platform configuration file. @@ -83,9 +83,6 @@ if (api_get_setting('login_is_email') == 'true') { } define('USERNAME_MAX_LENGTH', $default_username_length); -// Do not over-use this variable. It is only for this script's local use. -$lib_path = dirname(__FILE__).'/../../main/inc/lib/'; - // Fix bug in IIS that doesn't fill the $_SERVER['REQUEST_URI']. api_request_uri(); @@ -96,22 +93,22 @@ ini_set('include_path', api_create_include_path_setting()); ini_set('auto_detect_line_endings', '1'); // Include the libraries that are necessary everywhere -require_once dirname(__FILE__).'/../../vendor/autoload.php'; +require_once __DIR__.'/../../vendor/autoload.php'; + +// Do not over-use this variable. It is only for this script's local use. +$libraryPath = api_get_path(LIBRARY_PATH); // @todo convert this libs in classes -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 $lib_path.'mail.lib.inc.php'; -require_once api_get_path(SYS_CODE_PATH).'exercice/exercise.lib.php'; -require_once $lib_path.'course_category.lib.php'; + +require_once $libraryPath.'database.constants.inc.php'; +require_once $libraryPath.'text.lib.php'; +require_once $libraryPath.'array.lib.php'; +require_once $libraryPath.'online.inc.php'; +require_once $libraryPath.'banner.lib.php'; +require_once $libraryPath.'fileManage.lib.php'; +require_once $libraryPath.'fileUpload.lib.php'; +require_once $libraryPath.'fileDisplay.lib.php'; +require_once $libraryPath.'course_category.lib.php'; define('_MPDF_TEMP_PATH', api_get_path(SYS_ARCHIVE_PATH).'mpdf/'); if (!is_dir(_MPDF_TEMP_PATH)) { @@ -313,7 +310,7 @@ foreach ($result as & $row) { } // Load allowed tag definitions for kses and/or HTMLPurifier. -require_once $lib_path.'formvalidator/Rule/allowed_tags.inc.php'; +require_once $libraryPath.'formvalidator/Rule/allowed_tags.inc.php'; // Before we call local.inc.php, let's define a global $this_section variable // which will then be usable from the banner and header scripts @@ -328,14 +325,22 @@ require $includePath.'/local.inc.php'; $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com'; $administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin'; -$mail_conf = api_get_path(CONFIGURATION_PATH).'mail.conf.php'; -if (file_exists($mail_conf)) { - require_once $mail_conf; -} +// Including configuration files +$configurationFiles = array( + 'mail.conf.php', + 'profile.conf.php', + 'course_info.conf.php', + 'add_course.conf.php', + 'events.conf.php', + 'auth.conf.php', + 'portfolio.conf.php' +); -$profileConf = api_get_path(CONFIGURATION_PATH).'profile.conf.php'; -if (file_exists($profileConf)) { - require_once $profileConf; +foreach ($configurationFiles as $file) { + $file = api_get_path(CONFIGURATION_PATH).$file; + if (file_exists($file)) { + require_once $file; + } } if (api_get_setting('server_type') == 'test') { @@ -343,41 +348,7 @@ if (api_get_setting('server_type') == 'test') { ini_set('log_errors', '1'); error_reporting(-1); } else { - /* - Server type is not test - - normal error reporting level - - full fake register globals block - */ error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR); - - // TODO: These obsolete variables $HTTP_* to be check whether they are actually used. - if (!isset($HTTP_GET_VARS)) { $HTTP_GET_VARS = $_GET; } - if (!isset($HTTP_POST_VARS)) { $HTTP_POST_VARS = $_POST; } - if (!isset($HTTP_POST_FILES)) { $HTTP_POST_FILES = $_FILES; } - if (!isset($HTTP_SESSION_VARS)) { $HTTP_SESSION_VARS = $_SESSION; } - if (!isset($HTTP_SERVER_VARS)) { $HTTP_SERVER_VARS = $_SERVER; } - - // Register SESSION variables into $GLOBALS - if (sizeof($HTTP_SESSION_VARS)) { - if (!is_array($_SESSION)) { - $_SESSION = array(); - } - foreach ($HTTP_SESSION_VARS as $key => $val) { - $_SESSION[$key] = $HTTP_SESSION_VARS[$key]; - $GLOBALS[$key] = $HTTP_SESSION_VARS[$key]; - } - } - - // Register SERVER variables into $GLOBALS - if (sizeof($HTTP_SERVER_VARS)) { - $_SERVER = array(); - foreach ($HTTP_SERVER_VARS as $key => $val) { - $_SERVER[$key] = $HTTP_SERVER_VARS[$key]; - if (!isset($_SESSION[$key]) && $key != 'includePath' && $key != 'rootSys' && $key!= 'lang_path' && $key!= 'extAuthSource' && $key!= 'thisAuthSource' && $key!= 'main_configuration_file_path' && $key!= 'phpDigIncCn' && $key!= 'drs') { - $GLOBALS[$key]=$HTTP_SERVER_VARS[$key]; - } - } - } } /* LOAD LANGUAGE FILES SECTION */ @@ -395,8 +366,7 @@ if (!empty($_POST['language_list'])) { } if (empty($user_language) && !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && !isset($_SESSION['_user'])) { - require_once __DIR__.'/../admin/sub_language.class.php'; - $l = subLanguageManager::getLanguageFromBrowserPreference($_SERVER['HTTP_ACCEPT_LANGUAGE']); + $l = SubLanguageManager::getLanguageFromBrowserPreference($_SERVER['HTTP_ACCEPT_LANGUAGE']); if (!empty($l)) { $user_language = $browser_language = $l; } @@ -408,7 +378,6 @@ $langpath = api_get_path(SYS_LANG_PATH); /* This will only work if we are in the page to edit a sub_language */ if (isset($this_script) && $this_script == 'sub_language') { - require_once '../admin/sub_language.class.php'; // getting the arrays of files i.e notification, trad4all, etc $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(api_get_path(SYS_LANG_PATH).'english', true); //getting parent info @@ -532,7 +501,6 @@ $language_interface_initial_value = $language_interface; $language_files = array(); $language_files[] = 'trad4all'; $language_files[] = 'notification'; -$language_files[] = 'accessibility'; if (isset($language_file)) { if (!is_array($language_file)) { @@ -545,7 +513,6 @@ if (isset($language_file)) { if (is_array($language_files)) { // if the sub-language feature is on if (api_get_setting('allow_use_sub_language') == 'true') { - require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php'; $parent_path = SubLanguageManager::get_parent_language_path($language_interface); foreach ($language_files as $index => $language_file) { // include English @@ -595,14 +562,14 @@ if (!$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) { // ===== end "who is logged in?" module section ===== - //Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time) if (!isset($_SESSION['login_as']) && isset($_user)) { // if $_SESSION['login_as'] is set, then the user is an admin logged as the user - $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN); - $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='".$_user["user_id"]."' ORDER BY login_date DESC LIMIT 0,1"; + $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN); + $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login + WHERE login_user_id='".$_user["user_id"]."' ORDER BY login_date DESC LIMIT 0,1"; $q_last_connection = Database::query($sql_last_connection); if (Database::num_rows($q_last_connection) > 0) { @@ -615,7 +582,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/announcements/announcements.inc.php b/main/inc/lib/AnnouncementManager.php similarity index 62% rename from main/announcements/announcements.inc.php rename to main/inc/lib/AnnouncementManager.php index aae8286f69..feed917576 100755 --- a/main/announcements/announcements.inc.php +++ b/main/inc/lib/AnnouncementManager.php @@ -104,10 +104,10 @@ class AnnouncementManager } /** - * This functions swithes the visibility a course resource + * This functions switches the visibility a course resource * using the visibility field in 'item_property' - * @param array the course array - * @param int ID of the element of the corresponding type + * @param array $_course + * @param int $id ID of the element of the corresponding type * @return bool False on failure, True on success */ public static function change_visibility_announcement($_course, $id) @@ -154,7 +154,7 @@ class AnnouncementManager public static function display_announcement($announcement_id) { if ($announcement_id != strval(intval($announcement_id))) { - return false; + return null; } global $charset; @@ -166,14 +166,14 @@ class AnnouncementManager if (api_is_allowed_to_edit(false, true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { $sql_query = " SELECT announcement.*, toolitemproperties.* FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties - WHERE announcement.id = toolitemproperties.ref - AND announcement.id = '$announcement_id' - AND toolitemproperties.tool='announcement' AND - announcement.c_id = $course_id AND - toolitemproperties.c_id = $course_id + WHERE + announcement.id = toolitemproperties.ref AND + announcement.id = '$announcement_id' AND + toolitemproperties.tool='announcement' AND + announcement.c_id = $course_id AND + toolitemproperties.c_id = $course_id ORDER BY display_order DESC"; } else { - $group_list = GroupManager::get_group_ids($course_id, api_get_user_id()); if (empty($group_list)) { $group_list[] = 0; @@ -181,38 +181,47 @@ class AnnouncementManager if (api_get_user_id() != 0) { $sql_query = " SELECT announcement.*, toolitemproperties.* FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties - WHERE announcement.id = toolitemproperties.ref - AND announcement.id = '$announcement_id' - AND toolitemproperties.tool='announcement' - AND (toolitemproperties.to_user_id='" . api_get_user_id() . "' OR toolitemproperties.to_group_id IN ('0', '" . implode("', '", $group_list) . "')) - AND toolitemproperties.visibility='1' AND - announcement.c_id = $course_id AND - toolitemproperties.c_id = $course_id + WHERE + announcement.id = toolitemproperties.ref AND + announcement.id = '$announcement_id' AND + toolitemproperties.tool='announcement' AND + ( + toolitemproperties.to_user_id='" . api_get_user_id() . "' OR + toolitemproperties.to_group_id IN ('0', '" . implode("', '", $group_list) . "') + ) AND + toolitemproperties.visibility='1' AND + announcement.c_id = $course_id AND + toolitemproperties.c_id = $course_id ORDER BY display_order DESC"; } else { $sql_query = " SELECT announcement.*, toolitemproperties.* FROM $tbl_announcement announcement, $tbl_item_property toolitemproperties - WHERE announcement.id = toolitemproperties.ref - AND announcement.id = '$announcement_id' - AND toolitemproperties.tool='announcement' - AND toolitemproperties.to_group_id='0' - AND toolitemproperties.visibility='1' AND - announcement.c_id = $course_id AND - toolitemproperties.c_id = $course_id + WHERE + announcement.id = toolitemproperties.ref AND + announcement.id = '$announcement_id' AND + toolitemproperties.tool='announcement' AND + toolitemproperties.to_group_id='0' AND + toolitemproperties.visibility='1' AND + announcement.c_id = $course_id AND + toolitemproperties.c_id = $course_id "; } } $sql_result = Database::query($sql_query); + $html = null; if (Database::num_rows($sql_result) > 0) { $result = Database::fetch_array($sql_result, 'ASSOC'); $title = $result['title']; $content = $result['content']; - echo ""; - echo ""; - - if (api_is_allowed_to_edit(false, true) || (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { - $modify_icons = "" . Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . ""; + $html .= "

    " . $title . "

    "; + $html .= ""; + + if (api_is_allowed_to_edit(false, true) || + (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) + ) { + $modify_icons = "" . + Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL) . ""; if ($result['visibility'] == 1) { $image_visibility = "visible"; $alt_visibility = get_lang('Hide'); @@ -230,14 +239,13 @@ class AnnouncementManager Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . ""; } - echo ""; + $html .= ""; } $content = self::parse_content($result['to_user_id'], $content, api_get_course_id(), api_get_session_id()); - echo ""; - - echo ""; + $html .= ""; + $html .= ""; // User or group icon $sent_to_icon = ''; @@ -246,27 +254,31 @@ class AnnouncementManager } $sent_to = self::sent_to('announcement', $announcement_id); $sent_to_form = self::sent_to_form($sent_to); - echo Display::tag('td', get_lang('SentTo') . ' : ' . $sent_to_form, array('class' => 'announcements_datum')); + $html .= Display::tag('td', get_lang('SentTo') . ' : ' . $sent_to_form, array('class' => 'announcements_datum')); $attachment_list = self::get_attachment($announcement_id); if (count($attachment_list) > 0) { - echo "'; + $html .= ''; } - echo "

    " . $title . "

    $modify_icons
    $modify_icons
    $content
    " . get_lang('LastUpdateDate') . " : " . api_convert_and_format_date($result['insert_date'], DATE_TIME_FORMAT_LONG) . "
    $content
    " . get_lang('LastUpdateDate') . " : " . api_convert_and_format_date($result['insert_date'], DATE_TIME_FORMAT_LONG) . "
    "; + $html .= "
    "; $realname = $attachment_list['path']; $user_filename = $attachment_list['filename']; $full_file_name = 'download.php?'.api_get_cidreq().'&file=' . $realname; - echo '
    '; - echo Display::return_icon('attachment.gif', get_lang('Attachment')); - echo ' ' . $user_filename . ' '; - echo ' - ' . $attachment_list['comment'] . ''; + $html .= '
    '; + $html .= Display::return_icon('attachment.gif', get_lang('Attachment')); + $html .= ' ' . $user_filename . ' '; + $html .= ' - ' . $attachment_list['comment'] . ''; if (api_is_allowed_to_edit(false, true)) { - echo Display::url(Display::return_icon('delete.png', get_lang('Delete'), '', 16), api_get_self() . "?" . api_get_cidreq() . "&action=delete_attachment&id_attach=" . $attachment_list['id'] . "&sec_token=" . $stok); + $html .= Display::url( + Display::return_icon('delete.png', get_lang('Delete'), '', 16), + api_get_self() . "?" . api_get_cidreq() . "&action=delete_attachment&id_attach=" . $attachment_list['id'] . "&sec_token=" . $stok + ); } - echo '
    "; - } else { - return false; + $html .= ""; + return $html; } + + return null; } /** @@ -295,6 +307,7 @@ class AnnouncementManager * @param array Array of users and groups to send the announcement to * @param array uploaded file $_FILES * @param string Comment describing the attachment + * @param bool $sendToUsersInSession * @return int false on failure, ID of the announcement on success */ public static function add_announcement( @@ -324,43 +337,71 @@ class AnnouncementManager $order = self::get_last_announcement_order(); // store in the table announcement - $sql = "INSERT INTO $tbl_announcement SET - c_id = '$course_id', - content = '$newContent', - title = '$emailTitle', - end_date = '$end_date', - display_order = '$order', - session_id = ".api_get_session_id(); - $result = Database::query($sql); + $params = array( + 'c_id' => $course_id, + 'content' => $newContent, + 'title' => $emailTitle, + 'end_date' => $end_date, + 'display_order' => $order, + 'session_id' => api_get_session_id() + ); - if ($result === false) { + $last_id = Database::insert($tbl_announcement, $params); + + if (empty($last_id)) { return false; } else { - // Store the attach file. - $last_id = Database::insert_id(); if (!empty($file)) { - self::add_announcement_attachment_file($last_id, $file_comment, $_FILES['user_upload']); + self::add_announcement_attachment_file( + $last_id, + $file_comment, + $_FILES['user_upload'] + ); } // store in item_property (first the groups, then the users - if (empty($sentTo) || !empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone') { + if (empty($sentTo) || !empty($sentTo) && + isset($sentTo[0]) && $sentTo[0] == 'everyone' + ) { // The message is sent to EVERYONE, so we set the group to 0 - api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '0'); + api_item_property_update( + $_course, + TOOL_ANNOUNCEMENT, + $last_id, + "AnnouncementAdded", + api_get_user_id(), + '0' + ); } else { $send_to = self::separate_users_groups($sentTo); // Storing the selected groups - if (is_array($send_to['groups'])) { + if (is_array($send_to['groups']) && !empty($send_to['groups'])) { foreach ($send_to['groups'] as $group) { - api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), $group); + api_item_property_update( + $_course, + TOOL_ANNOUNCEMENT, + $last_id, + "AnnouncementAdded", + api_get_user_id(), + $group + ); } } // Storing the selected users if (is_array($send_to['users'])) { foreach ($send_to['users'] as $user) { - api_item_property_update($_course, TOOL_ANNOUNCEMENT, $last_id, "AnnouncementAdded", api_get_user_id(), '', $user); + api_item_property_update( + $_course, + TOOL_ANNOUNCEMENT, + $last_id, + "AnnouncementAdded", + api_get_user_id(), + '', + $user + ); } } } @@ -910,8 +951,10 @@ class AnnouncementManager $id = intval($id); $course_id = api_get_course_int_id(); - $sql = "SELECT * FROM $tbl_item_property WHERE c_id = $course_id AND tool='$tool' AND ref = $id"; + $sql = "SELECT * FROM $tbl_item_property + WHERE c_id = $course_id AND tool='$tool' AND ref = $id"; $result = Database::query($sql); + $to = array(); while ($row = Database::fetch_array($result)) { $to_group = $row['to_group_id']; switch ($to_group) { @@ -922,7 +965,6 @@ class AnnouncementManager // it was sent to everyone case 0: return "everyone"; - exit; break; default: $to[] = "GROUP:" . $row['to_group_id']; @@ -1024,7 +1066,11 @@ class AnnouncementManager $user_info = api_get_user_info($sent_to_array['users'][0]); $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']); } - if (isset($sent_to_array['groups']) and is_array($sent_to_array['groups']) and isset($sent_to_array['groups'][0]) and $sent_to_array['groups'][0] !== 0) { + if (isset($sent_to_array['groups']) and + is_array($sent_to_array['groups']) and + isset($sent_to_array['groups'][0]) and + $sent_to_array['groups'][0] !== 0 + ) { $group_id = $sent_to_array['groups'][0]; $output[] = " " . $group_names[$group_id]['name']; } @@ -1252,4 +1298,451 @@ class AnnouncementManager $email = AnnouncementEmail::create(null, $id); $email->send($sendToUsersInSession); } + + /** + * @param $stok + * @param $announcement_number + */ + public static function getAnnouncements($stok, $announcement_number) + { + $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT); + $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY); + + $user_id = api_get_user_id(); + $group_id = api_get_group_id(); + $session_id = api_get_session_id(); + $condition_session = api_get_session_condition($session_id, true, true); + $course_id = api_get_course_int_id(); + $_course = api_get_course_info(); + + $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id()); + $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement'); + + if (api_is_allowed_to_edit(false, true) OR + ($allowUserEditSetting && !api_is_anonymous()) + ) { + // A.1. you are a course admin with a USER filter + // => see only the messages of this specific user + the messages of the group (s)he is member of. + if (!empty($user_id)) { + if (is_array($group_memberships) && count($group_memberships) > 0 ) { + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool = 'announcement' AND + (ip.to_user_id = $user_id OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) + $condition_session + + ORDER BY display_order DESC"; + + } else { + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool ='announcement' AND + (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND + ip.visibility='1' + $condition_session + ORDER BY display_order DESC"; + + } + } elseif (api_get_group_id() != 0 ) { + // A.2. you are a course admin with a GROUP filter + // => see only the messages of this specific group + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND ip.visibility<>'2' + AND (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC"; + } else { + + // A.3 you are a course admin without any group or user filter + // A.3.a you are a course admin without user or group filter but WITH studentview + // => see all the messages of all the users and groups without editing possibilities + + if (isset($isStudentView) and $isStudentView=="true") { + $sql="SELECT + announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND ip.visibility='1' + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC"; + } else { + // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view) + // => see all the messages of all the users and groups with editing possibilities + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND (ip.visibility='0' or ip.visibility='1') + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC"; + } + } + } else { + //STUDENT + if (is_array($group_memberships) && count($group_memberships)>0) { + if ($allowUserEditSetting && !api_is_anonymous()) { + if (api_get_group_id() == 0) { + // No group + $cond_user_id = " AND ( + ip.lastedit_user_id = '".$user_id."' OR ( + ip.to_user_id='".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) + ) "; + } else { + $cond_user_id = " AND ( + ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.") + )"; + } + } else { + if (api_get_group_id() == 0) { + $cond_user_id = " AND ( + ip.to_user_id=$user_id OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") + ) "; + } else { + $cond_user_id = " AND ( + ip.to_user_id=$user_id OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".api_get_group_id().") + )"; + } + } + + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + $cond_user_id + $condition_session AND + ip.visibility='1' + ORDER BY display_order DESC"; + } else { + if ($user_id) { + if ($allowUserEditSetting && !api_is_anonymous()) { + $cond_user_id = " AND ( + ip.lastedit_user_id = '".api_get_user_id()."' OR (ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL ) + ) "; + } else { + $cond_user_id = " AND (ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL ) "; + } + + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool='announcement' + $cond_user_id + $condition_session + AND ip.visibility='1' + AND announcement.session_id IN(0,".api_get_session_id().") + ORDER BY display_order DESC"; + } else { + if (($allowUserEditSetting && !api_is_anonymous())) { + $cond_user_id = " AND ( + ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL + )"; + } else { + $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL "; + } + + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.insert_date + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool='announcement' + $cond_user_id + $condition_session AND + ip.visibility='1' AND + announcement.session_id IN ( 0,".api_get_session_id().")"; + } + } + } + + $result = Database::query($sql); + $num_rows = Database::num_rows($result); + $html = null; + + if ($num_rows == 0) { + if ((api_is_allowed_to_edit(false, true) OR + (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) and + (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') + ) { + $html .= '
    '; + $html .= '

    ' . get_lang('Announcements') . '

    '; + $html .= Display::return_icon('valves.png', '', array(), 64); + $html .= '
    '; + $html .= Display::url( + get_lang('AddAnnouncement'), + api_get_self() . "?" . api_get_cidreq() . "&action=add", + array('class' => 'btn') + ); + $html .= '
    '; + $html .= '
    '; + } else { + $html = Display::return_message(get_lang('NoAnnouncements'), 'warning'); + } + return $html; + } + + $iterator = 1; + $bottomAnnouncement = $announcement_number; + $origin = null; + + $html .= ''; + $ths = Display::tag('th', get_lang('Title')); + $ths .= Display::tag('th', get_lang('By') ); + $ths .= Display::tag('th', get_lang('LastUpdateDate') ); + if (api_is_allowed_to_edit(false,true) OR (api_is_course_coach() && + api_is_element_in_the_session(TOOL_ANNOUNCEMENT,$myrow['id'])) + OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { + $ths .= Display::tag('th', get_lang('Modify')); + } + + $html .= Display::tag('tr', $ths); + $displayed = array(); + while ($myrow = Database::fetch_array($result, 'ASSOC')) { + if (!in_array($myrow['id'], $displayed)) { + $sent_to_icon = ''; + // the email icon + if ($myrow['email_sent'] == '1') { + $sent_to_icon = ' '.Display::return_icon('email.gif', get_lang('AnnounceSentByEmail')); + } + + $title = $myrow['title'].$sent_to_icon; + $item_visibility = api_get_item_visibility($_course, TOOL_ANNOUNCEMENT, $myrow['id'], $session_id); + $myrow['visibility'] = $item_visibility; + + // the styles + if ($myrow['visibility'] == '0') { + $style='invisible'; + } else { + $style = ''; + } + + $html .= ''; + + // show attachment list + $attachment_list = AnnouncementManager::get_attachment($myrow['id']); + + $attachment_icon = ''; + if (count($attachment_list)>0) { + $attachment_icon = ' '.Display::return_icon('attachment.gif',get_lang('Attachment')); + } + + /* TITLE */ + $user_info = api_get_user_info($myrow['insert_user_id']); + $username = sprintf(get_lang("LoginX"), $user_info['username']); + $username_span = Display::tag('span', api_get_person_name($user_info['firstName'], $user_info['lastName']), array('title'=>$username)); + $title = Display::url($title.$attachment_icon, api_get_self().'?'.api_get_cidreq().'&action=view&id='.$myrow['id']); + + $html .= Display::tag('td', Security::remove_XSS($title), array('class' => 'announcements-list-line-title '.$style)); + $html .= Display::tag('td', $username_span, array('class' => 'announcements-list-line-by-user')); + $html .= Display::tag('td', api_convert_and_format_date($myrow['insert_date'], DATE_TIME_FORMAT_LONG), array('class' => 'announcements-list-line-datetime')); + + // we can edit if : we are the teacher OR the element belongs to + // the session we are coaching OR the option to allow users to edit is on + if (api_is_allowed_to_edit(false,true) OR + (api_is_course_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $myrow['id'])) + OR (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) + ) { + + $modify_icons = "". + Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).""; + if ($myrow['visibility']==1) { + $image_visibility="visible"; + $alt_visibility=get_lang('Hide'); + } else { + $image_visibility="invisible"; + $alt_visibility=get_lang('Visible'); + } + $modify_icons .= "". + Display::return_icon($image_visibility.'.png', $alt_visibility,'',ICON_SIZE_SMALL).""; + + // DISPLAY MOVE UP COMMAND only if it is not the top announcement + if ($iterator != 1) { + $modify_icons .= "". + Display::return_icon('up.gif', get_lang('Up')).""; + } else { + $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up')); + } + if ($iterator < $bottomAnnouncement) { + $modify_icons .= "". + Display::return_icon('down.gif', get_lang('Down')).""; + } else { + $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down')); + } + if (api_is_allowed_to_edit(false,true)) { + $modify_icons .= "". + Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL). + ""; + } + $iterator ++; + $html .= Display::tag('td', $modify_icons, array('class' => 'announcements-list-line-actions')); + } + $html .= ""; + } + $displayed[] = $myrow['id']; + } + $html .= "
    "; + + return $html; + } + + /** + * @return int + */ + public static function getNumberAnnouncements() + { + // Maximum title messages to display + $maximum = '12'; + // Database Table Definitions + $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT); + $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY); + + $course_id = api_get_course_int_id(); + $_course = api_get_course_info(); + $session_id = api_get_session_id(); + $userId = api_get_user_id(); + $condition_session = api_get_session_condition($session_id, true, true); + + if (api_is_allowed_to_edit(false,true)) { + // check teacher status + if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') { + + if (api_get_group_id() == 0) { + $group_condition = ""; + } else { + $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0)"; + } + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool = 'announcement' AND + ip.visibility <> '2' + $group_condition + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC + LIMIT 0,$maximum"; + } + } else { + // students only get to see the visible announcements + if (empty($_GET['origin']) or $_GET['origin'] !== 'learnpath') { + $group_memberships = GroupManager::get_group_ids($_course['real_id'], $userId); + + if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { + + if (api_get_group_id() == 0) { + $cond_user_id = " AND (ip.lastedit_user_id = '".$userId."' OR ( ip.to_user_id='".$userId."'" . + "OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))) "; + } else { + $cond_user_id = " AND (ip.lastedit_user_id = '".$userId."' + OR ip.to_group_id IN (0, ".api_get_group_id()."))"; + } + } else { + if (api_get_group_id() == 0) { + $cond_user_id = " AND ( ip.to_user_id='".$userId."'" . + "OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) "; + } else { + $cond_user_id = " AND ( ip.to_user_id='".$userId."'" . + "OR ip.to_group_id IN (0, ".api_get_group_id().")) "; + } + } + + // the user is member of several groups => display personal announcements AND his group announcements AND the general announcements + if (is_array($group_memberships) && count($group_memberships)>0) { + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref AND + ip.tool='announcement' + AND ip.visibility='1' + $cond_user_id + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC + LIMIT 0, $maximum"; + } else { + // the user is not member of any group + // this is an identified user => show the general announcements AND his personal announcements + if ($userId) { + if ((api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())) { + $cond_user_id = " AND (ip.lastedit_user_id = '".$userId."' OR ( ip.to_user_id='".$userId."' OR ip.to_group_id='0')) "; + } else { + $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0') "; + } + $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND ip.visibility='1' + $cond_user_id + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC + LIMIT 0, $maximum"; + } else { + + if (api_get_course_setting('allow_user_edit_announcement')) { + $cond_user_id = " AND (ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0') "; + } else { + $cond_user_id = " AND ip.to_group_id='0' "; + } + + // the user is not identiefied => show only the general announcements + $sql="SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id + FROM $tbl_announcement announcement, $tbl_item_property ip + WHERE + announcement.c_id = $course_id AND + ip.c_id = $course_id AND + announcement.id = ip.ref + AND ip.tool='announcement' + AND ip.visibility='1' + AND ip.to_group_id='0' + $condition_session + GROUP BY ip.ref + ORDER BY display_order DESC + LIMIT 0,$maximum"; + } + } + } + } + + $result = Database::query($sql); + return Database::num_rows($result); + } } diff --git a/main/inc/lib/WCAG/WCAG_rendering.php b/main/inc/lib/WCAG/WCAG_rendering.php deleted file mode 100755 index ec7691687b..0000000000 --- a/main/inc/lib/WCAG/WCAG_rendering.php +++ /dev/null @@ -1,192 +0,0 @@ - | -// | Bertrand Mansion | -// +----------------------------------------------------------------------+ -// -// $Id: wai_rendering.php,v 1.0 2006/10/07 20:12:17 avb Exp $ -/** - * @package chamilo.include - */ - -/** - * helper for WCAG rendering. - * - * @author Patrick Vandermaesen - * @version 1.0 - * @package chamilo.include - */ -class WCAG_Rendering -{ - - function editor_header() { - return '
    '.get_lang('WCAGEditor').'
    '; - } - - function editor_footer() { - return '
    '; - } - - function prepareXHTML() { - $text = $_POST['text']; - $text = WCAG_Rendering::text_to_HTML ( $text ); - $imageFile = $_POST['imagefile']; - $imageLabel = $_POST['imageLabel']; - $link = $_POST['link']; - $linkLabel = $_POST['linkLabel']; - if (strlen($linkLabel) == 0) { - $linkLabel = $link; - } - $home_top='
    '.$imageLabel.''.'

    '.$text.'

    '; - if (strlen($link) > 0) { - $home_top = $home_top.''.$linkLabel.''; - } - $home_top=$home_top."
    "; - return $home_top; - } - - /** - * this method validate the content of current request (from WCAG editor). - * this function return the error msg. - */ - function request_validation() { - $imageFile = $_POST['imagefile']; - $imageLabel = $_POST['imageLabel']; - if ((strlen($imageFile) > 0) and (strlen($imageLabel) == 0)) { - return get_lang('ErrorNoLabel'); - } - return ''; - } - -/** -* Converter Plaintext to (x)HTML -*/ -function text_to_HTML ($Text) -{ - $t = $Text; - $t = stripslashes($t); - $t = str_replace(">", ">", $t); - $t = str_replace("<", "<", $t); - - $t = preg_replace("/(\015\012)|(\015)|(\012)/", "
    \n", $t); - $t = str_replace(" ", "  ", $t); - return $t; -} - -function HTML_to_text ($xhtml) { - // convert HTML to text. - $text = str_replace("
    ", "", $xhtml); - $text = str_replace("
    ", "", $text); - $text = str_replace(" ", " ", $text); - return $text; -} - -function extract_data ($xhtml) { - $text = $xhtml; - if (stripos($xhtml, '

    ')) { - $startP = stripos ($xhtml, "

    "); - $endP = stripos ($xhtml, "

    "); - $text = substr ($xhtml, $startP+3, $endP-$startP-3 ); - } - - // convert HTML to text. - $text = WCAG_Rendering::HTML_to_text($text); - - $url=''; - if (stripos($xhtml, '"); - $link = substr ($subxhtml, $startLinkURL+5, $endLinkURL-$startLinkURL-5 ); - - $endLinkLabel = stripos ($subxhtml, ""); - $linkLabel = substr ( $subxhtml, $endLinkURL+2, $endLinkLabel-$endLinkURL-2 ); - } - - $values = array("text"=>$text, - "imagefile"=>$url, - "imageLabel"=>$label, - "link"=>$link, - "linkLabel"=>$linkLabel); - return $values; -} - -/** -* add a form for set WCAG content (replace FCK) -* @version 1.1 -*/ -function &prepare_admin_form( $xhtml, &$form ) -{ - $values = WCAG_Rendering::extract_data($xhtml); - - if ($form == null) { - $form = new FormValidator('waiForm'); - } - $form->addElement('textarea','text',get_lang('WCAGContent')); - $file =& $form->addElement('text','imagefile',get_lang('WCAGImage')); - $form->addElement('text','imageLabel',get_lang('WCAGLabel')); - $form->addElement('text','link',get_lang('WCAGLink')); - $form->addElement('text','linkLabel',get_lang('WCAGLinkLabel')); - - $form->setDefaults($values); - - $renderer =& $form->defaultRenderer(); - $element_template = '* {label}
    - {error}
    {element}
    '; - $renderer->setElementTemplate($element_template); - - return $form; -} - -function &create_xhtml($xhtml) { - $values = WCAG_Rendering::extract_data($xhtml); - $xhtml = WCAG_Rendering::editor_header(); - $xhtml .= get_lang('WCAGContent').'
    '; - $xhtml .= ''; - $xhtml .= get_lang('WCAGImage').'
    '; - $xhtml .= ''; - $xhtml .= '
    '; - $xhtml .= ''.get_lang('SelectPicture').''; - $xhtml .= '
    '; - $xhtml .= get_lang('WCAGLabel').'
    '; - $xhtml .= ''; - $xhtml .= get_lang('WCAGLink').'
    '; - $xhtml .= ''; - $xhtml .= get_lang('WCAGLinkLabel').'
    '; - $xhtml .= ''; - - $xhtml .= WCAG_Rendering::editor_footer();; - return $xhtml; -} - -} // end class WAI_Rendering diff --git a/main/inc/lib/WCAG/index.html b/main/inc/lib/WCAG/index.html deleted file mode 100755 index aa7b9c934b..0000000000 --- a/main/inc/lib/WCAG/index.html +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/main/inc/lib/add_course.lib.inc.php b/main/inc/lib/add_course.lib.inc.php index c9e48eddf8..c116600342 100755 --- a/main/inc/lib/add_course.lib.inc.php +++ b/main/inc/lib/add_course.lib.inc.php @@ -1,2983 +1,3284 @@ '', 'CourseDb' => '', 'CourseDir' => ''); + $limit_numb_try = 100; + $keys_are_unique = false; + $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0; - $keys = array(); - $final_suffix = array('CourseId' => '', 'CourseDb' => '', 'CourseDir' => ''); - $limit_numb_try = 100; - $keys_are_unique = false; - $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0; + while (!$keys_are_unique) { - while (!$keys_are_unique) { + $keys_course_id = $prefix_for_all . $unique_prefix . $wanted_code . $final_suffix['CourseId']; + //$keys_course_db_name = $prefix_for_base_name . $unique_prefix . strtoupper($keys_course_id) . $final_suffix['CourseDb']; + $keys_course_repository = $prefix_for_path . $unique_prefix . $wanted_code . $final_suffix['CourseDir']; + $keys_are_unique = true; - $keys_course_id = $prefix_for_all . $unique_prefix . $wanted_code . $final_suffix['CourseId']; - //$keys_course_db_name = $prefix_for_base_name . $unique_prefix . strtoupper($keys_course_id) . $final_suffix['CourseDb']; - $keys_course_repository = $prefix_for_path . $unique_prefix . $wanted_code . $final_suffix['CourseDir']; - $keys_are_unique = true; + // Check whether they are unique. + $query = "SELECT 1 FROM ".$course_table." WHERE code='".$keys_course_id."' LIMIT 0,1"; + $result = Database::query($query); - // Check whether they are unique. - $query = "SELECT 1 FROM ".$course_table." WHERE code='".$keys_course_id."' LIMIT 0,1"; - $result = Database::query($query); + if (Database::num_rows($result)) { + $keys_are_unique = false; + $try_new_fsc_id ++; + $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4); + } + if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) { + $keys_are_unique = false; + $try_new_fsc_dir ++; + $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4); + } - if (Database::num_rows($result)) { - $keys_are_unique = false; - $try_new_fsc_id ++; - $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4); - } - if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) { - $keys_are_unique = false; - $try_new_fsc_dir ++; - $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4); + if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) { + return $keys; + } } - if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) { - return $keys; - } - } + $keys['currentCourseCode'] = $keys_course_code; + $keys['currentCourseId'] = $keys_course_id; + $keys['currentCourseRepository'] = $keys_course_repository; - $keys['currentCourseCode'] = $keys_course_code; - $keys['currentCourseId'] = $keys_course_id; - $keys['currentCourseRepository'] = $keys_course_repository; + return $keys; + } - return $keys; -} + /** + * Initializes a file repository for a newly created course. + * @param string Course repository + * @param string Course code + * @return int 0 + * @assert (null,null) === false + */ + public static function prepare_course_repository($course_repository, $course_code) + { + $perm = api_get_permissions_for_new_directories(); + $perm_file = api_get_permissions_for_new_files(); + $htmlpage = "\n\n \n \n Not authorized\n \n \n \n"; + $cp = api_get_path(SYS_COURSE_PATH) . $course_repository; -/** - * Initializes a file repository for a newly created course. - * @param string Course repository - * @param string Course code - * @return int 0 - * @assert (null,null) === false - */ -function prepare_course_repository($course_repository, $course_code) { - - $perm = api_get_permissions_for_new_directories(); - $perm_file = api_get_permissions_for_new_files(); - $htmlpage = "\n\n \n \n Not authorized\n \n \n \n"; - $cp = api_get_path(SYS_COURSE_PATH).$course_repository; - - //Creating document folder - mkdir($cp, $perm); - mkdir($cp . '/document', $perm); - $cpt = $cp.'/document/index.html'; - $fd = fopen($cpt, 'w'); - fwrite($fd, $htmlpage); - fclose($fd); - - /* - @chmod($cpt, $perm_file); - @copy($cpt, $cp . '/document/index.html'); - mkdir($cp . '/document/images', $perm); - @copy($cpt, $cp . '/document/images/index.html'); - mkdir($cp . '/document/images/gallery/', $perm); - @copy($cpt, $cp . '/document/images/gallery/index.html'); - mkdir($cp . '/document/shared_folder/', $perm); - @copy($cpt, $cp . '/document/shared_folder/index.html'); - mkdir($cp . '/document/audio', $perm); - @copy($cpt, $cp . '/document/audio/index.html'); - mkdir($cp . '/document/flash', $perm); - @copy($cpt, $cp . '/document/flash/index.html'); - mkdir($cp . '/document/video', $perm); - @copy($cpt, $cp . '/document/video/index.html'); */ - - //Creatind dropbox folder - mkdir($cp . '/dropbox', $perm); - $cpt = $cp.'/dropbox/index.html'; - $fd = fopen($cpt, 'w'); - fwrite($fd, $htmlpage); - fclose($fd); - @chmod($cpt, $perm_file); - mkdir($cp . '/group', $perm); - @copy($cpt, $cp . '/group/index.html'); - mkdir($cp . '/page', $perm); - @copy($cpt, $cp . '/page/index.html'); - mkdir($cp . '/scorm', $perm); - @copy($cpt, $cp . '/scorm/index.html'); - mkdir($cp . '/upload', $perm); - @copy($cpt, $cp . '/upload/index.html'); - mkdir($cp . '/upload/forum', $perm); - @copy($cpt, $cp . '/upload/forum/index.html'); - mkdir($cp . '/upload/forum/images', $perm); - @copy($cpt, $cp . '/upload/forum/images/index.html'); - mkdir($cp . '/upload/test', $perm); - @copy($cpt, $cp . '/upload/test/index.html'); - mkdir($cp . '/upload/blog', $perm); - @copy($cpt, $cp . '/upload/blog/index.html'); - mkdir($cp . '/upload/learning_path', $perm); - @copy($cpt, $cp . '/upload/learning_path/index.html'); - mkdir($cp . '/upload/learning_path/images', $perm); - @copy($cpt, $cp . '/upload/learning_path/images/index.html'); - mkdir($cp . '/upload/calendar', $perm); - @copy($cpt, $cp . '/upload/calendar/index.html'); - mkdir($cp . '/upload/calendar/images', $perm); - @copy($cpt, $cp . '/upload/calendar/images/index.html'); - mkdir($cp . '/work', $perm); - @copy($cpt, $cp . '/work/index.html'); - mkdir($cp . '/upload/announcements', $perm); - @copy($cpt, $cp . '/upload/announcements/index.html'); - mkdir($cp . '/upload/announcements/images', $perm); - @copy($cpt, $cp . '/upload/announcements/images/index.html'); - - //Oral expression question type - mkdir($cp . '/exercises', $perm); - @copy($cpt, $cp . '/exercises/index.html'); - - // Create .htaccess in the dropbox directory. - $fp = fopen($cp . '/dropbox/.htaccess', 'w'); - fwrite($fp, "AuthName AllowLocalAccess - AuthType Basic - - order deny,allow - deny from all - - php_flag zlib.output_compression off"); - fclose($fp); - - // Build index.php of the course. - $fd = fopen($cp . '/index.php', 'w'); - - // str_replace() removes \r that cause squares to appear at the end of each line - //@todo fix the harcoded include - $string = str_replace("\r", "", ""); - fwrite($fd, $string); - @chmod($cp . '/index.php',$perm_file); - return 0; -}; + //Creating document folder + mkdir($cp, $perm); + mkdir($cp . '/document', $perm); + $cpt = $cp . '/document/index.html'; + $fd = fopen($cpt, 'w'); + fwrite($fd, $htmlpage); + fclose($fd); -/** - * Gets an array with all the course tables (deprecated?) - * @return array - * @assert (null) !== null - */ -function get_course_tables() { - $tables = array(); - - $tables[]= 'tool'; - $tables[]= 'tool_intro'; - $tables[]= 'group_info'; - $tables[]= 'group_category'; - $tables[]= 'group_rel_user'; - $tables[]= 'group_rel_tutor'; - $tables[]= 'item_property'; - $tables[]= 'userinfo_content'; - $tables[]= 'userinfo_def'; - $tables[]= 'course_description'; - $tables[]= 'calendar_event'; - $tables[]= 'calendar_event_repeat'; - $tables[]= 'calendar_event_repeat_not'; - $tables[]= 'calendar_event_attachment'; - $tables[]= 'announcement'; - $tables[]= 'announcement_attachment'; - $tables[]= 'resource'; - $tables[]= 'student_publication'; - $tables[]= 'student_publication_assignment'; - $tables[]= 'document'; - $tables[]= 'forum_category'; - $tables[]= 'forum_forum'; - $tables[]= 'forum_thread'; - $tables[]= 'forum_post'; - $tables[]= 'forum_mailcue'; - $tables[]= 'forum_attachment'; - $tables[]= 'forum_notification'; - $tables[]= 'forum_thread_qualify'; - $tables[]= 'forum_thread_qualify_log'; - $tables[]= 'link'; - $tables[]= 'link_category'; - $tables[]= 'online_connected'; - $tables[]= 'online_link'; - $tables[]= 'chat_connected'; - $tables[]= 'quiz'; - $tables[]= 'quiz_rel_question'; - $tables[]= 'quiz_question'; - $tables[]= 'quiz_answer'; - $tables[]= 'quiz_question_option'; - $tables[]= 'quiz_question_category'; - $tables[]= 'quiz_question_rel_category'; - $tables[]= 'dropbox_post'; - $tables[]= 'dropbox_file'; - $tables[]= 'dropbox_person'; - $tables[]= 'dropbox_category'; - $tables[]= 'dropbox_feedback'; - $tables[]= 'lp'; - $tables[]= 'lp_item'; - $tables[]= 'lp_view'; - $tables[]= 'lp_item_view'; - $tables[]= 'lp_iv_interaction'; - $tables[]= 'lp_iv_objective'; - $tables[]= 'blog'; - $tables[]= 'blog_comment'; - $tables[]= 'blog_post'; - $tables[]= 'blog_rating'; - $tables[]= 'blog_rel_user'; - $tables[]= 'blog_task'; - $tables[]= 'blog_task_rel_user'; - $tables[]= 'blog_attachment'; - $tables[]= 'permission_group'; - $tables[]= 'permission_user'; - $tables[]= 'permission_task'; - $tables[]= 'role'; - $tables[]= 'role_group'; - $tables[]= 'role_permissions'; - $tables[]= 'role_user'; - $tables[]= 'survey'; - $tables[]= 'survey_question'; - $tables[]= 'survey_question_option'; - $tables[]= 'survey_invitation'; - $tables[]= 'survey_answer'; - $tables[]= 'survey_group'; - $tables[]= 'wiki'; - $tables[]= 'wiki_conf'; - $tables[]= 'wiki_discuss'; - $tables[]= 'wiki_mailcue'; - $tables[]= 'course_setting'; - $tables[]= 'glossary'; - $tables[]= 'notebook'; - $tables[]= 'attendance'; - $tables[]= 'attendance_sheet'; - $tables[]= 'attendance_calendar'; - $tables[]= 'attendance_result'; - $tables[]= 'attendance_sheet_log'; - $tables[]= 'thematic'; - $tables[]= 'thematic_plan'; - $tables[]= 'thematic_advance'; - $tables[]= 'metadata'; - - return $tables; -} + /* + @chmod($cpt, $perm_file); + @copy($cpt, $cp . '/document/index.html'); + mkdir($cp . '/document/images', $perm); + @copy($cpt, $cp . '/document/images/index.html'); + mkdir($cp . '/document/images/gallery/', $perm); + @copy($cpt, $cp . '/document/images/gallery/index.html'); + mkdir($cp . '/document/shared_folder/', $perm); + @copy($cpt, $cp . '/document/shared_folder/index.html'); + mkdir($cp . '/document/audio', $perm); + @copy($cpt, $cp . '/document/audio/index.html'); + mkdir($cp . '/document/flash', $perm); + @copy($cpt, $cp . '/document/flash/index.html'); + mkdir($cp . '/document/video', $perm); + @copy($cpt, $cp . '/document/video/index.html'); */ + + //Creatind dropbox folder + mkdir($cp . '/dropbox', $perm); + $cpt = $cp . '/dropbox/index.html'; + $fd = fopen($cpt, 'w'); + fwrite($fd, $htmlpage); + fclose($fd); + @chmod($cpt, $perm_file); + mkdir($cp . '/group', $perm); + @copy($cpt, $cp . '/group/index.html'); + mkdir($cp . '/page', $perm); + @copy($cpt, $cp . '/page/index.html'); + mkdir($cp . '/scorm', $perm); + @copy($cpt, $cp . '/scorm/index.html'); + mkdir($cp . '/upload', $perm); + @copy($cpt, $cp . '/upload/index.html'); + mkdir($cp . '/upload/forum', $perm); + @copy($cpt, $cp . '/upload/forum/index.html'); + mkdir($cp . '/upload/forum/images', $perm); + @copy($cpt, $cp . '/upload/forum/images/index.html'); + mkdir($cp . '/upload/test', $perm); + @copy($cpt, $cp . '/upload/test/index.html'); + mkdir($cp . '/upload/blog', $perm); + @copy($cpt, $cp . '/upload/blog/index.html'); + mkdir($cp . '/upload/learning_path', $perm); + @copy($cpt, $cp . '/upload/learning_path/index.html'); + mkdir($cp . '/upload/learning_path/images', $perm); + @copy($cpt, $cp . '/upload/learning_path/images/index.html'); + mkdir($cp . '/upload/calendar', $perm); + @copy($cpt, $cp . '/upload/calendar/index.html'); + mkdir($cp . '/upload/calendar/images', $perm); + @copy($cpt, $cp . '/upload/calendar/images/index.html'); + mkdir($cp . '/work', $perm); + @copy($cpt, $cp . '/work/index.html'); + mkdir($cp . '/upload/announcements', $perm); + @copy($cpt, $cp . '/upload/announcements/index.html'); + mkdir($cp . '/upload/announcements/images', $perm); + @copy($cpt, $cp . '/upload/announcements/images/index.html'); + + //Oral expression question type + mkdir($cp . '/exercises', $perm); + @copy($cpt, $cp . '/exercises/index.html'); + + // Create .htaccess in the dropbox directory. + $fp = fopen($cp . '/dropbox/.htaccess', 'w'); + fwrite( + $fp, + "AuthName AllowLocalAccess + AuthType Basic + + order deny,allow + deny from all + + php_flag zlib.output_compression off" + ); + fclose($fp); + + // Build index.php of the course. + $fd = fopen($cp . '/index.php', 'w'); + + // str_replace() removes \r that cause squares to appear at the end of each line + //@todo fix the harcoded include + $string = str_replace( + "\r", + "", + "" + ); + fwrite($fd, $string); + @chmod($cp . '/index.php', $perm_file); + return 0; + } -/** - * Executed only before create_course_tables() - * @return void - * @assert (null) === null - */ -function drop_course_tables() { - $list = get_course_tables(); - foreach ($list as $table) { - $sql = "DROP TABLE IF EXISTS ".DB_COURSE_PREFIX.$table; - Database::query($sql); + /** + * Gets an array with all the course tables (deprecated?) + * @return array + * @assert (null) !== null + */ + public static function get_course_tables() + { + $tables = array(); + + $tables[] = 'tool'; + $tables[] = 'tool_intro'; + $tables[] = 'group_info'; + $tables[] = 'group_category'; + $tables[] = 'group_rel_user'; + $tables[] = 'group_rel_tutor'; + $tables[] = 'item_property'; + $tables[] = 'userinfo_content'; + $tables[] = 'userinfo_def'; + $tables[] = 'course_description'; + $tables[] = 'calendar_event'; + $tables[] = 'calendar_event_repeat'; + $tables[] = 'calendar_event_repeat_not'; + $tables[] = 'calendar_event_attachment'; + $tables[] = 'announcement'; + $tables[] = 'announcement_attachment'; + $tables[] = 'resource'; + $tables[] = 'student_publication'; + $tables[] = 'student_publication_assignment'; + $tables[] = 'document'; + $tables[] = 'forum_category'; + $tables[] = 'forum_forum'; + $tables[] = 'forum_thread'; + $tables[] = 'forum_post'; + $tables[] = 'forum_mailcue'; + $tables[] = 'forum_attachment'; + $tables[] = 'forum_notification'; + $tables[] = 'forum_thread_qualify'; + $tables[] = 'forum_thread_qualify_log'; + $tables[] = 'link'; + $tables[] = 'link_category'; + $tables[] = 'online_connected'; + $tables[] = 'online_link'; + $tables[] = 'chat_connected'; + $tables[] = 'quiz'; + $tables[] = 'quiz_rel_question'; + $tables[] = 'quiz_question'; + $tables[] = 'quiz_answer'; + $tables[] = 'quiz_question_option'; + $tables[] = 'quiz_question_category'; + $tables[] = 'quiz_question_rel_category'; + $tables[] = 'dropbox_post'; + $tables[] = 'dropbox_file'; + $tables[] = 'dropbox_person'; + $tables[] = 'dropbox_category'; + $tables[] = 'dropbox_feedback'; + $tables[] = 'lp'; + $tables[] = 'lp_item'; + $tables[] = 'lp_view'; + $tables[] = 'lp_item_view'; + $tables[] = 'lp_iv_interaction'; + $tables[] = 'lp_iv_objective'; + $tables[] = 'blog'; + $tables[] = 'blog_comment'; + $tables[] = 'blog_post'; + $tables[] = 'blog_rating'; + $tables[] = 'blog_rel_user'; + $tables[] = 'blog_task'; + $tables[] = 'blog_task_rel_user'; + $tables[] = 'blog_attachment'; + $tables[] = 'permission_group'; + $tables[] = 'permission_user'; + $tables[] = 'permission_task'; + $tables[] = 'role'; + $tables[] = 'role_group'; + $tables[] = 'role_permissions'; + $tables[] = 'role_user'; + $tables[] = 'survey'; + $tables[] = 'survey_question'; + $tables[] = 'survey_question_option'; + $tables[] = 'survey_invitation'; + $tables[] = 'survey_answer'; + $tables[] = 'survey_group'; + $tables[] = 'wiki'; + $tables[] = 'wiki_conf'; + $tables[] = 'wiki_discuss'; + $tables[] = 'wiki_mailcue'; + $tables[] = 'course_setting'; + $tables[] = 'glossary'; + $tables[] = 'notebook'; + $tables[] = 'attendance'; + $tables[] = 'attendance_sheet'; + $tables[] = 'attendance_calendar'; + $tables[] = 'attendance_result'; + $tables[] = 'attendance_sheet_log'; + $tables[] = 'thematic'; + $tables[] = 'thematic_plan'; + $tables[] = 'thematic_advance'; + $tables[] = 'metadata'; + + return $tables; } -} -/** - * Creates all the necessary tables for a new course (deprecated since 1.9.0 as - * we only use a single database, configured at install time) - * @param string Course DB name - * @return int 0 - * @assert (null) === false - */ -function create_course_tables($course_db_name = null) { - global $_configuration; - $charset_clause = ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci'; - $use_one_db = true; - - if ($use_one_db) { - $course_db_name = DB_COURSE_PREFIX; - } else { - if (!$_configuration['single_database']) { - Database::query("CREATE DATABASE IF NOT EXISTS " . $course_db_name . "" . $charset_clause); + /** + * Executed only before create_course_tables() + * @return void + * @assert (null) === null + */ + public static function drop_course_tables() + { + $list = self::get_course_tables(); + foreach ($list as $table) { + $sql = "DROP TABLE IF EXISTS " . DB_COURSE_PREFIX . $table; + Database::query($sql); } - $course_db_name = $_configuration['table_prefix'].$course_db_name.$_configuration['db_glue']; } - //@todo define the backticks inside those table names directly (instead of adding them afterwards) - $tbl_course_homepage = $course_db_name . 'tool'; - $TABLEINTROS = $course_db_name . 'tool_intro'; - $TABLEGROUPS = $course_db_name . 'group_info'; - $TABLEGROUPCATEGORIES = $course_db_name . 'group_category'; - $TABLEGROUPUSER = $course_db_name . 'group_rel_user'; - $TABLEGROUPTUTOR = $course_db_name . 'group_rel_tutor'; - $TABLEITEMPROPERTY = $course_db_name . 'item_property'; - $TABLETOOLUSERINFOCONTENT = $course_db_name . 'userinfo_content'; - $TABLETOOLUSERINFODEF = $course_db_name . 'userinfo_def'; - $TABLETOOLCOURSEDESC = $course_db_name . 'course_description'; - $TABLETOOLAGENDA = $course_db_name . 'calendar_event'; - $TABLETOOLAGENDAREPEAT = $course_db_name . 'calendar_event_repeat'; - $TABLETOOLAGENDAREPEATNOT = $course_db_name . 'calendar_event_repeat_not'; - $TABLETOOLAGENDAATTACHMENT = $course_db_name . 'calendar_event_attachment'; - - // Announcements - $TABLETOOLANNOUNCEMENTS = $course_db_name . 'announcement'; - $TABLETOOLANNOUNCEMENTSATTACHMENT = $course_db_name . 'announcement_attachment'; - - // Resourcelinker - $TABLEADDEDRESOURCES = $course_db_name . 'resource'; - - // Student Publication - $TABLETOOLWORKS = $course_db_name . 'student_publication'; - $TABLETOOLWORKSASS = $course_db_name . 'student_publication_assignment'; - - // Document - $TABLETOOLDOCUMENT = $course_db_name . 'document'; - - // Forum - $TABLETOOLFORUMCATEGORY = $course_db_name . 'forum_category'; - $TABLETOOLFORUM = $course_db_name . 'forum_forum'; - $TABLETOOLFORUMTHREAD = $course_db_name . 'forum_thread'; - $TABLETOOLFORUMPOST = $course_db_name . 'forum_post'; - $TABLETOOLFORUMMAILCUE = $course_db_name . 'forum_mailcue'; - $TABLETOOLFORUMATTACHMENT = $course_db_name . 'forum_attachment'; - $TABLETOOLFORUMNOTIFICATION = $course_db_name . 'forum_notification'; - $TABLETOOLFORUMQUALIFY = $course_db_name . 'forum_thread_qualify'; - $TABLETOOLFORUMQUALIFYLOG = $course_db_name . 'forum_thread_qualify_log'; - - // Link - $TABLETOOLLINK = $course_db_name . 'link'; - $TABLETOOLLINKCATEGORIES = $course_db_name . 'link_category'; - - $TABLETOOLONLINECONNECTED = $course_db_name . 'online_connected'; - $TABLETOOLONLINELINK = $course_db_name . 'online_link'; - - // Chat - $TABLETOOLCHATCONNECTED = $course_db_name . 'chat_connected'; - - // Quiz (a.k.a. exercises) - $TABLEQUIZ = $course_db_name . 'quiz'; - $TABLEQUIZQUESTION = $course_db_name . 'quiz_rel_question'; - $TABLEQUIZQUESTIONLIST = $course_db_name . 'quiz_question'; - $TABLEQUIZANSWERSLIST = $course_db_name . 'quiz_answer'; - $TABLEQUIZQUESTIONOPTION = $course_db_name . 'quiz_question_option'; - $table_quiz_question_category = $course_db_name . 'quiz_question_category'; - $table_quiz_question_rel_category = $course_db_name . 'quiz_question_rel_category'; - - // Dropbox - $TABLETOOLDROPBOXPOST = $course_db_name . 'dropbox_post'; - $TABLETOOLDROPBOXFILE = $course_db_name . 'dropbox_file'; - $TABLETOOLDROPBOXPERSON = $course_db_name . 'dropbox_person'; - $TABLETOOLDROPBOXCATEGORY = $course_db_name . 'dropbox_category'; - $TABLETOOLDROPBOXFEEDBACK = $course_db_name . 'dropbox_feedback'; - - // New Learning path - $TABLELP = $course_db_name . 'lp'; - $TABLELPITEM = $course_db_name . 'lp_item'; - $TABLELPVIEW = $course_db_name . 'lp_view'; - $TABLELPITEMVIEW = $course_db_name . 'lp_item_view'; - $TABLELPIVINTERACTION = $course_db_name . 'lp_iv_interaction'; - $TABLELPIVOBJECTIVE = $course_db_name . 'lp_iv_objective'; - - // Blogs - $tbl_blogs = $course_db_name . 'blog'; - $tbl_blogs_comments = $course_db_name . 'blog_comment'; - $tbl_blogs_posts = $course_db_name . 'blog_post'; - $tbl_blogs_rating = $course_db_name . 'blog_rating'; - $tbl_blogs_rel_user = $course_db_name . 'blog_rel_user'; - $tbl_blogs_tasks = $course_db_name . 'blog_task'; - $tbl_blogs_tasks_rel_user = $course_db_name . 'blog_task_rel_user'; - $tbl_blogs_attachment = $course_db_name . 'blog_attachment'; - - //Blogs permissions - $tbl_permission_group = $course_db_name . 'permission_group'; - $tbl_permission_user = $course_db_name . 'permission_user'; - $tbl_permission_task = $course_db_name . 'permission_task'; - - //Blog roles - $tbl_role = $course_db_name . 'role'; - $tbl_role_group = $course_db_name . 'role_group'; - $tbl_role_permissions = $course_db_name . 'role_permissions'; - $tbl_role_user = $course_db_name . 'role_user'; - - //Survey variables for course homepage; - $TABLESURVEY = $course_db_name . 'survey'; - $TABLESURVEYQUESTION = $course_db_name . 'survey_question'; - $TABLESURVEYQUESTIONOPTION = $course_db_name . 'survey_question_option'; - $TABLESURVEYINVITATION = $course_db_name . 'survey_invitation'; - $TABLESURVEYANSWER = $course_db_name . 'survey_answer'; - $TABLESURVEYGROUP = $course_db_name . 'survey_group'; - - // Wiki - $TABLETOOLWIKI = $course_db_name . 'wiki'; - $TABLEWIKICONF = $course_db_name . 'wiki_conf'; - $TABLEWIKIDISCUSS = $course_db_name . 'wiki_discuss'; - $TABLEWIKIMAILCUE = $course_db_name . 'wiki_mailcue'; - - // Course settings - $TABLESETTING = $course_db_name . 'course_setting'; - - // Glossary - $TBL_GLOSSARY = $course_db_name . 'glossary'; - - // Notebook - $TBL_NOTEBOOK = $course_db_name . 'notebook'; - - // Attendance - $TBL_ATTENDANCE = $course_db_name . 'attendance'; - $TBL_ATTENDANCE_SHEET = $course_db_name . 'attendance_sheet'; - $TBL_ATTENDANCE_CALENDAR = $course_db_name . 'attendance_calendar'; - $TBL_ATTENDANCE_RESULT = $course_db_name . 'attendance_result'; - $TBL_ATTENDANCE_SHEET_LOG = $course_db_name . 'attendance_sheet_log'; - - // Thematic - $TBL_THEMATIC = $course_db_name . 'thematic'; - $TBL_THEMATIC_PLAN = $course_db_name . 'thematic_plan'; - $TBL_THEMATIC_ADVANCE = $course_db_name . 'thematic_advance'; - $TBL_METADATA = $course_db_name . 'metadata'; - - $add_to_all_tables = ' c_id INT NOT NULL, '; - - - /* Announcement tool */ - - $sql = " - CREATE TABLE `".$TABLETOOLANNOUNCEMENTS . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - title text, - content mediumtext, - end_date date default NULL, - display_order mediumint NOT NULL default 0, - email_sent tinyint default 0, - session_id int default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLANNOUNCEMENTS . "` ADD INDEX ( session_id ) "; - Database::query($sql); + /** + * Creates all the necessary tables for a new course (deprecated since 1.9.0 as + * we only use a single database, configured at install time) + * @param string Course DB name + * @return int 0 + * @assert (null) === false + */ + public static function create_course_tables($course_db_name = null) + { + global $_configuration; + $charset_clause = ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci'; + $use_one_db = true; + + if ($use_one_db) { + $course_db_name = DB_COURSE_PREFIX; + } else { + if (!$_configuration['single_database']) { + Database::query( + "CREATE DATABASE IF NOT EXISTS " . $course_db_name . "" . $charset_clause + ); + } + $course_db_name = $_configuration['table_prefix'] . $course_db_name . $_configuration['db_glue']; + } - // Announcement Attachment - $sql = "CREATE TABLE `".$TABLETOOLANNOUNCEMENTSATTACHMENT."` ( + //@todo define the backticks inside those table names directly (instead of adding them afterwards) + $tbl_course_homepage = $course_db_name . 'tool'; + $TABLEINTROS = $course_db_name . 'tool_intro'; + $TABLEGROUPS = $course_db_name . 'group_info'; + $TABLEGROUPCATEGORIES = $course_db_name . 'group_category'; + $TABLEGROUPUSER = $course_db_name . 'group_rel_user'; + $TABLEGROUPTUTOR = $course_db_name . 'group_rel_tutor'; + $TABLEITEMPROPERTY = $course_db_name . 'item_property'; + $TABLETOOLUSERINFOCONTENT = $course_db_name . 'userinfo_content'; + $TABLETOOLUSERINFODEF = $course_db_name . 'userinfo_def'; + $TABLETOOLCOURSEDESC = $course_db_name . 'course_description'; + $TABLETOOLAGENDA = $course_db_name . 'calendar_event'; + $TABLETOOLAGENDAREPEAT = $course_db_name . 'calendar_event_repeat'; + $TABLETOOLAGENDAREPEATNOT = $course_db_name . 'calendar_event_repeat_not'; + $TABLETOOLAGENDAATTACHMENT = $course_db_name . 'calendar_event_attachment'; + + // Announcements + $TABLETOOLANNOUNCEMENTS = $course_db_name . 'announcement'; + $TABLETOOLANNOUNCEMENTSATTACHMENT = $course_db_name . 'announcement_attachment'; + + // Resourcelinker + $TABLEADDEDRESOURCES = $course_db_name . 'resource'; + + // Student Publication + $TABLETOOLWORKS = $course_db_name . 'student_publication'; + $TABLETOOLWORKSASS = $course_db_name . 'student_publication_assignment'; + + // Document + $TABLETOOLDOCUMENT = $course_db_name . 'document'; + + // Forum + $TABLETOOLFORUMCATEGORY = $course_db_name . 'forum_category'; + $TABLETOOLFORUM = $course_db_name . 'forum_forum'; + $TABLETOOLFORUMTHREAD = $course_db_name . 'forum_thread'; + $TABLETOOLFORUMPOST = $course_db_name . 'forum_post'; + $TABLETOOLFORUMMAILCUE = $course_db_name . 'forum_mailcue'; + $TABLETOOLFORUMATTACHMENT = $course_db_name . 'forum_attachment'; + $TABLETOOLFORUMNOTIFICATION = $course_db_name . 'forum_notification'; + $TABLETOOLFORUMQUALIFY = $course_db_name . 'forum_thread_qualify'; + $TABLETOOLFORUMQUALIFYLOG = $course_db_name . 'forum_thread_qualify_log'; + + // Link + $TABLETOOLLINK = $course_db_name . 'link'; + $TABLETOOLLINKCATEGORIES = $course_db_name . 'link_category'; + + $TABLETOOLONLINECONNECTED = $course_db_name . 'online_connected'; + $TABLETOOLONLINELINK = $course_db_name . 'online_link'; + + // Chat + $TABLETOOLCHATCONNECTED = $course_db_name . 'chat_connected'; + + // Quiz (a.k.a. exercises) + $TABLEQUIZ = $course_db_name . 'quiz'; + $TABLEQUIZQUESTION = $course_db_name . 'quiz_rel_question'; + $TABLEQUIZQUESTIONLIST = $course_db_name . 'quiz_question'; + $TABLEQUIZANSWERSLIST = $course_db_name . 'quiz_answer'; + $TABLEQUIZQUESTIONOPTION = $course_db_name . 'quiz_question_option'; + $table_quiz_question_category = $course_db_name . 'quiz_question_category'; + $table_quiz_question_rel_category = $course_db_name . 'quiz_question_rel_category'; + + // Dropbox + $TABLETOOLDROPBOXPOST = $course_db_name . 'dropbox_post'; + $TABLETOOLDROPBOXFILE = $course_db_name . 'dropbox_file'; + $TABLETOOLDROPBOXPERSON = $course_db_name . 'dropbox_person'; + $TABLETOOLDROPBOXCATEGORY = $course_db_name . 'dropbox_category'; + $TABLETOOLDROPBOXFEEDBACK = $course_db_name . 'dropbox_feedback'; + + // New Learning path + $TABLELP = $course_db_name . 'lp'; + $TABLELPITEM = $course_db_name . 'lp_item'; + $TABLELPVIEW = $course_db_name . 'lp_view'; + $TABLELPITEMVIEW = $course_db_name . 'lp_item_view'; + $TABLELPIVINTERACTION = $course_db_name . 'lp_iv_interaction'; + $TABLELPIVOBJECTIVE = $course_db_name . 'lp_iv_objective'; + + // Blogs + $tbl_blogs = $course_db_name . 'blog'; + $tbl_blogs_comments = $course_db_name . 'blog_comment'; + $tbl_blogs_posts = $course_db_name . 'blog_post'; + $tbl_blogs_rating = $course_db_name . 'blog_rating'; + $tbl_blogs_rel_user = $course_db_name . 'blog_rel_user'; + $tbl_blogs_tasks = $course_db_name . 'blog_task'; + $tbl_blogs_tasks_rel_user = $course_db_name . 'blog_task_rel_user'; + $tbl_blogs_attachment = $course_db_name . 'blog_attachment'; + + //Blogs permissions + $tbl_permission_group = $course_db_name . 'permission_group'; + $tbl_permission_user = $course_db_name . 'permission_user'; + $tbl_permission_task = $course_db_name . 'permission_task'; + + //Blog roles + $tbl_role = $course_db_name . 'role'; + $tbl_role_group = $course_db_name . 'role_group'; + $tbl_role_permissions = $course_db_name . 'role_permissions'; + $tbl_role_user = $course_db_name . 'role_user'; + + //Survey variables for course homepage; + $TABLESURVEY = $course_db_name . 'survey'; + $TABLESURVEYQUESTION = $course_db_name . 'survey_question'; + $TABLESURVEYQUESTIONOPTION = $course_db_name . 'survey_question_option'; + $TABLESURVEYINVITATION = $course_db_name . 'survey_invitation'; + $TABLESURVEYANSWER = $course_db_name . 'survey_answer'; + $TABLESURVEYGROUP = $course_db_name . 'survey_group'; + + // Wiki + $TABLETOOLWIKI = $course_db_name . 'wiki'; + $TABLEWIKICONF = $course_db_name . 'wiki_conf'; + $TABLEWIKIDISCUSS = $course_db_name . 'wiki_discuss'; + $TABLEWIKIMAILCUE = $course_db_name . 'wiki_mailcue'; + + // Course settings + $TABLESETTING = $course_db_name . 'course_setting'; + + // Glossary + $TBL_GLOSSARY = $course_db_name . 'glossary'; + + // Notebook + $TBL_NOTEBOOK = $course_db_name . 'notebook'; + + // Attendance + $TBL_ATTENDANCE = $course_db_name . 'attendance'; + $TBL_ATTENDANCE_SHEET = $course_db_name . 'attendance_sheet'; + $TBL_ATTENDANCE_CALENDAR = $course_db_name . 'attendance_calendar'; + $TBL_ATTENDANCE_RESULT = $course_db_name . 'attendance_result'; + $TBL_ATTENDANCE_SHEET_LOG = $course_db_name . 'attendance_sheet_log'; + + // Thematic + $TBL_THEMATIC = $course_db_name . 'thematic'; + $TBL_THEMATIC_PLAN = $course_db_name . 'thematic_plan'; + $TBL_THEMATIC_ADVANCE = $course_db_name . 'thematic_advance'; + $TBL_METADATA = $course_db_name . 'metadata'; + + $add_to_all_tables = ' c_id INT NOT NULL, '; + + + /* Announcement tool */ + + $sql = " + CREATE TABLE `" . $TABLETOOLANNOUNCEMENTS . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - path varchar(255) NOT NULL, - comment text, - size int NOT NULL default 0, - announcement_id int NOT NULL, - filename varchar(255) NOT NULL, + id int unsigned NOT NULL auto_increment, + title text, + content mediumtext, + end_date date default NULL, + display_order mediumint NOT NULL default 0, + email_sent tinyint default 0, + session_id int default 0, PRIMARY KEY (c_id, id) )" . $charset_clause; - Database::query($sql); - - /* - Resources - */ - - $sql = " - CREATE TABLE `".$TABLEADDEDRESOURCES . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - source_type varchar(50) default NULL, - source_id int unsigned default NULL, - resource_type varchar(50) default NULL, - resource_id int unsigned default NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLUSERINFOCONTENT . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - user_id int unsigned NOT NULL, - definition_id int unsigned NOT NULL, - editor_ip varchar(39) default NULL, - edition_time datetime default NULL, - content text NOT NULL, - PRIMARY KEY (c_id, id), - KEY user_id (user_id) - )" . $charset_clause; - Database::query($sql); - - // Unused table. Temporarily ignored for tests. - // Reused because of user/userInfo and user/userInfoLib scripts - $sql = " - CREATE TABLE `".$TABLETOOLUSERINFODEF . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - title varchar(80) NOT NULL default '', - comment text, - line_count tinyint unsigned NOT NULL default 5, - rank tinyint unsigned NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - /* Forum tool */ - - // Forum Category - $sql = " - CREATE TABLE `".$TABLETOOLFORUMCATEGORY . "` ( - $add_to_all_tables - cat_id int NOT NULL auto_increment, - cat_title varchar(255) NOT NULL default '', - cat_comment text, - cat_order int NOT NULL default 0, - locked int NOT NULL default 0, - session_id int unsigned NOT NULL default 0, - PRIMARY KEY (c_id, cat_id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLFORUMCATEGORY . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - // Forum - $sql = " - CREATE TABLE `".$TABLETOOLFORUM . "` ( - $add_to_all_tables - forum_id int NOT NULL auto_increment, - forum_title varchar(255) NOT NULL default '', - forum_comment text, - forum_threads int default 0, - forum_posts int default 0, - forum_last_post int default 0, - forum_category int default NULL, - allow_anonymous int default NULL, - allow_edit int default NULL, - approval_direct_post varchar(20) default NULL, - allow_attachments int default NULL, - allow_new_threads int default NULL, - default_view varchar(20) default NULL, - forum_of_group varchar(20) default NULL, - forum_group_public_private varchar(20) default 'public', - forum_order int default NULL, - locked int NOT NULL default 0, - session_id int NOT NULL default 0, - forum_image varchar(255) NOT NULL default '', - start_time datetime NOT NULL default '0000-00-00 00:00:00', - end_time datetime NOT NULL default '0000-00-00 00:00:00', - PRIMARY KEY (c_id, forum_id) - )" . $charset_clause; - Database::query($sql); - - // Forum Threads - $sql = " - CREATE TABLE `".$TABLETOOLFORUMTHREAD . "` ( - $add_to_all_tables - thread_id int NOT NULL auto_increment, - thread_title varchar(255) default NULL, - forum_id int default NULL, - thread_replies int default 0, - thread_poster_id int default NULL, - thread_poster_name varchar(100) default '', - thread_views int default 0, - thread_last_post int default NULL, - thread_date datetime default '0000-00-00 00:00:00', - thread_sticky tinyint unsigned default 0, - locked int NOT NULL default 0, - session_id int unsigned default NULL, - thread_title_qualify varchar(255) default '', - thread_qualify_max float(6,2) UNSIGNED NOT NULL default 0, - thread_close_date datetime default '0000-00-00 00:00:00', - thread_weight float(6,2) UNSIGNED NOT NULL default 0, - PRIMARY KEY (c_id, thread_id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLFORUMTHREAD . "` ADD INDEX idx_forum_thread_forum_id (forum_id)"; - Database::query($sql); - - // Forum Posts - $sql = " - CREATE TABLE `".$TABLETOOLFORUMPOST . "` ( - $add_to_all_tables - post_id int NOT NULL auto_increment, - post_title varchar(250) default NULL, - post_text text, - thread_id int default 0, - forum_id int default 0, - poster_id int default 0, - poster_name varchar(100) default '', - post_date datetime default '0000-00-00 00:00:00', - post_notification tinyint default 0, - post_parent_id int default 0, - visible tinyint default 1, - PRIMARY KEY (c_id, post_id), - KEY poster_id (poster_id), - KEY forum_id (forum_id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLFORUMPOST . "` ADD INDEX idx_forum_post_thread_id (thread_id)"; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLFORUMPOST . "` ADD INDEX idx_forum_post_visible (visible)"; - Database::query($sql); - - // Forum Mailcue - $sql = " - CREATE TABLE `".$TABLETOOLFORUMMAILCUE."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - user_id int default NULL, - thread_id int default NULL, - post_id int default NULL, - PRIMARY KEY (id, c_id, thread_id, user_id, post_id ) - )" . $charset_clause; - Database::query($sql); + Database::query($sql); - // Forum Attachment - $sql = "CREATE TABLE `".$TABLETOOLFORUMATTACHMENT."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - path varchar(255) NOT NULL, - comment text, - size int NOT NULL default 0, - post_id int NOT NULL, - filename varchar(255) NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLANNOUNCEMENTS . "` ADD INDEX ( session_id ) "; + Database::query($sql); - // Forum notification - $sql = "CREATE TABLE `".$TABLETOOLFORUMNOTIFICATION."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - user_id int, - forum_id int, - thread_id int, - post_id int, - KEY user_id (user_id), - KEY forum_id (forum_id), - PRIMARY KEY (id, c_id, user_id, forum_id, thread_id, post_id ) + // Announcement Attachment + $sql = "CREATE TABLE `" . $TABLETOOLANNOUNCEMENTSATTACHMENT . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + path varchar(255) NOT NULL, + comment text, + size int NOT NULL default 0, + announcement_id int NOT NULL, + filename varchar(255) NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + + /* + Resources + */ + + $sql = " + CREATE TABLE `" . $TABLEADDEDRESOURCES . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + source_type varchar(50) default NULL, + source_id int unsigned default NULL, + resource_type varchar(50) default NULL, + resource_id int unsigned default NULL, + PRIMARY KEY (c_id, id) )" . $charset_clause; - Database::query($sql); + Database::query($sql); - // Forum thread qualify :Add table forum_thread_qualify - $sql = "CREATE TABLE `".$TABLETOOLFORUMQUALIFY."` ( + $sql = " + CREATE TABLE `" . $TABLETOOLUSERINFOCONTENT . "` ( $add_to_all_tables - id int unsigned AUTO_INCREMENT, + id int unsigned NOT NULL auto_increment, user_id int unsigned NOT NULL, - thread_id int NOT NULL, - qualify float(6,2) NOT NULL default 0, - qualify_user_id int default NULL, - qualify_time datetime default '0000-00-00 00:00:00', - session_id int default NULL, + definition_id int unsigned NOT NULL, + editor_ip varchar(39) default NULL, + edition_time datetime default NULL, + content text NOT NULL, + PRIMARY KEY (c_id, id), + KEY user_id (user_id) + )" . $charset_clause; + Database::query($sql); + + // Unused table. Temporarily ignored for tests. + // Reused because of user/userInfo and user/userInfoLib scripts + $sql = " + CREATE TABLE `" . $TABLETOOLUSERINFODEF . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + title varchar(80) NOT NULL default '', + comment text, + line_count tinyint unsigned NOT NULL default 5, + rank tinyint unsigned NOT NULL default 0, PRIMARY KEY (c_id, id) )" . $charset_clause; - Database::query($sql); + Database::query($sql); + + /* Forum tool */ + + // Forum Category + $sql = " + CREATE TABLE `" . $TABLETOOLFORUMCATEGORY . "` ( + $add_to_all_tables + cat_id int NOT NULL auto_increment, + cat_title varchar(255) NOT NULL default '', + cat_comment text, + cat_order int NOT NULL default 0, + locked int NOT NULL default 0, + session_id int unsigned NOT NULL default 0, + PRIMARY KEY (c_id, cat_id) + )" . $charset_clause; + Database::query($sql); - $sql = "ALTER TABLE `".$TABLETOOLFORUMQUALIFY . "` ADD INDEX (user_id, thread_id)"; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLFORUMCATEGORY . "` ADD INDEX ( session_id ) "; + Database::query($sql); - //Forum thread qualify: Add table forum_thread_qualify_historical - $sql = "CREATE TABLE `".$TABLETOOLFORUMQUALIFYLOG."` ( + // Forum + $sql = " + CREATE TABLE `" . $TABLETOOLFORUM . "` ( $add_to_all_tables - id int unsigned AUTO_INCREMENT, - user_id int unsigned NOT NULL, - thread_id int NOT NULL, - qualify float(6,2) NOT NULL default 0, - qualify_user_id int default NULL, - qualify_time datetime default '0000-00-00 00:00:00', - session_id int default NULL, - PRIMARY KEY (c_id, id) + forum_id int NOT NULL auto_increment, + forum_title varchar(255) NOT NULL default '', + forum_comment text, + forum_threads int default 0, + forum_posts int default 0, + forum_last_post int default 0, + forum_category int default NULL, + allow_anonymous int default NULL, + allow_edit int default NULL, + approval_direct_post varchar(20) default NULL, + allow_attachments int default NULL, + allow_new_threads int default NULL, + default_view varchar(20) default NULL, + forum_of_group varchar(20) default NULL, + forum_group_public_private varchar(20) default 'public', + forum_order int default NULL, + locked int NOT NULL default 0, + session_id int NOT NULL default 0, + forum_image varchar(255) NOT NULL default '', + start_time datetime NOT NULL default '0000-00-00 00:00:00', + end_time datetime NOT NULL default '0000-00-00 00:00:00', + PRIMARY KEY (c_id, forum_id) )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLFORUMQUALIFYLOG. "` ADD INDEX (user_id, thread_id)"; - Database::query($sql); - - /* - * Exercise tool - */ - - // Exercise tool - Tests/exercises - $sql = "CREATE TABLE `".$TABLEQUIZ . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - title varchar(255) NOT NULL, - description text default NULL, - sound varchar(255) default NULL, - type tinyint unsigned NOT NULL default 1, - random int NOT NULL default 0, - random_answers tinyint unsigned NOT NULL default 0, - active tinyint NOT NULL default 0, - results_disabled INT UNSIGNED NOT NULL DEFAULT 0, - access_condition TEXT DEFAULT NULL, - max_attempt int NOT NULL default 0, - start_time datetime NOT NULL default '0000-00-00 00:00:00', - end_time datetime NOT NULL default '0000-00-00 00:00:00', - feedback_type int NOT NULL default 0, - expired_time int NOT NULL default '0', - session_id int default 0, - propagate_neg INT NOT NULL DEFAULT 0, - review_answers INT NOT NULL DEFAULT 0, - random_by_category INT NOT NULL DEFAULT 0, - text_when_finished TEXT default NULL, - display_category_name INT NOT NULL DEFAULT 1, - pass_percentage INT DEFAULT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLEQUIZ . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - // Exercise tool - questions - $sql = " - CREATE TABLE `".$TABLEQUIZQUESTIONLIST . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - question TEXT NOT NULL, - description text default NULL, - ponderation float(6,2) NOT NULL default 0, - position mediumint unsigned NOT NULL default 1, - type tinyint unsigned NOT NULL default 2, - picture varchar(50) default NULL, - level int unsigned NOT NULL default 0, - extra varchar(255) default NULL, - question_code char(10) default '', - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLEQUIZQUESTIONLIST . "` ADD INDEX (position)"; - Database::query($sql); - - // Exercise tool - answers - $sql = " - CREATE TABLE `".$TABLEQUIZANSWERSLIST . "` ( - $add_to_all_tables - id int unsigned NOT NULL, - id_auto int NOT NULL AUTO_INCREMENT, - question_id int unsigned NOT NULL, - answer text NOT NULL, - correct mediumint unsigned default NULL, - comment text default NULL, - ponderation float(6,2) NOT NULL default 0, - position mediumint unsigned NOT NULL default 1, - hotspot_coordinates text, - hotspot_type enum('square','circle','poly','delineation','oar') default NULL, - destination text NOT NULL, - answer_code char(10) default '', - PRIMARY KEY (c_id, id_auto) - )" . $charset_clause; - Database::query($sql); - - // Exercise tool - answer options - $sql = " - CREATE TABLE `".$TABLEQUIZQUESTIONOPTION . "` ( - $add_to_all_tables - id int NOT NULL auto_increment, - question_id int NOT NULL, - name varchar(255), - position int unsigned NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); + Database::query($sql); + // Forum Threads + $sql = " + CREATE TABLE `" . $TABLETOOLFORUMTHREAD . "` ( + $add_to_all_tables + thread_id int NOT NULL auto_increment, + thread_title varchar(255) default NULL, + forum_id int default NULL, + thread_replies int default 0, + thread_poster_id int default NULL, + thread_poster_name varchar(100) default '', + thread_views int default 0, + thread_last_post int default NULL, + thread_date datetime default '0000-00-00 00:00:00', + thread_sticky tinyint unsigned default 0, + locked int NOT NULL default 0, + session_id int unsigned default NULL, + thread_title_qualify varchar(255) default '', + thread_qualify_max float(6,2) UNSIGNED NOT NULL default 0, + thread_close_date datetime default '0000-00-00 00:00:00', + thread_weight float(6,2) UNSIGNED NOT NULL default 0, + PRIMARY KEY (c_id, thread_id) + )" . $charset_clause; + Database::query($sql); - // Exercise tool - Test/question relations - $sql = " - CREATE TABLE `".$TABLEQUIZQUESTION . "` ( - $add_to_all_tables - question_id int unsigned NOT NULL, - exercice_id int unsigned NOT NULL, - question_order int unsigned NOT NULL default 1, - PRIMARY KEY (c_id, question_id,exercice_id) - )" . $charset_clause; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLFORUMTHREAD . "` ADD INDEX idx_forum_thread_forum_id (forum_id)"; + Database::query($sql); + // Forum Posts + $sql = " + CREATE TABLE `" . $TABLETOOLFORUMPOST . "` ( + $add_to_all_tables + post_id int NOT NULL auto_increment, + post_title varchar(250) default NULL, + post_text text, + thread_id int default 0, + forum_id int default 0, + poster_id int default 0, + poster_name varchar(100) default '', + post_date datetime default '0000-00-00 00:00:00', + post_notification tinyint default 0, + post_parent_id int default 0, + visible tinyint default 1, + PRIMARY KEY (c_id, post_id), + KEY poster_id (poster_id), + KEY forum_id (forum_id) + )" . $charset_clause; + Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLFORUMPOST . "` ADD INDEX idx_forum_post_thread_id (thread_id)"; + Database::query($sql); - $sql = "CREATE TABLE `".$table_quiz_question_category . "` ( - $add_to_all_tables - id int NOT NULL AUTO_INCREMENT, - title varchar(255) NOT NULL, - description text NOT NULL, - PRIMARY KEY (c_id,id) - )" . $charset_clause; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLFORUMPOST . "` ADD INDEX idx_forum_post_visible (visible)"; + Database::query($sql); + // Forum Mailcue + $sql = " + CREATE TABLE `" . $TABLETOOLFORUMMAILCUE . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + user_id int default NULL, + thread_id int default NULL, + post_id int default NULL, + PRIMARY KEY (id, c_id, thread_id, user_id, post_id ) + )" . $charset_clause; + Database::query($sql); - $sql = "CREATE TABLE `".$table_quiz_question_rel_category . "` ( - $add_to_all_tables - question_id int NOT NULL, - category_id int NOT NULL, - PRIMARY KEY (c_id,question_id) - )" . $charset_clause; - Database::query($sql); + // Forum Attachment + $sql = "CREATE TABLE `" . $TABLETOOLFORUMATTACHMENT . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + path varchar(255) NOT NULL, + comment text, + size int NOT NULL default 0, + post_id int NOT NULL, + filename varchar(255) NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + // Forum notification + $sql = "CREATE TABLE `" . $TABLETOOLFORUMNOTIFICATION . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + user_id int, + forum_id int, + thread_id int, + post_id int, + KEY user_id (user_id), + KEY forum_id (forum_id), + PRIMARY KEY (id, c_id, user_id, forum_id, thread_id, post_id ) + )" . $charset_clause; + Database::query($sql); - /* Course description */ + // Forum thread qualify :Add table forum_thread_qualify + $sql = "CREATE TABLE `" . $TABLETOOLFORUMQUALIFY . "` ( + $add_to_all_tables + id int unsigned AUTO_INCREMENT, + user_id int unsigned NOT NULL, + thread_id int NOT NULL, + qualify float(6,2) NOT NULL default 0, + qualify_user_id int default NULL, + qualify_time datetime default '0000-00-00 00:00:00', + session_id int default NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - $sql = " - CREATE TABLE `".$TABLETOOLCOURSEDESC . "` ( - $add_to_all_tables - id int UNSIGNED NOT NULL auto_increment, - title VARCHAR(255), - content TEXT, - session_id int default 0, - description_type tinyint unsigned NOT NULL default 0, - progress INT NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLCOURSEDESC . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - /* Course homepage tool list */ - - $sql = " - CREATE TABLE `" . $tbl_course_homepage . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - name varchar(255) NOT NULL, - link varchar(255) NOT NULL, - image varchar(255) default NULL, - visibility tinyint unsigned default 0, - admin varchar(255) default NULL, - address varchar(255) default NULL, - added_tool tinyint unsigned default 1, - target enum('_self','_blank') NOT NULL default '_self', - category varchar(20) not null default 'authoring', - session_id int default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - $sql = "ALTER TABLE `".$tbl_course_homepage . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - /* Agenda tool */ - - $sql = " - CREATE TABLE `".$TABLETOOLAGENDA . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - title varchar(255) NOT NULL, - content text, - start_date datetime NOT NULL default '0000-00-00 00:00:00', - end_date datetime NOT NULL default '0000-00-00 00:00:00', - parent_event_id INT NULL, - session_id int unsigned NOT NULL default 0, - all_day INT NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLAGENDA . "` ADD INDEX ( session_id ) ;"; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLAGENDAREPEAT. "` ( - $add_to_all_tables - cal_id INT DEFAULT 0 NOT NULL, - cal_type VARCHAR(20), - cal_end INT, - cal_frequency INT DEFAULT 1, - cal_days CHAR(7), - PRIMARY KEY (c_id, cal_id) - )" . $charset_clause; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLAGENDAREPEATNOT."` ( - $add_to_all_tables - cal_id INT NOT NULL, - cal_date INT NOT NULL, - PRIMARY KEY (c_id, cal_id, cal_date ) - )" . $charset_clause; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLFORUMQUALIFY . "` ADD INDEX (user_id, thread_id)"; + Database::query($sql); - // Agenda Attachment - $sql = "CREATE TABLE `".$TABLETOOLAGENDAATTACHMENT."` ( + //Forum thread qualify: Add table forum_thread_qualify_historical + $sql = "CREATE TABLE `" . $TABLETOOLFORUMQUALIFYLOG . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - path varchar(255) NOT NULL, - comment text, - size int NOT NULL default 0, - agenda_id int NOT NULL, - filename varchar(255) NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); + id int unsigned AUTO_INCREMENT, + user_id int unsigned NOT NULL, + thread_id int NOT NULL, + qualify float(6,2) NOT NULL default 0, + qualify_user_id int default NULL, + qualify_time datetime default '0000-00-00 00:00:00', + session_id int default NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + + $sql = "ALTER TABLE `" . $TABLETOOLFORUMQUALIFYLOG . "` ADD INDEX (user_id, thread_id)"; + Database::query($sql); - /* - Document tool - */ + /* + * Exercise tool + */ - $sql = " - CREATE TABLE `".$TABLETOOLDOCUMENT . "` ( + // Exercise tool - Tests/exercises + $sql = "CREATE TABLE `" . $TABLEQUIZ . "` ( $add_to_all_tables id int unsigned NOT NULL auto_increment, - path varchar(255) NOT NULL default '', - comment text, - title varchar(255) default NULL, - filetype set('file','folder') NOT NULL default 'file', - size int NOT NULL default 0, - readonly TINYINT UNSIGNED NOT NULL, - session_id int UNSIGNED NOT NULL default 0, + title varchar(255) NOT NULL, + description text default NULL, + sound varchar(255) default NULL, + type tinyint unsigned NOT NULL default 1, + random int NOT NULL default 0, + random_answers tinyint unsigned NOT NULL default 0, + active tinyint NOT NULL default 0, + results_disabled INT UNSIGNED NOT NULL DEFAULT 0, + access_condition TEXT DEFAULT NULL, + max_attempt int NOT NULL default 0, + start_time datetime NOT NULL default '0000-00-00 00:00:00', + end_time datetime NOT NULL default '0000-00-00 00:00:00', + feedback_type int NOT NULL default 0, + expired_time int NOT NULL default '0', + session_id int default 0, + propagate_neg INT NOT NULL DEFAULT 0, + review_answers INT NOT NULL DEFAULT 0, + random_by_category INT NOT NULL DEFAULT 0, + text_when_finished TEXT default NULL, + display_category_name INT NOT NULL DEFAULT 1, + pass_percentage INT DEFAULT NULL, PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - /* - Student publications - */ - $sql = " - CREATE TABLE `".$TABLETOOLWORKS . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - url varchar(255) default NULL, - title varchar(255) default NULL, - description text default NULL, - author varchar(255) default NULL, - active tinyint default NULL, - accepted tinyint default 0, - post_group_id int DEFAULT 0 NOT NULL, - sent_date datetime NOT NULL default '0000-00-00 00:00:00', - filetype set('file','folder') NOT NULL default 'file', - has_properties int UNSIGNED NOT NULL DEFAULT 0, - view_properties tinyint NULL, - qualification float(6,2) UNSIGNED NOT NULL DEFAULT 0, - date_of_qualification datetime NOT NULL default '0000-00-00 00:00:00', - parent_id INT UNSIGNED NOT NULL DEFAULT 0, - qualificator_id INT UNSIGNED NOT NULL DEFAULT 0, - weight float(6,2) UNSIGNED NOT NULL default 0, - session_id INT UNSIGNED NOT NULL default 0, - user_id INTEGER NOT NULL, - allow_text_assignment INTEGER NOT NULL DEFAULT 0, - contains_file INTEGER NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLWORKSASS."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - expires_on datetime NOT NULL default '0000-00-00 00:00:00', - ends_on datetime NOT NULL default '0000-00-00 00:00:00', - add_to_calendar tinyint NOT NULL, - enable_qualification tinyint NOT NULL, - publication_id int NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLWORKS . "` ADD INDEX ( session_id )" ; - Database::query($sql); - - /* - Links tool - */ - - $sql = " - CREATE TABLE `".$TABLETOOLLINK . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - url TEXT NOT NULL, - title varchar(150) default NULL, - description text, - category_id int unsigned default NULL, - display_order int unsigned NOT NULL default 0, - on_homepage enum('0','1') NOT NULL default '0', - target char(10) default '_self', - session_id int default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLLINK . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLLINKCATEGORIES . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - category_title varchar(255) NOT NULL, - description text, - display_order mediumint unsigned NOT NULL default 0, - session_id int default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLLINKCATEGORIES . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - /* Wiki */ - - $sql = "CREATE TABLE `".$TABLETOOLWIKI . "` ( - $add_to_all_tables - id int NOT NULL auto_increment, - page_id int NOT NULL default 0, - reflink varchar(255) NOT NULL default 'index', - title varchar(255) NOT NULL, - content mediumtext NOT NULL, - user_id int NOT NULL default 0, - group_id int DEFAULT NULL, - dtime datetime NOT NULL default '0000-00-00 00:00:00', - addlock int NOT NULL default 1, - editlock int NOT NULL default 0, - visibility int NOT NULL default 1, - addlock_disc int NOT NULL default 1, - visibility_disc int NOT NULL default 1, - ratinglock_disc int NOT NULL default 1, - assignment int NOT NULL default 0, - comment text NOT NULL, - progress text NOT NULL, - score int NULL default 0, - version int default NULL, - is_editing int NOT NULL default 0, - time_edit datetime NOT NULL default '0000-00-00 00:00:00', - hits int default 0, - linksto text NOT NULL, - tag text NOT NULL, - user_ip varchar(39) NOT NULL, - session_id int default 0, - PRIMARY KEY (c_id, id), - KEY reflink (reflink), - KEY group_id (group_id), - KEY page_id (page_id), - KEY session_id (session_id) - )" . $charset_clause; - Database::query($sql); - - $sql = "CREATE TABLE `".$TABLEWIKICONF . "` ( - $add_to_all_tables - page_id int NOT NULL default 0, - task text NOT NULL, - feedback1 text NOT NULL, - feedback2 text NOT NULL, - feedback3 text NOT NULL, - fprogress1 varchar(3) NOT NULL, - fprogress2 varchar(3) NOT NULL, - fprogress3 varchar(3) NOT NULL, - max_size int default NULL, - max_text int default NULL, - max_version int default NULL, - startdate_assig datetime NOT NULL default '0000-00-00 00:00:00', - enddate_assig datetime NOT NULL default '0000-00-00 00:00:00', - delayedsubmit int NOT NULL default 0, - KEY page_id (page_id), - PRIMARY KEY ( c_id, page_id ) - )" . $charset_clause; - Database::query($sql); - - $sql = "CREATE TABLE `".$TABLEWIKIDISCUSS . "` ( - $add_to_all_tables - id int NOT NULL auto_increment, - publication_id int NOT NULL default 0, - userc_id int NOT NULL default 0, - comment text NOT NULL, - p_score varchar(255) default NULL, - dtime datetime NOT NULL default '0000-00-00 00:00:00', - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = "CREATE TABLE `".$TABLEWIKIMAILCUE . "` ( - $add_to_all_tables - id int NOT NULL, - user_id int NOT NULL, - type text NOT NULL, - group_id int DEFAULT NULL, - session_id int default 0, - KEY (c_id, id), - PRIMARY KEY ( c_id, id, user_id ) - )" . $charset_clause; - Database::query($sql); - - /* - Online - */ - - $sql = " - CREATE TABLE `".$TABLETOOLONLINECONNECTED . "` ( - $add_to_all_tables - user_id int unsigned NOT NULL, - last_connection datetime NOT NULL default '0000-00-00 00:00:00', - PRIMARY KEY (c_id, user_id) - )" . $charset_clause; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLONLINELINK . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - name char(50) NOT NULL default '', - url char(100) NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - Database::query($sql); - - $sql = " - CREATE TABLE `".$TABLETOOLCHATCONNECTED . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - user_id int unsigned NOT NULL default '0', - last_connection datetime NOT NULL default '0000-00-00 00:00:00', - session_id INT NOT NULL default 0, - to_group_id INT NOT NULL default 0, - PRIMARY KEY (c_id, id, user_id, last_connection) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLCHATCONNECTED . "` ADD INDEX char_connected_index(user_id, session_id, to_group_id) "; - Database::query($sql); - - /* - Groups tool - */ - - Database::query("CREATE TABLE `".$TABLEGROUPS . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - name varchar(100) default NULL, - category_id int unsigned NOT NULL default 0, - description text, - max_student int unsigned NOT NULL default 8, - doc_state tinyint unsigned NOT NULL default 1, - calendar_state tinyint unsigned NOT NULL default 0, - work_state tinyint unsigned NOT NULL default 0, - announcements_state tinyint unsigned NOT NULL default 0, - forum_state tinyint unsigned NOT NULL default 0, - wiki_state tinyint unsigned NOT NULL default 1, - chat_state tinyint unsigned NOT NULL default 1, - secret_directory varchar(255) default NULL, - self_registration_allowed tinyint unsigned NOT NULL default '0', - self_unregistration_allowed tinyint unsigned NOT NULL default '0', - session_id int unsigned NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - Database::query("ALTER TABLE `".$TABLEGROUPS . "` ADD INDEX ( session_id )"); - - Database::query("CREATE TABLE `".$TABLEGROUPCATEGORIES . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - title varchar(255) NOT NULL default '', - description text NOT NULL, - doc_state tinyint unsigned NOT NULL default 1, - calendar_state tinyint unsigned NOT NULL default 1, - work_state tinyint unsigned NOT NULL default 1, - announcements_state tinyint unsigned NOT NULL default 1, - forum_state tinyint unsigned NOT NULL default 1, - wiki_state tinyint unsigned NOT NULL default 1, - chat_state tinyint unsigned NOT NULL default 1, - max_student int unsigned NOT NULL default 8, - self_reg_allowed tinyint unsigned NOT NULL default 0, - self_unreg_allowed tinyint unsigned NOT NULL default 0, - groups_per_user int unsigned NOT NULL default 0, - display_order int unsigned NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - Database::query("CREATE TABLE `".$TABLEGROUPUSER . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - user_id int unsigned NOT NULL, - group_id int unsigned NOT NULL default 0, - status int NOT NULL default 0, - role char(50) NOT NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - Database::query("CREATE TABLE `".$TABLEGROUPTUTOR . "` ( - $add_to_all_tables - id int NOT NULL auto_increment, - user_id int NOT NULL, - group_id int NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - Database::query("CREATE TABLE `".$TABLEITEMPROPERTY . "` ( - $add_to_all_tables - id int NOT NULL auto_increment, - tool varchar(100) NOT NULL default '', - insert_user_id int unsigned NOT NULL default '0', - insert_date datetime NOT NULL default '0000-00-00 00:00:00', - lastedit_date datetime NOT NULL default '0000-00-00 00:00:00', - ref int NOT NULL default '0', - lastedit_type varchar(100) NOT NULL default '', - lastedit_user_id int unsigned NOT NULL default '0', - to_group_id int unsigned default NULL, - to_user_id int unsigned default NULL, - visibility tinyint NOT NULL default '1', - start_visible datetime NOT NULL default '0000-00-00 00:00:00', - end_visible datetime NOT NULL default '0000-00-00 00:00:00', - id_session INT NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - Database::query("ALTER TABLE `$TABLEITEMPROPERTY` ADD INDEX idx_item_property_toolref (tool,ref)"); - - /* Tool introductions */ - Database::query(" - CREATE TABLE `".$TABLEINTROS . "` ( - $add_to_all_tables - id varchar(50) NOT NULL, - intro_text MEDIUMTEXT NOT NULL, - session_id INT NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id, session_id) - )" . $charset_clause); - - /* Dropbox tool */ - - Database::query(" - CREATE TABLE `".$TABLETOOLDROPBOXFILE . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - uploader_id int unsigned NOT NULL default 0, - filename varchar(250) NOT NULL default '', - filesize int unsigned NOT NULL, - title varchar(250) default '', - description varchar(250) default '', - author varchar(250) default '', - upload_date datetime NOT NULL default '0000-00-00 00:00:00', - last_upload_date datetime NOT NULL default '0000-00-00 00:00:00', - cat_id int NOT NULL default 0, - session_id int UNSIGNED NOT NULL, - PRIMARY KEY (c_id, id), - UNIQUE KEY UN_filename (filename) - )" . $charset_clause); - - Database::query("ALTER TABLE `$TABLETOOLDROPBOXFILE` ADD INDEX ( session_id )"); - - Database::query(" - CREATE TABLE `".$TABLETOOLDROPBOXPOST . "` ( - $add_to_all_tables - file_id int unsigned NOT NULL, - dest_user_id int unsigned NOT NULL default 0, - feedback_date datetime NOT NULL default '0000-00-00 00:00:00', - feedback text default '', - cat_id int NOT NULL default 0, - session_id int UNSIGNED NOT NULL, - PRIMARY KEY (c_id, file_id, dest_user_id) - )" . $charset_clause); - - Database::query("ALTER TABLE `$TABLETOOLDROPBOXPOST` ADD INDEX ( session_id )"); - - Database::query(" - CREATE TABLE `".$TABLETOOLDROPBOXPERSON . "` ( - $add_to_all_tables - file_id int unsigned NOT NULL, - user_id int unsigned NOT NULL default 0, - PRIMARY KEY (c_id, file_id, user_id) - )" . $charset_clause); - - $sql = "CREATE TABLE `".$TABLETOOLDROPBOXCATEGORY."` ( - $add_to_all_tables - cat_id int NOT NULL auto_increment, - cat_name text NOT NULL, - received tinyint unsigned NOT NULL default 0, - sent tinyint unsigned NOT NULL default 0, - user_id int NOT NULL default 0, - session_id int NOT NULL default 0, - PRIMARY KEY (c_id, cat_id) - )" . $charset_clause; - Database::query($sql); - - $sql = "ALTER TABLE `".$TABLETOOLDROPBOXCATEGORY . "` ADD INDEX ( session_id ) "; - Database::query($sql); - - $sql = "CREATE TABLE `".$TABLETOOLDROPBOXFEEDBACK."` ( - $add_to_all_tables - feedback_id int NOT NULL auto_increment, - file_id int NOT NULL default 0, - author_user_id int NOT NULL default 0, - feedback text NOT NULL, - feedback_date datetime NOT NULL default '0000-00-00 00:00:00', - PRIMARY KEY (c_id, feedback_id), - KEY file_id (file_id), - KEY author_user_id (author_user_id) - )" . $charset_clause; - Database::query($sql); - - /* - New learning path tool - */ - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELP` ( - $add_to_all_tables - " . - "id int unsigned auto_increment," . // unique ID, generated by MySQL - "lp_type int unsigned not null," . // lp_types can be found in the main database's lp_type table - "name varchar(255) not null," . // name is the text name of the learning path (e.g. Word 2000) - "ref tinytext null," . // ref for SCORM elements is the SCORM ID in imsmanifest. For other learnpath types, just ignore - "description text null,". // textual description - "path text not null," . // path, starting at the platforms root (so all paths should start with 'courses/...' for now) - "force_commit tinyint unsigned not null default 0, " . // stores the default behaviour regarding SCORM information - "default_view_mod char(32) not null default 'embedded'," . // stores the default view mode (embedded or fullscreen) - "default_encoding char(32) not null default 'UTF-8', " . // stores the encoding detected at learning path reading - "display_order int unsigned not null default 0," . // order of learnpaths display in the learnpaths list - not really important - "content_maker tinytext not null default ''," . // the content make for this course (ENI, Articulate, ...) - "content_local varchar(32) not null default 'local'," . // content localisation ('local' or 'distant') - "content_license text not null default ''," . // content license - "prevent_reinit tinyint unsigned not null default 1," . // stores the default behaviour regarding items re-initialisation when viewed a second time after success - "js_lib tinytext not null default ''," . // the JavaScript library to load for this lp - "debug tinyint unsigned not null default 0," . // stores the default behaviour regarding items re-initialisation when viewed a second time after success - "theme varchar(255) not null default '', " . // stores the theme of the LP - "preview_image varchar(255) not null default '', " . // stores the theme of the LP - "author varchar(255) not null default '', " . // stores the theme of the LP - "session_id int unsigned not null default 0, " . // the session_id - "prerequisite int unsigned not null default 0," . // pre requisite for next lp - "hide_toc_frame tinyint NOT NULL DEFAULT 0, ". - "seriousgame_mode tinyint NOT NULL DEFAULT 0, ". - "use_max_score int unsigned not null default 1, " . - "autolunch int unsigned not null default 0, " . // auto lunch LP - "created_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . - "modified_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . - "publicated_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . - "expired_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - PRIMARY KEY (c_id, id) - )" . $charset_clause; + )" . $charset_clause; + Database::query($sql); - Database::query($sql); - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPVIEW` ( - $add_to_all_tables" . - "id int unsigned auto_increment," . // unique ID from MySQL - "lp_id int unsigned not null," . // learnpath ID from 'lp' - "user_id int unsigned not null," . // user ID from main.user - "view_count int unsigned not null default 0," . // integer counting the amount of times this learning path has been attempted - "last_item int unsigned not null default 0," . // last item seen in this view - "progress int unsigned default 0," . - "session_id int not null default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; // lp's progress for this user - - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (lp_id) "; - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (user_id) "; - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (session_id) "; - Database::query($sql); - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEM` ( - $add_to_all_tables - " . - "id int unsigned auto_increment," . // unique ID from MySQL - "lp_id int unsigned not null," . // lp_id from 'lp' - "item_type char(32) not null default 'dokeos_document'," . // can be dokeos_document, dokeos_chapter or scorm_asset, scorm_sco, scorm_chapter - "ref tinytext not null default ''," . // the ID given to this item in the imsmanifest file - "title varchar(511) not null," . // the title/name of this item (to display in the T.O.C.) - "description varchar(511) not null default ''," . // the description of this item - deprecated - "path text not null," . // the path to that item, starting at 'courses/...' level - "min_score float unsigned not null default 0," . // min score allowed - "max_score float unsigned default 100," . // max score allowed - "mastery_score float unsigned null," . // minimum score to pass the test - "parent_item_id int unsigned not null default 0," . // the item one level higher - "previous_item_id int unsigned not null default 0," . // the item before this one in the sequential learning order (MySQL id) - "next_item_id int unsigned not null default 0," . // the item after this one in the sequential learning order (MySQL id) - "display_order int unsigned not null default 0," . // this is needed for ordering items under the same parent (previous_item_id doesn't give correct order after reordering) - "prerequisite text null default null," . // prerequisites in AICC scripting language as defined in the SCORM norm (allow logical operators) - "parameters text null," . // prerequisites in AICC scripting language as defined in the SCORM norm (allow logical operators) - "launch_data text not null default ''," . // data from imsmanifest - "max_time_allowed char(13) NULL default ''," . // data from imsmanifest - "terms TEXT NULL," . // contains the indexing tags (search engine) - "search_did INT NULL,". // contains the internal search-engine id of this element - "audio VARCHAR(250), - PRIMARY KEY (c_id, id) - - )" . $charset_clause; // contains the audio file that goes with the learning path step - - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPITEM` ADD INDEX (lp_id)"; - Database::query($sql); - - $sql = "ALTER TABLE $TABLELPITEM ADD INDEX idx_c_lp_item_cid_lp_id (c_id, lp_id)"; - Database::query($sql); - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEMVIEW` ( - $add_to_all_tables - " . - "id bigint unsigned auto_increment," . // unique ID - "lp_item_id int unsigned not null," . // item ID (MySQL id) - "lp_view_id int unsigned not null," . // learning path view id (attempt) - "view_count int unsigned not null default 0," . // how many times this item has been viewed in the current attempt (generally 0 or 1) - "start_time int unsigned not null," . // when did the user open it? - "total_time int unsigned not null default 0," . // after how many seconds did he close it? - "score float unsigned not null default 0," . // score returned by SCORM or other techs - "status char(32) not null default 'not attempted'," . // status for this item (SCORM) - "suspend_data longtext null default ''," . - "lesson_location text null default ''," . - "core_exit varchar(32) not null default 'none'," . - "max_score varchar(8) default '', - PRIMARY KEY (c_id, id) - )" . $charset_clause; + $sql = "ALTER TABLE `" . $TABLEQUIZ . "` ADD INDEX ( session_id ) "; + Database::query($sql); - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPITEMVIEW` ADD INDEX (lp_item_id) "; - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPITEMVIEW` ADD INDEX (lp_view_id) "; - Database::query($sql); - - $sql = "ALTER TABLE $TABLELPITEMVIEW ADD INDEX idx_c_lp_item_view_cid_lp_view_id_lp_item_id (c_id, lp_view_id, lp_item_id) "; - Database::query($sql); - - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVINTERACTION`( - $add_to_all_tables" . - "id bigint unsigned auto_increment," . - "order_id int unsigned not null default 0,". // internal order (0->...) given by Dokeos - "lp_iv_id bigint unsigned not null," . // identifier of the related sco_view - "interaction_id varchar(255) not null default ''," . // sco-specific, given by the sco - "interaction_type varchar(255) not null default ''," . // literal values, SCORM-specific (see p.63 of SCORM 1.2 RTE) - "weighting double not null default 0," . - "completion_time varchar(16) not null default ''," . // completion time for the interaction (timestamp in a day's time) - expected output format is scorm time - "correct_responses text not null default ''," . // actually a serialised array. See p.65 os SCORM 1.2 RTE) - "student_response text not null default ''," . // student response (format depends on type) - "result varchar(255) not null default ''," . // textual result - "latency varchar(16) not null default ''," . // time necessary for completion of the interaction - "PRIMARY KEY (c_id, id)". - ")" . $charset_clause; - - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPIVINTERACTION` ADD INDEX (lp_iv_id) "; - Database::query($sql); - - $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVOBJECTIVE`( - $add_to_all_tables" . - "id bigint unsigned auto_increment," . - "lp_iv_id bigint unsigned not null," . // identifier of the related sco_view - "order_id int unsigned not null default 0,". // internal order (0->...) given by Dokeos - "objective_id varchar(255) not null default ''," . // sco-specific, given by the sco - "score_raw float unsigned not null default 0," . // score - "score_max float unsigned not null default 0," . // max score - "score_min float unsigned not null default 0," . // min score - "status char(32) not null default 'not attempted', " . //status, just as sco status - "PRIMARY KEY (c_id, id) ". - ")" . $charset_clause; - - Database::query($sql); - - $sql = "ALTER TABLE `$TABLELPIVOBJECTIVE` ADD INDEX (lp_iv_id) "; - Database::query($sql); - - /* Blogs */ - - $sql = " - CREATE TABLE `" . $tbl_blogs . "` ( + // Exercise tool - questions + $sql = " + CREATE TABLE `" . $TABLEQUIZQUESTIONLIST . "` ( $add_to_all_tables - blog_id int NOT NULL AUTO_INCREMENT , - blog_name varchar( 250 ) NOT NULL default '', - blog_subtitle varchar( 250 ) default NULL , - date_creation datetime NOT NULL default '0000-00-00 00:00:00', - visibility tinyint unsigned NOT NULL default 0, - session_id int default 0, - PRIMARY KEY (c_id, blog_id ) - )" . $charset_clause . " COMMENT = 'Table with blogs in this course';"; - - Database::query($sql); + id int unsigned NOT NULL auto_increment, + question TEXT NOT NULL, + description text default NULL, + ponderation float(6,2) NOT NULL default 0, + position mediumint unsigned NOT NULL default 1, + type tinyint unsigned NOT NULL default 2, + picture varchar(50) default NULL, + level int unsigned NOT NULL default 0, + extra varchar(255) default NULL, + question_code char(10) default '', + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - $sql = "ALTER TABLE `".$tbl_blogs . "` ADD INDEX ( session_id ) "; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLEQUIZQUESTIONLIST . "` ADD INDEX (position)"; + Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_blogs_comments . "` ( + // Exercise tool - answers + $sql = " + CREATE TABLE `" . $TABLEQUIZANSWERSLIST . "` ( $add_to_all_tables - comment_id int NOT NULL AUTO_INCREMENT , - title varchar( 250 ) NOT NULL default '', - comment longtext NOT NULL , - author_id int NOT NULL default 0, - date_creation datetime NOT NULL default '0000-00-00 00:00:00', - blog_id int NOT NULL default 0, - post_id int NOT NULL default 0, - task_id int default NULL , - parent_comment_id int NOT NULL default 0, - PRIMARY KEY (c_id, comment_id ) - )" . $charset_clause . " COMMENT = 'Table with comments on posts in a blog';"; - - Database::query($sql); - - $sql = " - CREATE TABLE `" . $tbl_blogs_posts . "` ( - $add_to_all_tables - post_id int NOT NULL AUTO_INCREMENT , - title varchar( 250 ) NOT NULL default '', - full_text longtext NOT NULL , - date_creation datetime NOT NULL default '0000-00-00 00:00:00', - blog_id int NOT NULL default 0, - author_id int NOT NULL default 0, - PRIMARY KEY (c_id, post_id ) - )" . $charset_clause . " COMMENT = 'Table with posts / blog.';"; - - Database::query($sql); - - $sql = " - CREATE TABLE `" . $tbl_blogs_rating . "` ( + id int unsigned NOT NULL, + id_auto int NOT NULL AUTO_INCREMENT, + question_id int unsigned NOT NULL, + answer text NOT NULL, + correct mediumint unsigned default NULL, + comment text default NULL, + ponderation float(6,2) NOT NULL default 0, + position mediumint unsigned NOT NULL default 1, + hotspot_coordinates text, + hotspot_type enum('square','circle','poly','delineation','oar') default NULL, + destination text NOT NULL, + answer_code char(10) default '', + PRIMARY KEY (c_id, id_auto) + )" . $charset_clause; + Database::query($sql); + + // Exercise tool - answer options + $sql = " + CREATE TABLE `" . $TABLEQUIZQUESTIONOPTION . "` ( $add_to_all_tables - rating_id int NOT NULL AUTO_INCREMENT , - blog_id int NOT NULL default 0, - rating_type enum( 'post', 'comment' ) NOT NULL default 'post', - item_id int NOT NULL default 0, - user_id int NOT NULL default 0, - rating int NOT NULL default 0, - PRIMARY KEY (c_id, rating_id ) - )" . $charset_clause . " COMMENT = 'Table with ratings for post/comments in a certain blog';"; + id int NOT NULL auto_increment, + question_id int NOT NULL, + name varchar(255), + position int unsigned NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_blogs_rel_user . "` ( + // Exercise tool - Test/question relations + $sql = " + CREATE TABLE `" . $TABLEQUIZQUESTION . "` ( $add_to_all_tables - blog_id int NOT NULL default 0, - user_id int NOT NULL default 0, - PRIMARY KEY ( c_id, blog_id , user_id ) - )" . $charset_clause . " COMMENT = 'Table representing users subscribed to a blog';"; + question_id int unsigned NOT NULL, + exercice_id int unsigned NOT NULL, + question_order int unsigned NOT NULL default 1, + PRIMARY KEY (c_id, question_id,exercice_id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_blogs_tasks . "` ( - $add_to_all_tables - task_id int NOT NULL AUTO_INCREMENT , - blog_id int NOT NULL default 0, - title varchar( 250 ) NOT NULL default '', - description text NOT NULL , - color varchar( 10 ) NOT NULL default '', - system_task tinyint unsigned NOT NULL default 0, - PRIMARY KEY (c_id, task_id ) - )" . $charset_clause . " COMMENT = 'Table with tasks for a blog';"; - - Database::query($sql); - - $sql = " - CREATE TABLE `" . $tbl_blogs_tasks_rel_user . "` ( - $add_to_all_tables - blog_id int NOT NULL default 0, - user_id int NOT NULL default 0, - task_id int NOT NULL default 0, - target_date date NOT NULL default '0000-00-00', - PRIMARY KEY (c_id, blog_id , user_id , task_id ) - )" . $charset_clause . " COMMENT = 'Table with tasks assigned to a user in a blog';"; + $sql = "CREATE TABLE `" . $table_quiz_question_category . "` ( + $add_to_all_tables + id int NOT NULL AUTO_INCREMENT, + title varchar(255) NOT NULL, + description text NOT NULL, + PRIMARY KEY (c_id,id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); - $sql ="CREATE TABLE `" .$tbl_blogs_attachment."` ( + $sql = "CREATE TABLE `" . $table_quiz_question_rel_category . "` ( $add_to_all_tables - id int unsigned NOT NULL auto_increment, - path varchar(255) NOT NULL COMMENT 'the real filename', - comment text, - size int NOT NULL default '0', - post_id int NOT NULL, - filename varchar(255) NOT NULL COMMENT 'the user s file name', - blog_id int NOT NULL, - comment_id int NOT NULL default '0', - PRIMARY KEY (c_id, id) + question_id int NOT NULL, + category_id int NOT NULL, + PRIMARY KEY (c_id,question_id) )" . $charset_clause; + Database::query($sql); - Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_permission_group . "` ( + /* Course description */ + + $sql = " + CREATE TABLE `" . $TABLETOOLCOURSEDESC . "` ( $add_to_all_tables - id int NOT NULL AUTO_INCREMENT , - group_id int NOT NULL default 0, - tool varchar( 250 ) NOT NULL default '', - action varchar( 250 ) NOT NULL default '', + id int UNSIGNED NOT NULL auto_increment, + title VARCHAR(255), + content TEXT, + session_id int default 0, + description_type tinyint unsigned NOT NULL default 0, + progress INT NOT NULL default 0, PRIMARY KEY (c_id, id) - )" . $charset_clause; + )" . $charset_clause; + Database::query($sql); + + $sql = "ALTER TABLE `" . $TABLETOOLCOURSEDESC . "` ADD INDEX ( session_id ) "; + Database::query($sql); - Database::query($sql); + /* Course homepage tool list */ - $sql = " - CREATE TABLE `" . $tbl_permission_user . "` ( + $sql = " + CREATE TABLE `" . $tbl_course_homepage . "` ( $add_to_all_tables - id int NOT NULL AUTO_INCREMENT , - user_id int NOT NULL default 0, - tool varchar( 250 ) NOT NULL default '', - action varchar( 250 ) NOT NULL default '', - PRIMARY KEY (c_id, id ) - )" . $charset_clause; + id int unsigned NOT NULL auto_increment, + name varchar(255) NOT NULL, + link varchar(255) NOT NULL, + image varchar(255) default NULL, + visibility tinyint unsigned default 0, + admin varchar(255) default NULL, + address varchar(255) default NULL, + added_tool tinyint unsigned default 1, + target enum('_self','_blank') NOT NULL default '_self', + category varchar(20) not null default 'authoring', + session_id int default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + $sql = "ALTER TABLE `" . $tbl_course_homepage . "` ADD INDEX ( session_id ) "; + Database::query($sql); - Database::query($sql); + /* Agenda tool */ - $sql = " - CREATE TABLE `" . $tbl_permission_task . "` ( + $sql = " + CREATE TABLE `" . $TABLETOOLAGENDA . "` ( $add_to_all_tables - id int NOT NULL AUTO_INCREMENT, - task_id int NOT NULL default 0, - tool varchar( 250 ) NOT NULL default '', - action varchar( 250 ) NOT NULL default '', - PRIMARY KEY (c_id, id ) - )" . $charset_clause; + id int unsigned NOT NULL auto_increment, + title varchar(255) NOT NULL, + content text, + start_date datetime NOT NULL default '0000-00-00 00:00:00', + end_date datetime NOT NULL default '0000-00-00 00:00:00', + parent_event_id INT NULL, + session_id int unsigned NOT NULL default 0, + all_day INT NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLAGENDA . "` ADD INDEX ( session_id ) ;"; + Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_role . "` ( + $sql = " + CREATE TABLE `" . $TABLETOOLAGENDAREPEAT . "` ( $add_to_all_tables - role_id int NOT NULL AUTO_INCREMENT, - role_name varchar( 250 ) NOT NULL default '', - role_comment text, - default_role tinyint default 0, - PRIMARY KEY (c_id, role_id) - )" . $charset_clause; + cal_id INT DEFAULT 0 NOT NULL, + cal_type VARCHAR(20), + cal_end INT, + cal_frequency INT DEFAULT 1, + cal_days CHAR(7), + PRIMARY KEY (c_id, cal_id) + )" . $charset_clause; + Database::query($sql); + + $sql = " + CREATE TABLE `" . $TABLETOOLAGENDAREPEATNOT . "` ( + $add_to_all_tables + cal_id INT NOT NULL, + cal_date INT NOT NULL, + PRIMARY KEY (c_id, cal_id, cal_date ) + )" . $charset_clause; + Database::query($sql); + + // Agenda Attachment + $sql = "CREATE TABLE `" . $TABLETOOLAGENDAATTACHMENT . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + path varchar(255) NOT NULL, + comment text, + size int NOT NULL default 0, + agenda_id int NOT NULL, + filename varchar(255) NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + + /* + Document tool + */ - Database::query($sql); + $sql = " + CREATE TABLE `" . $TABLETOOLDOCUMENT . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + path varchar(255) NOT NULL default '', + comment text, + title varchar(255) default NULL, + filetype set('file','folder') NOT NULL default 'file', + size int NOT NULL default 0, + readonly TINYINT UNSIGNED NOT NULL, + session_id int UNSIGNED NOT NULL default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_role_group . "` ( + /* + Student publications + */ + $sql = " + CREATE TABLE `" . $TABLETOOLWORKS . "` ( $add_to_all_tables - id int NOT NULL AUTO_INCREMENT, - role_id int NOT NULL default 0, - scope varchar( 20 ) NOT NULL default 'course', - group_id int NOT NULL default 0, - PRIMARY KEY (id, c_id, group_id ) - )" . $charset_clause; + id int unsigned NOT NULL auto_increment, + url varchar(255) default NULL, + title varchar(255) default NULL, + description text default NULL, + author varchar(255) default NULL, + active tinyint default NULL, + accepted tinyint default 0, + post_group_id int DEFAULT 0 NOT NULL, + sent_date datetime NOT NULL default '0000-00-00 00:00:00', + filetype set('file','folder') NOT NULL default 'file', + has_properties int UNSIGNED NOT NULL DEFAULT 0, + view_properties tinyint NULL, + qualification float(6,2) UNSIGNED NOT NULL DEFAULT 0, + date_of_qualification datetime NOT NULL default '0000-00-00 00:00:00', + parent_id INT UNSIGNED NOT NULL DEFAULT 0, + qualificator_id INT UNSIGNED NOT NULL DEFAULT 0, + weight float(6,2) UNSIGNED NOT NULL default 0, + session_id INT UNSIGNED NOT NULL default 0, + user_id INTEGER NOT NULL, + allow_text_assignment INTEGER NOT NULL DEFAULT 0, + contains_file INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + + $sql = " + CREATE TABLE `" . $TABLETOOLWORKSASS . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + expires_on datetime NOT NULL default '0000-00-00 00:00:00', + ends_on datetime NOT NULL default '0000-00-00 00:00:00', + add_to_calendar tinyint NOT NULL, + enable_qualification tinyint NOT NULL, + publication_id int NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); + + $sql = "ALTER TABLE `" . $TABLETOOLWORKS . "` ADD INDEX ( session_id )"; + Database::query($sql); - Database::query($sql); + /* + Links tool + */ - $sql = " - CREATE TABLE `" . $tbl_role_permissions . "` ( + $sql = " + CREATE TABLE `" . $TABLETOOLLINK . "` ( $add_to_all_tables - id int NOT NULL AUTO_INCREMENT, - role_id int NOT NULL default 0, - tool varchar( 250 ) NOT NULL default '', - action varchar( 50 ) NOT NULL default '', - default_perm tinyint NOT NULL default 0, - PRIMARY KEY (id, c_id, role_id, tool, action ) - )" . $charset_clause; + id int unsigned NOT NULL auto_increment, + url TEXT NOT NULL, + title varchar(150) default NULL, + description text, + category_id int unsigned default NULL, + display_order int unsigned NOT NULL default 0, + on_homepage enum('0','1') NOT NULL default '0', + target char(10) default '_self', + session_id int default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLLINK . "` ADD INDEX ( session_id ) "; + Database::query($sql); - $sql = " - CREATE TABLE `" . $tbl_role_user . "` ( + $sql = " + CREATE TABLE `" . $TABLETOOLLINKCATEGORIES . "` ( $add_to_all_tables - role_id int NOT NULL default 0, - scope varchar( 20 ) NOT NULL default 'course', - user_id int NOT NULL default 0, - PRIMARY KEY ( c_id, role_id, user_id ) - )" . $charset_clause; + id int unsigned NOT NULL auto_increment, + category_title varchar(255) NOT NULL, + description text, + display_order mediumint unsigned NOT NULL default 0, + session_id int default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + Database::query($sql); - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLLINKCATEGORIES . "` ADD INDEX ( session_id ) "; + Database::query($sql); - /* - * Course Config Settings - * - */ + /* Wiki */ - Database::query(" - CREATE TABLE `".$TABLESETTING . "` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - variable varchar(255) NOT NULL default '', - subkey varchar(255) default NULL, - type varchar(255) default NULL, - category varchar(255) default NULL, - value varchar(255) NOT NULL default '', - title varchar(255) NOT NULL default '', - comment varchar(255) default NULL, - subkeytext varchar(255) default NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause); - - /* - Survey - */ - - $sql = "CREATE TABLE `".$TABLESURVEY."` ( + $sql = "CREATE TABLE `" . $TABLETOOLWIKI . "` ( $add_to_all_tables - survey_id int unsigned NOT NULL auto_increment, - code varchar(20) default NULL, - title text default NULL, - subtitle text default NULL, - author varchar(20) default NULL, - lang varchar(20) default NULL, - avail_from date default NULL, - avail_till date default NULL, - is_shared char(1) default '1', - template varchar(20) default NULL, - intro text, - surveythanks text, - creation_date datetime NOT NULL default '0000-00-00 00:00:00', - invited int NOT NULL, - answered int NOT NULL, - invite_mail text NOT NULL, - reminder_mail text NOT NULL, - mail_subject VARCHAR( 255 ) NOT NULL, - anonymous enum('0','1') NOT NULL default '0', - access_condition TEXT DEFAULT NULL, - shuffle bool NOT NULL default '0', - one_question_per_page bool NOT NULL default '0', - survey_version varchar(255) NOT NULL default '', - parent_id int unsigned NOT NULL, - survey_type int NOT NULL default 0, - show_form_profile int NOT NULL default 0, - form_fields TEXT NOT NULL, - session_id int unsigned NOT NULL default 0, - visible_results int unsigned DEFAULT 0, - PRIMARY KEY (c_id, survey_id) + id int NOT NULL auto_increment, + page_id int NOT NULL default 0, + reflink varchar(255) NOT NULL default 'index', + title varchar(255) NOT NULL, + content mediumtext NOT NULL, + user_id int NOT NULL default 0, + group_id int DEFAULT NULL, + dtime datetime NOT NULL default '0000-00-00 00:00:00', + addlock int NOT NULL default 1, + editlock int NOT NULL default 0, + visibility int NOT NULL default 1, + addlock_disc int NOT NULL default 1, + visibility_disc int NOT NULL default 1, + ratinglock_disc int NOT NULL default 1, + assignment int NOT NULL default 0, + comment text NOT NULL, + progress text NOT NULL, + score int NULL default 0, + version int default NULL, + is_editing int NOT NULL default 0, + time_edit datetime NOT NULL default '0000-00-00 00:00:00', + hits int default 0, + linksto text NOT NULL, + tag text NOT NULL, + user_ip varchar(39) NOT NULL, + session_id int default 0, + PRIMARY KEY (c_id, id), + KEY reflink (reflink), + KEY group_id (group_id), + KEY page_id (page_id), + KEY session_id (session_id) )" . $charset_clause; - $result = Database::query($sql); + Database::query($sql); - $sql = "ALTER TABLE `".$TABLESURVEY."` ADD INDEX ( session_id )"; - Database::query($sql); + $sql = "CREATE TABLE `" . $TABLEWIKICONF . "` ( + $add_to_all_tables + page_id int NOT NULL default 0, + task text NOT NULL, + feedback1 text NOT NULL, + feedback2 text NOT NULL, + feedback3 text NOT NULL, + fprogress1 varchar(3) NOT NULL, + fprogress2 varchar(3) NOT NULL, + fprogress3 varchar(3) NOT NULL, + max_size int default NULL, + max_text int default NULL, + max_version int default NULL, + startdate_assig datetime NOT NULL default '0000-00-00 00:00:00', + enddate_assig datetime NOT NULL default '0000-00-00 00:00:00', + delayedsubmit int NOT NULL default 0, + KEY page_id (page_id), + PRIMARY KEY ( c_id, page_id ) + )" . $charset_clause; + Database::query($sql); - $sql = "CREATE TABLE `".$TABLESURVEYINVITATION."` ( - $add_to_all_tables - survey_invitation_id int unsigned NOT NULL auto_increment, - survey_code varchar(20) NOT NULL, - user varchar(250) NOT NULL, - invitation_code varchar(250) NOT NULL, - invitation_date datetime NOT NULL, - reminder_date datetime NOT NULL, - answered int NOT NULL default 0, - session_id int UNSIGNED NOT NULL default 0, - PRIMARY KEY (c_id, survey_invitation_id) + $sql = "CREATE TABLE `" . $TABLEWIKIDISCUSS . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + publication_id int NOT NULL default 0, + userc_id int NOT NULL default 0, + comment text NOT NULL, + p_score varchar(255) default NULL, + dtime datetime NOT NULL default '0000-00-00 00:00:00', + PRIMARY KEY (c_id, id) )" . $charset_clause; - $result = Database::query($sql); + Database::query($sql); - $sql = "CREATE TABLE `".$TABLESURVEYQUESTION."` ( - $add_to_all_tables - question_id int unsigned NOT NULL auto_increment, - survey_id int unsigned NOT NULL, - survey_question text NOT NULL, - survey_question_comment text NOT NULL, - type varchar(250) NOT NULL, - display varchar(10) NOT NULL, - sort int NOT NULL, - shared_question_id int, - max_value int, - survey_group_pri int unsigned NOT NULL default '0', - survey_group_sec1 int unsigned NOT NULL default '0', - survey_group_sec2 int unsigned NOT NULL default '0', - PRIMARY KEY (c_id, question_id) + $sql = "CREATE TABLE `" . $TABLEWIKIMAILCUE . "` ( + $add_to_all_tables + id int NOT NULL, + user_id int NOT NULL, + type text NOT NULL, + group_id int DEFAULT NULL, + session_id int default 0, + KEY (c_id, id), + PRIMARY KEY ( c_id, id, user_id ) )" . $charset_clause; - $result = Database::query($sql); - - $sql ="CREATE TABLE `".$TABLESURVEYQUESTIONOPTION."` ( - $add_to_all_tables - question_option_id int unsigned NOT NULL auto_increment, - question_id int unsigned NOT NULL, - survey_id int unsigned NOT NULL, - option_text text NOT NULL, - sort int NOT NULL, - value int NOT NULL default '0', - PRIMARY KEY (c_id, question_option_id) - )" . $charset_clause; - - $result = Database::query($sql); - - $sql = "CREATE TABLE `".$TABLESURVEYANSWER."` ( - $add_to_all_tables - answer_id int unsigned NOT NULL auto_increment, - survey_id int unsigned NOT NULL, - question_id int unsigned NOT NULL, - option_id TEXT NOT NULL, - value int unsigned NOT NULL, - user varchar(250) NOT NULL, - PRIMARY KEY (c_id, answer_id) + Database::query($sql); + + /* + Online + */ + + $sql = " + CREATE TABLE `" . $TABLETOOLONLINECONNECTED . "` ( + $add_to_all_tables + user_id int unsigned NOT NULL, + last_connection datetime NOT NULL default '0000-00-00 00:00:00', + PRIMARY KEY (c_id, user_id) )" . $charset_clause; - $result = Database::query($sql); + Database::query($sql); - $sql = "CREATE TABLE `".$TABLESURVEYGROUP."` ( - $add_to_all_tables - id int unsigned NOT NULL auto_increment, - name varchar(20) NOT NULL, - description varchar(255) NOT NULL, - survey_id int unsigned NOT NULL, - PRIMARY KEY (c_id, id) + $sql = " + CREATE TABLE `" . $TABLETOOLONLINELINK . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + name char(50) NOT NULL default '', + url char(100) NOT NULL, + PRIMARY KEY (c_id, id) )" . $charset_clause; - $result = Database::query($sql); + Database::query($sql); - // Table glosary - $sql = "CREATE TABLE `".$TBL_GLOSSARY."` ( - $add_to_all_tables - glossary_id int unsigned NOT NULL auto_increment, - name varchar(255) NOT NULL, - description text not null, - display_order int, - session_id int default 0, - PRIMARY KEY (c_id, glossary_id) + $sql = " + CREATE TABLE `" . $TABLETOOLCHATCONNECTED . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + user_id int unsigned NOT NULL default '0', + last_connection datetime NOT NULL default '0000-00-00 00:00:00', + session_id INT NOT NULL default 0, + to_group_id INT NOT NULL default 0, + PRIMARY KEY (c_id, id, user_id, last_connection) )" . $charset_clause; - $result = Database::query($sql); + Database::query($sql); - $sql = "ALTER TABLE `".$TBL_GLOSSARY . "` ADD INDEX ( session_id ) "; - Database::query($sql); + $sql = "ALTER TABLE `" . $TABLETOOLCHATCONNECTED . "` ADD INDEX char_connected_index(user_id, session_id, to_group_id) "; + Database::query($sql); - // Table notebook - $sql = "CREATE TABLE `".$TBL_NOTEBOOK."` ( - $add_to_all_tables - notebook_id int unsigned NOT NULL auto_increment, - user_id int unsigned NOT NULL, - course varchar(40) not null, - session_id int NOT NULL default 0, - title varchar(255) NOT NULL, - description text NOT NULL, - creation_date datetime NOT NULL default '0000-00-00 00:00:00', - update_date datetime NOT NULL default '0000-00-00 00:00:00', - status int, - PRIMARY KEY (c_id, notebook_id) - )" . $charset_clause; - $result = Database::query($sql); + /* + Groups tool + */ + + Database::query( + "CREATE TABLE `" . $TABLEGROUPS . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + name varchar(100) default NULL, + category_id int unsigned NOT NULL default 0, + description text, + max_student int unsigned NOT NULL default 8, + doc_state tinyint unsigned NOT NULL default 1, + calendar_state tinyint unsigned NOT NULL default 0, + work_state tinyint unsigned NOT NULL default 0, + announcements_state tinyint unsigned NOT NULL default 0, + forum_state tinyint unsigned NOT NULL default 0, + wiki_state tinyint unsigned NOT NULL default 1, + chat_state tinyint unsigned NOT NULL default 1, + secret_directory varchar(255) default NULL, + self_registration_allowed tinyint unsigned NOT NULL default '0', + self_unregistration_allowed tinyint unsigned NOT NULL default '0', + session_id int unsigned NOT NULL default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); + + Database::query( + "ALTER TABLE `" . $TABLEGROUPS . "` ADD INDEX ( session_id )" + ); + + Database::query( + "CREATE TABLE `" . $TABLEGROUPCATEGORIES . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + title varchar(255) NOT NULL default '', + description text NOT NULL, + doc_state tinyint unsigned NOT NULL default 1, + calendar_state tinyint unsigned NOT NULL default 1, + work_state tinyint unsigned NOT NULL default 1, + announcements_state tinyint unsigned NOT NULL default 1, + forum_state tinyint unsigned NOT NULL default 1, + wiki_state tinyint unsigned NOT NULL default 1, + chat_state tinyint unsigned NOT NULL default 1, + max_student int unsigned NOT NULL default 8, + self_reg_allowed tinyint unsigned NOT NULL default 0, + self_unreg_allowed tinyint unsigned NOT NULL default 0, + groups_per_user int unsigned NOT NULL default 0, + display_order int unsigned NOT NULL default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); - /* Attendance tool */ + Database::query( + "CREATE TABLE `" . $TABLEGROUPUSER . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + user_id int unsigned NOT NULL, + group_id int unsigned NOT NULL default 0, + status int NOT NULL default 0, + role char(50) NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); - // Attendance table - $sql = " - CREATE TABLE `".$TBL_ATTENDANCE."` ( + Database::query( + "CREATE TABLE `" . $TABLEGROUPTUTOR . "` ( $add_to_all_tables id int NOT NULL auto_increment, - name text NOT NULL, - description TEXT NULL, - active tinyint NOT NULL default 1, - attendance_qualify_title varchar(255) NULL, - attendance_qualify_max int NOT NULL default 0, - attendance_weight float(6,2) NOT NULL default '0.0', - session_id int NOT NULL default 0, - locked int NOT NULL default 0, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - $result = Database::query($sql); + user_id int NOT NULL, + group_id int NOT NULL default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE . "` ADD INDEX (session_id)"; - Database::query($sql); + Database::query( + "CREATE TABLE `" . $TABLEITEMPROPERTY . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + tool varchar(100) NOT NULL default '', + insert_user_id int unsigned NOT NULL default '0', + insert_date datetime NOT NULL default '0000-00-00 00:00:00', + lastedit_date datetime NOT NULL default '0000-00-00 00:00:00', + ref int NOT NULL default '0', + lastedit_type varchar(100) NOT NULL default '', + lastedit_user_id int unsigned NOT NULL default '0', + to_group_id int unsigned default NULL, + to_user_id int unsigned default NULL, + visibility tinyint NOT NULL default '1', + start_visible datetime NOT NULL default '0000-00-00 00:00:00', + end_visible datetime NOT NULL default '0000-00-00 00:00:00', + id_session INT NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE . "` ADD INDEX (active)"; - Database::query($sql); + Database::query( + "ALTER TABLE `$TABLEITEMPROPERTY` ADD INDEX idx_item_property_toolref (tool,ref)" + ); - // Attendance sheet table - $sql = " - CREATE TABLE `".$TBL_ATTENDANCE_SHEET."` ( + /* Tool introductions */ + Database::query( + " + CREATE TABLE `" . $TABLEINTROS . "` ( $add_to_all_tables - user_id int NOT NULL, - attendance_calendar_id int NOT NULL, - presence tinyint NOT NULL DEFAULT 0, - PRIMARY KEY(c_id, user_id, attendance_calendar_id) - )" . $charset_clause; - $result = Database::query($sql); + id varchar(50) NOT NULL, + intro_text MEDIUMTEXT NOT NULL, + session_id INT NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id, session_id) + )" . $charset_clause + ); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE_SHEET . "` ADD INDEX (presence) "; - Database::query($sql); + /* Dropbox tool */ - // Attendance calendar table - $sql = " - CREATE TABLE `".$TBL_ATTENDANCE_CALENDAR."` ( + Database::query( + " + CREATE TABLE `" . $TABLETOOLDROPBOXFILE . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - attendance_id int NOT NULL , - date_time datetime NOT NULL default '0000-00-00 00:00:00', - done_attendance tinyint NOT NULL default 0, - PRIMARY KEY(c_id, id) - )" . $charset_clause; - $result = Database::query($sql); + id int unsigned NOT NULL auto_increment, + uploader_id int unsigned NOT NULL default 0, + filename varchar(250) NOT NULL default '', + filesize int unsigned NOT NULL, + title varchar(250) default '', + description varchar(250) default '', + author varchar(250) default '', + upload_date datetime NOT NULL default '0000-00-00 00:00:00', + last_upload_date datetime NOT NULL default '0000-00-00 00:00:00', + cat_id int NOT NULL default 0, + session_id int UNSIGNED NOT NULL, + PRIMARY KEY (c_id, id), + UNIQUE KEY UN_filename (filename) + )" . $charset_clause + ); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE_CALENDAR."` ADD INDEX (attendance_id)"; - Database::query($sql); + Database::query( + "ALTER TABLE `$TABLETOOLDROPBOXFILE` ADD INDEX ( session_id )" + ); + + Database::query( + " + CREATE TABLE `" . $TABLETOOLDROPBOXPOST . "` ( + $add_to_all_tables + file_id int unsigned NOT NULL, + dest_user_id int unsigned NOT NULL default 0, + feedback_date datetime NOT NULL default '0000-00-00 00:00:00', + feedback text default '', + cat_id int NOT NULL default 0, + session_id int UNSIGNED NOT NULL, + PRIMARY KEY (c_id, file_id, dest_user_id) + )" . $charset_clause + ); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE_CALENDAR."` ADD INDEX (done_attendance)"; - Database::query($sql); + Database::query( + "ALTER TABLE `$TABLETOOLDROPBOXPOST` ADD INDEX ( session_id )" + ); - // Attendance result table - $sql = " - CREATE TABLE `".$TBL_ATTENDANCE_RESULT."` ( + Database::query( + " + CREATE TABLE `" . $TABLETOOLDROPBOXPERSON . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - user_id int NOT NULL, - attendance_id int NOT NULL, - score int NOT NULL DEFAULT 0, + file_id int unsigned NOT NULL, + user_id int unsigned NOT NULL default 0, + PRIMARY KEY (c_id, file_id, user_id) + )" . $charset_clause + ); + + $sql = "CREATE TABLE `" . $TABLETOOLDROPBOXCATEGORY . "` ( + $add_to_all_tables + cat_id int NOT NULL auto_increment, + cat_name text NOT NULL, + received tinyint unsigned NOT NULL default 0, + sent tinyint unsigned NOT NULL default 0, + user_id int NOT NULL default 0, + session_id int NOT NULL default 0, + PRIMARY KEY (c_id, cat_id) + )" . $charset_clause; + Database::query($sql); + + $sql = "ALTER TABLE `" . $TABLETOOLDROPBOXCATEGORY . "` ADD INDEX ( session_id ) "; + Database::query($sql); + + $sql = "CREATE TABLE `" . $TABLETOOLDROPBOXFEEDBACK . "` ( + $add_to_all_tables + feedback_id int NOT NULL auto_increment, + file_id int NOT NULL default 0, + author_user_id int NOT NULL default 0, + feedback text NOT NULL, + feedback_date datetime NOT NULL default '0000-00-00 00:00:00', + PRIMARY KEY (c_id, feedback_id), + KEY file_id (file_id), + KEY author_user_id (author_user_id) + )" . $charset_clause; + Database::query($sql); + + /* + New learning path tool + */ + + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELP` ( + $add_to_all_tables + " . + "id int unsigned auto_increment," . // unique ID, generated by MySQL + "lp_type int unsigned not null," . // lp_types can be found in the main database's lp_type table + "name varchar(255) not null," . // name is the text name of the learning path (e.g. Word 2000) + "ref tinytext null," . // ref for SCORM elements is the SCORM ID in imsmanifest. For other learnpath types, just ignore + "description text null," . // textual description + "path text not null," . // path, starting at the platforms root (so all paths should start with 'courses/...' for now) + "force_commit tinyint unsigned not null default 0, " . // stores the default behaviour regarding SCORM information + "default_view_mod char(32) not null default 'embedded'," . // stores the default view mode (embedded or fullscreen) + "default_encoding char(32) not null default 'UTF-8', " . // stores the encoding detected at learning path reading + "display_order int unsigned not null default 0," . // order of learnpaths display in the learnpaths list - not really important + "content_maker tinytext not null default ''," . // the content make for this course (ENI, Articulate, ...) + "content_local varchar(32) not null default 'local'," . // content localisation ('local' or 'distant') + "content_license text not null default ''," . // content license + "prevent_reinit tinyint unsigned not null default 1," . // stores the default behaviour regarding items re-initialisation when viewed a second time after success + "js_lib tinytext not null default ''," . // the JavaScript library to load for this lp + "debug tinyint unsigned not null default 0," . // stores the default behaviour regarding items re-initialisation when viewed a second time after success + "theme varchar(255) not null default '', " . // stores the theme of the LP + "preview_image varchar(255) not null default '', " . // stores the theme of the LP + "author varchar(255) not null default '', " . // stores the theme of the LP + "session_id int unsigned not null default 0, " . // the session_id + "prerequisite int unsigned not null default 0," . // pre requisite for next lp + "hide_toc_frame tinyint NOT NULL DEFAULT 0, " . + "seriousgame_mode tinyint NOT NULL DEFAULT 0, " . + "use_max_score int unsigned not null default 1, " . + "autolunch int unsigned not null default 0, " . // auto lunch LP + "created_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . + "modified_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . + "publicated_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', " . + "expired_on DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (c_id, id) + )" . $charset_clause; + + Database::query($sql); + + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPVIEW` ( + $add_to_all_tables" . + "id int unsigned auto_increment," . // unique ID from MySQL + "lp_id int unsigned not null," . // learnpath ID from 'lp' + "user_id int unsigned not null," . // user ID from main.user + "view_count int unsigned not null default 0," . // integer counting the amount of times this learning path has been attempted + "last_item int unsigned not null default 0," . // last item seen in this view + "progress int unsigned default 0," . + "session_id int not null default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; // lp's progress for this user + + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (lp_id) "; + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (user_id) "; + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPVIEW` ADD INDEX (session_id) "; + Database::query($sql); + + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEM` ( + $add_to_all_tables + " . + "id int unsigned auto_increment," . // unique ID from MySQL + "lp_id int unsigned not null," . // lp_id from 'lp' + "item_type char(32) not null default 'dokeos_document'," . // can be dokeos_document, dokeos_chapter or scorm_asset, scorm_sco, scorm_chapter + "ref tinytext not null default ''," . // the ID given to this item in the imsmanifest file + "title varchar(511) not null," . // the title/name of this item (to display in the T.O.C.) + "description varchar(511) not null default ''," . // the description of this item - deprecated + "path text not null," . // the path to that item, starting at 'courses/...' level + "min_score float unsigned not null default 0," . // min score allowed + "max_score float unsigned default 100," . // max score allowed + "mastery_score float unsigned null," . // minimum score to pass the test + "parent_item_id int unsigned not null default 0," . // the item one level higher + "previous_item_id int unsigned not null default 0," . // the item before this one in the sequential learning order (MySQL id) + "next_item_id int unsigned not null default 0," . // the item after this one in the sequential learning order (MySQL id) + "display_order int unsigned not null default 0," . // this is needed for ordering items under the same parent (previous_item_id doesn't give correct order after reordering) + "prerequisite text null default null," . // prerequisites in AICC scripting language as defined in the SCORM norm (allow logical operators) + "parameters text null," . // prerequisites in AICC scripting language as defined in the SCORM norm (allow logical operators) + "launch_data text not null default ''," . // data from imsmanifest + "max_time_allowed char(13) NULL default ''," . // data from imsmanifest + "terms TEXT NULL," . // contains the indexing tags (search engine) + "search_did INT NULL," . // contains the internal search-engine id of this element + "audio VARCHAR(250), PRIMARY KEY (c_id, id) - )" . $charset_clause; - $result = Database::query($sql); - $sql = "ALTER TABLE `".$TBL_ATTENDANCE_RESULT."` ADD INDEX (attendance_id)"; - Database::query($sql); + )" . $charset_clause; // contains the audio file that goes with the learning path step - $sql = "ALTER TABLE `".$TBL_ATTENDANCE_RESULT."` ADD INDEX (user_id)"; - Database::query($sql); + Database::query($sql); - // attendance sheet log table - $sql = "CREATE TABLE `".$TBL_ATTENDANCE_SHEET_LOG."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - attendance_id int NOT NULL DEFAULT 0, - lastedit_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - lastedit_type varchar(200) NOT NULL, - lastedit_user_id int NOT NULL DEFAULT 0, - calendar_date_value datetime NULL, - PRIMARY KEY (c_id, id) - )" . $charset_clause; - $result = Database::query($sql) or die(Database::error()); + $sql = "ALTER TABLE `$TABLELPITEM` ADD INDEX (lp_id)"; + Database::query($sql); + $sql = "ALTER TABLE $TABLELPITEM ADD INDEX idx_c_lp_item_cid_lp_id (c_id, lp_id)"; + Database::query($sql); - // Thematic table - $sql = "CREATE TABLE `".$TBL_THEMATIC."` ( - $add_to_all_tables - id int NOT NULL auto_increment, - title varchar(255) NOT NULL, - content text NULL, - display_order int unsigned NOT NULL DEFAULT 0, - active tinyint NOT NULL DEFAULT 0, - session_id int NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id) + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPITEMVIEW` ( + $add_to_all_tables + " . + "id bigint unsigned auto_increment," . // unique ID + "lp_item_id int unsigned not null," . // item ID (MySQL id) + "lp_view_id int unsigned not null," . // learning path view id (attempt) + "view_count int unsigned not null default 0," . // how many times this item has been viewed in the current attempt (generally 0 or 1) + "start_time int unsigned not null," . // when did the user open it? + "total_time int unsigned not null default 0," . // after how many seconds did he close it? + "score float unsigned not null default 0," . // score returned by SCORM or other techs + "status char(32) not null default 'not attempted'," . // status for this item (SCORM) + "suspend_data longtext null default ''," . + "lesson_location text null default ''," . + "core_exit varchar(32) not null default 'none'," . + "max_score varchar(8) default '', + PRIMARY KEY (c_id, id) )" . $charset_clause; - $result = Database::query($sql); - $sql = "ALTER TABLE `".$TBL_THEMATIC."` ADD INDEX (active, session_id)"; - Database::query($sql); + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPITEMVIEW` ADD INDEX (lp_item_id) "; + Database::query($sql); - // thematic plan table - $sql = "CREATE TABLE `".$TBL_THEMATIC_PLAN."` ( + $sql = "ALTER TABLE `$TABLELPITEMVIEW` ADD INDEX (lp_view_id) "; + Database::query($sql); + + $sql = "ALTER TABLE $TABLELPITEMVIEW ADD INDEX idx_c_lp_item_view_cid_lp_view_id_lp_item_id (c_id, lp_view_id, lp_item_id) "; + Database::query($sql); + + + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVINTERACTION`( + $add_to_all_tables" . + "id bigint unsigned auto_increment," . + "order_id int unsigned not null default 0," . // internal order (0->...) given by Dokeos + "lp_iv_id bigint unsigned not null," . // identifier of the related sco_view + "interaction_id varchar(255) not null default ''," . // sco-specific, given by the sco + "interaction_type varchar(255) not null default ''," . // literal values, SCORM-specific (see p.63 of SCORM 1.2 RTE) + "weighting double not null default 0," . + "completion_time varchar(16) not null default ''," . // completion time for the interaction (timestamp in a day's time) - expected output format is scorm time + "correct_responses text not null default ''," . // actually a serialised array. See p.65 os SCORM 1.2 RTE) + "student_response text not null default ''," . // student response (format depends on type) + "result varchar(255) not null default ''," . // textual result + "latency varchar(16) not null default ''," . // time necessary for completion of the interaction + "PRIMARY KEY (c_id, id)" . + ")" . $charset_clause; + + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPIVINTERACTION` ADD INDEX (lp_iv_id) "; + Database::query($sql); + + $sql = "CREATE TABLE IF NOT EXISTS `$TABLELPIVOBJECTIVE`( + $add_to_all_tables" . + "id bigint unsigned auto_increment," . + "lp_iv_id bigint unsigned not null," . // identifier of the related sco_view + "order_id int unsigned not null default 0," . // internal order (0->...) given by Dokeos + "objective_id varchar(255) not null default ''," . // sco-specific, given by the sco + "score_raw float unsigned not null default 0," . // score + "score_max float unsigned not null default 0," . // max score + "score_min float unsigned not null default 0," . // min score + "status char(32) not null default 'not attempted', " . //status, just as sco status + "PRIMARY KEY (c_id, id) " . + ")" . $charset_clause; + + Database::query($sql); + + $sql = "ALTER TABLE `$TABLELPIVOBJECTIVE` ADD INDEX (lp_iv_id) "; + Database::query($sql); + + /* Blogs */ + + $sql = " + CREATE TABLE `" . $tbl_blogs . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - thematic_id int NOT NULL, - title varchar(255) NOT NULL, - description text NULL, - description_type int NOT NULL, - PRIMARY KEY (c_id, id) + blog_id int NOT NULL AUTO_INCREMENT , + blog_name varchar( 250 ) NOT NULL default '', + blog_subtitle varchar( 250 ) default NULL , + date_creation datetime NOT NULL default '0000-00-00 00:00:00', + visibility tinyint unsigned NOT NULL default 0, + session_id int default 0, + PRIMARY KEY (c_id, blog_id ) + )" . $charset_clause . " COMMENT = 'Table with blogs in this course';"; + + Database::query($sql); + + $sql = "ALTER TABLE `" . $tbl_blogs . "` ADD INDEX ( session_id ) "; + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_comments . "` ( + $add_to_all_tables + comment_id int NOT NULL AUTO_INCREMENT , + title varchar( 250 ) NOT NULL default '', + comment longtext NOT NULL , + author_id int NOT NULL default 0, + date_creation datetime NOT NULL default '0000-00-00 00:00:00', + blog_id int NOT NULL default 0, + post_id int NOT NULL default 0, + task_id int default NULL , + parent_comment_id int NOT NULL default 0, + PRIMARY KEY (c_id, comment_id ) + )" . $charset_clause . " COMMENT = 'Table with comments on posts in a blog';"; + + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_posts . "` ( + $add_to_all_tables + post_id int NOT NULL AUTO_INCREMENT , + title varchar( 250 ) NOT NULL default '', + full_text longtext NOT NULL , + date_creation datetime NOT NULL default '0000-00-00 00:00:00', + blog_id int NOT NULL default 0, + author_id int NOT NULL default 0, + PRIMARY KEY (c_id, post_id ) + )" . $charset_clause . " COMMENT = 'Table with posts / blog.';"; + + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_rating . "` ( + $add_to_all_tables + rating_id int NOT NULL AUTO_INCREMENT , + blog_id int NOT NULL default 0, + rating_type enum( 'post', 'comment' ) NOT NULL default 'post', + item_id int NOT NULL default 0, + user_id int NOT NULL default 0, + rating int NOT NULL default 0, + PRIMARY KEY (c_id, rating_id ) + )" . $charset_clause . " COMMENT = 'Table with ratings for post/comments in a certain blog';"; + + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_rel_user . "` ( + $add_to_all_tables + blog_id int NOT NULL default 0, + user_id int NOT NULL default 0, + PRIMARY KEY ( c_id, blog_id , user_id ) + )" . $charset_clause . " COMMENT = 'Table representing users subscribed to a blog';"; + + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_tasks . "` ( + $add_to_all_tables + task_id int NOT NULL AUTO_INCREMENT , + blog_id int NOT NULL default 0, + title varchar( 250 ) NOT NULL default '', + description text NOT NULL , + color varchar( 10 ) NOT NULL default '', + system_task tinyint unsigned NOT NULL default 0, + PRIMARY KEY (c_id, task_id ) + )" . $charset_clause . " COMMENT = 'Table with tasks for a blog';"; + + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_blogs_tasks_rel_user . "` ( + $add_to_all_tables + blog_id int NOT NULL default 0, + user_id int NOT NULL default 0, + task_id int NOT NULL default 0, + target_date date NOT NULL default '0000-00-00', + PRIMARY KEY (c_id, blog_id , user_id , task_id ) + )" . $charset_clause . " COMMENT = 'Table with tasks assigned to a user in a blog';"; + + Database::query($sql); + + $sql = "CREATE TABLE `" . $tbl_blogs_attachment . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + path varchar(255) NOT NULL COMMENT 'the real filename', + comment text, + size int NOT NULL default '0', + post_id int NOT NULL, + filename varchar(255) NOT NULL COMMENT 'the user s file name', + blog_id int NOT NULL, + comment_id int NOT NULL default '0', + PRIMARY KEY (c_id, id) )" . $charset_clause; - $result = Database::query($sql); - $sql = "ALTER TABLE `".$TBL_THEMATIC_PLAN."` ADD INDEX (thematic_id, description_type)"; - Database::query($sql); + Database::query($sql); - // thematic advance table - $sql = " - CREATE TABLE `".$TBL_THEMATIC_ADVANCE."` ( + $sql = " + CREATE TABLE `" . $tbl_permission_group . "` ( $add_to_all_tables - id int NOT NULL auto_increment, - thematic_id int NOT NULL, - attendance_id int NOT NULL DEFAULT 0, - content text NULL, - start_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - duration int NOT NULL DEFAULT 0, - done_advance tinyint NOT NULL DEFAULT 0, - PRIMARY KEY (c_id, id) + id int NOT NULL AUTO_INCREMENT , + group_id int NOT NULL default 0, + tool varchar( 250 ) NOT NULL default '', + action varchar( 250 ) NOT NULL default '', + PRIMARY KEY (c_id, id) )" . $charset_clause; - $result = Database::query($sql); - $sql = "ALTER TABLE `".$TBL_THEMATIC_ADVANCE."` ADD INDEX (thematic_id)"; - Database::query($sql); + Database::query($sql); + $sql = " + CREATE TABLE `" . $tbl_permission_user . "` ( + $add_to_all_tables + id int NOT NULL AUTO_INCREMENT , + user_id int NOT NULL default 0, + tool varchar( 250 ) NOT NULL default '', + action varchar( 250 ) NOT NULL default '', + PRIMARY KEY (c_id, id ) + )" . $charset_clause; - $sql = "CREATE TABLE IF NOT EXISTS " . $TBL_METADATA . " ( " . - $add_to_all_tables. - "eid VARCHAR(250) NOT NULL," . // entry-id, e.g. doc.1 - "mdxmltext TEXT default ''," . // MD-text, XML-formatted - "md5 CHAR(32) default ''," . // hash-validator - "htmlcache1 TEXT default ''," . // cached HTML, part 1 - "htmlcache2 TEXT default ''," . // cached HTML, part 2 - "indexabletext TEXT default ''," . // indexable for search - "PRIMARY KEY (c_id, eid) )".$charset_clause; + Database::query($sql); - Database::query($sql); + $sql = " + CREATE TABLE `" . $tbl_permission_task . "` ( + $add_to_all_tables + id int NOT NULL AUTO_INCREMENT, + task_id int NOT NULL default 0, + tool varchar( 250 ) NOT NULL default '', + action varchar( 250 ) NOT NULL default '', + PRIMARY KEY (c_id, id ) + )" . $charset_clause; - // New course tables for 1.10.x come here + Database::query($sql); + + $sql = " + CREATE TABLE `" . $tbl_role . "` ( + $add_to_all_tables + role_id int NOT NULL AUTO_INCREMENT, + role_name varchar( 250 ) NOT NULL default '', + role_comment text, + default_role tinyint default 0, + PRIMARY KEY (c_id, role_id) + )" . $charset_clause; + Database::query($sql); - return 0; -} + $sql = " + CREATE TABLE `" . $tbl_role_group . "` ( + $add_to_all_tables + id int NOT NULL AUTO_INCREMENT, + role_id int NOT NULL default 0, + scope varchar( 20 ) NOT NULL default 'course', + group_id int NOT NULL default 0, + PRIMARY KEY (id, c_id, group_id ) + )" . $charset_clause; -/** - * Returns a list of all files in the given course directory. The requested - * directory will be checked against a "checker" directory to avoid access to - * protected/unauthorized files - * @param string Complete path to directory we want to list - * @param array A list of files to which we want to add the files found - * @param string Type of base directory from which we want to recover the files - * @return array - * @assert (null,null,null) === false - * @assert ('abc',array(),'') === array() - */ -function browse_folders($path, $files, $media) { - if ($media == 'images') { - $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'; - } - if ($media == 'audio') { - $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/audio/'; - } - if ($media == 'flash') { - $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/flash/'; - } - if ($media == 'video') { - $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/video/'; - } - if ($media == 'certificates') { - $code_path = api_get_path(SYS_CODE_PATH).'default_course_document/certificates/'; - } - if (is_dir($path)) { - $handle = opendir($path); - while (false !== ($file = readdir($handle))) { - if (is_dir($path.$file) && strpos($file, '.') !== 0) { - $files[]['dir'] = str_replace($code_path, '', $path.$file.'/'); - $files = browse_folders($path.$file.'/', $files, $media); - } elseif (is_file($path.$file) && strpos($file, '.') !== 0) { - $files[]['file'] = str_replace($code_path, '', $path.$file); - } - } - } - return $files; -} + Database::query($sql); -/** - * Sorts pictures by type (used?) - * @param array List of files (sthg like array(0=>array('png'=>1))) - * @param string File type - * @return array The received array without files not matching type - * @assert (array(),null) === array() - */ -function sort_pictures($files, $type) { - $pictures = array(); - foreach ($files as $key => $value){ - if ($value[$type] != '') { - $pictures[][$type] = $value[$type]; - } - } - return $pictures; -} + $sql = " + CREATE TABLE `" . $tbl_role_permissions . "` ( + $add_to_all_tables + id int NOT NULL AUTO_INCREMENT, + role_id int NOT NULL default 0, + tool varchar( 250 ) NOT NULL default '', + action varchar( 50 ) NOT NULL default '', + default_perm tinyint NOT NULL default 0, + PRIMARY KEY (id, c_id, role_id, tool, action ) + )" . $charset_clause; -/** - * Fills the course repository with some example content. - * @param string Course directory name (without prefix/suffix). eg "ABC" - * @param bool Whether we want to fill it with example content or not - * @return array The (structured) list of files created - * @version 1.2 - * @deprecated this function has been merged into the fill_db_course - * @assert (null, null) === false - */ -function fill_course_repository($course_repository, $fill_with_exemplary_content = null) { + Database::query($sql); - if (is_null($fill_with_exemplary_content)) { - $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false'; - } + $sql = " + CREATE TABLE `" . $tbl_role_user . "` ( + $add_to_all_tables + role_id int NOT NULL default 0, + scope varchar( 20 ) NOT NULL default 'course', + user_id int NOT NULL default 0, + PRIMARY KEY ( c_id, role_id, user_id ) + )" . $charset_clause; - $default_document_array = array(); + Database::query($sql); - if ($fill_with_exemplary_content) { + /* + * Course Config Settings + * + */ - $sys_course_path = api_get_path(SYS_COURSE_PATH); + Database::query( + " + CREATE TABLE `" . $TABLESETTING . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + variable varchar(255) NOT NULL default '', + subkey varchar(255) default NULL, + type varchar(255) default NULL, + category varchar(255) default NULL, + value varchar(255) NOT NULL default '', + title varchar(255) NOT NULL default '', + comment varchar(255) default NULL, + subkeytext varchar(255) default NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause + ); - $perm = api_get_permissions_for_new_directories(); - $perm_file = api_get_permissions_for_new_files(); + /* + Survey + */ - $img_code_path = api_get_path(SYS_CODE_PATH).'default_course_document/images/'; - $audio_code_path = api_get_path(SYS_CODE_PATH).'default_course_document/audio/'; - $flash_code_path = api_get_path(SYS_CODE_PATH).'default_course_document/flash/'; - $video_code_path = api_get_path(SYS_CODE_PATH).'default_course_document/video/'; - $cert_code_path = api_get_path(SYS_CODE_PATH).'default_course_document/certificates/'; + $sql = "CREATE TABLE `" . $TABLESURVEY . "` ( + $add_to_all_tables + survey_id int unsigned NOT NULL auto_increment, + code varchar(20) default NULL, + title text default NULL, + subtitle text default NULL, + author varchar(20) default NULL, + lang varchar(20) default NULL, + avail_from date default NULL, + avail_till date default NULL, + is_shared char(1) default '1', + template varchar(20) default NULL, + intro text, + surveythanks text, + creation_date datetime NOT NULL default '0000-00-00 00:00:00', + invited int NOT NULL, + answered int NOT NULL, + invite_mail text NOT NULL, + reminder_mail text NOT NULL, + mail_subject VARCHAR( 255 ) NOT NULL, + anonymous enum('0','1') NOT NULL default '0', + access_condition TEXT DEFAULT NULL, + shuffle bool NOT NULL default '0', + one_question_per_page bool NOT NULL default '0', + survey_version varchar(255) NOT NULL default '', + parent_id int unsigned NOT NULL, + survey_type int NOT NULL default 0, + show_form_profile int NOT NULL default 0, + form_fields TEXT NOT NULL, + session_id int unsigned NOT NULL default 0, + visible_results int unsigned DEFAULT 0, + PRIMARY KEY (c_id, survey_id) + )" . $charset_clause; + $result = Database::query($sql); - $course_documents_folder_images = $sys_course_path.$course_repository.'/document/images/gallery/'; - $course_documents_folder_audio = $sys_course_path.$course_repository.'/document/audio/'; - $course_documents_folder_flash = $sys_course_path.$course_repository.'/document/flash/'; - $course_documents_folder_video = $sys_course_path.$course_repository.'/document/video/'; - $course_documents_folder_cert = $sys_course_path.$course_repository.'/document/certificates/'; + $sql = "ALTER TABLE `" . $TABLESURVEY . "` ADD INDEX ( session_id )"; + Database::query($sql); - /* Images */ - $files = array(); + $sql = "CREATE TABLE `" . $TABLESURVEYINVITATION . "` ( + $add_to_all_tables + survey_invitation_id int unsigned NOT NULL auto_increment, + survey_code varchar(20) NOT NULL, + user varchar(250) NOT NULL, + invitation_code varchar(250) NOT NULL, + invitation_date datetime NOT NULL, + reminder_date datetime NOT NULL, + answered int NOT NULL default 0, + session_id int UNSIGNED NOT NULL default 0, + PRIMARY KEY (c_id, survey_invitation_id) + )" . $charset_clause; + $result = Database::query($sql); - $files = browse_folders($img_code_path, $files, 'images'); + $sql = "CREATE TABLE `" . $TABLESURVEYQUESTION . "` ( + $add_to_all_tables + question_id int unsigned NOT NULL auto_increment, + survey_id int unsigned NOT NULL, + survey_question text NOT NULL, + survey_question_comment text NOT NULL, + type varchar(250) NOT NULL, + display varchar(10) NOT NULL, + sort int NOT NULL, + shared_question_id int, + max_value int, + survey_group_pri int unsigned NOT NULL default '0', + survey_group_sec1 int unsigned NOT NULL default '0', + survey_group_sec2 int unsigned NOT NULL default '0', + PRIMARY KEY (c_id, question_id) + )" . $charset_clause; + $result = Database::query($sql); - $pictures_array = sort_pictures($files, 'dir'); - $pictures_array = array_merge($pictures_array, sort_pictures($files, 'file')); + $sql = "CREATE TABLE `" . $TABLESURVEYQUESTIONOPTION . "` ( + $add_to_all_tables + question_option_id int unsigned NOT NULL auto_increment, + question_id int unsigned NOT NULL, + survey_id int unsigned NOT NULL, + option_text text NOT NULL, + sort int NOT NULL, + value int NOT NULL default '0', + PRIMARY KEY (c_id, question_option_id) + )" . $charset_clause; - if (!is_dir($course_documents_folder_images)) { - mkdir($course_documents_folder_images,$perm); - } + $result = Database::query($sql); - $handle = opendir($img_code_path); + $sql = "CREATE TABLE `" . $TABLESURVEYANSWER . "` ( + $add_to_all_tables + answer_id int unsigned NOT NULL auto_increment, + survey_id int unsigned NOT NULL, + question_id int unsigned NOT NULL, + option_id TEXT NOT NULL, + value int unsigned NOT NULL, + user varchar(250) NOT NULL, + PRIMARY KEY (c_id, answer_id) + )" . $charset_clause; + $result = Database::query($sql); + + $sql = "CREATE TABLE `" . $TABLESURVEYGROUP . "` ( + $add_to_all_tables + id int unsigned NOT NULL auto_increment, + name varchar(20) NOT NULL, + description varchar(255) NOT NULL, + survey_id int unsigned NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - foreach ($pictures_array as $key => $value) { - if ($value['dir'] != '') { - mkdir($course_documents_folder_images.$value['dir'], $perm); - } - if ($value['file'] != '') { - copy($img_code_path.$value['file'], $course_documents_folder_images.$value['file']); - chmod($course_documents_folder_images.$value['file'], $perm_file); - } - } + // Table glosary + $sql = "CREATE TABLE `" . $TBL_GLOSSARY . "` ( + $add_to_all_tables + glossary_id int unsigned NOT NULL auto_increment, + name varchar(255) NOT NULL, + description text not null, + display_order int, + session_id int default 0, + PRIMARY KEY (c_id, glossary_id) + )" . $charset_clause; + $result = Database::query($sql); - // Trainer thumbnails fix. + $sql = "ALTER TABLE `" . $TBL_GLOSSARY . "` ADD INDEX ( session_id ) "; + Database::query($sql); - $path_thumb = mkdir($course_documents_folder_images.'trainer/.thumbs', $perm); - $handle = opendir($img_code_path.'trainer/.thumbs/'); + // Table notebook + $sql = "CREATE TABLE `" . $TBL_NOTEBOOK . "` ( + $add_to_all_tables + notebook_id int unsigned NOT NULL auto_increment, + user_id int unsigned NOT NULL, + course varchar(40) not null, + session_id int NOT NULL default 0, + title varchar(255) NOT NULL, + description text NOT NULL, + creation_date datetime NOT NULL default '0000-00-00 00:00:00', + update_date datetime NOT NULL default '0000-00-00 00:00:00', + status int, + PRIMARY KEY (c_id, notebook_id) + )" . $charset_clause; + $result = Database::query($sql); - while (false !== ($file = readdir($handle))) { - if (is_file($img_code_path.'trainer/.thumbs/'.$file)) { - copy($img_code_path.'trainer/.thumbs/'.$file, $course_documents_folder_images.'trainer/.thumbs/'.$file); - chmod($course_documents_folder_images.'trainer/.thumbs/'.$file, $perm_file); - } - } + /* Attendance tool */ - $default_document_array['images'] = $pictures_array; + // Attendance table + $sql = " + CREATE TABLE `" . $TBL_ATTENDANCE . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + name text NOT NULL, + description TEXT NULL, + active tinyint NOT NULL default 1, + attendance_qualify_title varchar(255) NULL, + attendance_qualify_max int NOT NULL default 0, + attendance_weight float(6,2) NOT NULL default '0.0', + session_id int NOT NULL default 0, + locked int NOT NULL default 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - /* Audio */ - $files = array(); + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE . "` ADD INDEX (session_id)"; + Database::query($sql); - $files = browse_folders($audio_code_path, $files, 'audio'); + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE . "` ADD INDEX (active)"; + Database::query($sql); - $audio_array = sort_pictures($files, 'dir'); - $audio_array = array_merge($audio_array,sort_pictures($files, 'file')); + // Attendance sheet table + $sql = " + CREATE TABLE `" . $TBL_ATTENDANCE_SHEET . "` ( + $add_to_all_tables + user_id int NOT NULL, + attendance_calendar_id int NOT NULL, + presence tinyint NOT NULL DEFAULT 0, + PRIMARY KEY(c_id, user_id, attendance_calendar_id) + )" . $charset_clause; + $result = Database::query($sql); - if (!is_dir($course_documents_folder_audio)) { - mkdir($course_documents_folder_audio, $perm); - } + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE_SHEET . "` ADD INDEX (presence) "; + Database::query($sql); - $handle = opendir($audio_code_path); + // Attendance calendar table + $sql = " + CREATE TABLE `" . $TBL_ATTENDANCE_CALENDAR . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + attendance_id int NOT NULL , + date_time datetime NOT NULL default '0000-00-00 00:00:00', + done_attendance tinyint NOT NULL default 0, + PRIMARY KEY(c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - foreach ($audio_array as $key => $value){ + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE_CALENDAR . "` ADD INDEX (attendance_id)"; + Database::query($sql); - if ($value['dir'] != '') { - mkdir($course_documents_folder_audio.$value['dir'], $perm); - } - if ($value['file'] != '') { - copy($audio_code_path.$value['file'], $course_documents_folder_audio.$value['file']); - chmod($course_documents_folder_audio.$value['file'], $perm_file); - } + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE_CALENDAR . "` ADD INDEX (done_attendance)"; + Database::query($sql); - } - $default_document_array['audio'] = $audio_array; + // Attendance result table + $sql = " + CREATE TABLE `" . $TBL_ATTENDANCE_RESULT . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + user_id int NOT NULL, + attendance_id int NOT NULL, + score int NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - /* - * Flash - */ - $files = array(); + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE_RESULT . "` ADD INDEX (attendance_id)"; + Database::query($sql); - $files = browse_folders($flash_code_path, $files, 'flash'); + $sql = "ALTER TABLE `" . $TBL_ATTENDANCE_RESULT . "` ADD INDEX (user_id)"; + Database::query($sql); - $flash_array = sort_pictures($files, 'dir'); - $flash_array = array_merge($flash_array, sort_pictures($files, 'file')); + // attendance sheet log table + $sql = "CREATE TABLE `" . $TBL_ATTENDANCE_SHEET_LOG . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + attendance_id int NOT NULL DEFAULT 0, + lastedit_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + lastedit_type varchar(200) NOT NULL, + lastedit_user_id int NOT NULL DEFAULT 0, + calendar_date_value datetime NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql) or die(Database::error()); + + + // Thematic table + $sql = "CREATE TABLE `" . $TBL_THEMATIC . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + title varchar(255) NOT NULL, + content text NULL, + display_order int unsigned NOT NULL DEFAULT 0, + active tinyint NOT NULL DEFAULT 0, + session_id int NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - if (!is_dir($course_documents_folder_flash)) { - mkdir($course_documents_folder_flash, $perm); - } + $sql = "ALTER TABLE `" . $TBL_THEMATIC . "` ADD INDEX (active, session_id)"; + Database::query($sql); - $handle = opendir($flash_code_path); + // thematic plan table + $sql = "CREATE TABLE `" . $TBL_THEMATIC_PLAN . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + thematic_id int NOT NULL, + title varchar(255) NOT NULL, + description text NULL, + description_type int NOT NULL, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - foreach ($flash_array as $key => $value) { + $sql = "ALTER TABLE `" . $TBL_THEMATIC_PLAN . "` ADD INDEX (thematic_id, description_type)"; + Database::query($sql); - if ($value['dir'] != '') { - mkdir($course_documents_folder_flash.$value['dir'], $perm); - } - if ($value['file'] != '') { - copy($flash_code_path.$value['file'], $course_documents_folder_flash.$value['file']); - chmod($course_documents_folder_flash.$value['file'], $perm_file); - } + // thematic advance table + $sql = " + CREATE TABLE `" . $TBL_THEMATIC_ADVANCE . "` ( + $add_to_all_tables + id int NOT NULL auto_increment, + thematic_id int NOT NULL, + attendance_id int NOT NULL DEFAULT 0, + content text NULL, + start_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + duration int NOT NULL DEFAULT 0, + done_advance tinyint NOT NULL DEFAULT 0, + PRIMARY KEY (c_id, id) + )" . $charset_clause; + $result = Database::query($sql); - } - $default_document_array['flash'] = $flash_array; + $sql = "ALTER TABLE `" . $TBL_THEMATIC_ADVANCE . "` ADD INDEX (thematic_id)"; + Database::query($sql); - /* Video */ - $files = browse_folders($video_code_path, $files, 'video'); - $video_array = sort_pictures($files, 'dir'); - $video_array = array_merge($video_array, sort_pictures($files, 'file')); + $sql = "CREATE TABLE IF NOT EXISTS " . $TBL_METADATA . " ( " . + $add_to_all_tables . + "eid VARCHAR(250) NOT NULL," . // entry-id, e.g. doc.1 + "mdxmltext TEXT default ''," . // MD-text, XML-formatted + "md5 CHAR(32) default ''," . // hash-validator + "htmlcache1 TEXT default ''," . // cached HTML, part 1 + "htmlcache2 TEXT default ''," . // cached HTML, part 2 + "indexabletext TEXT default ''," . // indexable for search + "PRIMARY KEY (c_id, eid) )" . $charset_clause; - if (!is_dir($course_documents_folder_video)) { - mkdir($course_documents_folder_video, $perm); - } + Database::query($sql); - $handle = opendir($video_code_path); + // New course tables for 1.10.x come here - foreach ($video_array as $key => $value) { - if ($value['dir'] != '') { - @mkdir($course_documents_folder_video.$value['dir'], $perm); - } - if ($value['file'] != '') { - copy($video_code_path.$value['file'], $course_documents_folder_video.$value['file']); - chmod($course_documents_folder_video.$value['file'], $perm_file); - } + return 0; + } + /** + * Returns a list of all files in the given course directory. The requested + * directory will be checked against a "checker" directory to avoid access to + * protected/unauthorized files + * @param string Complete path to directory we want to list + * @param array A list of files to which we want to add the files found + * @param string Type of base directory from which we want to recover the files + * @return array + * @assert (null,null,null) === false + * @assert ('abc',array(),'') === array() + */ + public static function browse_folders($path, $files, $media) + { + if ($media == 'images') { + $code_path = api_get_path( + SYS_CODE_PATH + ) . 'default_course_document/images/'; } - $default_document_array['video'] = $video_array; - - /* Certificates */ - $files = browse_folders($cert_code_path, $files, 'certificates'); - $cert_array = sort_pictures($files, 'dir'); //only one file so far - $cert_array = array_merge($cert_array, sort_pictures($files, 'file')); - if (!is_dir($course_documents_folder_cert)) { - mkdir($course_documents_folder_cert, $perm); + if ($media == 'audio') { + $code_path = api_get_path( + SYS_CODE_PATH + ) . 'default_course_document/audio/'; } - $handle = opendir($cert_code_path); - foreach ($cert_array as $key => $value) { - - if ($value['dir'] != '') { - @mkdir($course_documents_folder_cert.$value['dir'], $perm); - } - if ($value['file'] != '') { - copy($cert_code_path.$value['file'], $course_documents_folder_cert.$value['file']); - chmod($course_documents_folder_cert.$value['file'], $perm_file); + if ($media == 'flash') { + $code_path = api_get_path( + SYS_CODE_PATH + ) . 'default_course_document/flash/'; + } + if ($media == 'video') { + $code_path = api_get_path( + SYS_CODE_PATH + ) . 'default_course_document/video/'; + } + if ($media == 'certificates') { + $code_path = api_get_path( + SYS_CODE_PATH + ) . 'default_course_document/certificates/'; + } + if (is_dir($path)) { + $handle = opendir($path); + while (false !== ($file = readdir($handle))) { + if (is_dir($path . $file) && strpos($file, '.') !== 0) { + $files[]['dir'] = str_replace( + $code_path, + '', + $path . $file . '/' + ); + $files = self::browse_folders( + $path . $file . '/', + $files, + $media + ); + } elseif (is_file($path . $file) && strpos($file, '.') !== 0) { + $files[]['file'] = str_replace( + $code_path, + '', + $path . $file + ); + } } - } - $default_document_array['cert'] = $cert_array; - - } - return $default_document_array; -} - -/** - * Function to convert a string from the language files to a string ready - * to insert into the database (escapes single quotes) - * @author Bart Mollet (bart.mollet@hogent.be) - * @param string $string The string to convert - * @return string The string converted to insert into the database - * @assert ('a\'b') === 'ab' - */ -function lang2db($string) { - $string = str_replace("\\'", "'", $string); - $string = Database::escape_string($string); - return $string; -} - -/** - * Fills the course database with some required content and example content. - * @param int Course (int) ID - * @param string Course directory name (e.g. 'ABC') - * @param string Language used for content (e.g. 'spanish') - * @param bool Whether to fill the course with example content - * @return bool False on error, true otherwise - * @version 1.2 - * @assert (null, '', '', null) === false - * @assert (1, 'ABC', null, null) === false - * @assert (1, 'TEST', 'spanish', true) === true - */ -function fill_db_course($course_id, $course_repository, $language, $fill_with_exemplary_content = null) { - if (is_null($fill_with_exemplary_content)) { - $fill_with_exemplary_content = api_get_setting('example_material_course_creation') != 'false'; - } - global $_configuration; - $course_id = intval($course_id); - - if (empty($course_id)) { - return false; - } - $now = api_get_utc_datetime(time()); - - $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST); - $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO); - $TABLEGROUPCATEGORIES = Database::get_course_table(TABLE_GROUP_CATEGORY); - $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY); - $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA); - $TABLETOOLANNOUNCEMENTS = Database::get_course_table(TABLE_ANNOUNCEMENT); - $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT); - $TABLETOOLLINK = Database::get_course_table(TABLE_LINK); - $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST); - $TABLEQUIZQUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION); - $TABLEQUIZQUESTIONLIST = Database::get_course_table(TABLE_QUIZ_QUESTION); - $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER); - $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING); - - $TABLEFORUMCATEGORIES = Database::get_course_table(TABLE_FORUM_CATEGORY); - $TABLEFORUMS = Database::get_course_table(TABLE_FORUM); - $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD); - $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST); - $TABLEGRADEBOOK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY); - $TABLEGRADEBOOKLINK = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK); - $TABLEGRADEBOOKCERT = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE); - - include api_get_path(SYS_CODE_PATH).'lang/english/create_course.inc.php'; - $file_to_include = api_get_path(SYS_CODE_PATH).'lang/'.$language.'/create_course.inc.php'; - - if (file_exists($file_to_include)) { - include $file_to_include; + return $files; } - $visible_for_all = 1; - $visible_for_course_admin = 0; - $visible_for_platform_admin = 2; - - /* Course tools */ - - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_DESCRIPTION . "','course_description/','info.gif','".string2binary(api_get_setting('course_create_active_tools', 'course_description')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CALENDAR_EVENT . "','calendar/agenda.php','agenda.gif','".string2binary(api_get_setting('course_create_active_tools', 'agenda')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DOCUMENT . "','document/document.php','folder_document.gif','".string2binary(api_get_setting('course_create_active_tools', 'documents')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LEARNPATH . "','newscorm/lp_controller.php','scorms.gif','".string2binary(api_get_setting('course_create_active_tools', 'learning_path')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LINK . "','link/link.php','links.gif','".string2binary(api_get_setting('course_create_active_tools', 'links')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_QUIZ . "','exercice/exercice.php','quiz.gif','".string2binary(api_get_setting('course_create_active_tools', 'quiz')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ANNOUNCEMENT . "','announcements/announcements.php','valves.gif','".string2binary(api_get_setting('course_create_active_tools', 'announcements')) . "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_FORUM . "','forum/index.php','forum.gif','".string2binary(api_get_setting('course_create_active_tools', 'forums')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DROPBOX . "','dropbox/index.php','dropbox.gif','".string2binary(api_get_setting('course_create_active_tools', 'dropbox')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_USER . "','user/user.php','members.gif','".string2binary(api_get_setting('course_create_active_tools', 'users')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GROUP . "','group/group.php','group.gif','".string2binary(api_get_setting('course_create_active_tools', 'groups')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CHAT . "','chat/chat.php','chat.gif','".string2binary(api_get_setting('course_create_active_tools', 'chat')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_STUDENTPUBLICATION . "','work/work.php','works.gif','".string2binary(api_get_setting('course_create_active_tools', 'student_publications')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SURVEY."','survey/survey_list.php','survey.gif','".string2binary(api_get_setting('course_create_active_tools', 'survey')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_WIKI ."','wiki/index.php','wiki.gif','".string2binary(api_get_setting('course_create_active_tools', 'wiki')) . "','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GRADEBOOK."','gradebook/index.php','gradebook.gif','".string2binary(api_get_setting('course_create_active_tools', 'gradebook')). "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GLOSSARY."','glossary/index.php','glossary.gif','".string2binary(api_get_setting('course_create_active_tools', 'glossary')). "','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_NOTEBOOK."','notebook/index.php','notebook.gif','".string2binary(api_get_setting('course_create_active_tools', 'notebook'))."','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ATTENDANCE."','attendance/index.php','attendance.gif','".string2binary(api_get_setting('course_create_active_tools', 'attendances'))."','0','squaregrey.gif','NO','_self','authoring','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_PROGRESS."','course_progress/index.php','course_progress.gif','".string2binary(api_get_setting('course_create_active_tools', 'course_progress'))."','0','squaregrey.gif','NO','_self','authoring','0')"); - - if (api_get_setting('service_visio', 'active') == 'true') { - $mycheck = api_get_setting('service_visio', 'visio_host'); - if (!empty($mycheck)) { - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CONFERENCE . "','conference/index.php?type=conference','visio_meeting.gif','1','0','squaregrey.gif','NO','_self','interaction','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CLASSROOM . "','conference/index.php?type=classroom','visio.gif','1','0','squaregrey.gif','NO','_self','authoring','0')"); + /** + * Sorts pictures by type (used?) + * @param array List of files (sthg like array(0=>array('png'=>1))) + * @param string File type + * @return array The received array without files not matching type + * @assert (array(),null) === array() + */ + public static function sort_pictures($files, $type) + { + $pictures = array(); + foreach ($files as $key => $value) { + if ($value[$type] != '') { + $pictures[][$type] = $value[$type]; + } } + return $pictures; } - if (api_get_setting('search_enabled') == 'true') { - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SEARCH. "','search/','info.gif','".string2binary(api_get_setting('course_create_active_tools', 'enable_search')) . "','0','search.gif','NO','_self','authoring','0')"); + /** + * Function to convert a string from the language files to a string ready + * to insert into the database (escapes single quotes) + * @author Bart Mollet (bart.mollet@hogent.be) + * @param string $string The string to convert + * @return string The string converted to insert into the database + * @assert ('a\'b') === 'ab' + */ + public static function lang2db($string) + { + $string = str_replace("\\'", "'", $string); + $string = Database::escape_string($string); + return $string; } - // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be) - $sql = "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . string2binary(api_get_setting('course_create_active_tools', 'blogs')) . "','1','squaregrey.gif','NO','_self','admin','0')"; - Database::query($sql); - // end of Smartblogs - - /* Course homepage tools for course admin only */ - - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_TRACKING . "','tracking/courseLog.php','statistics.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_COURSE_SETTING . "','course_info/infocours.php','reference.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')"); - Database::query("INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '".TOOL_COURSE_MAINTENANCE."','course_info/maintenance.php','backup.gif','$visible_for_course_admin','1','','NO','_self', 'admin','0')"); + /** + * Fills the course database with some required content and example content. + * @param int Course (int) ID + * @param string Course directory name (e.g. 'ABC') + * @param string Language used for content (e.g. 'spanish') + * @param bool Whether to fill the course with example content + * @return bool False on error, true otherwise + * @version 1.2 + * @assert (null, '', '', null) === false + * @assert (1, 'ABC', null, null) === false + * @assert (1, 'TEST', 'spanish', true) === true + */ + public static function fill_db_course( + $course_id, + $course_repository, + $language, + $fill_with_exemplary_content = null + ) { + if (is_null($fill_with_exemplary_content)) { + $fill_with_exemplary_content = api_get_setting( + 'example_material_course_creation' + ) != 'false'; + } + global $_configuration; + $course_id = intval($course_id); - $defaultEmailExerciseAlert = 1; - if (isset($_configuration['email_alert_manager_on_new_quiz'])) { - $defaultEmailExerciseAlert = intval($_configuration['email_alert_manager_on_new_quiz']); - } + if (empty($course_id)) { + return false; + } + $now = api_get_utc_datetime(time()); - /* course_setting table (courseinfo tool) */ + $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST); + $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO); + $TABLEGROUPCATEGORIES = Database::get_course_table( + TABLE_GROUP_CATEGORY + ); + $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY); + $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA); + $TABLETOOLANNOUNCEMENTS = Database::get_course_table( + TABLE_ANNOUNCEMENT + ); + $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT); + $TABLETOOLLINK = Database::get_course_table(TABLE_LINK); + $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST); + $TABLEQUIZQUESTION = Database::get_course_table( + TABLE_QUIZ_TEST_QUESTION + ); + $TABLEQUIZQUESTIONLIST = Database::get_course_table( + TABLE_QUIZ_QUESTION + ); + $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER); + $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_doc',0,'work')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_on_new_doc_dropbox',0,'dropbox')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_agenda',0,'agenda')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_announcement',0,'announcement')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_quiz', $defaultEmailExerciseAlert,'quiz')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_image_forum',1,'forum')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'course_theme','','theme')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_learning_path_theme','1','theme')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_open_chat_window',1,'chat')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_to_teacher_on_new_user_in_course',0,'registration')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_view_user_list',1,'user')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'display_info_advance_inside_homecourse',1,'thematic_advance')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_students_on_new_homework',0,'work')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_lp_auto_launch',0,'learning_path')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'pdf_export_watermark_text','','learning_path')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_public_certificates','','certificates')"); - Database::query("INSERT INTO $TABLESETTING (c_id, variable, value) VALUES ($course_id, 'documents_default_visibility', 'visible')"); + $TABLEFORUMCATEGORIES = Database::get_course_table( + TABLE_FORUM_CATEGORY + ); + $TABLEFORUMS = Database::get_course_table(TABLE_FORUM); + $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD); + $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST); + $TABLEGRADEBOOK = Database::get_main_table( + TABLE_MAIN_GRADEBOOK_CATEGORY + ); + $TABLEGRADEBOOKLINK = Database::get_main_table( + TABLE_MAIN_GRADEBOOK_LINK + ); + $TABLEGRADEBOOKCERT = Database::get_main_table( + TABLE_MAIN_GRADEBOOK_CERTIFICATE + ); + include api_get_path( + SYS_CODE_PATH + ) . 'lang/english/create_course.inc.php'; + $file_to_include = api_get_path( + SYS_CODE_PATH + ) . 'lang/' . $language . '/create_course.inc.php'; + if (file_exists($file_to_include)) { + include $file_to_include; + } - /* Course homepage tools for platform admin only */ + $visible_for_all = 1; + $visible_for_course_admin = 0; + $visible_for_platform_admin = 2; - /* Group tool */ + /* Course tools */ - Database::query("INSERT INTO $TABLEGROUPCATEGORIES (c_id, id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order ) - VALUES ($course_id, '2', '".lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');"); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_DESCRIPTION . "','course_description/','info.gif','" . self::string2binary( + api_get_setting( + 'course_create_active_tools', + 'course_description' + ) + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CALENDAR_EVENT . "','calendar/agenda.php','agenda.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'agenda') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DOCUMENT . "','document/document.php','folder_document.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'documents') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LEARNPATH . "','newscorm/lp_controller.php','scorms.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'learning_path') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_LINK . "','link/link.php','links.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'links') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_QUIZ . "','exercice/exercice.php','quiz.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'quiz') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ANNOUNCEMENT . "','announcements/announcements.php','valves.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'announcements') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_FORUM . "','forum/index.php','forum.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'forums') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_DROPBOX . "','dropbox/index.php','dropbox.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'dropbox') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_USER . "','user/user.php','members.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'users') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GROUP . "','group/group.php','group.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'groups') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_CHAT . "','chat/chat.php','chat.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'chat') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_STUDENTPUBLICATION . "','work/work.php','works.gif','" . self::string2binary( + api_get_setting( + 'course_create_active_tools', + 'student_publications' + ) + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SURVEY . "','survey/survey_list.php','survey.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'survey') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_WIKI . "','wiki/index.php','wiki.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'wiki') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GRADEBOOK . "','gradebook/index.php','gradebook.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'gradebook') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_GLOSSARY . "','glossary/index.php','glossary.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'glossary') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_NOTEBOOK . "','notebook/index.php','notebook.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'notebook') + ) . "','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_ATTENDANCE . "','attendance/index.php','attendance.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'attendances') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_PROGRESS . "','course_progress/index.php','course_progress.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'course_progress') + ) . "','0','squaregrey.gif','NO','_self','authoring','0')" + ); - /* Example Material */ - global $language_interface; - $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('platformLanguage'); + if (api_get_setting('service_visio', 'active') == 'true') { + $mycheck = api_get_setting('service_visio', 'visio_host'); + if (!empty($mycheck)) { + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CONFERENCE . "','conference/index.php?type=conference','visio_meeting.gif','1','0','squaregrey.gif','NO','_self','interaction','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_VISIO_CLASSROOM . "','conference/index.php?type=classroom','visio.gif','1','0','squaregrey.gif','NO','_self','authoring','0')" + ); + } + } + if (api_get_setting('search_enabled') == 'true') { + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_SEARCH . "','search/','info.gif','" . self::string2binary( + api_get_setting( + 'course_create_active_tools', + 'enable_search' + ) + ) . "','0','search.gif','NO','_self','authoring','0')" + ); + } - // Example material should be in the same language as the course is. - $language_interface_original = $language_interface; - $language_interface = $language; + // Smartblogs (Kevin Van Den Haute :: kevin@develop-it.be) + $sql = "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL,'" . TOOL_BLOGS . "','blog/blog_admin.php','blog_admin.gif','" . self::string2binary( + api_get_setting('course_create_active_tools', 'blogs') + ) . "','1','squaregrey.gif','NO','_self','admin','0')"; + Database::query($sql); + // end of Smartblogs - //Share folder - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/shared_folder','".get_lang('UserFolders')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + /* Course homepage tools for course admin only */ - //Chat folder - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/chat_files','".get_lang('ChatFiles')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_TRACKING . "','tracking/courseLog.php','statistics.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_SETTING . "','course_info/infocours.php','reference.gif','$visible_for_course_admin','1','', 'NO','_self','admin','0')" + ); + Database::query( + "INSERT INTO $tbl_course_homepage VALUES ($course_id, NULL, '" . TOOL_COURSE_MAINTENANCE . "','course_info/maintenance.php','backup.gif','$visible_for_course_admin','1','','NO','_self', 'admin','0')" + ); - $sys_course_path = api_get_path(SYS_COURSE_PATH); - $perm = api_get_permissions_for_new_directories(); - $perm_file = api_get_permissions_for_new_files(); + $defaultEmailExerciseAlert = 1; + if (isset($_configuration['email_alert_manager_on_new_quiz'])) { + $defaultEmailExerciseAlert = intval( + $_configuration['email_alert_manager_on_new_quiz'] + ); + } - $chat_path = $sys_course_path.$course_repository.'/document/chat_files'; + /* course_setting table (courseinfo tool) */ - if (!is_dir($chat_path)) { - @mkdir($chat_path, api_get_permissions_for_new_directories()); - } + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_doc',0,'work')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_on_new_doc_dropbox',0,'dropbox')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_agenda',0,'agenda')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_edit_announcement',0,'announcement')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_manager_on_new_quiz', $defaultEmailExerciseAlert,'quiz')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_image_forum',1,'forum')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'course_theme','','theme')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_learning_path_theme','1','theme')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_open_chat_window',1,'chat')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_to_teacher_on_new_user_in_course',0,'registration')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_user_view_user_list',1,'user')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'display_info_advance_inside_homecourse',1,'thematic_advance')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'email_alert_students_on_new_homework',0,'work')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'enable_lp_auto_launch',0,'learning_path')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'pdf_export_watermark_text','','learning_path')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable,value,category) VALUES ($course_id, 'allow_public_certificates','','certificates')" + ); + Database::query( + "INSERT INTO $TABLESETTING (c_id, variable, value) VALUES ($course_id, 'documents_default_visibility', 'visible')" + ); - /* Documents */ - if ($fill_with_exemplary_content) { - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id,path,title,filetype,size) VALUES ($course_id,'/images','".get_lang('Images')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + /* Course homepage tools for platform admin only */ - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/images/gallery','".get_lang('DefaultCourseImages')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + /* Group tool */ - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/audio','".get_lang('Audio')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + Database::query( + "INSERT INTO $TABLEGROUPCATEGORIES (c_id, id , title , description , max_student , self_reg_allowed , self_unreg_allowed , groups_per_user , display_order ) + VALUES ($course_id, '2', '" . self::lang2db( + get_lang('DefaultGroupCategory') + ) . "', '', '8', '0', '0', '0', '0');" + ); - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/flash','".get_lang('Flash')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + /* Example Material */ + global $language_interface; + $language_interface = !empty($language_interface) ? $language_interface : api_get_setting( + 'platformLanguage' + ); - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/video','".get_lang('Video')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/certificates','".get_lang('Certificates')."','folder','0')"); - $example_doc_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"); + // Example material should be in the same language as the course is. + $language_interface_original = $language_interface; + $language_interface = $language; - // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES + //Share folder + Database::query( + "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/shared_folder','" . get_lang( + 'UserFolders' + ) . "','folder','0')" + ); + $example_doc_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)" + ); - $folders_to_copy_from_default_course = array( - 'images', - 'audio', - 'flash', - 'video', - 'certificates', + //Chat folder + Database::query( + "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/chat_files','" . get_lang( + 'ChatFiles' + ) . "','folder','0')" ); + $example_doc_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)" + ); + + $sys_course_path = api_get_path(SYS_COURSE_PATH); + $perm = api_get_permissions_for_new_directories(); + $perm_file = api_get_permissions_for_new_files(); - $default_course_path = api_get_path(SYS_CODE_PATH).'default_course_document/'; + $chat_path = $sys_course_path . $course_repository . '/document/chat_files'; - $default_document_array = array(); - foreach ($folders_to_copy_from_default_course as $folder) { - $default_course_folder_path = $default_course_path.$folder.'/'; - $files = browse_folders($default_course_folder_path, array(), $folder); - $sorted_array = sort_pictures($files, 'dir'); - $sorted_array = array_merge($sorted_array, sort_pictures($files, 'file')); - $default_document_array[$folder] = $sorted_array; + if (!is_dir($chat_path)) { + @mkdir($chat_path, api_get_permissions_for_new_directories()); } - //echo '
    '; print_r($default_document_array);exit;
    +        /*    Documents   */
    +        if ($fill_with_exemplary_content) {
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id,path,title,filetype,size) VALUES ($course_id,'/images','" . get_lang(
    +                    'Images'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/images/gallery','" . get_lang(
    +                    'DefaultCourseImages'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/audio','" . get_lang(
    +                    'Audio'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/flash','" . get_lang(
    +                    'Flash'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/video','" . get_lang(
    +                    'Video'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            Database::query(
    +                "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'/certificates','" . get_lang(
    +                    'Certificates'
    +                ) . "','folder','0')"
    +            );
    +            $example_doc_id = Database:: insert_id();
    +            Database::query(
    +                "INSERT INTO $TABLEITEMPROPERTY  (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$example_doc_id,'DocumentAdded',1,0,NULL,0)"
    +            );
    +
    +            // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
    +
    +            $folders_to_copy_from_default_course = array(
    +                'images',
    +                'audio',
    +                'flash',
    +                'video',
    +                'certificates',
    +            );
    +
    +            $default_course_path = api_get_path(
    +                    SYS_CODE_PATH
    +                ) . 'default_course_document/';
    +
    +            $default_document_array = array();
    +            foreach ($folders_to_copy_from_default_course as $folder) {
    +                $default_course_folder_path = $default_course_path . $folder . '/';
    +                $files = self::browse_folders(
    +                    $default_course_folder_path,
    +                    array(),
    +                    $folder
    +                );
    +                $sorted_array = self::sort_pictures($files, 'dir');
    +                $sorted_array = array_merge(
    +                    $sorted_array,
    +                    self::sort_pictures($files, 'file')
    +                );
    +                $default_document_array[$folder] = $sorted_array;
    +            }
     
    -        //Light protection (adding index.html in every document folder)
    -        $htmlpage = "\n\n \n \n Not authorized\n  \n  \n  \n";
    +            //echo '
    '; print_r($default_document_array);exit;
    +
    +            //Light protection (adding index.html in every document folder)
    +            $htmlpage = "\n\n \n \n Not authorized\n  \n  \n  \n";
    +
    +            $example_cert_id = 0;
    +            if (is_array($default_document_array) && count(
    +                    $default_document_array
    +                ) > 0
    +            ) {
    +                foreach ($default_document_array as $media_type => $array_media) {
    +                    $path_documents = "/$media_type/";
    +
    +                    //hack until feature #5242 is implemented
    +                    if ($media_type == 'images') {
    +                        $media_type = 'images/gallery';
    +                        $images_folder = $sys_course_path . $course_repository . "/document/images/";
    +
    +                        if (!is_dir($images_folder)) {
    +                            //Creating index.html
    +                            mkdir($images_folder, $perm);
    +                            $fd = fopen($images_folder . 'index.html', 'w');
    +                            fwrite($fd, $htmlpage);
    +                            @chmod($images_folder . 'index.html', $perm_file);
    +                        }
    +                    }
     
    -        $example_cert_id = 0;
    -        if (is_array($default_document_array) && count($default_document_array) > 0) {
    -            foreach ($default_document_array as $media_type => $array_media) {
    -                $path_documents = "/$media_type/";
    +                    $course_documents_folder = $sys_course_path . $course_repository . "/document/$media_type/";
    +                    $default_course_path = api_get_path(
    +                            SYS_CODE_PATH
    +                        ) . 'default_course_document' . $path_documents;
     
    -                //hack until feature #5242 is implemented
    -                if ($media_type == 'images') {
    -                    $media_type = 'images/gallery';
    -                    $images_folder = $sys_course_path.$course_repository."/document/images/";
    +                    //echo 'try '.$course_documents_folder; echo '
    '; - if (!is_dir($images_folder)) { + if (!is_dir($course_documents_folder)) { //Creating index.html - mkdir($images_folder, $perm); - $fd = fopen($images_folder.'index.html', 'w'); + mkdir($course_documents_folder, $perm); + $fd = fopen( + $course_documents_folder . 'index.html', + 'w' + ); fwrite($fd, $htmlpage); - @chmod($images_folder.'index.html', $perm_file); + @chmod( + $course_documents_folder . 'index.html', + $perm_file + ); } - } - - $course_documents_folder = $sys_course_path.$course_repository."/document/$media_type/"; - $default_course_path = api_get_path(SYS_CODE_PATH).'default_course_document'.$path_documents; - - //echo 'try '.$course_documents_folder; echo '
    '; - - if (!is_dir($course_documents_folder)) { - //Creating index.html - mkdir($course_documents_folder, $perm); - $fd = fopen($course_documents_folder.'index.html', 'w'); - fwrite($fd, $htmlpage); - @chmod($course_documents_folder.'index.html', $perm_file); - } - - if (is_array($array_media) && count($array_media)>0) { - foreach ($array_media as $key => $value) { - if (isset($value['dir']) && !empty($value['dir'])) { - - if (!is_dir($course_documents_folder.$value['dir'])) { - //Creating folder - mkdir($course_documents_folder.$value['dir'], $perm); - - //Creating index.html (for light protection) - $index_html = $course_documents_folder.$value['dir'].'/index.html'; - $fd = fopen($index_html, 'w'); - fwrite($fd, $htmlpage); - @chmod($index_html, $perm_file); - //Inserting folder in the DB - $folder_path = substr($value['dir'], 0, strlen($value['dir']) - 1); - $temp = explode('/', $folder_path); - $title = $temp[count($temp)-1]; - - //hack until feature #5242 is implemented - if ($title == 'gallery') { - $title = get_lang('DefaultCourseImages'); - } - - if ($media_type == 'images/gallery') { - $folder_path = 'gallery/'.$folder_path; + if (is_array($array_media) && count($array_media) > 0) { + foreach ($array_media as $key => $value) { + if (isset($value['dir']) && !empty($value['dir'])) { + + if (!is_dir( + $course_documents_folder . $value['dir'] + ) + ) { + //Creating folder + mkdir( + $course_documents_folder . $value['dir'], + $perm + ); + + //Creating index.html (for light protection) + $index_html = $course_documents_folder . $value['dir'] . '/index.html'; + $fd = fopen($index_html, 'w'); + fwrite($fd, $htmlpage); + @chmod($index_html, $perm_file); + + //Inserting folder in the DB + $folder_path = substr( + $value['dir'], + 0, + strlen($value['dir']) - 1 + ); + $temp = explode('/', $folder_path); + $title = $temp[count($temp) - 1]; + + //hack until feature #5242 is implemented + if ($title == 'gallery') { + $title = get_lang( + 'DefaultCourseImages' + ); + } + + if ($media_type == 'images/gallery') { + $folder_path = 'gallery/' . $folder_path; + } + + Database::query( + "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents" . $folder_path . "','" . $title . "','folder','0')" + ); + $image_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,0)" + ); } - - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$folder_path."','".$title."','folder','0')"); - $image_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,0)"); } - } - - if (isset($value['file']) && !empty($value['file'])) { - if (!file_exists($course_documents_folder.$value['file'])) { - //Copying file - copy($default_course_path.$value['file'], $course_documents_folder.$value['file']); - chmod($course_documents_folder.$value['file'], $perm_file); - //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '
    '; - $temp = explode('/', $value['file']); - $file_size = filesize($course_documents_folder.$value['file']); - - //hack until feature #5242 is implemented - if ($media_type == 'images/gallery') { - $value["file"] = 'gallery/'.$value["file"]; - } - //Inserting file in the DB - Database::query("INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents".$value["file"]."','".$temp[count($temp)-1]."','file','$file_size')"); - $image_id = Database :: insert_id(); - if ($path_documents.$value['file'] == '/certificates/default.html') { - $example_cert_id = $image_id; + if (isset($value['file']) && !empty($value['file'])) { + if (!file_exists( + $course_documents_folder . $value['file'] + ) + ) { + //Copying file + copy( + $default_course_path . $value['file'], + $course_documents_folder . $value['file'] + ); + chmod( + $course_documents_folder . $value['file'], + $perm_file + ); + //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '
    '; + $temp = explode('/', $value['file']); + $file_size = filesize( + $course_documents_folder . $value['file'] + ); + + //hack until feature #5242 is implemented + if ($media_type == 'images/gallery') { + $value["file"] = 'gallery/' . $value["file"]; + } + + //Inserting file in the DB + Database::query( + "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size) VALUES ($course_id,'$path_documents" . $value["file"] . "','" . $temp[count( + $temp + ) - 1] . "','file','$file_size')" + ); + $image_id = Database:: insert_id(); + if ($path_documents . $value['file'] == '/certificates/default.html') { + $example_cert_id = $image_id; + } + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,1)" + ); } - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id,'document',1,NOW(),NOW(),$image_id,'DocumentAdded',1,0,NULL,1)"); } } } } } - } - - /* Agenda tool */ - - Database::query("INSERT INTO $TABLETOOLAGENDA VALUES ($course_id, NULL, '".lang2db(get_lang('AgendaCreationTitle')) . "', '".lang2db(get_lang('AgendaCreationContenu')) . "', now(), now(), NULL, 0, 0)"); - // We need to add the item properties too! - $insert_id = Database :: insert_id(); - $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),$insert_id,'AgendaAdded',1,0,NULL,1)"; - Database::query($sql); - - /* Links tool */ - - $add_google_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target) - VALUES ($course_id, 'http://www.google.com','Google','".lang2db(get_lang('Google')) . "','0','0','0','_self')"; - Database::query($add_google_link_sql); - - // We need to add the item properties too! - $insert_id = Database :: insert_id(); - $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) - VALUES ($course_id, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)"; - Database::query($sql); - - $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target) - VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','".lang2db(get_lang('Wikipedia')) . "','0','1','0','_self')"; - Database::query($add_wikipedia_link_sql); - - // We need to add the item properties too! - $insert_id = Database :: insert_id(); - $sql = "INSERT INTO $TABLEITEMPROPERTY (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)"; - Database::query($sql); - - /* Annoucement tool */ - - $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS (c_id, title,content,end_date,display_order,email_sent) - VALUES ($course_id, '".lang2db(get_lang('AnnouncementExampleTitle')) . "', '".lang2db(get_lang('AnnouncementEx')) . "', NOW(), '1','0')"; - Database::query($sql); - - // We need to add the item properties too! - $insert_id = Database :: insert_id(); - $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) - VALUES ($course_id, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)"; - Database::query($sql); - - /* Introduction text */ - - $intro_text='

    - Mr. Chamilo -

    '.lang2db(get_lang('IntroductionText')).'

    -

    '; - Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_COURSE_HOMEPAGE . "','".$intro_text."', 0)"); - Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','".lang2db(get_lang('IntroductionTwo')) . "', 0)"); - - // Wiki intro - $intro_wiki='
    '.lang2db(get_lang('IntroductionWiki')).'
    '; - Database::query("INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_WIKI . "','".$intro_wiki. "', 0)"); - - /* Exercise tool */ - - Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '1', '1', '".lang2db(get_lang('Ridiculise')) . "', '0', '".lang2db(get_lang('NoPsychology')) . "', '-5', '1')"); - Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '2', '1', '".lang2db(get_lang('AdmitError')) . "', '0', '".lang2db(get_lang('NoSeduction')) . "', '-5', '2')"); - Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '3', '1', '".lang2db(get_lang('Force')) . "', '1', '".lang2db(get_lang('Indeed')) . "', '5', '3')"); - Database::query("INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '4', '1', '".lang2db(get_lang('Contradiction')) . "', '1', '".lang2db(get_lang('NotFalse')) . "', '5', '4')"); - - $html=Database::escape_string('
    '.get_lang('Antique').'
    '); - - Database::query('INSERT INTO '.$TABLEQUIZ . - ' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' . - ' VALUES ('.$course_id.', "'.lang2db(get_lang('ExerciceEx')) . '",' . - ' "'.$html.'", "1", "0", "0", "1", "0")'); - $exercise_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEQUIZQUESTIONLIST (c_id, id, question, description, ponderation, position, type, picture, level) - VALUES ( '.$course_id.', '1', '".lang2db(get_lang('SocraticIrony')) . "', '".lang2db(get_lang('ManyAnswers')) . "', '10', '1', '2','',1)"); - Database::query("INSERT INTO $TABLEQUIZQUESTION (c_id, question_id, exercice_id, question_order) VALUES ('.$course_id.', 1,1,1)"); - - /* Forum tool */ - - Database::query("INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'".lang2db(get_lang('ExampleForumCategory'))."', '', 1, 0, 0)"); - $insert_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) - VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)"); - - Database::query("INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id ) - VALUES ($course_id, '".lang2db(get_lang('ExampleForum'))."', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)"); - $insert_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) - VALUES ($course_id, '".TOOL_FORUM."', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)"); - - Database::query("INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id) - VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)"); - $insert_id = Database :: insert_id(); - Database::query("INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) - VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)"); - - Database::query("INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '".lang2db(get_lang('ExampleThread'))."', '".lang2db(get_lang('ExampleThreadContent'))."', 1, 1, 1, '', NOW(), 0, 0, 1)"); - - /* Gradebook tool */ - $course = api_get_course_info_by_id($course_id); - $course_code = $course['code']; - // father gradebook - Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',0,100,0,75,NULL,$example_cert_id)"); - $gbid = Database :: insert_id(); - Database::query("INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',$gbid,100,1,75,NULL,$example_cert_id)"); - $gbid = Database :: insert_id(); - Database::query("INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked) VALUES (1,$exercise_id,1,'$course_code',$gbid,'$now',100,1,0)"); - } - //Installing plugins in course - $app_plugin = new AppPlugin(); - $app_plugin->install_course_plugins($course_id); + /* Agenda tool */ + + Database::query( + "INSERT INTO $TABLETOOLAGENDA VALUES ($course_id, NULL, '" . self::lang2db( + get_lang('AgendaCreationTitle') + ) . "', '" . self::lang2db( + get_lang('AgendaCreationContenu') + ) . "', now(), now(), NULL, 0, 0)" + ); + // We need to add the item properties too! + $insert_id = Database:: insert_id(); + $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ($course_id, '" . TOOL_CALENDAR_EVENT . "',1,NOW(),NOW(),$insert_id,'AgendaAdded',1,0,NULL,1)"; + Database::query($sql); + + /* Links tool */ + + $add_google_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target) + VALUES ($course_id, 'http://www.google.com','Google','" . self::lang2db( + get_lang('Google') + ) . "','0','0','0','_self')"; + Database::query($add_google_link_sql); + + // We need to add the item properties too! + $insert_id = Database:: insert_id(); + $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) + VALUES ($course_id, '" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)"; + Database::query($sql); + + $add_wikipedia_link_sql = "INSERT INTO $TABLETOOLLINK (c_id, url, title, description, category_id, display_order, on_homepage, target) + VALUES ($course_id, 'http://www.wikipedia.org','Wikipedia','" . self::lang2db( + get_lang('Wikipedia') + ) . "','0','1','0','_self')"; + Database::query($add_wikipedia_link_sql); + + // We need to add the item properties too! + $insert_id = Database:: insert_id(); + $sql = "INSERT INTO $TABLEITEMPROPERTY (tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) VALUES ('" . TOOL_LINK . "',1,NOW(),NOW(),$insert_id,'LinkAdded',1,0,NULL,1)"; + Database::query($sql); + + /* Annoucement tool */ + + $sql = "INSERT INTO $TABLETOOLANNOUNCEMENTS (c_id, title,content,end_date,display_order,email_sent) + VALUES ($course_id, '" . self::lang2db( + get_lang('AnnouncementExampleTitle') + ) . "', '" . self::lang2db( + get_lang('AnnouncementEx') + ) . "', NOW(), '1','0')"; + Database::query($sql); + + // We need to add the item properties too! + $insert_id = Database:: insert_id(); + $sql = "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) + VALUES ($course_id, '" . TOOL_ANNOUNCEMENT . "',1,NOW(),NOW(),$insert_id,'AnnouncementAdded',1,0,NULL,1)"; + Database::query($sql); + + /* Introduction text */ + + $intro_text = '

    + Mr. Chamilo +

    ' . self::lang2db(get_lang('IntroductionText')) . '

    +

    '; + Database::query( + "INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_COURSE_HOMEPAGE . "','" . $intro_text . "', 0)" + ); + Database::query( + "INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_STUDENTPUBLICATION . "','" . self::lang2db( + get_lang('IntroductionTwo') + ) . "', 0)" + ); + + // Wiki intro + $intro_wiki = '
    ' . self::lang2db( + get_lang('IntroductionWiki') + ) . '
    '; + Database::query( + "INSERT INTO $TABLEINTROS VALUES ($course_id, '" . TOOL_WIKI . "','" . $intro_wiki . "', 0)" + ); + + /* Exercise tool */ + + Database::query( + "INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '1', '1', '" . self::lang2db( + get_lang('Ridiculise') + ) . "', '0', '" . self::lang2db( + get_lang('NoPsychology') + ) . "', '-5', '1')" + ); + Database::query( + "INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '2', '1', '" . self::lang2db( + get_lang('AdmitError') + ) . "', '0', '" . self::lang2db( + get_lang('NoSeduction') + ) . "', '-5', '2')" + ); + Database::query( + "INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '3', '1', '" . self::lang2db( + get_lang('Force') + ) . "', '1', '" . self::lang2db(get_lang('Indeed')) . "', '5', '3')" + ); + Database::query( + "INSERT INTO $TABLEQUIZANSWERSLIST (c_id, id, question_id, answer, correct, comment, ponderation, position) VALUES ($course_id, '4', '1', '" . self::lang2db( + get_lang('Contradiction') + ) . "', '1', '" . self::lang2db(get_lang('NotFalse')) . "', '5', '4')" + ); + + $html = Database::escape_string( + '
    ' . get_lang( + 'Antique' + ) . '
    ' + ); + + Database::query( + 'INSERT INTO ' . $TABLEQUIZ . + ' (c_id, title, description, type, random, random_answers, active, results_disabled ) ' . + ' VALUES (' . $course_id . ', "' . self::lang2db( + get_lang('ExerciceEx') + ) . '",' . + ' "' . $html . '", "1", "0", "0", "1", "0")' + ); + $exercise_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEQUIZQUESTIONLIST (c_id, id, question, description, ponderation, position, type, picture, level) + VALUES ( '.$course_id.', '1', '" . self::lang2db( + get_lang('SocraticIrony') + ) . "', '" . self::lang2db( + get_lang('ManyAnswers') + ) . "', '10', '1', '2','',1)" + ); + Database::query( + "INSERT INTO $TABLEQUIZQUESTION (c_id, question_id, exercice_id, question_order) VALUES ('.$course_id.', 1,1,1)" + ); + + /* Forum tool */ + + Database::query( + "INSERT INTO $TABLEFORUMCATEGORIES VALUES ($course_id, 1,'" . self::lang2db( + get_lang('ExampleForumCategory') + ) . "', '', 1, 0, 0)" + ); + $insert_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) + VALUES ($course_id, 'forum_category',1,NOW(),NOW(),$insert_id,'ForumCategoryAdded',1,0,NULL,1)" + ); + + Database::query( + "INSERT INTO $TABLEFORUMS (c_id, forum_title, forum_comment, forum_threads,forum_posts,forum_last_post,forum_category, allow_anonymous, allow_edit,allow_attachments, allow_new_threads,default_view,forum_of_group,forum_group_public_private, forum_order,locked,session_id ) + VALUES ($course_id, '" . self::lang2db( + get_lang('ExampleForum') + ) . "', '', 0, 0, 0, 1, 0, 1, '0', 1, 'flat','0', 'public', 1, 0,0)" + ); + $insert_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) + VALUES ($course_id, '" . TOOL_FORUM . "', 1,NOW(),NOW(),$insert_id,'ForumAdded',1,0,NULL,1)" + ); + + Database::query( + "INSERT INTO $TABLEFORUMTHREADS (c_id, thread_id, thread_title, forum_id, thread_replies, thread_poster_id, thread_poster_name, thread_views, thread_last_post, thread_date, locked, thread_qualify_max, session_id) + VALUES ($course_id, 1, '" . self::lang2db( + get_lang('ExampleThread') + ) . "', 1, 0, 1, '', 0, 1, NOW(), 0, 10, 0)" + ); + $insert_id = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEITEMPROPERTY (c_id, tool,insert_user_id,insert_date,lastedit_date,ref,lastedit_type,lastedit_user_id,to_group_id,to_user_id,visibility) + VALUES ($course_id, 'forum_thread',1,NOW(),NOW(),$insert_id,'ForumThreadAdded',1,0,NULL,1)" + ); + + Database::query( + "INSERT INTO $TABLEFORUMPOSTS VALUES ($course_id, 1, '" . self::lang2db( + get_lang('ExampleThread') + ) . "', '" . self::lang2db( + get_lang('ExampleThreadContent') + ) . "', 1, 1, 1, '', NOW(), 0, 0, 1)" + ); + + /* Gradebook tool */ + $course = api_get_course_info_by_id($course_id); + $course_code = $course['code']; + // father gradebook + Database::query( + "INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',0,100,0,75,NULL,$example_cert_id)" + ); + $gbid = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEGRADEBOOK (name, description, user_id, course_code, parent_id, weight, visible, certif_min_score, session_id, document_id) VALUES ('$course_code','',1,'$course_code',$gbid,100,1,75,NULL,$example_cert_id)" + ); + $gbid = Database:: insert_id(); + Database::query( + "INSERT INTO $TABLEGRADEBOOKLINK (type, ref_id, user_id, course_code, category_id, created_at, weight, visible, locked) VALUES (1,$exercise_id,1,'$course_code',$gbid,'$now',100,1,0)" + ); + } - $language_interface = $language_interface_original; - return true; -} + //Installing plugins in course + $app_plugin = new AppPlugin(); + $app_plugin->install_course_plugins($course_id); -/** - * function string2binary converts the string "true" or "false" to the boolean true false (0 or 1) - * This is used for the Chamilo Config Settings as these store true or false as string - * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for - * the visibility of the tool) - * @param string $variable - * @author Patrick Cool, patrick.cool@ugent.be - * @assert ('true') === true - * @assert ('false') === false - */ -function string2binary($variable) { - if ($variable == 'true') { + $language_interface = $language_interface_original; return true; } - if ($variable == 'false') { - return false; - } -} -/** - * Function register_course to create a record in the course table of the main database - * @param array Course details (see code for details) - * @return int Created course ID - * @todo use an array called $params instead of lots of params - * @assert (null) === false - */ -function register_course($params) -{ - global $error_msg, $firstExpirationDelay; - - $title = $params['title']; - $code = $params['code']; - $visual_code = $params['visual_code']; - $directory = $params['directory']; - $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null; - //$description = $params['description']; - - $category_code = $params['course_category']; - $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting('platformLanguage'); - $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']); - $department_name = isset($params['department_name']) ? - $params['department_name'] : null; - $department_url = isset($params['department_url']) ? - $params['department_url'] : null; - $disk_quota = isset($params['disk_quota']) ? - $params['disk_quota'] : null; - - if (!isset($params['visibility'])) { - $default_course_visibility = api_get_setting('courses_default_creation_visibility'); - if (isset($default_course_visibility)) { - $visibility = $default_course_visibility; - } else { - $visibility = COURSE_VISIBILITY_OPEN_PLATFORM; + /** + * string2binary converts the string "true" or "false" to the boolean true false (0 or 1) + * This is used for the Chamilo Config Settings as these store true or false as string + * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for + * the visibility of the tool) + * @param string $variable + * @author Patrick Cool, patrick.cool@ugent.be + * @assert ('true') === true + * @assert ('false') === false + */ + public static function string2binary($variable) + { + if ($variable == 'true') { + return true; + } + if ($variable == 'false') { + return false; } - } else { - $visibility = $params['visibility']; } - $subscribe = isset($params['subscribe']) ? intval($params['subscribe']) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0); - $unsubscribe = isset($params['unsubscribe']) ? intval($params['unsubscribe']) : 0; - $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null; - $teachers = isset($params['teachers']) ? $params['teachers'] : null; - $status = isset($params['status']) ? $params['status'] : null; + /** + * Function register_course to create a record in the course table of the main database + * @param array Course details (see code for details) + * @return int Created course ID + * @todo use an array called $params instead of lots of params + * @assert (null) === false + */ + public static function register_course($params) + { + global $error_msg, $firstExpirationDelay; + + $title = $params['title']; + $code = $params['code']; + $visual_code = $params['visual_code']; + $directory = $params['directory']; + $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null; + //$description = $params['description']; + + $category_code = $params['course_category']; + $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting( + 'platformLanguage' + ); + $user_id = empty($params['user_id']) ? api_get_user_id() : intval( + $params['user_id'] + ); + $department_name = isset($params['department_name']) ? + $params['department_name'] : null; + $department_url = isset($params['department_url']) ? + $params['department_url'] : null; + $disk_quota = isset($params['disk_quota']) ? + $params['disk_quota'] : null; + + if (!isset($params['visibility'])) { + $default_course_visibility = api_get_setting( + 'courses_default_creation_visibility' + ); + if (isset($default_course_visibility)) { + $visibility = $default_course_visibility; + } else { + $visibility = COURSE_VISIBILITY_OPEN_PLATFORM; + } + } else { + $visibility = $params['visibility']; + } - $TABLECOURSE = Database :: get_main_table(TABLE_MAIN_COURSE); - $TABLECOURSUSER = Database :: get_main_table(TABLE_MAIN_COURSE_USER); + $subscribe = isset($params['subscribe']) ? intval( + $params['subscribe'] + ) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0); + $unsubscribe = isset($params['unsubscribe']) ? intval( + $params['unsubscribe'] + ) : 0; + $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null; + $teachers = isset($params['teachers']) ? $params['teachers'] : null; + $status = isset($params['status']) ? $params['status'] : null; + + $TABLECOURSE = Database:: get_main_table(TABLE_MAIN_COURSE); + $TABLECOURSUSER = Database:: get_main_table(TABLE_MAIN_COURSE_USER); + + $ok_to_register_course = true; + + // Check whether all the needed parameters are present. + if (empty($code)) { + $error_msg[] = 'courseSysCode is missing'; + $ok_to_register_course = false; + } + if (empty($visual_code)) { + $error_msg[] = 'courseScreenCode is missing'; + $ok_to_register_course = false; + } + if (empty($directory)) { + $error_msg[] = 'courseRepository is missing'; + $ok_to_register_course = false; + } - $ok_to_register_course = true; + if (empty($title)) { + $error_msg[] = 'title is missing'; + $ok_to_register_course = false; + } - // Check whether all the needed parameters are present. - if (empty($code)) { - $error_msg[] = 'courseSysCode is missing'; - $ok_to_register_course = false; - } - if (empty($visual_code)) { - $error_msg[] = 'courseScreenCode is missing'; - $ok_to_register_course = false; - } - if (empty($directory)) { - $error_msg[] = 'courseRepository is missing'; - $ok_to_register_course = false; - } + if (empty($expiration_date)) { + $expiration_date = api_get_utc_datetime( + time() + $firstExpirationDelay + ); + } else { + $expiration_date = api_get_utc_datetime($expiration_date); + } - if (empty($title)) { - $error_msg[] = 'title is missing'; - $ok_to_register_course = false; - } + if ($visibility < 0 || $visibility > 4) { + $error_msg[] = 'visibility is invalid'; + $ok_to_register_course = false; + } - if (empty($expiration_date)) { - $expiration_date = api_get_utc_datetime(time() + $firstExpirationDelay); - } else { - $expiration_date = api_get_utc_datetime($expiration_date); - } + if (empty($disk_quota)) { + $disk_quota = api_get_setting('default_document_quotum'); + } - if ($visibility < 0 || $visibility > 4) { - $error_msg[] = 'visibility is invalid'; - $ok_to_register_course = false; - } + $time = api_get_utc_datetime(); - if (empty($disk_quota)) { - $disk_quota = api_get_setting('default_document_quotum'); - } + if (stripos($department_url, 'http://') === false && stripos( + $department_url, + 'https://' + ) === false + ) { + $department_url = 'http://' . $department_url; + } + //just in case + if ($department_url == 'http://') { + $department_url = ''; + } + $course_id = 0; - $time = api_get_utc_datetime(); + if ($ok_to_register_course) { - if (stripos($department_url, 'http://') === false && stripos($department_url, 'https://') === false) { - $department_url = 'http://'.$department_url; - } - //just in case - if ($department_url == 'http://') { - $department_url = ''; - } - $course_id = 0; - - if ($ok_to_register_course) { - - // Here we must add 2 fields. - $sql = "INSERT INTO ".$TABLECOURSE . " SET - code = '".Database :: escape_string($code) . "', - directory = '".Database :: escape_string($directory) . "', - course_language = '".Database :: escape_string($course_language) . "', - title = '".Database :: escape_string($title) . "', - description = '".lang2db(get_lang('CourseDescription')) . "', - category_code = '".Database :: escape_string($category_code) . "', - visibility = '".$visibility . "', - show_score = '1', - disk_quota = '".intval($disk_quota) . "', - creation_date = '$time', - expiration_date = '".$expiration_date . "', - last_edit = '$time', - last_visit = NULL, - tutor_name = '".Database :: escape_string($tutor_name) . "', - department_name = '".Database :: escape_string($department_name) . "', - department_url = '".Database :: escape_string($department_url) . "', - subscribe = '".intval($subscribe) . "', - unsubscribe = '".intval($unsubscribe) . "', - visual_code = '".Database :: escape_string($visual_code) . "'"; - Database::query($sql); - $course_id = Database::insert_id(); - - if ($course_id) { - $sort = api_max_sort_value('0', api_get_user_id()); - // Default true - $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true; - if ($addTeacher) { - - $i_course_sort = CourseManager:: userCourseSort( - $user_id, + // Here we must add 2 fields. + $sql = "INSERT INTO " . $TABLECOURSE . " SET + code = '" . Database:: escape_string( $code - ); - - if (!empty($user_id)) { - $sql = "INSERT INTO " . $TABLECOURSUSER . " SET - course_code = '" . Database:: escape_string($code) . "', - user_id = '" . intval($user_id) . "', - status = '1', - role = '" . lang2db(get_lang('Professor')) . "', - tutor_id = '0', - sort = '" . ($i_course_sort) . "', - user_course_cat = '0'"; - Database::query($sql); + ) . "', + directory = '" . Database:: escape_string( + $directory + ) . "', + course_language = '" . Database:: escape_string( + $course_language + ) . "', + title = '" . Database:: escape_string( + $title + ) . "', + description = '" . self::lang2db( + get_lang('CourseDescription') + ) . "', + category_code = '" . Database:: escape_string( + $category_code + ) . "', + visibility = '" . $visibility . "', + show_score = '1', + disk_quota = '" . intval($disk_quota) . "', + creation_date = '$time', + expiration_date = '" . $expiration_date . "', + last_edit = '$time', + last_visit = NULL, + tutor_name = '" . Database:: escape_string( + $tutor_name + ) . "', + department_name = '" . Database:: escape_string( + $department_name + ) . "', + department_url = '" . Database:: escape_string( + $department_url + ) . "', + subscribe = '" . intval($subscribe) . "', + unsubscribe = '" . intval($unsubscribe) . "', + visual_code = '" . Database:: escape_string( + $visual_code + ) . "'"; + Database::query($sql); + $course_id = Database::insert_id(); + + if ($course_id) { + $sort = api_max_sort_value('0', api_get_user_id()); + // Default true + $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true; + if ($addTeacher) { + + $i_course_sort = CourseManager:: userCourseSort( + $user_id, + $code + ); + + if (!empty($user_id)) { + $sql = "INSERT INTO " . $TABLECOURSUSER . " SET + course_code = '" . Database:: escape_string( + $code + ) . "', + user_id = '" . intval($user_id) . "', + status = '1', + role = '" . self::lang2db( + get_lang('Professor') + ) . "', + tutor_id = '0', + sort = '" . ($i_course_sort) . "', + user_course_cat = '0'"; + Database::query($sql); + } } - } - if (!empty($teachers)) { - if (!is_array($teachers)) { - $teachers = array($teachers); - } - foreach ($teachers as $key) { - //just in case - if ($key == $user_id) { - continue; + if (!empty($teachers)) { + if (!is_array($teachers)) { + $teachers = array($teachers); } - if (empty($key)) { - continue; + foreach ($teachers as $key) { + //just in case + if ($key == $user_id) { + continue; + } + if (empty($key)) { + continue; + } + $sql = "INSERT INTO " . $TABLECOURSUSER . " SET + course_code = '" . Database::escape_string( + $code + ) . "', + user_id = '" . Database::escape_string( + $key + ) . "', + status = '1', + role = '', + tutor_id = '0', + sort = '" . ($sort + 1) . "', + user_course_cat = '0'"; + Database::query($sql); } - $sql = "INSERT INTO ".$TABLECOURSUSER . " SET - course_code = '".Database::escape_string($code) . "', - user_id = '".Database::escape_string($key) . "', - status = '1', - role = '', - tutor_id = '0', - sort = '". ($sort +1) . "', - user_course_cat = '0'"; - Database::query($sql); } - } - // Adding the course to an URL. - global $_configuration; - if ($_configuration['multiple_access_urls']) { - $url_id = 1; - if (api_get_current_access_url_id() != -1) { - $url_id = api_get_current_access_url_id(); + // Adding the course to an URL. + if (api_is_multiple_url_enabled()) { + $url_id = 1; + if (api_get_current_access_url_id() != -1) { + $url_id = api_get_current_access_url_id(); + } + UrlManager::add_course_to_url($code, $url_id); + } else { + UrlManager::add_course_to_url($code, 1); } - UrlManager::add_course_to_url($code, $url_id); - } else { - UrlManager::add_course_to_url($code, 1); - } - // Add event to the system log. - $user_id = api_get_user_id(); - event_system(LOG_COURSE_CREATE, LOG_COURSE_CODE, $code, api_get_utc_datetime(), $user_id, $code); - - $send_mail_to_admin = api_get_setting('send_email_to_admin_when_create_course'); - - // @todo Improve code to send to all current portal administrators. - if ($send_mail_to_admin == 'true') { - $siteName = api_get_setting('siteName'); - $recipient_email = api_get_setting('emailAdministrator'); - $recipient_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')); - $iname = api_get_setting('Institution'); - $subject = get_lang('NewCourseCreatedIn').' '.$siteName.' - '.$iname; - $message = get_lang('Dear').' '.$recipient_name.",\n\n".get_lang('MessageOfNewCourseToAdmin').' '.$siteName.' - '.$iname."\n"; - $message .= get_lang('CourseName').' '.$title."\n"; - $message .= get_lang('Category').' '.$category_code."\n"; - $message .= get_lang('Tutor').' '.$tutor_name."\n"; - $message .= get_lang('Language').' '.$course_language; - - $userInfo = api_get_user_info($user_id); - $plugin = new AppPlugin(); - $additionalParameters = array( - 'smsType' => constant($plugin->getSMSPluginName().'::NEW_COURSE_BEEN_CREATED'), - 'userId' => $user_id, - 'courseName' => $title, - 'creatorUsername' => $userInfo['username'] + // Add event to the system log. + $user_id = api_get_user_id(); + Event::addEvent( + LOG_COURSE_CREATE, + LOG_COURSE_CODE, + $code, + api_get_utc_datetime(), + $user_id, + $code ); - api_mail_html( - $recipient_name, - $recipient_email, - $subject, - $message, - $siteName, - $recipient_email, - null, - null, - null, - $additionalParameters + $send_mail_to_admin = api_get_setting( + 'send_email_to_admin_when_create_course' ); + + // @todo Improve code to send to all current portal administrators. + if ($send_mail_to_admin == 'true') { + $siteName = api_get_setting('siteName'); + $recipient_email = api_get_setting('emailAdministrator'); + $recipient_name = api_get_person_name( + api_get_setting('administratorName'), + api_get_setting('administratorSurname') + ); + $iname = api_get_setting('Institution'); + $subject = get_lang( + 'NewCourseCreatedIn' + ) . ' ' . $siteName . ' - ' . $iname; + $message = get_lang( + 'Dear' + ) . ' ' . $recipient_name . ",\n\n" . get_lang( + 'MessageOfNewCourseToAdmin' + ) . ' ' . $siteName . ' - ' . $iname . "\n"; + $message .= get_lang('CourseName') . ' ' . $title . "\n"; + $message .= get_lang( + 'Category' + ) . ' ' . $category_code . "\n"; + $message .= get_lang('Tutor') . ' ' . $tutor_name . "\n"; + $message .= get_lang('Language') . ' ' . $course_language; + + $userInfo = api_get_user_info($user_id); + $plugin = new AppPlugin(); + $additionalParameters = array( + 'smsType' => constant( + $plugin->getSMSPluginName( + ) . '::NEW_COURSE_BEEN_CREATED' + ), + 'userId' => $user_id, + 'courseName' => $title, + 'creatorUsername' => $userInfo['username'] + ); + + api_mail_html( + $recipient_name, + $recipient_email, + $subject, + $message, + $siteName, + $recipient_email, + null, + null, + null, + $additionalParameters + ); + } } } - } - return $course_id; -} + return $course_id; + } -/** - * Extract properties of the files from a ZIP package, write them to disk and - * return them as an array. - * @todo this function seems not to be used - * @param string Absolute path to the ZIP file - * @param bool Whether the ZIP file is compressed (not implemented). Defaults to TRUE. - * @return array List of files properties from the ZIP package - * @assert (null) === false - */ -function readPropertiesInArchive($archive, $is_compressed = true) { - include api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php'; - debug::printVar(dirname($archive), 'Zip : '); - $uid = api_get_user_id(); - /* - string tempnam (string dir, string prefix) - tempnam() creates a unique temporary file in the dir directory. If the - directory doesn't existm tempnam() will generate a filename in the system's - temporary directory. - Before PHP 4.0.6, the behaviour of tempnam() depended of the underlying OS. - Under Windows, the "TMP" environment variable replaces the dir parameter; - under Linux, the "TMPDIR" environment variable has priority, while for the - OSes based on system V R4, the dir parameter will always be used if the - directory which it represents exists. Consult your documentation for more - details. - tempnam() returns the temporary filename, or the string NULL upon failure. - */ - $zip_file = new PclZip($archive); - $tmp_dir_name = dirname($archive) . '/tmp'.$uid.uniqid($uid); - if (mkdir($tmp_dir_name, api_get_permissions_for_new_directories(), true)) { - $unzipping_state = $zip_file->extract($tmp_dir_name); - } else { - die ('mkdir failed'); + /** + * Extract properties of the files from a ZIP package, write them to disk and + * return them as an array. + * @todo this function seems not to be used + * @param string Absolute path to the ZIP file + * @param bool Whether the ZIP file is compressed (not implemented). Defaults to TRUE. + * @return array List of files properties from the ZIP package + * @deprecated seems not to be used + * @assert (null) === false + */ + public static function readPropertiesInArchive($archive, $is_compressed = true) + { + include api_get_path(LIBRARY_PATH) . 'pclzip/pclzip.lib.php'; + debug::printVar(dirname($archive), 'Zip : '); + $uid = api_get_user_id(); + /* + string tempnam (string dir, string prefix) + tempnam() creates a unique temporary file in the dir directory. If the + directory doesn't existm tempnam() will generate a filename in the system's + temporary directory. + Before PHP 4.0.6, the behaviour of tempnam() depended of the underlying OS. + Under Windows, the "TMP" environment variable replaces the dir parameter; + under Linux, the "TMPDIR" environment variable has priority, while for the + OSes based on system V R4, the dir parameter will always be used if the + directory which it represents exists. Consult your documentation for more + details. + tempnam() returns the temporary filename, or the string NULL upon failure. + */ + $zip_file = new PclZip($archive); + $tmp_dir_name = dirname($archive) . '/tmp' . $uid . uniqid($uid); + if (mkdir( + $tmp_dir_name, + api_get_permissions_for_new_directories(), + true + )) { + $unzipping_state = $zip_file->extract($tmp_dir_name); + } else { + die ('mkdir failed'); + } + $path_to_archive_ini = dirname($tmp_dir_name) . '/archive.ini'; + //echo $path_to_archive_ini; + $course_properties = parse_ini_file($path_to_archive_ini); + rmdir($tmp_dir_name); + return $course_properties; } - $path_to_archive_ini = dirname($tmp_dir_name) . '/archive.ini'; - //echo $path_to_archive_ini; - $course_properties = parse_ini_file($path_to_archive_ini); - rmdir($tmp_dir_name); - return $course_properties; } diff --git a/main/inc/lib/add_courses_to_session_functions.lib.php b/main/inc/lib/add_courses_to_session_functions.lib.php index 24ee992f63..55129097f4 100755 --- a/main/inc/lib/add_courses_to_session_functions.lib.php +++ b/main/inc/lib/add_courses_to_session_functions.lib.php @@ -1,9 +1,6 @@ + * + * @param string name of recipient + * @param string email of recipient + * @param string email subject + * @param string email body + * @param string sender name + * @param string sender e-mail + * @param array extra headers in form $headers = array($name => $value) to allow parsing + * @param array data file (path and filename) + * @param array data to attach a file (optional) + * @param bool True for attaching a embedded file inside content html (optional) + * @return returns true if mail was sent + * @see class.phpmailer.php + */ +function api_mail_html( + $recipient_name, + $recipient_email, + $subject, + $message, + $senderName = '', + $senderEmail = '', + $extra_headers = array(), + $data_file = array(), + $embedded_image = false, + $additionalParameters = array() +) { + global $platform_email; + + $mail = new PHPMailer(); + $mail->Mailer = $platform_email['SMTP_MAILER']; + $mail->Host = $platform_email['SMTP_HOST']; + $mail->Port = $platform_email['SMTP_PORT']; + $mail->CharSet = $platform_email['SMTP_CHARSET']; + // Stay far below SMTP protocol 980 chars limit. + $mail->WordWrap = 200; + + if ($platform_email['SMTP_AUTH']) { + $mail->SMTPAuth = 1; + $mail->Username = $platform_email['SMTP_USER']; + $mail->Password = $platform_email['SMTP_PASS']; + } + + // 5 = low, 1 = high + $mail->Priority = 3; + $mail->SMTPKeepAlive = true; + + // Default values + $notification = new Notification(); + $defaultEmail = $notification->getDefaultPlatformSenderEmail(); + $defaultName = $notification->getDefaultPlatformSenderName(); + + // Error to admin. + $mail->AddCustomHeader('Errors-To: '.$defaultEmail); + + // If the parameter is set don't use the admin. + $senderName = !empty($senderName) ? $senderName : $defaultEmail; + $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultName; + + // Reply to first + if (isset($extra_headers['reply_to'])) { + $mail->AddReplyTo( + $extra_headers['reply_to']['mail'], + $extra_headers['reply_to']['name'] + ); + $mail->Sender = $extra_headers['reply_to']['mail']; + unset($extra_headers['reply_to']); + } + + $mail->SetFrom($senderEmail, $senderName); + + $mail->Subject = $subject; + $mail->AltBody = strip_tags( + str_replace('
    ', "\n", api_html_entity_decode($message)) + ); + + // Send embedded image. + if ($embedded_image) { + // Get all images html inside content. + preg_match_all("/]*)[\"\']?[^>]*>/i", $message, $m); + // Prepare new tag images. + $new_images_html = array(); + $i = 1; + if (!empty($m[1])) { + foreach ($m[1] as $image_path) { + $real_path = realpath($image_path); + $filename = basename($image_path); + $image_cid = $filename.'_'.$i; + $encoding = 'base64'; + $image_type = mime_content_type($real_path); + $mail->AddEmbeddedImage( + $real_path, + $image_cid, + $filename, + $encoding, + $image_type + ); + $new_images_html[] = ''; + $i++; + } + } + + // Replace origin image for new embedded image html. + $x = 0; + if (!empty($m[0])) { + foreach ($m[0] as $orig_img) { + $message = str_replace($orig_img, $new_images_html[$x], $message); + $x++; + } + } + } + $message = str_replace(array("\n\r", "\n", "\r"), '
    ', $message); + $mail->Body = ''.$message.''; + + // Attachment ... + if (!empty($data_file)) { + $mail->AddAttachment($data_file['path'], $data_file['filename']); + } + + // Only valid addresses are accepted. + if (is_array($recipient_email)) { + foreach ($recipient_email as $dest) { + if (api_valid_email($dest)) { + $mail->AddAddress($dest, $recipient_name); + } + } + } else { + if (api_valid_email($recipient_email)) { + $mail->AddAddress($recipient_email, $recipient_name); + } else { + return 0; + } + } + + if (is_array($extra_headers) && count($extra_headers) > 0) { + foreach ($extra_headers as $key => $value) { + switch (strtolower($key)) { + case 'encoding': + case 'content-transfer-encoding': + $mail->Encoding = $value; + break; + case 'charset': + $mail->Charset = $value; + break; + case 'contenttype': + case 'content-type': + $mail->ContentType = $value; + break; + default: + $mail->AddCustomHeader($key.':'.$value); + break; + } + } + } else { + if (!empty($extra_headers)) { + $mail->AddCustomHeader($extra_headers); + } + } + + // WordWrap the html body (phpMailer only fixes AltBody) FS#2988 + $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap); + // Send the mail message. + if (!$mail->Send()) { + error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'
    '); + return 0; + } + + $plugin = new AppPlugin(); + $installedPluginsList = $plugin->getInstalledPluginListObject(); + foreach ($installedPluginsList as $installedPlugin) { + if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) { + $className = str_replace("Plugin", "", get_class($installedPlugin)); + $smsObject = new $className; + $smsObject->send($additionalParameters); + } + } + + // Clear all the addresses. + $mail->ClearAddresses(); + return 1; +} diff --git a/main/inc/lib/attendance.lib.php b/main/inc/lib/attendance.lib.php index e3987972e2..846eedf301 100755 --- a/main/inc/lib/attendance.lib.php +++ b/main/inc/lib/attendance.lib.php @@ -1520,6 +1520,7 @@ class Attendance $sessionId = api_get_session_id(); $courseCode = api_get_course_id(); + $courseId = api_get_course_int_id(); if (!empty($sessionId)) { $users = CourseManager:: get_user_list_from_course_code( $courseCode, @@ -1558,7 +1559,7 @@ class Attendance } $accessData = CourseManager::getCourseAccessPerCourseAndSession( - $courseCode, + $courseId, $sessionId, $dateTimeStartOriginal->format('Y-m-d H:i:s'), $dateTimeEnd->format('Y-m-d H:i:s') diff --git a/main/inc/lib/auth.lib.php b/main/inc/lib/auth.lib.php index 6ad0825761..b8a848829f 100755 --- a/main/inc/lib/auth.lib.php +++ b/main/inc/lib/auth.lib.php @@ -515,7 +515,11 @@ class Auth while ($row = Database::fetch_array($result_find)) { $row['registration_code'] = !empty($row['registration_code']); $count_users = count(CourseManager::get_user_list_from_course_code($row['code'])); - $count_connections_last_month = Tracking::get_course_connections_count($row['code'], 0, api_get_utc_datetime(time() - (30 * 86400))); + $count_connections_last_month = Tracking::get_course_connections_count( + $row['id'], + 0, + api_get_utc_datetime(time() - (30 * 86400)) + ); $point_info = CourseManager::get_course_ranking($row['id'], 0); diff --git a/main/inc/lib/blog.lib.php b/main/inc/lib/blog.lib.php index 2a77cde331..6078c80c17 100755 --- a/main/inc/lib/blog.lib.php +++ b/main/inc/lib/blog.lib.php @@ -15,7 +15,8 @@ * Class * @package chamilo.blogs */ -class Blog { +class Blog +{ /** * Get the title of a blog * @author Toon Keppens @@ -227,19 +228,18 @@ class Blog { * @param String $full_text * @param Integer $blog_id */ - public static function create_post ($title, $full_text, $file_comment, $blog_id) { - global $_user; - global $_course; + public static function create_post($title, $full_text, $file_comment, $blog_id) + { + $_user = api_get_user_info(); + $_course = api_get_course_info(); + $course_id = api_get_course_int_id(); $blog_table_attachment = Database::get_course_table(TABLE_BLOGS_ATTACHMENT); $upload_ok=true; $has_attachment=false; - $current_date=date('Y-m-d H:i:s',time()); - - $course_id = api_get_course_int_id(); + $current_date = api_get_utc_datetime(); - - if(!empty($_FILES['user_upload']['name'])) { + if (!empty($_FILES['user_upload']['name'])) { $upload_ok = process_uploaded_file($_FILES['user_upload']); $has_attachment=true; } @@ -270,16 +270,16 @@ class Blog { Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension')); } else { $new_file_name = uniqid(''); - $new_path=$updir.'/'.$new_file_name; + $new_path = $updir.'/'.$new_file_name; $result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path); - $comment=Database::escape_string($file_comment); + $comment = Database::escape_string($file_comment); // Storing the attachments if any if ($result) { - $sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '. - "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."', '".$blog_id."', '0' )"; - $result=Database::query($sql); - $message.=' / '.get_lang('AttachmentUpload'); + $sql = 'INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size, blog_id,comment_id) '. + "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$last_post_id."', '".intval($_FILES['user_upload']['size'])."', '".$blog_id."', '0' )"; + Database::query($sql); + //Display::display_confirmation_message(get_lang('AttachmentUpload')); } } } @@ -346,9 +346,10 @@ class Blog { * @param Integer $post_id * @param Integer $parent_id */ - public static function create_comment($title, $full_text, $file_comment,$blog_id, $post_id, $parent_id, $task_id = 'NULL') { - global $_user; - global $_course; + public static function create_comment($title, $full_text, $file_comment, $blog_id, $post_id, $parent_id, $task_id = 'NULL') + { + $_user = api_get_user_info(); + $_course = api_get_course_info(); global $blog_table_attachment; $upload_ok = true; @@ -356,7 +357,7 @@ class Blog { $current_date = date('Y-m-d H:i:s',time()); $course_id = api_get_course_int_id(); - if(!empty($_FILES['user_upload']['name'])) { + if (!empty($_FILES['user_upload']['name'])) { $upload_ok = process_uploaded_file($_FILES['user_upload']); $has_attachment=true; } @@ -371,10 +372,7 @@ class Blog { Database::query($sql); // Empty post values, or they are shown on the page again - $_POST['comment_title'] = ""; - $_POST['comment_text'] = ""; - - $last_id=Database::insert_id(); + $last_id = Database::insert_id(); if ($has_attachment) { $courseDir = $_course['path'].'/upload/blog'; @@ -382,29 +380,28 @@ class Blog { $updir = $sys_course_path.$courseDir; // Try to add an extension to the file if it hasn't one - $new_file_name = add_ext_on_mime(stripslashes($_FILES['user_upload']['name']), $_FILES['user_upload']['type']); + $new_file_name = add_ext_on_mime( + stripslashes($_FILES['user_upload']['name']), + $_FILES['user_upload']['type'] + ); // user's file name $file_name =$_FILES['user_upload']['name']; - if (!filter_extension($new_file_name)) - { + if (!filter_extension($new_file_name)) { Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension')); - } - else - { + } else { $new_file_name = uniqid(''); $new_path=$updir.'/'.$new_file_name; $result= @move_uploaded_file($_FILES['user_upload']['tmp_name'], $new_path); - $comment=Database::escape_string($file_comment); + $comment = Database::escape_string($file_comment); // Storing the attachments if any - if ($result) - { + if ($result) { $sql='INSERT INTO '.$blog_table_attachment.'(c_id, filename,comment, path, post_id,size,blog_id,comment_id) '. "VALUES ($course_id, '".Database::escape_string($file_name)."', '".$comment."', '".Database::escape_string($new_file_name)."' , '".$post_id."', '".$_FILES['user_upload']['size']."', '".$blog_id."', '".$last_id."' )"; - $result=Database::query($sql); - $message.=' / '.get_lang('AttachmentUpload'); + Database::query($sql); + //$message.=' / '.get_lang('AttachmentUpload'); } } } @@ -417,24 +414,25 @@ class Blog { * @param Integer $blog_id * @param Integer $comment_id */ - public static function delete_comment ($blog_id, $post_id, $comment_id) { - // Init + public static function delete_comment ($blog_id, $post_id, $comment_id) + { $tbl_blogs_comments = Database::get_course_table(TABLE_BLOGS_COMMENTS); $tbl_blogs_rating = Database::get_course_table(TABLE_BLOGS_RATING); $blog_id = intval($blog_id); $post_id = intval($post_id); $comment_id = intval($comment_id); - $course_id = api_get_course_int_id(); - delete_all_blog_attachment($blog_id,$post_id,$comment_id); + delete_all_blog_attachment($blog_id, $post_id, $comment_id); // Delete ratings on this comment - $sql = "DELETE FROM $tbl_blogs_rating WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND item_id = '".(int)$comment_id."' AND rating_type = 'comment'"; + $sql = "DELETE FROM $tbl_blogs_rating + WHERE c_id = $course_id AND blog_id = '".$blog_id."' AND item_id = '".$comment_id."' AND rating_type = 'comment'"; Database::query($sql); // select comments that have the selected comment as their parent - $sql = "SELECT comment_id FROM $tbl_blogs_comments WHERE c_id = $course_id AND parent_comment_id = '".(int)$comment_id."'"; + $sql = "SELECT comment_id FROM $tbl_blogs_comments + WHERE c_id = $course_id AND parent_comment_id = '".$comment_id."'"; $result = Database::query($sql); // Delete them recursively @@ -443,7 +441,8 @@ class Blog { } // Finally, delete the selected comment to - $sql = "DELETE FROM $tbl_blogs_comments WHERE c_id = $course_id AND comment_id = '".(int)$comment_id."'"; + $sql = "DELETE FROM $tbl_blogs_comments + WHERE c_id = $course_id AND comment_id = '".$comment_id."'"; Database::query($sql); } @@ -455,9 +454,10 @@ class Blog { * @param String $description * @param String $color */ - public static function create_task ($blog_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) { + public static function create_task ($blog_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) + { // Init - $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); + $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS); $course_id = api_get_course_int_id(); @@ -491,7 +491,7 @@ class Blog { Database::query($sql); } - if($commentsDelete == 'on') { + if ($commentsDelete == 'on') { $sql = " INSERT INTO " . $tbl_tasks_permissions . " (c_id, task_id, tool, action ) VALUES ( '" . (int)$course_id . "', @@ -512,14 +512,13 @@ class Blog { * @param String $description * @param String $color */ - public static function edit_task($blog_id, $task_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) { - // Init + public static function edit_task($blog_id, $task_id, $title, $description, $articleDelete, $articleEdit, $commentsDelete, $color) + { $tbl_blogs_tasks = Database::get_course_table(TABLE_BLOGS_TASKS); $tbl_tasks_permissions = Database::get_course_table(TABLE_BLOGS_TASKS_PERMISSIONS); $course_id = api_get_course_int_id(); - // Create the task $sql = "UPDATE $tbl_blogs_tasks SET title = '".Database::escape_string($title)."', @@ -530,7 +529,8 @@ class Blog { $tool = 'BLOG_' . $blog_id; - $sql = "DELETE FROM " . $tbl_tasks_permissions . " WHERE c_id = $course_id AND task_id = '" . (int)$task_id."'"; + $sql = "DELETE FROM " . $tbl_tasks_permissions . " + WHERE c_id = $course_id AND task_id = '" . (int)$task_id."'"; Database::query($sql); if ($articleDelete == 'on') { @@ -575,7 +575,8 @@ class Blog { $course_id = api_get_course_int_id(); // Delete posts - $sql = "DELETE FROM $tbl_blogs_tasks WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."'"; + $sql = "DELETE FROM $tbl_blogs_tasks + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."'"; Database::query($sql); } @@ -584,12 +585,14 @@ class Blog { * @param Integer $blog_id * @param Integer $assignment_id */ - public static function delete_assigned_task ($blog_id, $task_id,$user_id) { + public static function delete_assigned_task ($blog_id, $task_id, $user_id) + { $tbl_blogs_tasks_rel_user = Database::get_course_table(TABLE_BLOGS_TASKS_REL_USER); $course_id = api_get_course_int_id(); // Delete posts - $sql = "DELETE FROM $tbl_blogs_tasks_rel_user WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."' AND user_id = '".(int)$user_id."'"; + $sql = "DELETE FROM $tbl_blogs_tasks_rel_user + WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."' AND task_id = '".(int)$task_id."' AND user_id = '".(int)$user_id."'"; Database::query($sql); } @@ -628,17 +631,12 @@ class Blog { echo '
  • '.stripslashes($mytask['title']) . '
  • '; } echo '
      '; - } - else - { + } else { echo get_lang('NoTasks'); } - } - else - { + } else { echo get_lang('NoTasks'); } - } /** @@ -646,14 +644,16 @@ class Blog { * @author Toon Keppens * @param Integer $blog_id */ - public static function change_blog_visibility ($blog_id) { + public static function change_blog_visibility($blog_id) + { // Init $tbl_blogs = Database::get_course_table(TABLE_BLOGS); $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST); $course_id = api_get_course_int_id(); // Get blog properties - $sql = "SELECT blog_name, visibility FROM $tbl_blogs WHERE c_id = $course_id AND blog_id='".(int)$blog_id."'"; + $sql = "SELECT blog_name, visibility FROM $tbl_blogs + WHERE c_id = $course_id AND blog_id='".(int)$blog_id."'"; $result = Database::query($sql); $blog = Database::fetch_array($result); $visibility = $blog['visibility']; @@ -672,11 +672,11 @@ class Blog { { // Change visibility state, add to course home. $sql = "UPDATE $tbl_blogs SET visibility = '1' WHERE c_id = $course_id AND blog_id ='".(int)$blog_id."' LIMIT 1"; - $result = Database::query($sql); + Database::query($sql); $sql = "INSERT INTO $tbl_tool (c_id, name, link, image, visibility, admin, address, added_tool, target ) VALUES ($course_id, '".Database::escape_string($title)."', 'blog/blog.php?blog_id=".(int)$blog_id."', 'blog.gif', '1', '0', 'pastillegris.gif', '0', '_self')"; - $result = Database::query($sql); + Database::query($sql); } } @@ -720,8 +720,6 @@ class Blog { $blog_post_date = api_convert_and_format_date($blog_post['date_creation'], null, date_default_timezone_get()); // Create an introduction text (but keep FULL sentences) - - $introduction_text = ""; $words = 0; $blog_post_text_cut = cut($blog_post_text, $limit) ; $words = strlen($blog_post_text); @@ -742,8 +740,7 @@ class Blog { echo '
      ' . $introduction_text.$readMoreLink.'
      '; echo ''; - - $file_name_array=get_blog_attachment($blog_id,$blog_post_id,0); + $file_name_array = get_blog_attachment($blog_id,$blog_post_id,0); if (!empty($file_name_array)) { echo '

      '; @@ -1107,144 +1104,32 @@ class Blog { * * @param Integer $blog_id */ - public static function display_form_new_post ($blog_id) { - if(api_is_allowed('BLOG_' . $blog_id, 'article_add')) { - echo ''; - - - echo '
      '; - - echo ''; - - // form title - echo '' . get_lang('NewPost') . ''; - - // article title - echo '
      *'.get_lang('Title') . ':

      '; - - // article text - //@todo use formvalidator - //$oFCKeditor = new FCKeditor('post_full_text') ; - $oFCKeditor = new CKeditor(); - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '200'; - if(!api_is_allowed_to_edit()) { - $oFCKeditor->ToolbarSet = 'Project_Student'; + public static function display_form_new_post($blog_id) + { + if (api_is_allowed('BLOG_' . $blog_id, 'article_add')) { + $form = new FormValidator( + 'add_post', + 'post', + api_get_path(WEB_CODE_PATH)."blog/blog.php?action=new_post&blog_id=" . $blog_id . "&" . api_get_cidreq(), + null, + array('enctype' => 'multipart/form-data') + ); + $form->addHidden('post_title_edited', 'false'); + $form->addHeader(get_lang('NewPost')); + $form->add_textfield('title', get_lang('Title')); + $config = array(); + if (!api_is_allowed_to_edit()) { + $config['ToolbarSet'] = 'ProjectStudent'; } else { - $oFCKeditor->ToolbarSet = 'Project'; + $config['ToolbarSet'] = 'Project'; } - $oFCKeditor->Value = isset($_POST['post_full_text'])?stripslashes($_POST['post_full_text']):''; + $form->add_html_editor('full_text', get_lang('Content'), false, false, $config); + $form->add_file('user_upload', get_lang('AddAnAttachment')); + $form->add_textarea('post_file_comment', get_lang('FileComment')); + $form->addHidden('new_post_submit', 'true'); + $form->addButton('save', get_lang('Save')); - echo '
      '; - //$oFCKeditor->Create(); - $oFCKeditor->editor('post_full_text'); - echo '
      '; - - // attachment - echo '
      - -
      - -
      -
      '; - - // comment - echo '
      - -
      - -
      -
      '; - - // submit - echo '
      -
      - - - -
      -
      '; - echo '
      '; + $form->display(); } else { api_not_allowed(); } @@ -1256,15 +1141,16 @@ class Blog { * * @param Integer $blog_id */ - public static function display_form_edit_post ($blog_id, $post_id) { - // Init + public static function display_form_edit_post($blog_id, $post_id) + { $tbl_blogs_posts = Database::get_course_table(TABLE_BLOGS_POSTS); $tbl_users = Database::get_main_table(TABLE_MAIN_USER); $course_id = api_get_course_int_id(); // Get posts and author - $sql = "SELECT post.*, user.lastname, user.firstname FROM $tbl_blogs_posts post + $sql = "SELECT post.*, user.lastname, user.firstname + FROM $tbl_blogs_posts post INNER JOIN $tbl_users user ON post.author_id = user.user_id WHERE post.c_id = $course_id AND @@ -1274,48 +1160,30 @@ class Blog { $result = Database::query($sql); $blog_post = Database::fetch_array($result); - // Prepare data - $blog_post_text = stripslashes($blog_post['full_text']); - - echo '
      '; - - // form title - echo '' . get_lang('EditPost') . ''; - - // article title - echo '
      *' . get_lang('Title') . ':
      '; + // Form - // article text - //$oFCKeditor = new FCKeditor('post_full_text') ; - $oFCKeditor = new CKeditor(); + $form = new FormValidator( + 'edit_post', + 'post', + api_get_path(WEB_CODE_PATH).'blog/blog.php?action=edit_post&post_id=' . intval($_GET['post_id']) . '&blog_id=' . intval($blog_id) . '&article_id='.intval($_GET['article_id']).'&task_id='.intval($_GET['task_id']) + ); - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '200'; + $form->addHeader(get_lang('EditPost')); + $form->add_textfield('title', get_lang('Title')); - if(!api_is_allowed_to_edit()) { - $oFCKeditor->ToolbarSet = 'Project_Student'; + if (!api_is_allowed_to_edit()) { + $config['ToolbarSet'] = 'ProjectStudent'; } else { - $oFCKeditor->ToolbarSet = 'Project'; + $config['ToolbarSet'] = 'Project'; } - $oFCKeditor->Value = isset($_POST['post_full_text'])?stripslashes($_POST['post_full_text']):$blog_post_text; - echo '
      '; - //echo $oFCKeditor->Create(); - $oFCKeditor->editor('post_full_text', $oFCKeditor->Value); - echo '
      '; - - // submit - echo '
      - -
      - - - - -
      -
      '; - - - echo '
      '; + $form->add_html_editor('full_text', get_lang('Content'), false, false, $config); + + $form->addHidden('action', ''); + $form->addHidden('edit_post_submit', 'true'); + $form->addHidden('post_id', intval($_GET['post_id'])); + $form->addButton('save', get_lang('Save')); + $form->setDefaults($blog_post); + $form->display(); } /** @@ -2334,75 +2202,45 @@ class Blog { * * @param Integer $blog_id */ - public static function display_new_comment_form ($blog_id, $post_id, $title) { - echo '
      '; - - // form title - echo ''; - echo (isset($_GET['task_id']) ? get_lang('ExecuteThisTask') : get_lang('AddNewComment')); - echo ''; - - // comment title - echo '
      *' . get_lang('Title') . ':

      '; - - // comment text - //$oFCKeditor = new FCKeditor('comment_text') ; - $oFCKeditor = new CKeditor(); - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '200'; - if(!api_is_allowed_to_edit()) - { - $oFCKeditor->ToolbarSet = 'Project_Comment_Student'; + public static function display_new_comment_form($blog_id, $post_id, $title) + { + $form = new FormValidator( + 'add_post', + 'post', + api_get_path(WEB_CODE_PATH)."blog/blog.php?action=view_post&blog_id=" . intval($blog_id) . "&post_id=".intval($post_id)."&".api_get_cidreq(), + null, + array('enctype' => 'multipart/form-data') + ); + + $header = get_lang('AddNewComment'); + if (isset($_GET['task_id'])) { + $header = get_lang('ExecuteThisTask'); } - else - { - $oFCKeditor->ToolbarSet = 'Project_Comment'; + $form->addHeader($header); + $form->add_textfield('title', get_lang('Title')); + + $config = array(); + if (!api_is_allowed_to_edit()) { + $config['ToolbarSet'] = 'ProjectComment'; + } else { + $config['ToolbarSet'] = 'ProjectCommentStudent'; } - $oFCKeditor->Value = isset($_POST['comment_text'])?stripslashes($_POST['comment_text']):''; - echo '
      '; - //echo $oFCKeditor->Create() ; - $oFCKeditor->editor('comment_text'); - echo ' -
      '; + $form->add_html_editor('comment', get_lang('Comment'), false, false, $config); + $form->add_file('user_upload', get_lang('AddAnAttachment')); - // attachment - echo '
      - -
      - -
      -
      '; + $form->add_textarea('post_file_comment', get_lang('FileComment')); - // attachment comment - echo '
      - -
      - -
      -
      '; + $form->addHidden('action', null); + $form->addHidden('comment_parent_id', 0); - // attachment comment - echo '
      -
      - - '; - if(isset($_GET['task_id'])) - { - echo ' '; - echo ' '; - } - else - { - echo ' '; - } - echo ' -
      -
      '; - echo '
      '; + if (isset($_GET['task_id'])) { + $form->addHidden('new_task_execution_submit', 'true'); + $form->addHidden('task_id', intval($_GET['task_id'])); + } else { + $form->addHidden('new_comment_submit', 'true'); + } + $form->addButton('save', get_lang('Save')); + $form->display(); } @@ -2418,7 +2256,8 @@ class Blog { * * @return html code */ - public static function display_minimonthcalendar ($month, $year, $blog_id) { + public static function display_minimonthcalendar ($month, $year, $blog_id) + { // Init global $_user; global $DaysShort; @@ -2447,17 +2286,21 @@ class Blog { //Start the week on monday $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6; - $backwardsURL = api_get_self()."?blog_id=" . (int)$_GET['blog_id']."&filter=" . Security::remove_XSS($_GET['filter'])."&month=". ($month == 1 ? 12 : $month -1)."&year=". ($month == 1 ? $year -1 : $year); - $forewardsURL = api_get_self()."?blog_id=" . (int)$_GET['blog_id']."&filter=" . Security::remove_XSS($_GET['filter'])."&month=". ($month == 12 ? 1 : $month +1)."&year=". ($month == 12 ? $year +1 : $year); + $blogId = isset($_GET['blog_id']) ? intval($_GET['blog_id']) : null; + $filter = isset($_GET['filter']) ? Security::remove_XSS($_GET['filter']) : null; + $backwardsURL = api_get_self()."?blog_id=" . $blogId."&filter=" . $filter."&month=". ($month == 1 ? 12 : $month -1)."&year=". ($month == 1 ? $year -1 : $year); + $forewardsURL = api_get_self()."?blog_id=" . $blogId."&filter=" . $filter."&month=". ($month == 12 ? 1 : $month +1)."&year=". ($month == 12 ? $year +1 : $year); // Get posts for this month - $sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname FROM $tbl_blogs_posts post + $sql = "SELECT post.*, DAYOFMONTH(date_creation) as post_day, user.lastname, user.firstname + FROM $tbl_blogs_posts post INNER JOIN $tbl_users user ON post.author_id = user.user_id - WHERE post.c_id = $course_id AND - post.blog_id = '".(int)$blog_id."' AND - MONTH(date_creation) = '".(int)$month."' AND - YEAR(date_creation) = '".(int)$year."' + WHERE + post.c_id = $course_id AND + post.blog_id = '".(int)$blog_id."' AND + MONTH(date_creation) = '".(int)$month."' AND + YEAR(date_creation) = '".(int)$year."' ORDER BY date_creation"; $result = Database::query($sql); @@ -2526,12 +2369,11 @@ class Blog { if(($curday == -1) && ($ii == $startdayofweek)) $curday = 1; - if(($curday > 0) && ($curday <= $numberofdays[$month])) - { + if(($curday > 0) && ($curday <= $numberofdays[$month])) { $bgcolor = $ii < 5 ? $class="class=\"days_week\"" : $class="class=\"days_weekend\""; $dayheader = "$curday"; - if(($curday == $today[mday]) && ($year == $today[year]) && ($month == $today[mon])) + if(($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) { $dayheader = "$curday"; $class = "class=\"days_today\""; @@ -2575,9 +2417,9 @@ class Blog { * Blog admin | Display the form to add a new blog. * */ - public static function display_new_blog_form () { - - $form = new FormValidator('add_blog', 'post','blog_admin.php?action=add'); + public static function display_new_blog_form() + { + $form = new FormValidator('add_blog', 'post', 'blog_admin.php?action=add'); $form->addElement('header', get_lang('AddBlog')); $form->addElement('text', 'blog_name', get_lang('Title')); $form->addElement('textarea', 'blog_subtitle', get_lang('Subtitle')); @@ -2585,9 +2427,10 @@ class Blog { $form->addElement('hidden', 'new_blog_submit', 'true'); $form->addElement('style_submit_button', null, get_lang('SaveProject')); - $defaults = array(); - $defaults['blog_name'] = Security::remove_XSS($_POST['blog_name']); - $defaults['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']); + $defaults = array( + 'blog_name' => isset($_POST['blog_name']) ? Security::remove_XSS($_POST['blog_name']) : null, + 'blog_subtitle' => isset($_POST['blog_subtitle']) ? Security::remove_XSS($_POST['blog_subtitle']) : null + ); $form->setDefaults($defaults); $form->display(); } @@ -2596,11 +2439,13 @@ class Blog { * Blog admin | Display the form to edit a blog. * */ - public static function display_edit_blog_form ($blog_id) { + public static function display_edit_blog_form($blog_id) + { $course_id = api_get_course_int_id(); + $blog_id= intval($blog_id); $tbl_blogs = Database::get_course_table(TABLE_BLOGS); - $sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = '".(int)$blog_id."'"; + $sql = "SELECT blog_id, blog_name, blog_subtitle FROM $tbl_blogs WHERE c_id = $course_id AND blog_id = '".$blog_id."'"; $result = Database::query($sql); $blog = Database::fetch_array($result); @@ -2610,7 +2455,7 @@ class Blog { $blog['blog_subtitle'] = Security::remove_XSS($_POST['blog_subtitle']); } - $form = new FormValidator('edit_blog', 'post','blog_admin.php?action=edit&blog_id='.Security::remove_XSS($_GET['blog_id'])); + $form = new FormValidator('edit_blog', 'post','blog_admin.php?action=edit&blog_id='.intval($_GET['blog_id'])); $form->addElement('header', get_lang('EditBlog')); $form->addElement('text', 'blog_name', get_lang('Title')); $form->addElement('textarea', 'blog_subtitle', get_lang('Subtitle')); @@ -2641,21 +2486,24 @@ class Blog { $session_id = api_get_session_id(); $condition_session = api_get_session_condition($session_id, false); - $sql = "SELECT blog_name,blog_subtitle,visibility,blog_id FROM $tbl_blogs WHERE c_id = $course_id ORDER BY date_creation DESC"; + $sql = "SELECT blog_name, blog_subtitle, visibility, blog_id, session_id + FROM $tbl_blogs WHERE c_id = $course_id + ORDER BY date_creation DESC"; $result = Database::query($sql); + $list_info = array(); if (Database::num_rows($result)) { while ($row_project=Database::fetch_row($result)) { $list_info[]=$row_project; } } - $list_content_blog = array(); $list_body_blog = array(); + $_user = api_get_user_info(); if (is_array($list_info)) { - foreach($list_info as $key => $info_log) { - //validacion when belongs to a session + foreach ($list_info as $key => $info_log) { + // Validation when belongs to a session $session_img = api_get_session_image($info_log[4], $_user['status']); $url_start_blog = 'blog.php' ."?". "blog_id=".$info_log[3]. "&".api_get_cidreq(); @@ -2668,19 +2516,18 @@ class Blog { $visibility_icon=($info_log[2]==0) ? 'invisible' : 'visible'; $visibility_info=($info_log[2]==0) ? 'Visible' : 'Invisible'; - $my_image.=''; - $my_image.=''; - $my_image.="\n"; - $my_image.=''; - $my_image.=''; - $my_image.="\n"; - $my_image.=''; - $my_image.=''; - $my_image.="\n"; + $my_image = ''; + $my_image.= ''; + $my_image.= "\n"; + $my_image.= ''; + $my_image.= ''; + $my_image.= "\n"; + $my_image.= ''; + $my_image.= ''; + $my_image.= "\n"; $list_body_blog[]=$my_image; - $my_image=''; $list_content_blog[]=$list_body_blog; $list_body_blog = array(); 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/certificate.lib.php b/main/inc/lib/certificate.lib.php index 9892f88b2a..33354e2b54 100755 --- a/main/inc/lib/certificate.lib.php +++ b/main/inc/lib/certificate.lib.php @@ -3,14 +3,19 @@ /** * Certificate Class - * The certificates class is used to generate certificates from inside the - * gradebook tool. + * Generate certificates based in the gradebook tool. * @package chamilo.library.certificates */ class Certificate extends Model { public $table; - public $columns = array('id','cat_id','score_certificate','created_at','path_certificate'); + public $columns = array( + 'id', + 'cat_id', + 'score_certificate', + 'created_at', + 'path_certificate' + ); /** * Certification data */ @@ -21,8 +26,8 @@ class Certificate extends Model */ public $certification_user_path = null; public $certification_web_user_path = null; - public $html_file = null; - public $qr_file = null; + public $html_file = null; + public $qr_file = null; public $user_id; /* If true every time we enter to the certificate URL @@ -34,16 +39,18 @@ class Certificate extends Model /** * Constructor - * @param int ID of the certificate. If no ID given, take user_id and try to generate one + * @param int $certificate_id ID of the certificate. + * + * If no ID given, take user_id and try to generate one */ public function __construct($certificate_id = null) { - $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE); + $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE); $this->certificate_data = null; if (isset($certificate_id)) { $this->certificate_data = $this->get($certificate_id); - $this->user_id = $this->certificate_data['user_id']; + $this->user_id = $this->certificate_data['user_id']; } else { //Try with the current user $this->user_id = api_get_user_id(); @@ -51,10 +58,10 @@ class Certificate extends Model if ($this->user_id) { - //Need to be called before any operation + // Need to be called before any operation $this->check_certificate_path(); - //To force certification generation + // To force certification generation if ($this->force_certificate_generation) { $this->generate(); } @@ -102,9 +109,12 @@ class Certificate extends Model * Deletes the current certificate object. This is generally triggered by * the teacher from the gradebook tool to re-generate the certificate because * the original version wa flawed. + * @param bool $force_delete + * @return bool */ public function delete($force_delete = false) { + $delete_db = false; if (!empty($this->certificate_data)) { if (!is_null($this->html_file) || $this->html_file != '' || strlen($this->html_file)) { //Deleting HTML file @@ -121,12 +131,15 @@ class Certificate extends Model @unlink($this->qr_file); } if ($delete_db || $force_delete) { + return parent::delete($this->certificate_data['id']); } } else { + return parent::delete($this->certificate_data['id']); } } + return false; } @@ -142,24 +155,27 @@ class Certificate extends Model $params['hide_print_button'] = isset($params['hide_print_button']) ? true : false; $my_category = Category :: load($this->certificate_data['cat_id']); - - if (isset($my_category[0]) && $my_category[0]->is_certificate_available($this->user_id)) { - - $user = api_get_user_info($this->user_id); + if (isset($my_category[0]) && + $my_category[0]->is_certificate_available($this->user_id) + ) { + $user = api_get_user_info($this->user_id); $scoredisplay = ScoreDisplay :: instance(); - $scorecourse = $my_category[0]->calc_score($this->user_id); - - $scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable')); + $scorecourse = $my_category[0]->calc_score($this->user_id); + $scorecourse_display = isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'); - //Prepare all necessary variables: - $organization_name = api_get_setting('Institution'); + // Prepare all necessary variables: + $organization_name = api_get_setting('Institution'); //$portal_name = api_get_setting('siteName'); - $stud_fn = $user['firstname']; - $stud_ln = $user['lastname']; + $stud_fn = $user['firstname']; + $stud_ln = $user['lastname']; //@todo this code is not needed - $certif_text = sprintf(get_lang('CertificateWCertifiesStudentXFinishedCourseYWithGradeZ'), $organization_name, $stud_fn.' '.$stud_ln, $my_category[0]->get_name(), $scorecourse_display); - $certif_text = str_replace("\\n","\n", $certif_text); + $certif_text = sprintf( + get_lang('CertificateWCertifiesStudentXFinishedCourseYWithGradeZ'), + $organization_name, $stud_fn.' '.$stud_ln, $my_category[0]->get_name(), + $scorecourse_display + ); + $certif_text = str_replace("\\n","\n", $certif_text); //If the gradebook is related to skills we added the skills to the user @@ -167,7 +183,12 @@ class Certificate extends Model $sessionId = api_get_session_id(); $skill = new Skill(); - $skill->add_skill_to_user($this->user_id, $this->certificate_data['cat_id'], $courseId, $sessionId); + $skill->add_skill_to_user( + $this->user_id, + $this->certificate_data['cat_id'], + $courseId, + $sessionId + ); if (is_dir($this->certification_user_path)) { if (!empty($this->certificate_data)) { @@ -181,12 +202,16 @@ class Certificate extends Model if ($my_category[0]->get_id() == strval(intval($this->certificate_data['cat_id']))) { $name = $this->certificate_data['path_certificate']; $my_path_certificate = $this->certification_user_path.basename($name); - if (file_exists($my_path_certificate) && !empty($name) && !is_dir($my_path_certificate) && $this->force_certificate_generation == false) { + if (file_exists($my_path_certificate) && + !empty($name) && + !is_dir($my_path_certificate) && + $this->force_certificate_generation == false + ) { //Seems that the file was already generated return true; } else { - //Creating new name - $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html'; + // Creating new name + $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html'; $my_path_certificate = $this->certification_user_path.$name; $path_certificate ='/'.$name; @@ -194,13 +219,21 @@ class Certificate extends Model $file_info = pathinfo($path_certificate); $qr_code_filename = $this->certification_user_path.$file_info['filename'].'_qr.png'; - $my_new_content_html = str_replace('((certificate_barcode))', Display::img($this->certification_web_user_path.$file_info['filename'].'_qr.png', 'QR'), $new_content_html['content']); + $my_new_content_html = str_replace( + '((certificate_barcode))', + Display::img($this->certification_web_user_path.$file_info['filename'].'_qr.png', 'QR'), + $new_content_html['content'] + ); $my_new_content_html = mb_convert_encoding($my_new_content_html,'UTF-8', api_get_system_encoding()); $result = @file_put_contents($my_path_certificate, $my_new_content_html); if ($result) { //Updating the path - self::update_user_info_about_certificate($this->certificate_data['cat_id'], $this->user_id, $path_certificate); + self::update_user_info_about_certificate( + $this->certificate_data['cat_id'], + $this->user_id, + $path_certificate + ); $this->certificate_data['path_certificate'] = $path_certificate; if ($this->html_file_is_generated()) { @@ -210,24 +243,29 @@ class Certificate extends Model } } } + return $result; } } } } } + return false; } /** * update user info about certificate - * @param int The category id - * @param int The user id - * @param string the path name of the certificate + * @param int $cat_id category id + * @param int $user_id user id + * @param string $path_certificate the path name of the certificate * @return void() */ - public function update_user_info_about_certificate ($cat_id,$user_id,$path_certificate) - { + public function update_user_info_about_certificate( + $cat_id, + $user_id, + $path_certificate + ) { $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE); if (!UserManager::is_user_certified($cat_id,$user_id)) { $sql='UPDATE '.$table_certificate.' SET path_certificate="'.Database::escape_string($path_certificate).'" @@ -258,8 +296,8 @@ class Certificate extends Model /** * Generates a QR code for the certificate. The QR code embeds the text given - * @param string Text to be added in the QR code - * @param string file path of the image + * @param string $text Text to be added in the QR code + * @param string $path file path of the image * */ public function generate_qr($text, $path) { @@ -274,7 +312,8 @@ class Certificate extends Model /** * Transforms certificate tags into text values. This function is very static * (it doesn't allow for much flexibility in terms of what tags are printed). - * @param array Contains two array entris: first are the headers, second is an array of contents + * @param array $array Contains two array entris: first are the headers, + * second is an array of contents * @return string The translated string */ public function parse_certificate_variables($array) diff --git a/main/inc/lib/course.lib.php b/main/inc/lib/course.lib.php index 15b5e4c542..a42ae97ad4 100755 --- a/main/inc/lib/course.lib.php +++ b/main/inc/lib/course.lib.php @@ -1,9 +1,6 @@ $virtual_course) { - // Unsubscribe all classes from the virtual course - /*$sql = "DELETE FROM $table_course_class WHERE course_code='".$virtual_course['code']."'"; - Database::query($sql);*/ - // Unsubscribe all users from the virtual course - $sql = "DELETE FROM $table_course_user WHERE course_code='".$virtual_course['code']."'"; - Database::query($sql); - // Delete the course from the sessions tables - $sql = "DELETE FROM $table_session_course WHERE course_code='".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_session_course_user WHERE course_code='".$virtual_course['code']."'"; - Database::query($sql); - // Delete the course from the survey tables - $sql = "DELETE FROM $table_course_survey WHERE course_code='".$virtual_course['code']."'"; - Database::query($sql); - /*$sql = "DELETE FROM $table_course_survey_user WHERE db_name='".$virtual_course['db_name']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_course_survey_reminder WHERE db_name='".$virtual_course['db_name']."'"; - Database::query($sql);*/ - // Delete the course from the stats tables - - $sql = "DELETE FROM $table_stats_hotpots WHERE exe_cours_id = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_attempt WHERE course_code = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_exercises WHERE exe_cours_id = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_access WHERE access_cours_code = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_lastaccess WHERE access_cours_code = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_course_access WHERE course_code = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_online WHERE course = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_default WHERE default_cours_code = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_downloads WHERE down_cours_id = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_links WHERE links_cours_id = '".$virtual_course['code']."'"; - Database::query($sql); - $sql = "DELETE FROM $table_stats_uploads WHERE upload_cours_id = '".$virtual_course['code']."'"; - Database::query($sql); - - // Delete the course from the course table - $sql = "DELETE FROM $table_course WHERE code='".$virtual_course['code']."'"; + $sql = "SELECT * FROM $table_course WHERE code='".$codeFiltered."'"; + $res = Database::query($sql); + $course = Database::fetch_array($res); + $course_tables = AddCourse::get_course_tables(); + $courseId = $course['id']; + + // Cleaning c_x tables + if (!empty($courseId)) { + foreach ($course_tables as $table) { + $table = Database::get_course_table($table); + $sql = "DELETE FROM $table WHERE c_id = $courseId "; Database::query($sql); } + } - $sql = "SELECT * FROM $table_course WHERE code='".$codeFiltered."'"; - $res = Database::query($sql); - $course = Database::fetch_array($res); - $course_tables = get_course_tables(); - - //Cleaning c_x tables - if (!empty($course['id'])) { - foreach($course_tables as $table) { - $table = Database::get_course_table($table); - $sql = "DELETE FROM $table WHERE c_id = {$course['id']} "; - Database::query($sql); - } - } - $course_dir = api_get_path(SYS_COURSE_PATH).$course['directory']; - $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$course['directory'].'_'.time(); - if (is_dir($course_dir)) { - rename($course_dir, $archive_dir); - } + $course_dir = api_get_path(SYS_COURSE_PATH).$course['directory']; + $archive_dir = api_get_path(SYS_ARCHIVE_PATH).$course['directory'].'_'.time(); + if (is_dir($course_dir)) { + rename($course_dir, $archive_dir); } // Unsubscribe all classes from the course @@ -2349,21 +2296,21 @@ class CourseManager Database::query($sql); $sql = "DELETE FROM $table_stats_exercises WHERE exe_cours_id = '".$codeFiltered."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_access WHERE access_cours_code = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_access WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_lastaccess WHERE access_cours_code = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_lastaccess WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_course_access WHERE course_code = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_course_access WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_online WHERE course = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_online WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_default WHERE default_cours_code = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_default WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_downloads WHERE down_cours_id = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_downloads WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_links WHERE links_cours_id = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_links WHERE c_id = '".$courseId."'"; Database::query($sql); - $sql = "DELETE FROM $table_stats_uploads WHERE upload_cours_id = '".$codeFiltered."'"; + $sql = "DELETE FROM $table_stats_uploads WHERE c_id = '".$courseId."'"; Database::query($sql); // Delete the course from the database @@ -2371,13 +2318,13 @@ class CourseManager Database::query($sql); // delete extra course fields - $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD); - $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES); + $t_cf = Database::get_main_table(TABLE_MAIN_COURSE_FIELD); + $t_cfv = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES); $sql = "SELECT distinct field_id FROM $t_cfv WHERE course_code = '$codeFiltered'"; $res_field_ids = Database::query($sql); $field_ids = array(); - while($row_field_id = Database::fetch_row($res_field_ids)){ + while($row_field_id = Database::fetch_row($res_field_ids)) { $field_ids[] = $row_field_id[0]; } @@ -2408,7 +2355,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, @@ -2437,7 +2384,7 @@ class CourseManager $res = Database::query($sql); $course = Database::fetch_array($res); - $course_tables = get_course_tables(); + $course_tables = AddCourse::get_course_tables(); if (!empty($course['id'])) { //Cleaning c_x tables @@ -2685,11 +2632,10 @@ class CourseManager $user_id = intval($user_id); $course_list = array(); $codes = array(); - $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); - $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); - $tbl_user_course_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY); - - $special_course_list = self::get_special_course_list(); + $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE); + $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER); + $tbl_user_course_category = Database::get_user_personal_table(TABLE_USER_COURSE_CATEGORY); + $special_course_list = self::get_special_course_list(); $with_special_courses = $without_special_courses = ''; if (!empty($special_course_list)) { @@ -3487,6 +3433,7 @@ class CourseManager // image name for courses $courseImage = $storePath.'/course-pic.png'; $courseMediumImage = $storePath.'/course-pic85x85.png'; + $courseSmallImage = $storePath.'/course-pic32.png'; if (file_exists($courseImage)) { unlink($courseImage); @@ -3494,6 +3441,9 @@ class CourseManager if (file_exists($courseMediumImage)) { unlink($courseMediumImage); } + if (file_exists($courseSmallImage)) { + unlink($courseSmallImage); + } } /** @@ -4256,10 +4206,9 @@ class CourseManager */ public static function generate_nice_next_course_code($wanted_code) { - require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php'; $course_code_ok = !self::course_code_exists($wanted_code); if (!$course_code_ok) { - $wanted_code = generate_course_code($wanted_code); + $wanted_code = CourseManager::generate_course_code($wanted_code); $table = Database::get_main_table(TABLE_MAIN_COURSE); $wanted_code = Database::escape_string($wanted_code); $sql = "SELECT count(*) as count FROM $table WHERE code LIKE '$wanted_code%'"; @@ -4678,16 +4627,18 @@ class CourseManager //$table_course_access table uses the now() and interval ... $now = api_get_utc_datetime(time()); - $sql = "SELECT COUNT(course_access_id) course_count, a.course_code, visibility ". - "FROM $table_course c INNER JOIN $table_course_access a ". - " ON (c.code = a.course_code) INNER JOIN $table_course_url u ON u.course_code = a.course_code ". - " WHERE u.access_url_id = ".$_configuration['access_url']." AND". - " login_course_date <= '$now' AND ". - " login_course_date > DATE_SUB(now(), INTERVAL $days DAY) AND". - " visibility <> '".COURSE_VISIBILITY_CLOSED."' AND visibility <> '".COURSE_VISIBILITY_HIDDEN."'". - " GROUP BY course_code". - " ORDER BY course_count DESC". - " LIMIT $limit"; + $sql = "SELECT COUNT(course_access_id) course_count, a.c_id, visibility + FROM $table_course c INNER JOIN $table_course_access a + ON (c.code = a.c_id) INNER JOIN $table_course_url u ON u.course_code = c.code + WHERE + u.access_url_id = ".api_get_current_access_url_id()." AND + login_course_date <= '$now' AND + login_course_date > DATE_SUB(now(), INTERVAL $days DAY) AND + visibility <> '".COURSE_VISIBILITY_CLOSED."' AND visibility <> '".COURSE_VISIBILITY_HIDDEN."' + GROUP BY a.c_id + ORDER BY course_count DESC + LIMIT $limit + "; $result = Database::query($sql); $courses = array(); @@ -4709,14 +4660,19 @@ class CourseManager $stok = Security::get_existing_token(); - foreach ($courses as &$my_course) { - $course_info = api_get_course_info($my_course['course_code']); - $courseCode = $my_course['course_code']; - $categoryCode = !empty($my_course['categoryCode']) ? $my_course['categoryCode'] : ""; + foreach ($courses as $courseId) { + $course_info = api_get_course_info_by_id($courseId); + $courseCode = $course_info['code']; + $categoryCode = !empty($course_info['categoryCode']) ? $course_info['categoryCode'] : ""; $my_course['extra_info'] = $course_info; $my_course['extra_info']['go_to_course_button'] = ''; $my_course['extra_info']['register_button'] = ''; - $access_link = self::get_access_link_by_user(api_get_user_id(), $course_info, $my_course_code_list); + + $access_link = self::get_access_link_by_user( + api_get_user_id(), + $course_info, + $my_course_code_list + ); //Course visibility if ($access_link && in_array('register', $access_link)) { @@ -5191,27 +5147,27 @@ class CourseManager /** * Get information from the track_e_course_access table - * @param string $courseCode + * @param int $courseId * @param int $sessionId * @param string $startDate * @param string $endDate * @return array */ public static function getCourseAccessPerCourseAndSession( - $courseCode, + $courseId, $sessionId, $startDate, $endDate ) { $table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); - $courseCode = Database::escape_string($courseCode); + $courseId = intval($courseId); $sessionId = intval($sessionId); $startDate = Database::escape_string($startDate); $endDate = Database::escape_string($endDate); $sql = "SELECT * FROM $table WHERE - course_code = '$courseCode' AND + c_id = '$courseId' AND session_id = $sessionId AND login_course_date BETWEEN '$startDate' AND '$endDate' "; @@ -5355,4 +5311,180 @@ class CourseManager return $col['title']; } } + + /** + * Generates a course code from a course title + * @todo Such a function might be useful in other places too. It might be moved in the CourseManager class. + * @todo the function might be upgraded for avoiding code duplications (currently, it might suggest a code that is already in use) + * @param string A course title + * @param string The course title encoding (defaults to type defined globally) + * @return string A proposed course code + * @assert (null,null) === false + * @assert ('ABC_DEF', null) === 'ABCDEF' + * @assert ('ABC09*^[%A', null) === 'ABC09A' + */ + public static function generate_course_code($course_title, $encoding = null) + { + if (empty($encoding)) { + $encoding = api_get_system_encoding(); + } + return substr(preg_replace('/[^A-Z0-9]/', '', strtoupper(api_transliterate($course_title, 'X', $encoding))), 0, CourseManager::MAX_COURSE_LENGTH_CODE); + } + + /** + * @param $courseId + * @return array + */ + public static function getCourseSettings($courseId) + { + $settingTable = Database::get_course_table(TABLE_COURSE_SETTING); + $courseId = intval($courseId); + $sql = "SELECT * FROM $settingTable WHERE c_id = $courseId"; + $result = Database::query($sql); + $settings = array(); + if (Database::num_rows($result)) { + while ($row = Database::fetch_array($result, 'ASSOC')) { + $settings[$row['variable']] = $row; + } + } + return $settings; + } + + /** + * this function gets all the users of the course, + * including users from linked courses + */ + public static function getCourseUsers() + { + //this would return only the users from real courses: + $session_id = api_get_session_id(); + if ($session_id != 0) { + $user_list = self::get_real_and_linked_user_list(api_get_course_id(), true, $session_id); + } else { + $user_list = self::get_real_and_linked_user_list(api_get_course_id(), false, 0); + } + + return $user_list; + } + + /** + * this function gets all the groups of the course, + * not including linked courses + */ + public static function getCourseGroups() + { + $session_id = api_get_session_id(); + if ($session_id != 0) { + $new_group_list = self::get_group_list_of_course(api_get_course_id(), $session_id, 1); + } else { + $new_group_list = self::get_group_list_of_course(api_get_course_id(), 0, 1); + } + + return $new_group_list; + } + + /** + * @param FormValidator $form + * @param array $to_already_selected + */ + public static function addUserGroupMultiSelect(&$form, $to_already_selected) + { + $user_list = self::getCourseUsers(); + $group_list = self::getCourseGroups(); + $array = self::buildSelectOptions($group_list, $user_list, $to_already_selected); + + $result = array(); + foreach ($array as $content) { + $result[$content['value']] = $content['content']; + } + + $group = $form->addElement('advmultiselect', 'users', get_lang('Users'), $result, array('select_all_checkbox' => true)); + $group->setButtonAttributes('add'); + $group->setButtonAttributes('remove'); + } + + /** + * this function shows the form for sending a message to a specific group or user. + */ + /** + * @param FormValidator $form + * @param int $group_id + * @param array $to + */ + public static function addGroupMultiSelect($form, $group_id, $to = array()) + { + $group_users = GroupManager::get_subscribed_users($group_id); + + $array = self::buildSelectOptions(null, $group_users, $to); + + $result = array(); + foreach ($array as $content) { + $result[$content['value']] = $content['content']; + } + + $group = $form->addElement('advmultiselect', 'users', get_lang('Users'), $result); + $group->setButtonAttributes('add'); + $group->setButtonAttributes('remove'); + } + + /** + * this function shows the form for sending a message to a specific group or user. + * @param array $group_list + * @param array $user_list + * @param array $to_already_selected + * @return array + */ + public static function buildSelectOptions( + $group_list = array(), + $user_list = array(), + $to_already_selected = array() + ) { + if (empty($to_already_selected)) { + $to_already_selected = array(); + } + + $result = array(); + // adding the groups to the select form + if ($group_list) { + foreach ($group_list as $this_group) { + if (is_array($to_already_selected)) { + if (!in_array( + "GROUP:".$this_group['id'], + $to_already_selected + ) + ) { // $to_already_selected is the array containing the groups (and users) that are already selected + $user_label = ($this_group['userNb'] > 0) ? get_lang('Users') : get_lang('LowerCaseUser'); + $user_disabled = ($this_group['userNb'] > 0) ? "" : "disabled=disabled"; + $result []= array( + 'disabled' => $user_disabled, + 'value' => "GROUP:".$this_group['id'], + 'content' => "G: ".$this_group['name']." - ".$this_group['userNb']." ".$user_label + ); + } + } + } + } + + // adding the individual users to the select form + if ($user_list) { + foreach ($user_list as $user) { + if (is_array($to_already_selected)) { + if (!in_array( + "USER:".$user['user_id'], + $to_already_selected + ) + ) { // $to_already_selected is the array containing the users (and groups) that are already selected + + $result[]= array( + 'value' => "USER:".$user['user_id'], + 'content' => api_get_person_name($user['firstname'], $user['lastname']) + ); + } + } + } + } + + return $result; + } + } diff --git a/main/inc/lib/course_category.lib.php b/main/inc/lib/course_category.lib.php index 8fbb1801a8..7c7f44ca42 100755 --- a/main/inc/lib/course_category.lib.php +++ b/main/inc/lib/course_category.lib.php @@ -101,15 +101,14 @@ function addNode($code, $name, $canHaveCourses, $parent_id) $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY); $code = trim(Database::escape_string($code)); $name = trim(Database::escape_string($name)); - $parent_id = intval($parent_id); + $parent_id = trim(Database::escape_string($parent_id)); $canHaveCourses = Database::escape_string($canHaveCourses); - $code = generate_course_code($code); + $code = CourseManager::generate_course_code($code); $result = Database::query("SELECT 1 FROM $tbl_category WHERE code='$code'"); if (Database::num_rows($result)) { return false; } - $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category"); $row = Database::fetch_array($result); $tree_pos = $row['maxTreePos'] + 1; @@ -142,7 +141,8 @@ function updateCategoryChildren($category) } $children_count = compterFils($category, 0) - 1; - Database::query("UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'"); + $sql = "UPDATE $tbl_category SET children_count='$children_count' WHERE code='$category'"; + Database::query($sql); } /** @@ -192,7 +192,7 @@ function editNode($code, $name, $canHaveCourses, $old_code) $old_code = Database::escape_string($old_code); $canHaveCourses = Database::escape_string($canHaveCourses); - $code = generate_course_code($code); + $code = CourseManager::generate_course_code($code); // Updating category $sql = "UPDATE $tbl_category SET name='$name', code='$code', auth_course_child = '$canHaveCourses' WHERE code = '$old_code'"; @@ -689,12 +689,14 @@ function browseCoursesInCategory($category_code, $random_value = null, $limit = $url_access_id = api_get_current_access_url_id(); $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE); if ($category_code != "ALL") { - $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course + $sql = "SELECT * FROM $tbl_course as course + INNER JOIN $tbl_url_rel_course as url_rel_course ON (url_rel_course.course_code=course.code) WHERE access_url_id = $url_access_id AND category_code='$category_code' $without_special_courses $visibilityCondition ORDER BY title $limitFilter"; } else { - $sql = "SELECT * FROM $tbl_course as course INNER JOIN $tbl_url_rel_course as url_rel_course + $sql = "SELECT * FROM $tbl_course as course + INNER JOIN $tbl_url_rel_course as url_rel_course ON (url_rel_course.course_code=course.code) WHERE access_url_id = $url_access_id $without_special_courses $visibilityCondition ORDER BY title $limitFilter"; @@ -709,7 +711,7 @@ function browseCoursesInCategory($category_code, $random_value = null, $limit = $row['registration_code'] = !empty($row['registration_code']); $count_users = CourseManager::get_users_count_in_course($row['code']); $count_connections_last_month = Tracking::get_course_connections_count( - $row['code'], + $row['id'], 0, api_get_utc_datetime(time() - (30 * 86400)) ); diff --git a/main/inc/lib/course_request.lib.php b/main/inc/lib/course_request.lib.php index 6e52b0e7ed..f66f651e3b 100755 --- a/main/inc/lib/course_request.lib.php +++ b/main/inc/lib/course_request.lib.php @@ -86,7 +86,7 @@ class CourseRequestManager $request_date = api_get_utc_datetime(); $status = COURSE_REQUEST_PENDING; $info = 0; - $keys = define_course_keys($wanted_code, ''); + $keys = AddCourse::define_course_keys($wanted_code, ''); if (!count($keys)) { return false; } @@ -268,7 +268,7 @@ class CourseRequestManager if (self::course_code_exists($wanted_code)) { return false; } - $keys = define_course_keys($wanted_code, ''); + $keys = AddCourse::define_course_keys($wanted_code, ''); if (count($keys)) { $visual_code = $keys['currentCourseCode']; $code = $keys['currentCourseId']; diff --git a/main/inc/lib/database.constants.inc.php b/main/inc/lib/database.constants.inc.php index deab8d8ca9..04dde44317 100755 --- a/main/inc/lib/database.constants.inc.php +++ b/main/inc/lib/database.constants.inc.php @@ -345,7 +345,7 @@ define('TABLE_MAIN_SKILL_REL_PROFILE', 'skill_rel_profile'); define('TABLE_MAIN_CHAT', 'chat'); define('TABLE_TIMELINE', 'timeline'); -//Gradebook model +// Gradebook model define('TABLE_GRADE_MODEL', 'grade_model'); define('TABLE_GRADE_MODEL_COMPONENTS', 'grade_components'); diff --git a/main/inc/lib/database.lib.php b/main/inc/lib/database.lib.php index 28cbcdd019..b399a02452 100755 --- a/main/inc/lib/database.lib.php +++ b/main/inc/lib/database.lib.php @@ -1,9 +1,5 @@ - * @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,328 @@ 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); + $courseId = api_get_course_int_id(); + $reallyNow = api_get_utc_datetime(); + $user_id = api_get_user_id(); + $doc_id = intval($doc_id); + + $sql = "INSERT INTO ".$TABLETRACK_UPLOADS." + ( upload_user_id, + c_id, + upload_work_id, + upload_date, + upload_session_id + ) + VALUES ( + ".$user_id.", + '".$courseId."', + '".$doc_id."', + '".$reallyNow."', + '".api_get_session_id()."' + )"; + Database::query($sql); -/** - * @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; -} + 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 = ''; + } + + if (empty($end_date)) { + $end_date = api_get_utc_datetime(); + } - $sql = "UPDATE $TABLETRACK_EXERCICES SET + $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 +380,1466 @@ 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); + $res = Database::query($sql); - if ($debug) error_log('update_event_exercice called'); - if ($debug) error_log("$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; + //Deleting control time session track + //ExerciseLib::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']; - } + /** + * 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; + $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)) { + $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)) { + $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; + } - // 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; -} + $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT); -/** - * 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("----- entering saveQuestionAttempt() function ------"); + error_log("answer: $answer"); + error_log("score: $score"); + error_log("question_id : $question_id"); + error_log("position: $position"); + } - if (!empty($user_id)) { - $user_id = "'".$user_id."'"; - } else { - // anonymous - $user_id = api_get_anonymous_id(); - } + //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; + } - $file = ''; - if (isset($nano)) { - $file = Database::escape_string(basename($nano->load_filename_if_exists(false))); - } + $file = ''; + if (isset($nano)) { + $file = Database::escape_string(basename($nano->load_filename_if_exists(false))); + } - $course_code = api_get_course_id(); - $session_id = api_get_session_id(); + $session_id = api_get_session_id(); + $courseInfo = api_get_course_info_by_id($course_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, + 'course_code' => $courseInfo['real_id'], + '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; + } - if (!empty($question_id) && !empty($exe_id) && !empty($user_id)) { + if ($debug) { + error_log("updateResults : $updateResults"); + error_log("Saving question attempt: "); + error_log($sql); + } - // 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 + $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; } + } - $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); + /** + * 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 + ))); - $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); + } else { + $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_course_code, hotspot_user_id, c_id, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate) + VALUES ( + '".api_get_course_id()."', + ".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); } - 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; - } + /** + * 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); + } + } - $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); -} + $event_value = Database::escape_string($event_value); + $course_info = api_get_course_info($course_code); -/** - * 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']); + if (!empty($course_info)) { + $course_id = $course_info['real_id']; + } else { + $course_id = null; + $course_code = null; } - } - if (is_array($event_value)) { - $event_value = serialize($event_value); - } + if (!isset($datetime)) { + $datetime = api_get_utc_datetime(); + } - $event_value = Database::escape_string($event_value); - $course_info = api_get_course_info($course_code); + $datetime = Database::escape_string($datetime); - 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; - } + if (!isset($user_id)) { + $user_id = api_get_user_id(); + } - if (!isset($datetime)) { - $datetime = api_get_utc_datetime(); + $params = array( + 'default_user_id' => $user_id, + 'c_id' => $course_id, + 'default_date' => $datetime, + 'default_event_type' => $event_type, + 'default_value_type' => $event_value_type, + 'default_value' => $event_value, + ); + Database::insert($TABLETRACK_DEFAULT, $params); + return true; } - $datetime = Database::escape_string($datetime); - - if (!isset($user_id)) { - $user_id = api_get_user_id(); + /** + * 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; } - $user_id = intval($user_id); - - $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; -} - -/** - * Get every email stored in the database - * - * @param int $etId - * @return array - * @assert () !== false - */ -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; + /** + * 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); } - 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 - */ -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); + + //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); - $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); + if (Database::num_rows($result)) { + $view = Database::fetch_array($result, 'ASSOC'); + $lp_view_id = $view['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); - - 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); + $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 $lpInteraction - 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 $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); + 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 - "; + $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']; + } - $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); + } - $sql = "DELETE FROM $recording_table WHERE exe_id IN (".implode(',',$exe_list).")"; - Database::query($sql); + Event::addEvent( + LOG_LP_ATTEMPT_DELETE, + LOG_LP_ID, + $lp_id, + null, + null, + $course['code'], + $session_id + ); } - event_system( - LOG_LP_ATTEMPT_DELETE, - LOG_LP_ID, - $lp_id, - null, - null, - $course['code'], - $session_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 - */ -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_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 int $course_id + * @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 int $courseId + * @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 int $courseId + * @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 int $courseId + * @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 $user_id + * @param int exercise id + * @param int $courseId + * @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 $courseId + * @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 + /** + * @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'); - return $row['count']; -} + $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 int $courseId + * @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); - $course_code = Database::escape_string($course_code); - $user_id = intval($user_id); - $session_id = intval($session_id); - $session_lifetime = 3600; + $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); + $courseInfo = api_get_course_info_by_id($courseId); + Event::addEvent( + LOG_QUESTION_RESULT_DELETE, + LOG_EXERCISE_ATTEMPT_QUESTION_ID, + $exe_id . '-' . $question_id, + null, + null, + $courseInfo['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 int $courseId + * @param int $user_id + * @param int $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 = intval($courseId); + $user_id = intval($user_id); + $session_id = intval($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/events_email.class.php b/main/inc/lib/events_email.class.php index 9cb24455d5..2d6769b692 100755 --- a/main/inc/lib/events_email.class.php +++ b/main/inc/lib/events_email.class.php @@ -93,14 +93,11 @@ class EventsMail $recipient_name = api_get_person_name($user_info['firstname'], $user_info['lastname']); // checks if there's a file we need to join to the mail - if (isset($values["certificate_pdf_file"])) - { + if (isset($values["certificate_pdf_file"])) { $message = str_replace("\n", "
      ", $message); - @api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin, null, array($values['certificate_pdf_file'])); - } - else - { - @api_mail($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin); + api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin, null, array($values['certificate_pdf_file'])); + } else { + api_mail_html($recipient_name, $user_info["mail"], $subject, $message, $sender_name, $email_admin); } // If the mail only need to be send once (we know that thanks to the events.conf), we log it in the table @@ -150,7 +147,7 @@ class EventsMail // we send the mail $recipient_name = api_get_person_name($value['firstname'], $value['lastname']); - @api_mail($recipient_name, $value["email"], $subject, $message, $sender_name, $email_admin); + api_mail_html($recipient_name, $value["email"], $subject, $message, $sender_name, $email_admin); // If the mail only need to be send once (we know that thanks to the events.conf, we log it in the table if ($event_config[$event_name]["sending_mail_once"]) diff --git a/main/inc/lib/exercise.lib.php b/main/inc/lib/exercise.lib.php new file mode 100644 index 0000000000..350c061511 --- /dev/null +++ b/main/inc/lib/exercise.lib.php @@ -0,0 +1,3624 @@ + + * @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; + + $form = new FormValidator('free_choice_'.$questionId); + $config = array( + 'ToolbarSet' => 'TestFreeAnswer' + ); + $form->add_html_editor("choice[" . $questionId . "]", null, false, false, $config); + $form->setDefaults(array("choice[" . $questionId . "]" => $fck_content)); + $s .= $form->return_form(); + } 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(); + } + + $form = new FormValidator('free_choice_'.$questionId); + $config = array( + 'ToolbarSet' => 'TestFreeAnswer' + ); + $form->add_html_editor("choice[" . $questionId . "]", null, false, false, $config); + //$form->setDefaults(array("choice[" . $questionId . "]" => $fck_content)); + $s .= $form->return_form(); + } + + // 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_main_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_main_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_main_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_main_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_main_table( + TABLE_STATISTIC_TRACK_E_EXERCICES + ); + $TBL_TRACK_HOTPOTATOES = Database:: get_main_table( + TABLE_STATISTIC_TRACK_E_HOTPOTATOES + ); + $TBL_TRACK_ATTEMPT_RECORDING = Database:: get_main_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 = StatsUtils::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, + $courseId, + $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, + $courseId, + $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 int $courseId + * @param int $session_id + * + * @return array + */ + public static function get_best_attempt_in_course($exercise_id, $courseId, $session_id) + { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $courseId, + $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 int $courseId + * @param int $session_id + * + * @return array + */ + public static function get_best_attempt_by_user( + $user_id, + $exercise_id, + $courseId, + $session_id + ) { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $courseId, + $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 int $courseId + * @param int session id + * @return float Average score + */ + public static function get_average_score($exercise_id, $courseId, $session_id) + { + $user_results = Event::get_all_exercise_results( + $exercise_id, + $courseId, + $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 int $courseId + * @param int session id + * @return float Average score + */ + public static function get_average_score_by_course($courseId, $session_id) + { + $user_results = Event::get_all_exercise_results_by_course( + $courseId, + $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 = ($avg_score / count($user_results)); + } + + return $avg_score; + } + + /** + * @param int $user_id + * @param int $courseId + * @param int $session_id + * + * @return float|int + */ + public static function get_average_score_by_course_by_user( + $user_id, + $courseId, + $session_id + ) { + $user_results = Event::get_all_exercise_results_by_user( + $user_id, + $courseId, + $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 int $courseId + * @param int session id + * @return float Best average score + */ + public static function get_best_average_score_by_exercise( + $exercise_id, + $courseId, + $session_id, + $user_count + ) { + $user_results = Event::get_best_exercise_results_by_user( + $exercise_id, + $courseId, + $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; + } + + /** + * @param int $exe_id + */ + public static function create_chat_exercise_session($exe_id) + { + if (!isset($_SESSION['current_exercises'])) { + $_SESSION['current_exercises'] = array(); + } + $_SESSION['current_exercises'][$exe_id] = true; + } + + /** + * @param int $exe_id + */ + 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 .= self::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/extra_field.lib.php b/main/inc/lib/extra_field.lib.php index 59fbc6f131..058b1929db 100755 --- a/main/inc/lib/extra_field.lib.php +++ b/main/inc/lib/extra_field.lib.php @@ -917,7 +917,7 @@ class ExtraField extends Model break; case ExtraField::FIELD_TYPE_DATETIME: $form->addElement( - 'datepicker', + 'DatePicker', 'extra_'.$field_details['field_variable'], $field_details['field_display_text'], array('form_name' => $form_name) @@ -1230,7 +1230,6 @@ EOF; } break; case ExtraField::FIELD_TYPE_FILE: - require_once api_get_path(LIBRARY_PATH) . 'fileUpload.lib.php'; $fieldVariable = "extra_{$field_details['field_variable']}"; diff --git a/main/inc/lib/formvalidator/Element/DatePicker.php b/main/inc/lib/formvalidator/Element/DatePicker.php index 785659e633..d6aaff46de 100755 --- a/main/inc/lib/formvalidator/Element/DatePicker.php +++ b/main/inc/lib/formvalidator/Element/DatePicker.php @@ -1,8 +1,6 @@ _persistantFreeze = true; - $this->_appendName = true; - $this->_type = 'datepicker'; - $popup_link = ' - Select Date'; - - $hour_minute_devider = get_lang("HourMinuteDivider"); - $special_chars = array('D', 'l', 'd', 'M', 'F', 'm', 'y', 'H', 'a', 'A', 's', 'i', 'h', 'g', ' '); - foreach ($special_chars as $char) { - $popup_link = str_replace($char, "\\".$char, $popup_link); - $hour_minute_devider = str_replace($char, "\\".$char, $hour_minute_devider); - } - $lang_code = api_get_language_isocode(); - // If translation not available in PEAR::HTML_QuickForm_date, add the Chamilo-translation - if (!array_key_exists($lang_code,$this->_locale)) { - $this->_locale[$lang_code]['months_long'] = api_get_months_long(); - } - $this->_options['format'] = 'dFY '.$popup_link.' H '.$hour_minute_devider.' i'; - $this->_options['minYear'] = date('Y')-5; - $this->_options['maxYear'] = date('Y')+10; - $this->_options['language'] = $lang_code; - if (isset($optionIncrement)) { - $this->_options['optionIncrement']['i'] = intval($optionIncrement); - } - } - - /** - * HTML code to display this datepicker - */ - public function toHtml() - { - $js = $this->getElementJS(); - return $js.parent :: toHtml(); - } - - /** - * Get the necessary javascript for this datepicker - */ - function getElementJS() - { - $js = ''; - if (!defined('DATEPICKER_JAVASCRIPT_INCLUDED')) { - define('DATEPICKER_JAVASCRIPT_INCLUDED', 1); - $js = "\n"; - $js .= ''; - $js .= "\n"; - } - return $js; - } - - /** - * Export the date value in MySQL format - * @param array - * @param bool - * @return string YYYY-MM-DD HH:II:SS - */ - function exportValue(&$submitValues, $assoc = false) - { - $values = parent::getValue(); - $y = $values['Y'][0]; - $m = $values['F'][0]; - $d = $values['d'][0]; - $h = $values['H'][0]; - $i = $values['i'][0]; - $m = $m < 10 ? '0'.$m : $m; - $d = $d < 10 ? '0'.$d : $d; - $h = $h < 10 ? '0'.$h : $h; - $i = $i < 10 ? '0'.$i : $i; - $datetime = $y.'-'.$m.'-'.$d.' '.$h.':'.$i.':00'; - $result[$this->getName()]= $datetime; - return $result; - } - - /** - * Sets an option to a value - */ - function setLocalOption($name,$value) - { - $this->_options[$name] = $value; - } -} diff --git a/main/inc/lib/formvalidator/Element/receivers.php b/main/inc/lib/formvalidator/Element/receivers.php index 1ad16f1fed..ad35994946 100755 --- a/main/inc/lib/formvalidator/Element/receivers.php +++ b/main/inc/lib/formvalidator/Element/receivers.php @@ -1,8 +1,6 @@ form elements * @@ -35,7 +30,7 @@ require_once 'HTML/QuickForm/element.php'; * @author Hans De Bisschop * @abstract */ -class HTML_QuickForm_stylebutton extends HTML_QuickForm_element +class HTML_QuickForm_style_button extends HTML_QuickForm_element { // {{{ constructor /** @@ -48,7 +43,8 @@ class HTML_QuickForm_stylebutton extends HTML_QuickForm_element * @access public * @return void */ - function HTML_QuickForm_stylebutton($elementName=null, $elementLabel=null, $attributes=null) { + function HTML_QuickForm_style_button($elementName=null, $elementLabel=null, $attributes=null) + { $this->HTML_QuickForm_element($elementName, $elementLabel, $attributes); } //end constructor diff --git a/main/inc/lib/formvalidator/Element/style_reset_button.php b/main/inc/lib/formvalidator/Element/style_reset_button.php index 9a4ac4e4bc..160e8084fa 100755 --- a/main/inc/lib/formvalidator/Element/style_reset_button.php +++ b/main/inc/lib/formvalidator/Element/style_reset_button.php @@ -22,11 +22,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'style_button.php'; - /** * HTML class for a submit type element * @@ -37,7 +32,7 @@ require_once 'style_button.php'; * @version Release: 3.2.10 * @since 1.0 */ -class HTML_QuickForm_styleresetbutton extends HTML_QuickForm_stylebutton +class HTML_QuickForm_styleresetbutton extends HTML_QuickForm_style_button { // {{{ constructor @@ -53,7 +48,7 @@ class HTML_QuickForm_styleresetbutton extends HTML_QuickForm_stylebutton */ function HTML_QuickForm_styleresetbutton($elementName=null, $value=null, $attributes=null) { - HTML_QuickForm_stylebutton::HTML_QuickForm_stylebutton($elementName, null, $attributes, $value); + HTML_QuickForm_style_button::HTML_QuickForm_style_button($elementName, null, $attributes, $value); $this->setValue($value); $this->setType('reset'); } //end constructor diff --git a/main/inc/lib/formvalidator/Element/style_submit_button.php b/main/inc/lib/formvalidator/Element/style_submit_button.php index d01d38e948..91d6bda972 100755 --- a/main/inc/lib/formvalidator/Element/style_submit_button.php +++ b/main/inc/lib/formvalidator/Element/style_submit_button.php @@ -22,11 +22,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'style_button.php'; - /** * HTML class for a submit type element * @@ -37,7 +32,7 @@ require_once 'style_button.php'; * @version Release: 3.2.10 * @since 1.0 */ -class HTML_QuickForm_stylesubmitbutton extends HTML_QuickForm_stylebutton +class HTML_QuickForm_style_submit_button extends HTML_QuickForm_style_button { // {{{ constructor @@ -51,17 +46,17 @@ class HTML_QuickForm_stylesubmitbutton extends HTML_QuickForm_stylebutton * @access public * @return void */ - function HTML_QuickForm_stylesubmitbutton($elementName = null, $value = null, $attributes = null, $img = null) { + function HTML_QuickForm_style_submit_button($elementName = null, $value = null, $attributes = null, $img = null) { if (empty($attributes)) { $attributes = array(); } - + if (!isset($attributes['class'])) { if (is_array($attributes)) { $attributes['class'] = 'btn'; - } + } } - HTML_QuickForm_stylebutton::HTML_QuickForm_stylebutton($elementName, null, $attributes, $value, $img); + HTML_QuickForm_style_button::HTML_QuickForm_style_button($elementName, null, $attributes, $value, $img); $this->setValue($value); $this->setType('submit'); } //end constructor @@ -87,4 +82,4 @@ class HTML_QuickForm_stylesubmitbutton extends HTML_QuickForm_stylebutton return $this->_prepareValue($this->_findValue($submitValues), $assoc); } // }}} -} //end class HTML_QuickForm_submit \ No newline at end of file +} //end class HTML_QuickForm_submit diff --git a/main/inc/lib/formvalidator/FormValidator.class.php b/main/inc/lib/formvalidator/FormValidator.class.php index e0e7a0c8b8..b91b6e3cc5 100755 --- a/main/inc/lib/formvalidator/FormValidator.class.php +++ b/main/inc/lib/formvalidator/FormValidator.class.php @@ -1,15 +1,6 @@ defaultRenderer(); //Form template - $form_template = ' + $formTemplate = '
      {content}
      {hidden} '; - $renderer->setFormTemplate($form_template); + $renderer->setFormTemplate($formTemplate); //Element template if (isset($attributes['class']) && $attributes['class'] == 'well form-inline') { @@ -281,27 +272,49 @@ EOT; * @param string $name * @param string $value */ - function add_hidden($name, $value) + public function addHidden($name, $value) { $this->addElement('hidden', $name, $value); } + /** + * @param string $name + * @param string $label + * @param array $attributes + */ public function add_textarea($name, $label, $attributes = array()) { $this->addElement('textarea', $name, $label, $attributes); } - public function add_button($name, $label, $attributes = array()) + /** + * @param string $name + * @param string $label + * @param array $attributes + */ + public function addButton($name, $label, $attributes = array()) { + //$attributes['class'] = isset($attributes['class']) ? $attributes['class'] : 'btn btn-default'; $this->addElement('button', $name, $label, $attributes); } - public function add_checkbox($name, $label, $trailer = '', $attributes = array()) + /** + * @param string $name + * @param string $label + * @param string $trailer + * @param array $attributes + */ + public function addCheckBox($name, $label, $trailer = '', $attributes = array()) { $this->addElement('checkbox', $name, $label, $trailer, $attributes); } - public function add_radio($name, $label, $options = '') + /** + * @param string $name + * @param string $label + * @param array $options + */ + public function addRadio($name, $label, $options = array()) { $group = array(); foreach ($options as $key => $value) { @@ -310,26 +323,47 @@ EOT; $this->addGroup($group, $name, $label); } + /** + * @param string $name + * @param string $label + * @param string $options + * @param array $attributes + */ public function add_select($name, $label, $options = '', $attributes = array()) { $this->addElement('select', $name, $label, $options, $attributes); } + /** + * @param string $label + * @param string $text + */ public function add_label($label, $text) { $this->addElement('label', $label, $text); } - public function add_header($text) + /** + * @param string $text + */ + public function addHeader($text) { $this->addElement('header', $text); } + /** + * @param string $name + * @param string $label + * @param array $attributes + */ public function add_file($name, $label, $attributes = array()) { $this->addElement('file', $name, $label, $attributes); } + /** + * @param string $snippet + */ public function add_html($snippet) { $this->addElement('html', $snippet); @@ -347,7 +381,7 @@ EOT; * @param array $config (optional) Configuration settings for the online editor. * */ - public function add_html_editor($name, $label, $required = true, $full_page = false, $config = null) + public function add_html_editor($name, $label, $required = true, $fullPage = false, $config = null) { $this->addElement('html_editor', $name, $label, 'rows="15" cols="80"', $config); $this->applyFilter($name, 'trim'); @@ -355,9 +389,13 @@ EOT; $this->addRule($name, get_lang('ThisFieldIsRequired'), 'required'); } - /** @var HTML_QuickForm_html_editor $element */ + /** @var HtmlEditor $element */ $element = $this->getElement($name); + if ($fullPage) { + $config['FullPage'] = true; + } + if ($element->editor) { $element->editor->processConfig($config); } @@ -372,7 +410,7 @@ EOT; */ function add_datepicker($name, $label) { - $this->addElement('datepicker', $name, $label, array('form_name' => $this->getAttribute('name'))); + $this->addElement('DatePicker', $name, $label, array('form_name' => $this->getAttribute('name'))); $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900); // TODO: Now - 9 years $this->addRule($name, get_lang('InvalidDate'), 'date'); } @@ -386,7 +424,7 @@ EOT; */ public function add_datepickerdate($name, $label) { - $this->addElement('datepickerdate', $name, $label, array('form_name' => $this->getAttribute('name'))); + $this->addElement('DatePickerDate', $name, $label, array('form_name' => $this->getAttribute('name'))); $this->_elements[$this->_elementIndex[$name]]->setLocalOption('minYear', 1900); // TODO: Now - 9 years $this->addRule($name, get_lang('InvalidDate'), 'date'); } @@ -454,10 +492,6 @@ EOT; return; } - if (!class_exists('xajax')) { - require_once api_get_path(LIBRARY_PATH) . 'xajax/xajax.inc.php'; - } - $xajax_upload = new xajax(api_get_path(WEB_LIBRARY_PATH) . 'upload.xajax.php'); $xajax_upload->registerFunction('updateProgress'); @@ -604,7 +638,6 @@ EOT; */ function html_filter($html, $mode = NO_HTML) { - require_once api_get_path(LIBRARY_PATH) . 'formvalidator/Rule/HTML.php'; $allowed_tags = HTML_QuickForm_Rule_HTML::get_allowed_tags($mode); $cleaned_html = kses($html, $allowed_tags); return $cleaned_html; diff --git a/main/inc/lib/formvalidator/Rule/CompareFields.php b/main/inc/lib/formvalidator/Rule/CompareFields.php index 866a795e76..f36669f045 100755 --- a/main/inc/lib/formvalidator/Rule/CompareFields.php +++ b/main/inc/lib/formvalidator/Rule/CompareFields.php @@ -1,5 +1,6 @@ | // +----------------------------------------------------------------------+ -require_once('HTML/QuickForm/Rule.php'); - /** * Required elements validation * @version 1.0 diff --git a/main/inc/lib/formvalidator/Rule/Url.php b/main/inc/lib/formvalidator/Rule/Url.php index 5267aa7f07..9c6c9b3b1d 100755 --- a/main/inc/lib/formvalidator/Rule/Url.php +++ b/main/inc/lib/formvalidator/Rule/Url.php @@ -3,7 +3,6 @@ /** * Abstract base class for QuickForm validation rules */ -require_once 'HTML/QuickForm/Rule.php'; /** * Validate urls diff --git a/main/inc/lib/formvalidator/Rule/Username.php b/main/inc/lib/formvalidator/Rule/Username.php index 1761771b0e..0e67498b08 100755 --- a/main/inc/lib/formvalidator/Rule/Username.php +++ b/main/inc/lib/formvalidator/Rule/Username.php @@ -1,8 +1,6 @@ table = Database::get_main_table(TABLE_GRADE_MODEL); @@ -55,14 +58,6 @@ class GradeModel extends Model */ public function return_form($url, $action) { - /* - $oFCKeditor = new FCKeditor('description') ; - $oFCKeditor->ToolbarSet = 'grade_model'; - $oFCKeditor->Width = '100%'; - $oFCKeditor->Height = '200'; - $oFCKeditor->Value = ''; - $oFCKeditor->CreateHtml(); - */ $form = new FormValidator('grades', 'post', $url); // Setting the form elements @@ -77,7 +72,17 @@ class GradeModel extends Model $form->addElement('hidden', 'id', $id); $form->addElement('text', 'name', get_lang('Name'), array('size' => '70')); - $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250')); + $form->add_html_editor( + 'description', + get_lang('Description'), + false, + false, + array( + 'ToolbarSet' => 'careers', + 'Width' => '100%', + 'Height' => '250' + ) + ); $form->addElement('label', get_lang('Components')); 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/internationalization.lib.php b/main/inc/lib/internationalization.lib.php index f483e04c50..bba16b38e4 100755 --- a/main/inc/lib/internationalization.lib.php +++ b/main/inc/lib/internationalization.lib.php @@ -190,7 +190,6 @@ function get_lang($variable, $reserved = null, $language = null) { if (isset($language_files)) { $parent_language = null; if (api_get_setting('allow_use_sub_language') == 'true') { - require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php'; $parent_language = SubLanguageManager::get_parent_language_path($language); } if (!is_array($language_files)) { diff --git a/main/inc/lib/javascript/pear/qfamsHandler-min.js b/main/inc/lib/javascript/pear/qfamsHandler-min.js deleted file mode 100755 index b6f2f5c8f7..0000000000 --- a/main/inc/lib/javascript/pear/qfamsHandler-min.js +++ /dev/null @@ -1 +0,0 @@ -if(typeof QFAMS==="undefined"||!QFAMS){var QFAMS={}}QFAMS.env=QFAMS.env||{persistantSelection:false,persistantMove:true};QFAMS.updateCounter=function(c,v){var i;var nodeText=null;if(c!==null){if(c.childNodes){for(i=0;i0&&target.options[0].value===""){target.removeAttribute("disabled");target.options[0]=null}for(i=(maxFrom-1);i>=0;i--){if(action==='all'||action==='none'||action==='toggle'||source.options[i].selected===true){if(source.options[i].disabled===false){if(isIE){option=source.options[i].removeNode(true);option.selected=QFAMS.env.persistantSelection;target.appendChild(option)}else{option=source.options[i].cloneNode(true);option.selected=QFAMS.env.persistantSelection;target.options[target.options.length]=option}}}}if(!isIE){for(i=(maxFrom-1);i>=0;i--){if(action==='all'||action==='none'||action==='toggle'||source.options[i].selected===true){if(source.options[i].disabled===false){source.options[i]=null}}}}if(action==='toggle'){for(i=(maxTo-1);i>=0;i--){if(target.options[i].disabled===false){if(isIE){option=target.options[i].removeNode(true);option.selected=QFAMS.env.persistantSelection;source.appendChild(option)}else{option=target.options[i].cloneNode(true);option.selected=QFAMS.env.persistantSelection;source.options[source.options.length]=option}}}if(!isIE){for(i=(maxTo-1);i>=0;i--){if(target.options[i].disabled===false){target.options[i]=null}}}}c=document.getElementById(qfamsName+'_unselected');s=document.getElementById(qfamsName+'-f');QFAMS.updateCounter(c,s.length);c=document.getElementById(qfamsName+'_selected');s=document.getElementById(qfamsName+'-t');QFAMS.updateCounter(c,s.length);if(arrange!=='none'){QFAMS.sortList(target,QFAMS.compareText,arrange)}QFAMS.updateHidden(selectHidden,selectRight)};QFAMS.sortList=function(list,compareFunction,arrange){var i;var options=new Array(list.options.length);for(i=0;i0){QFAMS.moveSwap(l,indice,indice-1);QFAMS.updateHidden(h,l)}};QFAMS.moveDown=function(l,h){var indice=l.selectedIndex;if(indice<0){return}if(indice0){QFAMS.moveSwap(l,indice,indice-1);QFAMS.updateHidden(h,l);indice--}};QFAMS.moveBottom=function(l,h){var indice=l.selectedIndex;if(indice<0){return}while(indicej){l.insertBefore(node,l.options[j].nextSibling)}else{l.insertBefore(node,l.options[i])}if(QFAMS.env.persistantMove){l.selectedIndex=j}else{l.selectedIndex=-1}};QFAMS.init=function(elm){var e,i;for(e=0;e now() - INTERVAL $session_lifetime SECOND - ORDER BY login_course_date DESC LIMIT 0,1"; + WHERE + user_id = " . intval($_user ['user_id']) . " AND + c_id = '".api_get_course_int_id()."' AND + session_id = " . api_get_session_id() . " AND + login_course_date > now() - 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 = " . api_get_session_id(); - //error_log($sql); + WHERE course_access_id = " . intval($i_course_access_id) . " AND session_id = " . api_get_session_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['user_id'] . "', '$time', '$time', '1','" . api_get_session_id() . "')"; - //error_log($sql); + $sql = "INSERT INTO $course_tracking_table (c_id, user_id, login_course_date, logout_course_date, counter, session_id)" . + "VALUES('" . api_get_course_int_id() . "', '" . $_user['user_id'] . "', '$time', '$time', '1','" . api_get_session_id() . "')"; Database::query($sql); } } diff --git a/main/inc/lib/mail.lib.inc.php b/main/inc/lib/mail.lib.inc.php deleted file mode 100755 index a972292686..0000000000 --- a/main/inc/lib/mail.lib.inc.php +++ /dev/null @@ -1,239 +0,0 @@ - - * - * @param string name of recipient - * @param string email of recipient - * @param string email subject - * @param string email body - * @param string sender name - * @param string sender e-mail - * @param array extra headers in form $headers = array($name => $value) to allow parsing - * @param array data file (path and filename) - * @param array data to attach a file (optional) - * @param bool True for attaching a embedded file inside content html (optional) - * @return returns true if mail was sent - * @see class.phpmailer.php - */ -function api_mail_html( - $recipient_name, - $recipient_email, - $subject, - $message, - $senderName = '', - $senderEmail = '', - $extra_headers = array(), - $data_file = array(), - $embedded_image = false, - $additionalParameters = array() -) { - global $platform_email; - - $mail = new PHPMailer(); - $mail->Mailer = $platform_email['SMTP_MAILER']; - $mail->Host = $platform_email['SMTP_HOST']; - $mail->Port = $platform_email['SMTP_PORT']; - $mail->CharSet = $platform_email['SMTP_CHARSET']; - // Stay far below SMTP protocol 980 chars limit. - $mail->WordWrap = 200; - - if ($platform_email['SMTP_AUTH']) { - $mail->SMTPAuth = 1; - $mail->Username = $platform_email['SMTP_USER']; - $mail->Password = $platform_email['SMTP_PASS']; - } - - // 5 = low, 1 = high - $mail->Priority = 3; - $mail->SMTPKeepAlive = true; - - // Default values - $notification = new Notification(); - $defaultEmail = $notification->getDefaultPlatformSenderEmail(); - $defaultName = $notification->getDefaultPlatformSenderName(); - - // Error to admin. - $mail->AddCustomHeader('Errors-To: '.$defaultEmail); - - // If the parameter is set don't use the admin. - $senderName = !empty($senderName) ? $senderName : $defaultEmail; - $senderEmail = !empty($senderEmail) ? $senderEmail : $defaultName; - - // Reply to first - if (isset($extra_headers['reply_to'])) { - $mail->AddReplyTo( - $extra_headers['reply_to']['mail'], - $extra_headers['reply_to']['name'] - ); - $mail->Sender = $extra_headers['reply_to']['mail']; - unset($extra_headers['reply_to']); - } - - $mail->SetFrom($senderEmail, $senderName); - - $mail->Subject = $subject; - $mail->AltBody = strip_tags( - str_replace('
      ', "\n", api_html_entity_decode($message)) - ); - - // Send embedded image. - if ($embedded_image) { - // Get all images html inside content. - preg_match_all("/]*)[\"\']?[^>]*>/i", $message, $m); - // Prepare new tag images. - $new_images_html = array(); - $i = 1; - if (!empty($m[1])) { - foreach ($m[1] as $image_path) { - $real_path = realpath($image_path); - $filename = basename($image_path); - $image_cid = $filename.'_'.$i; - $encoding = 'base64'; - $image_type = mime_content_type($real_path); - $mail->AddEmbeddedImage( - $real_path, - $image_cid, - $filename, - $encoding, - $image_type - ); - $new_images_html[] = ''; - $i++; - } - } - - // Replace origin image for new embedded image html. - $x = 0; - if (!empty($m[0])) { - foreach ($m[0] as $orig_img) { - $message = str_replace($orig_img, $new_images_html[$x], $message); - $x++; - } - } - } - $message = str_replace(array("\n\r", "\n", "\r"), '
      ', $message); - $mail->Body = ''.$message.''; - - // Attachment ... - if (!empty($data_file)) { - $mail->AddAttachment($data_file['path'], $data_file['filename']); - } - - // Only valid addresses are accepted. - if (is_array($recipient_email)) { - foreach ($recipient_email as $dest) { - if (api_valid_email($dest)) { - $mail->AddAddress($dest, $recipient_name); - } - } - } else { - if (api_valid_email($recipient_email)) { - $mail->AddAddress($recipient_email, $recipient_name); - } else { - return 0; - } - } - - if (is_array($extra_headers) && count($extra_headers) > 0) { - foreach ($extra_headers as $key => $value) { - switch (strtolower($key)) { - case 'encoding': - case 'content-transfer-encoding': - $mail->Encoding = $value; - break; - case 'charset': - $mail->Charset = $value; - break; - case 'contenttype': - case 'content-type': - $mail->ContentType = $value; - break; - default: - $mail->AddCustomHeader($key.':'.$value); - break; - } - } - } else { - if (!empty($extra_headers)) { - $mail->AddCustomHeader($extra_headers); - } - } - - // WordWrap the html body (phpMailer only fixes AltBody) FS#2988 - $mail->Body = $mail->WrapText($mail->Body, $mail->WordWrap); - // Send the mail message. - if (!$mail->Send()) { - error_log('ERROR: mail not sent to '.$recipient_name.' ('.$recipient_email.') because of '.$mail->ErrorInfo.'
      '); - return 0; - } - - $plugin = new AppPlugin(); - $installedPluginsList = $plugin->getInstalledPluginListObject(); - foreach ($installedPluginsList as $installedPlugin) { - if ($installedPlugin->isMailPlugin and array_key_exists("smsType", $additionalParameters)) { - $className = str_replace("Plugin", "", get_class($installedPlugin)); - $smsObject = new $className; - $smsObject->send($additionalParameters); - } - } - - // Clear all the addresses. - $mail->ClearAddresses(); - return 1; -} diff --git a/main/inc/lib/message.lib.php b/main/inc/lib/message.lib.php index 429eb659a6..9115ef9700 100755 --- a/main/inc/lib/message.lib.php +++ b/main/inc/lib/message.lib.php @@ -1,27 +1,6 @@ $timestamp_login_date, 'logout' => $timestamp_logout_date,'course_code' => $row['course_code']); - } - return $connections; - } - - /** - * TODO: Not used, to b deleted? - * Enter description here... - * @param int $user_id - * @param string $course_code - * @param date $year - * @param date $month - * @param date $day - * @return unknown - */ - static function get_connections_to_course_by_time($user_id, $course_code, $year = '', $month = '', $day = '') { - // Database table definitions - $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); - - $sql = 'SELECT login_course_date, logout_course_date FROM ' . $tbl_track_course . ' - WHERE user_id = ' . intval($user_id) . ' - AND course_code="' . Database::escape_string($course_code) . '" - ORDER BY login_course_date DESC'; - - $rs = Database::query($sql); - $connections = array(); - while ($row = Database::fetch_array($rs)) { - $login_date = $row['login_course_date']; - $logout_date = $row['logout_course_date']; - $timestamp_login_date = strtotime($login_date); - $timestamp_logout_date = strtotime($logout_date); - $connections[] = array('login' => $timestamp_login_date, 'logout' => $timestamp_logout_date); + $connections[] = array( + 'login' => $timestamp_login_date, + 'logout' => $timestamp_logout_date, + 'c_id' => $row['c_id'] + ); } return $connections; } @@ -216,18 +199,23 @@ class MySpace $tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER); // getting all the courses of the user - $sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".intval($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." "; + $sql = "SELECT * FROM $tbl_course_user + WHERE user_id = '".intval($user_id)."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." "; $result = Database::query($sql); while ($row = Database::fetch_row($result)) { + $courseCode = $row[0]; + $courseInfo = api_get_course_info($courseCode); + $courseId = $courseInfo['real_id']; + $return .= ''; // course code - $return .= ' '.cut($row[0], 20, true).''; + $return .= ' '.cut($courseCode, 20, true).''; // time spent in the course - $return .= '
      '.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $row[0])).'
      '; + $return .= '
      '.api_time_to_hms(Tracking :: get_time_spent_on_the_course($user_id, $courseId)).'
      '; // student progress in course - $return .= '
      '.round(Tracking :: get_avg_student_progress($user_id, $row[0]), 2).'
      '; + $return .= '
      '.round(Tracking :: get_avg_student_progress($user_id, $courseCode), 2).'
      '; // student score - $avg_score = Tracking :: get_avg_student_score($user_id, $row[0]); + $avg_score = Tracking :: get_avg_student_score($user_id, $courseCode); if (is_numeric($avg_score)) { $avg_score = round($avg_score,2); } else { @@ -236,21 +224,17 @@ class MySpace $return .= '
      '.$avg_score.'
      '; // student tes score - //$return .= '
      '.round(Tracking :: get_avg_student_exercise_score ($user_id, $row[0]),2).'%
      '; + //$return .= '
      '.round(Tracking :: get_avg_student_exercise_score ($user_id, $courseCode),2).'%
      '; // student messages - $return .= '
      '.Tracking :: count_student_messages($user_id, $row[0]).'
      '; + $return .= '
      '.Tracking :: count_student_messages($user_id, $courseCode).'
      '; // student assignments - $return .= '
      '.Tracking :: count_student_assignments($user_id, $row[0]).'
      '; + $return .= '
      '.Tracking :: count_student_assignments($user_id, $courseCode).'
      '; // student exercises results (obtained score, maximum score, number of exercises answered, score percentage) - $exercises_results = MySpace::exercises_results($user_id, $row[0]); + $exercises_results = MySpace::exercises_results($user_id, $courseCode); $return .= '
      '.(is_null($exercises_results['percentage']) ? '' : $exercises_results['score_obtained'].'/'.$exercises_results['score_possible'].' ( '.$exercises_results['percentage'].'% )').'
      '; //$return .= '
      '.$exercises_results['score_possible'].'
      '; $return .= '
      '.$exercises_results['questions_answered'].'
      '; - //$return .= '
      '.$exercises_results['percentage'].'%
      '; - // first connection - //$return .= ' '.Tracking :: get_first_connection_date_on_the_course ($user_id, $row[0]).''; - // last connection - $return .= '
      '.Tracking :: get_last_connection_date_on_the_course ($user_id, $row[0]).'
      '; + $return .= '
      '.Tracking :: get_last_connection_date_on_the_course ($user_id, $courseId).'
      '; $return .= ''; } $return .= ''; @@ -1239,16 +1223,21 @@ class MySpace public static function course_tracking_filter($course_code, $url_params, $row) { $course_code = $row[0]; + $courseInfo = api_get_course_info($course_code); + // the table header $return = ''; // database table definition $tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER); - $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE); $tbl_user = Database :: get_main_table(TABLE_MAIN_USER); // getting all the courses of the user - $sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);"; + $sql = "SELECT * + FROM $tbl_user AS u + INNER JOIN $tbl_course_rel_user AS cu + ON cu.user_id = u.user_id + WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);"; $result = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1263,7 +1252,7 @@ class MySpace $total_questions_answered = 0; while ($row = Database::fetch_object($result)) { // get time spent in the course and session - $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code); + $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $courseInfo['real_id']); $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true); $progress += $progress_tmp[0]; $nb_progress_lp += $progress_tmp[1]; @@ -1274,8 +1263,7 @@ class MySpace } $nb_messages += Tracking::count_student_messages($row->user_id, $course_code); $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code); - - $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false); + $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $courseInfo['real_id'], null, false); if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned $last_login_date = $last_login_date_tmp; } else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition. To be cleaned. @@ -1344,7 +1332,6 @@ class MySpace { // database table definition $tbl_course_rel_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER); - $tbl_course = Database :: get_main_table(TABLE_MAIN_COURSE); $tbl_user = Database :: get_main_table(TABLE_MAIN_USER); // the values of the sortable table @@ -1387,13 +1374,19 @@ class MySpace // the other lines (the data) foreach ($course_data as $key => $course) { $course_code = $course[0]; - $course_title = $course[1]; + $courseInfo = api_get_course_info($course_code); + $course_title = $courseInfo['title']; + $courseId = $courseInfo['real_id']; $csv_row = array(); $csv_row[] = $course_title; // getting all the courses of the session - $sql = "SELECT * FROM $tbl_user AS u INNER JOIN $tbl_course_rel_user AS cu ON cu.user_id = u.user_id WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);"; + $sql = "SELECT * + FROM $tbl_user AS u + INNER JOIN $tbl_course_rel_user AS cu + ON cu.user_id = u.user_id + WHERE cu.course_code = '".$course_code."' AND ISNULL(cu.role);"; $result = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1408,7 +1401,7 @@ class MySpace $total_questions_answered = 0; while ($row = Database::fetch_object($result)) { // get time spent in the course and session - $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $course_code); + $time_spent += Tracking::get_time_spent_on_the_course($row->user_id, $courseId); $progress_tmp = Tracking::get_avg_student_progress($row->user_id, $course_code, array(), null, true); $progress += $progress_tmp[0]; $nb_progress_lp += $progress_tmp[1]; @@ -1420,7 +1413,7 @@ class MySpace $nb_messages += Tracking::count_student_messages($row->user_id, $course_code); $nb_assignments += Tracking::count_student_assignments($row->user_id, $course_code); - $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $course_code, null, false); + $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row->user_id, $courseId, null, false); if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned. $last_login_date = $last_login_date_tmp; } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned. @@ -1602,14 +1595,24 @@ class MySpace $tbl_user = Database :: get_main_table(TABLE_MAIN_USER); // getting all the courses of the user - $sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';"; + $sql = "SELECT * FROM $tbl_course AS c + INNER JOIN $tbl_session_rel_course AS sc + ON sc.course_code = c.code + WHERE sc.id_session = '".$session_id."';"; $result = Database::query($sql); while ($row = Database::fetch_object($result)) { + $courseCode = $row->code; + $courseInfo = api_get_course_info($row->code); + $courseId = $courseInfo['real_id']; $return .= ''; // course code $return .= ' '; // get the users in the course - $sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';"; + $sql = "SELECT user_id + FROM $tbl_user AS u + INNER JOIN $tbl_session_rel_course_rel_user AS scu + ON u.user_id = scu.id_user + WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$courseCode."';"; $result_users = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1624,7 +1627,7 @@ class MySpace $total_questions_answered = 0; while($row_user = Database::fetch_object($result_users)) { // get time spent in the course and session - $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id); + $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id); $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true); $progress += $progress_tmp[0]; $nb_progress_lp += $progress_tmp[1]; @@ -1635,8 +1638,7 @@ class MySpace } $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id); $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id); - - $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false); + $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $courseId, $session_id, false); if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned. $last_login_date = $last_login_date_tmp; } else if($last_login_date_tmp != false && $last_login_date != false) { // TODO: Repeated previous condition! To be cleaned. @@ -1753,14 +1755,22 @@ class MySpace $session_title = $session[1]; // getting all the courses of the session - $sql = "SELECT * FROM $tbl_course AS c INNER JOIN $tbl_session_rel_course AS sc ON sc.course_code = c.code WHERE sc.id_session = '".$session_id."';"; + $sql = "SELECT * FROM $tbl_course AS c + INNER JOIN $tbl_session_rel_course AS sc + ON sc.course_code = c.code + WHERE sc.id_session = '".$session_id."';"; $result = Database::query($sql); while ($row = Database::fetch_object($result)) { + $courseInfo = api_get_course_info($row->code); + $courseId = $courseInfo['real_id']; $csv_row = array(); $csv_row[] = $session_title; $csv_row[] = $row->title; // get the users in the course - $sql = "SELECT user_id FROM $tbl_user AS u INNER JOIN $tbl_session_rel_course_rel_user AS scu ON u.user_id = scu.id_user WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';"; + $sql = "SELECT user_id FROM $tbl_user AS u + INNER JOIN $tbl_session_rel_course_rel_user AS scu + ON u.user_id = scu.id_user + WHERE scu.id_session = '".$session_id."' AND scu.course_code = '".$row->code."';"; $result_users = Database::query($sql); $time_spent = 0; $progress = 0; @@ -1775,7 +1785,7 @@ class MySpace $total_questions_answered = 0; while($row_user = Database::fetch_object($result_users)) { // get time spent in the course and session - $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $row->code, $session_id); + $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id); $progress_tmp = Tracking::get_avg_student_progress($row_user->user_id, $row->code, array(), $session_id, true); $progress += $progress_tmp[0]; $nb_progress_lp += $progress_tmp[1]; @@ -1787,7 +1797,7 @@ class MySpace $nb_messages += Tracking::count_student_messages($row_user->user_id, $row->code, $session_id); $nb_assignments += Tracking::count_student_assignments($row_user->user_id, $row->code, $session_id); - $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $row->code, $session_id, false); + $last_login_date_tmp = Tracking :: get_last_connection_date_on_the_course ($row_user->user_id, $courseId, $session_id, false); if($last_login_date_tmp != false && $last_login_date == false) { // TODO: To be cleaned. $last_login_date = $last_login_date_tmp; } else if($last_login_date_tmp != false && $last_login_date == false) { // TODO: Repeated previous condition. To be cleaned. @@ -1975,9 +1985,13 @@ class MySpace // the other lines (the data) foreach ($user_data as $key => $user) { // getting all the courses of the user - $sql = "SELECT * FROM $tbl_course_user WHERE user_id = '".intval($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." "; + $sql = "SELECT * FROM $tbl_course_user + WHERE user_id = '".intval($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." "; $result = Database::query($sql); while ($row = Database::fetch_row($result)) { + $courseInfo = api_get_course_info($row['course_code']); + $courseId = $courseInfo['real_id']; + $csv_row = array(); // user official code $csv_row[] = $user[0]; @@ -1998,7 +2012,7 @@ class MySpace } } // time spent in the course - $csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $row[0])); + $csv_row[] = api_time_to_hms(Tracking :: get_time_spent_on_the_course ($user[4], $courseId)); // student progress in course $csv_row[] = round(Tracking :: get_avg_student_progress ($user[4], $row[0]), 2); // student score @@ -2016,9 +2030,9 @@ class MySpace $csv_row[] = $exercises_results['questions_answered']; $csv_row[] = $exercises_results['percentage']; // first connection - $csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $row[0]); + $csv_row[] = Tracking :: get_first_connection_date_on_the_course ($user[4], $courseId); // last connection - $csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $row[0])); + $csv_row[] = strip_tags(Tracking :: get_last_connection_date_on_the_course ($user[4], $courseId)); $csv_content[] = $csv_row; } @@ -2062,20 +2076,23 @@ class MySpace $res = Database::query($sql); while ($row_course = Database::fetch_row($res)) { - $course_code = $row_course[0]; - $course_info = api_get_course_info($course_code); + $courseInfo = api_get_course_info($course_code); $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0; // students directly subscribed to the course if (empty($session_id)) { - $sql = "SELECT user_id FROM $tbl_course_user as course_rel_user WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'"; + $sql = "SELECT user_id FROM $tbl_course_user as course_rel_user + WHERE course_rel_user.status='5' AND course_rel_user.course_code='$course_code'"; } else { - $sql = "SELECT id_user as user_id FROM $tbl_session_course_user srcu WHERE srcu. course_code='$course_code' AND id_session = '$session_id' AND srcu.status<>2"; + $sql = "SELECT id_user as user_id FROM $tbl_session_course_user srcu + WHERE srcu. course_code='$course_code' AND id_session = '$session_id' AND srcu.status<>2"; } $rs = Database::query($sql); $users = array(); - while ($row = Database::fetch_array($rs)) { $users[] = $row['user_id']; } + while ($row = Database::fetch_array($rs)) { + $users[] = $row['user_id']; + } if (count($users) > 0) { $nb_students_in_course = count($users); @@ -2084,7 +2101,7 @@ class MySpace $avg_progress_in_course = Tracking::get_avg_student_progress($users, $course_code, array(), $session_id); $avg_score_in_course = Tracking::get_avg_student_score($users, $course_code, array(), $session_id); $avg_score_in_exercise = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id); - $avg_time_spent_in_course = Tracking::get_time_spent_on_the_course($users, $course_code, $session_id); + $avg_time_spent_in_course = Tracking::get_time_spent_on_the_course($users, $courseInfo['real_id'], $session_id); $avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2); if (is_numeric($avg_score_in_course)) { @@ -2641,13 +2658,19 @@ class MySpace } } - -function get_stats($user_id, $course_code, $start_date = null, $end_date = null) { +/** + * @param $user_id + * @param int $courseId + * @param null $start_date + * @param null $end_date + * @return array + */ +function get_stats($user_id, $courseId, $start_date = null, $end_date = null) +{ // Database table definitions - $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); - $tbl_main = Database :: get_main_table(TABLE_MAIN_COURSE); + $tbl_track_course = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); - $course_info = api_get_course_info($course_code); + $course_info = api_get_course_info_by_id($courseId); if (!empty($course_info)) { $strg_sd = ""; $strg_ed = ""; @@ -2656,13 +2679,15 @@ function get_stats($user_id, $course_code, $start_date = null, $end_date = null) $strg_sd = "AND login_course_date BETWEEN '$start_date' AND '$end_date'"; $strg_ed = "AND logout_course_date BETWEEN '$start_date' AND '$end_date'"; } - $sql = 'SELECT SEC_TO_TIME(avg(time_to_sec(timediff(logout_course_date,login_course_date)))) as avrg, - SEC_TO_TIME(sum(time_to_sec(timediff(logout_course_date,login_course_date)))) as total, - count(user_id) as times - FROM ' . $tbl_track_course . ' - WHERE user_id = ' . intval($user_id) . ' - AND course_code = "' . Database::escape_string($course_code) . '" '.$strg_sd.' '.$strg_ed.' '.' - ORDER BY login_course_date ASC'; + $sql = 'SELECT + SEC_TO_TIME(avg(time_to_sec(timediff(logout_course_date,login_course_date)))) as avrg, + SEC_TO_TIME(sum(time_to_sec(timediff(logout_course_date,login_course_date)))) as total, + count(user_id) as times + FROM ' . $tbl_track_course . ' + WHERE + user_id = ' . intval($user_id) . ' AND + c_id = "' . intval($courseId) . '" '.$strg_sd.' '.$strg_ed.' '.' + ORDER BY login_course_date ASC'; $rs = Database::query($sql); $result = array(); @@ -2689,18 +2714,19 @@ function add_day_to($end_date) { * Gets the connections to a course as an array of login and logout time * * @param int $user_id - * @param string $course_code + * @param int $courseId * @author Jorge Frisancho Jibaja * @author Julio Montoya fixing the function * @version OCT-22- 2010 * @return array */ -function get_connections_to_course_by_date($user_id, $course_code, $start_date, $end_date) +function get_connections_to_course_by_date($user_id, $courseId, $start_date, $end_date) { // Database table definitions - $tbl_track_course = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); - $course_info = api_get_course_info($course_code); + $tbl_track_course = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS); + $course_info = api_get_course_info_by_id($courseId); $user_id = intval($user_id); + $courseId = intval($courseId); $connections = array(); if (!empty($course_info)) { @@ -2709,7 +2735,7 @@ function get_connections_to_course_by_date($user_id, $course_code, $start_date, FROM $tbl_track_course WHERE user_id = $user_id AND - course_code = '$course_code' AND + c_id = '$courseId' AND login_course_date BETWEEN '$start_date' AND '$end_date' AND logout_course_date BETWEEN '$start_date' AND '$end_date' ORDER BY login_course_date ASC"; diff --git a/main/inc/lib/nanogong.lib.php b/main/inc/lib/nanogong.lib.php index 0029893dd5..d0a111ec34 100755 --- a/main/inc/lib/nanogong.lib.php +++ b/main/inc/lib/nanogong.lib.php @@ -286,7 +286,6 @@ class Nanogong */ public function upload_file($is_nano = false) { - require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; if (!empty($_FILES)) { $upload_ok = process_uploaded_file($_FILES['file'], false); diff --git a/main/inc/lib/nanogong/receiver.php b/main/inc/lib/nanogong/receiver.php index 388d1280a1..43814f0a70 100755 --- a/main/inc/lib/nanogong/receiver.php +++ b/main/inc/lib/nanogong/receiver.php @@ -13,7 +13,6 @@ * Code */ require_once '../../../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; api_protect_course_script(); api_block_anonymous_users(); diff --git a/main/inc/lib/nanogong/upload_nanogong_file.php b/main/inc/lib/nanogong/upload_nanogong_file.php index e7c75788f2..3b8e3025d6 100755 --- a/main/inc/lib/nanogong/upload_nanogong_file.php +++ b/main/inc/lib/nanogong/upload_nanogong_file.php @@ -13,7 +13,6 @@ * Code */ require_once '../../../inc/global.inc.php'; -require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php'; api_protect_course_script(); api_block_anonymous_users(); diff --git a/main/inc/lib/online.inc.php b/main/inc/lib/online.inc.php index 70aa53ccdb..f0e2d1b0f6 100755 --- a/main/inc/lib/online.inc.php +++ b/main/inc/lib/online.inc.php @@ -38,7 +38,7 @@ function LoginCheck($uid) { // if the $_course array exists this means we are in a course and we have to store this in the who's online table also // to have the x users in this course feature working if (is_array($_course) && count($_course)>0 && !empty($_course['id'])) { - $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, course, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['id']."' , '$session_id' , '$access_url_id' )"; + $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, c_id, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '".$_course['real_id']."' , '$session_id' , '$access_url_id' )"; } else { $query = "REPLACE INTO ".$online_table ." (login_id,login_user_id,login_date,login_ip, session_id, access_url_id) VALUES ($uid,$uid,'$login_date','$login_ip', '$session_id', '$access_url_id')"; } @@ -97,7 +97,7 @@ function online_logout($user_id = null, $logout_redirect = false) { global $_configuration, $extAuthSource; // Database table definition - $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN); + $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN); if (empty($user_id)) { $user_id = intval($_GET['uid']); @@ -159,10 +159,10 @@ function online_logout($user_id = null, $logout_redirect = false) { */ function LoginDelete($user_id) { - $online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE); + $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE); $user_id = intval($user_id); $query = "DELETE FROM ".$online_table ." WHERE login_user_id = '".$user_id."'"; - @Database::query($query); + Database::query($query); } /** @@ -171,7 +171,7 @@ function LoginDelete($user_id) */ function user_is_online($user_id) { - $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE); + $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE); $table_user = Database::get_main_table(TABLE_MAIN_USER); $access_url_id = api_get_current_access_url_id(); @@ -230,7 +230,7 @@ function who_is_online($from, $number_of_items, $column = null, $direction = nul $online_time = time() - $time_limit*60; $current_date = api_get_utc_datetime($online_time); - $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE); + $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE); $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER); $table_user = Database::get_main_table(TABLE_MAIN_USER); $query = ''; @@ -272,7 +272,8 @@ function who_is_online($from, $number_of_items, $column = null, $direction = nul LIMIT $from, $number_of_items"; } else { // all users online - $query = "SELECT login_user_id, login_date FROM ".$track_online_table ." track + $query = "SELECT login_user_id, login_date + FROM ".$track_online_table ." track INNER JOIN ".$table_user ." u ON (u.user_id=track.login_user_id) WHERE u.status != ".ANONYMOUS." AND track.access_url_id = $access_url_id AND @@ -308,7 +309,7 @@ function who_is_online_count($time_limit = null, $friends = false) } else { $time_limit = intval($time_limit); } - $track_online_table = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ONLINE); + $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE); $friend_user_table = Database::get_main_table(TABLE_MAIN_USER_REL_USER); $table_user = Database::get_main_table(TABLE_MAIN_USER); @@ -395,12 +396,14 @@ function who_is_online_in_this_course($from, $number_of_items, $uid, $time_limit $current_date = api_get_utc_datetime($online_time); $track_online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE); $course_code = Database::escape_string($course_code); + $courseInfo = api_get_course_info($course_code); + $courseId = $courseInfo['real_id']; $from = intval($from); $number_of_items = intval($number_of_items); $query = "SELECT login_user_id, login_date FROM $track_online_table - WHERE login_user_id <> 2 AND course='$course_code' AND login_date >= '$current_date' + WHERE login_user_id <> 2 AND c_id='$courseId' AND login_date >= '$current_date' LIMIT $from, $number_of_items "; $result = Database::query($query); @@ -430,10 +433,12 @@ function who_is_online_in_this_course_count($uid, $time_limit, $coursecode=null) $online_time = time() - $time_limit * 60; $current_date = api_get_utc_datetime($online_time); + $courseInfo = api_get_course_info($coursecode); + $courseId = $courseInfo['real_id']; $query = "SELECT count(login_user_id) as count FROM ".$track_online_table ." - WHERE login_user_id <> 2 AND course='".$coursecode."' AND login_date >= '$current_date' "; + WHERE login_user_id <> 2 AND c_id='".$courseId."' AND login_date >= '$current_date' "; $result = Database::query($query); if (Database::num_rows($result) > 0) { $row = Database::fetch_array($result); diff --git a/main/inc/lib/pear/HTML/Common.php b/main/inc/lib/pear/HTML/Common.php index cef3d2eb84..80766c4f96 100755 --- a/main/inc/lib/pear/HTML/Common.php +++ b/main/inc/lib/pear/HTML/Common.php @@ -77,7 +77,7 @@ class HTML_Common * @param int $tabOffset Indent offset in tabs * @access public */ - function HTML_Common($attributes = null, $tabOffset = 0) + public function HTML_Common($attributes = null, $tabOffset = 0) { $this->setAttributes($attributes); $this->setTabOffset($tabOffset); @@ -130,11 +130,11 @@ class HTML_Common /** * Returns an HTML formatted attribute string - * @param array $attributes + * @param array $attributes * @return string * @access private */ - function _getAttrString($attributes) + public function _getAttrString($attributes) { $strAttr = ''; @@ -142,17 +142,16 @@ class HTML_Common $charset = HTML_Common::charset(); foreach ($attributes as $key => $value) { // Modified by Ivan Tcholakov, 16-MAR-2010 - //$strAttr .= ' ' . $key . '="' . htmlspecialchars($value, ENT_COMPAT, $charset) . '"'; - $strAttr .= ' ' . $key . '="' . @htmlspecialchars($value, ENT_COMPAT, $charset) . '"'; - // + $value = @htmlspecialchars($value, ENT_COMPAT, $charset); + $strAttr .= ' ' . $key . '= "' . $value. '"'; } } return $strAttr; - } // end func _getAttrString + } /** - * Returns a valid atrributes array from either a string or array - * @param mixed $attributes Either a typical HTML attribute string or an associative array + * Returns a valid attributes array from either a string or array + * @param mixed $attributes Either a typical HTML attribute string or an associative array * @access private * @return array */ @@ -470,5 +469,4 @@ class HTML_Common } return $charset; } // end func charset -} // end class HTML_Common -?> +} diff --git a/main/inc/lib/pear/HTML/QuickForm.php b/main/inc/lib/pear/HTML/QuickForm.php index b7e28b4f67..a18e48369e 100755 --- a/main/inc/lib/pear/HTML/QuickForm.php +++ b/main/inc/lib/pear/HTML/QuickForm.php @@ -23,45 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * PEAR and PEAR_Error classes, for error handling - */ -require_once 'PEAR.php'; - -/** - * Element types known to HTML_QuickForm - * @see HTML_QuickForm::registerElementType(), HTML_QuickForm::getRegisteredTypes(), - * HTML_QuickForm::isTypeRegistered() - * @global array $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] - */ -$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array( - 'group' => array('HTML/QuickForm/group.php','HTML_QuickForm_group'), - 'hidden' => array('HTML/QuickForm/hidden.php','HTML_QuickForm_hidden'), - 'reset' => array('HTML/QuickForm/reset.php','HTML_QuickForm_reset'), - 'checkbox' => array('HTML/QuickForm/checkbox.php','HTML_QuickForm_checkbox'), - 'file' => array('HTML/QuickForm/file.php','HTML_QuickForm_file'), - 'image' => array('HTML/QuickForm/image.php','HTML_QuickForm_image'), - 'password' => array('HTML/QuickForm/password.php','HTML_QuickForm_password'), - 'radio' => array('HTML/QuickForm/radio.php','HTML_QuickForm_radio'), - 'button' => array('HTML/QuickForm/button.php','HTML_QuickForm_button'), - 'submit' => array('HTML/QuickForm/submit.php','HTML_QuickForm_submit'), - 'select' => array('HTML/QuickForm/select.php','HTML_QuickForm_select'), - 'hiddenselect' => array('HTML/QuickForm/hiddenselect.php','HTML_QuickForm_hiddenselect'), - 'text' => array('HTML/QuickForm/text.php','HTML_QuickForm_text'), - 'textarea' => array('HTML/QuickForm/textarea.php','HTML_QuickForm_textarea'), - 'link' => array('HTML/QuickForm/link.php','HTML_QuickForm_link'), - 'advcheckbox' => array('HTML/QuickForm/advcheckbox.php','HTML_QuickForm_advcheckbox'), - 'date' => array('HTML/QuickForm/date.php','HTML_QuickForm_date'), - 'static' => array('HTML/QuickForm/static.php','HTML_QuickForm_static'), - 'header' => array('HTML/QuickForm/header.php', 'HTML_QuickForm_header'), - 'html' => array('HTML/QuickForm/html.php', 'HTML_QuickForm_html'), - 'hierselect' => array('HTML/QuickForm/hierselect.php', 'HTML_QuickForm_hierselect'), - 'autocomplete' => array('HTML/QuickForm/autocomplete.php', 'HTML_QuickForm_autocomplete'), - 'xbutton' => array('HTML/QuickForm/xbutton.php','HTML_QuickForm_xbutton'), - 'advanced_settings' => array('HTML/QuickForm/advanced_settings.php','HTML_QuickForm_advanced_settings'), - 'label' => array('HTML/QuickForm/label.php','HTML_QuickForm_label'), - 'email' => array('HTML/QuickForm/email.php','HTML_QuickForm_email') -); /** * Validation rules known to HTML_QuickForm @@ -394,9 +355,8 @@ class HTML_QuickForm extends HTML_Common * @access public * @return void */ - function registerRule($ruleName, $type, $data1, $data2 = null) + public static function registerRule($ruleName, $type, $data1, $data2 = null) { - include_once('HTML/QuickForm/RuleRegistry.php'); $registry =& HTML_QuickForm_RuleRegistry::singleton(); $registry->registerRule($ruleName, $type, $data1, $data2); } // end func registerRule @@ -601,19 +561,18 @@ class HTML_QuickForm extends HTML_Common * @return HTML_QuickForm_Element * @throws HTML_QuickForm_Error */ - function &_loadElement($event, $type, $args) + public function &_loadElement($event, $type, $args) { - $type = strtolower($type); - if (!HTML_QuickForm::isTypeRegistered($type)) { - $error = PEAR::raiseError(null, QUICKFORM_UNREGISTERED_ELEMENT, null, E_USER_WARNING, "Element '$type' does not exist in HTML_QuickForm::_loadElement()", 'HTML_QuickForm_Error', true); - return $error; + $lowerType = strtolower($type); + $className = 'HTML_QuickForm_'.$lowerType; + // Try classic class name HTML_QuickForm_ + if (!class_exists($className)) { + // Try new class name CamelCase + $className = underScoreToCamelCase($type); + if (!class_exists($className)) { + throw new \Exception("Class '$className' does not exist. "); + } } - $className = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][1]; - $includeFile = $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'][$type][0]; - - include_once $includeFile; - // Modified by Ivan Tcholakov, 16-MAR-2010. Suppressing a deprecation warning on PHP 5.3 - //$elementObject =& new $className(); $elementObject = new $className(); for ($i = 0; $i < 5; $i++) { @@ -626,7 +585,7 @@ class HTML_QuickForm extends HTML_Common return $err; } return $elementObject; - } // end func _loadElement + } // }}} // {{{ addElement() @@ -1737,7 +1696,7 @@ class HTML_QuickForm extends HTML_Common * * @access public * @since 3.0 - * @return object a default renderer object + * @return HTML_QuickForm_Renderer_Default */ function &defaultRenderer() { if (!isset($GLOBALS['_HTML_QuickForm_default_renderer'])) { diff --git a/main/inc/lib/pear/HTML/QuickForm/Action/Back.php b/main/inc/lib/pear/HTML/QuickForm/Action/Back.php index 29a678e024..1fbb02f84a 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Action/Back.php +++ b/main/inc/lib/pear/HTML/QuickForm/Action/Back.php @@ -1,38 +1,33 @@ - * @copyright 2003-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version SVN: $Id: Back.php 289084 2009-10-02 06:53:09Z avb $ - * @link http://pear.php.net/package/HTML_QuickForm_Controller - */ - -/** - * Class representing an action to perform on HTTP request. - */ -require_once 'HTML/QuickForm/Action.php'; +/** + * The action for a 'back' button of wizard-type multipage form. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @copyright 2003-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version SVN: $Id: Back.php 289084 2009-10-02 06:53:09Z avb $ + * @link http://pear.php.net/package/HTML_QuickForm_Controller + */ /** * The action for a 'back' button of wizard-type multipage form. * - * @category HTML - * @package HTML_QuickForm_Controller - * @author Alexey Borzov - * @version Release: 1.0.10 + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @version Release: 1.0.10 */ class HTML_QuickForm_Action_Back extends HTML_QuickForm_Action { @@ -44,10 +39,10 @@ class HTML_QuickForm_Action_Back extends HTML_QuickForm_Action $data =& $page->controller->container(); $data['values'][$pageName] = $page->exportValues(); if (!$page->controller->isModal()) { - if (PEAR::isError($valid = $page->validate())) { - return $valid; - } - $data['valid'][$pageName] = $valid; + if (PEAR::isError($valid = $page->validate())) { + return $valid; + } + $data['valid'][$pageName] = $valid; } // get the previous page and go to it diff --git a/main/inc/lib/pear/HTML/QuickForm/Action/Direct.php b/main/inc/lib/pear/HTML/QuickForm/Action/Direct.php index 25d7bab62a..f41fbac9f4 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Action/Direct.php +++ b/main/inc/lib/pear/HTML/QuickForm/Action/Direct.php @@ -1,6 +1,6 @@ - * @version Release: 1.0.10 - */ -class HTML_QuickForm_Action_Direct extends HTML_QuickForm_Action -{ - function perform(&$page, $actionName) - { - // save the form values and validation status to the session - $page->isFormBuilt() or $page->buildForm(); - $pageName = $page->getAttribute('id'); - $data =& $page->controller->container(); - $data['values'][$pageName] = $page->exportValues(); + */ +class HTML_QuickForm_Action_Direct extends HTML_QuickForm_Action +{ + function perform(&$page, $actionName) + { + // save the form values and validation status to the session + $page->isFormBuilt() or $page->buildForm(); + $pageName = $page->getAttribute('id'); + $data =& $page->controller->container(); + $data['values'][$pageName] = $page->exportValues(); if (PEAR::isError($valid = $page->validate())) { return $valid; } $data['valid'][$pageName] = $valid; - - $target =& $page->controller->getPage($actionName); - if (PEAR::isError($target)) { - return $target; - } else { - return $target->handle('jump'); - } - } -} -?> + + $target =& $page->controller->getPage($actionName); + if (PEAR::isError($target)) { + return $target; + } else { + return $target->handle('jump'); + } + } +} +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Action/Jump.php b/main/inc/lib/pear/HTML/QuickForm/Action/Jump.php index 59f2647436..710d9c093e 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Action/Jump.php +++ b/main/inc/lib/pear/HTML/QuickForm/Action/Jump.php @@ -1,6 +1,6 @@ - * @version Release: 1.0.10 - */ -class HTML_QuickForm_Action_Jump extends HTML_QuickForm_Action -{ + */ +class HTML_QuickForm_Action_Jump extends HTML_QuickForm_Action +{ /** * Splits (part of) the URI into path and query components * @@ -130,33 +125,33 @@ class HTML_QuickForm_Action_Jump extends HTML_QuickForm_Action } } - function perform(&$page, $actionName) - { - // check whether the page is valid before trying to go to it - if ($page->controller->isModal()) { - // we check whether *all* pages up to current are valid - // if there is an invalid page we go to it, instead of the - // requested one - $pageName = $page->getAttribute('id'); - if (!$page->controller->isValid($pageName)) { - $pageName = $page->controller->findInvalid(); - } - $current =& $page->controller->getPage($pageName); - - } else { - $current =& $page; - } - // generate the URL for the page 'display' event and redirect to it - $action = $current->getAttribute('action'); + function perform(&$page, $actionName) + { + // check whether the page is valid before trying to go to it + if ($page->controller->isModal()) { + // we check whether *all* pages up to current are valid + // if there is an invalid page we go to it, instead of the + // requested one + $pageName = $page->getAttribute('id'); + if (!$page->controller->isValid($pageName)) { + $pageName = $page->controller->findInvalid(); + } + $current =& $page->controller->getPage($pageName); + + } else { + $current =& $page; + } + // generate the URL for the page 'display' event and redirect to it + $action = $current->getAttribute('action'); // Bug #13087: RFC 2616 requires an absolute URI in Location header if (!preg_match('!^https?://!i', $action)) { $action = $this->_resolveRelativeURL($action); } - $url = $action . (false === strpos($action, '?')? '?': '&') . - $current->getButtonName('display') . '=true' . + $url = $action . (false === strpos($action, '?')? '?': '&') . + $current->getButtonName('display') . '=true' . ((!defined('SID') || '' == SID || ini_get('session.use_only_cookies'))? '': '&' . SID); - header('Location: ' . $url); - exit; - } -} -?> + header('Location: ' . $url); + exit; + } +} +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Action/Next.php b/main/inc/lib/pear/HTML/QuickForm/Action/Next.php index 664bd33214..39539be566 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Action/Next.php +++ b/main/inc/lib/pear/HTML/QuickForm/Action/Next.php @@ -1,38 +1,33 @@ - * @copyright 2003-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version SVN: $Id: Next.php 289084 2009-10-02 06:53:09Z avb $ - * @link http://pear.php.net/package/HTML_QuickForm_Controller - */ - -/** - * Class representing an action to perform on HTTP request. - */ -require_once 'HTML/QuickForm/Action.php'; +/** + * The action for a 'next' button of wizard-type multipage form. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @copyright 2003-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version SVN: $Id: Next.php 289084 2009-10-02 06:53:09Z avb $ + * @link http://pear.php.net/package/HTML_QuickForm_Controller + */ /** * The action for a 'next' button of wizard-type multipage form. * - * @category HTML - * @package HTML_QuickForm_Controller - * @author Alexey Borzov - * @version Release: 1.0.10 + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @version Release: 1.0.10 */ class HTML_QuickForm_Action_Next extends HTML_QuickForm_Action { @@ -43,10 +38,10 @@ class HTML_QuickForm_Action_Next extends HTML_QuickForm_Action $pageName = $page->getAttribute('id'); $data =& $page->controller->container(); $data['values'][$pageName] = $page->exportValues(); - if (PEAR::isError($valid = $page->validate())) { - return $valid; - } - $data['valid'][$pageName] = $valid; + if (PEAR::isError($valid = $page->validate())) { + return $valid; + } + $data['valid'][$pageName] = $valid; // Modal form and page is invalid: don't go further if ($page->controller->isModal() && !$data['valid'][$pageName]) { diff --git a/main/inc/lib/pear/HTML/QuickForm/Action/Submit.php b/main/inc/lib/pear/HTML/QuickForm/Action/Submit.php index 6a4c1125ca..2fb79bcc33 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Action/Submit.php +++ b/main/inc/lib/pear/HTML/QuickForm/Action/Submit.php @@ -1,38 +1,33 @@ - * @copyright 2003-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version SVN: $Id: Submit.php 289084 2009-10-02 06:53:09Z avb $ - * @link http://pear.php.net/package/HTML_QuickForm_Controller - */ - -/** - * Class representing an action to perform on HTTP request. - */ -require_once 'HTML/QuickForm/Action.php'; +/** + * The action for a 'submit' button. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @copyright 2003-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version SVN: $Id: Submit.php 289084 2009-10-02 06:53:09Z avb $ + * @link http://pear.php.net/package/HTML_QuickForm_Controller + */ /** * The action for a 'submit' button. * - * @category HTML - * @package HTML_QuickForm_Controller - * @author Alexey Borzov - * @version Release: 1.0.10 + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @version Release: 1.0.10 */ class HTML_QuickForm_Action_Submit extends HTML_QuickForm_Action { @@ -43,10 +38,10 @@ class HTML_QuickForm_Action_Submit extends HTML_QuickForm_Action $pageName = $page->getAttribute('id'); $data =& $page->controller->container(); $data['values'][$pageName] = $page->exportValues(); - if (PEAR::isError($valid = $page->validate())) { - return $valid; - } - $data['valid'][$pageName] = $valid; + if (PEAR::isError($valid = $page->validate())) { + return $valid; + } + $data['valid'][$pageName] = $valid; // All pages are valid, process if ($page->controller->isValid()) { @@ -73,4 +68,4 @@ class HTML_QuickForm_Action_Submit extends HTML_QuickForm_Action } } -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA.php b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA.php index c5ae7040e0..2ba7abe414 100755 --- a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA.php +++ b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA.php @@ -51,12 +51,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -/** - * Required packages - */ -require_once 'HTML/QuickForm/input.php'; -require_once 'Text/CAPTCHA.php'; - /** * Common class for HTML_QuickForm elements to display a CAPTCHA * @@ -259,10 +253,3 @@ class HTML_QuickForm_CAPTCHA extends HTML_QuickForm_input return $html; } } - -/** - * Register the rule with QuickForm - */ -require_once 'HTML/QuickForm/Rule/CAPTCHA.php'; - -?> diff --git a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Equation.php b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Equation.php index 29edac9669..f8baf7a672 100755 --- a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Equation.php +++ b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Equation.php @@ -21,12 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -/** - * Required packages - */ -require_once 'HTML/QuickForm/CAPTCHA.php'; -require_once 'Text/CAPTCHA/Driver/Equation.php'; - /** * Element for HTML_QuickForm to display a CAPTCHA equation question * @@ -80,14 +74,3 @@ class HTML_QuickForm_CAPTCHA_Equation extends HTML_QuickForm_CAPTCHA */ var $_CAPTCHA_driver = 'Equation'; } - -/** - * Registers the class with QuickForm - */ -if (class_exists('HTML_QuickForm')) { - HTML_QuickForm::registerElementType('CAPTCHA_Equation', - 'HTML/QuickForm/CAPTCHA/Equation.php', - 'HTML_QuickForm_CAPTCHA_Equation'); -} - -?> \ No newline at end of file diff --git a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Figlet.php b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Figlet.php index 06c09ae11e..78e8e1d5ac 100755 --- a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Figlet.php +++ b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Figlet.php @@ -21,12 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -/** - * Required packages - */ -require_once 'HTML/QuickForm/CAPTCHA.php'; -require_once 'Text/CAPTCHA/Driver/Figlet.php'; - /** * Element for HTML_QuickForm to display a CAPTCHA figlet * @@ -113,14 +107,3 @@ class HTML_QuickForm_CAPTCHA_Figlet extends HTML_QuickForm_CAPTCHA return $html; } } - -/** - * Registers the class with QuickForm - */ -if (class_exists('HTML_QuickForm')) { - HTML_QuickForm::registerElementType('CAPTCHA_Figlet', - 'HTML/QuickForm/CAPTCHA/Figlet.php', - 'HTML_QuickForm_CAPTCHA_Figlet'); -} - -?> \ No newline at end of file diff --git a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Image.php b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Image.php index 02d685da02..e3b3401f63 100755 --- a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Image.php +++ b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Image.php @@ -21,12 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -/** - * Required packages - */ -require_once 'HTML/QuickForm/CAPTCHA.php'; -require_once 'Text/CAPTCHA/Driver/Image.php'; - /** * Element for HTML_QuickForm to display a CAPTCHA image * diff --git a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Word.php b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Word.php index 51929be4f0..bba5735c9f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Word.php +++ b/main/inc/lib/pear/HTML/QuickForm/CAPTCHA/Word.php @@ -21,12 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -/** - * Required packages - */ -require_once 'HTML/QuickForm/CAPTCHA.php'; -require_once 'Text/CAPTCHA/Driver/Word.php'; - /** * Element for HTML_QuickForm to display a CAPTCHA "word" question * @@ -78,13 +72,3 @@ class HTML_QuickForm_CAPTCHA_Word extends HTML_QuickForm_CAPTCHA */ var $_CAPTCHA_driver = 'Word'; } - -/** - * Registers the class with QuickForm - */ -if (class_exists('HTML_QuickForm')) { - HTML_QuickForm::registerElementType('CAPTCHA_Word', - 'HTML/QuickForm/CAPTCHA/Word.php', 'HTML_QuickForm_CAPTCHA_Word'); -} - -?> \ No newline at end of file diff --git a/main/inc/lib/pear/HTML/QuickForm/Controller.php b/main/inc/lib/pear/HTML/QuickForm/Controller.php index 9030576862..cf5a3c7770 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Controller.php +++ b/main/inc/lib/pear/HTML/QuickForm/Controller.php @@ -1,31 +1,27 @@ - * @author Bertrand Mansion - * @copyright 2003-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version SVN: $Id: Controller.php 289084 2009-10-02 06:53:09Z avb $ - * @link http://pear.php.net/package/HTML_QuickForm_Controller - */ - -/** - * The class representing a page of a multipage form. - */ -require_once 'HTML/QuickForm/Page.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/** + * The class representing a Controller of MVC design pattern. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @author Bertrand Mansion + * @copyright 2003-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version SVN: $Id: Controller.php 289084 2009-10-02 06:53:09Z avb $ + * @link http://pear.php.net/package/HTML_QuickForm_Controller + */ + /** * The class representing a Controller of MVC design pattern. @@ -36,11 +32,11 @@ require_once 'HTML/QuickForm/Page.php'; * * Generally you don't need to subclass this. * - * @category HTML - * @package HTML_QuickForm_Controller - * @author Alexey Borzov - * @author Bertrand Mansion - * @version Release: 1.0.10 + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @author Bertrand Mansion + * @version Release: 1.0.10 */ class HTML_QuickForm_Controller { @@ -132,7 +128,7 @@ class HTML_QuickForm_Controller * to the page's handle() method. * * @access public - * @throws PEAR_Error + * @throws PEAR_Error */ function run() { @@ -146,8 +142,8 @@ class HTML_QuickForm_Controller * Registers a handler for a specific action. * * @access public - * @param string name of the action - * @param HTML_QuickForm_Action the handler for the action + * @param string name of the action + * @param HTML_QuickForm_Action the handler for the action */ function addAction($actionName, &$action) { @@ -159,7 +155,7 @@ class HTML_QuickForm_Controller * Adds a new page to the form * * @access public - * @param HTML_QuickForm_Page + * @param HTML_QuickForm_Page */ function addPage(&$page) { @@ -172,9 +168,9 @@ class HTML_QuickForm_Controller * Returns a page * * @access public - * @param string Name of a page - * @return HTML_QuickForm_Page A reference to the page - * @throws PEAR_Error + * @param string Name of a page + * @return HTML_QuickForm_Page A reference to the page + * @throws PEAR_Error */ function &getPage($pageName) { @@ -193,9 +189,9 @@ class HTML_QuickForm_Controller * for common actions, if specific ones were not added. * * @access public - * @param HTML_QuickForm_Page The page that failed to handle the action - * @param string Name of the action - * @throws PEAR_Error + * @param HTML_QuickForm_Page The page that failed to handle the action + * @param string Name of the action + * @throws PEAR_Error */ function handle(&$page, $actionName) { @@ -237,7 +233,7 @@ class HTML_QuickForm_Controller * @access public * @param string If set, check only the pages before (not including) that page * @return bool - * @throws PEAR_Error + * @throws PEAR_Error */ function isValid($pageName = null) { @@ -250,11 +246,11 @@ class HTML_QuickForm_Controller // seen a page of a non-modal multipage form if (!$this->isModal() && null === $data['valid'][$key]) { $page =& $this->_pages[$key]; - // Fix for bug #8687: the unseen page was considered - // submitted, so defaults for checkboxes and multiselects - // were not used. Shouldn't break anything since this flag - // will be reset right below in loadValues(). - $page->_flagSubmitted = false; + // Fix for bug #8687: the unseen page was considered + // submitted, so defaults for checkboxes and multiselects + // were not used. Shouldn't break anything since this flag + // will be reset right below in loadValues(). + $page->_flagSubmitted = false; // Use controller's defaults and constants, if present $this->applyDefaults($key); $page->isFormBuilt() or $page->BuildForm(); @@ -262,11 +258,11 @@ class HTML_QuickForm_Controller $data['values'][$key] = $page->exportValues(); $page->loadValues($data['values'][$key]); // Is the page now valid? - if (PEAR::isError($valid = $page->validate())) { - return $valid; - } - $data['valid'][$key] = $valid; - if (true === $valid) { + if (PEAR::isError($valid = $page->validate())) { + return $valid; + } + $data['valid'][$key] = $valid; + if (true === $valid) { continue; } } diff --git a/main/inc/lib/pear/HTML/QuickForm/Page.php b/main/inc/lib/pear/HTML/QuickForm/Page.php index 71d73ddbb8..7667639acd 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Page.php +++ b/main/inc/lib/pear/HTML/QuickForm/Page.php @@ -1,44 +1,39 @@ - * @author Bertrand Mansion - * @copyright 2003-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version SVN: $Id: Page.php 289084 2009-10-02 06:53:09Z avb $ - * @link http://pear.php.net/package/HTML_QuickForm_Controller - */ - -/** - * Create, validate and process HTML forms - */ -require_once 'HTML/QuickForm.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** - * Class representing a page of a multipage form. + * Class representing a page of a multipage form. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @author Bertrand Mansion + * @copyright 2003-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version SVN: $Id: Page.php 289084 2009-10-02 06:53:09Z avb $ + * @link http://pear.php.net/package/HTML_QuickForm_Controller + */ + +/** + * Class representing a page of a multipage form. * * Generally you'll need to subclass this and define your buildForm() * method that will build the form. While it is also possible to instantiate * this class and build the form manually, this is not the recommended way. * - * @category HTML - * @package HTML_QuickForm_Controller - * @author Alexey Borzov - * @author Bertrand Mansion - * @version Release: 1.0.10 + * @category HTML + * @package HTML_QuickForm_Controller + * @author Alexey Borzov + * @author Bertrand Mansion + * @version Release: 1.0.10 */ class HTML_QuickForm_Page extends HTML_QuickForm { @@ -50,8 +45,8 @@ class HTML_QuickForm_Page extends HTML_QuickForm /** * Contains a reference to a Controller object containing this page - * @var HTML_QuickForm_Controller - * @access public + * @var HTML_QuickForm_Controller + * @access public */ var $controller = null; @@ -66,7 +61,7 @@ class HTML_QuickForm_Page extends HTML_QuickForm * * @access public */ - function HTML_QuickForm_Page($formName, $method = 'post', $target = '', $attributes = null) + function HTML_QuickForm_Page($formName, $method = 'post', $target = '', $attributes = null) { $this->HTML_QuickForm($formName, $method, '', $target, $attributes); } @@ -76,8 +71,8 @@ class HTML_QuickForm_Page extends HTML_QuickForm * Registers a handler for a specific action. * * @access public - * @param string name of the action - * @param HTML_QuickForm_Action the handler for the action + * @param string name of the action + * @param HTML_QuickForm_Action the handler for the action */ function addAction($actionName, &$action) { @@ -93,7 +88,7 @@ class HTML_QuickForm_Page extends HTML_QuickForm * * @access public * @param string Name of the action - * @throws PEAR_Error + * @throws PEAR_Error */ function handle($actionName) { @@ -128,7 +123,7 @@ class HTML_QuickForm_Page extends HTML_QuickForm */ function loadValues($values) { - $this->_flagSubmitted = true; + $this->_flagSubmitted = true; $this->_submitValues = $values; foreach (array_keys($this->_elements) as $key) { $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this); @@ -185,26 +180,26 @@ class HTML_QuickForm_Page extends HTML_QuickForm $this->addElement('hidden', '_qf_default', $this->getAttribute('id') . ':' . $actionName); } } - - - /** - * Returns 'safe' elements' values - * - * @param mixed Array/string of element names, whose values we want. If not set then return all elements. - * @param bool Whether to remove internal (_qf_...) values from the resultant array - */ - function exportValues($elementList = null, $filterInternal = false) - { - $values = parent::exportValues($elementList); - if ($filterInternal) { - foreach (array_keys($values) as $key) { - if (0 === strpos($key, '_qf_')) { - unset($values[$key]); - } - } - } - return $values; - } + + + /** + * Returns 'safe' elements' values + * + * @param mixed Array/string of element names, whose values we want. If not set then return all elements. + * @param bool Whether to remove internal (_qf_...) values from the resultant array + */ + function exportValues($elementList = null, $filterInternal = false) + { + $values = parent::exportValues($elementList); + if ($filterInternal) { + foreach (array_keys($values) as $key) { + if (0 === strpos($key, '_qf_')) { + unset($values[$key]); + } + } + } + return $values; + } } ?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/Array.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/Array.php index efc8a9e4b5..68ca9c8bb7 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/Array.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/Array.php @@ -1,41 +1,36 @@ - * @author Adam Daniel - * @author Bertrand Mansion - * @author Thomas Schulz - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Array.php,v 1.11 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * An abstract base class for QuickForm renderers - */ -require_once 'HTML/QuickForm/Renderer.php'; +/** + * A concrete renderer for HTML_QuickForm, makes an array of form contents + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @author Adam Daniel + * @author Bertrand Mansion + * @author Thomas Schulz + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Array.php,v 1.11 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * A concrete renderer for HTML_QuickForm, makes an array of form contents * - * Based on old HTML_QuickForm::toArray() code. + * Based on old HTML_QuickForm::toArray() code. * * The form array structure is the following: - *
      + * 
        * array(
        *   'frozen'           => 'whether the form is frozen',
        *   'javascript'       => 'javascript for client-side validation',
      @@ -78,10 +73,10 @@ require_once 'HTML/QuickForm/Renderer.php';
        *     )
        *   )
        * );
      - * 
      + *
      * * where element_i is an array of the form: - *
      + * 
        * array(
        *   'name'      => 'element name',
        *   'value'     => 'element value',
      @@ -101,22 +96,22 @@ require_once 'HTML/QuickForm/Renderer.php';
        *     element_N
        *   )
        * );
      - * 
      + *
      * - * @category HTML - * @package HTML_QuickForm - * @author Alexey Borzov - * @author Adam Daniel - * @author Bertrand Mansion - * @author Thomas Schulz - * @version Release: 3.2.11 - * @since 3.0 + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @author Adam Daniel + * @author Bertrand Mansion + * @author Thomas Schulz + * @version Release: 3.2.11 + * @since 3.0 */ class HTML_QuickForm_Renderer_Array extends HTML_QuickForm_Renderer { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * An array being generated * @var array @@ -158,8 +153,8 @@ class HTML_QuickForm_Renderer_Array extends HTML_QuickForm_Renderer * false: leave labels as defined * @var bool */ - var $_staticLabels = false; - /**#@-*/ + var $_staticLabels = false; + /**#@-*/ /** * Constructor @@ -256,9 +251,9 @@ class HTML_QuickForm_Renderer_Array extends HTML_QuickForm_Renderer * Creates an array representing an element * * @access private - * @param HTML_QuickForm_element element being processed - * @param bool Whether an element is required - * @param string Error associated with the element + * @param HTML_QuickForm_element element being processed + * @param bool Whether an element is required + * @param string Error associated with the element * @return array */ function _elementToArray(&$element, $required, $error) @@ -337,4 +332,4 @@ class HTML_QuickForm_Renderer_Array extends HTML_QuickForm_Renderer } } } -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/ArraySmarty.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/ArraySmarty.php index 83693ef042..8955f2f269 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/ArraySmarty.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/ArraySmarty.php @@ -1,42 +1,37 @@ - * @author Bertrand Mansion - * @author Thomas Schulz - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: ArraySmarty.php,v 1.14 2009/04/06 12:02:08 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * A concrete renderer for HTML_QuickForm, makes an array of form contents - */ -require_once 'HTML/QuickForm/Renderer/Array.php'; +/** + * A static renderer for HTML_QuickForm, makes an array of form content + * useful for a Smarty template + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @author Bertrand Mansion + * @author Thomas Schulz + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: ArraySmarty.php,v 1.14 2009/04/06 12:02:08 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * A static renderer for HTML_QuickForm, makes an array of form content - * useful for a Smarty template + * useful for a Smarty template * - * Based on old HTML_QuickForm::toArray() code and ITStatic renderer. + * Based on old HTML_QuickForm::toArray() code and ITStatic renderer. * * The form array structure is the following: - *
      + * 
        * Array (
        *  [frozen]       => whether the complete form is frozen'
        *  [javascript]   => javascript for client-side validation
      @@ -60,10 +55,10 @@ require_once 'HTML/QuickForm/Renderer/Array.php';
        *  [1st_element_name] => Array for the 1st element
        *  ...
        *  [nth_element_name] => Array for the nth element
      - * 
      + *
      * - * where an element array has the form: - *
      + * where an element array has the form:
      + * 
        *      (
        *          [name]      => element name
        *          [value]     => element value,
      @@ -80,21 +75,21 @@ require_once 'HTML/QuickForm/Renderer/Array.php';
        *          [nth_gitem_name] => Array for the nth element in group
        *      )
        * )
      - * 
      + *
      * - * @category HTML - * @package HTML_QuickForm - * @author Alexey Borzov - * @author Bertrand Mansion - * @author Thomas Schulz - * @version Release: 3.2.11 - * @since 3.0 + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @author Bertrand Mansion + * @author Thomas Schulz + * @version Release: 3.2.11 + * @since 3.0 */ class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * The Smarty template engine instance * @var object @@ -126,26 +121,26 @@ class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array * @see setErrorTemplate() */ var $_error = ''; - /**#@-*/ + /**#@-*/ /** * Constructor * - * @param Smarty reference to the Smarty template engine instance + * @param Smarty reference to the Smarty template engine instance * @param bool true: render an array of labels to many labels, $key 0 to 'label' and the oterh to "label_$key" - * @param bool true: collect all hidden elements into string; false: process them as usual form elements + * @param bool true: collect all hidden elements into string; false: process them as usual form elements * @access public */ - function HTML_QuickForm_Renderer_ArraySmarty(&$tpl, $staticLabels = false, $collectHidden = true) + function HTML_QuickForm_Renderer_ArraySmarty(&$tpl, $staticLabels = false, $collectHidden = true) { - $this->HTML_QuickForm_Renderer_Array($collectHidden, $staticLabels); + $this->HTML_QuickForm_Renderer_Array($collectHidden, $staticLabels); $this->_tpl =& $tpl; } // end constructor /** * Called when visiting a header element * - * @param HTML_QuickForm_header header element being visited + * @param HTML_QuickForm_header header element being visited * @access public * @return void */ @@ -162,9 +157,9 @@ class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array /** * Called when visiting a group, before processing any group elements * - * @param HTML_QuickForm_group group being visited - * @param bool Whether a group is required - * @param string An error message associated with a group + * @param HTML_QuickForm_group group being visited + * @param bool Whether a group is required + * @param string An error message associated with a group * @access public * @return void */ @@ -179,9 +174,9 @@ class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array * the key for storing this * * @access private - * @param HTML_QuickForm_element form element being visited - * @param bool Whether an element is required - * @param string Error associated with the element + * @param HTML_QuickForm_element form element being visited + * @param bool Whether an element is required + * @param string Error associated with the element * @return array */ function _elementToArray(&$element, $required, $error) @@ -400,4 +395,4 @@ class HTML_QuickForm_Renderer_ArraySmarty extends HTML_QuickForm_Renderer_Array $this->_error = $template; } // end func setErrorTemplate } -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/Default.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/Default.php index 8af54cabf8..cfb1b9a7c4 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/Default.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/Default.php @@ -23,11 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * An abstract base class for QuickForm renderers - */ -require_once 'HTML/QuickForm/Renderer.php'; - /** * A concrete renderer for HTML_QuickForm, based on QuickForm 2.x built-in one * @@ -197,9 +192,9 @@ class HTML_QuickForm_Renderer_Default extends HTML_QuickForm_Renderer if (!empty($form->_required) && !$form->_freezeAll) { $this->_html .= str_replace('{requiredNote}', $form->getRequiredNote(), $this->_requiredNoteTemplate); } - // add form attributes and content - $html = str_replace('{attributes}', $form->getAttributes(true), $this->_formTemplate); - + // add form attributes and content + $html = str_replace('{attributes}', $form->getAttributes(true), $this->_formTemplate); + if (strpos($this->_formTemplate, '{hidden}')) { $html = str_replace('{hidden}', $this->_hiddenHtml, $html); } else { @@ -389,7 +384,7 @@ class HTML_QuickForm_Renderer_Default extends HTML_QuickForm_Renderer if (!empty($this->_groupWrap)) { $html = str_replace('{content}', $html, $this->_groupWrap); } - $this->_html .= str_replace('{element}', $html, $this->_groupTemplate); + $this->_html .= str_replace('{element}', $html, $this->_groupTemplate); $this->_inGroup = false; } // end func finishGroup @@ -461,7 +456,7 @@ class HTML_QuickForm_Renderer_Default extends HTML_QuickForm_Renderer * @return void */ function setFormTemplate($html) { - $this->_formTemplate = $html; + $this->_formTemplate = $html; } // end func setFormTemplate /** @@ -490,4 +485,4 @@ class HTML_QuickForm_Renderer_Default extends HTML_QuickForm_Renderer $this->setRequiredNoteTemplate(''); $this->_templates = array(); } // end func clearAllTemplates -} // end class HTML_QuickForm_Renderer_Default \ No newline at end of file +} // end class HTML_QuickForm_Renderer_Default diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/ITDynamic.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/ITDynamic.php index 27a054154f..e71c76f4c8 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/ITDynamic.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/ITDynamic.php @@ -1,30 +1,25 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: ITDynamic.php,v 1.7 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * An abstract base class for QuickForm renderers - */ -require_once 'HTML/QuickForm/Renderer.php'; +/** + * A concrete renderer for HTML_QuickForm, using Integrated Templates. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: ITDynamic.php,v 1.7 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * A concrete renderer for HTML_QuickForm, using Integrated Templates. @@ -37,20 +32,20 @@ require_once 'HTML/QuickForm/Renderer.php'; * special block is not set for an element, the renderer falls back to * a default one. * - * @category HTML - * @package HTML_QuickForm - * @author Alexey Borzov - * @version Release: 3.2.11 - * @since 3.0 + * @category HTML + * @package HTML_QuickForm + * @author Alexey Borzov + * @version Release: 3.2.11 + * @since 3.0 */ class HTML_QuickForm_Renderer_ITDynamic extends HTML_QuickForm_Renderer { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * A template class (HTML_Template_ITX or HTML_Template_Sigma) instance - * @var HTML_Template_ITX|HTML_Template_Sigma + * @var HTML_Template_ITX|HTML_Template_Sigma */ var $_tpl = null; @@ -89,13 +84,13 @@ class HTML_QuickForm_Renderer_ITDynamic extends HTML_QuickForm_Renderer * @var string */ var $_headerBlock = null; - /**#@-*/ + /**#@-*/ /** * Constructor * - * @param HTML_Template_ITX|HTML_Template_Sigma Template object to use + * @param HTML_Template_ITX|HTML_Template_Sigma Template object to use */ function HTML_QuickForm_Renderer_ITDynamic(&$tpl) { @@ -239,7 +234,7 @@ class HTML_QuickForm_Renderer_ITDynamic extends HTML_QuickForm_Renderer * the names '{prefix}_{element type}' and '{prefix}_{element}', where * prefix is either 'qf' or the name of the current group's block * - * @param HTML_QuickForm_element form element being rendered + * @param HTML_QuickForm_element form element being rendered * @access private * @return string block name */ diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/ITStatic.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/ITStatic.php index e7472c9560..07781a9126 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/ITStatic.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/ITStatic.php @@ -1,31 +1,26 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: ITStatic.php,v 1.9 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * An abstract base class for QuickForm renderers - */ -require_once 'HTML/QuickForm/Renderer.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/** + * A static renderer for HTML_QuickForm compatible + * with HTML_Template_IT and HTML_Template_Sigma. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: ITStatic.php,v 1.9 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * A static renderer for HTML_QuickForm compatible @@ -35,17 +30,17 @@ require_once 'HTML/QuickForm/Renderer.php'; * every elements and labels in the form to be specified by * placeholders at the position you want them to be displayed. * - * @category HTML - * @package HTML_QuickForm - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 3.0 + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 3.0 */ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * An HTML_Template_IT or some other API compatible Template instance * @var object @@ -105,12 +100,12 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer * @var string */ var $_hidden = ''; - /**#@-*/ + /**#@-*/ /** * Constructor * - * @param HTML_Template_IT|HTML_Template_Sigma Template object to use + * @param HTML_Template_IT|HTML_Template_Sigma Template object to use */ function HTML_QuickForm_Renderer_ITStatic(&$tpl) { @@ -121,7 +116,7 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a form, before processing any form elements * - * @param HTML_QuickForm form object being visited + * @param HTML_QuickForm form object being visited * @access public * @return void */ @@ -140,7 +135,7 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a form, after processing all form elements * - * @param HTML_QuickForm form object being visited + * @param HTML_QuickForm form object being visited * @access public * @return void */ @@ -170,7 +165,7 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a header element * - * @param HTML_QuickForm_header header element being visited + * @param HTML_QuickForm_header header element being visited * @access public * @return void */ @@ -189,9 +184,9 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting an element * - * @param HTML_QuickForm_element form element being visited - * @param bool Whether an element is required - * @param string An error message associated with an element + * @param HTML_QuickForm_element form element being visited + * @param bool Whether an element is required + * @param string An error message associated with an element * @access public * @return void */ @@ -265,7 +260,7 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a hidden element * - * @param HTML_QuickForm_element hidden element being visited + * @param HTML_QuickForm_element hidden element being visited * @access public * @return void */ @@ -283,9 +278,9 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a group, before processing any group elements * - * @param HTML_QuickForm_group group being visited - * @param bool Whether a group is required - * @param string An error message associated with a group + * @param HTML_QuickForm_group group being visited + * @param bool Whether a group is required + * @param string An error message associated with a group * @access public * @return void */ @@ -336,7 +331,7 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer /** * Called when visiting a group, after processing all group elements * - * @param HTML_QuickForm_group group being visited + * @param HTML_QuickForm_group group being visited * @access public * @return void */ @@ -501,4 +496,4 @@ class HTML_QuickForm_Renderer_ITStatic extends HTML_QuickForm_Renderer return $ret; } } // end class HTML_QuickForm_Renderer_ITStatic -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/Object.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/Object.php index c73c6fecbf..9256df96a6 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/Object.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/Object.php @@ -1,50 +1,45 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Object.php,v 1.6 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * An abstract base class for QuickForm renderers - */ -require_once 'HTML/QuickForm/Renderer.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ + +/** + * A concrete renderer for HTML_QuickForm, makes an object from form contents + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Object.php,v 1.6 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * A concrete renderer for HTML_QuickForm, makes an object from form contents * * Based on HTML_Quickform_Renderer_Array code * - * @category HTML - * @package HTML_QuickForm - * @author Ron McClain - * @version Release: 3.2.11 - * @since 3.1.1 + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @version Release: 3.2.11 + * @since 3.1.1 */ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * The object being generated - * @var QuickformForm + * @var QuickformForm */ var $_obj= null; @@ -83,13 +78,13 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer * @var bool $_collectHidden */ var $_collectHidden = false; - /**#@-*/ + /**#@-*/ /** * Constructor * - * @param bool true: collect all hidden elements + * @param bool true: collect all hidden elements * @access public */ function HTML_QuickForm_Renderer_Object($collecthidden = false) @@ -110,7 +105,7 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer /** * Set the class of the form elements. Defaults to QuickformElement. - * @param string Name of element class + * @param string Name of element class * @access public */ function setElementType($type) @@ -180,7 +175,7 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer * Creates an object representing an element * * @access private - * @param HTML_QuickForm_element form element being rendered + * @param HTML_QuickForm_element form element being rendered * @param required bool Whether an element is required * @param error string Error associated with the element * @return object @@ -224,7 +219,7 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer * Stores an object representation of an element in the form array * * @access private - * @param QuickformElement Object representation of an element + * @param QuickformElement Object representation of an element * @return void */ function _storeObject($elObj) @@ -256,7 +251,7 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer * Convenience class for the form object passed to outputObject() * * Eg. - *
      + * 
        * {form.outputJavaScript():h}
        * {form.outputHeader():h}
        *   
      '.$row->title.'
      @@ -265,13 +260,13 @@ class HTML_QuickForm_Renderer_Object extends HTML_QuickForm_Renderer * *
      * - *
      - * - * @category HTML - * @package HTML_QuickForm - * @author Ron McClain - * @version Release: 3.2.11 - * @since 3.1.1 + *
    + * + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @version Release: 3.2.11 + * @since 3.1.1 */ class QuickformForm { @@ -351,16 +346,16 @@ class QuickformForm /** * Convenience class describing a form element. - * + * * The properties defined here will be available from * your flexy templates by referencing * {form.zip.label:h}, {form.zip.html:h}, etc. - * - * @category HTML - * @package HTML_QuickForm - * @author Ron McClain - * @version Release: 3.2.11 - * @since 3.1.1 + * + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @version Release: 3.2.11 + * @since 3.1.1 */ class QuickformElement { diff --git a/main/inc/lib/pear/HTML/QuickForm/Renderer/ObjectFlexy.php b/main/inc/lib/pear/HTML/QuickForm/Renderer/ObjectFlexy.php index ddd85f1c88..dbef7482f5 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Renderer/ObjectFlexy.php +++ b/main/inc/lib/pear/HTML/QuickForm/Renderer/ObjectFlexy.php @@ -1,30 +1,25 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: ObjectFlexy.php,v 1.10 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * A concrete renderer for HTML_QuickForm, makes an object from form contents - */ -require_once 'HTML/QuickForm/Renderer/Object.php'; +/** + * QuickForm renderer for Flexy template engine, static version. + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: ObjectFlexy.php,v 1.10 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * QuickForm renderer for Flexy template engine, static version. @@ -33,7 +28,7 @@ require_once 'HTML/QuickForm/Renderer/Object.php'; * from the form content suitable for use with a Flexy template * * Usage: - * + * * $form =& new HTML_QuickForm('form', 'POST'); * $template =& new HTML_Template_Flexy(); * $renderer =& new HTML_QuickForm_Renderer_ObjectFlexy(&$template); @@ -43,21 +38,21 @@ require_once 'HTML/QuickForm/Renderer/Object.php'; * $view = new StdClass; * $view->form = $renderer->toObject(); * $template->compile("mytemplate.html"); - * + * * * Based on the code for HTML_QuickForm_Renderer_ArraySmarty * - * @category HTML - * @package HTML_QuickForm - * @author Ron McClain - * @version Release: 3.2.11 - * @since 3.1.1 + * @category HTML + * @package HTML_QuickForm + * @author Ron McClain + * @version Release: 3.2.11 + * @since 3.1.1 */ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object { - /**#@+ - * @access private - */ + /**#@+ + * @access private + */ /** * HTML_Template_Flexy instance * @var object $_flexy @@ -96,12 +91,12 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object * @var string $_elementType */ var $_elementType = 'QuickformFlexyElement'; - /**#@-*/ + /**#@-*/ /** * Constructor * - * @param HTML_Template_Flexy template object to use + * @param HTML_Template_Flexy template object to use * @public */ function HTML_QuickForm_Renderer_ObjectFlexy(&$flexy) @@ -132,9 +127,9 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object * the key for storing this * * @access private - * @param HTML_QuickForm_element form element being rendered - * @param bool Whether an element is required - * @param string Error associated with the element + * @param HTML_QuickForm_element form element being rendered + * @param bool Whether an element is required + * @param string Error associated with the element * @return object */ function _elementToObject(&$element, $required, $error) @@ -194,7 +189,7 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object * QuickformFormObject instance * * @access private - * @param QuickformElement Object representation of an element + * @param QuickformElement Object representation of an element * @return void */ function _storeObject($elObj) @@ -216,15 +211,15 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object * In your template, {html} is replaced by the unmodified html. * If the element is required, {required} will be true. * Eg. - *
    +     * 
          * {if:error}
          *   {error:h}
    * {end:} * {html:h} - *
    + *
    * * @access public - * @param string Filename of template + * @param string Filename of template * @return void */ function setHtmlTemplate($template) @@ -238,15 +233,15 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object * {error} will be set to the error, if any. {required} will * be true if this is a required field * Eg. - *
    +     * 
          * {if:required}
          * *
          * {end:}
          * {label:h}
    -     * 
    + *
    * * @access public - * @param string Filename of template + * @param string Filename of template * @return void */ function setLabelTemplate($template) @@ -269,10 +264,10 @@ class HTML_QuickForm_Renderer_ObjectFlexy extends HTML_QuickForm_Renderer_Object /** * Adds nothing to QuickformForm, left for backwards compatibility - * - * @category HTML - * @package HTML_QuickForm - * @ignore + * + * @category HTML + * @package HTML_QuickForm + * @ignore */ class QuickformFlexyForm extends QuickformForm { @@ -280,10 +275,10 @@ class QuickformFlexyForm extends QuickformForm /** * Adds nothing to QuickformElement, left for backwards compatibility - * - * @category HTML - * @package HTML_QuickForm - * @ignore + * + * @category HTML + * @package HTML_QuickForm + * @ignore */ class QuickformFlexyElement extends QuickformElement { diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php b/main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php index 1ca9c98b09..450101347f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php @@ -17,8 +17,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_CAPTCHA */ -require_once 'HTML/QuickForm/Rule.php'; - /** * Rule to compare a field with a CAPTCHA image * diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Callback.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Callback.php index 0a7eb6bd51..3c715b8032 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Callback.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Callback.php @@ -1,40 +1,35 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Callback.php,v 1.9 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; +/** + * Validates values using callback functions or methods + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Callback.php,v 1.9 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * Validates values using callback functions or methods - * - * @category HTML - * @package HTML_QuickForm - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 3.2 - */ + * Validates values using callback functions or methods + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 3.2 + */ class HTML_QuickForm_Rule_Callback extends HTML_QuickForm_Rule { /** @@ -121,4 +116,4 @@ class HTML_QuickForm_Rule_Callback extends HTML_QuickForm_Rule } // end func getValidationScript } // end class HTML_QuickForm_Rule_Callback -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Compare.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Compare.php index 4b5478e273..ba4edef058 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Compare.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Compare.php @@ -21,11 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; - /** * Rule to compare two form fields * diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Date.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Date.php index da75f72390..21d1bb928b 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Date.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Date.php @@ -1,13 +1,5 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Email.php,v 1.7 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; +/** + * Email validation rule + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Email.php,v 1.7 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * Email validation rule - * - * @category HTML - * @package HTML_QuickForm - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 3.2 - */ + * Email validation rule + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 3.2 + */ class HTML_QuickForm_Rule_Email extends HTML_QuickForm_Rule { var $regex = '/^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/'; @@ -49,8 +44,8 @@ class HTML_QuickForm_Rule_Email extends HTML_QuickForm_Rule */ function validate($email, $checkDomain = false) { - // Fix for bug #10799: add 'D' modifier to regex - if (preg_match($this->regex . 'D', $email)) { + // Fix for bug #10799: add 'D' modifier to regex + if (preg_match($this->regex . 'D', $email)) { if ($checkDomain && function_exists('checkdnsrr')) { $tokens = explode('@', $email); if (checkdnsrr($tokens[1], 'MX') || checkdnsrr($tokens[1], 'A')) { @@ -70,4 +65,4 @@ class HTML_QuickForm_Rule_Email extends HTML_QuickForm_Rule } // end func getValidationScript } // end class HTML_QuickForm_Rule_Email -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Range.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Range.php index 69ccc289da..b40222ca31 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Range.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Range.php @@ -1,40 +1,35 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Range.php,v 1.8 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; +/** + * Checks that the length of value is within range + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Range.php,v 1.8 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * Checks that the length of value is within range - * - * @category HTML - * @package HTML_QuickForm - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 3.2 - */ + * Checks that the length of value is within range + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 3.2 + */ class HTML_QuickForm_Rule_Range extends HTML_QuickForm_Rule { /** @@ -75,4 +70,4 @@ class HTML_QuickForm_Rule_Range extends HTML_QuickForm_Rule } // end func getValidationScript } // end class HTML_QuickForm_Rule_Range -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Regex.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Regex.php index 61dff6c1ee..e3a2cae5df 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Regex.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Regex.php @@ -1,40 +1,35 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: Regex.php,v 1.6 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; +/** + * Validates values using regular expressions + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: Regex.php,v 1.6 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * Validates values using regular expressions - * - * @category HTML - * @package HTML_QuickForm - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 3.2 - */ + * Validates values using regular expressions + * + * @category HTML + * @package HTML_QuickForm + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 3.2 + */ class HTML_QuickForm_Rule_Regex extends HTML_QuickForm_Rule { /** @@ -64,13 +59,13 @@ class HTML_QuickForm_Rule_Regex extends HTML_QuickForm_Rule */ function validate($value, $regex = null) { - // Fix for bug #10799: add 'D' modifier to regex + // Fix for bug #10799: add 'D' modifier to regex if (isset($this->_data[$this->name])) { - if (!preg_match($this->_data[$this->name] . 'D', $value)) { + if (!preg_match($this->_data[$this->name] . 'D', $value)) { return false; } } else { - if (!preg_match($regex . 'D', $value)) { + if (!preg_match($regex . 'D', $value)) { return false; } } @@ -94,14 +89,14 @@ class HTML_QuickForm_Rule_Regex extends HTML_QuickForm_Rule { $regex = isset($this->_data[$this->name]) ? $this->_data[$this->name] : $options; - // bug #12376, converting unicode escapes and stripping 'u' modifier - if ($pos = strpos($regex, 'u', strrpos($regex, '/'))) { - $regex = substr($regex, 0, $pos) . substr($regex, $pos + 1); - $regex = preg_replace('/(?\\\\\\\\)*\\\\x{([a-fA-F0-9]+)}/', '\\u$1', $regex); - } - + // bug #12376, converting unicode escapes and stripping 'u' modifier + if ($pos = strpos($regex, 'u', strrpos($regex, '/'))) { + $regex = substr($regex, 0, $pos) . substr($regex, $pos + 1); + $regex = preg_replace('/(?\\\\\\\\)*\\\\x{([a-fA-F0-9]+)}/', '\\u$1', $regex); + } + return array(" var regex = " . $regex . ";\n", "{jsVar} != '' && !regex.test({jsVar})"); } // end func getValidationScript } // end class HTML_QuickForm_Rule_Regex -?> \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/Rule/Required.php b/main/inc/lib/pear/HTML/QuickForm/Rule/Required.php index 7f36749690..49958d0237 100755 --- a/main/inc/lib/pear/HTML/QuickForm/Rule/Required.php +++ b/main/inc/lib/pear/HTML/QuickForm/Rule/Required.php @@ -21,11 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Abstract base class for QuickForm validation rules - */ -require_once 'HTML/QuickForm/Rule.php'; - /** * Required elements validation * diff --git a/main/inc/lib/pear/HTML/QuickForm/advanced_settings.php b/main/inc/lib/pear/HTML/QuickForm/advanced_settings.php index f48943b4a5..cb980059a0 100755 --- a/main/inc/lib/pear/HTML/QuickForm/advanced_settings.php +++ b/main/inc/lib/pear/HTML/QuickForm/advanced_settings.php @@ -3,7 +3,6 @@ * HTML class for static data * @example $form->addElement('advanced_settings', 'advanced settings'); */ -require_once 'HTML/QuickForm/static.php'; /** * A pseudo-element used for adding raw HTML to form @@ -34,7 +33,7 @@ class HTML_QuickForm_advanced_settings extends HTML_QuickForm_static $this->HTML_QuickForm_static(null, null, $text); $this->_type = 'html'; } - + /** * Accepts a renderer * @@ -46,8 +45,8 @@ class HTML_QuickForm_advanced_settings extends HTML_QuickForm_static { $renderer->renderHtml($this); } // end func accept - - + + function toHtml() { return '
    @@ -55,7 +54,7 @@ class HTML_QuickForm_advanced_settings extends HTML_QuickForm_static '.HTML_QuickForm_static::toHtml().'
    - + '; } //end func toHtml } //end class HTML_QuickForm_html diff --git a/main/inc/lib/pear/HTML/QuickForm/advcheckbox.php b/main/inc/lib/pear/HTML/QuickForm/advcheckbox.php index 2568fc1f89..c11d1b0bfa 100755 --- a/main/inc/lib/pear/HTML/QuickForm/advcheckbox.php +++ b/main/inc/lib/pear/HTML/QuickForm/advcheckbox.php @@ -1,31 +1,26 @@ - * @author Alexey Borzov - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: advcheckbox.php,v 1.18 2009/04/04 21:34:02 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * HTML class for a checkbox type field - */ -require_once 'HTML/QuickForm/checkbox.php'; +/** + * HTML class for an advanced checkbox type field + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Jason Rust + * @author Alexey Borzov + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: advcheckbox.php,v 1.18 2009/04/04 21:34:02 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * HTML class for an advanced checkbox type field @@ -42,12 +37,12 @@ require_once 'HTML/QuickForm/checkbox.php'; * checked, PHP overwrites the value of the hidden field with * its value. * - * @category HTML - * @package HTML_QuickForm - * @author Jason Rust - * @author Alexey Borzov - * @version Release: 3.2.11 - * @since 2.0 + * @category HTML + * @package HTML_QuickForm + * @author Jason Rust + * @author Alexey Borzov + * @version Release: 3.2.11 + * @since 2.0 */ class HTML_QuickForm_advcheckbox extends HTML_QuickForm_checkbox { @@ -236,7 +231,7 @@ class HTML_QuickForm_advcheckbox extends HTML_QuickForm_checkbox * * @param string $event Name of event * @param mixed $arg event arguments - * @param object &$caller calling object + * @param object &$caller calling object * @since 1.0 * @access public * @return void diff --git a/main/inc/lib/pear/HTML/QuickForm/advmultiselect.php b/main/inc/lib/pear/HTML/QuickForm/advmultiselect.php index e7b9333e6f..ff4fa28eab 100755 --- a/main/inc/lib/pear/HTML/QuickForm/advmultiselect.php +++ b/main/inc/lib/pear/HTML/QuickForm/advmultiselect.php @@ -40,10 +40,6 @@ * @link http://pear.php.net/package/HTML_QuickForm_advmultiselect * @since File available since Release 0.4.0 */ -/** - * Code - */ -require_once 'HTML/QuickForm/select.php'; /** * Basic error codes @@ -220,6 +216,8 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select */ var $_attributesHidden; + public $selectAllCheckBox = false; + /** * Default Element template string * @@ -274,14 +272,19 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select * @return void * @since version 0.4.0 (2005-06-25) */ - function HTML_QuickForm_advmultiselect($elementName = null, $elementLabel = null, - $options = null, $attributes = null, - $sort = null) - { - $opts = $options; + public function HTML_QuickForm_advmultiselect( + $elementName = null, + $elementLabel = null, + $options = null, + $attributes = null, + $sort = null + ) { + $opts = $options; $options = null; // prevent to use the default select element load options - $this->HTML_QuickForm_select($elementName, $elementLabel, - $options, $attributes); + + $this->HTML_QuickForm_select($elementName, $elementLabel, $options, $attributes); + + $this->selectAllCheckBox = isset($attributes['select_all_checkbox']) ? $attributes['select_all_checkbox'] : false; // allow to load options at once and take care of fancy attributes $this->load($opts); @@ -295,13 +298,12 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select } if (is_null($this->getAttribute('style'))) { // default width of each select box - $this->updateAttributes(array('style' => 'width:100px;')); + $this->updateAttributes(array('style' => 'min-width:180px;')); } $this->_tableAttributes = $this->getAttribute('class'); if (is_null($this->_tableAttributes)) { // default table layout - $attr = array('border' => '0', - 'cellpadding' => '10', 'cellspacing' => '0'); + $attr = array('border' => '0', 'cellpadding' => '10', 'cellspacing' => '0'); } else { $attr = array('class' => $this->_tableAttributes); $this->_removeAttr('class', $this->_attributes); @@ -396,116 +398,119 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select { if (!is_string($button)) { return PEAR::throwError('Argument 1 of HTML_QuickForm_advmultiselect::' . - 'setButtonAttributes is not a string', - HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, - array('level' => 'exception')); + 'setButtonAttributes is not a string', + HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, + array('level' => 'exception')); } switch ($button) { - case 'add': - if (is_null($attributes)) { - $this->_addButtonAttributes - = array('name' => 'add', - 'value' => ' ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_addButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'remove': - if (is_null($attributes)) { - $this->_removeButtonAttributes - = array('name' => 'remove', - 'value' => ' ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_removeButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'all': - if (is_null($attributes)) { - $this->_allButtonAttributes - = array('name' => 'all', - 'value' => ' Select All ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_allButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'none': - if (is_null($attributes)) { - $this->_noneButtonAttributes - = array('name' => 'none', - 'value' => ' Select None ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_noneButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'toggle': - if (is_null($attributes)) { - $this->_toggleButtonAttributes - = array('name' => 'toggle', - 'value' => ' Toggle Selection ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_toggleButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'moveup': - if (is_null($attributes)) { - $this->_upButtonAttributes - = array('name' => 'up', - 'value' => ' Up ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_upButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'movedown': - if (is_null($attributes)) { - $this->_downButtonAttributes - = array('name' => 'down', - 'value' => ' Down ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_downButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'movetop': - if (is_null($attributes)) { - $this->_topButtonAttributes - = array('name' => 'top', - 'value' => ' Top ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_topButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - case 'movebottom': - if (is_null($attributes)) { - $this->_bottomButtonAttributes - = array('name' => 'bottom', - 'value' => ' Bottom ', - 'type' => 'button'); - } else { - $this->_updateAttrArray($this->_bottomButtonAttributes, - $this->_parseAttributes($attributes)); - } - break; - default; - return PEAR::throwError('Argument 1 of HTML_QuickForm_advmultiselect::' . - 'setButtonAttributes has unexpected value', - HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, - array('level' => 'error')); + case 'add': + if (is_null($attributes)) { + $this->_addButtonAttributes = array( + 'name' => 'add', + 'value' => ' ', + 'type' => 'button' + ); + } else { + $this->_updateAttrArray( + $this->_addButtonAttributes, + $this->_parseAttributes($attributes) + ); + } + break; + case 'remove': + if (is_null($attributes)) { + $this->_removeButtonAttributes + = array('name' => 'remove', + 'value' => ' ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_removeButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'all': + if (is_null($attributes)) { + $this->_allButtonAttributes + = array('name' => 'all', + 'value' => ' Select All ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_allButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'none': + if (is_null($attributes)) { + $this->_noneButtonAttributes + = array('name' => 'none', + 'value' => ' Select None ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_noneButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'toggle': + if (is_null($attributes)) { + $this->_toggleButtonAttributes + = array('name' => 'toggle', + 'value' => ' Toggle Selection ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_toggleButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'moveup': + if (is_null($attributes)) { + $this->_upButtonAttributes + = array('name' => 'up', + 'value' => ' Up ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_upButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'movedown': + if (is_null($attributes)) { + $this->_downButtonAttributes + = array('name' => 'down', + 'value' => ' Down ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_downButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'movetop': + if (is_null($attributes)) { + $this->_topButtonAttributes + = array('name' => 'top', + 'value' => ' Top ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_topButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + case 'movebottom': + if (is_null($attributes)) { + $this->_bottomButtonAttributes + = array('name' => 'bottom', + 'value' => ' Bottom ', + 'type' => 'button'); + } else { + $this->_updateAttrArray($this->_bottomButtonAttributes, + $this->_parseAttributes($attributes)); + } + break; + default; + return PEAR::throwError('Argument 1 of HTML_QuickForm_advmultiselect::' . + 'setButtonAttributes has unexpected value', + HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, + array('level' => 'error')); } } @@ -541,7 +546,7 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select } if ($js == false) { $this->_elementTemplate = str_replace('{javascript}', '', - $this->_elementTemplate); + $this->_elementTemplate); } return $oldTemplate; } @@ -572,13 +577,13 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select if ($raw !== true) { $css = ''; + // Modified by Chamilo team, 16-MAR-2010. + //. '' . PHP_EOL + . '/**/' . PHP_EOL + // + . ''; } return $css; } @@ -590,14 +595,14 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select * @return string * @since version 0.4.0 (2005-06-25) */ - function toHtml() + public function toHtml() { if ($this->_flagFrozen) { return $this->getFrozenHtml(); } - $tabs = $this->_getTabs(); - $tab = $this->_getTab(); + $tabs = $this->_getTabs(); + $tab = $this->_getTab(); $selectId = $this->getName(); $selectName = $this->getName() . '[]'; @@ -614,7 +619,6 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select $strHtmlSelected = $tab . '
    ' . PHP_EOL; $unselected_count = count($this->_options); - $checkbox_id_suffix = 0; foreach ($this->_options as $option) { @@ -639,15 +643,15 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select } $checkbox_id_suffix++; $strHtmlSelected .= $tab - . '_getAttrString($labelAttributes) .'>' - . '_getAttrString($option['attr']) - . ' />' . $option['text'] . '' - . PHP_EOL; + . '_getAttrString($labelAttributes) .'>' + . '_getAttrString($option['attr']) + . ' />' . $option['text'] . '' + . PHP_EOL; } $strHtmlSelected .= $tab . '
    '. PHP_EOL; @@ -658,27 +662,22 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the select all button with all its attributes $jsName = $this->_jsPrefix . $this->_jsPostfix; - $attributes = array('onclick' => $jsName . - "('". $selectId ."', 1);"); - $this->_allButtonAttributes - = array_merge($this->_allButtonAttributes, $attributes); + $attributes = array('onclick' => $jsName ."('". $selectId ."', 1);"); + $this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes); $attrStrAll = $this->_getAttrString($this->_allButtonAttributes); $strHtmlAll = "". PHP_EOL; // build the select none button with all its attributes - $attributes = array('onclick' => $jsName . - "('". $selectId ."', 0);"); + $attributes = array('onclick' => $jsName ."('". $selectId ."', 0);"); $this->_noneButtonAttributes - = array_merge($this->_noneButtonAttributes, $attributes); + = array_merge($this->_noneButtonAttributes, $attributes); $attrStrNone = $this->_getAttrString($this->_noneButtonAttributes); $strHtmlNone = "". PHP_EOL; // build the toggle selection button with all its attributes $attributes = array('onclick' => $jsName . - "('". $selectId ."', 2);"); - $this->_toggleButtonAttributes - = array_merge($this->_toggleButtonAttributes, - $attributes); + "('". $selectId ."', 2);"); + $this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes); $attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes); $strHtmlToggle = "". PHP_EOL; @@ -697,13 +696,13 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // set name of Select From Box $this->_attributesUnselected = array('id' => $selectId . '-f', - 'name' => $selectNameFrom, - 'ondblclick' => $jsName . - "('{$selectId}', ". - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'add', '{$this->_sort}')"); + 'name' => $selectNameFrom, + 'ondblclick' => $jsName . + "('{$selectId}', ". + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'add', '{$this->_sort}')"); $this->_attributesUnselected = array_merge($this->_attributes, $this->_attributesUnselected); $attrUnselected = $this->_getAttrString($this->_attributesUnselected); @@ -711,13 +710,13 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // set name of Select To Box $this->_attributesSelected = array('id' => $selectId . '-t', - 'name' => $selectNameTo, - 'ondblclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], ". - "this.form.elements['" . $selectName . "'], " . - "'remove', '{$this->_sort}')"); + 'name' => $selectNameTo, + 'ondblclick' => $jsName . + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], ". + "this.form.elements['" . $selectName . "'], " . + "'remove', '{$this->_sort}')"); $this->_attributesSelected = array_merge($this->_attributes, $this->_attributesSelected); $attrSelected = $this->_getAttrString($this->_attributesSelected); @@ -725,8 +724,8 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // set name of Select hidden Box $this->_attributesHidden = array('name' => $selectName, - 'style' => 'overflow: hidden; visibility: hidden; ' . - 'width: 1px; height: 0;'); + 'style' => 'overflow: hidden; visibility: hidden; ' . + 'width: 1px; height: 0;'); $this->_attributesHidden = array_merge($this->_attributes, $this->_attributesHidden); $attrHidden = $this->_getAttrString($this->_attributesHidden); @@ -747,16 +746,16 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select foreach ($this->_options as $option) { if (is_array($this->_values) && in_array((string)$option['attr']['value'], - $this->_values)) { + $this->_values)) { // Get the post order $key = array_search($option['attr']['value'], - $this->_values); + $this->_values); /** The items is *selected* so we want to put it - in the 'selected' multi-select */ + in the 'selected' multi-select */ $arrHtmlSelected[$key] = $option; /** Add it to the 'hidden' multi-select - and set it as 'selected' */ + and set it as 'selected' */ if (isset($option['attr']['disabled'])) { unset($option['attr']['disabled']); } @@ -764,7 +763,7 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select $arrHtmlHidden[$key] = $option; } else { /** The item is *unselected* so we want to put it - in the 'unselected' multi-select */ + in the 'unselected' multi-select */ $arrHtmlUnselected[] = $option; // Add it to the hidden multi-select as 'unselected' $arrHtmlHidden[$append] = $option; @@ -806,13 +805,22 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select = array_merge($this->_attributes, $this->_attributesSelected); $attrSelected = $this->_getAttrString($this->_attributesSelected); } - $strHtmlSelected = "". PHP_EOL; + $strHtmlSelected = ""; if ($selected_count > 0) { foreach ($arrHtmlSelected as $data) { + $attribute = null; + if (isset($data['attr'])) { + $attribute = $this->_getAttrString($data['attr']); + } + + $text = null; + if (isset($data['text'])) { + $text = $data['text']; + } $strHtmlSelected .= $tabs . $tab - . '_getAttrString($data['attr']) . '>' - . $data['text'] . '' . PHP_EOL; + . '' + . $text . ''; } } else { $strHtmlSelected .= ''; @@ -823,10 +831,18 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select $strHtmlHidden = "". PHP_EOL; if (count($arrHtmlHidden) > 0) { foreach ($arrHtmlHidden as $data) { + $attribute = null; + if (isset($data['attr'])) { + $attribute = $this->_getAttrString($data['attr']); + } + $text = null; + if (isset($data['text'])) { + $text = $data['text']; + } $strHtmlHidden .= $tabs . $tab - . '_getAttrString($data['attr']) . '>' - . $data['text'] . '' . PHP_EOL; + . '' + . $text . '' . PHP_EOL; } } $strHtmlHidden .= ''; @@ -834,50 +850,48 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the remove button with all its attributes $attributes = array('onclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'remove', '{$this->_sort}'); return false;"); + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'remove', '{$this->_sort}'); return false;"); $this->_removeButtonAttributes = array_merge($this->_removeButtonAttributes, $attributes); $attrStrRemove = $this->_getAttrString($this->_removeButtonAttributes); - $strHtmlRemove = "". PHP_EOL; + $strHtmlRemove = ""; // build the add button with all its attributes $attributes = array('onclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'add', '{$this->_sort}'); return false;"); - $this->_addButtonAttributes - = array_merge($this->_addButtonAttributes, $attributes); + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'add', '{$this->_sort}'); return false;"); + $this->_addButtonAttributes = array_merge($this->_addButtonAttributes, $attributes); $attrStrAdd = $this->_getAttrString($this->_addButtonAttributes); - $strHtmlAdd = "". PHP_EOL; + $strHtmlAdd = "

    "; // build the select all button with all its attributes $attributes = array('onclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'all', '{$this->_sort}'); return false;"); - $this->_allButtonAttributes - = array_merge($this->_allButtonAttributes, $attributes); + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'all', '{$this->_sort}'); return false;"); + $this->_allButtonAttributes = array_merge($this->_allButtonAttributes, $attributes); $attrStrAll = $this->_getAttrString($this->_allButtonAttributes); $strHtmlAll = "". PHP_EOL; // build the select none button with all its attributes $attributes = array('onclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'none', '{$this->_sort}'); return false;"); + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'none', '{$this->_sort}'); return false;"); $this->_noneButtonAttributes = array_merge($this->_noneButtonAttributes, $attributes); $attrStrNone = $this->_getAttrString($this->_noneButtonAttributes); @@ -886,11 +900,11 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the toggle button with all its attributes $attributes = array('onclick' => $jsName . - "('{$selectId}', " . - "this.form.elements['" . $selectNameFrom . "'], " . - "this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "'], " . - "'toggle', '{$this->_sort}'); return false;"); + "('{$selectId}', " . + "this.form.elements['" . $selectNameFrom . "'], " . + "this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "'], " . + "'toggle', '{$this->_sort}'); return false;"); $this->_toggleButtonAttributes = array_merge($this->_toggleButtonAttributes, $attributes); $attrStrToggle = $this->_getAttrString($this->_toggleButtonAttributes); @@ -899,9 +913,9 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the move up button with all its attributes $attributes = array('onclick' => "{$this->_jsPrefix}moveUp" . - "(this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "']); " . - "return false;"); + "(this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "']); " . + "return false;"); $this->_upButtonAttributes = array_merge($this->_upButtonAttributes, $attributes); $attrStrUp = $this->_getAttrString($this->_upButtonAttributes); @@ -910,9 +924,9 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the move down button with all its attributes $attributes = array('onclick' => "{$this->_jsPrefix}moveDown" . - "(this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "']); " . - "return false;"); + "(this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "']); " . + "return false;"); $this->_downButtonAttributes = array_merge($this->_downButtonAttributes, $attributes); $attrStrDown = $this->_getAttrString($this->_downButtonAttributes); @@ -921,9 +935,9 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the move top button with all its attributes $attributes = array('onclick' => "{$this->_jsPrefix}moveTop" . - "(this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "']); " . - "return false;"); + "(this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "']); " . + "return false;"); $this->_topButtonAttributes = array_merge($this->_topButtonAttributes, $attributes); $attrStrTop = $this->_getAttrString($this->_topButtonAttributes); @@ -932,9 +946,9 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // build the move bottom button with all its attributes $attributes = array('onclick' => "{$this->_jsPrefix}moveBottom" . - "(this.form.elements['" . $selectNameTo . "'], " . - "this.form.elements['" . $selectName . "']); " . - "return false;"); + "(this.form.elements['" . $selectNameTo . "'], " . + "this.form.elements['" . $selectName . "']); " . + "return false;"); $this->_bottomButtonAttributes = array_merge($this->_bottomButtonAttributes, $attributes); $attrStrBottom = $this->_getAttrString($this->_bottomButtonAttributes); @@ -968,7 +982,7 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select // clean up useless label tags if (strpos($strHtml, '{label_')) { $strHtml = preg_replace('/\s*'. - '.*\s*/i', '', $strHtml); + '.*\s*/i', '', $strHtml); } $placeHolders = array( @@ -994,6 +1008,14 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select $strHtmlMoveTop, $strHtmlMoveBottom ); + if ($this->selectAllCheckBox) { + $strHtml .= ' + + '; + } + $strHtml = str_replace($placeHolders, $htmlElements, $strHtml); $comment = $this->getComment(); @@ -1002,6 +1024,7 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select $strHtml = $tabs . '" . PHP_EOL . $strHtml; } + return $strHtml; } @@ -1017,23 +1040,21 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select */ function getElementJs($raw = true, $min = true) { - $js = '@data_dir@' . DIRECTORY_SEPARATOR - . '@package_name@' . DIRECTORY_SEPARATOR; - - $js = api_get_path(LIBRARY_PATH).'javascript'.DIRECTORY_SEPARATOR.'pear'.DIRECTORY_SEPARATOR; - - if ($min) { + $js = api_get_path(LIBRARY_PATH).'javascript'.DIRECTORY_SEPARATOR.'pear'.DIRECTORY_SEPARATOR; + + /*if ($min) { $js .= 'qfamsHandler-min.js'; } else { $js .= 'qfamsHandler.js'; - } + }*/ + $js .= 'qfamsHandler.js'; - if (file_exists($js)) { - $js = file_get_contents($js); + if (file_exists($js)) { + $js = file_get_contents($js); } else { $js = ''; } - + if ($raw !== true) { $js = '' . PHP_EOL; } + return $js; } @@ -1064,7 +1086,7 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select * @see loadArray() */ function load(&$options, - $param1 = null, $param2 = null, $param3 = null, $param4 = null) + $param1 = null, $param2 = null, $param3 = null, $param4 = null) { if (is_array($options)) { $ret = $this->loadArray($options, $param1); @@ -1093,9 +1115,9 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select { if (!is_array($arr)) { return PEAR::throwError('Argument 1 of HTML_QuickForm_advmultiselect::' . - 'loadArray is not a valid array', - HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, - array('level' => 'exception')); + 'loadArray is not a valid array', + HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, + array('level' => 'exception')); } if (isset($values)) { $this->setSelected($values); @@ -1130,18 +1152,18 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select { if (!is_bool($persistant)) { return PEAR::throwError('Argument 2 of HTML_QuickForm_advmultiselect::' . - 'setPersistantOptions is not a boolean', - HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, - array('level' => 'exception')); + 'setPersistantOptions is not a boolean', + HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, + array('level' => 'exception')); } if (is_string($optionValues)) { $optionValues = array($optionValues); } if (!is_array($optionValues)) { return PEAR::throwError('Argument 1 of HTML_QuickForm_advmultiselect::' . - 'setPersistantOptions is not a valid array', - HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, - array('level' => 'exception')); + 'setPersistantOptions is not a valid array', + HTML_QUICKFORM_ADVMULTISELECT_ERROR_INVALID_INPUT, + array('level' => 'exception')); } foreach ($this->_options as $k => $v) { @@ -1179,8 +1201,3 @@ class HTML_QuickForm_advmultiselect extends HTML_QuickForm_select return $options; } } - -// @todo this fires an PHP notice, needed in order to parse the advmultiselect test it in main/group/group_edit.php -if (class_exists('HTML_QuickForm')) { - @HTML_QuickForm::registerElementType('advmultiselect','HTML/QuickForm/advmultiselect.php', 'HTML_QuickForm_advmultiselect'); -} diff --git a/main/inc/lib/pear/HTML/QuickForm/autocomplete.php b/main/inc/lib/pear/HTML/QuickForm/autocomplete.php index 46fff9588f..f9db2e9e22 100755 --- a/main/inc/lib/pear/HTML/QuickForm/autocomplete.php +++ b/main/inc/lib/pear/HTML/QuickForm/autocomplete.php @@ -1,54 +1,49 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: autocomplete.php,v 1.8 2009/04/04 21:34:02 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * HTML class for a text field - */ -require_once 'HTML/QuickForm/text.php'; +/** + * HTML class for an autocomplete element + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Matteo Di Giovinazzo + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: autocomplete.php,v 1.8 2009/04/04 21:34:02 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * HTML class for an autocomplete element - * - * Creates an HTML input text element that - * at every keypressed javascript event checks in an array of options - * if there's a match and autocompletes the text in case of match. + * HTML class for an autocomplete element + * + * Creates an HTML input text element that + * at every keypressed javascript event checks in an array of options + * if there's a match and autocompletes the text in case of match. + * + * For the JavaScript code thanks to Martin Honnen and Nicholas C. Zakas + * See {@link http://www.faqts.com/knowledge_base/view.phtml/aid/13562} and + * {@link http://www.sitepoint.com/article/1220} * - * For the JavaScript code thanks to Martin Honnen and Nicholas C. Zakas - * See {@link http://www.faqts.com/knowledge_base/view.phtml/aid/13562} and - * {@link http://www.sitepoint.com/article/1220} - * - * Example: - * + * Example: + * * $autocomplete =& $form->addElement('autocomplete', 'fruit', 'Favourite fruit:'); * $options = array("Apple", "Orange", "Pear", "Strawberry"); * $autocomplete->setOptions($options); - * + * * - * @category HTML - * @package HTML_QuickForm - * @author Matteo Di Giovinazzo - * @version Release: 3.2.11 - * @since 3.2 + * @category HTML + * @package HTML_QuickForm + * @author Matteo Di Giovinazzo + * @version Release: 3.2.11 + * @since 3.2 */ class HTML_QuickForm_autocomplete extends HTML_QuickForm_text { diff --git a/main/inc/lib/pear/HTML/QuickForm/button.php b/main/inc/lib/pear/HTML/QuickForm/button.php index 5ff95ac1e8..0492d7b6e6 100755 --- a/main/inc/lib/pear/HTML/QuickForm/button.php +++ b/main/inc/lib/pear/HTML/QuickForm/button.php @@ -1,67 +1,87 @@ elements - * - * PHP versions 4 and 5 - * - * LICENSE: This source file is subject to version 3.01 of the PHP license - * that is available through the world-wide-web at the following URI: - * http://www.php.net/license/3_01.txt If you did not receive a copy of - * the PHP License and are unable to obtain it through the web, please - * send a note to license@php.net so we can mail you a copy immediately. - * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: button.php,v 1.6 2009/04/04 21:34:02 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; +/** + * HTML class for an elements + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: button.php,v 1.6 2009/04/04 21:34:02 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * HTML class for an elements + * HTML class for an elements * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 */ class HTML_QuickForm_button extends HTML_QuickForm_input { - // {{{ constructor - /** * Class constructor * - * @param string $elementName (optional)Input field name attribute - * @param string $value (optional)Input field value - * @param mixed $attributes (optional)Either a typical HTML attribute string + * @param string $elementName (optional)Input field name attribute + * @param string $value (optional)Input field value + * @param mixed $attributes (optional)Either a typical HTML attribute string * or an associative array * @since 1.0 * @access public * @return void */ - function HTML_QuickForm_button($elementName=null, $value=null, $attributes=null) - { - HTML_QuickForm_input::HTML_QuickForm_input($elementName, null, $attributes); + public function HTML_QuickForm_button( + $elementName = null, + $value = null, + $attributes = null + ) { + HTML_QuickForm_input::HTML_QuickForm_input( + $elementName, + null, + $attributes + ); $this->_persistantFreeze = false; $this->setValue($value); - $this->setType('button'); - } //end constructor + $this->setType('submit'); + } - // }}} - // {{{ freeze() + /** + * @return string + */ + public function toHtml() + { + if ($this->_flagFrozen) { + return $this->getFrozenHtml(); + } else { + $value = $this->_attributes['value']; + unset($this->_attributes['value']); + $icon = null; + //$class = isset($this->_attributes['class']) ? $this->_attributes['class'] : 'btn btn-large'; + switch ($this->_attributes['name']) { + case 'save': + case 'submit': + $icon = ' '; + break; + } + + return $this->_getTabs() . '_getAttrString($this->_attributes) . ' />'.$icon.$value.''; + } + } /** * Freeze the element so that only its value is returned @@ -69,12 +89,8 @@ class HTML_QuickForm_button extends HTML_QuickForm_input * @access public * @return void */ - function freeze() + public function freeze() { return false; - } //end func freeze - - // }}} - -} //end class HTML_QuickForm_button -?> + } +} diff --git a/main/inc/lib/pear/HTML/QuickForm/checkbox.php b/main/inc/lib/pear/HTML/QuickForm/checkbox.php index 8a165515c7..2e8681cc64 100755 --- a/main/inc/lib/pear/HTML/QuickForm/checkbox.php +++ b/main/inc/lib/pear/HTML/QuickForm/checkbox.php @@ -23,10 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; /** * HTML class for a checkbox type field diff --git a/main/inc/lib/pear/HTML/QuickForm/date.php b/main/inc/lib/pear/HTML/QuickForm/date.php index 3fffb4dbdb..7093cafc3d 100755 --- a/main/inc/lib/pear/HTML/QuickForm/date.php +++ b/main/inc/lib/pear/HTML/QuickForm/date.php @@ -21,15 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Class for a group of form elements - */ -require_once 'HTML/QuickForm/group.php'; -/** - * Class for elements - */ -require_once 'HTML/QuickForm/select.php'; - /** * Class for a group of elements used to input dates (and times). * diff --git a/main/inc/lib/pear/HTML/QuickForm/email.php b/main/inc/lib/pear/HTML/QuickForm/email.php index 82462c1429..9239abc388 100755 --- a/main/inc/lib/pear/HTML/QuickForm/email.php +++ b/main/inc/lib/pear/HTML/QuickForm/email.php @@ -1,8 +1,4 @@ form elements - */ -require_once 'HTML/QuickForm/input.php'; /** * HTML class for a password type field @@ -73,4 +69,4 @@ class HTML_QuickForm_email extends HTML_QuickForm_input // }}} -} //end class HTML_QuickForm_password \ No newline at end of file +} //end class HTML_QuickForm_password diff --git a/main/inc/lib/pear/HTML/QuickForm/file.php b/main/inc/lib/pear/HTML/QuickForm/file.php index 79ac953a8e..57192f1de9 100755 --- a/main/inc/lib/pear/HTML/QuickForm/file.php +++ b/main/inc/lib/pear/HTML/QuickForm/file.php @@ -23,11 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; - // register file-related rules if (class_exists('HTML_QuickForm')) { HTML_QuickForm::registerRule('uploadedfile', 'callback', '_ruleIsUploadedFile', 'HTML_QuickForm_file'); @@ -221,9 +216,9 @@ class HTML_QuickForm_file extends HTML_QuickForm_input * @access public * @return bool true if file has been uploaded, false otherwise */ - function isUploadedFile() + public function isUploadedFile() { - return $this->_ruleIsUploadedFile($this->_value); + return HTML_QuickForm_file::_ruleIsUploadedFile($this->_value); } // end func isUploadedFile // }}} @@ -236,7 +231,7 @@ class HTML_QuickForm_file extends HTML_QuickForm_input * @access private * @return bool true if file has been uploaded, false otherwise */ - function _ruleIsUploadedFile($elementValue) + public static function _ruleIsUploadedFile($elementValue) { if ((isset($elementValue['error']) && $elementValue['error'] == 0) || (!empty($elementValue['tmp_name']) && $elementValue['tmp_name'] != 'none')) { diff --git a/main/inc/lib/pear/HTML/QuickForm/group.php b/main/inc/lib/pear/HTML/QuickForm/group.php index fd37af9078..681c3cd374 100755 --- a/main/inc/lib/pear/HTML/QuickForm/group.php +++ b/main/inc/lib/pear/HTML/QuickForm/group.php @@ -23,11 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/element.php'; - /** * HTML class for a form element group * diff --git a/main/inc/lib/pear/HTML/QuickForm/header.php b/main/inc/lib/pear/HTML/QuickForm/header.php index d38b172e24..5869507d14 100755 --- a/main/inc/lib/pear/HTML/QuickForm/header.php +++ b/main/inc/lib/pear/HTML/QuickForm/header.php @@ -21,11 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * HTML class for static data - */ -require_once 'HTML/QuickForm/static.php'; - /** * A pseudo-element used for adding headers to form * @@ -50,7 +45,7 @@ class HTML_QuickForm_header extends HTML_QuickForm_static function HTML_QuickForm_header($elementName = null, $text = null) { if (!empty($elementName)) { $text = $elementName; - } + } $this->HTML_QuickForm_static($elementName, null, $text); $this->_type = 'header'; } diff --git a/main/inc/lib/pear/HTML/QuickForm/hidden.php b/main/inc/lib/pear/HTML/QuickForm/hidden.php index 8e75d5047c..94dccd0628 100755 --- a/main/inc/lib/pear/HTML/QuickForm/hidden.php +++ b/main/inc/lib/pear/HTML/QuickForm/hidden.php @@ -22,11 +22,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; - /** * HTML class for a hidden type element * diff --git a/main/inc/lib/pear/HTML/QuickForm/hiddenselect.php b/main/inc/lib/pear/HTML/QuickForm/hiddenselect.php index 835228a5ec..f0a58efc25 100755 --- a/main/inc/lib/pear/HTML/QuickForm/hiddenselect.php +++ b/main/inc/lib/pear/HTML/QuickForm/hiddenselect.php @@ -1,45 +1,40 @@ - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: hiddenselect.php,v 1.7 2009/04/04 21:34:03 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ +/** + * Hidden select pseudo-element + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Isaac Shepard + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: hiddenselect.php,v 1.7 2009/04/04 21:34:03 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** - * Class for elements - */ -require_once 'HTML/QuickForm/select.php'; - -/** - * Hidden select pseudo-element - * + * Hidden select pseudo-element + * * This class takes the same arguments as a select element, but instead * of creating a select ring it creates hidden elements for all values * already selected with setDefault or setConstant. This is useful if * you have a select ring that you don't want visible, but you need all * selected values to be passed. * - * @category HTML - * @package HTML_QuickForm - * @author Isaac Shepard - * @version Release: 3.2.11 - * @since 2.1 + * @category HTML + * @package HTML_QuickForm + * @author Isaac Shepard + * @version Release: 3.2.11 + * @since 2.1 */ class HTML_QuickForm_hiddenselect extends HTML_QuickForm_select { diff --git a/main/inc/lib/pear/HTML/QuickForm/hierselect.php b/main/inc/lib/pear/HTML/QuickForm/hierselect.php index 6e26f9bf30..5cb66018ce 100755 --- a/main/inc/lib/pear/HTML/QuickForm/hierselect.php +++ b/main/inc/lib/pear/HTML/QuickForm/hierselect.php @@ -1,52 +1,43 @@ - * @author Bertrand Mansion - * @author Alexey Borzov - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: hierselect.php,v 1.20 2009/04/04 21:34:03 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Class for a group of form elements - */ -require_once 'HTML/QuickForm/group.php'; -/** - * Class for elements - */ -require_once 'HTML/QuickForm/select.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** - * Hierarchical select element - * + * Hierarchical select element + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Herim Vasquez + * @author Bertrand Mansion + * @author Alexey Borzov + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: hierselect.php,v 1.20 2009/04/04 21:34:03 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ + +/** + * Hierarchical select element + * * Class to dynamically create two or more HTML Select elements * The first select changes the content of the second select and so on. * This element is considered as a group. Selects will be named * groupName[0], groupName[1], groupName[2]... * - * @category HTML - * @package HTML_QuickForm - * @author Herim Vasquez - * @author Bertrand Mansion - * @author Alexey Borzov - * @version Release: 3.2.11 - * @since 3.1 + * @category HTML + * @package HTML_QuickForm + * @author Herim Vasquez + * @author Bertrand Mansion + * @author Alexey Borzov + * @version Release: 3.2.11 + * @since 3.1 */ class HTML_QuickForm_hierselect extends HTML_QuickForm_group { @@ -55,7 +46,7 @@ class HTML_QuickForm_hierselect extends HTML_QuickForm_group /** * Options for all the select elements * - * @see setOptions() + * @see setOptions() * @var array * @access private */ @@ -110,45 +101,45 @@ class HTML_QuickForm_hierselect extends HTML_QuickForm_group * Initialize the array structure containing the options for each select element. * Call the functions that actually do the magic. * - * Format is a bit more complex than for a simple select as we need to know - * which options are related to the ones in the previous select: - * - * Ex: - * - * // first select - * $select1[0] = 'Pop'; - * $select1[1] = 'Classical'; - * $select1[2] = 'Funeral doom'; - * - * // second select - * $select2[0][0] = 'Red Hot Chil Peppers'; - * $select2[0][1] = 'The Pixies'; - * $select2[1][0] = 'Wagner'; - * $select2[1][1] = 'Strauss'; - * $select2[2][0] = 'Pantheist'; - * $select2[2][1] = 'Skepticism'; - * - * // If only need two selects - * // - and using the deprecated functions - * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); - * $sel->setMainOptions($select1); - * $sel->setSecOptions($select2); - * - * // - and using the new setOptions function - * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); - * $sel->setOptions(array($select1, $select2)); - * - * // If you have a third select with prices for the cds - * $select3[0][0][0] = '15.00$'; - * $select3[0][0][1] = '17.00$'; - * // etc - * - * // You can now use - * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); - * $sel->setOptions(array($select1, $select2, $select3)); - * + * Format is a bit more complex than for a simple select as we need to know + * which options are related to the ones in the previous select: + * + * Ex: + * + * // first select + * $select1[0] = 'Pop'; + * $select1[1] = 'Classical'; + * $select1[2] = 'Funeral doom'; * - * @param array $options Array of options defining each element + * // second select + * $select2[0][0] = 'Red Hot Chil Peppers'; + * $select2[0][1] = 'The Pixies'; + * $select2[1][0] = 'Wagner'; + * $select2[1][1] = 'Strauss'; + * $select2[2][0] = 'Pantheist'; + * $select2[2][1] = 'Skepticism'; + * + * // If only need two selects + * // - and using the deprecated functions + * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); + * $sel->setMainOptions($select1); + * $sel->setSecOptions($select2); + * + * // - and using the new setOptions function + * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); + * $sel->setOptions(array($select1, $select2)); + * + * // If you have a third select with prices for the cds + * $select3[0][0][0] = '15.00$'; + * $select3[0][0][1] = '17.00$'; + * // etc + * + * // You can now use + * $sel =& $form->addElement('hierselect', 'cds', 'Choose CD:'); + * $sel->setOptions(array($select1, $select2, $select3)); + * + * + * @param array $options Array of options defining each element * @access public * @return void */ @@ -313,9 +304,9 @@ class HTML_QuickForm_hierselect extends HTML_QuickForm_group $this->_js .= << \ No newline at end of file +?> diff --git a/main/inc/lib/pear/HTML/QuickForm/html.php b/main/inc/lib/pear/HTML/QuickForm/html.php index cc6a9f22a0..61e750a52f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/html.php +++ b/main/inc/lib/pear/HTML/QuickForm/html.php @@ -21,11 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * HTML class for static data - */ -require_once 'HTML/QuickForm/static.php'; - /** * A pseudo-element used for adding raw HTML to form * diff --git a/main/inc/lib/pear/HTML/QuickForm/image.php b/main/inc/lib/pear/HTML/QuickForm/image.php index f84f420eef..34c4f7215b 100755 --- a/main/inc/lib/pear/HTML/QuickForm/image.php +++ b/main/inc/lib/pear/HTML/QuickForm/image.php @@ -1,41 +1,36 @@ element + * HTML class for an element * - * PHP versions 4 and 5 - * - * LICENSE: This source file is subject to version 3.01 of the PHP license - * that is available through the world-wide-web at the following URI: - * http://www.php.net/license/3_01.txt If you did not receive a copy of - * the PHP License and are unable to obtain it through the web, please - * send a note to license@php.net so we can mail you a copy immediately. - * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: image.php,v 1.6 2009/04/04 21:34:03 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; - -/** - * HTML class for an element - * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: image.php,v 1.6 2009/04/04 21:34:03 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ + +/** + * HTML class for an element + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 */ class HTML_QuickForm_image extends HTML_QuickForm_input { diff --git a/main/inc/lib/pear/HTML/QuickForm/input.php b/main/inc/lib/pear/HTML/QuickForm/input.php index bb5578e946..836fd81dbd 100755 --- a/main/inc/lib/pear/HTML/QuickForm/input.php +++ b/main/inc/lib/pear/HTML/QuickForm/input.php @@ -1,41 +1,36 @@ form elements - * - * PHP versions 4 and 5 - * - * LICENSE: This source file is subject to version 3.01 of the PHP license - * that is available through the world-wide-web at the following URI: - * http://www.php.net/license/3_01.txt If you did not receive a copy of - * the PHP License and are unable to obtain it through the web, please - * send a note to license@php.net so we can mail you a copy immediately. - * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: input.php,v 1.10 2009/04/04 21:34:03 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/element.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** - * Base class for form elements + * Base class for form elements * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: input.php,v 1.10 2009/04/04 21:34:03 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ + +/** + * Base class for form elements + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 * @abstract */ class HTML_QuickForm_input extends HTML_QuickForm_element @@ -163,7 +158,7 @@ class HTML_QuickForm_input extends HTML_QuickForm_element * * @param string $event Name of event * @param mixed $arg event arguments - * @param object &$caller calling object + * @param object &$caller calling object * @since 1.0 * @access public * @return void diff --git a/main/inc/lib/pear/HTML/QuickForm/label.php b/main/inc/lib/pear/HTML/QuickForm/label.php index fd313d9b6c..e13582c59f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/label.php +++ b/main/inc/lib/pear/HTML/QuickForm/label.php @@ -3,7 +3,6 @@ * HTML class for static data * @example $form->addElement('label', 'My label', 'Content'); */ -require_once 'HTML/QuickForm/static.php'; /** * A pseudo-element used for adding raw HTML to form diff --git a/main/inc/lib/pear/HTML/QuickForm/link.php b/main/inc/lib/pear/HTML/QuickForm/link.php index a2b5742b5a..379d62489f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/link.php +++ b/main/inc/lib/pear/HTML/QuickForm/link.php @@ -1,41 +1,36 @@ - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: link.php,v 1.4 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * HTML class for static data - */ -require_once 'HTML/QuickForm/static.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * HTML class for a link type field * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 2.0 + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: link.php,v 1.4 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ + +/** + * HTML class for a link type field + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 2.0 */ class HTML_QuickForm_link extends HTML_QuickForm_static { diff --git a/main/inc/lib/pear/HTML/QuickForm/password.php b/main/inc/lib/pear/HTML/QuickForm/password.php index dd800b5f11..5e57eaacf0 100755 --- a/main/inc/lib/pear/HTML/QuickForm/password.php +++ b/main/inc/lib/pear/HTML/QuickForm/password.php @@ -1,41 +1,36 @@ - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: password.php,v 1.8 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; +/** + * HTML class for a password type field + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: password.php,v 1.8 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * HTML class for a password type field * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 */ class HTML_QuickForm_password extends HTML_QuickForm_input { diff --git a/main/inc/lib/pear/HTML/QuickForm/radio.php b/main/inc/lib/pear/HTML/QuickForm/radio.php index 7dbe4e0bf5..efcce6c87f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/radio.php +++ b/main/inc/lib/pear/HTML/QuickForm/radio.php @@ -22,11 +22,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; - /** * HTML class for a radio type element * diff --git a/main/inc/lib/pear/HTML/QuickForm/reset.php b/main/inc/lib/pear/HTML/QuickForm/reset.php index b9518831a3..c08b9fb785 100755 --- a/main/inc/lib/pear/HTML/QuickForm/reset.php +++ b/main/inc/lib/pear/HTML/QuickForm/reset.php @@ -1,41 +1,36 @@ - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: reset.php,v 1.6 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; +/** + * HTML class for a reset type element + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: reset.php,v 1.6 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * HTML class for a reset type element * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 */ class HTML_QuickForm_reset extends HTML_QuickForm_input { diff --git a/main/inc/lib/pear/HTML/QuickForm/select.php b/main/inc/lib/pear/HTML/QuickForm/select.php index ee8cecc820..06b36b1b25 100755 --- a/main/inc/lib/pear/HTML/QuickForm/select.php +++ b/main/inc/lib/pear/HTML/QuickForm/select.php @@ -23,11 +23,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/element.php'; - /** * Class to dynamically create an HTML SELECT * @@ -116,7 +111,7 @@ class HTML_QuickForm_select extends HTML_QuickForm_element { function setSelected($values) { if (is_string($values) && $this->getMultiple()) { - $values = split("[ ]?,[ ]?", $values); + $values = explode("[ ]?,[ ]?", $values); } if (is_array($values)) { $this->_values = array_values($values); diff --git a/main/inc/lib/pear/HTML/QuickForm/static.php b/main/inc/lib/pear/HTML/QuickForm/static.php index 3561ce4e59..a07b48906f 100755 --- a/main/inc/lib/pear/HTML/QuickForm/static.php +++ b/main/inc/lib/pear/HTML/QuickForm/static.php @@ -21,11 +21,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/element.php'; - /** * HTML class for static data * diff --git a/main/inc/lib/pear/HTML/QuickForm/submit.php b/main/inc/lib/pear/HTML/QuickForm/submit.php index 3ff6f5ff90..2b476f3e8e 100755 --- a/main/inc/lib/pear/HTML/QuickForm/submit.php +++ b/main/inc/lib/pear/HTML/QuickForm/submit.php @@ -1,41 +1,36 @@ - * @author Bertrand Mansion - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: submit.php,v 1.6 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; +/** + * HTML class for a submit type element + * + * PHP versions 4 and 5 + * + * LICENSE: This source file is subject to version 3.01 of the PHP license + * that is available through the world-wide-web at the following URI: + * http://www.php.net/license/3_01.txt If you did not receive a copy of + * the PHP License and are unable to obtain it through the web, please + * send a note to license@php.net so we can mail you a copy immediately. + * + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @copyright 2001-2009 The PHP Group + * @license http://www.php.net/license/3_01.txt PHP License 3.01 + * @version CVS: $Id: submit.php,v 1.6 2009/04/04 21:34:04 avb Exp $ + * @link http://pear.php.net/package/HTML_QuickForm + */ /** * HTML class for a submit type element * - * @category HTML - * @package HTML_QuickForm - * @author Adam Daniel - * @author Bertrand Mansion - * @version Release: 3.2.11 - * @since 1.0 + * @category HTML + * @package HTML_QuickForm + * @author Adam Daniel + * @author Bertrand Mansion + * @version Release: 3.2.11 + * @since 1.0 */ class HTML_QuickForm_submit extends HTML_QuickForm_input { diff --git a/main/inc/lib/pear/HTML/QuickForm/text.php b/main/inc/lib/pear/HTML/QuickForm/text.php index 8a45cd552a..a739198fdb 100755 --- a/main/inc/lib/pear/HTML/QuickForm/text.php +++ b/main/inc/lib/pear/HTML/QuickForm/text.php @@ -22,11 +22,6 @@ * @link http://pear.php.net/package/HTML_QuickForm */ -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/input.php'; - /** * HTML class for a text field * diff --git a/main/inc/lib/pear/HTML/QuickForm/xbutton.php b/main/inc/lib/pear/HTML/QuickForm/xbutton.php index 9f30af556b..343d0dbe42 100755 --- a/main/inc/lib/pear/HTML/QuickForm/xbutton.php +++ b/main/inc/lib/pear/HTML/QuickForm/xbutton.php @@ -1,39 +1,34 @@ element - * - * PHP versions 4 and 5 - * - * LICENSE: This source file is subject to version 3.01 of the PHP license - * that is available through the world-wide-web at the following URI: - * http://www.php.net/license/3_01.txt If you did not receive a copy of - * the PHP License and are unable to obtain it through the web, please - * send a note to license@php.net so we can mail you a copy immediately. - * - * @category HTML - * @package HTML_QuickForm - * @author Alexey Borzov - * @copyright 2001-2009 The PHP Group - * @license http://www.php.net/license/3_01.txt PHP License 3.01 - * @version CVS: $Id: xbutton.php,v 1.3 2009/04/04 21:34:04 avb Exp $ - * @link http://pear.php.net/package/HTML_QuickForm - */ - -/** - * Base class for form elements - */ -require_once 'HTML/QuickForm/element.php'; +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Class for HTML 4.0