Surveys: User CSurvey entities + fix queries

pull/3844/head
Julio Montoya 5 years ago
parent b3a74ac0d7
commit 5fe08f86f7
  1. 7
      public/main/inc/ajax/survey.ajax.php
  2. 4
      public/main/inc/lib/display.lib.php
  3. 31
      public/main/inc/lib/sessionmanager.lib.php
  4. 374
      public/main/survey/fillsurvey.php
  5. 41
      public/main/survey/link.php
  6. 74
      public/main/survey/meeting.php
  7. 6
      public/main/survey/pending.php
  8. 28
      public/main/survey/preview.php
  9. 308
      public/main/survey/survey.lib.php
  10. 12
      public/main/survey/survey.php
  11. 423
      public/main/survey/surveyUtil.class.php
  12. 117
      public/main/survey/survey_invitation.php
  13. 112
      public/main/survey/survey_invite.php
  14. 98
      public/main/survey/survey_list.php
  15. 43
      public/main/survey/survey_question.php
  16. 2
      public/main/template/default/survey/pending.html.twig

@ -3,6 +3,7 @@
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use Chamilo\CourseBundle\Entity\CSurveyQuestion;
require_once __DIR__.'/../global.inc.php';
@ -10,6 +11,7 @@ $current_user_id = api_get_user_id();
$courseId = api_get_course_int_id();
$repo = Container::getSurveyRepository();
$repoQuestion = Container::getSurveyQuestionRepository();
$action = $_GET['a'] ?? null;
$surveyId = $_REQUEST['survey_id'] ?? 0;
@ -39,6 +41,9 @@ switch ($action) {
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
/** @var CSurveyQuestion $survey */
$question = $repoQuestion->find($questionId);
if (null === $survey) {
exit;
}
@ -53,7 +58,7 @@ switch ($action) {
SurveyUtil::saveAnswer(
$userId,
$survey,
$questionId,
$question,
1,
$status
);

@ -1639,13 +1639,13 @@ class Display
if (TOOL_SURVEY == $toolName) {
$survey_info = SurveyManager::get_survey($notification['ref'], 0, $course_code);
if (!empty($survey_info)) {
$invited_users = SurveyUtil::get_invited_users(
/*$invited_users = SurveyUtil::get_invited_users(
$survey_info['code'],
$course_code
);
if (!in_array($user_id, $invited_users['course_users'])) {
continue;
}
}*/
}
}

@ -12,6 +12,7 @@ use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
use Chamilo\CoreBundle\Entity\SessionRelUser;
use Chamilo\CoreBundle\Entity\User;
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use ExtraField as ExtraFieldModel;
use Monolog\Logger;
@ -942,10 +943,9 @@ class SessionManager
$date_to,
$options
) {
//escaping vars
$sessionId = intval($sessionId);
$courseId = intval($courseId);
$surveyId = intval($surveyId);
$sessionId = (int) $sessionId;
$courseId = (int) $courseId;
$surveyId = (int) $surveyId;
//tables
$session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
@ -983,14 +983,11 @@ class SessionManager
while ($user = Database::fetch_array($rs)) {
$users[$user['user_id']] = $user;
}
//Get survey questions
$questions = SurveyManager::get_questions($surveyId, $courseId);
//Survey is anonymous?
$result = Database::query(sprintf("SELECT anonymous FROM $c_survey WHERE survey_id = %d", $surveyId));
$row = Database::fetch_array($result);
$anonymous = (1 == $row['anonymous']) ? true : false;
$repo = Container::getSurveyRepository();
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
$questions = $survey->getQuestions();
$anonymous = (1 == $survey->getAnonymous()) ? true : false;
$table = [];
foreach ($users as $user) {
@ -1017,23 +1014,21 @@ class SessionManager
sa.user = %d
"; //. $where_survey;
$sql_query = sprintf($sql, $surveyId, $courseId, $user['user_id']);
$result = Database::query($sql_query);
$user_questions = [];
while ($row = Database::fetch_array($result)) {
$user_questions[$row['question_id']] = $row;
}
//Match course lessons with user progress
foreach ($questions as $question_id => $question) {
foreach ($questions as $question) {
$questionId = $question->getIid();
$option_text = 'option_text';
if ('open' == $user_questions[$question_id]['type']) {
if ('open' === $user_questions[$questionId]['type']) {
$option_text = 'option_id';
}
$data[$question_id] = $user_questions[$question_id][$option_text];
$data[$questionId] = $user_questions[$questionId][$option_text];
}
$table[] = $data;
}

@ -2,6 +2,8 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use ChamiloSession as Session;
$lastQuestion = 0;
@ -55,24 +57,39 @@ if (empty($courseInfo)) {
api_not_allowed(true);
}
$courseId = $courseInfo['real_id'];
$userInfo = api_get_user_info();
$sessionId = isset($_GET['sid']) ? (int) $_GET['sid'] : api_get_session_id();
// Breadcrumbs
if (!empty($userInfo)) {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cid='.$courseInfo['real_id'].'&sid='.$sessionId,
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cid='.$courseId.'&sid='.$sessionId,
'name' => get_lang('Survey list'),
];
}
$course_id = $courseInfo['real_id'];
$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
// First we check if the needed parameters are present
if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
api_not_allowed(true, get_lang('There is a parameter missing in the link. Please use copy and past'));
}
$repo = Container::getSurveyRepository();
$surveyId = isset($_GET['iid']) ? (int) $_GET['iid'] : 0;
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
if (null === $survey) {
api_not_allowed(true);
}
$surveyId = $survey->getIid();
$invitationCode = $_GET['invitationcode'] ?? null;
/*$surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
if ('' != $surveyCode) {
// Firstly we check if this survey is ready for anonymous use:
$sql = "SELECT anonymous FROM $table_survey
WHERE c_id = $course_id AND code ='".$surveyCode."'";
WHERE c_id = $courseId AND code ='".$surveyCode."'";
$resultAnonymous = Database::query($sql);
$rowAnonymous = Database::fetch_array($resultAnonymous, 'ASSOC');
// If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
@ -83,78 +100,68 @@ if ('' != $surveyCode) {
api_not_allowed(true);
}
// If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous.
}
}*/
// First we check if the needed parameters are present
if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
api_not_allowed(true, get_lang('There is a parameter missing in the link. Please use copy and past'));
if ((0 == $survey->getAnonymous() && api_is_anonymous())) {
api_not_allowed(true);
}
$invitationcode = $_GET['invitationcode'];
// Start auto-invitation feature FS#3403 (all-users-can-do-the-survey-URL handling)
if ('auto' === $invitationcode && isset($_GET['scode'])) {
if ('auto' === $invitationCode) {
$userid = api_get_user_id();
// Survey_code of the survey
$surveyCode = $_GET['scode'];
$surveyCode = $survey->getCode();
if ($isAnonymous) {
$autoInvitationcode = 'auto-ANONY_'.md5(time())."-$surveyCode";
$autoInvitationCode = 'auto-ANONY_'.md5(time())."-$surveyCode";
} else {
$invitations = SurveyManager::getUserInvitationsForSurveyInCourse(
$userid,
$surveyCode,
$courseInfo['real_id'],
$courseId,
$sessionId
);
$lastInvitation = current($invitations);
if (!$lastInvitation) {
// New invitation code from userid
$autoInvitationcode = "auto-$userid-$surveyCode";
$autoInvitationCode = "auto-$userid-$surveyCode";
} else {
$autoInvitationcode = $lastInvitation->getInvitationCode();
$autoInvitationCode = $lastInvitation->getInvitationCode();
}
}
// The survey code must exist in this course, or the URL is invalid
$sql = "SELECT * FROM $table_survey
WHERE c_id = $course_id AND code = '".Database::escape_string($surveyCode)."'";
// Check availability.
SurveyManager::checkTimeAvailability($survey);
// Check for double invitation records (insert should be done once)
$sql = "SELECT user
FROM $table_survey_invitation
WHERE
c_id = $courseId AND
invitation_code = '".Database::escape_string($autoInvitationCode)."'";
$result = Database::query($sql);
if (Database :: num_rows($result) > 0) {
// Check availability
$row = Database::fetch_array($result, 'ASSOC');
$tempdata = SurveyManager::get_survey($row['survey_id']);
SurveyManager::checkTimeAvailability($tempdata);
// Check for double invitation records (insert should be done once)
$sql = "SELECT user
FROM $table_survey_invitation
WHERE
c_id = $course_id AND
invitation_code = '".Database::escape_string($autoInvitationcode)."'";
$result = Database::query($sql);
$now = api_get_utc_datetime();
if (0 == Database :: num_rows($result)) {
$params = [
'c_id' => $course_id,
'survey_code' => $surveyCode,
'user' => $userid,
'invitation_code' => $autoInvitationcode,
'invitation_date' => $now,
];
Database::insert($table_survey_invitation, $params);
}
// From here we use the new invitationcode auto-userid-surveycode string
$_GET['invitationcode'] = $autoInvitationcode;
Session::write('auto_invitation_code_'.$surveyCode, $autoInvitationcode);
$invitationcode = $autoInvitationcode;
$now = api_get_utc_datetime();
if (0 == Database::num_rows($result)) {
$params = [
'c_id' => $courseId,
'survey_id' => $surveyId,
'user' => $userid,
'invitation_code' => $autoInvitationCode,
'invitation_date' => $now,
];
Database::insert($table_survey_invitation, $params);
}
// From here we use the new invitationcode auto-userid-surveycode string
$_GET['invitationcode'] = $autoInvitationCode;
Session::write('auto_invitation_code_'.$surveyCode, $autoInvitationCode);
$invitationCode = $autoInvitationCode;
}
// Now we check if the invitation code is valid
$sql = "SELECT * FROM $table_survey_invitation
WHERE
c_id = $course_id AND
invitation_code = '".Database::escape_string($invitationcode)."'";
c_id = $courseId AND
invitation_code = '".Database::escape_string($invitationCode)."'";
$result = Database::query($sql);
if (Database::num_rows($result) < 1) {
api_not_allowed(true, get_lang('Wrong invitation code'));
@ -167,7 +174,7 @@ if (!isset($_POST['finish_survey']) &&
(
$isAnonymous &&
!empty($surveyUserFromSession) &&
SurveyUtil::isSurveyAnsweredFlagged($survey_invitation['survey_code'], $survey_invitation['c_id'])
SurveyUtil::isSurveyAnsweredFlagged($survey->getCode(), $survey_invitation['c_id'])
) ||
(1 == $survey_invitation['answered'] && !isset($_GET['user_id']))
) {
@ -178,7 +185,7 @@ $logInfo = [
'tool' => TOOL_SURVEY,
'tool_id' => $survey_invitation['iid'],
'action' => 'invitationcode',
'action_details' => $invitationcode,
'action_details' => $invitationCode,
];
Event::registerLog($logInfo);
@ -186,9 +193,7 @@ Event::registerLog($logInfo);
// If this is the case there will be a language choice
$sql = "SELECT * FROM $table_survey
WHERE
c_id = $course_id AND
code = '".Database::escape_string($survey_invitation['survey_code'])."'";
$sql .= api_get_session_condition($sessionId);
code = '".Database::escape_string($survey->getCode())."'";
$result = Database::query($sql);
if (Database::num_rows($result) > 1) {
@ -213,49 +218,35 @@ if (Database::num_rows($result) > 1) {
Display::display_footer();
exit();
}
} else {
$row = Database::fetch_array($result, 'ASSOC');
$survey_invitation['survey_id'] = $row['iid'];
}
// Getting the survey information
$survey_data = SurveyManager::get_survey($survey_invitation['survey_id']);
if (empty($survey_data)) {
api_not_allowed(true);
}
// Checking time availability
SurveyManager::checkTimeAvailability($survey_data);
$survey_data['survey_id'] = $survey_invitation['survey_id'];
if ('3' == $survey_data['survey_type']) {
SurveyManager::checkTimeAvailability($survey);
$surveyType = $survey->getSurveyType();
if (3 === $surveyType) {
header('Location: '.
api_get_path(WEB_CODE_PATH).
'survey/meeting.php?cid='.$courseInfo['real_id'].'&sid='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationcode)
'survey/meeting.php?cid='.$courseId.'&sid='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationCode)
);
exit;
}
if (!empty($survey_data['anonymous'])) {
if (!empty($survey->getAnonymous())) {
define('USER_IN_ANON_SURVEY', true);
}
// Storing the answers
if (count($_POST) > 0) {
if ('0' === $survey_data['survey_type']) {
if (0 === $surveyType) {
$types = [];
$required = [];
// Getting all the types of the question
// (because of the special treatment of the score question type
$sql = "SELECT * FROM $table_survey_question
WHERE
c_id = $course_id AND
survey_id = '".intval($survey_invitation['survey_id'])."'";
$result = Database::query($sql);
while ($row = Database::fetch_array($result, 'ASSOC')) {
$types[$row['iid']] = $row['type'];
$required[$row['iid']] = $allowRequiredSurveyQuestions && $row['is_required'];
$questions = $survey->getQuestions();
$questionList = [];
foreach ($questions as $question) {
$id = $question->getIid();
$questionList[$id] = $question;
$types[$id] = $question->getType();
$required[$id] = $allowRequiredSurveyQuestions && $question->isMandatory();
}
// Looping through all the post values
@ -274,6 +265,11 @@ if (count($_POST) > 0) {
}
$other = isset($_POST['other_question'.$survey_question_id]) ? $_POST['other_question'.$survey_question_id] : '';
$question = $questionList[$survey_question_id] ?? null;
if (null === $question) {
continue;
}
/* If the post value is an array then we have a multiple response question or a scoring question type
remark: when it is a multiple response then the value of the array is the option_id
@ -282,9 +278,8 @@ if (count($_POST) > 0) {
if (is_array($value)) {
SurveyUtil::remove_answer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$course_id
$surveyId,
$survey_question_id
);
foreach ($value as $answer_key => &$answer_value) {
@ -296,28 +291,27 @@ if (count($_POST) > 0) {
$option_value = '';
}
SurveyUtil::store_answer(
SurveyUtil::saveAnswer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$survey,
$question,
$option_id,
$option_value,
$survey_data
$option_value
);
}
} else {
// All the other question types (open question, multiple choice, percentage, ...)
if (isset($types[$survey_question_id]) &&
'percentage' === $types[$survey_question_id]) {
$option_value = 0;
if (isset($types[$survey_question_id]) && 'percentage' === $types[$survey_question_id]) {
$sql = "SELECT * FROM $table_survey_question_option
WHERE
c_id = $course_id AND
iid='".intval($value)."'";
$result = Database::query($sql);
$row = Database::fetch_array($result, 'ASSOC');
$option_value = $row['option_text'];
if ($row) {
$option_value = $row['option_text'];
}
} else {
$option_value = 0;
if (isset($types[$survey_question_id]) && 'open' === $types[$survey_question_id]) {
$option_value = $value;
}
@ -326,39 +320,41 @@ if (count($_POST) > 0) {
$survey_question_answer = $value;
SurveyUtil::remove_answer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$course_id
$surveyId,
$survey_question_id
);
SurveyUtil::store_answer(
SurveyUtil::saveAnswer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$survey,
$question,
$value,
$option_value,
$survey_data,
$other
);
}
}
}
} elseif ('1' === $survey_data['survey_type']) {
} elseif (1 === $survey->getSurveyType()) {
//conditional/personality-test type surveys
// Getting all the types of the question (because of the special treatment of the score question type
$shuffle = '';
if ('1' == $survey_data['shuffle']) {
if (1 == $survey->getShuffle()) {
$shuffle = ' ORDER BY RAND() ';
}
$sql = "SELECT * FROM $table_survey_question
/*$sql = "SELECT * FROM $table_survey_question
WHERE
c_id = $course_id AND
survey_id = '".intval($survey_invitation['survey_id'])."' AND
survey_group_pri = '0' $shuffle";
$result = Database::query($sql);
survey_id = $surveyId AND
survey_group_pri = '0'
$shuffle";
$result = Database::query($sql);*/
// There is only one question type for conditional surveys
while ($row = Database::fetch_array($result, 'ASSOC')) {
$types[$row['iid']] = $row['type'];
$types = [];
//while ($row = Database::fetch_array($result, 'ASSOC')) {
$questions = $survey->getQuestions();
$questionList = [];
foreach ($questions as $question) {
$questionList[$question->getIid()] = $question;
}
// Looping through all the post values
@ -375,7 +371,7 @@ if (count($_POST) > 0) {
}
// We select the correct answer and the puntuacion
$sql = "SELECT value FROM $table_survey_question_option
WHERE c_id = $course_id AND iid='".intval($value)."'";
WHERE iid='".intval($value)."'";
$result = Database::query($sql);
$row = Database::fetch_array($result, 'ASSOC');
$option_value = $row['value'];
@ -385,17 +381,15 @@ if (count($_POST) > 0) {
SurveyUtil::remove_answer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$course_id
$survey_question_id
);
SurveyUtil::store_answer(
SurveyUtil::saveAnswer(
$survey_invitation['user'],
$survey_invitation['survey_id'],
$survey_question_id,
$questionList[$survey_question_id],
$value,
$option_value,
$survey_data
$option_value
);
}
}
@ -411,11 +405,11 @@ if (0 == $user_id) {
}
$user_data = api_get_user_info($user_id);
if ('' != $survey_data['form_fields'] &&
0 == $survey_data['anonymous'] &&
if ('' != $survey->getFormFields() &&
0 == $survey->getAnonymous() &&
is_array($user_data)
) {
$form_fields = explode('@', $survey_data['form_fields']);
$form_fields = explode('@', $survey->getFormFields());
$list = [];
foreach ($form_fields as $field) {
$field_value = explode(':', $field);
@ -427,8 +421,8 @@ if ('' != $survey_data['form_fields'] &&
}
}
$url = api_get_self().'?cid='.$courseInfo['real_id'].'&sid='.$sessionId;
$listQueryParams = preg_split('/&/', $_SERVER['QUERY_STRING']);
$url = api_get_self().'?cid='.$courseId.'&sid='.$sessionId;
$listQueryParams = explode('&', $_SERVER['QUERY_STRING']);
foreach ($listQueryParams as $param) {
$url .= '&'.Security::remove_XSS($param);
}
@ -487,8 +481,8 @@ if ('' != $survey_data['form_fields'] &&
}
$form->applyFilter('official_code', 'stripslashes');
$form->applyFilter('official_code', 'trim');
if ('true' == api_get_setting('registration', 'officialcode') &&
'true' == api_get_setting('profile', 'officialcode')
if ('true' === api_get_setting('registration', 'officialcode') &&
'true' === api_get_setting('profile', 'officialcode')
) {
$form->addRule('official_code', get_lang('Required field'), 'required');
}
@ -502,7 +496,7 @@ if ('' != $survey_data['form_fields'] &&
}
$form->applyFilter('email', 'stripslashes');
$form->applyFilter('email', 'trim');
if ('true' == api_get_setting('registration', 'email')) {
if ('true' === api_get_setting('registration', 'email')) {
$form->addRule('email', get_lang('Required field'), 'required');
}
$form->addEmailRule('email');
@ -527,7 +521,7 @@ if ('' != $survey_data['form_fields'] &&
if ('true' !== api_get_setting('profile', 'language')) {
$form->freeze('language');
}
if ('true' == api_get_setting('profile', 'language')) {
if ('true' === api_get_setting('profile', 'language')) {
$form->addRule('language', get_lang('Required field'), 'required');
}
}
@ -559,9 +553,9 @@ Display::display_header(get_lang('Surveys'));
echo '<div class="survey-block">';
echo '<div class="page-header">';
echo '<h2>';
echo strip_tags($survey_data['survey_title'], '<span>').'</h2></div>';
if (!empty($survey_data['survey_subtitle'])) {
echo '<div class="survey_subtitle"><p>'.strip_tags($survey_data['survey_subtitle']).'</p></div>';
echo strip_tags($survey->getTitle(), '<span>').'</h2></div>';
if (!empty($survey->getSubtitle())) {
echo '<div class="survey_subtitle"><p>'.strip_tags($survey->getSubtitle()).'</p></div>';
}
// Displaying the survey introduction
@ -572,14 +566,14 @@ if (
Session::erase('paged_questions');
Session::erase('page_questions_sec');
$paged_questions_sec = [];
if (!empty($survey_data['survey_introduction'])) {
echo '<div class="survey_content">'.Security::remove_XSS($survey_data['survey_introduction']).'</div>';
if (!empty($survey->getIntro())) {
echo '<div class="survey_content">'.Security::remove_XSS($survey->getIntro()).'</div>';
}
$limit = 0;
}
if ($survey_data['form_fields'] &&
0 == $survey_data['anonymous'] &&
if ($survey->getFormFields() &&
0 == $survey->getAnonymous() &&
is_array($user_data) &&
!isset($_GET['show'])
) {
@ -616,7 +610,6 @@ if ($survey_data['form_fields'] &&
$extraFieldValue = new ExtraFieldValue('user');
$extraFieldValue->saveFieldValues($user_data);
echo '<div id="survey_content" class="survey_content">'.
get_lang('Information updated').' '.get_lang('Please fill survey').'</div>';
}
@ -640,18 +633,9 @@ if ($survey_data['form_fields'] &&
// Displaying the survey thanks message
if (isset($_POST['finish_survey'])) {
echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
echo Security::remove_XSS($survey_data['survey_thanks']);
SurveyManager::update_survey_answered(
$survey_data,
$survey_invitation['user'],
$survey_invitation['survey_code']
);
SurveyUtil::flagSurveyAsAnswered(
$survey_invitation['survey_code'],
$survey_invitation['c_id']
);
echo Security::remove_XSS($survey->getSurveythanks());
SurveyManager::updateSurveyAnswered($survey, $survey_invitation['user']);
SurveyUtil::flagSurveyAsAnswered($survey->getCode(), $survey_invitation['c_id']);
if ($courseInfo && !api_is_anonymous()) {
echo '<br /><br />';
@ -670,7 +654,7 @@ if (isset($_POST['finish_survey'])) {
// Sets the random questions
$shuffle = '';
if (1 == $survey_data['shuffle']) {
if (1 == $survey->getShuffle()) {
$shuffle = ' BY RAND() ';
}
@ -691,17 +675,16 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
}
// If non-conditional survey
if ('0' == $survey_data['survey_type']) {
if (0 === $survey->getSurveyType()) {
if (empty($paged_questions)) {
$sql = "SELECT * FROM $table_survey_question
WHERE
survey_question NOT LIKE '%{{%' AND
c_id = $course_id AND
survey_id = '".intval($survey_invitation['survey_id'])."'
survey_id = '".$surveyId."'
ORDER BY sort ASC";
$result = Database::query($sql);
while ($row = Database::fetch_array($result, 'ASSOC')) {
if (1 == $survey_data['one_question_per_page']) {
if (1 == $survey->getOneQuestionPerPage()) {
if ('pagebreak' !== $row['type']) {
$paged_questions[$counter][] = $row['iid'];
$counter++;
@ -721,14 +704,14 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
// Redefinition of variables and session ids to fix issue of survey not
// showing questions - see support.chamilo.org #5529
$course_id = $survey_invitation['c_id'];
Session::write('_cid', $course_id);
Session::write('_real_cid', $course_id);
$courseId = $survey_invitation['c_id'];
Session::write('_cid', $courseId);
Session::write('_real_cid', $courseId);
if (array_key_exists($_GET['show'], $paged_questions)) {
if (isset($_GET['user_id'])) {
// Get the user into survey answer table (user or anonymus)
$my_user_id = 1 == $survey_data['anonymous'] ? $surveyUserFromSession : api_get_user_id();
$my_user_id = 1 == $survey->getAnonymous() ? $surveyUserFromSession : api_get_user_id();
$sql = "SELECT
survey_question.survey_group_sec1,
@ -748,15 +731,15 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
survey_question_option.c_id = $courseId
WHERE
survey_question.survey_id = '".Database::escape_string($survey_invitation['survey_id'])."' AND
survey_question.survey_id = '".$surveyId."' AND
survey_question.iid NOT IN (
SELECT sa.question_id
FROM ".$table_survey_answer." sa
WHERE
sa.user='".$my_user_id."') AND
survey_question.c_id = $course_id
survey_question.c_id = $courseId
ORDER BY survey_question.sort, survey_question_option.sort ASC";
} else {
$sql = "SELECT
@ -777,13 +760,11 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
ON survey_question.iid = survey_question_option.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
survey_question.iid IN (".implode(',', $paged_questions[$_GET['show']]).") AND
survey_question.c_id = $course_id
survey_question.survey_id = '".$surveyId."' AND
survey_question.iid IN (".implode(',', $paged_questions[$_GET['show']]).")
ORDER BY survey_question.sort, survey_question_option.sort ASC";
}
@ -805,8 +786,9 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
$questions[$sort]['maximum_score'] = $row['max_value'];
$questions[$sort]['sort'] = $sort;
$questions[$sort]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
$questions[$sort]['parent_id'] = isset($row['parent_id']) ? $row['parent_id'] : 0;
$questions[$sort]['parent_option_id'] = isset($row['parent_option_id']) ? $row['parent_option_id'] : 0;
$questions[$sort]['parent_id'] = $row['parent_id'] ?? 0;
$questions[$sort]['parent_option_id'] =
isset($row['parent_option_id']) ? $row['parent_option_id'] : 0;
}
$counter++;
if (isset($_GET['show']) && (int) $_GET['show'] >= 0) {
@ -816,7 +798,7 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
}
}
}
} elseif ('1' === $survey_data['survey_type']) {
} elseif (1 === $survey->getSurveyType()) {
$my_survey_id = (int) $survey_invitation['survey_id'];
$current_user = Database::escape_string($survey_invitation['user']);
@ -839,9 +821,7 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
ON (survey_question.iid = survey_answer.question_id)
WHERE
survey_answer.survey_id='".$my_survey_id."' AND
survey_answer.user='".$current_user."' AND
survey_answer.c_id = $course_id AND
survey_question.c_id = $course_id AND
survey_answer.user='".$current_user."'
GROUP BY survey_group_pri
ORDER BY survey_group_pri
";
@ -866,8 +846,8 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
ON (survey_question.iid = survey_question_option.question_id)
WHERE
survey_question.survey_id='".$my_survey_id."' AND
survey_question.c_id = $course_id AND
survey_question_option.c_id = $course_id AND
survey_question.c_id = $courseId AND
survey_question_option.c_id = $courseId AND
survey_group_sec1='0' AND
survey_group_sec2='0'
GROUP BY survey_group_pri, survey_question.iid
@ -996,17 +976,16 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
) {
$sql = "SELECT * FROM $table_survey_question
WHERE
c_id = $course_id AND
survey_id = '".$my_survey_id."' AND
($secondary )
ORDER BY sort ASC";
$result = Database::query($sql);
$counter = 0;
while ($row = Database::fetch_array($result, 'ASSOC')) {
if (1 == $survey_data['one_question_per_page']) {
if (1 == $survey->getOneQuestionPerPage()) {
$paged_questions_sec[$counter][] = $row['question_id'];
$counter++;
} elseif ('pagebreak' == $row['type']) {
} elseif ('pagebreak' === $row['type']) {
$counter++;
$pageBreakText[$counter] = $row['survey_question'];
} else {
@ -1041,11 +1020,9 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".$my_survey_id."' AND
survey_question.c_id = $course_id AND
survey_question.survey_id = '".$my_survey_id."'
survey_question.iid IN (".implode(',', $paged_questions_sec[$val]).")
ORDER $shuffle ";
@ -1056,7 +1033,7 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
$questions = [];
while ($row = Database::fetch_array($result, 'ASSOC')) {
// If the type is not a pagebreak we store it in the $questions array
if ('pagebreak' != $row['type']) {
if ('pagebreak' !== $row['type']) {
$questions[$row['sort']]['question_id'] = $row['question_id'];
$questions[$row['sort']]['survey_id'] = $row['survey_id'];
$questions[$row['sort']]['survey_question'] = $row['survey_question'];
@ -1099,19 +1076,18 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
if (empty($_SESSION['paged_questions'])) {
$sql = "SELECT * FROM $table_survey_question
WHERE
c_id = $course_id AND
survey_id = '".intval($survey_invitation['survey_id'])."' AND
survey_id = '".$surveyId."' AND
survey_group_sec1='0' AND
survey_group_sec2='0'
ORDER ".$order_sql." ";
$result = Database::query($sql);
$counter = 0;
while ($row = Database::fetch_array($result, 'ASSOC')) {
if (1 == $survey_data['one_question_per_page']) {
if (1 == $survey->getOneQuestionPerPage()) {
$paged_questions[$counter][] = $row['question_id'];
$counter++;
} else {
if ('pagebreak' == $row['type']) {
if ('pagebreak' === $row['type']) {
$counter++;
$pageBreakText[$counter] = $row['survey_question'];
} else {
@ -1153,11 +1129,11 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
survey_question_option.c_id = $courseId
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
survey_question.c_id = $course_id AND
survey_question.c_id = $courseId AND
survey_question.iid IN (".$imploded.")
ORDER $order_sql ";
$result = Database::query($sql);
@ -1171,7 +1147,7 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
$questions = [];
while ($row = Database :: fetch_array($result, 'ASSOC')) {
// If the type is not a pagebreak we store it in the $questions array
if ('pagebreak' != $row['type']) {
if ('pagebreak' !== $row['type']) {
$questions[$row['sort']]['question_id'] = $row['question_id'];
$questions[$row['sort']]['survey_id'] = $row['survey_id'];
$questions[$row['sort']]['survey_question'] = $row['survey_question'];
@ -1198,7 +1174,7 @@ if ((isset($_GET['show']) && '' != $_GET['show']) ||
}
}
$numberOfPages = SurveyManager::getCountPages($survey_data);
$numberOfPages = SurveyManager::getCountPages($survey);
// Displaying the form with the questions
$show = 0;
@ -1228,10 +1204,12 @@ $g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationc
$g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
$p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
$add_parameters = isset($_GET['user_id']) ? '&user_id='.intval($_GET['user_id']) : '';
$url = api_get_self().'?cid='.$courseInfo['real_id'].'&sid='.$sessionId.$add_parameters.
$url = api_get_self().'?cid='.$courseId.'&sid='.$sessionId.$add_parameters.
'&course='.$g_c.
'&invitationcode='.$g_ic.
'&show='.$show;
'&show='.$show.
'&iid='.$surveyId
;
if (!empty($_GET['language'])) {
$lang = Security::remove_XSS($_GET['language']);
$url .= '&language='.$lang;
@ -1247,7 +1225,7 @@ $form = new FormValidator(
$form->addHidden('language', $p_l);
$showNumber = true;
if (SurveyManager::hasDependency($survey_data)) {
if (SurveyManager::hasDependency($survey)) {
$showNumber = false;
}
@ -1266,7 +1244,6 @@ if (isset($questions) && is_array($questions)) {
$form->addHtml('<div class="start-survey">');
$js = '';
if (isset($pageBreakText[$originalShow]) && !empty(strip_tags($pageBreakText[$originalShow]))) {
// Only show page-break texts if there is something there, apart from
// HTML tags
@ -1279,6 +1256,7 @@ if (isset($questions) && is_array($questions)) {
}
foreach ($questions as $key => &$question) {
$ch_type = 'ch_'.$question['type'];
$questionNumber = $questionCounter;
$display = new $ch_type();
@ -1313,12 +1291,12 @@ if (isset($questions) && is_array($questions)) {
case 'score':
$finalAnswer = [];
foreach ($userAnswer as $userChoice) {
list($choiceId, $choiceValue) = explode('*', $userChoice);
[$choiceId, $choiceValue] = explode('*', $userChoice);
$finalAnswer[$choiceId] = $choiceValue;
}
break;
case 'percentage':
list($choiceId, $choiceValue) = explode('*', current($userAnswer));
[$choiceId, $choiceValue] = explode('*', current($userAnswer));
$finalAnswer = $choiceId;
break;
default:
@ -1335,8 +1313,8 @@ if (isset($questions) && is_array($questions)) {
}
$form->addHtml('<div class="start-survey">');
if ('0' == $survey_data['survey_type']) {
if (0 == $survey_data['show_form_profile']) {
if ('0' == $survey->getSurveyType()) {
if (0 == $survey->getShowFormProfile()) {
// The normal survey as always
if ($show < $numberOfPages) {
if (0 == $show) {
@ -1406,7 +1384,7 @@ if ('0' == $survey_data['survey_type']) {
}
}
}
} elseif ('1' == $survey_data['survey_type']) {
} elseif (1 === $survey->getSurveyType()) {
// Conditional/personality-test type survey
if (isset($_GET['show']) || isset($_POST['personality'])) {
$numberOfPages = count($paged_questions);
@ -1422,7 +1400,7 @@ if ('0' == $survey_data['survey_type']) {
if (0 == $personality) {
if (($show <= $numberOfPages) || !$_GET['show']) {
$form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
if (0 == $survey_data['one_question_per_page']) {
if (0 == $survey->getOneQuestionPerPage()) {
if ($personality >= 0) {
$form->addHidden('personality', $personality);
}
@ -1441,7 +1419,7 @@ if ('0' == $survey_data['survey_type']) {
if ($show > $numberOfPages && $_GET['show'] && 0 == $personality) {
$form->addHidden('personality', $personality);
} elseif ($personality > 0) {
if (1 == $survey_data['one_question_per_page']) {
if (1 == $survey->getOneQuestionPerPage()) {
if ($show >= $numberOfPages) {
$form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right', 'success');
} else {
@ -1453,7 +1431,7 @@ if ('0' == $survey_data['survey_type']) {
$form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right');
}
}
} elseif ('' == $survey_data['form_fields']) {
} elseif ('' == $survey->getFormFields()) {
// This is the case when the show_profile_form is true but there are not form_fields
$form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
} elseif (!is_array($user_data)) {

@ -1,6 +1,9 @@
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
require_once __DIR__.'/../inc/global.inc.php';
$surveyId = isset($_REQUEST['i']) ? (int) $_REQUEST['i'] : 0;
@ -10,10 +13,16 @@ $courseId = isset($_REQUEST['c']) ? (int) $_REQUEST['c'] : 0;
if (empty($surveyId)) {
api_not_allowed(true);
}
$repo = Container::getSurveyRepository();
$survey = $repo->find($surveyId);
if (null === $survey) {
api_not_allowed(true);
}
if (!SurveyManager::survey_generation_hash_available()) {
api_not_allowed(true);
}
$courseInfo = api_get_course_info_by_id($courseId);
$course = api_get_course_entity($courseId);
$hashIsValid = SurveyManager::validate_survey_hash(
$surveyId,
$courseId,
@ -21,26 +30,18 @@ $hashIsValid = SurveyManager::validate_survey_hash(
$_REQUEST['g'],
$_REQUEST['h']
);
if ($hashIsValid && $courseInfo) {
$survey_data = SurveyManager::get_survey(
$surveyId,
null,
$courseInfo['code']
if ($hashIsValid && $course) {
$invitationCode = api_get_unique_id();
$invitation = SurveyUtil::saveInvitation(
$invitationCode,
$invitationCode,
api_get_utc_datetime(time(), false, true),
$survey,
$course,
api_get_session_entity()
);
$invitation_code = api_get_unique_id();
$params = [
'c_id' => $courseId,
'session_id' => $sessionId,
'user' => $invitation_code,
'survey_code' => $survey_data['code'],
'invitation_code' => $invitation_code,
'invitation_date' => api_get_utc_datetime(),
];
$invitation_id = SurveyUtil::save_invitation($params);
if ($invitation_id) {
$link = SurveyUtil::generateFillSurveyLink($invitation_code, $courseInfo['code'], $sessionId);
if ($invitation) {
$link = SurveyUtil::generateFillSurveyLink($survey,$invitationCode, $course, $sessionId);
header('Location: '.$link);
exit;
}

@ -2,6 +2,9 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
require_once __DIR__.'/../inc/global.inc.php';
api_protect_course_script(true);
@ -14,7 +17,8 @@ $courseInfo = api_get_course_info();
$surveyId = isset($_REQUEST['survey_id']) ? (int) $_REQUEST['survey_id'] : 0;
$invitationcode = isset($_REQUEST['invitationcode']) ? Database::escape_string($_REQUEST['invitationcode']) : 0;
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
$survey = null;
$repo = Container::getSurveyRepository();
if (!empty($invitationcode) || !api_is_allowed_to_edit()) {
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
$table_survey = Database::get_course_table(TABLE_SURVEY);
@ -29,83 +33,63 @@ if (!empty($invitationcode) || !api_is_allowed_to_edit()) {
}
$survey_invitation = Database::fetch_array($result, 'ASSOC');
$sql = "SELECT * FROM $table_survey
WHERE
c_id = $courseId AND
code = '".Database::escape_string($survey_invitation['survey_code'])."'";
$sql .= api_get_session_condition($sessionId);
$result = Database::query($sql);
$result = Database::fetch_array($result, 'ASSOC');
$surveyId = $result['iid'];
/** @var CSurvey $survey */
$survey = $repo->find($survey_invitation['survey_id']);
$surveyId = $survey->getIid();
}
$surveyData = SurveyManager::get_survey($surveyId);
if (empty($surveyData)) {
if (null === $survey) {
api_not_allowed(true);
}
SurveyManager::checkTimeAvailability($surveyData);
$invitations = SurveyUtil::get_invited_users($surveyData['code']);
$students = isset($invitations['course_users']) ? $invitations['course_users'] : [];
$content = Display::page_header($surveyData['title']);
SurveyManager::checkTimeAvailability($survey);
$invitations = SurveyUtil::get_invited_users($survey);
$students = $invitations['course_users'] ?? [];
$content = Display::page_header($survey->getTitle());
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cid='.$courseInfo['real_id'].'&sid='.$sessionId,
'name' => get_lang('Survey list'),
];
$questions = SurveyManager::get_questions($surveyData['iid']);
$url = api_get_self().'?survey_id='.$surveyId.'&invitationcode='.$invitationcode.'&'.api_get_cidreq();
$urlEdit = $url.'&action=edit';
$questions = $survey->getQuestions();
if (isset($_POST) && !empty($_POST)) {
$options = isset($_POST['options']) ? array_keys($_POST['options']) : [];
foreach ($questions as $item) {
$questionId = $item['question_id'];
SurveyUtil::remove_answer(
$userId,
$surveyId,
$questionId,
$courseId
);
$questionId = $item->getIid();
SurveyUtil::remove_answer($userId, $surveyId, $questionId, $courseId);
}
$status = 1;
if (!empty($options)) {
foreach ($options as $selectedQuestionId) {
SurveyUtil::store_answer(
SurveyUtil::saveAnswer(
$userId,
$surveyId,
$survey,
$selectedQuestionId,
1,
$status,
$surveyData
$status
);
}
} else {
foreach ($questions as $item) {
$questionId = $item['question_id'];
SurveyUtil::store_answer(
SurveyUtil::saveAnswer(
$userId,
$surveyId,
$survey,
$questionId,
1,
0,
$surveyData
0
);
}
}
SurveyManager::update_survey_answered(
$surveyData,
$survey_invitation['user'],
$survey_invitation['survey_code']
);
SurveyManager::updateSurveyAnswered($survey, $survey_invitation['user']);
Display::addFlash(Display::return_message(get_lang('Saved.')));
header('Location: '.$url);
@ -115,19 +99,19 @@ if (isset($_POST) && !empty($_POST)) {
$template = new Template();
$table = new HTML_Table(['class' => 'table']);
$row = 0;
$column = 1;
$answerList = [];
foreach ($questions as $item) {
$answers = SurveyUtil::get_answers_of_question_by_user($surveyId, $item['question_id']);
$questionId = $item->getIid();
$answers = SurveyUtil::get_answers_of_question_by_user($surveyId, $questionId);
foreach ($answers as $tempUserId => &$value) {
$value = $value[0];
$value = explode('*', $value);
$value = isset($value[1]) ? $value[1] : 0;
$value = $value[1] ?? 0;
}
$answerList[$item['question_id']] = $answers;
$parts = explode('@@', $item['question']);
$answerList[$questionId] = $answers;
$parts = explode('@@', $item->getSurveyQuestion());
$startDateTime = api_get_local_time($parts[0]);
$endDateTime = api_get_local_time($parts[1]);

@ -14,7 +14,6 @@ api_block_anonymous_users();
$em = Database::getManager();
$currentUser = api_get_user_entity(api_get_user_id());
$avatarPath = UserManager::getUserPicture($currentUser->getId());
$pending = SurveyUtil::getUserPendingInvitations($currentUser->getId());
$surveysData = [];
@ -41,9 +40,9 @@ foreach ($pending as $i => $item) {
'course' => $course,
'session' => $session,
'link' => SurveyUtil::generateFillSurveyLink(
$survey,
$invitation->getInvitationCode(),
$courseInfo,
$survey->getSessionId()
$course
),
];
}
@ -52,7 +51,6 @@ $toolName = get_lang('Pending surveys');
$template = new Template($toolName);
$template->assign('user', $currentUser);
$template->assign('user_avatar', $avatarPath);
$template->assign('surveys', $surveysData);
$layout = $template->get_template('survey/pending.tpl');
$content = $template->fetch($layout);

@ -6,6 +6,10 @@
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
* @author Julio Montoya <gugli100@gmail.com>
*/
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
require_once __DIR__.'/../inc/global.inc.php';
api_protect_course_script(true);
@ -21,9 +25,12 @@ if (empty($surveyId)) {
}
// Getting the survey information
$survey_data = SurveyManager::get_survey($surveyId);
$repo = Container::getSurveyRepository();
$surveyId = isset($_GET['iid']) ? (int) $_GET['iid'] : 0;
if (empty($survey_data)) {
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
if (null === $survey) {
api_not_allowed(true);
}
@ -42,7 +49,7 @@ $interbreadcrumb[] = [
];
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$surveyId.'&'.api_get_cidreq(),
'name' => strip_tags($survey_data['title'], '<span>'),
'name' => strip_tags($survey->getTitle(), '<span>'),
];
$htmlHeadXtra[] = '<script>'.api_get_language_translate_html().'</script>';
@ -55,22 +62,22 @@ Display::display_header(get_lang('Survey preview'));
SurveyUtil::check_first_last_question($surveyId, false);
// Survey information
echo '<div class="page-header"><h2>'.$survey_data['survey_title'].'</h2></div>';
echo '<div class="page-header"><h2>'.$survey->getTitle().'</h2></div>';
if (!empty($survey_data['survey_subtitle'])) {
echo '<div id="survey_subtitle">'.$survey_data['survey_subtitle'].'</div>';
echo '<div id="survey_subtitle">'.$survey->getSubtitle().'</div>';
}
// Displaying the survey introduction
if (!isset($_GET['show'])) {
if (!empty($survey_data['survey_introduction'])) {
echo '<div class="survey_content">'.$survey_data['survey_introduction'].'</div>';
if (!empty($survey->getIntro())) {
echo '<div class="survey_content">'.$survey->getIntro().'</div>';
}
}
// Displaying the survey thanks message
if (isset($_POST['finish_survey'])) {
echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
echo $survey_data['survey_thanks'];
echo $survey->getSurveythanks();
Display::display_footer();
exit;
}
@ -159,8 +166,7 @@ if (isset($_GET['show'])) {
}
}
$numberOfPages = SurveyManager::getCountPages($survey_data);
$numberOfPages = SurveyManager::getCountPages($survey);
// Displaying the form with the questions
if (isset($_GET['show'])) {
$show = (int) $_GET['show'] + 1;
@ -191,7 +197,7 @@ if (is_array($questions) && count($questions) > 0) {
}
$showNumber = true;
if (SurveyManager::hasDependency($survey_data)) {
if (SurveyManager::hasDependency($survey)) {
$showNumber = false;
}

@ -69,18 +69,18 @@ class SurveyManager
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
$table_survey = Database::get_course_table(TABLE_SURVEY);
$sql = "SELECT iid, survey_code
$sql = "SELECT iid, survey_id
FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
$result = Database::query($sql);
while ($row = Database::fetch_array($result, 'ASSOC')) {
$survey_invitation_id = $row['iid'];
$survey_code = $row['survey_code'];
$surveyId = $row['survey_id'];
$sql2 = "DELETE FROM $table_survey_invitation
WHERE iid = '$survey_invitation_id' AND c_id <> 0";
if (Database::query($sql2)) {
$sql3 = "UPDATE $table_survey SET
invited = invited-1
WHERE c_id <> 0 AND code ='$survey_code'";
invited = invited - 1
WHERE iid = $surveyId";
Database::query($sql3);
}
}
@ -290,24 +290,21 @@ class SurveyManager
->setSurveyType(1)
->setShuffle($values['shuffle'])
->setOneQuestionPerPage($values['one_question_per_page'])
->setParentId($values['parent_id'])
;
// Logic for versioning surveys
if (!empty($values['parent_id'])) {
$versionValue = '';
$parentId = (int) $values['parent_id'];
$sql = 'SELECT survey_version
FROM '.$table_survey.'
WHERE
c_id = '.$course_id.' AND
parent_id = '.intval($values['parent_id']).'
parent_id = '.$parentId.'
ORDER BY survey_version DESC
LIMIT 1';
$rs = Database::query($sql);
if (0 === Database::num_rows($rs)) {
$sql = 'SELECT survey_version FROM '.$table_survey.'
WHERE
c_id = '.$course_id.' AND
iid = '.intval($values['parent_id']);
iid = '.$parentId;
$rs = Database::query($sql);
$getversion = Database::fetch_array($rs, 'ASSOC');
if (empty($getversion['survey_version'])) {
@ -603,66 +600,39 @@ class SurveyManager
return $return;
}
/**
* This function deletes a survey (and also all the question in that survey.
*
* @param int $survey_id id of the survey that has to be deleted
* @param bool $shared
* @param int $course_id
*
* @return true
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version January 2007
*/
public static function delete_survey($survey_id, $shared = false, $course_id = 0)
public static function deleteSharedSurvey(SharedSurvey $survey)
{
// Database table definitions
if (empty($course_id)) {
$course_id = api_get_course_int_id();
}
$survey_id = (int) $survey_id;
if (empty($survey_id)) {
return false;
}
$em = Database::getManager();
$em->remove($survey);
$em->flush();
}
$course_info = api_get_course_info_by_id($course_id);
$course_id = $course_info['real_id'];
public static function deleteSurvey(CSurvey $survey)
{
$repo = Container::getSurveyRepository();
$surveyId = $survey->getIid();
$repo->delete($survey);
$table_survey = Database::get_course_table(TABLE_SURVEY);
$table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
if ($shared) {
$table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
// Deleting the survey
$sql = "DELETE FROM $table_survey
WHERE iid ='".$survey_id."'";
Database::query($sql);
} else {
$sql = "DELETE FROM $table_survey
WHERE c_id = $course_id AND iid ='".$survey_id."'";
Database::query($sql);
}
Event::addEvent(
LOG_SURVEY_DELETED,
LOG_SURVEY_ID,
$survey_id,
$surveyId,
null,
api_get_user_id(),
api_get_course_int_id(),
api_get_session_id()
);
// Deleting groups of this survey
/*// Deleting groups of this survey
$sql = "DELETE FROM $table_survey_question_group
WHERE c_id = $course_id AND iid='".$survey_id."'";
Database::query($sql);
Database::query($sql);*/
// Deleting the questions of the survey
self::delete_all_survey_questions($survey_id, $shared);
self::delete_all_survey_questions($surveyId, false);
// Update into item_property (delete)
/*api_item_property_update(
@ -673,7 +643,7 @@ class SurveyManager
api_get_user_id()
);*/
Skill::deleteSkillsFromItem($survey_id, ITEM_TYPE_SURVEY);
Skill::deleteSkillsFromItem($surveyId, ITEM_TYPE_SURVEY);
return true;
}
@ -868,60 +838,30 @@ class SurveyManager
}
/**
* This function recalculates the number of people who have taken the survey (=filled at least one question).
*
* @param array $survey_data
* @param array $user
* @param string $survey_code
*
* @return bool
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version February 2007
* Updates c_survey.answered: number of people who have taken the survey (=filled at least one question).
*/
public static function update_survey_answered($survey_data, $user, $survey_code)
public static function updateSurveyAnswered(CSurvey $survey, $user)
{
if (empty($survey_data)) {
return false;
}
// Database table definitions
$table_survey = Database::get_course_table(TABLE_SURVEY);
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
$survey_id = (int) $survey_data['survey_id'];
$course_id = (int) $survey_data['c_id'];
$session_id = $survey_data['session_id'];
// Getting a list with all the people who have filled the survey
/*$people_filled = self::get_people_who_filled_survey($survey_id, false, $course_id);
$number = count($people_filled);*/
// Storing this value in the survey table
$sql = "UPDATE $table_survey
SET answered = answered + 1
WHERE
c_id = $course_id AND
iid = ".$survey_id;
Database::query($sql);
$em = Database::getManager();
$surveyId = $survey->getIid();
$courseId = api_get_course_int_id();
$sessionId = api_get_session_id();
$allow = api_get_configuration_value('survey_answered_at_field');
// Requires DB change:
// ALTER TABLE c_survey_invitation ADD answered_at DATETIME DEFAULT NULL;
$answeredAt = '';
if ($allow) {
$answeredAt = "answered_at = '".api_get_utc_datetime()."',";
}
$survey->setAnswered($survey->getAnswered() + 1);
$em->persist($survey);
$em->flush();
$table = Database::get_course_table(TABLE_SURVEY_INVITATION);
// Storing that the user has finished the survey.
$sql = "UPDATE $table_survey_invitation
SET $answeredAt answered = 1
$sql = "UPDATE $table
SET
answered_at = '".api_get_utc_datetime()."',
answered = 1
WHERE
c_id = $course_id AND
session_id = $session_id AND
c_id = $courseId AND
session_id = $sessionId AND
user ='".Database::escape_string($user)."' AND
survey_code='".Database::escape_string($survey_code)."'";
survey_id ='".$surveyId."'";
Database::query($sql);
}
@ -1068,7 +1008,7 @@ class SurveyManager
* @return array containing all the questions of the survey
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @deprecated
* @version February 2007
*
* @todo one sql call should do the trick
@ -1434,17 +1374,17 @@ class SurveyManager
$table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
}
$sql = "DELETE FROM $table_survey_question
/*$sql = "DELETE FROM $table_survey_question
WHERE $course_condition survey_id = '".$survey_id."'";
// Deleting the survey questions
Database::query($sql);
Database::query($sql);*/
// Deleting all the options of the questions of the survey
self::delete_all_survey_questions_options($survey_id, $shared);
//self::delete_all_survey_questions_options($survey_id, $shared);
// Deleting all the answers on this survey
self::delete_all_survey_answers($survey_id);
//self::delete_all_survey_answers($survey_id);
return true;
}
@ -1596,7 +1536,6 @@ class SurveyManager
if ('multiplechoiceother' === $type) {
if (empty($dataFromDatabase['answer_data'])) {
$params = [
'c_id' => $course_id,
'question_id' => $form_content['question_id'],
'survey_id' => $form_content['survey_id'],
'option_text' => 'other',
@ -1614,8 +1553,7 @@ class SurveyManager
$table,
$params,
[
'c_id = ? AND question_id = ? AND survey_id = ? AND option_text = ?' => [
$course_id,
'question_id = ? AND survey_id = ? AND option_text = ?' => [
$form_content['question_id'],
$form_content['survey_id'],
'other',
@ -1714,34 +1652,6 @@ class SurveyManager
return true;
}
/**
* @param int $user_id
* @param int $survey_id
* @param int $course_id
*
* @return bool
*/
public static function is_user_filled_survey($user_id, $survey_id, $course_id)
{
$table = Database::get_course_table(TABLE_SURVEY_ANSWER);
$user_id = (int) $user_id;
$course_id = (int) $course_id;
$survey_id = (int) $survey_id;
$sql = "SELECT DISTINCT user
FROM $table
WHERE
c_id = $course_id AND
user = $user_id AND
survey_id = $survey_id";
$result = Database::query($sql);
if (Database::num_rows($result)) {
return true;
}
return false;
}
/**
* This function gets all the persons who have filled the survey.
*
@ -1790,7 +1700,7 @@ class SurveyManager
$order_clause;
} else {
$sql = "SELECT DISTINCT user FROM $table_survey_answer
WHERE c_id = $course_id AND survey_id= '".$survey_id."' ";
WHERE survey_id= '".$survey_id."' ";
if (api_get_configuration_value('survey_anonymous_show_answered')) {
$tblInvitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
@ -1949,7 +1859,12 @@ class SurveyManager
}
Display::addFlash(
Display::return_message(get_lang('A mandatory survey is waiting your answer. To enter the course, you must first complete the survey.'), 'warning')
Display::return_message(
get_lang(
'A mandatory survey is waiting your answer. To enter the course, you must first complete the survey.'
),
'warning'
)
);
$url = SurveyUtil::generateFillSurveyLink(
@ -2202,13 +2117,10 @@ class SurveyManager
*
* @return bool
*/
public static function removeMultiplicateQuestions($surveyData)
public static function removeMultiplicateQuestions(CSurvey $survey, $courseId)
{
if (empty($surveyData)) {
return false;
}
$surveyId = $surveyData['survey_id'];
$courseId = $surveyData['c_id'];
$surveyId = $survey->getIid();
$courseId = (int) $courseId;
if (empty($surveyId) || empty($courseId)) {
return false;
@ -2224,19 +2136,13 @@ class SurveyManager
}
/**
* @param array $surveyData
*
* @return bool
*/
public static function multiplicateQuestions($surveyData)
public static function multiplicateQuestions(CSurvey $survey, $courseId)
{
if (empty($surveyData)) {
return false;
}
$surveyId = $surveyData['survey_id'];
$courseId = $surveyData['c_id'];
$surveyId = $survey->getIid();
if (empty($surveyId) || empty($courseId)) {
if (empty($surveyId)) {
return false;
}
@ -2269,7 +2175,7 @@ class SurveyManager
'users' => $users,
];
}
self::parseMultiplicateUserList($classToParse, $questions, $courseId, $surveyData, true);
self::parseMultiplicateUserList($classToParse, $questions, $courseId, $survey, true);
} else {
$groupInfo = GroupManager::get_group_properties($groupId);
if (!empty($groupInfo)) {
@ -2285,7 +2191,7 @@ class SurveyManager
],
$questions,
$courseId,
$surveyData,
$survey,
false
);
}
@ -2295,13 +2201,13 @@ class SurveyManager
return true;
}
public static function parseMultiplicateUserList($itemList, $questions, $courseId, $surveyData, $addClassNewPage = false)
public static function parseMultiplicateUserList($itemList, $questions, $courseId, CSurvey $survey, $addClassNewPage = false)
{
if (empty($itemList) || empty($questions)) {
return false;
}
$surveyId = $surveyData['survey_id'];
$surveyId = $survey->getIid();
$classTag = '{{class_name}}';
$studentTag = '{{student_full_name}}';
$classCounter = 0;
@ -2346,7 +2252,7 @@ class SurveyManager
'shared_question_id' => 0,
'answers' => $question['answers'] ?? null,
];
self::save_question($surveyData, $values, false);
self::saveQuestion($survey, $values, false);
$classCounter++;
continue;
}
@ -2374,7 +2280,7 @@ class SurveyManager
}
}
$values['answers'] = $answers;
self::save_question($surveyData, $values, false);
self::saveQuestion($survey, $values, false);
}
}
@ -2390,7 +2296,7 @@ class SurveyManager
'question_id' => 0,
'shared_question_id' => 0,
];
self::save_question($surveyData, $values, false);
self::saveQuestion($survey, $values, false);
}
}
}
@ -2398,27 +2304,17 @@ class SurveyManager
return true;
}
public static function hasDependency($survey)
public static function hasDependency(CSurvey $survey)
{
if (false === api_get_configuration_value('survey_question_dependency')) {
return false;
}
if (empty($survey)) {
return false;
}
if (!isset($survey['survey_id'])) {
return false;
}
$courseId = (int) $survey['c_id'];
$surveyId = (int) $survey['survey_id'];
$surveyId = $survey->getIid();
$table = Database::get_course_table(TABLE_SURVEY_QUESTION);
$sql = "SELECT COUNT(iid) count FROM $table
WHERE
c_id = $courseId AND
survey_id = $surveyId AND
parent_option_id <> 0
LIMIT 1
@ -2434,18 +2330,11 @@ class SurveyManager
}
/**
* @param array $survey
*
* @return int
*/
public static function getCountPages($survey)
public static function getCountPages(CSurvey $survey)
{
if (empty($survey) || !isset($survey['iid'])) {
return 0;
}
$courseId = (int) $survey['c_id'];
$surveyId = (int) $survey['iid'];
$surveyId = $survey->getIid();
$table = Database::get_course_table(TABLE_SURVEY_QUESTION);
@ -2467,7 +2356,7 @@ class SurveyManager
$result = Database::query($sql);
$countOfQuestions = Database::result($result, 0, 0);
if (1 == $survey['one_question_per_page']) {
if (1 == $survey->getOneQuestionPerPage()) {
if (!empty($countOfQuestions)) {
return $countOfQuestions;
}
@ -2483,19 +2372,17 @@ class SurveyManager
}
/**
* Check whether this survey has ended. If so, display message and exit rhis script.
*
* @param array $surveyData Survey data
* Check whether this survey has ended. If so, display message and exit this script.
*/
public static function checkTimeAvailability($surveyData)
public static function checkTimeAvailability(?CSurvey $survey)
{
if (empty($surveyData)) {
if (null === $survey) {
api_not_allowed(true);
}
$utcZone = new DateTimeZone('UTC');
$startDate = new DateTime($surveyData['start_date'], $utcZone);
$endDate = new DateTime($surveyData['end_date'], $utcZone);
$startDate = $survey->getAvailFrom();
$endDate = $survey->getAvailTill();
$currentDate = new DateTime('now', $utcZone);
$currentDate->modify('today');
@ -2593,14 +2480,10 @@ class SurveyManager
/** @var CSurveyInvitation $invitation */
$row = 1;
foreach ($invitations as $invitation) {
$courseId = $invitation->getCId();
$courseInfo = api_get_course_info_by_id($courseId);
$courseCode = $courseInfo['code'];
if (empty($courseInfo)) {
continue;
}
$sessionId = $invitation->getSessionId();
$course = $invitation->getCourse();
$courseId = $course->getId();
$courseCode = $course->getCode();
$sessionId = $invitation->getSession() ? $invitation->getSession()->getId() : 0;
if (!empty($answered)) {
// check if user is subscribed to the course/session
@ -2621,30 +2504,22 @@ class SurveyManager
}
}
$surveyCode = $invitation->getSurveyCode();
$survey = $repoSurvey->findOneBy([
'cId' => $courseId,
'sessionId' => $sessionId,
'code' => $surveyCode,
]);
if (empty($survey)) {
$survey = $invitation->getSurvey();
if (null === $survey) {
continue;
}
$url = $mainUrl.'survey_id='.$survey->getIid().'&cid='.$courseId.'&sid='.$sessionId;
$title = $survey->getTitle();
$title = Display::url($title, $url);
$courseTitle = $course->getTitle();
if (!empty($sessionId)) {
$sessionInfo = api_get_session_info($sessionId);
$courseInfo['name'] .= ' ('.$sessionInfo['name'].')';
$courseTitle .= ' ('.$invitation->getSession()->getName().')';
}
$surveyData = self::get_survey($survey->getIid(), 0, $courseCode);
$table->setCellContents($row, 0, $title);
$table->setCellContents($row, 1, $courseInfo['name']);
$table->setCellContents($row, 1, $courseTitle);
if (empty($answered)) {
$table->setHeaderContents(
@ -2660,7 +2535,7 @@ class SurveyManager
);
}
if (!empty($answered) && 0 == $surveyData['anonymous']) {
if (!empty($answered) && 0 == $survey->getAnonymous()) {
$answers = SurveyUtil::displayCompleteReport(
$surveyData,
$userId,
@ -2682,12 +2557,9 @@ class SurveyManager
return $content;
}
public static function sendToTutors($surveyId)
public static function sendToTutors(CSurvey $survey)
{
$survey = Database::getManager()->getRepository(CSurvey::class)->find($surveyId);
if (null === $survey) {
return false;
}
$surveyId = $survey->getIid();
$extraFieldValue = new ExtraFieldValue('survey');
$groupData = $extraFieldValue->get_values_by_handler_and_field_variable($surveyId, 'group_id');
@ -2712,7 +2584,7 @@ class SurveyManager
);
SurveyUtil::saveInvitations(
$surveyId,
$survey,
['users' => $tutor['user_id']],
$subject,
$content,
@ -2724,7 +2596,7 @@ class SurveyManager
}
Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false));
}
SurveyUtil::update_count_invited($survey->getCode());
SurveyUtil::updateInvitedCount($survey);
return true;
}

@ -26,7 +26,7 @@ if ($isDrhOfCourse) {
exit;
}
if (!api_is_allowed_to_edit(false, true) ||
(api_is_session_general_coach() && 'false' == $extend_rights_for_coachs)
(api_is_session_general_coach() && 'false' === $extend_rights_for_coachs)
) {
api_not_allowed(true);
exit;
@ -42,11 +42,11 @@ $table_user = Database::get_main_table(TABLE_MAIN_USER);
$survey_id = (int) $_GET['survey_id'];
$course_id = api_get_course_int_id();
$action = isset($_GET['action']) ? $_GET['action'] : null;
$action = $_GET['action'] ?? null;
// Breadcrumbs
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php',
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
'name' => get_lang('Survey list'),
];
@ -72,9 +72,9 @@ if (api_strlen(strip_tags($survey_data['title'])) > 40) {
$tool_name .= '...';
}
if ($is_survey_type_1 && ('addgroup' == $action || 'deletegroup' == $action)) {
if ($is_survey_type_1 && ('addgroup' === $action || 'deletegroup' === $action)) {
$_POST['name'] = trim($_POST['name']);
if ('addgroup' == $action) {
if ('addgroup' === $action) {
if (!empty($_POST['group_id'])) {
Database::query('UPDATE '.$table_survey_question_group.' SET description = \''.Database::escape_string($_POST['description']).'\'
WHERE c_id = '.$course_id.' AND id = \''.Database::escape_string($_POST['group_id']).'\'');
@ -87,7 +87,7 @@ if ($is_survey_type_1 && ('addgroup' == $action || 'deletegroup' == $action)) {
}
}
if ('deletegroup' == $action) {
if ('deletegroup' === $action) {
$sql = 'DELETE FROM '.$table_survey_question_group.'
WHERE c_id = '.$course_id.' AND id = '.intval($_GET['gid']).' AND survey_id = '.$survey_id;
Database::query($sql);

@ -3,8 +3,14 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
use Chamilo\CourseBundle\Entity\CGroup;
use Chamilo\CourseBundle\Entity\CSurvey;
use Chamilo\CourseBundle\Entity\CSurveyAnswer;
use Chamilo\CourseBundle\Entity\CSurveyInvitation;
use Chamilo\CourseBundle\Entity\CSurveyQuestion;
use Chamilo\CourseBundle\Entity\CSurveyQuestionOption;
use ChamiloSession as Session;
/**
@ -66,10 +72,8 @@ class SurveyUtil
*
* @version January 2007
*/
public static function remove_answer($user, $survey_id, $question_id, $course_id)
public static function remove_answer($user, $survey_id, $question_id)
{
$course_id = intval($course_id);
// table definition
$table = Database::get_course_table(TABLE_SURVEY_ANSWER);
$sql = "DELETE FROM $table
WHERE
@ -79,38 +83,16 @@ class SurveyUtil
Database::query($sql);
}
/**
* This function stores an answer of a user on a question of a survey.
*
* @param mixed The user id or email of the person who fills the survey
* @param int Survey id
* @param int Question id
* @param int Option id
* @param string Option value
* @param array $survey_data Survey data settings
*
* @return bool False if insufficient data, true otherwise
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version January 2007
*/
public static function store_answer(
public static function saveAnswer(
$user,
$survey_id,
$question_id,
$option_id,
$option_value,
$survey_data,
CSurvey $survey,
CSurveyQuestion $question,
$optionId,
$optionValue,
$otherOption = ''
) {
// If the question_id is empty, don't store an answer
if (empty($question_id)) {
return false;
}
// Make the survey anonymous
if (1 == $survey_data['anonymous']) {
if (1 == $survey->getAnonymous()) {
$surveyUser = Session::read('surveyuser');
if (empty($surveyUser)) {
$user = md5($user.time());
@ -121,16 +103,16 @@ class SurveyUtil
}
if (!empty($otherOption)) {
$option_id = $option_id.'@:@'.$otherOption;
$optionId = $optionId.'@:@'.$otherOption;
}
$answer = new CSurveyAnswer();
$answer
->setUser($user)
->setSurveyId($survey_id)
->setQuestionId($question_id)
->setOptionId($option_id)
->setValue($option_value)
->setSurvey($survey)
->setQuestion($question)
->setOptionId($optionId)
->setValue((int) $optionValue)
;
$em = Database::getManager();
@ -292,11 +274,10 @@ class SurveyUtil
$sql = "UPDATE $table_survey_invitation SET answered = '0'
WHERE
c_id = $course_id AND
survey_code = (
SELECT code FROM $table_survey
survey_id = (
SELECT iid FROM $table_survey
WHERE
c_id = $course_id AND
survey_id = '".$survey_id."'
iid = '".$survey_id."'
) AND
user = '".$user_id."'";
$result = Database::query($sql);
@ -664,7 +645,7 @@ class SurveyUtil
echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
echo '</div>';
if ('score' == $question['type']) {
if ('score' === $question['type']) {
/** @todo This function should return the options as this is needed further in the code */
$options = self::display_question_report_score($survey_data, $question, $offset);
} elseif ('open' === $question['type'] || 'comment' === $question['type']) {
@ -672,7 +653,6 @@ class SurveyUtil
/** @todo Also get the user who has answered this */
$sql = "SELECT * FROM $table_survey_answer
WHERE
c_id = $course_id AND
survey_id= $surveyId AND
question_id = $questionId ";
$result = Database::query($sql);
@ -684,7 +664,6 @@ class SurveyUtil
// Getting the options ORDER BY sort ASC
$sql = "SELECT * FROM $table_survey_question_option
WHERE
c_id = $course_id AND
survey_id = $surveyId AND
question_id = $questionId
ORDER BY sort ASC";
@ -696,7 +675,6 @@ class SurveyUtil
$sql = "SELECT *, count(iid) as total
FROM $table_survey_answer
WHERE
c_id = $course_id AND
survey_id = $surveyId AND
question_id = $questionId
GROUP BY option_id, value";
@ -862,9 +840,8 @@ class SurveyUtil
// Getting the options
$sql = "SELECT * FROM $table_survey_question_option
WHERE
c_id = $course_id AND
survey_id= $surveyId AND
question_id = '".intval($question['question_id'])."'
question_id = '".intval($question['iid'])."'
ORDER BY sort ASC";
$result = Database::query($sql);
while ($row = Database::fetch_array($result)) {
@ -875,9 +852,8 @@ class SurveyUtil
$sql = "SELECT *, count(iid) as total
FROM $table_survey_answer
WHERE
c_id = $course_id AND
survey_id= $surveyId AND
question_id = '".Database::escape_string($question['question_id'])."'
question_id = '".Database::escape_string($question['iid'])."'
GROUP BY option_id, value";
$result = Database::query($sql);
$number_of_answers = 0;
@ -892,8 +868,8 @@ class SurveyUtil
$optionText = html_entity_decode($optionText);
for ($i = 1; $i <= $question['max_value']; $i++) {
$votes = null;
if (isset($data[$option['question_option_id']][$i])) {
$votes = $data[$option['question_option_id']][$i]['total'];
if (isset($data[$option['iid']][$i])) {
$votes = $data[$option['iid']][$i]['total'];
}
if (empty($votes)) {
@ -926,19 +902,27 @@ class SurveyUtil
foreach ($options as $key => &$value) {
for ($i = 1; $i <= $question['max_value']; $i++) {
$absolute_number = null;
if (isset($data[$value['question_option_id']][$i])) {
$absolute_number = $data[$value['question_option_id']][$i]['total'];
if (isset($data[$value['iid']][$i])) {
$absolute_number = $data[$value['iid']][$i]['total'];
}
echo ' <tr>';
echo ' <td>'.$value['option_text'].'</td>';
echo ' <td>'.$i.'</td>';
echo ' <td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action
echo '<tr>';
echo '<td>'.$value['option_text'].'</td>';
echo '<td>'.$i.'</td>';
echo '<td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action
.'&survey_id='.$surveyId.'&question='.Security::remove_XSS($offset)
.'&viewoption='.$value['question_option_id'].'&value='.$i.'">'.$absolute_number.'</a></td>';
echo ' <td>'.round($absolute_number / $number_of_answers * 100, 2).' %</td>';
echo ' <td>';
$size = ($absolute_number / $number_of_answers * 100 * 2);
.'&viewoption='.$value['iid'].'&value='.$i.'">'.$absolute_number.'</a></td>';
$percentage = 0;
$size = 0;
if (!empty($number_of_answers)) {
$percentage = round($absolute_number / $number_of_answers * 100, 2);
$size = ($absolute_number / $number_of_answers * 100 * 2);
}
echo '<td>'.$percentage.' %</td>';
echo '<td>';
if ($size > 0) {
echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
}
@ -1091,11 +1075,10 @@ class SurveyUtil
count(o.iid) as number_of_options
FROM $table_survey_question q
LEFT JOIN $table_survey_question_option o
ON q.iid = o.question_id AND q.c_id = o.c_id
ON q.iid = o.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
q.survey_id = '".$surveyId."' AND
q.c_id = $course_id
q.survey_id = '".$surveyId."'
GROUP BY q.iid
ORDER BY q.sort ASC";
$result = Database::query($sql);
@ -1109,7 +1092,7 @@ class SurveyUtil
in_array($row['question_id'], $_POST['questions_filter']))
) {
// We do not show comment and pagebreak question types
if ('pagebreak' != $row['type']) {
if ('pagebreak' !== $row['type']) {
$content .= ' <th';
if ($row['number_of_options'] > 0 && 'percentage' != $row['type']) {
$content .= ' colspan="'.$row['number_of_options'].'"';
@ -1159,11 +1142,10 @@ class SurveyUtil
sqo.sort as option_sort
FROM $table_survey_question sq
LEFT JOIN $table_survey_question_option sqo
ON sq.iid = sqo.question_id AND sq.c_id = sqo.c_id
ON sq.iid = sqo.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
sq.survey_id = '".$surveyId."' AND
sq.c_id = $course_id
sq.survey_id = $surveyId
ORDER BY sq.sort ASC, sqo.sort ASC";
$result = Database::query($sql);
@ -1439,13 +1421,11 @@ class SurveyUtil
FROM $table_survey_question questions
LEFT JOIN $table_survey_question_option options
ON
questions.iid = options.question_id AND
options.c_id = questions.c_id
questions.iid = options.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
questions.type <> 'pagebreak' AND
questions.survey_id = $surveyId AND
questions.c_id = $course_id
questions.survey_id = $surveyId
GROUP BY questions.question_id
ORDER BY questions.sort ASC";
@ -1728,23 +1708,11 @@ class SurveyUtil
return $return;
}
/**
* Quite similar to display_complete_report(), returns an HTML string
* that can be used in a csv file.
*
* @todo consider merging this function with display_complete_report
*
* @return string The contents of a csv file
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version February 2007
*/
public static function export_complete_report_xls($survey_data, $filename, $user_id = 0, $returnFile = false)
public static function export_complete_report_xls(CSurvey $survey, $filename, $user_id = 0, $returnFile = false)
{
$course_id = api_get_course_int_id();
$user_id = (int) $user_id;
$surveyId = $survey_data['iid'];
$surveyId = $survey->getIid();
if (empty($course_id) || empty($surveyId)) {
return false;
@ -1782,13 +1750,11 @@ class SurveyUtil
FROM $table_survey_question questions
LEFT JOIN $table_survey_question_option options
ON
questions.iid = options.question_id AND
options.c_id = questions.c_id
questions.iid = options.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
questions.type <> 'pagebreak' AND
questions.survey_id = $surveyId AND
questions.c_id = $course_id
questions.survey_id = $surveyId
GROUP BY questions.question_id
ORDER BY questions.sort ASC";
$result = Database::query($sql);
@ -1803,8 +1769,8 @@ class SurveyUtil
in_array($row['question_id'], $_POST['questions_filter']))
) {
// We do not show comment and pagebreak question types
if ('pagebreak' != $row['type']) {
if (0 == $row['number_of_options'] && ('open' == $row['type'] || 'comment' == $row['type'])) {
if ('pagebreak' !== $row['type']) {
if (0 == $row['number_of_options'] && ('open' === $row['type'] || 'comment' === $row['type'])) {
$list[$line][$column] = api_html_entity_decode(
strip_tags($row['survey_question']),
ENT_QUOTES
@ -1848,13 +1814,11 @@ class SurveyUtil
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON
survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = survey_question.c_id
survey_question.iid = survey_question_option.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.type <> 'pagebreak' AND
survey_question.survey_id = $surveyId AND
survey_question.c_id = $course_id
survey_question.survey_id = $surveyId
ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
$result = Database::query($sql);
$possible_answers = [];
@ -1868,7 +1832,7 @@ class SurveyUtil
in_array($row['question_id'], $_POST['questions_filter']))
) {
// We do not show comment and pagebreak question types
if ('pagebreak' != $row['type']) {
if ('pagebreak' !== $row['type']) {
$list[$line][$column] = api_html_entity_decode(
strip_tags($row['option_text']),
ENT_QUOTES
@ -1897,7 +1861,7 @@ class SurveyUtil
while ($row = Database::fetch_array($result)) {
if ($old_user != $row['user'] && '' != $old_user) {
$return = self::export_complete_report_row_xls(
$survey_data,
$survey,
$possible_answers,
$answers_of_user,
$old_user,
@ -1911,7 +1875,7 @@ class SurveyUtil
$line++;
$column = 0;
}
if ('open' == $possible_answers_type[$row['question_id']] || 'comment' == $possible_answers_type[$row['question_id']]) {
if ('open' === $possible_answers_type[$row['question_id']] || 'comment' === $possible_answers_type[$row['question_id']]) {
$temp_id = 'open'.$open_question_iterator;
$answers_of_user[$row['question_id']][$temp_id] = $row;
$open_question_iterator++;
@ -1922,7 +1886,7 @@ class SurveyUtil
}
$return = self::export_complete_report_row_xls(
$survey_data,
$survey,
$possible_answers,
$answers_of_user,
$old_user,
@ -1953,15 +1917,15 @@ class SurveyUtil
* @return array
*/
public static function export_complete_report_row_xls(
$survey_data,
CSurvey $survey,
$possible_options,
$answers_of_user,
$user,
$display_extra_user_fields = false
) {
$return = [];
if (0 == $survey_data['anonymous']) {
if (0 !== intval($user)) {
if (0 == $survey->getAnonymous()) {
if (0 !== (int) $user) {
$userInfo = api_get_user_info($user);
if ($userInfo) {
$user_displayed = $userInfo['complete_name_with_username'];
@ -1994,11 +1958,9 @@ class SurveyUtil
foreach ($possible_options as $question_id => &$possible_option) {
if (is_array($possible_option) && count($possible_option) > 0) {
foreach ($possible_option as $option_id => &$value) {
$my_answers_of_user = isset($answers_of_user[$question_id])
? $answers_of_user[$question_id]
: [];
$my_answers_of_user = $answers_of_user[$question_id] ?? [];
$key = array_keys($my_answers_of_user);
if (isset($key[0]) && 'open' == substr($key[0], 0, 4)) {
if (isset($key[0]) && 'open' === substr($key[0], 0, 4)) {
$return[] = api_html_entity_decode(
strip_tags($answers_of_user[$question_id][$key[0]]['option_id']),
ENT_QUOTES
@ -2298,7 +2260,6 @@ class SurveyUtil
$sql = "SELECT * FROM $table_survey_answer
WHERE
c_id = $course_id AND
survey_id='".intval($survey_id)."' AND
question_id='".intval($question_id)."'
ORDER BY USER ASC";
@ -2403,7 +2364,7 @@ class SurveyUtil
* @version January 2007
*/
public static function saveInvitations(
$surveyId,
CSurvey $survey,
$users_array,
$invitation_title,
$invitation_text,
@ -2413,15 +2374,15 @@ class SurveyUtil
$isAdditionalEmail = false,
$hideLink = false
) {
$surveyId = (int) $surveyId;
$surveyId = $survey->getIid();
if (!is_array($users_array)) {
return 0;
}
// Getting the survey information
$survey_data = SurveyManager::get_survey($surveyId);
$survey_invitations = self::get_invitations($survey_data['survey_code']);
$already_invited = self::get_invited_users($survey_data['code']);
$course = api_get_course_entity();
$session = api_get_session_entity();
$survey_invitations = self::get_invitations($surveyId);
$already_invited = self::get_invited_users($survey);
// Remind unanswered is a special version of remind all reminder
$exclude_users = [];
@ -2441,25 +2402,34 @@ class SurveyUtil
$users_array = $result['users'];
foreach ($groupList as $groupId) {
$group = api_get_group_entity($groupId);
$userGroupList = GroupManager::getStudents($groupId, true);
$userGroupIdList = array_column($userGroupList, 'user_id');
$users_array = array_merge($users_array, $userGroupIdList);
$params = [
/*$params = [
'c_id' => $course_id,
'session_id' => $session_id,
'group_id' => $groupId,
'survey_code' => $survey_data['code'],
];
];*/
$invitationExists = self::invitationExists(
$course_id,
$session_id,
$groupId,
$survey_data['code']
$survey->getIid()
);
if (empty($invitationExists)) {
self::save_invitation($params);
self::saveInvitation(
null,
null,
api_get_utc_datetime(time(), false, true),
$survey,
$course,
$session,
$group
);
}
}
}
@ -2482,25 +2452,25 @@ class SurveyUtil
$invitation_code = md5($value.microtime());
}
$new_user = false; // User not already invited
// Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
// Store the invitation if user_id not in $already_invited['course_users'] OR
// email is not in $already_invited['additional_users']
$addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users'])
? explode(';', $already_invited['additional_users'])
: [];
$my_alredy_invited = null == $already_invited['course_users'] ? [] : $already_invited['course_users'];
$my_alredy_invited = $already_invited['course_users'] ?? [];
if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
(!is_numeric($value) && !in_array($value, $addit_users_array))
) {
$new_user = true;
if (!array_key_exists($value, $survey_invitations)) {
$params = [
'c_id' => $course_id,
'session_id' => $session_id,
'user' => $value,
'survey_code' => $survey_data['code'],
'invitation_code' => $invitation_code,
'invitation_date' => api_get_utc_datetime(),
];
self::save_invitation($params);
self::saveInvitation(
$value,
$invitation_code,
api_get_utc_datetime(time(), null, true),
$survey,
$course,
$session
);
}
}
@ -2512,8 +2482,10 @@ class SurveyUtil
$invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
$invitation_text = trim(stripslashes($invitation_text));
}
self::send_invitation_mail(
self::sendInvitationMail(
$survey,
$value,
$course,
$invitation_code,
$invitation_title,
$invitation_text,
@ -2526,57 +2498,60 @@ class SurveyUtil
return $counter; // Number of invitations sent
}
/**
* @param $params
*
* @return bool|int
*/
public static function save_invitation($params)
{
// Database table to store the invitations data
$table = Database::get_course_table(TABLE_SURVEY_INVITATION);
if (!empty($params['c_id']) &&
(!empty($params['user']) || !empty($params['group_id'])) &&
!empty($params['survey_code'])
) {
if (!isset($params['iid'])) {
$params['iid'] = 0;
}
if (!isset($params['answered'])) {
$params['answered'] = 0;
}
if (!isset($params['group_id'])) {
$params['group_id'] = 0;
}
public static function saveInvitation(
$user,
$invitationCode,
$reminderDate,
CSurvey $survey,
Course $course,
SessionEntity $session = null,
CGroup $group = null
): ?CSurveyInvitation {
/*var_dump($params);
array(6) { ["c_id"]=> int(1) ["session_id"]=> int(0) ["user"]=> int(61) ["survey_code"]=> string(3) "aaa
" ["invitation_code"]=> string(32) "6046726ce1894c21437377a53903714a" ["invitation_date"]=> string(19) "2021-03-19 09:06:50" }
*/
$invitation = new CSurveyInvitation();
$invitation
->setUser($user)
->setInvitationCode($invitationCode)
->setReminderDate($reminderDate)
->setSurvey($survey)
->setCourse($course)
->setSession($session)
->setGroup($group)
;
return Database::insert($table, $params);
}
$em = Database::getManager();
$em->persist($invitation);
$em->flush();
return false;
return $invitation;
}
/**
* @param int $courseId
* @param int $sessionId
* @param int $groupId
* @param string $surveyCode
* @param int $surveyId
*
* @return int
*/
public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
public static function invitationExists($courseId, $sessionId, $groupId, $surveyId)
{
$table = Database::get_course_table(TABLE_SURVEY_INVITATION);
$courseId = (int) $courseId;
$sessionId = (int) $sessionId;
$groupId = (int) $groupId;
$surveyCode = Database::escape_string($surveyCode);
$surveyId = (int) $surveyId;
$sql = "SELECT iid FROM $table
WHERE
c_id = $courseId AND
session_id = $sessionId AND
group_id = $groupId AND
survey_code = '$surveyCode'
survey_id = $surveyId
";
$result = Database::query($sql);
@ -2589,19 +2564,20 @@ class SurveyUtil
* @param int invitedUser - the userId (course user) or emailaddress of additional user
* $param string $invitation_code - the unique invitation code for the URL
*/
public static function send_invitation_mail(
public static function sendInvitationMail(
CSurvey $survey,
$invitedUser,
Course $course,
$invitation_code,
$invitation_title,
$invitation_text,
$hideLink = false
) {
$_user = api_get_user_info();
$_course = api_get_course_info();
$sessionId = api_get_session_id();
// Replacing the **link** part with a valid link for the user
$link = self::generateFillSurveyLink($invitation_code, $_course, $sessionId);
$link = self::generateFillSurveyLink($survey, $invitation_code, $course, $sessionId);
if ($hideLink) {
$full_invitation_text = str_replace('**link**', '', $invitation_text);
} else {
@ -2621,7 +2597,7 @@ class SurveyUtil
$sender_user_id = api_get_user_id();
$replyto = [];
if ('noreply' == api_get_setting('survey_email_sender_noreply')) {
if ('noreply' === api_get_setting('survey_email_sender_noreply')) {
$noreply = api_get_setting('noreply_email_address');
if (!empty($noreply)) {
$replyto['Reply-to'] = $noreply;
@ -2662,20 +2638,10 @@ class SurveyUtil
/**
* This function recalculates the number of users who have been invited and updates the survey table with this
* value.
*
* @param string Survey code
* @param int $courseId
* @param int $sessionId
*
* @return int
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version January 2007
*/
public static function update_count_invited($survey_code, $courseId = 0, $sessionId = 0)
public static function updateInvitedCount(CSurvey $survey, $courseId = 0, $sessionId = 0)
{
$survey_code = Database::escape_string($survey_code);
$surveyId = $survey->getIid();
$courseId = (int) $courseId;
$sessionId = (int) $sessionId;
@ -2692,7 +2658,7 @@ class SurveyUtil
FROM $table_survey_invitation
WHERE
c_id = $courseId AND
survey_code = '".$survey_code."' AND
survey_id = '".$surveyId."' AND
user <> ''
$sessionCondition
";
@ -2704,9 +2670,7 @@ class SurveyUtil
$sql = "UPDATE $table_survey
SET invited = '".Database::escape_string($total_invited)."'
WHERE
c_id = $courseId AND
code = '".$survey_code."'
$sessionCondition
iid = '".$surveyId."'
";
Database::query($sql);
@ -2716,24 +2680,14 @@ class SurveyUtil
/**
* This function gets all the invited users for a given survey code.
*
* @param string Survey code
* @param string optional - course database
*
* @return array Array containing the course users and additional users (non course users)
*
* @todo consider making $defaults['additional_users'] also an array
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
* @author Julio Montoya, adding c_id fixes - Dec 2012
*
* @version January 2007
*/
public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
public static function get_invited_users(CSurvey $survey, $course_code = '', $session_id = 0)
{
$session_id = (int) $session_id;
$survey_code = Database::escape_string($survey_code);
$course_code = Database::escape_string($course_code);
$surveyId = $survey->getIid();
$course_code = Database::escape_string($course_code);
$course_id = api_get_course_int_id();
if (!empty($course_code)) {
@ -2756,13 +2710,13 @@ class SurveyUtil
FROM $table_survey_invitation as table_invitation
WHERE
table_invitation.c_id = $course_id AND
survey_code='".$survey_code."' AND
survey_id='".$surveyId."' AND
session_id = $session_id
";
$defaults = [];
$defaults['course_users'] = [];
$defaults['additional_users'] = []; // Textarea
$defaults['additional_users'] = ''; // Textarea
$defaults['users'] = []; // user and groups
$result = Database::query($sql);
@ -2802,15 +2756,14 @@ class SurveyUtil
/**
* Get all the invitations.
*
* @param string Survey code
* @param int $surveyId
*
* @return array Database rows matching the survey code
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version September 2007
*/
public static function get_invitations($survey_code)
public static function get_invitations($surveyId)
{
$course_id = api_get_course_int_id();
$sessionId = api_get_session_id();
@ -2821,7 +2774,7 @@ class SurveyUtil
WHERE
c_id = $course_id AND
session_id = $sessionId AND
survey_code = '".Database::escape_string($survey_code)."'";
survey_id = '".(int) $surveyId."'";
$result = Database::query($sql);
$return = [];
while ($row = Database::fetch_array($result)) {
@ -3398,15 +3351,14 @@ class SurveyUtil
";
//$res = Database::query($sql);
$array = [];
$efv = new ExtraFieldValue('survey');
$list = [];
foreach ($surveys as $survey) {
$array = [];
$surveyId = $survey->getIid();
$array[0] = $survey->getIid();
$array[0] = $surveyId;
$type = $survey->getSurveyType();
$title = $survey->getTitle();
if (self::checkHideEditionToolsByCode($survey->getCode())) {
$array[1] = $title;
} else {
@ -3427,12 +3379,11 @@ class SurveyUtil
// Validation when belonging to a session
//$session_img = api_get_session_image($survey['session_id'], $_user['status']);
$session_img = '';
$array[2] = '$survey[2]'.$session_img;
$array[3] = '$survey[3]';
$array[4] = '$survey[4]';
$array[2] = $survey->getCode();
$array[3] = $survey->getQuestions()->count();
$array[4] = UserManager::formatUserFullName($survey->getCreator());
// Dates
$array[5] = '';
$from = $survey->getAvailFrom() ? $survey->getAvailFrom()->format('Y-m-d H:i:s') : null;
if (null !== $from) {
$array[5] = api_convert_and_format_date(
@ -3594,6 +3545,7 @@ class SurveyUtil
*/
public static function getSurveyList($user_id)
{
$course = api_get_course_entity();
$_course = api_get_course_info();
$course_id = $_course['real_id'];
$user_id = (int) $user_id;
@ -3605,7 +3557,7 @@ class SurveyUtil
$table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
$table_survey = Database::get_course_table(TABLE_SURVEY);
echo '<table id="list-survey" class="table ">';
echo '<table id="list-survey" class="table">';
echo '<thead>';
echo '<tr>';
echo ' <th>'.get_lang('Survey name').'</th>';
@ -3620,8 +3572,10 @@ class SurveyUtil
/** @var \DateTime $now */
$now = api_get_utc_datetime(null, false, true);
$filterDate = $allowSurveyAvailabilityDatetime ? $now->format('Y-m-d H:i') : $now->format('Y-m-d');
$sessionCondition = api_get_session_condition($sessionId, true, false, 'survey_invitation.session_id');
$sql = "SELECT survey_invitation.answered,
$sql = "SELECT
survey_invitation.answered,
survey_invitation.invitation_code,
survey_invitation.session_id,
survey.title,
@ -3632,31 +3586,32 @@ class SurveyUtil
INNER JOIN
$table_survey_invitation survey_invitation
ON (
survey.code = survey_invitation.survey_code AND
survey.c_id = survey_invitation.c_id AND
survey.session_id = survey_invitation.session_id
survey.iid = survey_invitation.survey_id
)
WHERE
survey_invitation.user = $user_id AND
survey.avail_from <= '$filterDate' AND
survey.avail_till >= '$filterDate' AND
survey.c_id = $course_id AND
survey.session_id = $sessionId AND
survey_invitation.c_id = $course_id
$sessionCondition
";
$result = Database::query($sql);
$efv = new ExtraFieldValue('survey');
$surveyIds = [];
$repo = Container::getSurveyRepository();
while ($row = Database::fetch_array($result, 'ASSOC')) {
$surveyId = $row['iid'];
if (in_array($surveyId, $surveyIds)) {
continue;
}
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
echo '<tr>';
if (0 == $row['answered']) {
if (0 == $survey->getAnswered()) {
echo '<td>';
$url = self::generateFillSurveyLink($row['invitation_code'], $_course, $row['session_id']);
$url = self::generateFillSurveyLink($survey, $row['invitation_code'], $course, $row['session_id']);
$icon = Display::return_icon(
'survey.png',
get_lang('ClickHereToAnswerTheSurvey'),
@ -4057,19 +4012,19 @@ class SurveyUtil
}
/**
* @param string $surveyCode
* @param int $courseId
* @param int $sessionId
* @param int $surveyId
* @param int $courseId
* @param int $sessionId
*
* @return array
*/
public static function getSentInvitations($surveyCode, $courseId, $sessionId = 0)
public static function getSentInvitations($surveyId, $courseId, $sessionId = 0)
{
$tblUser = Database::get_main_table(TABLE_MAIN_USER);
$tblSurveyInvitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
$sessionCondition = api_get_session_condition($sessionId);
$surveyCode = Database::escape_string($surveyCode);
$surveyId = (int) $surveyId;
$courseId = (int) $courseId;
$sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email
@ -4077,8 +4032,8 @@ class SurveyUtil
LEFT JOIN $tblUser user
ON (survey_invitation.user = user.id AND survey_invitation.c_id = $courseId)
WHERE
survey_invitation.survey_code = '$surveyCode'
AND survey_invitation.c_id = $courseId
survey_invitation.survey_id = $surveyId AND
survey_invitation.c_id = $courseId
$sessionCondition";
$query = Database::query($sql);
@ -4088,35 +4043,25 @@ class SurveyUtil
/**
* @param string $code invitation code
* @param array $courseInfo
* @param Course $course
* @param int $sessionId
* @param string $surveyCode
*
* @return string
*/
public static function generateFillSurveyLink($code, $courseInfo, $sessionId, $surveyCode = '')
public static function generateFillSurveyLink(CSurvey $survey, $invitationCode, Course $course, $sessionId = 0)
{
$code = Security::remove_XSS($code);
$invitationCode = Security::remove_XSS($invitationCode);
$sessionId = (int) $sessionId;
if (empty($courseInfo)) {
return '';
}
$params = [
'invitationcode' => $code,
'cid' => $courseInfo['code'],
'course' => $courseInfo['code'],
'iid' => $survey->getIid(),
'invitationcode' => $invitationCode,
'cid' => $course->getId(),
'course' => $course->getCode(),
'sid' => $sessionId,
'language' => $course->getCourseLanguage(),
];
if (!empty($surveyCode)) {
$params['scode'] = Security::remove_XSS($surveyCode);
}
if (!empty($courseInfo['language'])) {
$params['language'] = $courseInfo['language'];
}
return api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?'.http_build_query($params);
}
}

@ -2,36 +2,35 @@
/* For licensing terms, see /license.txt */
/**
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
*
* @version $Id: survey_invite.php 10680 2007-01-11 21:26:23Z pcool $
*
* @todo the answered column
*/
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
require_once __DIR__.'/../inc/global.inc.php';
/** @todo this has to be moved to a more appropriate place (after the display_header of the code)*/
if (!api_is_allowed_to_edit(false, true)) {
api_not_allowed(true);
}
$tool_name = get_lang('Survey invitations');
$courseInfo = api_get_course_info();
// Getting the survey information
$survey_id = Security::remove_XSS($_GET['survey_id']);
$survey_data = SurveyManager::get_survey($survey_id);
if (empty($survey_data)) {
$course = api_get_course_entity();
$repo = Container::getSurveyRepository();
$surveyId = $_GET['survey_id'] ?? 0;
if (empty($surveyId)) {
api_not_allowed(true);
}
$view = isset($_GET['view']) ? $_GET['view'] : 'invited';
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
if (null === $survey) {
api_not_allowed(true);
}
$surveyId = $survey->getIid();
$view = $_GET['view'] ?? 'invited';
$urlname = strip_tags(
api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40)
api_substr(api_html_entity_decode($survey->getTitle(), ENT_QUOTES), 0, 40)
);
if (api_strlen(strip_tags($survey_data['title'])) > 40) {
if (api_strlen(strip_tags($survey->getTitle())) > 40) {
$urlname .= '...';
}
@ -41,42 +40,42 @@ $interbreadcrumb[] = [
'name' => get_lang('Survey list'),
];
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id,
'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$surveyId,
'name' => $urlname,
];
// Displaying the header
Display::display_header($tool_name);
$course_id = api_get_course_int_id();
$sessionId = api_get_session_id();
$sentInvitations = SurveyUtil::getSentInvitations($survey_data['code'], $course_id, $sessionId);
$sentInvitations = SurveyUtil::getSentInvitations($survey->getIid(), $course_id, $sessionId);
// Getting all the people who have filled this survey
$answered_data = SurveyManager::get_people_who_filled_survey($survey_id);
$answered_data = SurveyManager::get_people_who_filled_survey($surveyId);
$invitationsCount = count($sentInvitations);
$answeredCount = count($answered_data);
$unasnweredCount = count($sentInvitations) - count($answered_data);
$unAnsweredCount = count($sentInvitations) - count($answered_data);
if (1 == $survey_data['anonymous'] && !api_get_configuration_value('survey_anonymous_show_answered')) {
if (1 == $survey->getAnonymous() && !api_get_configuration_value('survey_anonymous_show_answered')) {
echo Display::return_message(
get_lang('This survey is anonymous. You can\'t see who answered.').' '.$answeredCount.' '.get_lang('people answered')
get_lang('This survey is anonymous. You can\'t see who answered.').' '.$answeredCount.' '.get_lang(
'people answered'
)
);
$answered_data = [];
}
if (1 == $survey_data['anonymous']) {
if (1 == $survey->getAnonymous()) {
if ($answeredCount < 2) {
$answeredCount = 0;
$unasnweredCount = $invitationsCount;
$unAnsweredCount = $invitationsCount;
}
}
$url = api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidreq();
$url = api_get_self().'?survey_id='.$surveyId.'&'.api_get_cidreq();
echo '<ul class="nav nav-tabs">';
if ('invited' == $view) {
if ('invited' === $view) {
echo '<li role="presentation" class="active"><a href="#">'.get_lang('View invited');
} else {
echo '<li role="presentation"><a href="'.$url.'&view=invited">'.
@ -84,83 +83,80 @@ if ('invited' == $view) {
}
echo ' <span class="badge badge-default">'.$invitationsCount.'</span>';
echo '</a></li>';
if ('answered' == $view) {
if ('answered' === $view) {
echo '<li role="presentation" class="active"><a href="#">'.get_lang('View people who answered');
} else {
echo '<li role="presentation"><a href="'.$url.'&view=answered">'.
echo '<li role="presentation">
<a href="'.$url.'&view=answered">'.
get_lang('View people who answered');
}
echo ' <span class="badge badge-default">'.$answeredCount.'</span>';
echo '</a></li>';
if ('unanswered' == $view) {
if ('unanswered' === $view) {
echo '<li role="presentation" class="active"><a href="#">'.get_lang('View people who didn\'t answer');
} else {
echo '<li role="presentation"><a href="'.$url.'&view=unanswered">'.
get_lang('View people who didn\'t answer');
}
echo ' <span class="badge badge-default">'.$unasnweredCount.'</span>';
echo ' <span class="badge badge-default">'.$unAnsweredCount.'</span>';
echo '</a></li>';
echo '</ul>';
// Table header
echo '<table class="table table-hover table-striped data_table" style="margin-top: 5px;">';
echo ' <tr>';
echo ' <th>'.get_lang('User').'</th>';
echo ' <th>'.get_lang('Invitation date').'</th>';
echo '<tr>';
echo '<th>'.get_lang('User').'</th>';
echo '<th>'.get_lang('Invitation date').'</th>';
switch ($view) {
case 'unanswered':
echo ' <th>'.get_lang('Survey invitation link').'</th>';
echo '<th>'.get_lang('Survey invitation link').'</th>';
break;
default:
echo ' <th>'.get_lang('Answered').'</th>';
echo '<th>'.get_lang('Answered').'</th>';
break;
}
echo ' </tr>';
echo '</tr>';
$surveyAnonymousShowAnswered = api_get_configuration_value('survey_anonymous_show_answered');
$hideSurveyReportingButton = api_get_configuration_value('hide_survey_reporting_button');
foreach ($sentInvitations as $row) {
$id = $row['iid'];
if ('invited' == $view ||
('answered' == $view && in_array($row['user'], $answered_data) && $answeredCount > 1) ||
('unanswered' == $view && !in_array($row['user'], $answered_data) && $answeredCount > 1)
$user = $row['user'];
if ('invited' === $view ||
('answered' === $view && in_array($user, $answered_data) && $answeredCount > 1) ||
('unanswered' === $view && !in_array($user, $answered_data) && $answeredCount > 1)
) {
echo '<tr>';
if (is_numeric($row['user'])) {
$userInfo = api_get_user_info($row['user']);
if (is_numeric($user)) {
$userInfo = api_get_user_info($user);
echo '<td>';
echo UserManager::getUserProfileLink($userInfo);
echo '</td>';
} else {
echo '<td>'.$row['user'].'</td>';
echo '<td>'.$user.'</td>';
}
echo ' <td>'.Display::dateToStringAgoAndLongDate($row['invitation_date']).'</td>';
if (in_array($row['user'], $answered_data)) {
if (in_array($user, $answered_data)) {
if (!$surveyAnonymousShowAnswered && !$hideSurveyReportingButton) {
echo '<td>';
echo '<a href="'.
api_get_path(WEB_CODE_PATH).
'survey/reporting.php?action=userreport&survey_id='.$survey_id.'&user='.$row['user'].'&'.api_get_cidreq().'">'.
'survey/reporting.php?action=userreport&survey_id='.$surveyId.'&user='.$user.'&'.api_get_cidreq().'">'.
get_lang('View answers').'</a>';
echo '</td>';
} else {
if (1 == $survey_data['anonymous'] && $answeredCount > 1) {
if (1 == $survey->getAnonymous() && $answeredCount > 1) {
echo '<td>'.get_lang('Answered').'</td>';
} else {
echo '<td>-</td>';
}
}
} else {
if ('unanswered' == $view) {
echo ' <td>';
if ('unanswered' === $view) {
echo '<td>';
$code = $row['invitation_code'];
$link = SurveyUtil::generateFillSurveyLink($code, $courseInfo, $sessionId);
$link = SurveyUtil::generateFillSurveyLink($survey, $code, $course, $sessionId);
$link = Display::input('text', 'copy_'.$id, $link, ['id' => 'copy_'.$id, 'class' => '']);
$link .= ' '.Display::url(
Display::returnFontAwesomeIcon('copy').get_lang('Copy text'),
@ -174,7 +170,6 @@ foreach ($sentInvitations as $row) {
echo '<td>-</td>';
}
}
echo '</tr>';
} elseif ('unanswered' === $view && 0 == $answeredCount) {
echo '<tr>';
@ -189,8 +184,7 @@ foreach ($sentInvitations as $row) {
echo ' <td>'.Display::dateToStringAgoAndLongDate($row['invitation_date']).'</td>';
echo ' <td>';
$code = $row['invitation_code'];
$link = SurveyUtil::generateFillSurveyLink($code, $courseInfo, $sessionId);
$link = SurveyUtil::generateFillSurveyLink($survey, $code, $course, $sessionId);
$link = Display::input('text', 'copy_'.$id, $link, ['id' => 'copy_'.$id, 'class' => '']);
$link .= ' '.Display::url(
Display::returnFontAwesomeIcon('copy').get_lang('Copy text'),
@ -199,12 +193,9 @@ foreach ($sentInvitations as $row) {
);
echo $link;
echo ' </td>';
echo '</tr>';
echo '</td></tr>';
}
}
// Closing the table
echo '</table>';
Display::display_footer();

@ -3,16 +3,7 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
/**
* @author unknown, the initial survey that did not make it in 1.8 because of bad code
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup, refactoring and rewriting large parts of the code
* @author Julio Montoya Chamilo: cleanup, refactoring, security improvements
*
* @todo checking if the additional emails are valid (or add a rule for this)
* @todo check if the mailtext contains the **link** part, if not, add the link to the end
* @todo add rules: title and text cannot be empty
*/
use Chamilo\CourseBundle\Entity\CSurvey;
require_once __DIR__.'/../inc/global.inc.php';
@ -21,45 +12,47 @@ $this_section = SECTION_COURSES;
if (!api_is_allowed_to_edit(false, true)) {
api_not_allowed(true);
}
$course = api_get_course_entity();
$course_id = api_get_course_int_id();
$_course = api_get_course_info();
// Getting the survey information
$survey_id = (int) $_GET['survey_id'];
$survey_data = SurveyManager::get_survey($survey_id);
if (empty($survey_data)) {
$surveyId = $_GET['survey_id'] ?? 0;
$repo = Container::getSurveyRepository();
$survey = null;
if (!empty($surveyId)) {
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
$surveyId = $survey->getIid();
}
if (null === $survey) {
api_not_allowed(true);
}
// Database table definitions
$survey_data = SurveyManager::get_survey($surveyId);
$table_survey = Database::get_course_table(TABLE_SURVEY);
$urlname = strip_tags(api_substr(api_html_entity_decode($survey_data['title'], ENT_QUOTES), 0, 40));
if (api_strlen(strip_tags($survey_data['title'])) > 40) {
$urlname = strip_tags(api_substr(api_html_entity_decode($survey->getTitle(), ENT_QUOTES), 0, 40));
if (api_strlen(strip_tags($survey->getTitle())) > 40) {
$urlname .= '...';
}
// Breadcrumbs
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
'name' => get_lang('Survey list'),
];
if (api_is_course_admin()) {
if (3 == $survey_data['survey_type']) {
if (3 == $survey->getSurveyType()) {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/meeting.php?survey_id='.$survey_id.'&'.api_get_cidreq(),
'url' => api_get_path(WEB_CODE_PATH).'survey/meeting.php?survey_id='.$surveyId.'&'.api_get_cidreq(),
'name' => $urlname,
];
} else {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey_id.'&'.api_get_cidreq(),
'url' => api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$surveyId.'&'.api_get_cidreq(),
'name' => $urlname,
];
}
} else {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?survey_id='.$survey_id.'&'.api_get_cidreq(),
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?survey_id='.$surveyId.'&'.api_get_cidreq(),
'name' => $urlname,
];
}
@ -76,7 +69,7 @@ $(function() {
// Checking if there is another survey with this code.
// If this is the case there will be a language choice
$sql = "SELECT * FROM $table_survey
/*$sql = "SELECT * FROM $table_survey
WHERE code='".Database::escape_string($survey_data['code'])."'";
$result = Database::query($sql);
if (Database::num_rows($result) > 1) {
@ -86,18 +79,14 @@ if (Database::num_rows($result) > 1) {
),
'warning'
);
}
}*/
$invitationUrl = api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?survey_id='.$surveyId.'&'.api_get_cidreq();
// Invited / answered message
if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) {
$message = Display::url(
$survey_data['answered'],
api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey_data['iid'].'&'.api_get_cidreq()
);
if ($survey->getInvited() > 0 && !isset($_POST['submit'])) {
$message = Display::url($survey->getAnswered(), $invitationUrl.'&view=answered');
$message .= ' '.get_lang('have answered').' ';
$message .= Display::url(
$survey_data['invited'],
api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey_data['iid'].'&'.api_get_cidreq());
$message .= Display::url($survey_data['invited'], $invitationUrl.'&view=invited');
$message .= ' '.get_lang('were invited');
echo Display::return_message($message, 'normal', false);
}
@ -106,25 +95,22 @@ if ($survey_data['invited'] > 0 && !isset($_POST['submit'])) {
$form = new FormValidator(
'publish_form',
'post',
api_get_self().'?survey_id='.$survey_id.'&'.api_get_cidreq()
api_get_self().'?survey_id='.$surveyId.'&'.api_get_cidreq()
);
$form->addHeader($tool_name);
$sessionId = api_get_session_id();
CourseManager::addUserGroupMultiSelect($form, [], true);
// Additional users
$form->addTextarea(
'textarea',
'additional_users',
[get_lang('Additional users'), get_lang('Additional usersComment')],
//['rows' => 5]
);
$form->addElement('html', '<div id="check_mail">');
$form->addHtml('<div id="check_mail">');
$form->addCheckBox('send_mail', '', get_lang('Send mail'));
$form->addElement('html', '</div>');
$form->addElement('html', '<div id="mail_text_wrapper">');
$form->addHtml('</div>');
$form->addHtml('<div id="mail_text_wrapper">');
// The title of the mail
$form->addText('mail_title', get_lang('Mail subject'), false);
@ -142,7 +128,7 @@ $form->addHtmlEditor(
);
$form->addElement('html', '</div>');
// You cab send a reminder to unanswered people if the survey is not anonymous
if (1 != $survey_data['anonymous'] || api_get_configuration_value('survey_anonymous_show_answered')) {
if (1 != $survey->getAnonymous() || api_get_configuration_value('survey_anonymous_show_answered')) {
$form->addElement('checkbox', 'remindUnAnswered', '', get_lang('Remind only users who didn\'t answer'));
}
// Allow resending to all selected users
@ -160,10 +146,10 @@ $form->addButtonSave(get_lang('Publish survey'));
// Show the URL that can be used by users to fill a survey without invitation
$auto_survey_link = SurveyUtil::generateFillSurveyLink(
$survey,
'auto',
$_course,
$survey_data['session_id'],
$survey_data['survey_code']
$course,
$sessionId
);
$form->addElement('label', null, get_lang('Users who are not invited can use this link to take the survey:'));
@ -171,7 +157,6 @@ $form->addElement('label', null, $auto_survey_link);
if ($form->validate()) {
$values = $form->exportValues();
$resendAll = isset($values['resend_to_all']) ? $values['resend_to_all'] : '';
$sendMail = isset($values['send_mail']) ? $values['send_mail'] : '';
$remindUnAnswered = isset($values['remindUnAnswered']) ? $values['remindUnAnswered'] : '';
@ -185,35 +170,32 @@ if ($form->validate()) {
'error'
);
// Getting the invited users
$defaults = SurveyUtil::get_invited_users($survey_data['code']);
$defaults = SurveyUtil::get_invited_users($survey);
// Getting the survey mail text
if (!empty($survey_data['reminder_mail'])) {
$defaults['mail_text'] = $survey_data['reminder_mail'];
if (!empty($survey->getReminderMail())) {
$defaults['mail_text'] = $survey->getReminderMail();
} else {
$defaults['mail_text'] = $survey_data['invite_mail'];
$defaults['mail_text'] = $survey->getInviteMail();
}
$defaults['mail_title'] = $survey_data['mail_subject'];
$defaults['mail_title'] = $survey->getMailSubject();
$defaults['send_mail'] = 1;
$form->setDefaults($defaults);
$form->display();
}
}
$repo = Container::getSurveyRepository();
$survey = $repo->find($survey_data['iid']);
// Save the invitation mail
SurveyUtil::saveInviteMail(
$survey,
$values['mail_text'],
$values['mail_title'],
!empty($survey_data['invite_mail'])
!empty($survey->getInviteMail())
);
// Saving the invitations for the course users
$count_course_users = SurveyUtil::saveInvitations(
$survey_data['iid'],
$survey,
$users,
$values['mail_title'],
$values['mail_text'],
@ -233,7 +215,7 @@ if ($form->validate()) {
}
$counter_additional_users = SurveyUtil::saveInvitations(
$survey_data['iid'],
$survey,
$additional_users,
$values['mail_title'],
$values['mail_text'],
@ -245,9 +227,9 @@ if ($form->validate()) {
// Updating the invited field in the survey table
// Counting the number of people that are invited
$total_invited = SurveyUtil::update_count_invited($survey_data['code']);
$total_invited = SurveyUtil::updateInvitedCount($survey);
$total_count = $count_course_users + $counter_additional_users;
$invitationUrl = api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?survey_id='.$survey_data['iid'].'&'.api_get_cidreq();
if ($total_invited > 0) {
$message = '<a href="'.$invitationUrl.'&view=answered">'.
$survey_data['answered'].'</a> ';
@ -262,14 +244,14 @@ if ($form->validate()) {
}
} else {
// Getting the invited users
$defaults = SurveyUtil::get_invited_users($survey_data['code']);
$defaults = SurveyUtil::get_invited_users($survey);
// Getting the survey mail text
if (!empty($survey_data['reminder_mail'])) {
$defaults['mail_text'] = $survey_data['reminder_mail'];
if (!empty($survey->getReminderMail())) {
$defaults['mail_text'] = $survey->getReminderMail();
} else {
$defaults['mail_text'] = $survey_data['invite_mail'];
$defaults['mail_text'] = $survey->getInviteMail();
}
$defaults['mail_title'] = $survey_data['mail_subject'];
$defaults['mail_title'] = $survey->getMailSubject();
$defaults['send_mail'] = 1;
$form->setDefaults($defaults);

@ -2,6 +2,8 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use ChamiloSession as Session;
/**
@ -25,7 +27,6 @@ $currentUserId = api_get_user_id();
api_protect_course_script(true);
$action = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : '';
// Tracking
Event::event_access_tool(TOOL_SURVEY);
$logInfo = [
@ -39,6 +40,8 @@ Event::registerLog($logInfo);
*/
$courseInfo = api_get_course_info();
$sessionId = api_get_session_id();
$courseId = api_get_course_int_id();
$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
$currentUserId,
$courseInfo
@ -78,7 +81,13 @@ if (isset($_GET['search']) && 'advanced' === $_GET['search']) {
}
$listUrl = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq();
$surveyId = isset($_GET['survey_id']) ? $_GET['survey_id'] : 0;
$surveyId = $_GET['survey_id'] ?? 0;
$repo = Container::getSurveyRepository();
$survey = null;
if (!empty($surveyId)) {
/** @var CSurvey $survey */
$survey = $repo->find($surveyId);
}
// Action handling: performing the same action on multiple surveys
if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_array($_POST['id'])) {
@ -97,12 +106,14 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
$table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value);
$surveyId = $surveyData['survey_id'];
if (empty($surveyData)) {
/** @var CSurvey $survey */
$survey = $repo->find($value);
if (null === $survey) {
continue;
}
$surveyData['title'] = api_html_entity_decode(trim(strip_tags($surveyData['title'])));
$surveyId = $survey->getIid();
$surveyData['title'] = api_html_entity_decode(trim(strip_tags($survey->getTitle())));
$groupData = $extraFieldValue->get_values_by_handler_and_field_variable(
$surveyId,
'group_id'
@ -149,17 +160,15 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option
ON
survey_question.iid = survey_question_option.question_id AND
survey_question_option.c_id = $course_id
survey_question.iid = survey_question_option.question_id
WHERE
survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".$surveyId."' AND
survey_question.c_id = $course_id
survey_question.survey_id = '".$surveyId."'
ORDER BY survey_question.sort, survey_question_option.sort ASC";
$result = Database::query($sql);
$questionsOptions = [];
while ($row = Database::fetch_array($result, 'ASSOC')) {
if ('pagebreak' != $row['type']) {
if ('pagebreak' !== $row['type']) {
$questionsOptions[$row['sort']]['question_id'] = $row['question_id'];
$questionsOptions[$row['sort']]['survey_id'] = $row['survey_id'];
$questionsOptions[$row['sort']]['survey_question'] = $row['survey_question'];
@ -370,23 +379,24 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
}
$exportList = [];
foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value);
if (empty($surveyData)) {
/** @var CSurvey $survey */
$survey = $repo->find($value);
if (null === $survey) {
continue;
}
$surveyData['title'] = trim(strip_tags($surveyData['title']));
$title = trim(strip_tags($survey->getTitle()));
switch ($action) {
case 'export_all':
$filename = $surveyData['code'].'.xlsx';
$exportList[] = @SurveyUtil::export_complete_report_xls($surveyData, $filename, 0, true);
$filename = $survey->getCode().'.xlsx';
$exportList[] = @SurveyUtil::export_complete_report_xls($survey, $filename, 0, true);
break;
case 'send_to_tutors':
$result = SurveyManager::sendToTutors($value);
if ($result) {
Display::addFlash(
Display::return_message(
get_lang('InvitationHasBeenSent').': '.$surveyData['title'],
get_lang('The invitation has been sent').': '.$title,
'confirmation',
false
)
@ -394,7 +404,7 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} else {
Display::addFlash(
Display::return_message(
get_lang('InvitationHasBeenNotSent').': '.$surveyData['title'],
get_lang("The invitation hasn't been sent").': '.$title,
'warning',
false
)
@ -402,12 +412,11 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
}
break;
case 'multiplicate':
$result = SurveyManager::multiplicateQuestions($surveyData);
$title = $surveyData['title'];
$result = SurveyManager::multiplicateQuestions($survey, $courseId);
if ($result) {
Display::addFlash(
Display::return_message(
sprintf(get_lang('SurveyXMultiplicated'), $title),
sprintf(get_lang('Survey %s multiplicated'), $title),
'confirmation',
false
)
@ -415,7 +424,7 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} else {
Display::addFlash(
Display::return_message(
sprintf(get_lang('SurveyXNotMultiplicated'), $title),
sprintf(get_lang('Survey %s not multiplicated'), $title),
'warning',
false
)
@ -424,14 +433,13 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
break;
case 'delete':
// if the survey is shared => also delete the shared content
if (is_numeric($surveyData['survey_share'])) {
/*if (is_numeric($surveyData['survey_share'])) {
SurveyManager::delete_survey($surveyData['survey_share'], true);
}
}*/
// delete the actual survey
SurveyManager::delete_survey($value);
SurveyManager::deleteSurvey($survey);
Display::addFlash(
Display::return_message(get_lang('SurveysDeleted').': '.$surveyData['title'], 'confirmation', false)
Display::return_message(get_lang('Surveys deleted').': '.$title, 'confirmation', false)
);
break;
}
@ -473,9 +481,8 @@ switch ($action) {
if (!api_is_allowed_to_edit()) {
api_not_allowed(true);
}
$surveyData = SurveyManager::get_survey($surveyId);
if (!empty($surveyData)) {
SurveyManager::multiplicateQuestions($surveyData);
if (null !== $survey) {
SurveyManager::multiplicateQuestions($survey, $courseId);
Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false));
}
header('Location: '.$listUrl);
@ -485,9 +492,8 @@ switch ($action) {
if (!api_is_allowed_to_edit()) {
api_not_allowed(true);
}
$surveyData = SurveyManager::get_survey($surveyId);
if (!empty($surveyData)) {
SurveyManager::removeMultiplicateQuestions($surveyData);
if (null !== $survey) {
SurveyManager::removeMultiplicateQuestions($survey, $courseId);
Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false));
}
header('Location: '.$listUrl);
@ -502,30 +508,32 @@ switch ($action) {
}
break;
case 'delete':
if (!empty($surveyId)) {
if (null !== $survey) {
// Getting the information of the survey (used for when the survey is shared)
$survey_data = SurveyManager::get_survey($surveyId);
/*$survey_data = SurveyManager::get_survey($surveyId);
if (api_is_session_general_coach() && $sessionId != $survey_data['session_id']) {
// The coach can't delete a survey not belonging to his session
api_not_allowed();
}
}*/
// If the survey is shared => also delete the shared content
if (isset($survey_data['survey_share']) &&
/*if (isset($survey_data['survey_share']) &&
is_numeric($survey_data['survey_share'])
) {
SurveyManager::delete_survey($survey_data['survey_share'], true);
}
$return = SurveyManager::delete_survey($surveyId);
}*/
$return = SurveyManager::deleteSurvey($survey);
if ($return) {
Display::addFlash(Display::return_message(get_lang('The survey has been deleted.'), 'confirmation', false));
Display::addFlash(
Display::return_message(get_lang('The survey has been deleted.'), 'confirmation', false)
);
} else {
Display::addFlash(Display::return_message(get_lang('An error occurred.'), 'error', false));
}
header('Location: '.$listUrl);
exit;
}
header('Location: '.$listUrl);
exit;
break;
case 'empty':
$mysession = api_get_session_id();
@ -542,7 +550,9 @@ switch ($action) {
}
$return = SurveyManager::empty_survey($surveyId);
if ($return) {
Display::addFlash(Display::return_message(get_lang('Answers to survey successfully deleted'), 'confirmation', false));
Display::addFlash(
Display::return_message(get_lang('Answers to survey successfully deleted'), 'confirmation', false)
);
} else {
Display::addFlash(Display::return_message(get_lang('An error occurred.'), 'error', false));
}

@ -150,9 +150,9 @@ class survey_question
$surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : null;
$type = isset($_GET['type']) ? Security::remove_XSS($_GET['type']) : null;
$actionHeader = get_lang('EditQuestion').': ';
$actionHeader = get_lang('Edit question').': ';
if ('add' === $action) {
$actionHeader = get_lang('AddQuestion').': ';
$actionHeader = get_lang('Add a question').': ';
}
$questionComment = '';
@ -164,25 +164,29 @@ class survey_question
$allowParent = true;
break;
case 'yesno':
$toolName = get_lang('YesNo');
$toolName = get_lang('Yes / No');
$allowParent = true;
break;
case 'multiplechoice':
$toolName = get_lang('UniqueSelect');
$toolName = get_lang('Multiple choice');
$allowParent = true;
break;
case 'multipleresponse':
$toolName = get_lang('MultipleResponse');
$toolName = get_lang('Multiple answers');
$allowParent = true;
break;
case 'selectivedisplay':
$toolName = get_lang('SurveyQuestionSelectiveDisplay');
$questionComment = get_lang('SurveyQuestionSelectiveDisplayComment');
$toolName = get_lang('Selective display');
$questionComment = get_lang(
"This question, when located on a single survey page with a first multiple choice question, will only show if the first *option* of the first question is selected. For example, 'Did you go on holiday?' -> if answering the first option 'Yes', the selective display question will appear with a list of possible holiday locations to select from."
);
$allowParent = true;
break;
case 'multiplechoiceother':
$toolName = get_lang('SurveyQuestionMultipleChoiceWithOther');
$questionComment = get_lang('SurveyQuestionMultipleChoiceWithOtherComment');
$toolName = get_lang('Multiple choice with free text');
$questionComment = get_lang(
'Offer some pre-defined options, then let the user answer by text if no option matches.'
);
$allowParent = true;
break;
case 'pagebreak':
@ -206,9 +210,10 @@ class survey_question
).' ';
$toolName = $icon.$actionHeader.$toolName;
$sharedQuestionId = isset($formData['shared_question_id']) ? $formData['shared_question_id'] : null;
$sharedQuestionId = $formData['shared_question_id'] ?? null;
$url = api_get_self().'?action='.$action.'&type='.$type.'&survey_id='.$surveyId.'&question_id='.$questionId.'&'.api_get_cidreq();
$url = api_get_self().
'?action='.$action.'&type='.$type.'&survey_id='.$surveyId.'&question_id='.$questionId.'&'.api_get_cidreq();
$form = new FormValidator('question_form', 'post', $url);
$form->addHeader($toolName);
if (!empty($questionComment)) {
@ -277,10 +282,10 @@ class survey_question
);
}
$this->html .= ' <tr><td colspan="">
<fieldset style="border:1px solid black">
<legend>'.get_lang('Condition').'</legend>
<b>'.get_lang('Primary').'</b><br />
$this->html .= '<tr><td colspan="">
<fieldset style="border:1px solid black">
<legend>'.get_lang('Condition').'</legend>
<b>'.get_lang('Primary').'</b><br />
<input type="radio" name="choose" value="1" '.((1 == $formData['choose']) ? 'checked' : '').'>
<select name="assigned">'.$grouplist.'</select><br />';
$this->html .= '
@ -310,15 +315,15 @@ class survey_question
$surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
$answersChecker = SurveyUtil::checkIfSurveyHasAnswers($surveyId);
$allowQuestionEdit = true == api_get_configuration_value('survey_allow_answered_question_edit');
if ($allowQuestionEdit or !$answersChecker) {
$this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('ModifyQuestionSurvey'), 'save', true);
if ($allowQuestionEdit || !$answersChecker) {
$this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('Edit question'), 'save', true);
} else {
$this->getForm()->addHtml('
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-8">
<div class="alert alert-info">'.
get_lang('YouCantNotEditThisQuestionBecauseAlreadyExistAnswers').'</div>
get_lang("You can't edit this question because answers by students have already been registered").'</div>
</div>
<div class="col-sm-2"></div>
</div>
@ -358,7 +363,7 @@ class survey_question
$answerList = Session::read('answer_list');
if (empty($answerList)) {
$answerList = isset($formData['answers']) ? $formData['answers'] : [];
$answerList = $formData['answers'] ?? [];
Session::write('answer_list', $answerList);
}

@ -1,7 +1,7 @@
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="{{ user_avatar }}" alt="{{ user.completeName }}">
<img class="media-object" src="{{ user | illustration }}" alt="{{ user.completeName }}">
</a>
</div>
<div class="media-body">

Loading…
Cancel
Save