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

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

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

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

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

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

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

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

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

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

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

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

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

@ -2,6 +2,8 @@
/* For licensing terms, see /license.txt */ /* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CSurvey;
use ChamiloSession as Session; use ChamiloSession as Session;
/** /**
@ -25,7 +27,6 @@ $currentUserId = api_get_user_id();
api_protect_course_script(true); api_protect_course_script(true);
$action = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : ''; $action = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : '';
// Tracking
Event::event_access_tool(TOOL_SURVEY); Event::event_access_tool(TOOL_SURVEY);
$logInfo = [ $logInfo = [
@ -39,6 +40,8 @@ Event::registerLog($logInfo);
*/ */
$courseInfo = api_get_course_info(); $courseInfo = api_get_course_info();
$sessionId = api_get_session_id(); $sessionId = api_get_session_id();
$courseId = api_get_course_int_id();
$isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh( $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
$currentUserId, $currentUserId,
$courseInfo $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(); $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 // Action handling: performing the same action on multiple surveys
if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_array($_POST['id'])) { 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); $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
foreach ($_POST['id'] as $value) { foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value); /** @var CSurvey $survey */
$surveyId = $surveyData['survey_id']; $survey = $repo->find($value);
if (empty($surveyData)) { if (null === $survey) {
continue; 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( $groupData = $extraFieldValue->get_values_by_handler_and_field_variable(
$surveyId, $surveyId,
'group_id' 'group_id'
@ -149,17 +160,15 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
FROM $table_survey_question survey_question FROM $table_survey_question survey_question
LEFT JOIN $table_survey_question_option survey_question_option LEFT JOIN $table_survey_question_option survey_question_option
ON ON
survey_question.iid = survey_question_option.question_id AND survey_question.iid = survey_question_option.question_id
survey_question_option.c_id = $course_id
WHERE WHERE
survey_question NOT LIKE '%{{%' AND survey_question NOT LIKE '%{{%' AND
survey_question.survey_id = '".$surveyId."' AND survey_question.survey_id = '".$surveyId."'
survey_question.c_id = $course_id
ORDER BY survey_question.sort, survey_question_option.sort ASC"; ORDER BY survey_question.sort, survey_question_option.sort ASC";
$result = Database::query($sql); $result = Database::query($sql);
$questionsOptions = []; $questionsOptions = [];
while ($row = Database::fetch_array($result, 'ASSOC')) { 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']]['question_id'] = $row['question_id'];
$questionsOptions[$row['sort']]['survey_id'] = $row['survey_id']; $questionsOptions[$row['sort']]['survey_id'] = $row['survey_id'];
$questionsOptions[$row['sort']]['survey_question'] = $row['survey_question']; $questionsOptions[$row['sort']]['survey_question'] = $row['survey_question'];
@ -370,23 +379,24 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} }
$exportList = []; $exportList = [];
foreach ($_POST['id'] as $value) { foreach ($_POST['id'] as $value) {
$surveyData = SurveyManager::get_survey($value); /** @var CSurvey $survey */
if (empty($surveyData)) { $survey = $repo->find($value);
if (null === $survey) {
continue; continue;
} }
$surveyData['title'] = trim(strip_tags($surveyData['title'])); $title = trim(strip_tags($survey->getTitle()));
switch ($action) { switch ($action) {
case 'export_all': case 'export_all':
$filename = $surveyData['code'].'.xlsx'; $filename = $survey->getCode().'.xlsx';
$exportList[] = @SurveyUtil::export_complete_report_xls($surveyData, $filename, 0, true); $exportList[] = @SurveyUtil::export_complete_report_xls($survey, $filename, 0, true);
break; break;
case 'send_to_tutors': case 'send_to_tutors':
$result = SurveyManager::sendToTutors($value); $result = SurveyManager::sendToTutors($value);
if ($result) { if ($result) {
Display::addFlash( Display::addFlash(
Display::return_message( Display::return_message(
get_lang('InvitationHasBeenSent').': '.$surveyData['title'], get_lang('The invitation has been sent').': '.$title,
'confirmation', 'confirmation',
false false
) )
@ -394,7 +404,7 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} else { } else {
Display::addFlash( Display::addFlash(
Display::return_message( Display::return_message(
get_lang('InvitationHasBeenNotSent').': '.$surveyData['title'], get_lang("The invitation hasn't been sent").': '.$title,
'warning', 'warning',
false false
) )
@ -402,12 +412,11 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} }
break; break;
case 'multiplicate': case 'multiplicate':
$result = SurveyManager::multiplicateQuestions($surveyData); $result = SurveyManager::multiplicateQuestions($survey, $courseId);
$title = $surveyData['title'];
if ($result) { if ($result) {
Display::addFlash( Display::addFlash(
Display::return_message( Display::return_message(
sprintf(get_lang('SurveyXMultiplicated'), $title), sprintf(get_lang('Survey %s multiplicated'), $title),
'confirmation', 'confirmation',
false false
) )
@ -415,7 +424,7 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
} else { } else {
Display::addFlash( Display::addFlash(
Display::return_message( Display::return_message(
sprintf(get_lang('SurveyXNotMultiplicated'), $title), sprintf(get_lang('Survey %s not multiplicated'), $title),
'warning', 'warning',
false false
) )
@ -424,14 +433,13 @@ if (isset($_POST['action']) && $_POST['action'] && isset($_POST['id']) && is_arr
break; break;
case 'delete': case 'delete':
// if the survey is shared => also delete the shared content // 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); SurveyManager::delete_survey($surveyData['survey_share'], true);
} }*/
// delete the actual survey SurveyManager::deleteSurvey($survey);
SurveyManager::delete_survey($value);
Display::addFlash( Display::addFlash(
Display::return_message(get_lang('SurveysDeleted').': '.$surveyData['title'], 'confirmation', false) Display::return_message(get_lang('Surveys deleted').': '.$title, 'confirmation', false)
); );
break; break;
} }
@ -473,9 +481,8 @@ switch ($action) {
if (!api_is_allowed_to_edit()) { if (!api_is_allowed_to_edit()) {
api_not_allowed(true); api_not_allowed(true);
} }
$surveyData = SurveyManager::get_survey($surveyId); if (null !== $survey) {
if (!empty($surveyData)) { SurveyManager::multiplicateQuestions($survey, $courseId);
SurveyManager::multiplicateQuestions($surveyData);
Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false)); Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false));
} }
header('Location: '.$listUrl); header('Location: '.$listUrl);
@ -485,9 +492,8 @@ switch ($action) {
if (!api_is_allowed_to_edit()) { if (!api_is_allowed_to_edit()) {
api_not_allowed(true); api_not_allowed(true);
} }
$surveyData = SurveyManager::get_survey($surveyId); if (null !== $survey) {
if (!empty($surveyData)) { SurveyManager::removeMultiplicateQuestions($survey, $courseId);
SurveyManager::removeMultiplicateQuestions($surveyData);
Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false)); Display::addFlash(Display::return_message(get_lang('Updated'), 'confirmation', false));
} }
header('Location: '.$listUrl); header('Location: '.$listUrl);
@ -502,30 +508,32 @@ switch ($action) {
} }
break; break;
case 'delete': case 'delete':
if (!empty($surveyId)) { if (null !== $survey) {
// Getting the information of the survey (used for when the survey is shared) // 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']) { if (api_is_session_general_coach() && $sessionId != $survey_data['session_id']) {
// The coach can't delete a survey not belonging to his session // The coach can't delete a survey not belonging to his session
api_not_allowed(); api_not_allowed();
} }*/
// If the survey is shared => also delete the shared content // 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']) is_numeric($survey_data['survey_share'])
) { ) {
SurveyManager::delete_survey($survey_data['survey_share'], true); SurveyManager::delete_survey($survey_data['survey_share'], true);
} }*/
$return = SurveyManager::delete_survey($surveyId);
$return = SurveyManager::deleteSurvey($survey);
if ($return) { 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 { } else {
Display::addFlash(Display::return_message(get_lang('An error occurred.'), 'error', false)); Display::addFlash(Display::return_message(get_lang('An error occurred.'), 'error', false));
} }
header('Location: '.$listUrl);
exit;
} }
header('Location: '.$listUrl);
exit;
break; break;
case 'empty': case 'empty':
$mysession = api_get_session_id(); $mysession = api_get_session_id();
@ -542,7 +550,9 @@ switch ($action) {
} }
$return = SurveyManager::empty_survey($surveyId); $return = SurveyManager::empty_survey($surveyId);
if ($return) { 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 { } else {
Display::addFlash(Display::return_message(get_lang('An error occurred.'), 'error', false)); 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; $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : null;
$type = isset($_GET['type']) ? Security::remove_XSS($_GET['type']) : null; $type = isset($_GET['type']) ? Security::remove_XSS($_GET['type']) : null;
$actionHeader = get_lang('EditQuestion').': '; $actionHeader = get_lang('Edit question').': ';
if ('add' === $action) { if ('add' === $action) {
$actionHeader = get_lang('AddQuestion').': '; $actionHeader = get_lang('Add a question').': ';
} }
$questionComment = ''; $questionComment = '';
@ -164,25 +164,29 @@ class survey_question
$allowParent = true; $allowParent = true;
break; break;
case 'yesno': case 'yesno':
$toolName = get_lang('YesNo'); $toolName = get_lang('Yes / No');
$allowParent = true; $allowParent = true;
break; break;
case 'multiplechoice': case 'multiplechoice':
$toolName = get_lang('UniqueSelect'); $toolName = get_lang('Multiple choice');
$allowParent = true; $allowParent = true;
break; break;
case 'multipleresponse': case 'multipleresponse':
$toolName = get_lang('MultipleResponse'); $toolName = get_lang('Multiple answers');
$allowParent = true; $allowParent = true;
break; break;
case 'selectivedisplay': case 'selectivedisplay':
$toolName = get_lang('SurveyQuestionSelectiveDisplay'); $toolName = get_lang('Selective display');
$questionComment = get_lang('SurveyQuestionSelectiveDisplayComment'); $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; $allowParent = true;
break; break;
case 'multiplechoiceother': case 'multiplechoiceother':
$toolName = get_lang('SurveyQuestionMultipleChoiceWithOther'); $toolName = get_lang('Multiple choice with free text');
$questionComment = get_lang('SurveyQuestionMultipleChoiceWithOtherComment'); $questionComment = get_lang(
'Offer some pre-defined options, then let the user answer by text if no option matches.'
);
$allowParent = true; $allowParent = true;
break; break;
case 'pagebreak': case 'pagebreak':
@ -206,9 +210,10 @@ class survey_question
).' '; ).' ';
$toolName = $icon.$actionHeader.$toolName; $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 = new FormValidator('question_form', 'post', $url);
$form->addHeader($toolName); $form->addHeader($toolName);
if (!empty($questionComment)) { if (!empty($questionComment)) {
@ -277,10 +282,10 @@ class survey_question
); );
} }
$this->html .= ' <tr><td colspan=""> $this->html .= '<tr><td colspan="">
<fieldset style="border:1px solid black"> <fieldset style="border:1px solid black">
<legend>'.get_lang('Condition').'</legend> <legend>'.get_lang('Condition').'</legend>
<b>'.get_lang('Primary').'</b><br /> <b>'.get_lang('Primary').'</b><br />
<input type="radio" name="choose" value="1" '.((1 == $formData['choose']) ? 'checked' : '').'> <input type="radio" name="choose" value="1" '.((1 == $formData['choose']) ? 'checked' : '').'>
<select name="assigned">'.$grouplist.'</select><br />'; <select name="assigned">'.$grouplist.'</select><br />';
$this->html .= ' $this->html .= '
@ -310,15 +315,15 @@ class survey_question
$surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0; $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
$answersChecker = SurveyUtil::checkIfSurveyHasAnswers($surveyId); $answersChecker = SurveyUtil::checkIfSurveyHasAnswers($surveyId);
$allowQuestionEdit = true == api_get_configuration_value('survey_allow_answered_question_edit'); $allowQuestionEdit = true == api_get_configuration_value('survey_allow_answered_question_edit');
if ($allowQuestionEdit or !$answersChecker) { if ($allowQuestionEdit || !$answersChecker) {
$this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('ModifyQuestionSurvey'), 'save', true); $this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('Edit question'), 'save', true);
} else { } else {
$this->getForm()->addHtml(' $this->getForm()->addHtml('
<div class="form-group"> <div class="form-group">
<label class="col-sm-2 control-label"></label> <label class="col-sm-2 control-label"></label>
<div class="col-sm-8"> <div class="col-sm-8">
<div class="alert alert-info">'. <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>
<div class="col-sm-2"></div> <div class="col-sm-2"></div>
</div> </div>
@ -358,7 +363,7 @@ class survey_question
$answerList = Session::read('answer_list'); $answerList = Session::read('answer_list');
if (empty($answerList)) { if (empty($answerList)) {
$answerList = isset($formData['answers']) ? $formData['answers'] : []; $answerList = $formData['answers'] ?? [];
Session::write('answer_list', $answerList); Session::write('answer_list', $answerList);
} }

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

Loading…
Cancel
Save