fillsurvey.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. /**
  5. * @package chamilo.survey
  6. *
  7. * @author unknown, the initial survey that did not make it in 1.8 because of bad code
  8. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup,
  9. * refactoring and rewriting large parts of the code
  10. * @author Julio Montoya <gugli100@gmail.com>, Chamilo: Personality Test
  11. * modification and rewriting large parts of the code as well
  12. *
  13. * @todo check if the user already filled the survey and if this
  14. * is the case then the answers have to be updated and not stored again.
  15. * @todo performance could be improved if not the survey_id was
  16. * stored with the invitation but the survey_code
  17. */
  18. // Unsetting the course id (because it is in the URL)
  19. if (!isset($_GET['cidReq'])) {
  20. $cidReset = true;
  21. } else {
  22. $_cid = $_GET['cidReq'];
  23. }
  24. require_once __DIR__.'/../inc/global.inc.php';
  25. // Database table definitions
  26. $table_survey = Database::get_course_table(TABLE_SURVEY);
  27. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  28. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  29. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  30. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  31. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  32. $allowRequiredSurveyQuestions = api_get_configuration_value('allow_required_survey_questions');
  33. // Check if user is anonymous or not
  34. $isAnonymous = false;
  35. if (api_is_anonymous(api_get_user_id(), true)) {
  36. $isAnonymous = true;
  37. }
  38. // getting all the course information
  39. if (isset($_GET['course'])) {
  40. $courseInfo = api_get_course_info($_GET['course']);
  41. } else {
  42. $courseInfo = api_get_course_info();
  43. }
  44. if (empty($courseInfo)) {
  45. api_not_allowed(true);
  46. }
  47. $userInfo = api_get_user_info();
  48. $sessionId = isset($_GET['id_session']) ? (int) $_GET['id_session'] : api_get_session_id();
  49. // Breadcrumbs
  50. if (!empty($userInfo)) {
  51. $interbreadcrumb[] = [
  52. 'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId,
  53. 'name' => get_lang('Survey list'),
  54. ];
  55. }
  56. $course_id = $courseInfo['real_id'];
  57. $surveyCode = isset($_GET['scode']) ? Database::escape_string($_GET['scode']) : '';
  58. if ($surveyCode != '') {
  59. // Firstly we check if this survey is ready for anonymous use:
  60. $sql = "SELECT anonymous FROM $table_survey
  61. WHERE c_id = $course_id AND code ='".$surveyCode."'";
  62. $resultAnonymous = Database::query($sql);
  63. $rowAnonymous = Database::fetch_array($resultAnonymous, 'ASSOC');
  64. // If is anonymous and is not allowed to take the survey to anonymous users, forbid access:
  65. if (!isset($rowAnonymous['anonymous']) ||
  66. ($rowAnonymous['anonymous'] == 0 && api_is_anonymous()) ||
  67. count($rowAnonymous) == 0
  68. ) {
  69. api_not_allowed(true);
  70. }
  71. // If is anonymous and it is allowed to take the survey as anonymous, mark survey as anonymous.
  72. }
  73. // First we check if the needed parameters are present
  74. if ((!isset($_GET['course']) || !isset($_GET['invitationcode'])) && !isset($_GET['user_id'])) {
  75. api_not_allowed(true, get_lang('There is a parameter missing in the link. Please use copy and past'));
  76. }
  77. $invitationcode = $_GET['invitationcode'];
  78. // Start auto-invitation feature FS#3403 (all-users-can-do-the-survey-URL handling)
  79. if ($invitationcode == 'auto' && isset($_GET['scode'])) {
  80. $userid = api_get_user_id();
  81. // Survey_code of the survey
  82. $surveyCode = $_GET['scode'];
  83. if ($isAnonymous) {
  84. $autoInvitationcode = 'auto-ANONY_'.md5(time())."-$surveyCode";
  85. } else {
  86. $invitations = SurveyManager::getUserInvitationsForSurveyInCourse(
  87. $userid,
  88. $surveyCode,
  89. $courseInfo['real_id'],
  90. $sessionId
  91. );
  92. $lastInvitation = current($invitations);
  93. if (!$lastInvitation) {
  94. // New invitation code from userid
  95. $autoInvitationcode = "auto-$userid-$surveyCode";
  96. } else {
  97. $autoInvitationcode = $lastInvitation->getInvitationCode();
  98. }
  99. }
  100. // The survey code must exist in this course, or the URL is invalid
  101. $sql = "SELECT * FROM $table_survey
  102. WHERE c_id = $course_id AND code = '".Database::escape_string($surveyCode)."'";
  103. $result = Database::query($sql);
  104. if (Database :: num_rows($result) > 0) {
  105. // Check availability
  106. $row = Database::fetch_array($result, 'ASSOC');
  107. $tempdata = SurveyManager::get_survey($row['survey_id']);
  108. SurveyManager::checkTimeAvailability($tempdata);
  109. // Check for double invitation records (insert should be done once)
  110. $sql = "SELECT user
  111. FROM $table_survey_invitation
  112. WHERE
  113. c_id = $course_id AND
  114. invitation_code = '".Database::escape_string($autoInvitationcode)."'";
  115. $result = Database::query($sql);
  116. $now = api_get_utc_datetime();
  117. if (Database :: num_rows($result) == 0) {
  118. $params = [
  119. 'c_id' => $course_id,
  120. 'survey_code' => $surveyCode,
  121. 'user' => $userid,
  122. 'invitation_code' => $autoInvitationcode,
  123. 'invitation_date' => $now,
  124. ];
  125. Database::insert($table_survey_invitation, $params);
  126. }
  127. // From here we use the new invitationcode auto-userid-surveycode string
  128. $_GET['invitationcode'] = $autoInvitationcode;
  129. $invitationcode = $autoInvitationcode;
  130. }
  131. }
  132. // Now we check if the invitation code is valid
  133. $sql = "SELECT * FROM $table_survey_invitation
  134. WHERE
  135. c_id = $course_id AND
  136. invitation_code = '".Database::escape_string($invitationcode)."'";
  137. $result = Database::query($sql);
  138. if (Database::num_rows($result) < 1) {
  139. api_not_allowed(true, get_lang('Wrong invitation code'));
  140. }
  141. $survey_invitation = Database::fetch_array($result, 'ASSOC');
  142. $surveyUserFromSession = Session::read('surveyuser');
  143. // Now we check if the user already filled the survey
  144. if (!isset($_POST['finish_survey']) &&
  145. (
  146. $isAnonymous &&
  147. !empty($surveyUserFromSession) &&
  148. SurveyUtil::isSurveyAnsweredFlagged($survey_invitation['survey_code'], $survey_invitation['c_id'])
  149. ) ||
  150. ($survey_invitation['answered'] == 1 && !isset($_GET['user_id']))
  151. ) {
  152. api_not_allowed(true, Display::return_message(get_lang('You already filled this survey')));
  153. }
  154. $logInfo = [
  155. 'tool' => TOOL_SURVEY,
  156. 'tool_id' => $survey_invitation['survey_invitation_id'],
  157. 'tool_id_detail' => 0,
  158. 'action' => 'invitationcode',
  159. 'action_details' => $invitationcode,
  160. ];
  161. Event::registerLog($logInfo);
  162. // Checking if there is another survey with this code.
  163. // If this is the case there will be a language choice
  164. $sql = "SELECT * FROM $table_survey
  165. WHERE
  166. c_id = $course_id AND
  167. code = '".Database::escape_string($survey_invitation['survey_code'])."'";
  168. $sql .= api_get_session_condition($sessionId);
  169. $result = Database::query($sql);
  170. if (Database::num_rows($result) > 1) {
  171. if ($_POST['language']) {
  172. $survey_invitation['survey_id'] = $_POST['language'];
  173. } else {
  174. Display::display_header(get_lang('Surveys'));
  175. $frmLangUrl = api_get_self().'?'.api_get_cidreq().'&'
  176. .http_build_query([
  177. 'course' => Security::remove_XSS($_GET['course']),
  178. 'invitationcode' => Security::remove_XSS($_GET['invitationcode']),
  179. ]);
  180. echo '<form id="language" name="language" method="POST" action="'.$frmLangUrl.'">';
  181. echo '<select name="language">';
  182. while ($row = Database::fetch_array($result, 'ASSOC')) {
  183. echo '<option value="'.$row['survey_id'].'">'.$row['lang'].'</option>';
  184. }
  185. echo '</select>';
  186. echo '<button type="submit" name="Submit" class="next">'.get_lang('Validate').'</button>';
  187. echo '</form>';
  188. Display::display_footer();
  189. exit();
  190. }
  191. } else {
  192. $row = Database::fetch_array($result, 'ASSOC');
  193. $survey_invitation['survey_id'] = $row['survey_id'];
  194. }
  195. // Getting the survey information
  196. $survey_data = SurveyManager::get_survey($survey_invitation['survey_id']);
  197. if (empty($survey_data)) {
  198. api_not_allowed(true);
  199. }
  200. // Checking time availability
  201. SurveyManager::checkTimeAvailability($survey_data);
  202. $survey_data['survey_id'] = $survey_invitation['survey_id'];
  203. if ($survey_data['survey_type'] == '3') {
  204. header('Location: '.
  205. api_get_path(WEB_CODE_PATH).
  206. 'survey/meeting.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&invitationcode='.Security::remove_XSS($invitationcode)
  207. );
  208. exit;
  209. }
  210. if (!empty($survey_data['anonymous'])) {
  211. define('USER_IN_ANON_SURVEY', true);
  212. }
  213. // Storing the answers
  214. if (count($_POST) > 0) {
  215. if ($survey_data['survey_type'] === '0') {
  216. $types = [];
  217. $required = [];
  218. // Getting all the types of the question
  219. // (because of the special treatment of the score question type
  220. $sql = "SELECT * FROM $table_survey_question
  221. WHERE
  222. c_id = $course_id AND
  223. survey_id = '".intval($survey_invitation['survey_id'])."'";
  224. $result = Database::query($sql);
  225. while ($row = Database::fetch_array($result, 'ASSOC')) {
  226. $types[$row['question_id']] = $row['type'];
  227. $required[$row['question_id']] = $allowRequiredSurveyQuestions && $row['is_required'];
  228. }
  229. // Looping through all the post values
  230. foreach ($_POST as $key => &$value) {
  231. // If the post value key contains the string 'question' then it is an answer on a question
  232. if (strpos($key, 'question') !== false && ($key != '_qf__question')) {
  233. // Finding the question id by removing 'question'
  234. $survey_question_id = str_replace('question', '', $key);
  235. // If not question ID was defined, we're on the start
  236. // screen or something else that doesn't require
  237. // saving an answer
  238. if (empty($survey_question_id)) {
  239. continue;
  240. }
  241. /* If the post value is an array then we have a multiple response question or a scoring question type
  242. remark: when it is a multiple response then the value of the array is the option_id
  243. when it is a scoring question then the key of the array is the option_id and the value is the value
  244. */
  245. if (is_array($value)) {
  246. SurveyUtil::remove_answer(
  247. $survey_invitation['user'],
  248. $survey_invitation['survey_id'],
  249. $survey_question_id,
  250. $course_id
  251. );
  252. foreach ($value as $answer_key => &$answer_value) {
  253. if ($types[$survey_question_id] == 'score') {
  254. $option_id = $answer_key;
  255. $option_value = $answer_value;
  256. } else {
  257. $option_id = $answer_value;
  258. $option_value = '';
  259. }
  260. SurveyUtil::store_answer(
  261. $survey_invitation['user'],
  262. $survey_invitation['survey_id'],
  263. $survey_question_id,
  264. $option_id,
  265. $option_value,
  266. $survey_data
  267. );
  268. }
  269. } else {
  270. // All the other question types (open question, multiple choice, percentage, ...)
  271. if (isset($types[$survey_question_id]) &&
  272. $types[$survey_question_id] == 'percentage') {
  273. $sql = "SELECT * FROM $table_survey_question_option
  274. WHERE
  275. c_id = $course_id AND
  276. question_option_id='".intval($value)."'";
  277. $result = Database::query($sql);
  278. $row = Database::fetch_array($result, 'ASSOC');
  279. $option_value = $row['option_text'];
  280. } else {
  281. $option_value = 0;
  282. if (isset($types[$survey_question_id]) &&
  283. $types[$survey_question_id] == 'open'
  284. ) {
  285. $option_value = $value;
  286. }
  287. }
  288. $survey_question_answer = $value;
  289. SurveyUtil::remove_answer(
  290. $survey_invitation['user'],
  291. $survey_invitation['survey_id'],
  292. $survey_question_id,
  293. $course_id
  294. );
  295. SurveyUtil::store_answer(
  296. $survey_invitation['user'],
  297. $survey_invitation['survey_id'],
  298. $survey_question_id,
  299. $value,
  300. $option_value,
  301. $survey_data
  302. );
  303. }
  304. }
  305. }
  306. } elseif ($survey_data['survey_type'] === '1') {
  307. //conditional/personality-test type surveys
  308. // Getting all the types of the question (because of the special treatment of the score question type
  309. $shuffle = '';
  310. if ($survey_data['shuffle'] == '1') {
  311. $shuffle = ' ORDER BY RAND() ';
  312. }
  313. $sql = "SELECT * FROM $table_survey_question
  314. WHERE
  315. c_id = $course_id AND
  316. survey_id = '".intval($survey_invitation['survey_id'])."' AND
  317. survey_group_pri = '0' $shuffle";
  318. $result = Database::query($sql);
  319. // There is only one question type for conditional surveys
  320. while ($row = Database::fetch_array($result, 'ASSOC')) {
  321. $types[$row['question_id']] = $row['type'];
  322. }
  323. // Looping through all the post values
  324. foreach ($_POST as $key => &$value) {
  325. // If the post value key contains the string 'question' then it is an answer to a question
  326. if (strpos($key, 'question') !== false) {
  327. // Finding the question id by removing 'question'
  328. $survey_question_id = str_replace('question', '', $key);
  329. // If not question ID was defined, we're on the start
  330. // screen or something else that doesn't require
  331. // saving an answer
  332. if (empty($survey_question_id)) {
  333. continue;
  334. }
  335. // We select the correct answer and the puntuacion
  336. $sql = "SELECT value FROM $table_survey_question_option
  337. WHERE c_id = $course_id AND question_option_id='".intval($value)."'";
  338. $result = Database::query($sql);
  339. $row = Database::fetch_array($result, 'ASSOC');
  340. $option_value = $row['value'];
  341. //$option_value = 0;
  342. $survey_question_answer = $value;
  343. // We save the answer after making sure that a possible previous attempt is deleted
  344. SurveyUtil::remove_answer(
  345. $survey_invitation['user'],
  346. $survey_invitation['survey_id'],
  347. $survey_question_id,
  348. $course_id
  349. );
  350. SurveyUtil::store_answer(
  351. $survey_invitation['user'],
  352. $survey_invitation['survey_id'],
  353. $survey_question_id,
  354. $value,
  355. $option_value,
  356. $survey_data
  357. );
  358. }
  359. }
  360. } else {
  361. // In case it's another type than 0 or 1
  362. api_not_allowed(true, get_lang('Survey type unknown'));
  363. }
  364. }
  365. $user_id = api_get_user_id();
  366. if ($user_id == 0) {
  367. $user_id = $survey_invitation['user'];
  368. }
  369. $user_data = api_get_user_info($user_id);
  370. if ($survey_data['form_fields'] != '' &&
  371. $survey_data['anonymous'] == 0 &&
  372. is_array($user_data)
  373. ) {
  374. $form_fields = explode('@', $survey_data['form_fields']);
  375. $list = [];
  376. foreach ($form_fields as $field) {
  377. $field_value = explode(':', $field);
  378. if (isset($field_value[1]) && $field_value[1] == 1) {
  379. if ($field_value[0] != '') {
  380. $val = api_substr($field_value[0], 8, api_strlen($field_value[0]));
  381. $list[$val] = 1;
  382. }
  383. }
  384. }
  385. $url = api_get_self().
  386. '?cidReq='.$courseInfo['code'].
  387. '&id_session='.$sessionId;
  388. $listQueryParams = preg_split('/&/', $_SERVER['QUERY_STRING']);
  389. foreach ($listQueryParams as $param) {
  390. $url .= '&'.Security::remove_XSS($param);
  391. }
  392. // We use the same form as in auth/profile.php
  393. $form = new FormValidator('profile', 'post', $url);
  394. if (api_is_western_name_order()) {
  395. if (isset($list['firstname']) && $list['firstname'] == 1) {
  396. //FIRST NAME
  397. $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
  398. if (api_get_setting('profile', 'name') !== 'true') {
  399. $form->freeze(['firstname']);
  400. }
  401. $form->applyFilter(['firstname'], 'stripslashes');
  402. $form->applyFilter(['firstname'], 'trim');
  403. $form->addRule('firstname', get_lang('Required field'), 'required');
  404. }
  405. if (isset($list['lastname']) && $list['lastname'] == 1) {
  406. // LAST NAME
  407. $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
  408. if (api_get_setting('profile', 'name') !== 'true') {
  409. $form->freeze(['lastname']);
  410. }
  411. $form->applyFilter(['lastname'], 'stripslashes');
  412. $form->applyFilter(['lastname'], 'trim');
  413. $form->addRule('lastname', get_lang('Required field'), 'required');
  414. }
  415. } else {
  416. if (isset($list['lastname']) && $list['lastname'] == 1) {
  417. // LAST NAME
  418. $form->addElement('text', 'lastname', get_lang('Last name'), ['size' => 40]);
  419. if (api_get_setting('profile', 'name') !== 'true') {
  420. $form->freeze(['lastname']);
  421. }
  422. $form->applyFilter(['lastname'], 'stripslashes');
  423. $form->applyFilter(['lastname'], 'trim');
  424. $form->addRule('lastname', get_lang('Required field'), 'required');
  425. }
  426. if (isset($list['firstname']) && $list['firstname'] == 1) {
  427. //FIRST NAME
  428. $form->addElement('text', 'firstname', get_lang('First name'), ['size' => 40]);
  429. if (api_get_setting('profile', 'name') !== 'true') {
  430. $form->freeze(['firstname']);
  431. }
  432. $form->applyFilter(['firstname'], 'stripslashes');
  433. $form->applyFilter(['firstname'], 'trim');
  434. $form->addRule('firstname', get_lang('Required field'), 'required');
  435. }
  436. }
  437. if (isset($list['official_code']) && $list['official_code'] == 1) {
  438. // OFFICIAL CODE
  439. $form->addElement('text', 'official_code', get_lang('Code'), ['size' => 40]);
  440. if (api_get_setting('profile', 'officialcode') !== 'true') {
  441. $form->freeze('official_code');
  442. }
  443. $form->applyFilter('official_code', 'stripslashes');
  444. $form->applyFilter('official_code', 'trim');
  445. if (api_get_setting('registration', 'officialcode') == 'true' &&
  446. api_get_setting('profile', 'officialcode') == 'true'
  447. ) {
  448. $form->addRule('official_code', get_lang('Required field'), 'required');
  449. }
  450. }
  451. if (isset($list['email']) && $list['email'] == 1) {
  452. // EMAIL
  453. $form->addElement('text', 'email', get_lang('e-mail'), ['size' => 40]);
  454. if (api_get_setting('profile', 'email') !== 'true') {
  455. $form->freeze('email');
  456. }
  457. $form->applyFilter('email', 'stripslashes');
  458. $form->applyFilter('email', 'trim');
  459. if (api_get_setting('registration', 'email') == 'true') {
  460. $form->addRule('email', get_lang('Required field'), 'required');
  461. }
  462. $form->addRule('email', get_lang('e-mailWrong'), 'email');
  463. }
  464. if (isset($list['phone']) && $list['phone'] == 1) {
  465. // PHONE
  466. $form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
  467. if (api_get_setting('profile', 'phone') !== 'true') {
  468. $form->freeze('phone');
  469. }
  470. $form->applyFilter('phone', 'stripslashes');
  471. $form->applyFilter('phone', 'trim');
  472. if (api_get_setting('profile', 'phone') == 'true') {
  473. $form->addRule('phone', get_lang('Required field'), 'required');
  474. }
  475. }
  476. if (isset($list['language']) && $list['language'] == 1) {
  477. // LANGUAGE
  478. $form->addSelectLanguage('language', get_lang('Language'));
  479. if (api_get_setting('profile', 'language') !== 'true') {
  480. $form->freeze('language');
  481. }
  482. if (api_get_setting('profile', 'language') == 'true') {
  483. $form->addRule('language', get_lang('Required field'), 'required');
  484. }
  485. }
  486. // EXTRA FIELDS
  487. $extraField = new ExtraField('user');
  488. $returnParams = $extraField->addElements($form, api_get_user_id());
  489. $jquery_ready_content = $returnParams['jquery_ready_content'];
  490. // the $jquery_ready_content variable collects all functions
  491. // that will be load in the $(document).ready javascript function
  492. $htmlHeadXtra[] = '<script>
  493. $(function() {
  494. '.$jquery_ready_content.'
  495. });
  496. </script>';
  497. $form->addButtonNext(get_lang('Next'));
  498. $form->setDefaults($user_data);
  499. }
  500. Display::display_header(get_lang('Surveys'));
  501. // Displaying the survey title and subtitle (appears on every page)
  502. echo '<div class="survey-block">';
  503. echo '<div class="page-header">';
  504. echo '<h2>';
  505. echo strip_tags($survey_data['survey_title']).'</h2></div>';
  506. if (!empty($survey_data['survey_subtitle'])) {
  507. echo '<div class="survey_subtitle"><p>'.strip_tags($survey_data['survey_subtitle']).'</p></div>';
  508. }
  509. // Displaying the survey introduction
  510. if (
  511. !isset($_GET['show']) ||
  512. (isset($_GET['show'])) && $_GET['show'] == '') {
  513. // The first thing we do is delete the session
  514. Session::erase('paged_questions');
  515. Session::erase('page_questions_sec');
  516. $paged_questions_sec = [];
  517. if (!empty($survey_data['survey_introduction'])) {
  518. echo '<div class="survey_content">'.$survey_data['survey_introduction'].'</div>';
  519. }
  520. $limit = 0;
  521. }
  522. if ($survey_data['form_fields'] &&
  523. $survey_data['anonymous'] == 0 &&
  524. is_array($user_data) &&
  525. !isset($_GET['show'])
  526. ) {
  527. if ($form->validate()) {
  528. $user_data = $form->exportValues();
  529. if (is_array($user_data)) {
  530. if (count($user_data) > 0) {
  531. $extras = [];
  532. // Build SQL query
  533. $sql = "UPDATE $table_user SET";
  534. $update = false;
  535. $allowedFields = [
  536. 'firstname',
  537. 'lastname',
  538. 'official_code',
  539. 'email',
  540. 'phone',
  541. 'language',
  542. ];
  543. foreach ($user_data as $key => $value) {
  544. if (in_array($key, $allowedFields)) {
  545. $sql .= " $key = '".Database :: escape_string($value)."',";
  546. $update = true;
  547. }
  548. }
  549. // Remove trailing , from the query we have so far
  550. $sql = rtrim($sql, ',');
  551. $sql .= " WHERE id = $user_id";
  552. if ($update) {
  553. Database::query($sql);
  554. }
  555. $extraFieldValue = new ExtraFieldValue('user');
  556. $extraFieldValue->saveFieldValues($user_data);
  557. echo '<div id="survey_content" class="survey_content">'.
  558. get_lang('Information updated').' '.get_lang('Please fill survey').'</div>';
  559. }
  560. }
  561. $_GET['show'] = 0;
  562. $show = 0;
  563. // We unset the sessions
  564. Session::erase('paged_questions');
  565. Session::erase('page_questions_sec');
  566. $paged_questions_sec = [];
  567. } else {
  568. echo '<div id="survey_content" class="survey_content">'.get_lang('Update information').'</div>';
  569. // We unset the sessions
  570. Session::erase('paged_questions');
  571. Session::erase('page_questions_sec');
  572. $paged_questions_sec = [];
  573. $form->display();
  574. }
  575. }
  576. // Displaying the survey thanks message
  577. if (isset($_POST['finish_survey'])) {
  578. echo Display::return_message(get_lang('You have finished this survey.'), 'confirm');
  579. echo $survey_data['survey_thanks'];
  580. SurveyManager::update_survey_answered(
  581. $survey_data,
  582. $survey_invitation['user'],
  583. $survey_invitation['survey_code']
  584. );
  585. SurveyUtil::flagSurveyAsAnswered(
  586. $survey_invitation['survey_code'],
  587. $survey_invitation['c_id']
  588. );
  589. if ($courseInfo && !api_is_anonymous()) {
  590. echo Display::toolbarButton(
  591. get_lang('Return to Course Homepage'),
  592. api_get_course_url($courseInfo['code']),
  593. 'home'
  594. );
  595. }
  596. Session::erase('paged_questions');
  597. Session::erase('page_questions_sec');
  598. Display::display_footer();
  599. exit();
  600. }
  601. // Sets the random questions
  602. $shuffle = '';
  603. if ($survey_data['shuffle'] == 1) {
  604. $shuffle = ' BY RAND() ';
  605. }
  606. if ((isset($_GET['show']) && $_GET['show'] != '') ||
  607. isset($_POST['personality'])
  608. ) {
  609. // Getting all the questions for this page and add them to a
  610. // multidimensional array where the first index is the page.
  611. // As long as there is no pagebreak fount we keep adding questions to the page
  612. $questions_displayed = [];
  613. $counter = 0;
  614. //$paged_questions = Session::read('paged_questions');
  615. $paged_questions = [];
  616. // If non-conditional survey
  617. if ($survey_data['survey_type'] == '0') {
  618. if (empty($paged_questions)) {
  619. $sql = "SELECT * FROM $table_survey_question
  620. WHERE
  621. survey_question NOT LIKE '%{{%' AND
  622. c_id = $course_id AND
  623. survey_id = '".intval($survey_invitation['survey_id'])."'
  624. ORDER BY sort ASC";
  625. $result = Database::query($sql);
  626. while ($row = Database::fetch_array($result, 'ASSOC')) {
  627. if ($survey_data['one_question_per_page'] == 1) {
  628. if ($row['type'] != 'pagebreak') {
  629. $paged_questions[$counter][] = $row['question_id'];
  630. $counter++;
  631. continue;
  632. }
  633. } else {
  634. if ($row['type'] == 'pagebreak') {
  635. $counter++;
  636. } else {
  637. $paged_questions[$counter][] = $row['question_id'];
  638. }
  639. }
  640. }
  641. Session::write('paged_questions', $paged_questions);
  642. }
  643. // Redefinition of variables and session ids to fix issue of survey not
  644. // showing questions - see support.chamilo.org #5529
  645. $course_id = $survey_invitation['c_id'];
  646. Session::write('_cid', $course_id);
  647. Session::write('_real_cid', $course_id);
  648. if (array_key_exists($_GET['show'], $paged_questions)) {
  649. if (isset($_GET['user_id'])) {
  650. // Get the user into survey answer table (user or anonymus)
  651. $my_user_id = $survey_data['anonymous'] == 1 ? $surveyUserFromSession : api_get_user_id();
  652. $sql = "SELECT
  653. survey_question.survey_group_sec1,
  654. survey_question.survey_group_sec2,
  655. survey_question.survey_group_pri,
  656. survey_question.question_id,
  657. survey_question.survey_id,
  658. survey_question.survey_question,
  659. survey_question.display,
  660. survey_question.sort,
  661. survey_question.type,
  662. survey_question.max_value,
  663. survey_question_option.question_option_id,
  664. survey_question_option.option_text,
  665. survey_question_option.sort as option_sort
  666. FROM $table_survey_question survey_question
  667. LEFT JOIN $table_survey_question_option survey_question_option
  668. ON survey_question.question_id = survey_question_option.question_id AND
  669. survey_question_option.c_id = $course_id
  670. WHERE
  671. survey_question.survey_id = '".Database::escape_string($survey_invitation['survey_id'])."' AND
  672. survey_question.question_id NOT IN (
  673. SELECT sa.question_id
  674. FROM ".$table_survey_answer." sa
  675. WHERE
  676. sa.user='".$my_user_id."') AND
  677. survey_question.c_id = $course_id
  678. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  679. } else {
  680. $sql = "SELECT
  681. survey_question.survey_group_sec1,
  682. survey_question.survey_group_sec2,
  683. survey_question.survey_group_pri,
  684. survey_question.question_id,
  685. survey_question.survey_id,
  686. survey_question.survey_question,
  687. survey_question.display,
  688. survey_question.sort,
  689. survey_question.type,
  690. survey_question.max_value,
  691. survey_question_option.question_option_id,
  692. survey_question_option.option_text,
  693. survey_question_option.sort as option_sort
  694. ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
  695. FROM $table_survey_question survey_question
  696. LEFT JOIN $table_survey_question_option survey_question_option
  697. ON survey_question.question_id = survey_question_option.question_id AND
  698. survey_question_option.c_id = $course_id
  699. WHERE
  700. survey_question NOT LIKE '%{{%' AND
  701. survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
  702. survey_question.question_id IN (".implode(',', $paged_questions[$_GET['show']]).") AND
  703. survey_question.c_id = $course_id
  704. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  705. }
  706. $result = Database::query($sql);
  707. $question_counter_max = Database::num_rows($result);
  708. $counter = 0;
  709. $limit = 0;
  710. $questions = [];
  711. while ($row = Database :: fetch_array($result, 'ASSOC')) {
  712. // If the type is not a pagebreak we store it in the $questions array
  713. if ($row['type'] != 'pagebreak') {
  714. $questions[$row['sort']]['question_id'] = $row['question_id'];
  715. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  716. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  717. $questions[$row['sort']]['display'] = $row['display'];
  718. $questions[$row['sort']]['type'] = $row['type'];
  719. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  720. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  721. $questions[$row['sort']]['sort'] = $row['sort'];
  722. $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
  723. }
  724. $counter++;
  725. }
  726. }
  727. } elseif ($survey_data['survey_type'] === '1') {
  728. $my_survey_id = (int) $survey_invitation['survey_id'];
  729. $current_user = Database::escape_string($survey_invitation['user']);
  730. if (isset($_POST['personality'])) {
  731. // Compute the results to get the 3 groups nearest to the user's personality
  732. if ($shuffle == '') {
  733. $order = 'BY sort ASC ';
  734. } else {
  735. $order = $shuffle;
  736. }
  737. $answer_list = [];
  738. // Get current user results
  739. $results = [];
  740. $sql = "SELECT
  741. survey_group_pri,
  742. user,
  743. SUM(value) as value
  744. FROM $table_survey_answer as survey_answer
  745. INNER JOIN $table_survey_question as survey_question
  746. ON (survey_question.question_id = survey_answer.question_id)
  747. WHERE
  748. survey_answer.survey_id='".$my_survey_id."' AND
  749. survey_answer.user='".$current_user."' AND
  750. survey_answer.c_id = $course_id AND
  751. survey_question.c_id = $course_id AND
  752. GROUP BY survey_group_pri
  753. ORDER BY survey_group_pri
  754. ";
  755. $result = Database::query($sql);
  756. while ($row = Database :: fetch_array($result)) {
  757. $answer_list['value'] = $row['value'];
  758. $answer_list['group'] = $row['survey_group_pri'];
  759. $results[] = $answer_list;
  760. }
  761. // Get the total score for each group of questions
  762. $totals = [];
  763. $sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
  764. (
  765. SELECT
  766. MAX(value) as value,
  767. survey_group_pri,
  768. survey_question.question_id
  769. FROM $table_survey_question as survey_question
  770. INNER JOIN $table_survey_question_option as survey_question_option
  771. ON (survey_question.question_id = survey_question_option.question_id)
  772. WHERE
  773. survey_question.survey_id='".$my_survey_id."' AND
  774. survey_question.c_id = $course_id AND
  775. survey_question_option.c_id = $course_id AND
  776. survey_group_sec1='0' AND
  777. survey_group_sec2='0'
  778. GROUP BY survey_group_pri, survey_question.question_id
  779. ) as temp
  780. GROUP BY temp.survey_group_pri
  781. ORDER BY temp.survey_group_pri";
  782. $result = Database::query($sql);
  783. while ($row = Database::fetch_array($result)) {
  784. $list['value'] = $row['value'];
  785. $list['group'] = $row['survey_group_pri'];
  786. $totals[] = $list;
  787. }
  788. $final_results = [];
  789. // Get a percentage score for each group
  790. for ($i = 0; $i < count($totals); $i++) {
  791. for ($j = 0; $j < count($results); $j++) {
  792. if ($totals[$i]['group'] == $results[$j]['group']) {
  793. $group = $totals[$i]['group'];
  794. $porcen = ($results[$j]['value'] / $totals[$i]['value']);
  795. $final_results[$group] = $porcen;
  796. }
  797. }
  798. }
  799. // Sort the results by score (getting a list of group IDs by score into $groups)
  800. arsort($final_results);
  801. $groups = array_keys($final_results);
  802. $result = [];
  803. $count_result = 0;
  804. foreach ($final_results as $key => &$sub_result) {
  805. $result[] = ['group' => $key, 'value' => $sub_result];
  806. $count_result++;
  807. }
  808. // i.e 70% - 70% -70% 70% $equal_count =3
  809. $i = 0;
  810. $group_cant = 0;
  811. $equal_count = 0;
  812. // This is the case if the user does not select any question
  813. if ($count_result > 0) {
  814. // Count the number of scores equal to the first
  815. while (1) {
  816. if ($result[$i]['value'] == $result[$i + 1]['value']) {
  817. $equal_count++;
  818. } else {
  819. break;
  820. }
  821. $i++;
  822. }
  823. } else {
  824. // We force the exit of the survey undeterminated
  825. $equal_count = 10;
  826. }
  827. // If we have only 3 or less equal scores (i.e. 0,1 or 2 equalities), then we can use the three first groups
  828. if ($equal_count < 4) {
  829. // If there is one or less score equalities
  830. if ($equal_count === 0 || $equal_count === 1) {
  831. // i.e 70% - 70% -60% - 60% $equal_count = 1 we only get the first 2 options
  832. if (($result[0]['value'] == $result[1]['value']) &&
  833. ($result[2]['value'] == $result[3]['value'])
  834. ) {
  835. $group_cant = 1;
  836. } elseif (($result[0]['value'] != $result[1]['value']) &&
  837. ($result[1]['value'] == $result[2]['value']) && ($result[2]['value'] == $result[3]['value'])
  838. ) {
  839. // i.e 70% - 70% -0% - 0% - $equal_count = 0 we only get the first 2 options
  840. /* elseif (($result[0]['value'] == $result[1]['value']) && ($result[1]['value'] != $result[2]['value'])) {
  841. $group_cant = 0;
  842. } */
  843. /*
  844. // i.e 70% - 70% -60% - 60% $equal_count = 0 we only get the first 2 options
  845. elseif (($result[0]['value'] == $result[1]['value']) && ($result[2]['value'] == $result[3]['value'])) {
  846. $group_cant = 0;
  847. } */
  848. // i.e. 80% - 70% - 70% - 70%
  849. $group_cant = 0;
  850. } else {
  851. // i.e. 80% - 70% - 70% - 50
  852. // i.e. 80% - 80% - 70% - 50
  853. // By default we choose the highest 3
  854. $group_cant = 2;
  855. }
  856. } else {
  857. // If there are two score equalities
  858. $group_cant = $equal_count;
  859. }
  860. //@todo Translate these comments.
  861. // conditional_status
  862. // 0 no determinado
  863. // 1 determinado
  864. // 2 un solo valor
  865. // 3 valores iguales
  866. if ($group_cant > 0) {
  867. //echo '$equal_count'.$group_cant;
  868. // We only get highest 3
  869. $secondary = '';
  870. $combi = '';
  871. for ($i = 0; $i <= $group_cant; $i++) {
  872. $group1 = $groups[$i];
  873. $group2 = $groups[$i + 1];
  874. // Here we made all the posibilities with the 3 groups
  875. if ($group_cant == 2 && $i == $group_cant) {
  876. $group2 = $groups[0];
  877. $secondary .= " OR ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  878. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  879. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  880. } else {
  881. if ($i != 0) {
  882. $secondary .= " OR ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  883. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  884. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  885. } else {
  886. $secondary .= " ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  887. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  888. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  889. }
  890. }
  891. }
  892. // Create the new select with the questions from the secondary phase
  893. if (empty($_SESSION['page_questions_sec']) &&
  894. !is_array($_SESSION['page_questions_sec']) &&
  895. count($_SESSION['page_questions_sec'] == 0)
  896. ) {
  897. $sql = "SELECT * FROM $table_survey_question
  898. WHERE
  899. c_id = $course_id AND
  900. survey_id = '".$my_survey_id."' AND
  901. ($secondary )
  902. ORDER BY sort ASC";
  903. $result = Database::query($sql);
  904. $counter = 0;
  905. while ($row = Database::fetch_array($result, 'ASSOC')) {
  906. if ($survey_data['one_question_per_page'] == 1) {
  907. $paged_questions_sec[$counter][] = $row['question_id'];
  908. $counter++;
  909. } elseif ($row['type'] == 'pagebreak') {
  910. $counter++;
  911. } else {
  912. // ids from question of the current survey
  913. $paged_questions_sec[$counter][] = $row['question_id'];
  914. }
  915. }
  916. Session::write('page_questions_sec', $paged_questions_sec);
  917. } else {
  918. $paged_questions_sec = Session::read('page_questions_sec');
  919. }
  920. $paged_questions = Session::read('paged_questions'); // For the sake of pages counting
  921. if ($shuffle == '') {
  922. $shuffle = ' BY survey_question.sort, survey_question_option.sort ASC ';
  923. }
  924. $val = (int) $_POST['personality'];
  925. if (is_array($paged_questions_sec)) {
  926. $sql = "SELECT
  927. survey_question.survey_group_sec1,
  928. survey_question.survey_group_sec2,
  929. survey_question.survey_group_pri,
  930. survey_question.question_id,
  931. survey_question.survey_id,
  932. survey_question.survey_question,
  933. survey_question.display,
  934. survey_question.sort,
  935. survey_question.type,
  936. survey_question.max_value,
  937. survey_question_option.question_option_id,
  938. survey_question_option.option_text,
  939. survey_question_option.sort as option_sort
  940. FROM $table_survey_question survey_question
  941. LEFT JOIN $table_survey_question_option survey_question_option
  942. ON survey_question.question_id = survey_question_option.question_id AND
  943. survey_question_option.c_id = $course_id
  944. WHERE
  945. survey_question NOT LIKE '%{{%' AND
  946. survey_question.survey_id = '".$my_survey_id."' AND
  947. survey_question.c_id = $course_id AND
  948. survey_question.question_id IN (".implode(',', $paged_questions_sec[$val]).")
  949. ORDER $shuffle ";
  950. $result = Database::query($sql);
  951. $question_counter_max = Database::num_rows($result);
  952. $counter = 0;
  953. $limit = 0;
  954. $questions = [];
  955. while ($row = Database::fetch_array($result, 'ASSOC')) {
  956. // If the type is not a pagebreak we store it in the $questions array
  957. if ($row['type'] != 'pagebreak') {
  958. $questions[$row['sort']]['question_id'] = $row['question_id'];
  959. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  960. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  961. $questions[$row['sort']]['display'] = $row['display'];
  962. $questions[$row['sort']]['type'] = $row['type'];
  963. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  964. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  965. // Personality params
  966. $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
  967. $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
  968. $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
  969. $questions[$row['sort']]['sort'] = $row['sort'];
  970. } else {
  971. // If the type is a pagebreak we are finished loading the questions for this page
  972. break;
  973. }
  974. $counter++;
  975. }
  976. } else {
  977. echo get_lang('Survey undefined');
  978. }
  979. } else {
  980. echo get_lang('Survey undefined');
  981. }
  982. } else {
  983. echo get_lang('Survey undefined');
  984. }
  985. } else {
  986. // We need this variable only in the 2nd set of questions when personality is set.
  987. Session::erase('page_questions_sec');
  988. $paged_questions_sec = [];
  989. // Only the questions from the basic group
  990. // the 50 questions A B C D E F G
  991. $order_sql = $shuffle;
  992. if ($shuffle == '') {
  993. $order_sql = ' BY question_id ';
  994. }
  995. if (empty($_SESSION['paged_questions'])) {
  996. $sql = "SELECT * FROM $table_survey_question
  997. WHERE
  998. c_id = $course_id AND
  999. survey_id = '".intval($survey_invitation['survey_id'])."' AND
  1000. survey_group_sec1='0' AND
  1001. survey_group_sec2='0'
  1002. ORDER ".$order_sql." ";
  1003. $result = Database::query($sql);
  1004. $counter = 0;
  1005. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1006. if ($survey_data['one_question_per_page'] == 1) {
  1007. $paged_questions[$counter][] = $row['question_id'];
  1008. $counter++;
  1009. } else {
  1010. if ($row['type'] == 'pagebreak') {
  1011. $counter++;
  1012. } else {
  1013. // ids from question of the current survey
  1014. $paged_questions[$counter][] = $row['question_id'];
  1015. }
  1016. }
  1017. }
  1018. Session::write('paged_questions', $paged_questions);
  1019. } else {
  1020. $paged_questions = Session::read('paged_questions');
  1021. }
  1022. $order_sql = $shuffle;
  1023. if ($shuffle == '') {
  1024. $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
  1025. }
  1026. $val = $_GET['show'];
  1027. $result = null;
  1028. if ($val != '') {
  1029. $imploded = Database::escape_string(implode(',', $paged_questions[$val]));
  1030. if ($imploded != '') {
  1031. // The answers are always in the same order NO shuffle
  1032. $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
  1033. $sql = "SELECT
  1034. survey_question.survey_group_sec1,
  1035. survey_question.survey_group_sec2,
  1036. survey_question.survey_group_pri,
  1037. survey_question.question_id,
  1038. survey_question.survey_id,
  1039. survey_question.survey_question,
  1040. survey_question.display,
  1041. survey_question.sort,
  1042. survey_question.type,
  1043. survey_question.max_value,
  1044. survey_question_option.question_option_id,
  1045. survey_question_option.option_text,
  1046. survey_question_option.sort as option_sort
  1047. ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
  1048. FROM $table_survey_question survey_question
  1049. LEFT JOIN $table_survey_question_option survey_question_option
  1050. ON survey_question.question_id = survey_question_option.question_id AND
  1051. survey_question_option.c_id = $course_id
  1052. WHERE
  1053. survey_question NOT LIKE '%{{%' AND
  1054. survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
  1055. survey_question.c_id = $course_id AND
  1056. survey_question.question_id IN (".$imploded.")
  1057. ORDER $order_sql ";
  1058. $result = Database::query($sql);
  1059. $question_counter_max = Database :: num_rows($result);
  1060. }
  1061. }
  1062. if (!is_null($result)) {
  1063. $counter = 0;
  1064. $limit = 0;
  1065. $questions = [];
  1066. while ($row = Database :: fetch_array($result, 'ASSOC')) {
  1067. // If the type is not a pagebreak we store it in the $questions array
  1068. if ($row['type'] != 'pagebreak') {
  1069. $questions[$row['sort']]['question_id'] = $row['question_id'];
  1070. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  1071. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  1072. $questions[$row['sort']]['display'] = $row['display'];
  1073. $questions[$row['sort']]['type'] = $row['type'];
  1074. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  1075. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  1076. $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
  1077. // Personality params
  1078. $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
  1079. $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
  1080. $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
  1081. $questions[$row['sort']]['sort'] = $row['sort'];
  1082. } else {
  1083. // If the type is a page break we are finished loading the questions for this page
  1084. //break;
  1085. }
  1086. $counter++;
  1087. }
  1088. }
  1089. }
  1090. } else { // In case it's another type than 0 or 1
  1091. echo get_lang('Survey type unknown');
  1092. }
  1093. }
  1094. $numberOfPages = SurveyManager::getCountPages($survey_data);
  1095. // Displaying the form with the questions
  1096. $show = 0;
  1097. if (isset($_GET['show']) && $_GET['show'] != '') {
  1098. $show = (int) $_GET['show'] + 1;
  1099. }
  1100. $displayFinishButton = true;
  1101. if (isset($_GET['show']) && $_GET['show'] != '') {
  1102. $pagesIndexes = array_keys($paged_questions);
  1103. $pagesIndexes[] = count($pagesIndexes);
  1104. if (end($pagesIndexes) <= $show - 1 && empty($_POST)) {
  1105. $displayFinishButton = false;
  1106. }
  1107. }
  1108. // Displaying the form with the questions
  1109. $personality = 0;
  1110. if (isset($_POST['personality'])) {
  1111. $personality = (int) $_POST['personality'] + 1;
  1112. }
  1113. // Displaying the form with the questions
  1114. $g_c = isset($_GET['course']) ? Security::remove_XSS($_GET['course']) : '';
  1115. $g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationcode']) : '';
  1116. $g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
  1117. $p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
  1118. $add_parameters = isset($_GET['user_id']) ? '&user_id='.intval($_GET['user_id']) : '';
  1119. $url = api_get_self().'?cidReq='.$courseInfo['code'].
  1120. '&id_session='.$sessionId.
  1121. $add_parameters.
  1122. '&course='.$g_c.
  1123. '&invitationcode='.$g_ic.
  1124. '&show='.$show;
  1125. $form = new FormValidator(
  1126. 'question',
  1127. 'post',
  1128. $url,
  1129. null,
  1130. null,
  1131. FormValidator::LAYOUT_INLINE
  1132. );
  1133. $form->addHidden('language', $p_l);
  1134. if (isset($questions) && is_array($questions)) {
  1135. $originalShow = isset($_GET['show']) ? (int) $_GET['show'] : 0;
  1136. $questionCounter = 1;
  1137. if (!empty($originalShow)) {
  1138. $before = 0;
  1139. foreach ($paged_questions as $keyQuestion => $list) {
  1140. if ($originalShow > $keyQuestion) {
  1141. $before += count($list);
  1142. }
  1143. }
  1144. $questionCounter = $before + 1;
  1145. }
  1146. foreach ($questions as $key => &$question) {
  1147. $ch_type = 'ch_'.$question['type'];
  1148. $questionNumber = $questionCounter;
  1149. $display = survey_question::createQuestion($question['type']);
  1150. // @todo move this in a function.
  1151. $form->addHtml('<div class="survey_question '.$ch_type.'">');
  1152. $form->addHtml('<div style="float:left; font-weight: bold; margin-right: 5px;"> '.$questionNumber.'. </div>');
  1153. $form->addHtml('<div>'.Security::remove_XSS($question['survey_question']).'</div> ');
  1154. $userAnswerData = SurveyUtil::get_answers_of_question_by_user($question['survey_id'], $question['question_id']);
  1155. $finalAnswer = null;
  1156. if (!empty($userAnswerData[$user_id])) {
  1157. $userAnswer = $userAnswerData[$user_id];
  1158. switch ($question['type']) {
  1159. case 'score':
  1160. $finalAnswer = [];
  1161. foreach ($userAnswer as $userChoice) {
  1162. list($choiceId, $choiceValue) = explode('*', $userChoice);
  1163. $finalAnswer[$choiceId] = $choiceValue;
  1164. }
  1165. break;
  1166. case 'percentage':
  1167. list($choiceId, $choiceValue) = explode('*', current($userAnswer));
  1168. $finalAnswer = $choiceId;
  1169. break;
  1170. default:
  1171. $finalAnswer = $userAnswer;
  1172. break;
  1173. }
  1174. }
  1175. $display->render($form, $question, $finalAnswer);
  1176. $form->addHtml('</div>');
  1177. $questionCounter++;
  1178. }
  1179. }
  1180. $form->addHtml('<div class="start-survey">');
  1181. if ($survey_data['survey_type'] == '0') {
  1182. if ($survey_data['show_form_profile'] == 0) {
  1183. // The normal survey as always
  1184. if ($show < $numberOfPages) {
  1185. if ($show == 0) {
  1186. $form->addButton(
  1187. 'next_survey_page',
  1188. get_lang('Start the Survey'),
  1189. 'arrow-right',
  1190. 'success'
  1191. );
  1192. } else {
  1193. $form->addButton(
  1194. 'next_survey_page',
  1195. get_lang('Next'),
  1196. 'arrow-right',
  1197. 'success'
  1198. );
  1199. }
  1200. }
  1201. if ($show >= $numberOfPages && $displayFinishButton) {
  1202. $form->addButton(
  1203. 'finish_survey',
  1204. get_lang('Finish survey'),
  1205. 'arrow-right',
  1206. 'success'
  1207. );
  1208. }
  1209. } else {
  1210. // The normal survey as always but with the form profile
  1211. if (isset($_GET['show'])) {
  1212. $numberOfPages = count($paged_questions);
  1213. if ($show < $numberOfPages) {
  1214. if ($show == 0) {
  1215. $form->addButton(
  1216. 'next_survey_page',
  1217. get_lang('Start the Survey'),
  1218. 'arrow-right',
  1219. 'success'
  1220. );
  1221. } else {
  1222. $form->addButton(
  1223. 'next_survey_page',
  1224. get_lang('Next'),
  1225. 'arrow-right',
  1226. 'success'
  1227. );
  1228. }
  1229. }
  1230. if ($show >= $numberOfPages && $displayFinishButton) {
  1231. $form->addButton(
  1232. 'finish_survey',
  1233. get_lang('Finish survey'),
  1234. 'arrow-right',
  1235. 'success'
  1236. );
  1237. }
  1238. }
  1239. }
  1240. } elseif ($survey_data['survey_type'] == '1') {
  1241. // Conditional/personality-test type survey
  1242. if (isset($_GET['show']) || isset($_POST['personality'])) {
  1243. $numberOfPages = count($paged_questions);
  1244. if (!empty($paged_questions_sec) && count($paged_questions_sec) > 0) {
  1245. // In case we're in the second phase, also sum the second group questions
  1246. $numberOfPages += count($paged_questions_sec);
  1247. } else {
  1248. // We need this variable only if personality == 1
  1249. Session::erase('page_questions_sec');
  1250. $paged_questions_sec = [];
  1251. }
  1252. if ($personality == 0) {
  1253. if (($show <= $numberOfPages) || !$_GET['show']) {
  1254. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1255. if ($survey_data['one_question_per_page'] == 0) {
  1256. if ($personality >= 0) {
  1257. $form->addHidden('personality', $personality);
  1258. }
  1259. } else {
  1260. if ($personality > 0) {
  1261. $form->addHidden('personality', $personality);
  1262. }
  1263. }
  1264. if ($numberOfPages == $show) {
  1265. $form->addHidden('personality', $personality);
  1266. }
  1267. }
  1268. }
  1269. if ($show > $numberOfPages && $_GET['show'] && $personality == 0) {
  1270. $form->addHidden('personality', $personality);
  1271. } elseif ($personality > 0) {
  1272. if ($survey_data['one_question_per_page'] == 1) {
  1273. if ($show >= $numberOfPages) {
  1274. $form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right', 'success');
  1275. } else {
  1276. $form->addHidden('personality', $personality);
  1277. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1278. }
  1279. } else {
  1280. // if the personality test hidden input was set.
  1281. $form->addButton('finish_survey', get_lang('Finish survey'), 'arrow-right');
  1282. }
  1283. }
  1284. } elseif ($survey_data['form_fields'] == '') {
  1285. // This is the case when the show_profile_form is true but there are not form_fields
  1286. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1287. } elseif (!is_array($user_data)) {
  1288. // If the user is not registered in the platform we do not show the form to update his information
  1289. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1290. }
  1291. }
  1292. $form->addHtml('</div>');
  1293. $form->display();
  1294. Display::display_footer();