fillsurvey.php 62 KB

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