Update from 1.11.x

pull/3016/head
Julio 6 years ago
parent 9cf881588c
commit a562d1f1ed
  1. 4
      main/admin/add_courses_to_usergroup.php
  2. 5
      main/admin/career_diagram.php
  3. 10
      main/admin/course_category.php
  4. 2
      main/admin/course_edit.php
  5. 2
      main/admin/course_list.php
  6. 8
      main/admin/course_user_import.php
  7. 12
      main/admin/legal_add.php
  8. 3
      main/admin/questions.php
  9. 15
      main/admin/resource_sequence.php
  10. 4
      main/admin/settings.lib.php
  11. 4
      main/admin/subscribe_user2course.php
  12. 2
      main/admin/user_add.php
  13. 2
      main/admin/user_edit.php
  14. 548
      main/admin/user_import.php
  15. 24
      main/admin/user_information.php
  16. 92
      main/admin/user_update_import.php
  17. 6
      main/admin/usergroup_import.php
  18. 17
      main/auth/courses.php
  19. 10
      main/auth/courses_categories.php
  20. 12
      main/auth/gotocourse.php
  21. 17
      main/auth/inscription.php
  22. 9
      main/auth/profile.php
  23. 25
      main/auth/set_temp_password.php
  24. 2
      main/auth/user_mail_confirmation.php
  25. 2
      main/badge/assertion.php
  26. 2
      main/badge/assign.php
  27. 4
      main/badge/class.php
  28. 4
      main/badge/issuer.php
  29. 9
      main/calendar/agenda_list.php
  30. 2
      main/course_description/edit.php
  31. 3
      main/course_description/index.php
  32. 2
      main/course_home/activity.php
  33. 7
      main/course_home/course_home.php
  34. 5
      main/coursecopy/import_moodle.php
  35. 2
      main/document/add_link.php
  36. 11
      main/document/create_audio.php
  37. 2
      main/document/create_document.php
  38. 2
      main/document/document_slideshow.inc.php
  39. 1
      main/document/downloadfolder.inc.php
  40. 2
      main/document/edit_document.php
  41. 10
      main/document/edit_odf.php
  42. 74
      main/document/showinframes.php
  43. 10
      main/dropbox/index.php
  44. 4
      main/exercise/Hpdownload.php
  45. 2
      main/exercise/MatchingDraggable.php
  46. 2
      main/exercise/MultipleAnswerTrueFalseDegreeCertainty.php
  47. 2
      main/exercise/TestCategory.php
  48. 9
      main/exercise/admin.php
  49. 401
      main/exercise/exercise.class.php
  50. 53
      main/exercise/exercise.php
  51. 12
      main/exercise/exercise_admin.php
  52. 6
      main/exercise/exercise_report.php
  53. 61
      main/exercise/exercise_show.php
  54. 80
      main/exercise/exercise_submit.php
  55. 42
      main/exercise/exercise_submit_modal.php
  56. 2
      main/exercise/export/aiken/aiken_import.inc.php
  57. 6
      main/exercise/fill_blanks.class.php
  58. 14
      main/exercise/hotspot_admin.inc.php
  59. 1
      main/exercise/matching.class.php
  60. 32
      main/exercise/overview.php
  61. 14
      main/exercise/question.class.php
  62. 14
      main/exercise/question_admin.inc.php
  63. 12
      main/exercise/question_list_admin.inc.php
  64. 34
      main/exercise/question_pool.php
  65. 8
      main/exercise/result.php
  66. 10
      main/exercise/tests_category.php
  67. 3
      main/exercise/upload_exercise.php
  68. 1
      main/extra/group_space_tracking.php
  69. 8
      main/extra/upgrade_school_calendar.php
  70. 2
      main/forum/download.php
  71. 2
      main/forum/editthread.php
  72. 115
      main/forum/forumfunction.inc.php
  73. 1
      main/forum/index.php
  74. 1
      main/forum/reply.php
  75. 2
      main/forum/viewforumcategory.php
  76. 154
      main/forum/viewthread.php
  77. 66
      main/glossary/index.php
  78. 4
      main/gradebook/gradebook_add_cat.php
  79. 4
      main/gradebook/gradebook_add_eval.php
  80. 6
      main/gradebook/gradebook_add_link.php
  81. 2
      main/gradebook/gradebook_edit_all.php
  82. 2
      main/gradebook/gradebook_edit_cat.php
  83. 2
      main/gradebook/gradebook_edit_eval.php
  84. 2
      main/gradebook/gradebook_edit_link.php
  85. 7
      main/gradebook/gradebook_statistics.php
  86. 7
      main/gradebook/gradebook_view_result.php
  87. 24
      main/gradebook/index.php
  88. 2
      main/gradebook/my_certificates.php
  89. 2
      main/group/group_category.php
  90. 112
      main/group/group_creation.php
  91. 3
      main/group/group_space.php
  92. 3
      main/group/import.php
  93. 4
      main/group/settings.php
  94. 105
      main/inc/ajax/chat.ajax.php
  95. 1
      main/inc/ajax/course_chat.ajax.php
  96. 6
      main/inc/ajax/course_home.ajax.php
  97. 111
      main/inc/ajax/extra_field.ajax.php
  98. 76
      main/inc/ajax/lang.ajax.php
  99. 29
      main/inc/ajax/mail.ajax.php
  100. 35
      main/inc/ajax/model.ajax.php
  101. Some files were not shown because too many files have changed in this diff Show More

@ -21,7 +21,7 @@ $xajax->registerFunction('search');
// Setting the section (for the tabs).
$this_section = SECTION_PLATFORM_ADMIN;
// Access restrictions.
// Setting breadcrumbs.
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
$interbreadcrumb[] = ['url' => 'usergroups.php', 'name' => get_lang('Classes')];
@ -137,7 +137,7 @@ if (!empty($course_list)) {
$ajax_search = $add_type == 'unique' ? true : false;
//checking for extra field with filter on
// checking for extra field with filter on
function search($needle, $type)
{
global $elements_in;

@ -1,6 +1,8 @@
<?php
/* For licensing terms, see /license.txt */
use Fhaculty\Graph\Graph;
/**
* @package chamilo.admin
*/
@ -106,7 +108,8 @@ if (!empty($itemUrls) && !empty($itemUrls['value'])) {
$tpl = new Template(get_lang('Diagram'));
$html = Display::page_subheader2($careerInfo['name'].$urlToString);
if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
$graph = unserialize($item['value']);
/** @var Graph $graph */
$graph = UnserializeApi::unserialize('career', $item['value']);
$html .= Career::renderDiagramByColumn($graph, $tpl);
} else {
Display::addFlash(

@ -92,7 +92,7 @@ $urlId = api_get_current_access_url_id();
if ($action == 'add' || $action == 'edit') {
echo '<div class="actions">';
echo Display::url(
Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM),
Display::return_icon('folder_up.png', get_lang('Back'), '', ICON_SIZE_MEDIUM),
api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.Security::remove_XSS($category)
);
echo '</div>';
@ -125,7 +125,7 @@ if ($action == 'add' || $action == 'edit') {
$form->createElement(
'radio',
'auth_course_child',
get_lang("AllowCoursesInCategory"),
get_lang('AllowCoursesInCategory'),
get_lang('Yes'),
'TRUE'
),
@ -137,7 +137,7 @@ if ($action == 'add' || $action == 'edit') {
'FALSE'
),
];
$form->addGroup($group, null, get_lang("AllowCoursesInCategory"));
$form->addGroup($group, null, get_lang('AllowCoursesInCategory'));
if ($myCourseListAsCategory) {
$form->addHtmlEditor(
@ -165,12 +165,12 @@ if ($action == 'add' || $action == 'edit') {
}
if (!empty($categoryInfo)) {
$class = "save";
$class = 'save';
$text = get_lang('Save');
$form->setDefaults($categoryInfo);
$form->addButtonSave($text);
} else {
$class = "add";
$class = 'add';
$text = get_lang('AddCategory');
$form->setDefaults(['auth_course_child' => 'TRUE']);
$form->addButtonCreate($text);

@ -291,6 +291,8 @@ $extra = $extra_field->addElements(
false,
[],
[],
[],
false,
true
);

@ -196,7 +196,7 @@ function get_course_data($from, $number_of_items, $column, $direction)
Display::return_icon('edit.png', get_lang('Edit'), [], ICON_SIZE_SMALL).'</a>&nbsp;'.
'<a href="'.$path.'coursecopy/create_backup.php?'.api_get_cidreq_params($courseCode).'">'.
Display::return_icon('backup.png', get_lang('CreateBackup')).'</a>&nbsp;'.
'<a href="'.$path.'admin/course_list.php?delete_course='.$courseCode.'" title="'.addslashes(api_htmlentities(get_lang('ConfirmYourChoice'))).'" class="delete-swal">'.
'<a href="'.$path.'admin/course_list.php?delete_course='.$courseCode.'" onclick="javascript: if (!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES))."'".')) return false;">'.
Display::return_icon('delete.png', get_lang('Delete'), [], ICON_SIZE_SMALL).'</a>';
$courseItem = [

@ -107,10 +107,10 @@ function save_data($users_courses)
$courseInfo = $courseListById[$courseId];
$courseCode = $courseInfo['code'];
$result = CourseManager::subscribeUser(
$user_id,
$courseCode,
$csv_subscriptions[$courseId]
);
$user_id,
$courseCode,
$csv_subscriptions[$courseId]
);
if ($result) {
$inserted_in_course[$courseInfo['code']] = $courseInfo['title'];
}

@ -29,6 +29,7 @@ $term_preview = [
$extraField = new ExtraField('terms_and_condition');
$types = LegalManager::getTreatmentTypeList();
foreach ($types as $variable => $name) {
$label = 'PersonalData'.ucfirst($name).'Title';
$params = [
@ -50,7 +51,7 @@ if ($form->validate()) {
if ($check) {
$values = $form->getSubmitValues();
$lang = $values['language'];
//language id
// language id
$lang = api_get_language_id($lang);
$type = 0;
if (isset($values['type'])) {
@ -151,6 +152,15 @@ if (isset($_POST['language'])) {
false,
[],
[],
[],
false,
true,
[],
[],
false,
[],
[],
false,
true
);

@ -1,4 +1,3 @@
<?php
/* For licensing terms, see /license.txt */
@ -36,7 +35,7 @@ if ($formSent) {
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : '';
$description = isset($_REQUEST['description']) ? Security::remove_XSS($_REQUEST['description']) : '';
$title = isset($_REQUEST['title']) ? Security::remove_XSS($_REQUEST['title']) : '';
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$page = isset($_GET['page']) && !empty($_GET['page']) ? (int) $_GET['page'] : 1;
$em = Database::getManager();
$repo = $em->getRepository('ChamiloCourseBundle:CQuizQuestion');

@ -45,15 +45,16 @@ $em = Database::getManager();
$sequenceList = $em->getRepository('ChamiloCoreBundle:Sequence')->findAll();
$selectSequence->addSelect(
$slcSequences = $selectSequence->addSelect(
'sequence',
get_lang('Sequence'),
$sequenceList,
['id' => 'sequence_id', 'cols-size' => [3, 7, 2]]
['id' => 'sequence_id', 'cols-size' => [3, 7, 2], 'disabled' => 'disabled']
);
if (!empty($sequenceList)) {
$selectSequence->addButtonDelete(get_lang('Delete'));
$slcSequences->removeAttribute('disabled');
}
if ($selectSequence->validate()) {
@ -83,19 +84,19 @@ $form->addSelect(
'sessions',
get_lang('Sessions'),
$sessionList,
['id' => 'item', 'cols-size' => [4, 7, 1]]
['id' => 'item', 'cols-size' => [4, 7, 1], 'disabled' => 'disabled']
);
$form->addButtonNext(get_lang('UseAsReference'), 'use_as_reference', ['cols-size' => [4, 7, 1]]);
$form->addButtonNext(get_lang('UseAsReference'), 'use_as_reference', ['cols-size' => [4, 7, 1], 'disabled' => 'disabled']);
$form->addHtml("</div>");
$form->addHtml("<div class='col-md-6'>");
$form->addSelect(
'requirements',
get_lang('Requirements'),
$sessionList,
['id' => 'requirements', 'cols-size' => [3, 7, 2]]
['id' => 'requirements', 'cols-size' => [3, 7, 2], 'disabled' => 'disabled']
);
$form->addButtonCreate(get_lang('SetAsRequirement'), 'set_requirement', false, ['cols-size' => [3, 7, 2]]);
$form->addButtonCreate(get_lang('SetAsRequirement'), 'set_requirement', false, ['cols-size' => [3, 7, 2], 'disabled' => 'disabled']);
$form->addHtml("</div>");
$formSave = new FormValidator('');
@ -107,7 +108,7 @@ $formSave->addButton(
'success',
null,
null,
['cols-size' => [1, 10, 1]]
['cols-size' => [1, 10, 1], 'disabled' => 'disabled']
);
$tpl->assign('create_sequence', $formSequence->returnForm());

@ -151,7 +151,7 @@ function handlePlugins()
// Plugins NOT installed
echo Display::page_subheader(get_lang('Plugins'));
echo '<form class="form-horizontal" name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'&sec_token='.$token.'">';
echo '<table class="table table-hover">';
echo '<table class="table table-hover table-striped table-bordered">';
echo '<tr>';
echo '<th width="20px">';
echo get_lang('Action');
@ -1496,7 +1496,7 @@ function generateSettingsForm($settings, $settings_by_access_list)
// Conversion of the textfield to a select box with valid values.
$default_values[$row['variable']] = $row['selected_value'];
} elseif ($row['variable'] == 'platform_charset') {
continue;
break;
} else {
$hideme['class'] = 'col-md-4';
$hideme['aria-label'] = get_lang($row['title']);

@ -54,7 +54,7 @@ $extra_field_list = UserManager::get_extra_fields();
$new_field_list = [];
if (is_array($extra_field_list)) {
foreach ($extra_field_list as $extra_field) {
//if is enabled to filter and is a "<select>" field type
// if is enabled to filter and is a "<select>" field type
if ($extra_field[8] == 1 && $extra_field[2] == ExtraField::FIELD_TYPE_SELECT) {
$new_field_list[] = [
'name' => $extra_field[3],
@ -304,7 +304,7 @@ if (is_array($extra_field_list)) {
<b><?php echo get_lang('CourseList'); ?> :</b>
<br/><br/>
<?php echo get_lang('FirstLetterCourse'); ?> :
<select name="firstLetterCourse"
<select name="firstLetterCourse"
onchange="javascript:document.formulaire.form_sent.value='2'; document.formulaire.submit();"
aria-label="<?php echo get_lang('FirstLetterCourse'); ?>">
<option value="">--</option>

@ -303,6 +303,8 @@ $returnParams = $extraField->addElements(
false,
[],
[],
[],
false,
true
);

@ -320,6 +320,8 @@ $returnParams = $extraField->addElements(
false,
[],
[],
[],
false,
true
);
$jqueryReadyContent = $returnParams['jquery_ready_content'];

@ -1,5 +1,8 @@
<?php
/* For licensing terms, see /license.txt */
use ChamiloSession as Session;
/**
* This tool allows platform admins to add users by uploading a CSV or XML file.
*
@ -10,6 +13,7 @@ require_once __DIR__.'/../inc/global.inc.php';
// Set this option to true to enforce strict purification for usenames.
$purification_option_for_usernames = false;
$userId = api_get_user_id();
/**
* @param array $users
@ -20,7 +24,6 @@ $purification_option_for_usernames = false;
function validate_data($users, $checkUniqueEmail = false)
{
global $defined_auth_sources;
$errors = [];
$usernames = [];
// 1. Check if mandatory fields are set.
@ -31,38 +34,49 @@ function validate_data($users, $checkUniqueEmail = false)
$classExistList = [];
$usergroup = new UserGroup();
foreach ($users as &$user) {
$user['has_error'] = false;
$user['message'] = '';
foreach ($users as $user) {
foreach ($mandatory_fields as $field) {
if (empty($user[$field])) {
$user['error'] = get_lang($field.'Mandatory');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang($field.'Mandatory'), 'warning');
$user['has_error'] = true;
}
}
$username = $user['UserName'];
$username = isset($user['UserName']) ? $user['UserName'] : '';
// 2. Check username, first, check whether it is empty.
if (!UserManager::is_username_empty($username)) {
// 2.1. Check whether username is too long.
if (UserManager::is_username_too_long($username)) {
$user['error'] = get_lang('UserNameTooLong');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('UserNameTooLong'), 'warning');
$user['has_error'] = true;
}
// 2.1.1
$hasDash = strpos($username, '-');
if ($hasDash !== false) {
$user['error'] = get_lang('UserNameHasDash');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('UserNameHasDash'), 'warning');
$user['has_error'] = true;
}
// 2.2. Check whether the username was used twice in import file.
if (isset($usernames[$username])) {
$user['error'] = get_lang('UserNameUsedTwice');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('UserNameUsedTwice'), 'warning');
$user['has_error'] = true;
}
$usernames[$username] = 1;
// 2.3. Check whether username is already occupied.
if (!UserManager::is_username_available($username)) {
$user['error'] = get_lang('UserNameNotAvailable');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('UserNameNotAvailable'), 'warning');
$user['has_error'] = true;
}
}
if (isset($user['Email'])) {
$result = api_valid_email($user['Email']);
if ($result === false) {
$user['message'] .= Display::return_message(get_lang('PleaseEnterValidEmail'), 'warning');
$user['has_error'] = true;
}
}
@ -70,16 +84,16 @@ function validate_data($users, $checkUniqueEmail = false)
if (isset($user['Email'])) {
$userFromEmail = api_get_user_info_from_email($user['Email']);
if (!empty($userFromEmail)) {
$user['error'] = get_lang('EmailUsedTwice');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('EmailUsedTwice'), 'warning');
$user['has_error'] = true;
}
}
}
// 3. Check status.
if (isset($user['Status']) && !api_status_exists($user['Status'])) {
$user['error'] = get_lang('WrongStatus');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('WrongStatus'), 'warning');
$user['has_error'] = true;
}
// 4. Check ClassId
@ -91,8 +105,11 @@ function validate_data($users, $checkUniqueEmail = false)
}
$info = $usergroup->get($id);
if (empty($info)) {
$user['error'] = sprintf(get_lang('ClassIdDoesntExists'), $id);
$errors[] = $user;
$user['message'] .= Display::return_message(
sprintf(get_lang('ClassIdDoesntExists'), $id),
'warning'
);
$user['has_error'] = true;
} else {
$classExistList[] = $info['id'];
}
@ -102,24 +119,28 @@ function validate_data($users, $checkUniqueEmail = false)
// 5. Check authentication source
if (!empty($user['AuthSource'])) {
if (!in_array($user['AuthSource'], $defined_auth_sources)) {
$user['error'] = get_lang('AuthSourceNotAvailable');
$errors[] = $user;
$user['message'] .= Display::return_message(get_lang('AuthSourceNotAvailable'), 'warning');
$user['has_error'] = true;
}
}
}
return $errors;
return $users;
}
/**
* Add missing user-information (which isn't required, like password, username etc).
*
* @param array $user
*/
function complete_missing_data($user)
{
global $purification_option_for_usernames;
$username = isset($user['UserName']) ? $user['UserName'] : '';
// 1. Create a username if necessary.
if (UserManager::is_username_empty($user['UserName'])) {
if (UserManager::is_username_empty($username)) {
$user['UserName'] = UserManager::create_unique_username(
$user['FirstName'],
$user['LastName']
@ -170,23 +191,27 @@ function complete_missing_data($user)
/**
* Save the imported data.
*
* @param array $users List of users
* @param array $users List of users
* @param bool $sendMail
*
* @uses \global variable $inserted_in_course, which returns the list of
* courses the user was inserted in
*/
function save_data($users)
function save_data($users, $sendMail = false)
{
global $inserted_in_course;
// Not all scripts declare the $inserted_in_course array (although they should).
if (!isset($inserted_in_course)) {
$inserted_in_course = [];
}
$usergroup = new UserGroup();
$send_mail = $_POST['sendMail'] ? true : false;
$usergroup = new UserGroup();
if (is_array($users)) {
foreach ($users as $user) {
foreach ($users as &$user) {
if ($user['has_error']) {
continue;
}
$user = complete_missing_data($user);
$user['Status'] = api_status_key($user['Status']);
$user_id = UserManager::create_user(
@ -206,67 +231,77 @@ function save_data($users)
0,
null,
null,
$send_mail
$sendMail
);
if (isset($user['Courses']) && is_array($user['Courses'])) {
foreach ($user['Courses'] as $course) {
if (CourseManager::course_exists($course)) {
$result = CourseManager::subscribeUser($user_id, $course, $user['Status']);
if ($result) {
$course_info = api_get_course_info($course);
$inserted_in_course[$course] = $course_info['title'];
if ($user_id) {
$returnMessage = Display::return_message(get_lang('UserAdded'), 'success');
if (isset($user['Courses']) && is_array($user['Courses'])) {
foreach ($user['Courses'] as $course) {
if (CourseManager::course_exists($course)) {
$result = CourseManager::subscribeUser($user_id, $course, $user['Status']);
if ($result) {
$course_info = api_get_course_info($course);
$inserted_in_course[$course] = $course_info['title'];
}
}
}
}
}
if (isset($user['Sessions']) && is_array($user['Sessions'])) {
foreach ($user['Sessions'] as $sessionId) {
$sessionInfo = api_get_session_info($sessionId);
if (!empty($sessionInfo)) {
SessionManager::subscribeUsersToSession(
$sessionId,
[$user_id],
SESSION_VISIBLE_READ_ONLY,
false
);
if (isset($user['Sessions']) && is_array($user['Sessions'])) {
foreach ($user['Sessions'] as $sessionId) {
$sessionInfo = api_get_session_info($sessionId);
if (!empty($sessionInfo)) {
SessionManager::subscribeUsersToSession(
$sessionId,
[$user_id],
SESSION_VISIBLE_READ_ONLY,
false
);
}
}
}
}
if (!empty($user['ClassId'])) {
$classId = explode('|', trim($user['ClassId']));
foreach ($classId as $id) {
$usergroup->subscribe_users_to_usergroup($id, [$user_id], false);
if (!empty($user['ClassId'])) {
$classId = explode('|', trim($user['ClassId']));
foreach ($classId as $id) {
$usergroup->subscribe_users_to_usergroup($id, [$user_id], false);
}
}
}
// Saving extra fields.
global $extra_fields;
// We are sure that the extra field exists.
foreach ($extra_fields as $extras) {
if (isset($user[$extras[1]])) {
$key = $extras[1];
$value = $user[$extras[1]];
UserManager::update_extra_field_value($user_id, $key, $value);
// Saving extra fields.
global $extra_fields;
// We are sure that the extra field exists.
foreach ($extra_fields as $extras) {
if (isset($user[$extras[1]])) {
$key = $extras[1];
$value = $user[$extras[1]];
UserManager::update_extra_field_value($user_id, $key, $value);
}
}
} else {
$returnMessage = Display::return_message(get_lang('Error'), 'warning');
}
$user['message'] = $returnMessage;
}
}
return $users;
}
/**
* Read the CSV-file.
* @param array $users
* @param string $fileName
* @param int $sendEmail
* @param bool $checkUniqueEmail
* @param bool $resumeImport
*
* @param string $file Path to the CSV-file
*
* @return array All userinformation read from the file
* @return array
*/
function parse_csv_data($file)
function parse_csv_data($users, $fileName, $sendEmail = 0, $checkUniqueEmail = true, $resumeImport = false)
{
$users = Import::csvToArray($file);
$usersFromOrigin = $users;
$allowRandom = api_get_configuration_value('generate_random_login');
if ($allowRandom) {
$factory = new RandomLib\Factory();
@ -274,8 +309,33 @@ function parse_csv_data($file)
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
$readMax = 50;
$userId = api_get_user_id();
$logMessages = '';
$importData = Session::read('user_import_data_'.$userId);
if (!empty($importData)) {
$counter = $importData['counter'];
$users = $importData['complete_list'];
$users = array_splice($users, $counter, $readMax);
$logMessages = $importData['log_messages'];
} else {
$users = array_splice($users, 0, $readMax);
}
if ($resumeImport === false) {
$users = $usersFromOrigin;
}
$counter = 0;
foreach ($users as $index => $user) {
if (isset($user['UserName'])) {
if ($resumeImport) {
if ($counter >= $readMax) {
$users = array_splice($users, $counter, $readMax);
break;
}
}
$counter++;
if (empty($user['UserName'])) {
if ($allowRandom) {
$username = $generator->generateString(10, $chars);
$user['UserName'] = $username;
@ -304,93 +364,111 @@ function parse_csv_data($file)
$users[$index] = $user;
}
return $users;
}
/**
* XML-parser: handle start of element.
*
* @param string $parser Deprecated?
* @param string $data The data to be parsed
*/
function element_start($parser, $data)
{
$data = api_utf8_decode($data);
global $user;
global $current_tag;
switch ($data) {
case 'Contact':
$user = [];
break;
default:
$current_tag = $data;
$globalCounter = $counter;
if (!empty($importData)) {
$globalCounter = $importData['counter'] + $counter;
}
$importData = [
'complete_list' => $usersFromOrigin,
'filename' => $fileName,
'counter' => $globalCounter,
'check_unique_email' => $checkUniqueEmail,
'send_email' => $sendEmail,
'date' => api_get_utc_datetime(),
'log_messages' => $logMessages,
'resume' => $resumeImport,
];
Session::write('user_import_data_'.$userId, $importData);
return $users;
}
/**
* XML-parser: handle end of element.
* Read the XML-file.
*
* @param string $file Path to the XML-file
*
* @param string $parser Deprecated?
* @param string $data The data to be parsed
* @return array All user information read from the file
*/
function element_end($parser, $data)
function parse_xml_data($file)
{
$data = api_utf8_decode($data);
global $user;
global $users;
global $current_value;
switch ($data) {
case 'Contact':
if ($user['Status'] == '5') {
$user['Status'] = STUDENT;
}
if ($user['Status'] == '1') {
$user['Status'] = COURSEMANAGER;
$crawler = new \Symfony\Component\DomCrawler\Crawler();
$crawler->addXmlContent(file_get_contents($file));
$crawler = $crawler->filter('Contacts > Contact ');
$array = [];
foreach ($crawler as $domElement) {
$row = [];
foreach ($domElement->childNodes as $node) {
if ($node->nodeName != '#text') {
$row[$node->nodeName] = $node->nodeValue;
}
$users[] = $user;
break;
default:
$user[$data] = $current_value;
break;
}
if (!empty($row)) {
$array[] = $row;
}
}
}
/**
* XML-parser: handle character data.
*
* @param string $parser Parser (deprecated?)
* @param string $data The data to be parsed
*/
function character_data($parser, $data)
{
$data = trim(api_utf8_decode($data));
global $current_value;
$current_value = $data;
return $array;
}
/**
* Read the XML-file.
*
* @param string $file Path to the XML-file
*
* @return array All user information read from the file
* @param array $users
* @param bool $sendMail
*/
function parse_xml_data($file)
function processUsers(&$users, $sendMail)
{
global $users;
$users = [];
$parser = xml_parser_create('UTF-8');
xml_set_element_handler($parser, 'element_start', 'element_end');
xml_set_character_data_handler($parser, 'character_data');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
xml_parser_free($parser);
$users = save_data($users, $sendMail);
$warningMessage = '';
if (!empty($users)) {
$table = new HTML_Table(['class' => 'table table-responsive']);
$headers = [
get_lang('User'),
get_lang('Status'),
];
$row = 0;
$column = 0;
foreach ($headers as $header) {
$table->setHeaderContents($row, $column, $header);
$column++;
}
$row++;
foreach ($users as $user) {
$column = 0;
$email = isset($user['Email']) ? ' - '.$user['Email'] : null;
$userData =
'<strong>'.$user['UserName'].'</strong> - '.
api_get_person_name(
$user['FirstName'],
$user['LastName']
).' '.$email;
$table->setCellContents($row, $column, $userData);
$table->setCellContents($row, ++$column, $user['message']);
$row++;
}
$warningMessage = $table->toHtml();
}
return $users;
// if the warning message is too long then we display the warning message trough a session
Display::addFlash(Display::return_message(get_lang('FileImported'), 'confirmation', false));
$importData = Session::read('user_import_data_'.api_get_user_id());
if (!empty($importData)) {
if (isset($importData['log_messages'])) {
$importData['log_messages'] .= $warningMessage;
} else {
$importData['log_messages'] = $warningMessage;
}
Session::write('user_import_data_'.api_get_user_id(), $importData);
}
}
$this_section = SECTION_PLATFORM_ADMIN;
api_protect_admin_script(true, null);
api_protect_limit_for_session_admin();
set_time_limit(0);
$defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
@ -399,111 +477,147 @@ if (isset($extAuthSource) && is_array($extAuthSource)) {
}
$tool_name = get_lang('ImportUserListXMLCSV');
$interbreadcrumb[] = ["url" => 'index.php', "name" => get_lang('PlatformAdmin')];
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
$reloadImport = (isset($_REQUEST['reload_import']) && (int) $_REQUEST['reload_import'] === 1);
set_time_limit(0);
$extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
$user_id_error = [];
$error_message = '';
if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['size'] !== 0) {
$file_type = $_POST['file_type'];
Security::clear_token();
$tok = Security::get_token();
$allowed_file_mimetype = ['csv', 'xml'];
$error_kind_file = false;
$error_kind_file = true;
$checkUniqueEmail = isset($_POST['check_unique_email']) ? $_POST['check_unique_email'] : null;
$sendMail = $_POST['sendMail'] ? true : false;
$resume = isset($_POST['resume_import']) ? true : false;
$uploadInfo = pathinfo($_FILES['import_file']['name']);
$ext_import_file = $uploadInfo['extension'];
$users = [];
if (in_array($ext_import_file, $allowed_file_mimetype)) {
if (strcmp($file_type, 'csv') === 0 &&
$ext_import_file == $allowed_file_mimetype[0]
) {
$users = parse_csv_data($_FILES['import_file']['tmp_name']);
$errors = validate_data($users, $checkUniqueEmail);
Session::erase('user_import_data_'.$userId);
$users = Import::csvToArray($_FILES['import_file']['tmp_name']);
$users = parse_csv_data(
$users,
$_FILES['import_file']['name'],
$sendMail,
$checkUniqueEmail,
$resume
);
$users = validate_data($users, $checkUniqueEmail);
$error_kind_file = false;
} elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
$users = parse_xml_data($_FILES['import_file']['tmp_name']);
$errors = validate_data($users, $checkUniqueEmail);
$users = validate_data($users, $checkUniqueEmail);
$error_kind_file = false;
}
processUsers($users, $sendMail);
if ($error_kind_file) {
Display::addFlash(
Display::return_message(
get_lang('YouMustImportAFileAccordingToSelectedOption'),
'error',
false
)
);
} else {
$error_kind_file = true;
$reload = '';
if ($resume) {
$reload = '?reload_import=1';
}
header('Location: '.api_get_self().$reload);
exit;
}
} else {
$error_kind_file = true;
Display::addFlash(
Display::return_message(
get_lang('YouMustImportAFileAccordingToSelectedOption'),
'error',
false
)
);
//header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
header('Location: '.api_get_self());
exit;
}
}
// List user id with error.
$users_to_insert = [];
$importData = Session::read('user_import_data_'.$userId);
$keyToCheck = 'UserName';
if ($checkUniqueEmail || api_get_setting('registration', 'email') == 'true') {
$keyToCheck = 'Email';
}
$formContinue = false;
$resumeStop = true;
if (!empty($importData)) {
$isResume = $importData['resume'];
if (is_array($errors)) {
foreach ($errors as $my_errors) {
$user_id_error[] = $my_errors[$keyToCheck];
}
$formContinue = new FormValidator('user_import_continue', 'post', api_get_self());
$label = get_lang('Results');
if ($isResume) {
$label = get_lang('ContinueLastImport');
}
if (is_array($users)) {
foreach ($users as $my_user) {
if (!in_array($my_user[$keyToCheck], $user_id_error)) {
$users_to_insert[] = $my_user;
}
$formContinue->addHeader($label);
$formContinue->addLabel(get_lang('File'), $importData['filename']);
$resumeStop = true;
if ($isResume) {
$totalUsers = isset($importData['complete_list']) ? count($importData['complete_list']) : 0;
$counter = isset($importData['counter']) ? $importData['counter'] : 0;
$bar = '';
if (!empty($totalUsers)) {
$bar = Display::bar_progress($counter / $totalUsers * 100);
}
}
$inserted_in_course = [];
if (strcmp($file_type, 'csv') === 0) {
save_data($users_to_insert);
} elseif (strcmp($file_type, 'xml') === 0) {
save_data($users_to_insert);
} else {
$error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
}
if (count($errors) > 0) {
$see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
$formContinue->addLabel(get_lang('Status'), $bar);
$formContinue->addLabel(
get_lang('UsersAdded'),
$importData['counter'].' / '.count($importData['complete_list'])
);
} else {
$see_message_import = get_lang('FileImported');
$formContinue->addLabel(
get_lang('Users'),
count($importData['complete_list'])
);
}
$warning_message = '';
if (count($errors) != 0) {
$warning_message = '<ul>';
foreach ($errors as $index => $error_user) {
$email = isset($error_user['Email']) ? ' - '.$error_user['Email'] : null;
$warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
$warning_message .=
'<strong>'.$error_user['UserName'].'</strong> - '.
api_get_person_name(
$error_user['FirstName'],
$error_user['LastName']
).' '.$email;
$warning_message .= '</li>';
$formContinue->addLabel(
get_lang('CheckUniqueEmail'),
$importData['check_unique_email'] ? get_lang('Yes') : get_lang('No')
);
$formContinue->addLabel(get_lang('SendMailToUsers'), $importData['send_email'] ? get_lang('Yes') : get_lang('No'));
$formContinue->addLabel(get_lang('Date'), Display::dateToStringAgoAndLongDate($importData['date']));
if ($isResume) {
$resumeStop = $importData['counter'] >= count($importData['complete_list']);
if ($resumeStop == false) {
$formContinue->addButtonImport(get_lang('ContinueImport'), 'import_continue');
}
$warning_message .= '</ul>';
}
// if the warning message is too long then we display the warning message trough a session
Display::addFlash(Display::return_message($warning_message, 'warning', false));
Display::addFlash(Display::return_message($see_message_import, 'confirmation', false));
$formContinue->addHtml(get_lang('Results').'<br />'.$importData['log_messages']);
if ($error_kind_file) {
Display::addFlash(
Display::return_message(
get_lang('YouMustImportAFileAccordingToSelectedOption'),
'error',
false
)
if ($formContinue->validate()) {
$users = parse_csv_data(
$importData['complete_list'],
$importData['filename'],
$importData['send_email'],
$importData['check_unique_email'],
true
);
} else {
header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
$users = validate_data($users, $importData['check_unique_email']);
processUsers($users, $importData['send_email']);
$reload = '';
if ($isResume && $resumeStop === false) {
$reload = '?reload_import=1';
}
header('Location: '.api_get_self().$reload);
exit;
}
}
@ -511,7 +625,7 @@ if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['s
Display::display_header($tool_name);
$form = new FormValidator('user_import', 'post', api_get_self());
$form->addElement('header', '', $tool_name);
$form->addHeader($tool_name);
$form->addElement('hidden', 'formSent');
$form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
$group = [
@ -519,14 +633,14 @@ $group = [
'radio',
'file_type',
'',
'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
'CSV (<a href="example.csv" target="_blank" download>'.get_lang('ExampleCSVFile').'</a>)',
'csv'
),
$form->createElement(
'radio',
'file_type',
null,
'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)',
'XML (<a href="example.xml" target="_blank" download>'.get_lang('ExampleXMLFile').'</a>)',
'xml'
),
];
@ -546,7 +660,15 @@ $form->addElement(
get_lang('CheckUniqueEmail')
);
$form->addElement(
'checkbox',
'resume_import',
'',
get_lang('ResumeImport')
);
$form->addButtonImport(get_lang('Import'));
$defaults['formSent'] = 1;
$defaults['sendMail'] = 0;
$defaults['file_type'] = 'csv';
@ -561,6 +683,22 @@ if (!empty($extraSettings) && isset($extraSettings['options']) &&
$form->setDefaults($defaults);
$form->display();
if ($formContinue) {
$formContinue->display();
}
if ($reloadImport) {
echo '<script>
$(function() {
function reload() {
$("#user_import_continue").submit();
}
setTimeout(reload, 3000);
});
</script>';
}
$list = [];
$list_reponse = [];
$result_xml = '';

@ -17,10 +17,12 @@ $this_section = SECTION_PLATFORM_ADMIN;
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
if (!isset($_GET['user_id'])) {
$userId = isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0;
if (empty($userId)) {
api_not_allowed(true);
}
$user = api_get_user_info($_GET['user_id'], true);
$user = api_get_user_info($userId, true);
if (empty($user)) {
api_not_allowed(true);
@ -39,8 +41,8 @@ if (!api_is_student_boss()) {
}
}
$interbreadcrumb[] = ["url" => 'index.php', "name" => get_lang('PlatformAdmin')];
$interbreadcrumb[] = ["url" => 'user_list.php', "name" => get_lang('UserList')];
$interbreadcrumb[] = ["url" => 'index.php', 'name' => get_lang('PlatformAdmin')];
$interbreadcrumb[] = ["url" => 'user_list.php', 'name' => get_lang('UserList')];
$userId = $user['user_id'];
@ -61,7 +63,7 @@ $actions = [
ICON_SIZE_MEDIUM
),
api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?'.http_build_query([
'student' => intval($_GET['user_id']),
'student' => $userId,
]),
['title' => get_lang('Reporting')]
),
@ -253,10 +255,7 @@ if (api_get_setting('allow_social_tool') === 'true') {
$count = SocialManager::get_message_number_invitation_by_user_id($user['user_id']);
$data[] = [get_lang('InvitationReceived'), $count];
$socialInformation = Display::return_sortable_table(
'',
$data
);
$socialInformation = Display::return_sortable_table('', $data);
}
/**
@ -379,7 +378,7 @@ if (count($sessions) > 0) {
$data,
[],
[],
['user_id' => intval($_GET['user_id'])]
['user_id' => $userId]
);
$sessionInformation .= $courseToolInformationTotal;
}
@ -477,7 +476,7 @@ if (Database::num_rows($res) > 0) {
$data,
[],
[],
['user_id' => intval($_GET['user_id'])]
['user_id' => $userId]
);
$courseInformation .= $courseToolInformationTotal;
} else {
@ -510,7 +509,7 @@ if (api_is_multiple_url_enabled()) {
$data,
[],
[],
['user_id' => intval($_GET['user_id'])]
['user_id' => $userId]
);
} else {
$urlInformation = '<p>'.get_lang('NoUrlForThisUser').'</p>';
@ -561,7 +560,6 @@ if (isset($_GET['action'])) {
exit;
break;
case 'unsubscribe_session_course':
$userId = empty($_GET['user_id']) ? 0 : intval($_GET['user_id']);
$courseId = !empty($_GET['course_id']) ? (int) $_GET['course_id'] : 0;
$sessionId = !empty($_GET['id_session']) ? (int) $_GET['id_session'] : 0;

@ -254,86 +254,26 @@ function parse_csv_data($file)
return $users;
}
/**
* XML-parser: handle start of element.
*
* @param string $parser Deprecated?
* @param string $data The data to be parsed
*/
function element_start($parser, $data)
{
$data = api_utf8_decode($data);
global $user;
global $current_tag;
switch ($data) {
case 'Contact':
$user = [];
break;
default:
$current_tag = $data;
}
}
/**
* XML-parser: handle end of element.
*
* @param string $parser Deprecated?
* @param string $data The data to be parsed
*/
function element_end($parser, $data)
function parse_xml_data($file)
{
$data = api_utf8_decode($data);
global $user;
global $users;
global $current_value;
switch ($data) {
case 'Contact':
if ($user['Status'] == '5') {
$user['Status'] = STUDENT;
}
if ($user['Status'] == '1') {
$user['Status'] = COURSEMANAGER;
$crawler = new \Symfony\Component\DomCrawler\Crawler();
$crawler->addXmlContent(file_get_contents($file));
$crawler = $crawler->filter('Contacts > Contact ');
$array = [];
foreach ($crawler as $domElement) {
$row = [];
foreach ($domElement->childNodes as $node) {
if ($node->nodeName != '#text') {
$row[$node->nodeName] = $node->nodeValue;
}
$users[] = $user;
break;
default:
$user[$data] = $current_value;
break;
}
if (!empty($row)) {
$array[] = $row;
}
}
}
/**
* XML-parser: handle character data.
*
* @param string $parser Parser (deprecated?)
* @param string $data The data to be parsed
*/
function character_data($parser, $data)
{
$data = trim(api_utf8_decode($data));
global $current_value;
$current_value = $data;
}
/**
* Read the XML-file.
*
* @param string $file Path to the XML-file
*
* @return array All user information read from the file
*/
function parse_xml_data($file)
{
global $users;
$users = [];
$parser = xml_parser_create('UTF-8');
xml_set_element_handler($parser, 'element_start', 'element_end');
xml_set_character_data_handler($parser, 'character_data');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
xml_parser_free($parser);
return $users;
return $array;
}
$this_section = SECTION_PLATFORM_ADMIN;
@ -429,7 +369,7 @@ if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['s
exit;
}
}
Display :: display_header($tool_name);
Display::display_header($tool_name);
if (!empty($error_message)) {
echo Display::return_message($error_message, 'error');

@ -84,11 +84,11 @@ $this_section = SECTION_PLATFORM_ADMIN;
$usergroup = new UserGroup();
$usergroup->protectScript();
// Access restrictions.
// setting breadcrumbs
$interbreadcrumb[] = ['url' => 'usergroups.php', 'name' => get_lang('Classes')];
// Database Table Definitions
// Setting the name of the tool.
$tool_name = get_lang('ImportClassListCSV');
set_time_limit(0);
@ -100,7 +100,7 @@ $group[] = $form->createElement(
'radio',
'file_type',
'',
'CSV (<a href="example_class.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
'CSV (<a href="example_class.csv" target="_blank" download>'.get_lang('ExampleCSVFile').'</a>)',
'csv'
);
$form->addGroup($group, '', get_lang('FileType'), null);

@ -29,7 +29,7 @@ if (api_get_setting('course_catalog_published') !== 'true') {
api_block_anonymous_users();
}
//For students
// For students
$user_can_view_page = true;
if (api_get_setting('allow_students_to_browse_courses') === 'false') {
$user_can_view_page = false;
@ -126,7 +126,7 @@ if (isset($_POST['submit_edit_course_category']) &&
}
}
// we are deleting a course category
// We are creating a new user defined course category (= Create Course Category).
if (isset($_POST['create_course_category']) &&
isset($_POST['title_course_category']) &&
strlen(trim($_POST['title_course_category'])) > 0
@ -151,7 +151,7 @@ if (isset($_REQUEST['search_course'])) {
}
}
// Subscribe user to course
// We are unsubscribing from a course (=Unsubscribe from course).
if (isset($_GET['unsubscribe'])) {
if (!empty($_GET['sec_token']) && $ctok == $_GET['sec_token']) {
$courseController->unsubscribe_user_from_course(
@ -235,9 +235,6 @@ switch ($action) {
case 'createcoursecategory':
$courseController->categoryList();
break;
case 'deletecoursecategory':
$courseController->courseList($action);
break;
case 'sortmycourses':
$courseController->courseList($action);
break;
@ -374,6 +371,7 @@ switch ($action) {
$userId = api_get_user_id();
$categoryId = isset($_REQUEST['categoryid']) ? (int) $_REQUEST['categoryid'] : 0;
$option = isset($_REQUEST['option']) ? (int) $_REQUEST['option'] : 0;
$redirect = isset($_REQUEST['redirect']) ? $_REQUEST['redirect'] : 0;
if (empty($userId) || empty($categoryId)) {
api_not_allowed(true);
@ -385,6 +383,13 @@ switch ($action) {
WHERE user_id = $userId AND id = $categoryId";
Database::query($sql);
Display::addFlash(Display::return_message(get_lang('Updated')));
if ($redirect === 'home') {
$url = api_get_path(WEB_PATH).'user_portal.php';
header('Location: '.$url);
exit;
}
$url = api_get_path(WEB_CODE_PATH).'auth/courses.php?action=sortmycourses';
header('Location: '.$url);
exit;

@ -20,19 +20,17 @@ $action = in_array($action, $actions) ? $action : 'display_courses';
$showCourses = CoursesAndSessionsCatalog::showCourses();
$showSessions = CoursesAndSessionsCatalog::showSessions();
$pageCurrent = isset($pageCurrent) ? $pageCurrent : isset($_GET['pageCurrent']) ? intval($_GET['pageCurrent']) : 1;
$pageLength = isset($pageLength) ? $pageLength : isset($_GET['pageLength']) ? intval($_GET['pageLength']) : CoursesAndSessionsCatalog::PAGE_LENGTH;
$pageTotal = intval(ceil(intval($countCoursesInCategory) / $pageLength));
$pageCurrent = isset($pageCurrent) ? $pageCurrent : isset($_GET['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
$pageLength = isset($pageLength) ? $pageLength : isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
$pageTotal = (int) ceil((int) $countCoursesInCategory / $pageLength);
$cataloguePagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($pageCurrent, $pageLength, $pageTotal) : '';
$searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : '';
$codeType = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : '';
$date = date('Y-m-d');
if ($showSessions && isset($_POST['date'])) {
$date = $_POST['date'];
} else {
$date = date('Y-m-d');
}
$userInfo = api_get_user_info();
$code = isset($code) ? $code : null;
$search = null;

@ -51,9 +51,21 @@ if (isset($_GET['firstpage'])) {
$params
);
$form->addButtonNext(get_lang('LoginEnter'), 'submitAuth');
// see same text in main_api.lib.php function api_not_allowed
if (api_is_cas_activated()) {
$msg .= Display::return_message(sprintf(get_lang('YouHaveAnInstitutionalAccount'), api_get_setting("Institution")), '', false);
$msg .= Display::div("<br/><a href='".get_cas_direct_URL(api_get_course_id())."'>".getCASLogoHTML()." ".sprintf(get_lang('LoginWithYourAccount'), api_get_setting("Institution"))."</a><br/><br/>", ['align' => 'center']);
$msg .= Display::return_message(get_lang('YouDontHaveAnInstitutionAccount'));
$msg .= "<p style='text-align:center'><a href='#' onclick='$(this).parent().next().toggle()'>".get_lang('LoginWithExternalAccount')."</a></p>";
$msg .= "<div style='display:none;'>";
}
$msg .= '<div class="well_login">';
$msg .= $form->returnForm();
$msg .= '</div>';
if (api_is_cas_activated()) {
$msg .= "</div>";
}
$msg .= '<hr/><p style="text-align:center"><a href="'.api_get_path(WEB_PATH).'">'.get_lang('ReturnToCourseHomepage').'</a></p>';
$tpl->assign('content', '<h4>'.get_lang('LoginToGoToThisCourse').'</h4>'.$msg);

@ -337,13 +337,28 @@ if ($user_already_registered_show_terms === false &&
if (isset($allowedFields['extra_fields']) && is_array($allowedFields['extra_fields'])) {
$extraFieldList = $allowedFields['extra_fields'];
}
$requiredFields = api_get_configuration_value('required_extra_fields_in_inscription');
if (!empty($requiredFields) && $requiredFields['options']) {
$requiredFields = $requiredFields['options'];
}
$returnParams = $extraField->addElements(
$form,
0,
[],
false,
false,
$extraFieldList
$extraFieldList,
[],
false,
false,
false,
[],
[],
[],
false,
$requiredFields
);
$extraFieldsLoaded = true;
}

@ -16,7 +16,8 @@ $cidReset = true;
require_once __DIR__.'/../inc/global.inc.php';
$this_section = SECTION_MYPROFILE;
if (api_get_setting('allow_social_tool') === 'true') {
$allowSocialTool = api_get_setting('allow_social_tool') == 'true';
if ($allowSocialTool) {
$this_section = SECTION_SOCIAL;
}
@ -25,8 +26,6 @@ $logInfo = [
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => $this_section,
'action_details' => '',
'current_id' => 0,
'info' => '',
];
Event::registerLog($logInfo);
@ -661,6 +660,10 @@ if ($form->validate()) {
Session::write('_user', $userInfo);
if ($hook) {
Database::getManager()->clear(User::class); //Avoid cache issue (user entity is used before)
$user = api_get_user_entity(api_get_user_id()); //Get updated user info for hook event
$hook->setEventData(['user' => $user]);
$hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
}

@ -11,36 +11,37 @@ use ChamiloSession as Session;
$cidReset = true;
require_once __DIR__.'/../inc/global.inc.php';
$this_section = SECTION_COURSES;
$course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : null;
$session_id = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
$user_id = api_get_user_id();
$courseId = isset($_GET['course_id']) ? intval($_GET['course_id']) : null;
$sessionId = isset($_GET['session_id']) ? intval($_GET['session_id']) : null;
$userId = api_get_user_id();
/**
* Security check.
*/
if (empty($course_id)) {
if (empty($courseId)) {
api_not_allowed();
}
$course_info = api_get_course_info_by_id($course_id);
$courseInfo = api_get_course_info_by_id($courseId);
// Build the form
$form = new FormValidator(
'set_temp_password',
'POST',
api_get_self().'?course_id='.$course_id.'&session_id='.$session_id
api_get_self().'?course_id='.$courseId.'&session_id='.$sessionId
);
$form->addElement('header', get_lang('CourseRequiresPassword'));
$form->addElement('hidden', 'course_id', $course_id);
$form->addElement('hidden', 'session_id', $session_id);
$form->addElement('hidden', 'course_id', $courseId);
$form->addElement('hidden', 'session_id', $sessionId);
$form->addElement('password', 'course_password', get_lang('Password'));
$form->addButtonSave(get_lang('Accept'));
if ($form->validate()) {
$form_values = $form->exportValues();
if (sha1($form_values['course_password']) === $course_info['registration_code']) {
Session::write('course_password_'.$course_info['real_id'], true);
header('Location: '.api_get_course_url($course_info['code'], $session_id));
$formValues = $form->exportValues();
if (sha1($formValues['course_password']) === $courseInfo['registration_code']) {
Session::write('course_password_'.$courseInfo['real_id'], true);
header('Location: '.api_get_course_url($courseInfo['code'], $sessionId).
'&action=subscribe&sec_token='.Security::get_existing_token());
exit;
} else {
Display::addFlash(

@ -13,7 +13,7 @@ if (!ctype_alnum($token)) {
$user = UserManager::getManager()->findUserByConfirmationToken($token);
if ($user) {
$user->setActive(1); // Setted 1 to active the user
$user->setActive(1); // Set to 1 to activate the user
$user->setConfirmationToken(null);
Database::getManager()->persist($user);

@ -60,4 +60,6 @@ $json = [
],
];
header('Content-Type: application/json');
echo json_encode($json);

@ -39,7 +39,7 @@ $skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser')
$skillLevels = api_get_configuration_value('skill_levels_names');
$skillsOptions = ['' => get_lang('Select')];
$acquiredLevel = [];
$acquiredLevel = ['' => get_lang('None')];
$formDefaultValues = [];
if (empty($skillLevels)) {

@ -8,8 +8,6 @@
*
* @package chamilo.badge
*/
header('Content-Type: application/json');
require_once __DIR__.'/../inc/global.inc.php';
$skillId = isset($_GET['id']) ? intval($_GET['id']) : 0;
@ -24,4 +22,6 @@ $json = [
'issuer' => api_get_path(WEB_CODE_PATH)."badge/issuer.php",
];
header('Content-Type: application/json');
echo json_encode($json);

@ -10,11 +10,11 @@
*/
require_once __DIR__.'/../inc/global.inc.php';
header('Content-Type: application/json');
$json = [
'name' => api_get_setting('Institution'),
'url' => api_get_path(WEB_PATH),
];
header('Content-Type: application/json');
echo json_encode($json);

@ -13,7 +13,6 @@ $logInfo = [
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => $action,
'info' => '',
];
Event::registerLog($logInfo);
@ -31,12 +30,12 @@ if (!empty($groupId)) {
$groupProperties = GroupManager::get_group_properties($groupId);
$groupId = $groupProperties['iid'];
$interbreadcrumb[] = [
"url" => api_get_path(WEB_CODE_PATH)."group/group.php?".api_get_cidreq(),
"name" => get_lang('Groups'),
'url' => api_get_path(WEB_CODE_PATH)."group/group.php?".api_get_cidreq(),
'name' => get_lang('Groups'),
];
$interbreadcrumb[] = [
"url" => api_get_path(WEB_CODE_PATH)."group/group_space.php?".api_get_cidreq(),
"name" => get_lang('GroupSpace').' '.$groupProperties['name'],
'url' => api_get_path(WEB_CODE_PATH)."group/group_space.php?".api_get_cidreq(),
'name' => get_lang('GroupSpace').' '.$groupProperties['name'],
];
}

@ -98,7 +98,7 @@ $form->addHtmlEditor(
true,
false,
[
'ToolbarSet' => 'Work',
'ToolbarSet' => 'Basic',
'Width' => '100%',
'Height' => '200',
]

@ -19,7 +19,6 @@ define('ADD_BLOCK', 8);
$this_section = SECTION_COURSES;
$action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : 'listing';
// protect a course script
$logInfo = [
'tool' => TOOL_COURSE_DESCRIPTION,
'tool_id' => 0,
@ -29,7 +28,7 @@ $logInfo = [
];
Event::registerLog($logInfo);
// get actions
// protect a course script
api_protect_course_script(true);
$description_type = '';

@ -42,7 +42,7 @@ if ($enabled === 'true') {
$pluginExtra = $plugin->getTeacherLink();
}
// COURSE ADMIN ONLY VIEW
// Start of tools for CourseAdmins (teachers/tutors)
if ($session_id === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
$content .= '<div class="alert alert-success" style="border:0px; margin-top: 0px;padding:0px;">
<div class="normal-message" id="id_normal_message" style="display:none">';

@ -2,6 +2,7 @@
/* For licensing terms, see /license.txt */
use ChamiloSession as Session;
use Fhaculty\Graph\Graph;
/**
* HOME PAGE FOR EACH COURSE.
@ -392,7 +393,11 @@ if ($allow === true) {
);
if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
$graph = unserialize($item['value']);
/** @var Graph $graph */
$graph = UnserializeApi::unserialize(
'career',
$item['value']
);
$diagram = Career::renderDiagram($careerInfo, $graph);
}
}

@ -42,7 +42,10 @@ if ($form->validate()) {
$responseImport = $moodleImport->import($file);
Display::addFlash(
Display::return_message(get_lang('MoodleFileImportedSuccessfully'), 'success')
Display::return_message(
get_lang('MoodleFileImportedSuccessfully'),
'success'
)
);
} catch (Exception $exception) {
Display::addFlash(

@ -175,7 +175,7 @@ echo DocumentManager::build_directory_selector(
// Add tooltip and correctly parse its inner HTML
echo '<script>
$(document).ready(function() {
$(function() {
$("[data-toggle=\'tooltip\']").tooltip({
content:
function() {

@ -76,11 +76,18 @@ if ($dir[strlen($dir) - 1] != '/') {
$dir .= '/';
}
$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
if (!is_dir($filepath)) {
$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
$dir = '/';
}
//groups //TODO: clean
if (!empty($groupId)) {
$interbreadcrumb[] = [
'url' => '../group/group_space.php?'.api_get_cidreq(),
'name' => get_lang('GroupSpace'),
"url" => "../group/group_space.php?".api_get_cidreq(),
"name" => get_lang('GroupSpace'),
];
$group = GroupManager:: get_group_properties($groupId);
$path = explode('/', $dir);

@ -17,7 +17,7 @@ $this_section = SECTION_COURSES;
$groupRights = Session::read('group_member_with_upload_rights');
$htmlHeadXtra[] = '
<script>
$(document).ready(function() {
$(function() {
$(".scrollbar-light").scrollbar();
expandColumnToogle("#hide_bar_template", {

@ -28,7 +28,7 @@
* file into document.php
*/
// Resetting the images of the slideshow = destroying the slideshow
// We check if there are images in this folder by searching the extensions for .jpg, .gif, .png
// grabbing the list of all the documents of this folder
$array_to_search = !empty($documentAndFolders) && is_array($documentAndFolders) ? $documentAndFolders : [];

@ -32,6 +32,7 @@ $documentInfo = DocumentManager::get_document_data_by_id(
if (!empty($sessionId)) {
/* If no data found and session id exists
try to look the file inside the session */
if (empty($documentInfo)) {
$documentInfo = DocumentManager::get_document_data_by_id(
$_GET['id'],

@ -36,7 +36,7 @@ $groupRights = Session::read('group_member_with_upload_rights');
// Template's javascript
$htmlHeadXtra[] = '
<script>
$(document).ready(function() {
$(function() {
$(".scrollbar-light").scrollbar();
expandColumnToogle("#hide_bar_template", {

@ -76,11 +76,11 @@ $htmlHeadXtra[] = api_get_js('wodotexteditor/wodotexteditor.js');
$htmlHeadXtra[] = api_get_js('wodotexteditor/localfileeditor.js');
$htmlHeadXtra[] = api_get_js('wodotexteditor/FileSaver.js');
$htmlHeadXtra[] = '
<script type="text/javascript" charset="utf-8">
$(document).on(\'ready\', function() {
createEditor(\''.$fileUrl.'\');
});
</script>
<script>
$(function() {
createEditor(\''.$fileUrl.'\');
});
</script>
';
$htmlHeadXtra[] = '
<style>

@ -180,7 +180,7 @@ if (in_array(strtolower($pathinfo['extension']), $web_odf_supported_files)) {
var topbarHeight = $("#topbar").height();
$("#viewerJSContent").height((bodyHeight - topbarHeight));
}
$(document).ready(function() {
$(function() {
$(window).resize(resizeIframe());
});
</script>'
@ -246,15 +246,14 @@ if (!$playerSupported && $execute_iframe) {
if ($originIsLearnpath) {
Display::display_reduced_header();
} else {
Display::display_header('');
Display::display_header();
}
echo '<div class="text-center">';
$file_url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document'.$header_file;
$file_url_web = $file_url.'?'.api_get_cidreq();
if ($show_web_odf) {
echo '<div class="text-center">';
$browser = api_get_navigator();
$pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file_url;
if ($browser['name'] == 'Mozilla' && preg_match('|.*\.pdf|i', $header_file)) {
@ -265,12 +264,11 @@ if ($show_web_odf) {
src="'.$pdfUrl.'">
</iframe>';
echo '</div>';
echo '</div>';
}
echo '</div>';
if ($playerSupported) {
echo DocumentManager::generateVideoPreview($file_url_web, $extension);
echo DocumentManager::generateMediaPreview($file_url_web, $extension);
}
if ($execute_iframe) {
@ -278,6 +276,68 @@ if ($execute_iframe) {
$content = Security::remove_XSS(file_get_contents($file_url_sys));
echo $content;
} else {
$parentId = $document_data['parent_id'];
$url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq().'&id='.$parentId;
$actionsLeft = Display::url(
Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM),
$url
);
$groupMemberWithEditRights = false;
$groupId = api_get_group_id();
if (!empty($groupId)) {
$groupInfo = GroupManager::get_group_properties($groupId);
if ($groupInfo) {
$groupMemberWithEditRights = GroupManager::allowUploadEditDocument(
api_get_user_id(),
api_get_course_int_id(),
$groupInfo,
$document_data
);
}
}
$allowToEdit = api_is_allowed_to_edit(null, true) || $groupMemberWithEditRights;
if ($allowToEdit) {
$actionsLeft .= Display::url(
Display::return_icon(
'edit.png',
get_lang('Modify'),
'',
ICON_SIZE_MEDIUM
),
api_get_path(WEB_CODE_PATH).'document/edit_document.php?'.api_get_cidreq().'&id='.$document_id
);
$titleToShow = addslashes(basename($document_data['title']));
$urlDeleteParams = http_build_query(
[
'action' => 'delete_item',
'id' => $parentId,
'deleteid' => $document_data['id'],
]
);
$actionsLeft .= Display::url(
Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_MEDIUM),
'#',
[
'data-item-title' => $titleToShow,
'data-href' => api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq(
).'&'.$urlDeleteParams,
'data-toggle' => 'modal',
'data-target' => '#confirm-delete',
]
);
$actionsLeft .= Display::url(
Display::return_icon('pdf.png', get_lang('Export2PDF'), [], ICON_SIZE_MEDIUM),
api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq(
).'&action=export_to_pdf&id='.$document_id
);
}
echo $toolbar = Display::toolbarAction('actions-documents', [$actionsLeft]);
echo '<iframe
id="mainFrame"
name="mainFrame"

@ -20,6 +20,7 @@ if (isset($_SESSION[$_course['id']]) &&
}
$postAction = isset($_POST['action']) ? $_POST['action'] : null;
$action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
$view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null;
$viewReceivedCategory = isset($_GET['view_received_category']) ? Security::remove_XSS($_GET['view_received_category']) : null;
$viewSentCategory = isset($_GET['view_sent_category']) ? Security::remove_XSS($_GET['view_sent_category']) : null;
@ -28,6 +29,14 @@ $showSentReceivedTabs = true;
// Do the tracking
Event::event_access_tool(TOOL_DROPBOX);
$logInfo = [
'tool' => TOOL_DROPBOX,
'tool_id' => 0,
'tool_id_detail' => 0,
'action' => $action,
];
Event::registerLog($logInfo);
/* DISPLAY SECTION */
Display::display_introduction_section(TOOL_DROPBOX);
@ -47,7 +56,6 @@ if (isset($_GET['dropbox_direction']) && in_array($_GET['dropbox_direction'], ['
}
$sort_params = Security::remove_XSS(implode('&', $sort_params));
$action = isset($_GET['action']) ? $_GET['action'] : null;
// Display the form for adding a new dropbox item.
if ($action == 'add') {

@ -107,8 +107,8 @@ if ($content_type == 'text/html') {
$content = $file_content;
$mit = "function Finish(){";
$js_content = "var SaveScoreVariable = 0; // This variable included by Dokeos System\n".
"function mySaveScore() // This function included by Dokeos System\n".
$js_content = "var SaveScoreVariable = 0; // This variable included by Chamilo\n".
"function mySaveScore() // This function included by Chamilo\n".
"{\n".
" if (SaveScoreVariable==0)\n".
" {\n".

@ -184,7 +184,6 @@ class MatchingDraggable extends Question
$form->addHtml('<tr>');
$form->addHtml('<td>'.chr(64 + $i).'</td>');
//$form->addText("option[$i]", null);
$form->addHtmlEditor(
"option[$i]",
null,
@ -272,6 +271,7 @@ class MatchingDraggable extends Question
$header .= '<th>'.get_lang('ExpectedChoice').'</th>';
$header .= '<th>'.get_lang('Status').'</th>';
} else {
$header .= '<th>'.get_lang('YourChoice').'</th>';
$header .= '<th>'.get_lang('CorrespondsTo').'</th>';
}
$header .= '</tr>';

@ -1246,7 +1246,7 @@ class MultipleAnswerTrueFalseDegreeCertainty extends Question
$objectExercise = new Exercise();
$objectExercise->read($exerciseId);
return $objectExercise->get_count_question_list();
return $objectExercise->getQuestionCount();
}
return 0;

@ -733,7 +733,7 @@ class TestCategory
category_id
FROM $tbl_track_attempt ta
INNER JOIN $tbl_question_rel_category qrc
ON (ta.question_id=qrc.question_id)
ON (ta.question_id = qrc.question_id)
WHERE
qrc.category_id = $in_cat_id AND
exe_id = $in_exe_id AND

@ -173,7 +173,6 @@ if (!is_object($objExercise)) {
// saves the object into the session
Session::write('objExercise', $objExercise);
}
// Exercise can be edited in their course.
if ($objExercise->sessionId != $sessionId) {
api_not_allowed(true);
@ -256,9 +255,9 @@ if (!empty($clone_question) && !empty($objExercise->id)) {
$new_answer_obj->duplicate($new_question_obj);
// Reloading tne $objExercise obj
$objExercise->read($objExercise->id);
$objExercise->read($objExercise->id, false);
header('Location: admin.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id);
header('Location: admin.php?'.api_get_cidreq().'&exerciseId='.$objExercise->id.'&page='.$page);
exit;
}
@ -284,7 +283,7 @@ if (api_is_in_gradebook()) {
$interbreadcrumb[] = ['url' => 'exercise.php?'.api_get_cidreq(), 'name' => get_lang('Exercises')];
if (isset($_GET['newQuestion']) || isset($_GET['editQuestion'])) {
$interbreadcrumb[] = [
'url' => "admin.php?exerciseId=".$objExercise->id.'&'.api_get_cidreq(),
'url' => 'admin.php?exerciseId='.$objExercise->id.'&'.api_get_cidreq(),
'name' => $objExercise->selectTitle(true),
];
} else {
@ -389,7 +388,7 @@ if ($inATest) {
if ($objExercise->random > 0) {
$alert .= '<br />'.sprintf(get_lang('OnlyXQuestionsPickedRandomly'), $objExercise->random);
}
echo Display::return_message($alert);
echo Display::return_message($alert, 'normal', false);
} elseif (isset($_GET['newQuestion'])) {
// we are in create a new question from question pool not in a test
echo '<div class="actions">';

@ -1,6 +1,7 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
use Chamilo\CoreBundle\Entity\TrackEHotspot;
use ChamiloSession as Session;
@ -1170,6 +1171,33 @@ class Exercise
return $inList;
}
/**
* If current exercise has a question.
*
* @param int $questionId
*
* @return int
*/
public function hasQuestion($questionId)
{
$questionId = (int) $questionId;
$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
$TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
$sql = "SELECT q.id
FROM $TBL_EXERCICE_QUESTION e
INNER JOIN $TBL_QUESTIONS q
ON (e.question_id = q.id AND e.c_id = q.c_id)
WHERE
q.id = $questionId AND
e.c_id = {$this->course_id} AND
e.exercice_id = ".$this->id;
$result = Database::query($sql);
return Database::num_rows($result) > 0;
}
/**
* changes the exercise title.
*
@ -1908,61 +1936,7 @@ class Exercise
);
// Type of results display on the final page
$radios_results_disabled = [];
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreAndRightAnswer'),
'0',
['id' => 'result_disabled_0']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DoNotShowScoreNorRightAnswer'),
'1',
['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('OnlyShowScore'),
'2',
['id' => 'result_disabled_2']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
'4',
['id' => 'result_disabled_4']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DontShowScoreOnlyWhenUserFinishesAllAttemptsButShowFeedbackEachAttempt'),
'5',
['id' => 'result_disabled_5', 'onclick' => 'check_results_disabled()']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ExerciseRankingMode'),
'6',
['id' => 'result_disabled_6']
);
$form->addGroup(
$radios_results_disabled,
null,
get_lang('ShowResultsToStudents')
);
$this->setResultDisabledGroup($form);
// Type of questions disposition on page
$radios = [];
@ -1992,7 +1966,7 @@ class Exercise
$form->addGroup($radios, null, get_lang('QuestionsPerPage'));
} else {
// if is Direct feedback but has not questions we can allow to modify the question type
if ($this->selectNbrQuestions() == 0) {
if ($this->getQuestionCount() === 0) {
// feedback type
$radios_feedback = [];
$radios_feedback[] = $form->createElement(
@ -2028,33 +2002,7 @@ class Exercise
[get_lang('FeedbackType'), get_lang('FeedbackDisplayOptions')]
);
$radios_results_disabled = [];
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreAndRightAnswer'),
'0',
['id' => 'result_disabled_0']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DoNotShowScoreNorRightAnswer'),
'1',
['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('OnlyShowScore'),
'2',
['id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()']
);
$form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
$this->setResultDisabledGroup($form);
// Type of questions disposition on page
$radios = [];
@ -2068,40 +2016,8 @@ class Exercise
);
$form->addGroup($radios, null, get_lang('ExerciseType'));
} else {
// Show options freeze
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreAndRightAnswer'),
'0',
['id' => 'result_disabled_0']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DoNotShowScoreNorRightAnswer'),
'1',
['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
);
$radios_results_disabled[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('OnlyShowScore'),
'2',
['id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()']
);
$form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
$result_disable_group = $form->addGroup(
$radios_results_disabled,
null,
get_lang('ShowResultsToStudents')
);
$result_disable_group->freeze();
$group = $this->setResultDisabledGroup($form);
$group->freeze();
// we force the options to the DirectFeedback exercisetype
$form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
@ -3090,7 +3006,7 @@ class Exercise
$myRemindList = []
) {
global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
$nbrQuestions = $this->get_count_question_list();
$nbrQuestions = $this->getQuestionCount();
$buttonList = [];
$html = $label = '';
$hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
@ -3289,7 +3205,7 @@ class Exercise
function onExpiredTimeExercise() {
$('#wrapper-clock').hide();
$('#expired-message-id').show();
//Fixes bug #5263
// Fixes bug #5263
$('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
openClockWarning();
}
@ -3457,7 +3373,7 @@ class Exercise
isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
);
//probably this attempt came in an exercise all question by page
// Probably this attempt came in an exercise all question by page
if ($feedback_type == 0) {
$objQuestionTmp->replaceWithRealExe($exeId);
}
@ -3610,8 +3526,10 @@ class Exercise
if (!empty($studentChoice)) {
if ($studentChoice == $answerCorrect) {
// correct answer and student is Unsure or PrettySur
if ($quiz_question_options[$studentChoiceDegree]['position'] >= 3
&& $quiz_question_options[$studentChoiceDegree]['position'] < 9) {
if (isset($quiz_question_options[$studentChoiceDegree]) &&
$quiz_question_options[$studentChoiceDegree]['position'] >= 3 &&
$quiz_question_options[$studentChoiceDegree]['position'] < 9
) {
$questionScore += $true_score;
} else {
// student ignore correct answer
@ -3702,21 +3620,15 @@ class Exercise
}
$studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
$real_answers[$answerId] = false;
if ($answerCorrect == $studentChoice) {
//$answerCorrect = 1;
$real_answers[$answerId] = true;
} else {
//$answerCorrect = 0;
$real_answers[$answerId] = false;
}
} else {
$studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
$real_answers[$answerId] = false;
if ($answerCorrect == $studentChoice) {
//$answerCorrect = 1;
$real_answers[$answerId] = true;
} else {
//$answerCorrect = 0;
$real_answers[$answerId] = false;
}
}
break;
@ -3732,31 +3644,27 @@ class Exercise
$studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
if ($answerCorrect == 1) {
$real_answers[$answerId] = false;
if ($studentChoice) {
$real_answers[$answerId] = true;
} else {
$real_answers[$answerId] = false;
}
} else {
$real_answers[$answerId] = true;
if ($studentChoice) {
$real_answers[$answerId] = false;
} else {
$real_answers[$answerId] = true;
}
}
} else {
$studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
if ($answerCorrect == 1) {
$real_answers[$answerId] = false;
if ($studentChoice) {
$real_answers[$answerId] = true;
} else {
$real_answers[$answerId] = false;
}
} else {
$real_answers[$answerId] = true;
if ($studentChoice) {
$real_answers[$answerId] = false;
} else {
$real_answers[$answerId] = true;
}
}
}
@ -4050,7 +3958,7 @@ class Exercise
$temp = $answer;
$answer = '';
$j = 0;
//initialise answer tags
// initialise answer tags
$userTags = $correctTags = $realText = [];
// the loop will stop at the end of the text
while (1) {
@ -4062,10 +3970,10 @@ class Exercise
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
// and ends with '[' into a general storage array
$realText[] = api_substr($temp, 0, $pos + 1);
$answer .= api_substr($temp, 0, $pos + 1);
//take the string remaining (after the last "[" we found)
// 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) {
@ -4101,11 +4009,11 @@ class Exercise
$choice[$j] = null;
}
} else {
// This value is the user input, not escaped while correct answer is escaped by fckeditor
// This value is the user input not escaped while correct answer is escaped by ckeditor
$choice[$j] = api_htmlentities(trim($choice[$j]));
}
$userTags[] = $choice[$j];
//put the contents of the [] answer tag into correct_tags[]
// put the contents of the [] answer tag into correct_tags[]
$correctTags[] = api_substr($temp, 0, $pos);
$j++;
$temp = api_substr($temp, $pos + 1);
@ -4307,19 +4215,27 @@ class Exercise
// Try with id
if (isset($real_list[$i_answer_id])) {
$user_answer = Display::span($real_list[$i_answer_id]);
$user_answer = Display::span(
$real_list[$i_answer_id],
['style' => 'color: #008000; font-weight: bold;']
);
}
// Try with $i_answer_id_auto
if (empty($user_answer)) {
if (isset($real_list[$i_answer_id_auto])) {
$user_answer = Display::span($real_list[$i_answer_id_auto]);
$user_answer = Display::span(
$real_list[$i_answer_id_auto],
['style' => 'color: #008000; font-weight: bold;']
);
}
}
if ($this->showExpectedChoice()) {
if (isset($real_list[$i_answer_correct_answer])) {
$user_answer = Display::span($real_list[$i_answer_correct_answer]);
}
if (isset($real_list[$i_answer_correct_answer])) {
$user_answer = Display::span(
$real_list[$i_answer_correct_answer],
['style' => 'color: #008000; font-weight: bold;']
);
}
} else {
$user_answer = Display::span(
@ -4348,6 +4264,12 @@ class Exercise
}
}
if ($results_disabled == RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER) {
if ($s_user_answer != $i_answer_correct_answer) {
continue;
}
}
if ($show_result) {
if ($this->showExpectedChoice() == false &&
$showTotalScoreAndUserChoicesInLastAttempt === false
@ -4375,7 +4297,7 @@ class Exercise
echo '<td>'.$status.'</td>';
} else {
echo '<td>'.$s_answer_label.'</td>';
//echo '<td>'.$user_answer.'</td>';
echo '<td>'.$user_answer.'</td>';
echo '<td>';
if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
if (isset($real_list[$i_answer_correct_answer]) &&
@ -4966,6 +4888,7 @@ class Exercise
if ($debug) {
error_log('Showing questions $from '.$from);
}
switch ($answerType) {
case UNIQUE_ANSWER:
case UNIQUE_ANSWER_IMAGE:
@ -5162,26 +5085,6 @@ class Exercise
case HOT_SPOT_DELINEATION:
$user_answer = $user_array;
if ($next) {
//$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)."')";
$result = Database::query($sql,__FILE__,__LINE__);
*/
$user_answer = $user_array;
// we compare only the delineation not the other points
$answer_question = $_SESSION['hotspot_coord'][1];
@ -5331,7 +5234,6 @@ class Exercise
)
);
echo '</tr>';
break;
case ANNOTATION:
ExerciseShowFunctions::displayAnnotationAnswer(
@ -5643,16 +5545,17 @@ class Exercise
) {
if ($choice != 0) {
$reply = array_keys($choice);
for ($i = 0; $i < sizeof($reply); $i++) {
$countReply = count($reply);
for ($i = 0; $i < $countReply; $i++) {
$chosenAnswer = $reply[$i];
if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
if ($choiceDegreeCertainty != 0) {
$replyDegreeCertainty = array_keys($choiceDegreeCertainty);
$answerDegreeCertainty = $replyDegreeCertainty[$i];
$answerDegreeCertainty = isset($replyDegreeCertainty[$i]) ? $replyDegreeCertainty[$i] : '';
$answerValue = isset($choiceDegreeCertainty[$answerDegreeCertainty]) ? $choiceDegreeCertainty[$answerDegreeCertainty] : '';
Event::saveQuestionAttempt(
$questionScore,
$chosenAnswer.':'.$choice[$chosenAnswer].':'.
$choiceDegreeCertainty[$answerDegreeCertainty],
$chosenAnswer.':'.$choice[$chosenAnswer].':'.$answerValue,
$quesId,
$exeId,
$i,
@ -6344,9 +6247,9 @@ class Exercise
}
// 4. We check if the student have attempts
$exerciseAttempts = $this->selectAttempts();
if ($isVisible) {
$exerciseAttempts = $this->selectAttempts();
if ($exerciseAttempts > 0) {
$attemptCount = Event::get_attempt_count_not_finished(
api_get_user_id(),
@ -6364,6 +6267,19 @@ class Exercise
);
$isVisible = false;
}
} else {
$isLimitReached = ExerciseLib::isQuestionsLimitPerDayReached(
api_get_user_id(),
$this->selectNbrQuestions(),
api_get_course_int_id(),
api_get_session_id()
);
if ($isLimitReached) {
$maxQuestionsAnswered = (int) api_get_course_setting('quiz_question_limit_per_day');
$message = sprintf(get_lang('QuizQuestionsLimitPerDayXReached'), $maxQuestionsAnswered);
$isVisible = false;
}
}
}
@ -6885,21 +6801,6 @@ class Exercise
return $html;
}
/**
* @return int
*/
public function get_count_question_list()
{
// Real question count
$question_count = 0;
$question_list = $this->get_question_list();
if (!empty($question_list)) {
$question_count = count($question_list);
}
return $question_count;
}
/**
* Get categories added in the exercise--category matrix.
*
@ -7366,8 +7267,8 @@ class Exercise
}
$attributes = ['id' => 'remind_list['.$questionId.']'];
// Showing the question
// Showing the question
$exercise_actions = null;
echo '<a id="questionanchor'.$questionId.'"></a><br />';
echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
@ -7929,8 +7830,10 @@ class Exercise
$hideLabel = api_get_configuration_value('exercise_hide_label');
$label = '<div class="rib rib-'.$class.'">
<h3>'.$scoreLabel.'</h3>
</div>
<h4>'.get_lang('Score').': '.$result.'</h4>';
</div>';
if (!empty($result)) {
$label .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
}
if ($hideLabel === true) {
$answerUsed = (int) $array['used'];
$answerMissing = (int) $array['missing'] - $answerUsed;
@ -7955,13 +7858,16 @@ class Exercise
</div>'
;
} else {
return '<div class="ribbon">
$html = '<div class="ribbon">
<div class="rib rib-'.$class.'">
<h3>'.$scoreLabel.'</h3>
</div>
<h4>'.get_lang('Score').': '.$result.'</h4>
</div>'
;
</div>';
if (!empty($result)) {
$html .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
}
$html .= '</div>';
return $html;
}
}
@ -8014,6 +7920,10 @@ class Exercise
public function getQuestionForTeacher($start = 0, $lenght = 10)
{
$start = (int) $start;
if ($start < 0) {
$start = 0;
}
$lenght = (int) $lenght;
$TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
@ -8402,4 +8312,95 @@ class Exercise
}
$this->mediaList = $mediaList;
}
/**
* @param FormValidator $form
*
* @return HTML_QuickForm_group
*/
private function setResultDisabledGroup(FormValidator $form)
{
$resultDisabledGroup = [];
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreAndRightAnswer'),
'0',
['id' => 'result_disabled_0']
);
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DoNotShowScoreNorRightAnswer'),
'1',
['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
);
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('OnlyShowScore'),
'2',
['id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()']
);
if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT) {
$group = $form->addGroup(
$resultDisabledGroup,
null,
get_lang('ShowResultsToStudents')
);
return $group;
}
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
'4',
['id' => 'result_disabled_4']
);
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('DontShowScoreOnlyWhenUserFinishesAllAttemptsButShowFeedbackEachAttempt'),
'5',
['id' => 'result_disabled_5', 'onclick' => 'check_results_disabled()']
);
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ExerciseRankingMode'),
'6',
['id' => 'result_disabled_6']
);
$resultDisabledGroup[] = $form->createElement(
'radio',
'results_disabled',
null,
get_lang('ExerciseShowOnlyGlobalScoreAndCorrectAnswers'),
'7',
['id' => 'result_disabled_7']
);
$group = $form->addGroup(
$resultDisabledGroup,
null,
get_lang('ShowResultsToStudents')
);
return $group;
}
}

@ -64,8 +64,8 @@ $exfile = explode('/', $exercisePath);
$exfile = strtolower($exfile[sizeof($exfile) - 1]);
$exercisePath = substr($exercisePath, 0, strpos($exercisePath, $exfile));
$exercisePath = $exercisePath.'exercise.php';
// Clear the exercise session
// Clear the exercise session
Session::erase('objExercise');
Session::erase('objQuestion');
Session::erase('objAnswer');
@ -179,6 +179,10 @@ if ($is_allowedToEdit) {
if ($choice === 'clean_all_test') {
$check = Security::check_token('get');
if ($check) {
if ($limitTeacherAccess && !api_is_platform_admin()) {
api_not_allowed(true);
}
// list of exercises in a course/session
// we got variable $courseId $courseInfo session api_get_session_id()
$exerciseList = ExerciseLib::get_all_exercises_for_course_id(
@ -328,7 +332,7 @@ if ($is_allowedToEdit) {
break;
}
//clean student results
// Clean student results
if ($exercise_action_locked == false) {
$quantity_results_deleted = $objExerciseTmp->cleanResults(true);
$title = $objExerciseTmp->selectTitle();
@ -399,7 +403,7 @@ if ($is_allowedToEdit) {
$newVisibilityStatus = '1'; //"visible"
$query = "SELECT id FROM $TBL_DOCUMENT
WHERE c_id = $courseId AND path='".Database :: escape_string($file)."'";
WHERE c_id = $courseId AND path='".Database::escape_string($file)."'";
$res = Database::query($query);
$row = Database :: fetch_array($res, 'ASSOC');
api_item_property_update(
@ -419,7 +423,7 @@ if ($is_allowedToEdit) {
}
$newVisibilityStatus = '0'; //"invisible"
$query = "SELECT id FROM $TBL_DOCUMENT
WHERE c_id = $courseId AND path='".Database :: escape_string($file)."'";
WHERE c_id = $courseId AND path='".Database::escape_string($file)."'";
$res = Database::query($query);
$row = Database :: fetch_array($res, 'ASSOC');
api_item_property_update(
@ -487,21 +491,21 @@ if ($is_allowedToEdit) {
$sql = "SELECT * FROM $TBL_DOCUMENT
WHERE
c_id = $courseId AND
path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'";
path LIKE '".Database::escape_string($uploadPath.'/%/%')."'";
$res = Database::query($sql);
$hp_count = Database :: num_rows($res);
} else {
$sql = "SELECT * FROM $TBL_DOCUMENT d
INNER JOIN $TBL_ITEM_PROPERTY ip
ON (d.id = ip.ref AND d.c_id = ip.c_id)
WHERE
WHERE
ip.tool = '".TOOL_DOCUMENT."' AND
d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."' AND
d.path LIKE '".Database::escape_string($uploadPath.'/%/%')."' AND
ip.visibility ='1' AND
d.c_id = $courseId AND
ip.c_id = $courseId";
$res = Database::query($sql);
$hp_count = Database :: num_rows($res);
$hp_count = Database::num_rows($res);
}
$total = $total_exercises + $hp_count;
@ -528,7 +532,7 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/aiken.php?'.api_get_cidreq().'">'.Display::return_icon('import_aiken.png', get_lang('ImportAikenQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
echo '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/upload_exercise.php?'.api_get_cidreq().'">'.Display::return_icon('import_excel.png', get_lang('ImportExcelQuiz'), '', ICON_SIZE_MEDIUM).'</a>';
echo Display::url(
$cleanAll = Display::url(
Display::return_icon(
'clean_all.png',
get_lang('CleanAllStudentsResultsForAllTests'),
@ -543,6 +547,14 @@ if ($is_allowedToEdit && $origin != 'learnpath') {
'data-target' => '#confirm-delete',
]
);
if ($limitTeacherAccess) {
if (api_is_platform_admin()) {
echo $cleanAll;
}
} else {
echo $cleanAll;
}
}
if ($is_allowedToEdit) {
@ -581,7 +593,7 @@ $offline_icon = Display::return_icon(
$exerciseList = [];
$list_ordered = null;
while ($row = Database :: fetch_array($result, 'ASSOC')) {
while ($row = Database::fetch_array($result, 'ASSOC')) {
$exerciseList[$row['iid']] = $row;
}
@ -813,9 +825,18 @@ if (!empty($exerciseList)) {
$actions .= $settings;
// Exercise results
$actions .= '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
$resultsLink = '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
if ($limitTeacherAccess) {
if (api_is_platform_admin()) {
$actions .= $resultsLink;
}
} else {
// Exercise results
$actions .= $resultsLink;
}
// Auto launch
if ($autoLaunchAvailable) {
$autoLaunch = $exercise->getAutoLaunch();
@ -915,7 +936,7 @@ if (!empty($exerciseList)) {
);
}
}
// Export qti ...
if ($limitTeacherAccess && !api_is_platform_admin()) {
$visibility = '';
}
@ -1223,6 +1244,12 @@ if (!empty($exerciseList)) {
}
if ($is_allowedToEdit) {
$additionalActions = ExerciseLib::getAdditionalTeacherActions($row['id']);
if (!empty($additionalActions)) {
$actions .= $additionalActions.PHP_EOL;
}
$item .= Display::tag('td', $actions, ['class' => 'td_actions']);
} else {
if ($isDrhOfCourse) {
@ -1467,5 +1494,5 @@ if (empty($exerciseList) && $hotpotatoes_exist == false) {
}
if ($origin != 'learnpath') { //so we are not in learnpath tool
Display :: display_footer();
Display::display_footer();
}

@ -19,12 +19,6 @@ if (!api_is_allowed_to_edit(null, true)) {
api_not_allowed(true);
}
$limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
if ($limitTeacherAccess && !api_is_platform_admin()) {
api_not_allowed(true);
}
$htmlHeadXtra[] = '<script>
function activate_start_date() {
if(document.getElementById(\'start_date_div\').style.display == \'none\') {
@ -140,7 +134,7 @@ if (isset($_GET['exerciseId'])) {
'post',
api_get_self().'?'.api_get_cidreq().'&exerciseId='.intval($_GET['exerciseId'])
);
$objExercise->read($_GET['exerciseId']);
$objExercise->read($_GET['exerciseId'], false);
$form->addElement('hidden', 'edit', 'true');
} else {
$form = new FormValidator(
@ -202,8 +196,8 @@ if ($form->validate()) {
$lp_id = $_GET['lp_id'];
}
$lp_id = (int) $lp_id;
echo "<a href=\"../lp/lp_controller.php?".api_get_cidreq()."&gradebook=&action=add_item&type=step&lp_id=".$lp_id."#resource_tab-2\">".Display::return_icon('back.png', get_lang("BackTo").' '.get_lang("LearningPaths"), '', ICON_SIZE_MEDIUM)."</a>";
Display::return_icon('back.png', get_lang("BackTo").' '.get_lang("LearningPaths"), '', ICON_SIZE_MEDIUM)."</a>";
echo "<a href=\"../lp/lp_controller.php?".api_get_cidreq()."&gradebook=&action=add_item&type=step&lp_id=".$lp_id."#resource_tab-2\">".
Display::return_icon('back.png', get_lang("BackTo").' '.get_lang("LearningPaths"), '', ICON_SIZE_MEDIUM)."</a>";
} else {
echo '<a href="exercise.php?'.api_get_cidreq().'">'.
Display::return_icon('back.png', get_lang('BackToExercisesList'), '', ICON_SIZE_MEDIUM).

@ -31,6 +31,12 @@ if (api_is_student_boss() && !empty($filter_user)) {
api_protect_course_script(true, false, true);
}
$limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
if ($limitTeacherAccess && !api_is_platform_admin()) {
api_not_allowed(true);
}
// including additional libraries
require_once 'hotpotatoes.lib.php';

@ -253,31 +253,31 @@ if (!empty($track_exercise_info)) {
);
}
}
break;
case RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK:
case RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT:
$attempts = Event::getExerciseResultsByUser(
$currentUserId,
$objExercise->id,
api_get_course_int_id(),
api_get_session_id(),
$track_exercise_info['orig_lp_id'],
$track_exercise_info['orig_lp_item_id'],
'desc'
);
$numberAttempts = count($attempts);
if ($numberAttempts >= $track_exercise_info['max_attempt']) {
$show_results = true;
$show_only_total_score = true;
// Attempt reach max so show score/feedback now
$showTotalScoreAndUserChoicesInLastAttempt = true;
} else {
$show_results = true;
$show_only_total_score = true;
// Last attempt not reach don't show score/feedback
$showTotalScoreAndUserChoicesInLastAttempt = false;
}
break;
break;
case RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK:
case RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT:
$attempts = Event::getExerciseResultsByUser(
$currentUserId,
$objExercise->id,
api_get_course_int_id(),
api_get_session_id(),
$track_exercise_info['orig_lp_id'],
$track_exercise_info['orig_lp_item_id'],
'desc'
);
$numberAttempts = count($attempts);
if ($numberAttempts >= $track_exercise_info['max_attempt']) {
$show_results = true;
$show_only_total_score = true;
// Attempt reach max so show score/feedback now
$showTotalScoreAndUserChoicesInLastAttempt = true;
} else {
$show_results = true;
$show_only_total_score = true;
// Last attempt not reach don't show score/feedback
$showTotalScoreAndUserChoicesInLastAttempt = false;
}
break;
}
} else {
echo Display::return_message(get_lang('CantViewResults'), 'warning');
@ -328,7 +328,7 @@ $sql = "SELECT attempts.question_id, answer
questions.id = quizz_rel_questions.question_id AND
questions.c_id = ".api_get_course_int_id()."
WHERE
attempts.exe_id = ".intval($id)." $user_restriction
attempts.exe_id = ".$id." $user_restriction
GROUP BY quizz_rel_questions.question_order, attempts.question_id";
$result = Database::query($sql);
$question_list_from_database = [];
@ -910,13 +910,18 @@ foreach ($questionList as $questionId) {
$score = [];
if ($show_results) {
$scorePassed = $my_total_score >= $my_total_weight;
if (function_exists('bccomp')) {
$compareResult = bccomp($my_total_score, $my_total_weight, 3);
$scorePassed = $compareResult === 1 || $compareResult === 0;
}
$score['result'] = ExerciseLib::show_score(
$my_total_score,
$my_total_weight,
false,
false
);
$score['pass'] = $my_total_score >= $my_total_weight ? true : false;
$score['pass'] = $scorePassed;
$score['type'] = $answerType;
$score['score'] = $my_total_score;
$score['weight'] = $my_total_weight;
@ -956,7 +961,7 @@ foreach ($questionList as $questionId) {
$totalScoreText = '';
//Total score
// Total score
$myTotalScoreTemp = $totalScore;
if ($origin != 'learnpath' || ($origin == 'learnpath' && isset($_GET['fb_type']))) {
if ($show_results || $show_only_total_score || $showTotalScoreAndUserChoicesInLastAttempt) {

@ -39,6 +39,7 @@ api_protect_course_script(true);
$origin = api_get_origin();
$is_allowedToEdit = api_is_allowed_to_edit(null, true);
$courseId = api_get_course_int_id();
$sessionId = api_get_session_id();
$glossaryExtraTools = api_get_setting('show_glossary_in_extra_tools');
$showGlossary = in_array($glossaryExtraTools, ['true', 'exercise', 'exercise_and_lp']);
@ -216,6 +217,12 @@ if ($time_control) {
$show_clock = true;
$user_id = api_get_user_id();
if ($objExercise->selectAttempts() > 0) {
$messageReachedMax = Display::return_message(
sprintf(get_lang('ReachedMaxAttempts'), $exercise_title, $objExercise->selectAttempts()),
'warning',
false
);
$attempt_html = '';
$attempt_count = Event::get_attempt_count(
$user_id,
@ -238,6 +245,35 @@ if ($objExercise->selectAttempts() > 0) {
);
if (!empty($exercise_stat_info)) {
$isQuestionsLimitReached = ExerciseLib::isQuestionsLimitPerDayReached(
$user_id,
$objExercise->selectNbrQuestions(),
$courseId,
$sessionId
);
if ($isQuestionsLimitReached) {
$maxQuestionsAnswered = (int) api_get_course_setting('quiz_question_limit_per_day');
Display::addFlash(
Display::return_message(
sprintf(get_lang('QuizQuestionsLimitPerDayXReached'), $maxQuestionsAnswered),
'warning',
false
)
);
if ($origin == 'learnpath') {
Display::display_reduced_header();
Display::display_reduced_footer();
} else {
Display::display_header(get_lang('Exercises'));
Display::display_footer();
}
exit;
}
$max_exe_id = max(array_keys($exercise_stat_info));
$last_attempt_info = $exercise_stat_info[$max_exe_id];
$attempt_html .= Display::div(
@ -245,15 +281,7 @@ if ($objExercise->selectAttempts() > 0) {
['id' => '']
);
$attempt_html .= Display::return_message(
sprintf(
get_lang('ReachedMaxAttempts'),
$exercise_title,
$objExercise->selectAttempts()
),
'warning',
false
);
$attempt_html .= $messageReachedMax;
if (!empty($last_attempt_info['question_list'])) {
foreach ($last_attempt_info['question_list'] as $questions) {
@ -282,37 +310,13 @@ if ($objExercise->selectAttempts() > 0) {
['id' => 'question_score']
);
} else {
$attempt_html .= Display::return_message(
sprintf(
get_lang('ReachedMaxAttempts'),
$exercise_title,
$objExercise->selectAttempts()
),
'warning',
false
);
$attempt_html .= $messageReachedMax;
}
} else {
$attempt_html .= Display::return_message(
sprintf(
get_lang('ReachedMaxAttempts'),
$exercise_title,
$objExercise->selectAttempts()
),
'warning',
false
);
$attempt_html .= $messageReachedMax;
}
} else {
$attempt_html .= Display::return_message(
sprintf(
get_lang('ReachedMaxAttempts'),
$exercise_title,
$objExercise->selectAttempts()
),
'warning',
false
);
$attempt_html .= $messageReachedMax;
}
if ($origin == 'learnpath') {
@ -1117,7 +1121,7 @@ if (!empty($error)) {
}
$(function() {
// This pre-load the save.png icon
//This pre-load the save.png icon
var saveImage = new Image();
saveImage.src = "'.$saveIcon.'";
@ -1139,7 +1143,7 @@ if (!empty($error)) {
$(".no_remind_highlight").hide();
// if the users validates the form using return key,
// if the users validates the form using return key, prevent form action and simulates click on validation button
// prevent form action and simulates click on validation button
/*$("#exercise_form").submit(function(){
$(".question-validate-btn").first().trigger("click");
return false;

@ -13,7 +13,7 @@ api_protect_course_script(false);
require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
Display::display_reduced_header();
//Display::display_reduced_header();
echo '<div id="delineation-container">';
@ -80,7 +80,7 @@ if (isset($_GET['choice'])) {
if (empty($choice_value)) {
echo "<script>
// this works for only radio buttons
var f = self.parent.window.document.frm_exercise;
var f = window.document.frm_exercise;
var choice_js='';
var hotspot = new Array();
var hotspotcoord = new Array();
@ -92,7 +92,7 @@ if (empty($choice_value)) {
}
if (f.elements[i].type=='hidden' ) {
name = f.elements[i].name;
var name = f.elements[i].name;
if (name.substr(0,7)=='hotspot')
hotspot.push(f.elements[i].value);
@ -304,6 +304,11 @@ if (!empty($choice_value)) {
$missing_color = true; //echo 'c';
}
$try_hotspot = null;
$lp_hotspot = null;
$url_hotspot = null;
$select_question_hotspot = null;
// if pass
//if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold2 && $final_excess<=$threadhold3) {
if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) {
@ -313,14 +318,15 @@ if (!empty($choice_value)) {
$next = 1; //Go to the oars. If $next = 0 we will show this message: "One (or more) area at risk has been hit" instead of the table resume with the results
$wrong_results = true;
$result_comment = get_lang('Unacceptable');
$special_comment = $comment = $answerDestination = $objAnswerTmp->selectComment(1);
$answerDestination = $objAnswerTmp->selectDestination(1);
$destination_items = explode('@@', $answerDestination);
$try_hotspot = $destination_items[1];
$lp_hotspot = $destination_items[2];
$select_question_hotspot = $destination_items[3];
$url_hotspot = $destination_items[4];
}
$special_comment = $comment = $answerDestination = $objAnswerTmp->selectComment(1);
$answerDestination = $objAnswerTmp->selectDestination(1);
$destination_items = explode('@@', $answerDestination);
$try_hotspot = $destination_items[1];
$lp_hotspot = $destination_items[2];
$select_question_hotspot = $destination_items[3];
$url_hotspot = $destination_items[4];
} elseif ($answerId > 1) {
if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
if ($dbg_local > 0) {
@ -464,7 +470,7 @@ Session::write('newquestionList', $newquestionList);
$links = '';
if (isset($choice_value) && $choice_value == -1) {
if ($answerType != HOT_SPOT_DELINEATION) {
$links .= '<a href="#" onclick="self.parent.tb_remove();">'.get_lang('ChooseAnAnswer').'</a><br />';
$links .= '<a href="#" onclick="tb_remove();">'.get_lang('ChooseAnAnswer').'</a><br />';
}
}
@ -561,13 +567,15 @@ if ($destinationid == -1) {
echo '<script>
function SendEx(num) {
if (num == -1) {
self.parent.window.location.href = "exercise_result.php?take_session=1&exerciseId='.$exerciseId.'&num="+num+"&exerciseType='.$exerciseType.'&origin='.$origin.'&learnpath_item_id='.$learnpath_item_id.'&learnpath_id='.$learnpath_id.'";
self.parent.tb_remove();
window.location.href = "exercise_result.php?take_session=1&exerciseId='.$exerciseId.'&num="+num+"&exerciseType='.$exerciseType.'&origin='.$origin.'&learnpath_item_id='.$learnpath_item_id.'&learnpath_id='.$learnpath_id.'";
//tb_remove();
} else {
num -= 1;
self.parent.window.location.href = "exercise_submit.php?tryagain=1&exerciseId='.$exerciseId.'&num="+num+"&exerciseType='.$exerciseType.'&origin='.$origin.'&learnpath_item_id='.$learnpath_item_id.'&learnpath_id='.$learnpath_id.'";
self.parent.tb_remove();
window.location.href = "exercise_submit.php?tryagain=1&exerciseId='.$exerciseId.'&num="+num+"&exerciseType='.$exerciseType.'&origin='.$origin.'&learnpath_item_id='.$learnpath_item_id.'&learnpath_id='.$learnpath_id.'";
//tb_remove();
}
return false;
}
</script>';
@ -606,8 +614,8 @@ if ($links != '') {
} else {
$questionNum++;
echo '<script>
self.parent.window.location.href = "exercise_submit.php?exerciseId='.$exerciseId.'&num='.$questionNum.'&exerciseType='.$exerciseType.'&'.api_get_cidreq().'";
//self.parent.tb_remove();
window.location.href = "exercise_submit.php?exerciseId='.$exerciseId.'&num='.$questionNum.'&exerciseType='.$exerciseType.'&'.api_get_cidreq().'";
//tb_remove();
</script>';
}

@ -182,7 +182,7 @@ function aiken_import_exercise($file)
if (!empty($last_exercise_id)) {
// For each question found...
foreach ($exercise_info['question'] as $key => $question_array) {
//2.create question
// 2.create question
$question = new Aiken2Question();
$question->type = $question_array['type'];
$question->setAnswer();

@ -1232,6 +1232,12 @@ class FillBlanks extends Question
// rebuild the sentence with student answer inserted
for ($i = 0; $i < count($listStudentAnswerInfo['common_words']); $i++) {
if ($resultsDisabled == RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER) {
if (isset($listStudentAnswerInfo['student_score'][$i]) &&
$listStudentAnswerInfo['student_score'][$i] != 1) {
continue;
}
}
$result .= isset($listStudentAnswerInfo['common_words'][$i]) ? $listStudentAnswerInfo['common_words'][$i] : '';
$result .= isset($listStudentAnswerInfo['student_answer'][$i]) ? $listStudentAnswerInfo['student_answer'][$i] : '';
}

@ -56,13 +56,13 @@ if ($modifyIn) {
$objAnswer = new Answer($questionId);
}
$color = unserialize($color);
$reponse = unserialize($reponse);
$comment = unserialize($comment);
$weighting = unserialize($weighting);
$hotspot_coordinates = unserialize($hotspot_coordinates);
$hotspot_type = unserialize($hotspot_type);
$destination = unserialize($destination);
$color = UnserializeApi::unserialize('not_allowed_classes', $color);
$reponse = UnserializeApi::unserialize('not_allowed_classes', $reponse);
$comment = UnserializeApi::unserialize('not_allowed_classes', $comment);
$weighting = UnserializeApi::unserialize('not_allowed_classes', $weighting);
$hotspot_coordinates = UnserializeApi::unserialize('not_allowed_classes', $hotspot_coordinates);
$hotspot_type = UnserializeApi::unserialize('not_allowed_classes', $hotspot_type);
$destination = UnserializeApi::unserialize('not_allowed_classes', $destination);
unset($buttonBack);
}

@ -291,6 +291,7 @@ class Matching extends Question
$header .= '<th>'.get_lang('ExpectedChoice').'</th>';
$header .= '<th>'.get_lang('Status').'</th>';
} else {
$header .= '<th>'.get_lang('YourChoice').'</th>';
$header .= '<th>'.get_lang('CorrespondsTo').'</th>';
}
$header .= '</tr>';

@ -52,7 +52,7 @@ $interbreadcrumb[] = [
'url' => 'exercise.php?'.api_get_cidreq(),
'name' => get_lang('Exercises'),
];
$interbreadcrumb[] = ["url" => "#", "name" => $objExercise->selectTitle(true)];
$interbreadcrumb[] = ['url' => '#', 'name' => $objExercise->selectTitle(true)];
$time_control = false;
$clock_expired_time = ExerciseLib::get_session_time_control_key($objExercise->id, $learnpath_id, $learnpath_item_id);
@ -103,8 +103,8 @@ if ($is_allowed_to_edit) {
}
$iconExercise = Display::return_icon('test-quiz.png', null, [], ICON_SIZE_MEDIUM);
// Exercise name.
// Exercise name.
if (api_get_configuration_value('save_titles_as_html')) {
$html .= Display::div(
$objExercise->get_formated_title().PHP_EOL.$editLink
@ -115,7 +115,7 @@ if (api_get_configuration_value('save_titles_as_html')) {
);
}
//Exercise description
// Exercise description
if (!empty($objExercise->description)) {
$html .= Display::div($objExercise->description, ['class' => 'exercise_description']);
}
@ -254,24 +254,26 @@ if (!empty($attempts)) {
RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT,
RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK,
RESULT_DISABLE_RANKING,
RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
]
)) {
$row['result'] = $score;
}
if (in_array(
$objExercise->results_disabled,
[
RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT,
RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK,
RESULT_DISABLE_RANKING,
]
) || (
$objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
$objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END
)
$objExercise->results_disabled,
[
RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES,
RESULT_DISABLE_SHOW_SCORE_ATTEMPT_SHOW_ANSWERS_LAST_ATTEMPT,
RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK,
RESULT_DISABLE_RANKING,
RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
]
) || (
$objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_ONLY &&
$objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_END
)
) {
if ($blockShowAnswers &&
$objExercise->results_disabled != RESULT_DISABLE_DONT_SHOW_SCORE_ONLY_IF_USER_FINISHES_ATTEMPTS_SHOW_ALWAYS_FEEDBACK

@ -1983,20 +1983,20 @@ abstract class Question
if (!empty($counter)) {
$counterLabel = (int) $counter;
}
$score_label = get_lang('Wrong');
$scoreLabel = get_lang('Wrong');
$class = 'error';
if (isset($score['pass']) && $score['pass'] == true) {
$score_label = get_lang('Correct');
$scoreLabel = get_lang('Correct');
$class = 'success';
}
if (in_array($this->type, [FREE_ANSWER, ORAL_EXPRESSION, ANNOTATION])) {
$score['revised'] = isset($score['revised']) ? $score['revised'] : false;
if ($score['revised'] == true) {
$score_label = get_lang('Revised');
$scoreLabel = get_lang('Revised');
$class = '';
} else {
$score_label = get_lang('NotRevised');
$scoreLabel = get_lang('NotRevised');
$class = 'warning';
if (isset($score['weight'])) {
$weight = float_format($score['weight'], 1);
@ -2032,7 +2032,10 @@ abstract class Question
// dont display score for certainty degree questions
if ($this->type != MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
if (isset($score['result'])) {
$header .= $exercise->getQuestionRibbon($class, $score_label, $score['result'], $scoreCurrent);
if ($exercise->results_disabled == RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER) {
$score['result'] = null;
}
$header .= $exercise->getQuestionRibbon($class, $scoreLabel, $score['result'], $scoreCurrent);
}
}
@ -2073,6 +2076,7 @@ abstract class Question
}
/**
* @deprecated
* Create a question from a set of parameters.
*
* @param int Quiz ID

@ -13,7 +13,7 @@
*/
if (isset($_GET['editQuestion'])) {
$objQuestion = Question::read($_GET['editQuestion']);
$action = api_get_self()."?".api_get_cidreq()."&myid=1&modifyQuestion=".$modifyQuestion."&editQuestion=".$objQuestion->id;
$action = api_get_self()."?".api_get_cidreq()."&myid=1&modifyQuestion=".$modifyQuestion."&editQuestion=".$objQuestion->id.'&page='.$page;
} else {
$objQuestion = Question::getInstance($_REQUEST['answerType']);
$action = api_get_self()."?".api_get_cidreq()."&modifyQuestion=".$modifyQuestion."&newQuestion=".$newQuestion;
@ -65,18 +65,18 @@ if (is_object($objQuestion)) {
$objQuestion->type != HOT_SPOT_DELINEATION
) {
if (isset($_GET['editQuestion'])) {
echo '<script type="text/javascript">window.location.href="admin.php?exerciseId='.$exerciseId.'&'.api_get_cidreq().'&message=ItemUpdated"</script>';
echo '<script type="text/javascript">window.location.href="admin.php?exerciseId='.$exerciseId.'&'.api_get_cidreq().'&page='.$page.'&message=ItemUpdated"</script>';
} else {
// New question
$page = '';
$page = 1;
$length = api_get_configuration_value('question_pagination_length');
if ($length) {
$page = round($objExercise->get_count_question_list() / $length);
if (!empty($length)) {
$page = round($objExercise->getQuestionCount() / $length);
}
echo '<script type="text/javascript">window.location.href="admin.php?exerciseId='.$exerciseId.'&'.api_get_cidreq().'&page='.$page.'&message=ItemAdded"</script>';
}
} else {
echo '<script type="text/javascript">window.location.href="admin.php?exerciseId='.$exerciseId.'&hotspotadmin='.$objQuestion->id.'&'.api_get_cidreq().'"</script>';
echo '<script type="text/javascript">window.location.href="admin.php?exerciseId='.$exerciseId.'&page='.$page.'&hotspotadmin='.$objQuestion->id.'&'.api_get_cidreq().'"</script>';
}
} else {
if (isset($questionName)) {
@ -86,7 +86,7 @@ if (is_object($objQuestion)) {
echo '<img src="../document/download.php?doc_url=%2Fimages%2F'.$pictureName.'" border="0">';
}
if (!empty($msgErr)) {
echo Display::return_message($msgErr, 'normal');
echo Display::return_message($msgErr);
}
// display the form
$form->display();

@ -170,7 +170,8 @@ if (!$inATest) {
$alloQuestionOrdering = true;
$showPagination = api_get_configuration_value('show_question_pagination');
if (!empty($showPagination) && $nbrQuestions > $showPagination) {
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
// $page is declare in admin.php
//$page = isset($_GET['page']) && !empty($_GET['page']) ? (int) $_GET['page'] : 1;
$length = api_get_configuration_value('question_pagination_length');
$url = api_get_self().'?'.api_get_cidreq();
// Use pagination for exercise with more than 200 questions.
@ -179,17 +180,16 @@ if (!$inATest) {
$questionList = $objExercise->getQuestionForTeacher($start, $length);
$paginator = new Knp\Component\Pager\Paginator();
$pagination = $paginator->paginate([]);
$pagination->setTotalItemCount($nbrQuestions);
$pagination->setItemNumberPerPage($length);
$pagination->setCurrentPageNumber($page);
$pagination->renderer = function ($data) use ($url) {
$render = '<ul class="pagination">';
for ($i = 1; $i <= $data['pageCount']; $i++) {
//foreach ($data['pagesInRange'] as $page) {
$page = (int) $i;
$pageContent = '<li><a href="'.$url.'&page='.$page.'">'.$page.'</a></li>';
if ($data['current'] == $page) {
$pageContent = '<li class="active"><a href="#" >'.$page.'</a></li>';
$pageContent = '<li><a href="'.$url.'&page='.$i.'">'.$i.'</a></li>';
if ($data['current'] == $i) {
$pageContent = '<li class="active"><a href="#" >'.$i.'</a></li>';
}
$render .= $pageContent;
}

@ -48,7 +48,7 @@ $_course = api_get_course_info();
if (empty($objExercise) && !empty($fromExercise)) {
$objExercise = new Exercise();
$objExercise->read($fromExercise);
$objExercise->read($fromExercise, false);
}
$nameTools = get_lang('QuestionPool');
@ -402,8 +402,6 @@ $question_list = Question::get_question_type_list();
$new_question_list = [];
$new_question_list['-1'] = get_lang('All');
if (!empty($_course)) {
$objExercise = new Exercise();
$objExercise->read($fromExercise);
foreach ($question_list as $key => $item) {
if ($objExercise->feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
if (!in_array($key, [HOT_SPOT_DELINEATION, UNIQUE_ANSWER])) {
@ -705,10 +703,9 @@ $pagination->renderer = function ($data) use ($url) {
if ($data['pageCount'] > 1) {
$render = '<ul class="pagination">';
for ($i = 1; $i <= $data['pageCount']; $i++) {
$page = (int) $i;
$pageContent = '<li><a href="'.$url.'&page='.$page.'">'.$page.'</a></li>';
if ($data['current'] == $page) {
$pageContent = '<li class="active"><a href="#" >'.$page.'</a></li>';
$pageContent = '<li><a href="'.$url.'&page='.$i.'">'.$i.'</a></li>';
if ($data['current'] == $i) {
$pageContent = '<li class="active"><a href="#" >'.$i.'</a></li>';
}
$render .= $pageContent;
}
@ -791,7 +788,6 @@ if (is_array($mainQuestionList)) {
if (empty($question_type)) {
continue;
}
$sessionId = isset($question['session_id']) ? $question['session_id'] : null;
$exerciseName = isset($question['exercise_name']) ? '<br />('.$question['exercise_id'].') ' : null;
$row[] = getLinkForQuestion(
@ -803,6 +799,7 @@ if (is_array($mainQuestionList)) {
$sessionId,
$question['exerciseId']
).$exerciseName;
$row[] = $question_type;
$row[] = TestCategory::getCategoryNameForQuestion($question['id'], $selected_course);
$row[] = $question['level'];
@ -817,7 +814,8 @@ if (is_array($mainQuestionList)) {
$exerciseLevel,
$answerType,
$session_id,
$question['exerciseId']
$question['exerciseId'],
$objExercise
).'&nbsp;'.
get_action_icon_for_question(
$actionIcon2,
@ -830,7 +828,8 @@ if (is_array($mainQuestionList)) {
$exerciseLevel,
$answerType,
$session_id,
$question['exerciseId']
$question['exerciseId'],
$objExercise
);
$data[] = $row;
}
@ -982,7 +981,8 @@ function get_action_icon_for_question(
$in_exerciseLevel,
$in_answerType,
$in_session_id,
$in_exercise_id
$in_exercise_id,
Exercise $myObjEx
) {
$limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
$getParams = "&selected_course=$in_selected_course&courseCategoryId=$in_courseCategoryId&exerciseId=$in_exercise_id&exerciseLevel=$in_exerciseLevel&answerType=$in_answerType&session_id=$in_session_id";
@ -1009,20 +1009,16 @@ function get_action_icon_for_question(
);
break;
case 'add':
// add if question is not already in test
$myObjEx = new Exercise();
$myObjEx->read($from_exercise);
$res = "-";
if (!$myObjEx->isInList($in_questionid)) {
$res = '-';
if (!$myObjEx->hasQuestion($in_questionid)) {
$res = "<a href='".api_get_self()."?".
api_get_cidreq().$getParams."&recup=$in_questionid&fromExercise=$from_exercise'>";
$res .= Display::return_icon("view_more_stats.gif", get_lang('InsertALinkToThisQuestionInTheExercise'));
$res .= Display::return_icon('view_more_stats.gif', get_lang('InsertALinkToThisQuestionInTheExercise'));
$res .= "</a>";
}
unset($myObjEx);
break;
case 'clone':
$url = api_get_self()."?".api_get_cidreq().$getParams.
$url = api_get_self().'?'.api_get_cidreq().$getParams.
"&question_copy=$in_questionid&course_id=$in_selected_course&fromExercise=$from_exercise";
$res = Display::url(
Display::return_icon('cd.png', get_lang('ReUseACopyInCurrentTest')),

@ -39,11 +39,14 @@ $student_id = $track_exercise_info['exe_user_id'];
$current_user_id = api_get_user_id();
$objExercise = new Exercise();
if (!empty($exercise_id)) {
$objExercise->read($exercise_id);
}
if (empty($objExercise)) {
api_not_allowed($show_headers);
}
// Only users can see their own results
if (!$is_allowedToEdit) {
if ($student_id != $current_user_id) {
@ -57,7 +60,7 @@ $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_JS_PATH).'annotation/
if ($show_headers) {
$interbreadcrumb[] = [
'url' => "exercise.php?".api_get_cidreq(),
'url' => 'exercise.php?'.api_get_cidreq(),
'name' => get_lang('Exercises'),
];
$interbreadcrumb[] = ['url' => '#', 'name' => get_lang('Result')];
@ -72,6 +75,7 @@ if ($show_headers) {
$message = Session::read('attempt_remaining');
Session::erase('attempt_remaining');
ExerciseLib::displayQuestionListByAttempt(
$objExercise,
$id,

@ -132,15 +132,15 @@ function edit_category_form($action)
get_lang('CategoryDescription'),
false,
false,
['ToolbarSet' => 'test_category', 'Height' => '200']
['ToolbarSet' => 'TestQuestionDescription', 'Height' => '200']
);
$form->addButtonSave(get_lang('ModifyCategory'), 'SubmitNote');
// setting the defaults
$defaults = [];
$defaults["category_id"] = $objcat->id;
$defaults["category_name"] = $objcat->name;
$defaults["category_description"] = $objcat->description;
$defaults['category_id'] = $objcat->id;
$defaults['category_name'] = $objcat->name;
$defaults['category_description'] = $objcat->description;
$form->setDefaults($defaults);
// setting the rules
@ -213,7 +213,7 @@ function add_category_form($action)
get_lang('CategoryDescription'),
false,
false,
['ToolbarSet' => 'test_category', 'Height' => '200']
['ToolbarSet' => 'TestQuestionDescription', 'Height' => '200']
);
$form->addButtonCreate(get_lang('AddTestCategory'), 'SubmitNote');
// setting the rules

@ -548,7 +548,8 @@ function lp_upload_quiz_action_handling()
$lpObject = Session::read('lpobject');
if (!empty($lpObject)) {
$oLP = unserialize($lpObject);
/** @var learnpath $oLP */
$oLP = UnserializeApi::unserialize('lp', $lpObject);
if (is_object($oLP)) {
if ((empty($oLP->cc)) || $oLP->cc != api_get_course_id()) {
$oLP = null;

@ -15,7 +15,6 @@ api_protect_course_script(true);
/* Libraries & config files */
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
require_once api_get_path(SYS_CODE_PATH).'forum/forumconfig.inc.php';
/* MAIN CODE */
$group_id = api_get_group_id();
$user_id = api_get_user_id();

@ -2,6 +2,7 @@
/* For licensing terms, see /license.txt */
// not used??
exit;
require_once '../inc/global.inc.php';
@ -28,6 +29,11 @@ $d_id = (int) $d_id;
$d_number = (int) $d_number;
$sql4 = "UPDATE set_module SET cal_day_num = $d_number WHERE id = $d_id ";
Database::query($sql4);
print_r(unserialize(Security::remove_XSS($_POST['aaa'])));
print_r(
UnserializeApi::unserialize(
'not_allowed_classes',
Security::remove_XSS($_POST['aaa'])
)
);
Display::display_footer();

@ -27,7 +27,7 @@ $doc_url = $_GET['file'];
$doc_url = str_replace('///', '&', $doc_url);
//still a space present? it must be a '+' (that got replaced by mod_rewrite)
$doc_url = str_replace(' ', '+', $doc_url);
$doc_url = str_replace('/..', '', $doc_url); //echo $doc_url;
$doc_url = str_replace('/..', '', $doc_url);
$tbl_forum_attachment = Database::get_course_table(TABLE_FORUM_ATTACHMENT);
$tbl_forum_post = Database::get_course_table(TABLE_FORUM_POST);

@ -127,7 +127,7 @@ $htmlHeadXtra[] = <<<JS
$('[name="thread_qualify_gradebook"]:checkbox').change(function () {
if (this.checked) {
$('#options_field').show();
} else {
} else {
$('#options_field').hide();
$("[name='numeric_calification']").val(0);
$("[name='calification_notebook_title']").val('');

@ -128,7 +128,7 @@ function handle_forum_and_forumcategories($lp_id = null)
// Edit a forum category
if (($action_forum_cat == 'edit' && $get_content == 'forumcategory') ||
(isset($_POST['SubmitEditForumCategory'])) ? true : false
(isset($_POST['SubmitEditForumCategory'])) ? true : false
) {
$forum_category = get_forum_categories($get_id);
$content = show_edit_forumcategory_form($forum_category);
@ -3337,9 +3337,9 @@ function show_add_post_form($current_forum, $action, $id = '', $form_values = ''
$defaults['post_text'] = '<div>&nbsp;</div>
<div style="margin: 5px;">
<div style="font-size: 90%; font-style: italic;">'.
get_lang('Quoting').' '.$posterName.':</div>
get_lang('Quoting').' '.$posterName.':</div>
<div style="color: #006600; font-size: 90%; font-style: italic; background-color: #FAFAFA; border: #D1D7DC 1px solid; padding: 3px;">'.
prepare4display($values['post_text']).'
prepare4display($values['post_text']).'
</div>
</div>
<div>&nbsp;</div>
@ -3403,6 +3403,11 @@ function show_add_post_form($current_forum, $action, $id = '', $form_values = ''
}
if ($postId) {
$postInfo = get_post_information($postId);
if ($postInfo) {
$threadId = $postInfo['thread_id'];
}
if (isset($values['give_revision']) && $values['give_revision'] == 1) {
$extraFieldValues = new ExtraFieldValue('forum_post');
$params = [
@ -4417,26 +4422,22 @@ function send_notification_mails($forumId, $thread_id, $reply_info)
$current_forum_category = null;
if (isset($current_forum['forum_category'])) {
$current_forum_category = get_forumcategory_information(
$current_forum['forum_category']
);
$current_forum_category = get_forumcategory_information($current_forum['forum_category']);
}
$send_mails = false;
if ($current_thread['visibility'] == '1' &&
$current_forum['visibility'] == '1' &&
($current_forum_category && $current_forum_category['visibility'] == '1') &&
$current_forum['approval_direct_post'] != '1'
) {
$send_mails = true;
} else {
$send_mails = false;
}
// The forum category, the forum, the thread and the reply are visible to the user
if ($send_mails) {
if (!empty($forumId)) {
send_notifications($forumId, $thread_id);
}
if ($send_mails && !empty($forumId)) {
$postId = isset($reply_info['new_post_id']) ? $reply_info['new_post_id'] : 0;
send_notifications($forumId, $thread_id, $postId);
} else {
$table_notification = Database::get_course_table(TABLE_FORUM_NOTIFICATION);
if (isset($current_forum['forum_id'])) {
@ -4506,7 +4507,8 @@ function handle_mail_cue($content, $id)
$result = Database::query($sql);
while ($row = Database::fetch_array($result)) {
send_mail($row, get_thread_information($post_info['forum_id'], $post_info['thread_id']));
$forumInfo = get_forum_information($post_info['forum_id']);
send_mail($row, $forumInfo, get_thread_information($post_info['forum_id'], $post_info['thread_id']), $post_info);
}
} elseif ($content == 'thread') {
// Sending the mail to all the users that wanted to be informed for replies on this thread.
@ -4523,7 +4525,8 @@ function handle_mail_cue($content, $id)
GROUP BY users.email";
$result = Database::query($sql);
while ($row = Database::fetch_array($result)) {
send_mail($row, get_thread_information($row['forum_id'], $id));
$forumInfo = get_forum_information($row['forum_id']);
send_mail($row, $forumInfo, get_thread_information($row['forum_id'], $id));
}
// Deleting the relevant entries from the mailcue.
@ -4554,28 +4557,58 @@ function handle_mail_cue($content, $id)
*
* @param array
* @param array
* @param array
* @param array
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version february 2006, dokeos 1.8
*/
function send_mail($user_info = [], $thread_information = [])
function send_mail($userInfo, $forumInfo, $thread_information, $postInfo = [])
{
if (empty($userInfo) || empty($forumInfo) || empty($thread_information)) {
return false;
}
$_course = api_get_course_info();
$user_id = api_get_user_id();
$subject = get_lang('NewForumPost').' - '.$_course['official_code'];
$thread_link = '';
if (isset($thread_information) && is_array($thread_information)) {
$thread_link = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$thread_information['forum_id'].'&thread='.$thread_information['thread_id'];
$thread_link = api_get_path(WEB_CODE_PATH).
'forum/viewthread.php?'.api_get_cidreq().'&forum='.$thread_information['forum_id'].'&thread='.$thread_information['thread_id'];
}
$email_body = get_lang('Dear').' '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS).", <br />\n\r";
$email_body .= get_lang('NewForumPost')."\n";
$email_body .= get_lang('Course').': '.$_course['name'].' - ['.$_course['official_code']."] - <br />\n";
$email_body = get_lang('Dear').' '.api_get_person_name($userInfo['firstname'], $userInfo['lastname'], null, PERSON_NAME_EMAIL_ADDRESS).", <br />\n\r";
$email_body .= get_lang('NewForumPost').': '.$forumInfo['forum_title'].' - '.$thread_information['thread_title']." <br />\n";
$courseId = api_get_configuration_value('global_forums_course_id');
$subject = get_lang('NewForumPost').' - '.$_course['official_code'].': '.$forumInfo['forum_title'].' - '.$thread_information['thread_title']." <br />\n";
$courseInfoTitle = get_lang('Course').': '.$_course['name'].' - ['.$_course['official_code']."] - <br />\n";
if (!empty($courseId) && $_course['real_id'] == $courseId) {
$subject = get_lang('NewForumPost').': '.$forumInfo['forum_title'].' - '.$thread_information['thread_title']." <br />\n";
$courseInfoTitle = " <br />\n";
}
$email_body .= $courseInfoTitle;
if (!empty($postInfo) && isset($postInfo['post_text'])) {
$text = cut(strip_tags($postInfo['post_text']), 100);
if (!empty($text)) {
$email_body .= get_lang('Message').": <br />\n ";
$email_body .= $text;
$email_body .= "<br /><br />\n";
}
}
$email_body .= get_lang('YouWantedToStayInformed')."<br />\n";
$email_body .= get_lang('ThreadCanBeFoundHere')." : <br /><a href=\"".$thread_link."\">".$thread_link."</a>\n";
if ($user_info['user_id'] != $user_id) {
if (!empty($thread_link)) {
$email_body .= get_lang('ThreadCanBeFoundHere')." : <br /><a href=\"".$thread_link."\">".$thread_link."</a>\n";
}
if ($userInfo['user_id'] != $user_id) {
MessageManager::send_message(
$user_info['user_id'],
$userInfo['user_id'],
$subject,
$email_body,
[],
@ -5702,19 +5735,19 @@ function get_notifications($content, $id)
*/
function send_notifications($forum_id = 0, $thread_id = 0, $post_id = 0)
{
$_course = api_get_course_info();
//$_course = api_get_course_info();
$forumCourseId = api_get_configuration_value('global_forums_course_id');
/*$forumCourseId = api_get_configuration_value('global_forums_course_id');
if (!empty($forumCourseId)) {
if ($_course['real_id'] == $forumCourseId) {
return false;
}
}
}*/
$forum_id = (int) $forum_id;
// The content of the mail
$thread_link = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum_id.'&thread='.$thread_id;
//$thread_link = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum_id.'&thread='.$thread_id;
// Users who subscribed to the forum
if ($forum_id != 0) {
@ -5724,33 +5757,27 @@ function send_notifications($forum_id = 0, $thread_id = 0, $post_id = 0)
}
$current_thread = get_thread_information($forum_id, $thread_id);
$current_forum = get_forum_information($current_thread['forum_id']);
$subject = get_lang('NewForumPost').' - '.$_course['official_code'].' - '.$current_forum['forum_title'].' - '.$current_thread['thread_title'];
//$current_forum = get_forum_information($current_thread['forum_id']);
//$subject = get_lang('NewForumPost').' - '.$_course['official_code'].' - '.$current_forum['forum_title'].' - '.$current_thread['thread_title'];
// User who subscribed to the thread
if ($thread_id != 0) {
$users_to_be_notified_by_thread = get_notifications('thread', $thread_id);
}
$postInfo = [];
if (!empty($post_id)) {
$postInfo = get_post_information($post_id);
}
// Merging the two
$users_to_be_notified = array_merge($users_to_be_notified_by_forum, $users_to_be_notified_by_thread);
$sender_id = api_get_user_id();
$forumInfo = get_forum_information($forum_id);
if (is_array($users_to_be_notified)) {
foreach ($users_to_be_notified as $value) {
$user_info = api_get_user_info($value['user_id']);
$email_body = get_lang('Dear').' '.api_get_person_name($user_info['firstname'], $user_info['lastname'], null, PERSON_NAME_EMAIL_ADDRESS).", <br />\n\r";
$email_body .= get_lang('NewForumPost').": ".$current_forum['forum_title'].' - '.$current_thread['thread_title']." <br />\n";
$email_body .= get_lang('Course').': '.$_course['name'].' - ['.$_course['official_code']."] <br />\n";
$email_body .= get_lang('YouWantedToStayInformed')."<br />\n";
$email_body .= get_lang('ThreadCanBeFoundHere').': <br /> <a href="'.$thread_link.'">'.$thread_link."</a>\n";
MessageManager::send_message_simple(
$value['user_id'],
$subject,
$email_body,
$sender_id
);
$userInfo = api_get_user_info($value['user_id']);
send_mail($userInfo, $forumInfo, $current_thread, $postInfo);
}
}
}
@ -6035,7 +6062,7 @@ function get_all_post_from_user($user_id, $course_code)
Display::return_icon('forum.gif', get_lang('Forum')).'&nbsp;'.Security::remove_XSS($forum['forum_title'], STUDENT).
'<div style="float:right;margin-top:-35px">
<a href="../forum/viewforum.php?'.api_get_cidreq_params($course_code).'&forum='.$forum['forum_id'].' " >'.
get_lang('SeeForum').'
get_lang('SeeForum').'
</a>
</div></div>';
$forum_results .= '<br / >';

@ -49,7 +49,6 @@ $_user = api_get_user_info();
$hideNotifications = api_get_course_setting('hide_forum_notifications');
$hideNotifications = $hideNotifications == 1;
// Including necessary files.
require_once 'forumfunction.inc.php';
if (api_is_in_gradebook()) {

@ -158,7 +158,6 @@ $logInfo = [
'tool_id' => $forumId,
'tool_id_detail' => $threadId,
'action' => !empty($my_action) ? $my_action : 'reply',
'action_details' => '',
];
Event::registerLog($logInfo);

@ -44,7 +44,7 @@ function hidecontent(content){
// The section (tabs)
$this_section = SECTION_COURSES;
// Notification for unauthorized people.
// Including additional library scripts.
$nameTools = get_lang('ToolForum');
$_user = api_get_user_info();

@ -28,6 +28,7 @@ $my_search = null;
$forumId = isset($_GET['forum']) ? (int) $_GET['forum'] : 0;
$threadId = isset($_GET['thread']) ? (int) $_GET['thread'] : 0;
/* MAIN DISPLAY SECTION */
/* Retrieving forum and forum category information */
@ -83,7 +84,7 @@ $logInfo = [
];
Event::registerLog($logInfo);
$currentUrl = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?forum='.$forumId.'&'.api_get_cidreq().'&thread='.intval($threadId);
$currentUrl = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?forum='.$forumId.'&'.api_get_cidreq().'&thread='.$threadId;
switch ($my_action) {
case 'delete':
@ -152,7 +153,7 @@ if (!empty($groupId)) {
'name' => Security::remove_XSS($current_forum['forum_title']),
];
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'forum/viewthread.php?forum='.$forumId.'&'.api_get_cidreq().'&thread='.intval($threadId),
'url' => api_get_path(WEB_CODE_PATH).'forum/viewthread.php?forum='.$forumId.'&'.api_get_cidreq().'&thread='.$threadId,
'name' => Security::remove_XSS($current_thread['thread_title']),
];
} else {
@ -177,7 +178,7 @@ if (!empty($groupId)) {
'name' => Security::remove_XSS($current_forum['forum_title']),
];
$interbreadcrumb[] = [
'url' => '#', 'name' => Security::remove_XSS($current_thread['thread_title']),
'url' => '#',
'name' => Security::remove_XSS($current_thread['thread_title']),
];
}
@ -188,95 +189,80 @@ if (!empty($groupId)) {
if (!api_is_allowed_to_edit(false, true) &&
($current_forum['visibility'] == 0 || $current_thread['visibility'] == 0)
) {
api_not_allowed(false);
api_not_allowed();
}
// this increases the number of times the thread has been viewed
increase_thread_view($threadId);
increase_thread_view($threadId);
/* Actions */
if ($origin == 'learnpath') {
$template = new Template('', false, false, true, true, false);
} else {
$template = new Template();
}
if ($origin == 'learnpath') {
$template = new Template('', false, false, true, true, false);
} else {
$template = new Template();
}
$actions = '<span style="float:right;">'.search_link().'</span>';
if ($origin != 'learnpath') {
$actions .= '<a href="'.$forumUrl.'viewforum.php?forum='.$forumId.'&'.api_get_cidreq().'">'
.Display::return_icon('back.png', get_lang('BackToForum'), '', ICON_SIZE_MEDIUM).'</a>';
}
if ($origin != 'learnpath') {
$actions .= '<a href="'.$forumUrl.'viewforum.php?forum='.$forumId.'&'.api_get_cidreq().'">'
.Display::return_icon('back.png', get_lang('BackToForum'), '', ICON_SIZE_MEDIUM).'</a>';
}
// The reply to thread link should only appear when the forum_category is
// not locked AND the forum is not locked AND the thread is not locked.
// If one of the three levels is locked then the link should not be displayed.
if (($current_forum_category &&
$current_forum_category['locked'] == 0) &&
$current_forum['locked'] == 0 &&
$current_thread['locked'] == 0 ||
api_is_allowed_to_edit(false, true)
) {
// The link should only appear when the user is logged in or when anonymous posts are allowed.
if ($_user['user_id'] || ($current_forum['allow_anonymous'] == 1 && !$_user['user_id'])) {
// reply link
if (!api_is_anonymous() && api_is_allowed_to_session_edit(false, true)) {
$actions .= '<a href="'.$forumUrl.'reply.php?'.api_get_cidreq().'&forum='.$forumId.'&thread='
.intval($threadId).'&action=replythread">'
.Display::return_icon('reply_thread.png', get_lang('ReplyToThread'), '', ICON_SIZE_MEDIUM)
.'</a>';
}
// new thread link
if ((
api_is_allowed_to_edit(false, true) &&
!(api_is_session_general_coach() && $current_forum['session_id'] != $sessionId)
) ||
($current_forum['allow_new_threads'] == 1 && isset($_user['user_id'])) ||
($current_forum['allow_new_threads'] == 1 && !isset($_user['user_id']) && $current_forum['allow_anonymous'] == 1)
) {
if ($current_forum['locked'] != 1 && $current_forum['locked'] != 1) {
$actions .= '&nbsp;&nbsp;';
} else {
$actions .= get_lang('ForumLocked');
}
// The reply to thread link should only appear when the forum_category is
// not locked AND the forum is not locked AND the thread is not locked.
// If one of the three levels is locked then the link should not be displayed.
if (($current_forum_category &&
$current_forum_category['locked'] == 0) &&
$current_forum['locked'] == 0 &&
$current_thread['locked'] == 0 ||
api_is_allowed_to_edit(false, true)
) {
// The link should only appear when the user is logged in or when anonymous posts are allowed.
if ($_user['user_id'] || ($current_forum['allow_anonymous'] == 1 && !$_user['user_id'])) {
// reply link
if (!api_is_anonymous() && api_is_allowed_to_session_edit(false, true)) {
$actions .= '<a href="'.$forumUrl.'reply.php?'.api_get_cidreq().'&forum='.$forumId.'&thread='
.$threadId.'&action=replythread">'
.Display::return_icon('reply_thread.png', get_lang('ReplyToThread'), '', ICON_SIZE_MEDIUM)
.'</a>';
}
// new thread link
if ((
api_is_allowed_to_edit(false, true) &&
!(api_is_session_general_coach() && $current_forum['session_id'] != $sessionId)) ||
($current_forum['allow_new_threads'] == 1 && isset($_user['user_id'])) ||
($current_forum['allow_new_threads'] == 1 && !isset($_user['user_id']) && $current_forum['allow_anonymous'] == 1)
) {
if ($current_forum['locked'] != 1 && $current_forum['locked'] != 1) {
$actions .= '&nbsp;&nbsp;';
} else {
$actions .= get_lang('ForumLocked');
}
}
}
// The different views of the thread.
if ($origin != 'learnpath') {
/*$actions .= '<a href="'.$forumUrl.'viewthread.php?'.api_get_cidreq().'&'.api_get_cidreq()
.'&forum='.intval($forumId).'&thread='.intval($threadId)
.'&search='.Security::remove_XSS(urlencode($my_search));
echo $my_url.'&view=flat">'
.Display::return_icon('forum_listview.png', get_lang('FlatView'), null, ICON_SIZE_MEDIUM)
.'</a>';
/*
echo $my_url.'&view=nested">'
.Display::return_icon('forum_nestedview.png', get_lang('NestedView'), null, ICON_SIZE_MEDIUM)
.'</a>';*/
}
}
$template->assign('forum_actions', $actions);
$template->assign('origin', api_get_origin());
/* Display Forum Category and the Forum information */
if (!isset($_SESSION['view'])) {
$viewMode = $current_forum['default_view'];
} else {
$viewMode = $_SESSION['view'];
}
/* Display Forum Category and the Forum information */
if (!isset($_SESSION['view'])) {
$viewMode = $current_forum['default_view'];
} else {
$viewMode = $_SESSION['view'];
}
$whiteList = ['flat', 'threaded', 'nested'];
if (isset($_GET['view']) && in_array($_GET['view'], $whiteList)) {
$viewMode = $_GET['view'];
$_SESSION['view'] = $viewMode;
}
$whiteList = ['flat', 'threaded', 'nested'];
if (isset($_GET['view']) && in_array($_GET['view'], $whiteList)) {
$viewMode = $_GET['view'];
$_SESSION['view'] = $viewMode;
}
if (empty($viewMode)) {
$viewMode = 'flat';
}
if (empty($viewMode)) {
$viewMode = 'flat';
}
if ($current_thread['thread_peer_qualify'] == 1) {
Display::addFlash(Display::return_message(get_lang('ForumThreadPeerScoringStudentComment'), 'info'));
}
if ($current_thread['thread_peer_qualify'] == 1) {
Display::addFlash(Display::return_message(get_lang('ForumThreadPeerScoringStudentComment'), 'info'));
}
$allowReport = reportAvailable();
@ -361,7 +347,7 @@ foreach ($posts as $post) {
}
}
$post['user_data'] .= '<div class="text-center">'.$iconStatus.'</div>';
$post['user_data'] .= '<div class="user-type text-center">'.$iconStatus.'</div>';
} else {
if ($allowUserImageForum) {
$post['user_data'] .= '<div class="thumbnail">'.
@ -638,6 +624,17 @@ foreach ($posts as $post) {
$post['current'] = true;
}
// Replace Re: with an icon
$search = [
get_lang('ReplyShort'),
'Re:',
'RE:',
'AW:',
'Aw:',
];
$replace = '<span>'.Display::returnFontAwesomeIcon('mail-reply').'</span>';
$post['post_title'] = str_replace($search, $replace, $post['post_title']);
// The post title
$titlePost = Display::tag('h3', $post['post_title'], ['class' => 'forum_post_title']);
$post['post_title'] = '<a name="post_id_'.$post['post_id'].'"></a>';
@ -675,7 +672,6 @@ foreach ($posts as $post) {
// The post has been displayed => it can be removed from the what's new array
unset($whatsnew_post_info[$current_forum['forum_id']][$current_thread['thread_id']][$post['post_id']]);
unset($_SESSION['whatsnew_post_info'][$current_forum['forum_id']][$current_thread['thread_id']][$post['post_id']]);
$count++;
}

@ -22,24 +22,36 @@ api_protect_course_script(true);
// Additional javascripts.
$htmlHeadXtra[] = GlossaryManager::javascript_glossary();
$htmlHeadXtra[] = '<script>
function setFocus(){
$("#glossary_title").focus();
}
$(document).ready(function () {
var targetUrl;
var export_format;
$("#export-glossary").click(function() {
targetUrl = $(this).attr("href");
setFocus();
$( "#dialog:ui-dialog" ).dialog( "destroy" );
$( "#dialog-confirm" ).dialog({
autoOpen: false,
show: "blind",
resizable: false,
height:300,
modal: true
});
$("#btn-download").click(function() {
export_format = $("input[name=export_format]:checked").val();
location.href = targetUrl+"&export_format="+export_format;
$("#modal-export").modal("hide");
$("#export_opener").click(function() {
var targetUrl = $(this).attr("href");
$( "#dialog-confirm" ).dialog({
width:400,
height:300,
buttons: {
"'.addslashes(get_lang('Download')).'": function() {
var export_format = $("input[name=export_format]:checked").val();
location.href = targetUrl+"&export_format="+export_format;
$( this ).dialog( "close" );
}
}
});
$( "#dialog-confirm" ).dialog("open");
return false;
});
});
</script>';
@ -447,7 +459,7 @@ Display::display_introduction_section(TOOL_GLOSSARY);
echo $content;
$extra = null;
$extra = '<div id="dialog-confirm" title="'.get_lang("ConfirmYourChoice").'">';
$form = new FormValidator(
'report',
'post',
@ -481,28 +493,8 @@ $form->addElement(
);
$form->setDefaults(['export_format' => 'csv']);
$extra .= '
<div class="modal fade" id="modal-export" tabindex="-1" role="dialog" aria-labelledby="exportModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exportModalLabel">'.get_lang("ConfirmYourChoice").'</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">'
.$form->returnForm().
'</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">'.get_lang('Close').'</button>
<button type="button" id="btn-download" class="btn btn-primary">'.get_lang('Download').'</button>
</div>
</div>
</div>
</div>
';
$extra .= $form->returnForm();
$extra .= '</div>';
echo $extra;

@ -96,8 +96,6 @@ if ($form->validate()) {
'tool_id_detail' => 0,
'action' => 'new-cat',
'action_details' => 'parent_id='.$cat->get_parent_id(),
'current_id' => $cat->get_id(),
'info' => '',
];
Event::registerLog($logInfo);
@ -111,8 +109,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => 'add-cat',
'action_details' => Category::getUrl().'selectcat='.$get_select_cat,
'current_id' => $current_id,
'info' => '',
];
Event::registerLog($logInfo);

@ -74,8 +74,6 @@ if ($form->validate()) {
'tool_id_detail' => 0,
'action' => 'new-eval',
'action_details' => 'selectcat='.$eval->get_category_id(),
'current_id' => $eval->get_id(),
'info' => '',
];
Event::registerLog($logInfo);
@ -106,8 +104,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => 'add-eval',
'action_details' => 'selectcat='.$select_cat,
'current_id' => 0,
'info' => '',
];
Event::registerLog($logInfo);

@ -39,7 +39,7 @@ if ($session_id == 0) {
$category = Category :: load($selectCat);
$url = api_get_self().'?selectcat='.$selectCat.'&newtypeselected='.$typeSelected.'&course_code='.api_get_course_id().'&'.api_get_cidreq();
$typeform = new LinkForm(
LinkForm :: TYPE_CREATE,
LinkForm::TYPE_CREATE,
$category[0],
null,
'create_link',
@ -138,8 +138,6 @@ if (isset($typeSelected) && $typeSelected != '0') {
'tool_id_detail' => 0,
'action' => 'new-link',
'action_details' => 'selectcat='.$selectCat,
'current_id' => $link->get_id(),
'info' => '',
];
Event::registerLog($logInfo);
@ -167,8 +165,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => 'add-link',
'action_details' => 'selectcat='.$selectCat,
'current_id' => $current_id,
'info' => '',
];
Event::registerLog($logInfo);

@ -33,8 +33,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => 'edit-weight',
'action_details' => $action_details,
'current_id' => $my_selectcat,
'info' => '',
];
Event::registerLog($logInfo);

@ -98,8 +98,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => 'edit-cat',
'action_details' => $action_details,
'current_id' => $current_id,
'info' => '',
];
Event::registerLog($logInfo);

@ -51,8 +51,6 @@ if ($form->validate()) {
'tool_id_detail' => 0,
'action' => 'edit-eval',
'action_details' => '',
'current_id' => $eval->get_category_id(),
'info' => '',
];
Event::registerLog($logInfo);

@ -111,8 +111,6 @@ if ($form->validate()) {
'tool_id_detail' => 0,
'action' => 'edit-link',
'action_details' => '',
'current_id' => $_GET['editlink'],
'info' => '',
];
Event::registerLog($logInfo);

@ -89,19 +89,18 @@ if (!$displayScore->is_custom() || empty($displays)) {
$stattable = '<table class="data_table" cellspacing="0" cellpadding="3">';
$stattable .= '<tr><th>'.get_lang('ScoringSystem').'</th>';
$stattable .= '<th>'.get_lang('Percentage').'</th>';
$stattable .= '<th>'.get_lang('CountUsers').'</th>';
//$stattable .= '<th>' . get_lang('Statistics') . '</th></tr>';
$stattable .= '<th>'.get_lang('CountUsers').'</th></tr>';
$counter = 0;
foreach ($keys as $key) {
$bar = ($highest_ratio > 0 ? ($nr_items[$key] / $highest_ratio) * 100 : 0);
$stattable .= '<tr class="row_'.($counter % 2 == 0 ? 'odd' : 'even').'">';
$stattable .= '<td width="150">'.$key.'</td>';
$stattable .= '<td width="550">'.Display::bar_progress($bar).'</td>';
$stattable .= '<td align="right">'.$nr_items[$key].'</td>';
$stattable .= '</tr>';
$counter++;
}
$stattable .= '</tr></table>';
$stattable .= '</table>';
echo $stattable;
}
Display :: display_footer();

@ -247,12 +247,7 @@ if (isset($_GET['import'])) {
$values = $import_result_form->exportValues();
$file_type = $_POST['file_type'];
$file_name = $_FILES['import_file']['tmp_name'];
if ($file_type == 'csv') {
$results = Import :: csvToArray($file_name);
} else {
$results = parse_xml_data($file_name);
}
$results = Import :: csvToArray($file_name);
$nr_results_added = 0;
foreach ($results as $index => $importedresult) {
//check username & score

@ -24,7 +24,7 @@ $stud_id = api_get_user_id();
$session_id = api_get_session_id();
$course_id = api_get_course_int_id();
//make sure the destination for scripts is index.php instead of gradebook.php
// Make sure the destination for scripts is index.php instead of gradebook.php
Category::setUrl('index.php');
$this_section = SECTION_COURSES;
@ -119,8 +119,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => $my_actions,
'action_details' => $my_actions_values,
'current_id' => 0,
'info' => '',
];
Event::registerLog($logInfo);
@ -283,7 +281,7 @@ if (isset($_GET['movelink'])) {
}
}
//parameters for categories
// Parameters for categories.
if (isset($_GET['visiblecat'])) {
GradebookUtils::block_students();
@ -322,7 +320,7 @@ if (isset($_GET['deletecat'])) {
$filter_confirm_msg = false;
}
//parameters for evaluations
// Parameters for evaluations.
if (isset($_GET['visibleeval'])) {
GradebookUtils::block_students();
if (isset($_GET['set_visible'])) {
@ -343,7 +341,7 @@ if (isset($_GET['visibleeval'])) {
}
}
//parameters for evaluations
// Parameters for evaluations.
if (isset($_GET['lockedeval'])) {
GradebookUtils::block_students();
$locked = Security::remove_XSS($_GET['lockedeval']);
@ -372,7 +370,7 @@ if (isset($_GET['deleteeval'])) {
$filter_confirm_msg = false;
}
//parameters for links
// Parameters for links.
if (isset($_GET['visiblelink'])) {
GradebookUtils::block_students();
if (isset($_GET['set_visible'])) {
@ -469,7 +467,7 @@ switch ($action) {
break;
}
//actions on the sortabletable
// Actions on the sortabletable.
if (isset($_POST['action'])) {
GradebookUtils::block_students();
$number_of_selected_items = count($_POST['id']);
@ -640,8 +638,8 @@ if (!isset($_GET['exportpdf'])) {
$viewTitle = get_lang('ToolGradebook');
}
}
// LOAD DATA & DISPLAY TABLE
// LOAD DATA & DISPLAY TABLE
$is_platform_admin = api_is_platform_admin();
$is_course_admin = api_is_allowed_to_edit(null, true);
$simple_search_form = '';
@ -703,7 +701,7 @@ if (isset($_GET['studentoverview'])) {
exit;
}
} else {
//Student view
// Student view
//in any other case (no search, no pdf), print the available gradebooks
// Important note: loading a category will actually load the *contents* of
@ -1012,9 +1010,9 @@ if (isset($first_time) && $first_time == 1 && api_is_allowed_to_edit(null, true)
];
if (!empty($loadStats)) {
for ($z = 5; $z < count($loadStats); $z++) {
$gradebookTable->td_attributes[$z] = 'class="text-center"';
}
for ($z = 5; $z < count($loadStats); $z++) {
$gradebookTable->td_attributes[$z] = 'class="text-center"';
}
}
} else {
$gradebookTable->td_attributes = [

@ -18,8 +18,6 @@ $logInfo = [
'tool_id_detail' => 0,
'action' => '',
'action_details' => '',
'current_id' => 0,
'info' => '',
];
Event::registerLog($logInfo);

@ -441,7 +441,7 @@ if ($form->validate()) {
}
// Else display the form
Display :: display_header($nameTools, 'Group');
Display::display_header($nameTools, 'Group');
// actions bar
echo '<div class="actions">';

@ -18,7 +18,6 @@ if (!api_is_allowed_to_edit(false, true)) {
$currentUrl = api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq();
/* Create the groups */
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'create_groups':
@ -28,6 +27,7 @@ if (isset($_POST['action'])) {
if (isset($_POST['same_category']) && $_POST['same_category']) {
$useOnlyFirstCategory = true;
}
for ($i = 0; $i < $_POST['number_of_groups']; $i++) {
$group1['name'] = empty($_POST['group_'.$i.'_name']) ? get_lang('Group').' '.$i : $_POST['group_'.$i.'_name'];
$group1['category'] = isset($_POST['group_'.$i.'_category']) ? $_POST['group_'.$i.'_category'] : null;
@ -55,7 +55,7 @@ if (isset($_POST['action'])) {
);
}
Display::addFlash(Display::return_message(get_lang('GroupsAdded')));
header("Location: ".$currentUrl);
header('Location: '.$currentUrl);
exit;
break;
case 'create_subgroups':
@ -64,13 +64,13 @@ if (isset($_POST['action'])) {
$_POST['number_of_groups']
);
Display::addFlash(Display::return_message(get_lang('GroupsAdded')));
header("Location: ".$currentUrl);
header('Location: '.$currentUrl);
exit;
break;
case 'create_class_groups':
$ids = GroupManager::create_class_groups($_POST['group_category']);
GroupManager::create_class_groups($_POST['group_category']);
Display::addFlash(Display::return_message(get_lang('GroupsAdded')));
header("Location: ".$currentUrl);
header('Location: '.$currentUrl);
exit;
break;
}
@ -81,7 +81,7 @@ $interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'group/group.php?'.api_get_cidreq(),
'name' => get_lang('Groups'),
];
Display :: display_header($nameTools, 'Group');
Display::display_header($nameTools, 'Group');
if (isset($_POST['number_of_groups'])) {
if (!is_numeric($_POST['number_of_groups']) || intval($_POST['number_of_groups']) < 1) {
@ -254,72 +254,88 @@ EOT;
/*
* Show form to generate subgroups
*/
if (api_get_setting('allow_group_categories') === 'true' && count(GroupManager :: get_group_list()) > 0) {
$base_group_options = [];
$groups = GroupManager :: get_group_list();
foreach ($groups as $index => $group) {
$number_of_students = GroupManager :: number_of_students($group['id']);
if ($number_of_students > 0) {
$base_group_options[$group['id']] = $group['name'].' ('.$number_of_students.' '.get_lang('Users').')';
if (api_get_setting('allow_group_categories') === 'true') {
$groups = GroupManager::get_group_list();
if (!empty($groups)) {
$base_group_options = [];
foreach ($groups as $index => $group) {
$number_of_students = GroupManager::number_of_students($group['id']);
if ($number_of_students > 0) {
$base_group_options[$group['id']] =
$group['name'].' ('.$number_of_students.' '.get_lang('Users').')';
}
}
if (count($base_group_options) > 0) {
$create_subgroups_form = new FormValidator(
'create_subgroups',
'post',
api_get_self().'?'.api_get_cidreq()
);
$create_subgroups_form->addElement('header', get_lang('CreateSubgroups'));
$create_subgroups_form->addElement('html', get_lang('CreateSubgroupsInfo'));
$create_subgroups_form->addElement('hidden', 'action');
$group_el = [];
$group_el[] = $create_subgroups_form->createElement(
'static',
null,
null,
get_lang('CreateNumberOfGroups')
);
$group_el[] = $create_subgroups_form->createElement('text', 'number_of_groups', null, ['size' => 3]);
$group_el[] = $create_subgroups_form->createElement('static', null, null, get_lang('WithUsersFrom'));
$group_el[] = $create_subgroups_form->createElement('select', 'base_group', null, $base_group_options);
$group_el[] = $create_subgroups_form->addButtonSave(get_lang('Ok'), 'submit', true);
$create_subgroups_form->addGroup($group_el, 'create_groups', null, null, false);
$defaults = [];
$defaults['action'] = 'create_subgroups';
$create_subgroups_form->setDefaults($defaults);
$create_subgroups_form->display();
}
}
if (count($base_group_options) > 0) {
$create_subgroups_form = new FormValidator('create_subgroups', 'post', api_get_self().'?'.api_get_cidreq());
$create_subgroups_form->addElement('header', get_lang('CreateSubgroups'));
$create_subgroups_form->addElement('html', get_lang('CreateSubgroupsInfo'));
$create_subgroups_form->addElement('hidden', 'action');
$group_el = [];
$group_el[] = $create_subgroups_form->createElement('static', null, null, get_lang('CreateNumberOfGroups'));
$group_el[] = $create_subgroups_form->createElement('text', 'number_of_groups', null, ['size' => 3]);
$group_el[] = $create_subgroups_form->createElement('static', null, null, get_lang('WithUsersFrom'));
$group_el[] = $create_subgroups_form->createElement('select', 'base_group', null, $base_group_options);
$group_el[] = $create_subgroups_form->createElement('button', 'submit', get_lang('Ok'));
$create_subgroups_form->addGroup($group_el, 'create_groups', null, null, false);
$defaults = [];
$defaults['action'] = 'create_subgroups';
$create_subgroups_form->setDefaults($defaults);
$create_subgroups_form->display();
}
}
/*
* Show form to generate groups from classes subscribed to the course
*/
$options['where'] = [" usergroup.course_id = ? " => api_get_course_int_id()];
$options['where'] = [' usergroup.course_id = ? ' => api_get_course_int_id()];
$obj = new UserGroup();
$classes = $obj->getUserGroupInCourse($options);
if (count($classes) > 0) {
echo '<b>'.get_lang('GroupsFromClasses').'</b>';
echo '<blockquote>';
echo '<p>'.get_lang('GroupsFromClassesInfo').'</p>';
echo '<ul>';
$description = '<p>'.get_lang('GroupsFromClassesInfo').'</p>';
$description .= '<ul>';
foreach ($classes as $index => $class) {
$number_of_users = count($obj->get_users_by_usergroup($class['id']));
echo '<li>';
echo $class['name'];
echo ' ('.$number_of_users.' '.get_lang('Users').')';
echo '</li>';
$description .= '<li>';
$description .= $class['name'];
$description .= ' ('.$number_of_users.' '.get_lang('Users').')';
$description .= '</li>';
}
echo '</ul>';
$description .= '</ul>';
$classForm = new FormValidator(
'create_class_groups_form',
'post',
api_get_self().'?'.api_get_cidreq()
);
$classForm->addHeader(get_lang('GroupsFromClasses'));
$create_class_groups_form = new FormValidator('create_class_groups_form', 'post', api_get_self().'?'.api_get_cidreq());
$create_class_groups_form->addElement('hidden', 'action');
$classForm->addHtml($description);
$classForm->addElement('hidden', 'action');
if (api_get_setting('allow_group_categories') === 'true') {
$group_categories = GroupManager :: get_categories();
$cat_options = [];
foreach ($group_categories as $index => $category) {
$cat_options[$category['id']] = $category['title'];
}
$create_class_groups_form->addElement('select', 'group_category', null, $cat_options);
$classForm->addElement('select', 'group_category', null, $cat_options);
} else {
$create_class_groups_form->addElement('hidden', 'group_category');
$classForm->addElement('hidden', 'group_category');
}
$create_class_groups_form->addElement('submit', 'submit', get_lang('Ok'));
$classForm->addButtonSave(get_lang('Ok'));
$defaults['group_category'] = GroupManager::DEFAULT_GROUP_CATEGORY;
$defaults['action'] = 'create_class_groups';
$create_class_groups_form->setDefaults($defaults);
$create_class_groups_form->display();
echo '</blockquote>';
$classForm->setDefaults($defaults);
$classForm->display();
}
}

@ -15,11 +15,8 @@ $current_course_tool = TOOL_GROUP;
// Notice for unauthorized people.
api_protect_course_script(true);
/* Libraries & config files */
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
require_once api_get_path(SYS_CODE_PATH).'forum/forumconfig.inc.php';
/* MAIN CODE */
$group_id = api_get_group_id();
$user_id = api_get_user_id();
$current_group = GroupManager::get_group_properties($group_id);

@ -38,7 +38,8 @@ $form->addElement(
null,
Display::url(
get_lang('ExampleCSVFile'),
api_get_path(WEB_CODE_PATH).'group/example.csv'
api_get_path(WEB_CODE_PATH).'group/example.csv',
['download' => true]
)
);
$form->addButtonImport(get_lang('Import'));

@ -323,10 +323,10 @@ if ($form->validate()) {
$max_member != GroupManager::MEMBER_PER_GROUP_NO_LIMIT
) {
Display::addFlash(Display::return_message(get_lang('GroupTooMuchMembers'), 'warning'));
header('Location: group.php?'.api_get_cidreq(true, false));
header('Location: group.php?'.api_get_cidreq(true, false).'&category='.$categoryId);
} else {
Display::addFlash(Display::return_message(get_lang('GroupSettingsModified'), 'success'));
header('Location: group.php?'.api_get_cidreq(true, false).'&category='.$cat['id']);
header('Location: group.php?'.api_get_cidreq(true, false).'&category='.$categoryId);
}
exit;
}

@ -8,74 +8,66 @@ $_dont_save_user_course_access = true;
require_once __DIR__.'/../global.inc.php';
api_block_anonymous_users();
if (api_get_setting('allow_global_chat') == 'false') {
exit;
}
if (api_is_anonymous()) {
exit;
}
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
// Course Chat
if ($action == 'preview') {
if ($action === 'preview') {
echo CourseChatUtils::prepareMessage($_REQUEST['message']);
exit;
}
$toUserId = isset($_REQUEST['to']) ? $_REQUEST['to'] : null;
$message = isset($_REQUEST['message']) ? $_REQUEST['message'] : null;
if (!isset($_SESSION['chatHistory'])) {
$_SESSION['chatHistory'] = [];
}
if (!isset($_SESSION['openChatBoxes'])) {
$_SESSION['openChatBoxes'] = [];
}
$currentUserId = api_get_user_id();
$chat = new Chat();
if (Chat::disableChat()) {
exit;
}
if ($chat->isChatBlockedByExercises()) {
// Disconnecting the user
$chat->setUserStatus(0);
exit;
}
switch ($action) {
case 'get_message_status':
$messageId = isset($_REQUEST['message_id']) ? $_REQUEST['message_id'] : 0;
$messageInfo = $chat->get($messageId);
if ($messageInfo && $messageInfo['from_user'] == $currentUserId) {
echo json_encode($messageInfo);
}
break;
case 'chatheartbeat':
$chat->heartbeat();
break;
case 'closechat':
$chat->close();
break;
case 'sendchat':
$chat->send(api_get_user_id(), $toUserId, $message);
break;
case 'startchatsession':
$chat->startSession();
break;
case 'get_previous_messages':
$userId = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;
$visibleMessages = isset($_REQUEST['visible_messages']) ? $_REQUEST['visible_messages'] : null;
if (empty($userId)) {
return '';
}
$items = $chat->getPreviousMessages(
$userId,
api_get_user_id(),
$visibleMessages
);
echo json_encode($items);
case 'close_window':
// Closes friend window
$chatId = isset($_POST['chatbox']) ? $_POST['chatbox'] : '';
$chat->closeWindow($chatId);
echo '1';
exit;
break;
case 'set_status':
$status = isset($_REQUEST['status']) ? (int) $_REQUEST['status'] : 0;
$chat->setUserStatus($status);
case 'close':
// Disconnects user from all chat
$chat->close();
echo '1';
exit;
break;
case 'create_room':
$room = VideoChat::getChatRoomByUsers(api_get_user_id(), $toUserId);
if (api_get_configuration_value('hide_chat_video')) {
api_not_allowed();
}
/*$room = VideoChat::getChatRoomByUsers(api_get_user_id(), $toUserId);
if ($room === false) {
$createdRoom = VideoChat::createRoom(api_get_user_id(), $toUserId);
@ -104,16 +96,49 @@ switch ($action) {
false,
false
);
echo Display::tag('p', $videoChatLink, ['class' => 'lead']);*/
break;
case 'get_contacts':
echo $chat->getContacts();
break;
case 'get_previous_messages':
$userId = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;
$visibleMessages = isset($_REQUEST['visible_messages']) ? $_REQUEST['visible_messages'] : 0;
if (empty($userId)) {
return '';
}
$items = $chat->getPreviousMessages(
$userId,
$currentUserId,
$visibleMessages
);
echo Display::tag('p', $videoChatLink, ['class' => 'lead']);
if (!empty($items)) {
sort($items);
echo json_encode($items);
exit;
}
echo json_encode([]);
exit;
break;
case 'notify_not_support':
$chat->send(
api_get_user_id(),
$currentUserId,
$toUserId,
get_lang('TheXUserBrowserDoesNotSupportWebRTC')
);
break;
case 'sendchat':
$chat->send($currentUserId, $toUserId, $message);
break;
case 'startchatsession':
$chat->startSession();
break;
case 'set_status':
$status = isset($_REQUEST['status']) ? (int) $_REQUEST['status'] : 0;
$chat->setUserStatus($status);
break;
default:
echo '';
}

@ -25,7 +25,6 @@ switch ($_REQUEST['action']) {
'tool_id_detail' => 0,
'action' => 'exit',
'action_details' => 'exit-chat',
'current_id' => 0,
'info' => '',
];
Event::registerLog($logInfo);

@ -157,12 +157,12 @@ switch ($action) {
while ($description = Database::fetch_object($result)) {
$descriptions[$description->id] = $description;
}
// Function that displays the details of the course description in html.
$content = CourseManager::get_details_course_description_html(
$descriptions,
$descriptions,
api_get_system_encoding(),
false
);
);
}
}
echo $content;

@ -65,6 +65,117 @@ switch ($action) {
echo json_encode(['items' => $result]);
break;
case 'search_options_from_tags':
$type = isset($_REQUEST['type']) ? $_REQUEST['type'] : null;
$fieldId = isset($_REQUEST['field_id']) ? $_REQUEST['field_id'] : null;
$tag = isset($_REQUEST['tag']) ? $_REQUEST['tag'] : null;
$extraFieldOption = new ExtraFieldOption($type);
$from = isset($_REQUEST['from']) ? $_REQUEST['from'] : '';
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$options = isset($_REQUEST['options']) ? json_decode($_REQUEST['options']) : '';
$extraField = new ExtraField('session');
$result = $extraField->searchOptionsFromTags($from, $search, $options);
$options = [];
$groups = [];
foreach ($result as $data) {
// Try to get the translation
$displayText = $data['display_text'];
$valueToTranslate = str_replace('-', '', $data['value']);
$valueTranslated = str_replace(['[=', '=]'], '', get_lang($valueToTranslate));
if ($valueToTranslate != $valueTranslated) {
$displayText = $valueTranslated;
}
$groups[$displayText][] = [
'id' => $data['id'],
'text' => $data['tag'],
];
}
foreach ($groups as $key => $data) {
$options[] = [
'text' => $key,
'children' => $groups[$key],
];
}
echo json_encode($options);
break;
case 'order':
$variable = isset($_REQUEST['field_variable']) ? $_REQUEST['field_variable'] : '';
$save = isset($_REQUEST['save']) ? $_REQUEST['save'] : '';
$values = isset($_REQUEST['values']) ? json_decode($_REQUEST['values']) : '';
$extraField = new ExtraField('session');
$extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(str_replace('extra_', '', $variable));
$em = Database::getManager();
$search = [
'user' => api_get_user_id(),
'field' => $extraFieldInfo['id'],
];
$extraFieldSavedSearch = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findOneBy($search);
if ($save) {
$extraField = new \Chamilo\CoreBundle\Entity\ExtraFieldSavedSearch('session');
if ($extraFieldSavedSearch) {
$extraFieldSavedSearch->setValue($values);
$em->merge($extraFieldSavedSearch);
$em->flush();
}
}
if ($extraFieldInfo) {
/** @var \Chamilo\CoreBundle\Entity\ExtraFieldSavedSearch $options */
$extraFieldSavedSearch = $em->getRepository('ChamiloCoreBundle:ExtraFieldSavedSearch')->findOneBy($search);
$values = $extraFieldSavedSearch->getValue();
$url = api_get_self().'?a=order&save=1&field_variable='.$variable;
$html = '
<script>
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#link_'.$variable.'" ).on("click", function() {
var newList = [];
$("#sortable").find("li").each(function(){
newList.push($(this).text());
});
var save = JSON.stringify(newList);
$.ajax({
url: "'.$url.'",
dataType: "json",
data: "values="+save,
success: function(data) {
console.log(data);
}
});
alert("'.get_lang('Saved').'");
location.reload();
return false;
});
});
</script>';
$html .= '<ul id="sortable">';
foreach ($values as $value) {
$html .= '<li class="ui-state-default">';
$html .= $value;
$html .= '</li>';
}
$html .= '</ul>';
$html .= Display::url(get_lang('Save'), '#', ['id' => 'link_'.$variable, 'class' => 'btn btn-primary']);
echo $html;
}
break;
default:
exit;
break;

@ -0,0 +1,76 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Responses to AJAX calls.
*/
require_once __DIR__.'/../global.inc.php';
api_protect_course_script(true);
$action = $_REQUEST['a'];
switch ($action) {
case 'translate_html':
$translate = api_get_configuration_value('translate_html');
if (!$translate) {
exit;
}
$languageList = api_get_languages();
$hideAll = '';
foreach ($languageList['all'] as $language) {
$hideAll .= '$("span:lang('.$language['isocode'].')").filter(
function() {
// Ignore ckeditor classes
return !this.className.match(/cke(.*)/);
}).hide();';
}
$userInfo = api_get_user_info();
$languageId = api_get_language_id($userInfo['language']);
$languageInfo = api_get_language_info($languageId);
echo '
$(document).ready(function() {
'.$hideAll.'
var defaultLanguageFromUser = "'.$languageInfo['isocode'].'";
$("span:lang('.$languageInfo['isocode'].')").filter(
function() {
// Ignore ckeditor classes
return !this.className.match(/cke(.*)/);
}).show();
var defaultLanguage = "";
var langFromUserFound = false;
$(this).find("span").filter(
function() {
// Ignore ckeditor classes
return !this.className.match(/cke(.*)/);
}).each(function() {
defaultLanguage = $(this).attr("lang");
if (defaultLanguage) {
$(this).before().next("br").remove();
if (defaultLanguageFromUser == defaultLanguage) {
langFromUserFound = true;
}
}
});
// Show default language
if (langFromUserFound == false && defaultLanguage) {
$("span:lang("+defaultLanguage+")").filter(
function() {
// Ignore ckeditor classes
return !this.className.match(/cke(.*)/);
}).show();
}
});
';
break;
default:
echo '';
}
exit;

@ -0,0 +1,29 @@
<?php
/* For licensing terms, see /license.txt */
require_once __DIR__.'/../global.inc.php';
api_protect_admin_script();
$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
switch ($action) {
case 'select_option':
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
if (!empty($id)) {
$mail = new MailTemplateManager();
$item = $mail->get($id);
echo $item['template'];
} else {
$templateName = isset($_REQUEST['template_name']) ? $_REQUEST['template_name'] : null;
if (!empty($templateName)) {
$templatePath = api_get_path(SYS_CODE_PATH).'template/default/mail/';
if (Security::check_abs_path($templatePath.$templateName, $templatePath)) {
if (file_exists($templatePath.$templateName)) {
echo file_get_contents($templatePath.$templateName);
}
}
}
}
break;
}

@ -73,6 +73,8 @@ if (!in_array(
api_protect_teacher_script(true);
}
$toRemove = ['extra_access_start_date', 'extra_access_end_date'];
// Search features
//@todo move this in the display_class or somewhere else
@ -130,6 +132,8 @@ $searchString = isset($_REQUEST['searchString']) ? $_REQUEST['searchString'] : f
$search = isset($_REQUEST['_search']) ? $_REQUEST['_search'] : false;
$forceSearch = isset($_REQUEST['_force_search']) ? $_REQUEST['_force_search'] : false;
$extra_fields = [];
$accessStartDate = '';
$accessEndDate = '';
$overwriteColumnHeaderExport = [];
if (!empty($searchString)) {
@ -150,6 +154,10 @@ if (($search || $forceSearch) && ($search !== 'false')) {
}
$filters = isset($_REQUEST['filters']) && !is_array($_REQUEST['filters']) ? json_decode($_REQUEST['filters']) : false;
if (isset($_REQUEST['filters2'])) {
$filters = json_decode($_REQUEST['filters2']);
}
if (!empty($filters)) {
if (in_array($action, ['get_questions', 'get_sessions'])) {
switch ($action) {
@ -164,7 +172,25 @@ if (($search || $forceSearch) && ($search !== 'false')) {
if (!empty($type)) {
// Extra field.
$extraField = new ExtraField($type);
foreach ($filters->rules as $key => $data) {
if (empty($data)) {
continue;
}
if ($data->field == 'extra_access_start_date') {
$accessStartDate = $data->data;
}
if ($data->field == 'extra_access_end_date') {
$accessEndDate = $data->data;
}
if (in_array($data->field, $toRemove)) {
unset($filters->rules[$key]);
}
}
$result = $extraField->getExtraFieldRules($filters, 'extra_');
$extra_fields = $result['extra_fields'];
$condition_array = $result['condition_array'];
@ -184,6 +210,7 @@ if (($search || $forceSearch) && ($search !== 'false')) {
$questionFields = $resultQuestion['extra_fields'];
$condition_array = $resultQuestion['condition_array'];
$extraQuestionCondition = '';
if (!empty($condition_array)) {
$extraQuestionCondition = $filters->groupOp.' ( ';
$extraQuestionCondition .= implode($filters->groupOp, $condition_array);
@ -197,6 +224,10 @@ if (($search || $forceSearch) && ($search !== 'false')) {
}
$whereCondition .= $extraQuestionCondition;
if (isset($filters->custom_dates)) {
$whereCondition .= $filters->custom_dates;
}
}
} elseif (!empty($filters->rules)) {
$whereCondition .= ' AND ( ';
@ -739,6 +770,10 @@ switch ($action) {
$obj = new Promotion();
$count = $obj->get_count();
break;
case 'get_mail_template':
$obj = new MailTemplateManager();
$count = $obj->get_count();
break;
case 'get_grade_models':
$obj = new GradeModel();
$count = $obj->get_count();

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save