fillsurvey.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  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. $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('WrongInvitationCode'));
  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('YouAlreadyFilledThisSurvey')));
  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('ToolSurvey'));
  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('Ok').'</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('ErrorSurveyTypeUnknown'));
  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('FirstName'), ['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('ThisFieldIsRequired'), 'required');
  404. }
  405. if (isset($list['lastname']) && $list['lastname'] == 1) {
  406. // LAST NAME
  407. $form->addElement('text', 'lastname', get_lang('LastName'), ['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('ThisFieldIsRequired'), 'required');
  414. }
  415. } else {
  416. if (isset($list['lastname']) && $list['lastname'] == 1) {
  417. // LAST NAME
  418. $form->addElement('text', 'lastname', get_lang('LastName'), ['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('ThisFieldIsRequired'), 'required');
  425. }
  426. if (isset($list['firstname']) && $list['firstname'] == 1) {
  427. //FIRST NAME
  428. $form->addElement('text', 'firstname', get_lang('FirstName'), ['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('ThisFieldIsRequired'), 'required');
  435. }
  436. }
  437. if (isset($list['official_code']) && $list['official_code'] == 1) {
  438. // OFFICIAL CODE
  439. if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
  440. $form->addElement('text', 'official_code', get_lang('OfficialCode'), ['size' => 40]);
  441. if (api_get_setting('profile', 'officialcode') !== 'true') {
  442. $form->freeze('official_code');
  443. }
  444. $form->applyFilter('official_code', 'stripslashes');
  445. $form->applyFilter('official_code', 'trim');
  446. if (api_get_setting('registration', 'officialcode') == 'true' &&
  447. api_get_setting('profile', 'officialcode') == 'true'
  448. ) {
  449. $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
  450. }
  451. }
  452. }
  453. if (isset($list['email']) && $list['email'] == 1) {
  454. // EMAIL
  455. $form->addElement('text', 'email', get_lang('Email'), ['size' => 40]);
  456. if (api_get_setting('profile', 'email') !== 'true') {
  457. $form->freeze('email');
  458. }
  459. $form->applyFilter('email', 'stripslashes');
  460. $form->applyFilter('email', 'trim');
  461. if (api_get_setting('registration', 'email') == 'true') {
  462. $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
  463. }
  464. $form->addRule('email', get_lang('EmailWrong'), 'email');
  465. }
  466. if (isset($list['phone']) && $list['phone'] == 1) {
  467. // PHONE
  468. $form->addElement('text', 'phone', get_lang('Phone'), ['size' => 20]);
  469. if (api_get_setting('profile', 'phone') !== 'true') {
  470. $form->freeze('phone');
  471. }
  472. $form->applyFilter('phone', 'stripslashes');
  473. $form->applyFilter('phone', 'trim');
  474. if (api_get_setting('profile', 'phone') == 'true') {
  475. $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
  476. }
  477. }
  478. if (isset($list['language']) && $list['language'] == 1) {
  479. // LANGUAGE
  480. $form->addSelectLanguage('language', get_lang('Language'));
  481. if (api_get_setting('profile', 'language') !== 'true') {
  482. $form->freeze('language');
  483. }
  484. if (api_get_setting('profile', 'language') == 'true') {
  485. $form->addRule('language', get_lang('ThisFieldIsRequired'), 'required');
  486. }
  487. }
  488. // EXTRA FIELDS
  489. $extraField = new ExtraField('user');
  490. $returnParams = $extraField->addElements($form, api_get_user_id());
  491. $jquery_ready_content = $returnParams['jquery_ready_content'];
  492. // the $jquery_ready_content variable collects all functions
  493. // that will be load in the $(document).ready javascript function
  494. $htmlHeadXtra[] = '<script>
  495. $(function() {
  496. '.$jquery_ready_content.'
  497. });
  498. </script>';
  499. $form->addButtonNext(get_lang('Next'));
  500. $form->setDefaults($user_data);
  501. }
  502. Display::display_header(get_lang('ToolSurvey'));
  503. // Displaying the survey title and subtitle (appears on every page)
  504. echo '<div class="survey-block">';
  505. echo '<div class="page-header">';
  506. echo '<h2>';
  507. echo strip_tags($survey_data['survey_title']).'</h2></div>';
  508. if (!empty($survey_data['survey_subtitle'])) {
  509. echo '<div class="survey_subtitle"><p>'.strip_tags($survey_data['survey_subtitle']).'</p></div>';
  510. }
  511. // Displaying the survey introduction
  512. if (
  513. !isset($_GET['show']) ||
  514. (isset($_GET['show'])) && $_GET['show'] == '') {
  515. // The first thing we do is delete the session
  516. Session::erase('paged_questions');
  517. Session::erase('page_questions_sec');
  518. $paged_questions_sec = [];
  519. if (!empty($survey_data['survey_introduction'])) {
  520. echo '<div class="survey_content">'.$survey_data['survey_introduction'].'</div>';
  521. }
  522. $limit = 0;
  523. }
  524. if ($survey_data['form_fields'] &&
  525. $survey_data['anonymous'] == 0 &&
  526. is_array($user_data) &&
  527. !isset($_GET['show'])
  528. ) {
  529. if ($form->validate()) {
  530. $user_data = $form->exportValues();
  531. if (is_array($user_data)) {
  532. if (count($user_data) > 0) {
  533. $extras = [];
  534. // Build SQL query
  535. $sql = "UPDATE $table_user SET";
  536. $update = false;
  537. $allowedFields = [
  538. 'firstname',
  539. 'lastname',
  540. 'official_code',
  541. 'email',
  542. 'phone',
  543. 'language',
  544. ];
  545. foreach ($user_data as $key => $value) {
  546. if (in_array($key, $allowedFields)) {
  547. $sql .= " $key = '".Database :: escape_string($value)."',";
  548. $update = true;
  549. }
  550. }
  551. // Remove trailing , from the query we have so far
  552. $sql = rtrim($sql, ',');
  553. $sql .= " WHERE id = $user_id";
  554. if ($update) {
  555. Database::query($sql);
  556. }
  557. $extraFieldValue = new ExtraFieldValue('user');
  558. $extraFieldValue->saveFieldValues($user_data);
  559. echo '<div id="survey_content" class="survey_content">'.
  560. get_lang('InformationUpdated').' '.get_lang('PleaseFillSurvey').'</div>';
  561. }
  562. }
  563. $_GET['show'] = 0;
  564. $show = 0;
  565. // We unset the sessions
  566. Session::erase('paged_questions');
  567. Session::erase('page_questions_sec');
  568. $paged_questions_sec = [];
  569. } else {
  570. echo '<div id="survey_content" class="survey_content">'.get_lang('UpdateInformation').'</div>';
  571. // We unset the sessions
  572. Session::erase('paged_questions');
  573. Session::erase('page_questions_sec');
  574. $paged_questions_sec = [];
  575. $form->display();
  576. }
  577. }
  578. // Displaying the survey thanks message
  579. if (isset($_POST['finish_survey'])) {
  580. echo Display::return_message(get_lang('SurveyFinished'), 'confirm');
  581. echo $survey_data['survey_thanks'];
  582. SurveyManager::update_survey_answered(
  583. $survey_data,
  584. $survey_invitation['user'],
  585. $survey_invitation['survey_code']
  586. );
  587. SurveyUtil::flagSurveyAsAnswered(
  588. $survey_invitation['survey_code'],
  589. $survey_invitation['c_id']
  590. );
  591. if ($courseInfo && !api_is_anonymous()) {
  592. echo Display::toolbarButton(
  593. get_lang('ReturnToCourseHomepage'),
  594. api_get_course_url($courseInfo['code']),
  595. 'home'
  596. );
  597. }
  598. Session::erase('paged_questions');
  599. Session::erase('page_questions_sec');
  600. Display::display_footer();
  601. exit();
  602. }
  603. // Sets the random questions
  604. $shuffle = '';
  605. if ($survey_data['shuffle'] == 1) {
  606. $shuffle = ' BY RAND() ';
  607. }
  608. if ((isset($_GET['show']) && $_GET['show'] != '') ||
  609. isset($_POST['personality'])
  610. ) {
  611. // Getting all the questions for this page and add them to a
  612. // multidimensional array where the first index is the page.
  613. // As long as there is no pagebreak fount we keep adding questions to the page
  614. $questions_displayed = [];
  615. $counter = 0;
  616. //$paged_questions = Session::read('paged_questions');
  617. $paged_questions = [];
  618. // If non-conditional survey
  619. if ($survey_data['survey_type'] == '0') {
  620. if (empty($paged_questions)) {
  621. $sql = "SELECT * FROM $table_survey_question
  622. WHERE
  623. survey_question NOT LIKE '%{{%' AND
  624. c_id = $course_id AND
  625. survey_id = '".intval($survey_invitation['survey_id'])."'
  626. ORDER BY sort ASC";
  627. $result = Database::query($sql);
  628. while ($row = Database::fetch_array($result, 'ASSOC')) {
  629. if ($survey_data['one_question_per_page'] == 1) {
  630. if ($row['type'] != 'pagebreak') {
  631. $paged_questions[$counter][] = $row['question_id'];
  632. $counter++;
  633. continue;
  634. }
  635. } else {
  636. if ($row['type'] == 'pagebreak') {
  637. $counter++;
  638. } else {
  639. $paged_questions[$counter][] = $row['question_id'];
  640. }
  641. }
  642. }
  643. Session::write('paged_questions', $paged_questions);
  644. }
  645. // Redefinition of variables and session ids to fix issue of survey not
  646. // showing questions - see support.chamilo.org #5529
  647. $course_id = $survey_invitation['c_id'];
  648. Session::write('_cid', $course_id);
  649. Session::write('_real_cid', $course_id);
  650. if (array_key_exists($_GET['show'], $paged_questions)) {
  651. if (isset($_GET['user_id'])) {
  652. // Get the user into survey answer table (user or anonymus)
  653. $my_user_id = $survey_data['anonymous'] == 1 ? $surveyUserFromSession : api_get_user_id();
  654. $sql = "SELECT
  655. survey_question.survey_group_sec1,
  656. survey_question.survey_group_sec2,
  657. survey_question.survey_group_pri,
  658. survey_question.question_id,
  659. survey_question.survey_id,
  660. survey_question.survey_question,
  661. survey_question.display,
  662. survey_question.sort,
  663. survey_question.type,
  664. survey_question.max_value,
  665. survey_question_option.question_option_id,
  666. survey_question_option.option_text,
  667. survey_question_option.sort as option_sort
  668. FROM $table_survey_question survey_question
  669. LEFT JOIN $table_survey_question_option survey_question_option
  670. ON survey_question.question_id = survey_question_option.question_id AND
  671. survey_question_option.c_id = $course_id
  672. WHERE
  673. survey_question.survey_id = '".Database::escape_string($survey_invitation['survey_id'])."' AND
  674. survey_question.question_id NOT IN (
  675. SELECT sa.question_id
  676. FROM ".$table_survey_answer." sa
  677. WHERE
  678. sa.user='".$my_user_id."') AND
  679. survey_question.c_id = $course_id
  680. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  681. } else {
  682. $sql = "SELECT
  683. survey_question.survey_group_sec1,
  684. survey_question.survey_group_sec2,
  685. survey_question.survey_group_pri,
  686. survey_question.question_id,
  687. survey_question.survey_id,
  688. survey_question.survey_question,
  689. survey_question.display,
  690. survey_question.sort,
  691. survey_question.type,
  692. survey_question.max_value,
  693. survey_question_option.question_option_id,
  694. survey_question_option.option_text,
  695. survey_question_option.sort as option_sort
  696. ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
  697. FROM $table_survey_question survey_question
  698. LEFT JOIN $table_survey_question_option survey_question_option
  699. ON survey_question.question_id = survey_question_option.question_id AND
  700. survey_question_option.c_id = $course_id
  701. WHERE
  702. survey_question NOT LIKE '%{{%' AND
  703. survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
  704. survey_question.question_id IN (".implode(',', $paged_questions[$_GET['show']]).") AND
  705. survey_question.c_id = $course_id
  706. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  707. }
  708. $result = Database::query($sql);
  709. $question_counter_max = Database::num_rows($result);
  710. $counter = 0;
  711. $limit = 0;
  712. $questions = [];
  713. while ($row = Database :: fetch_array($result, 'ASSOC')) {
  714. // If the type is not a pagebreak we store it in the $questions array
  715. if ($row['type'] != 'pagebreak') {
  716. $questions[$row['sort']]['question_id'] = $row['question_id'];
  717. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  718. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  719. $questions[$row['sort']]['display'] = $row['display'];
  720. $questions[$row['sort']]['type'] = $row['type'];
  721. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  722. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  723. $questions[$row['sort']]['sort'] = $row['sort'];
  724. $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
  725. }
  726. $counter++;
  727. }
  728. }
  729. } elseif ($survey_data['survey_type'] === '1') {
  730. $my_survey_id = (int) $survey_invitation['survey_id'];
  731. $current_user = Database::escape_string($survey_invitation['user']);
  732. if (isset($_POST['personality'])) {
  733. // Compute the results to get the 3 groups nearest to the user's personality
  734. if ($shuffle == '') {
  735. $order = 'BY sort ASC ';
  736. } else {
  737. $order = $shuffle;
  738. }
  739. $answer_list = [];
  740. // Get current user results
  741. $results = [];
  742. $sql = "SELECT
  743. survey_group_pri,
  744. user,
  745. SUM(value) as value
  746. FROM $table_survey_answer as survey_answer
  747. INNER JOIN $table_survey_question as survey_question
  748. ON (survey_question.question_id = survey_answer.question_id)
  749. WHERE
  750. survey_answer.survey_id='".$my_survey_id."' AND
  751. survey_answer.user='".$current_user."' AND
  752. survey_answer.c_id = $course_id AND
  753. survey_question.c_id = $course_id AND
  754. GROUP BY survey_group_pri
  755. ORDER BY survey_group_pri
  756. ";
  757. $result = Database::query($sql);
  758. while ($row = Database :: fetch_array($result)) {
  759. $answer_list['value'] = $row['value'];
  760. $answer_list['group'] = $row['survey_group_pri'];
  761. $results[] = $answer_list;
  762. }
  763. // Get the total score for each group of questions
  764. $totals = [];
  765. $sql = "SELECT SUM(temp.value) as value, temp.survey_group_pri FROM
  766. (
  767. SELECT
  768. MAX(value) as value,
  769. survey_group_pri,
  770. survey_question.question_id
  771. FROM $table_survey_question as survey_question
  772. INNER JOIN $table_survey_question_option as survey_question_option
  773. ON (survey_question.question_id = survey_question_option.question_id)
  774. WHERE
  775. survey_question.survey_id='".$my_survey_id."' AND
  776. survey_question.c_id = $course_id AND
  777. survey_question_option.c_id = $course_id AND
  778. survey_group_sec1='0' AND
  779. survey_group_sec2='0'
  780. GROUP BY survey_group_pri, survey_question.question_id
  781. ) as temp
  782. GROUP BY temp.survey_group_pri
  783. ORDER BY temp.survey_group_pri";
  784. $result = Database::query($sql);
  785. while ($row = Database::fetch_array($result)) {
  786. $list['value'] = $row['value'];
  787. $list['group'] = $row['survey_group_pri'];
  788. $totals[] = $list;
  789. }
  790. $final_results = [];
  791. // Get a percentage score for each group
  792. for ($i = 0; $i < count($totals); $i++) {
  793. for ($j = 0; $j < count($results); $j++) {
  794. if ($totals[$i]['group'] == $results[$j]['group']) {
  795. $group = $totals[$i]['group'];
  796. $porcen = ($results[$j]['value'] / $totals[$i]['value']);
  797. $final_results[$group] = $porcen;
  798. }
  799. }
  800. }
  801. // Sort the results by score (getting a list of group IDs by score into $groups)
  802. arsort($final_results);
  803. $groups = array_keys($final_results);
  804. $result = [];
  805. $count_result = 0;
  806. foreach ($final_results as $key => &$sub_result) {
  807. $result[] = ['group' => $key, 'value' => $sub_result];
  808. $count_result++;
  809. }
  810. /*
  811. //i.e 70% - 70% -70% 70% $equal_count =3
  812. while (1) {
  813. if ($result[$i]['value'] == $result[$i+1]['value']) {
  814. $equal_count++;
  815. } else {
  816. break;
  817. }
  818. $i++;
  819. }
  820. echo 'eq'. $equal_count;
  821. echo '<br />';
  822. if ($equal_count == 0) {
  823. //i.e 70% 70% -60% 60% $equal_count = 1 only we get the first 2 options
  824. if (($result[0]['value'] == $result[1]['value']) && ($result[2]['value'] == $result[3]['value'])) {
  825. $group_cant = 1;
  826. } else {
  827. // By default we chose the highest 3
  828. $group_cant=2;
  829. }
  830. } elseif ($equal_count == 2) {
  831. $group_cant = 2;
  832. } else {
  833. $group_cant = -1;
  834. }
  835. */
  836. // i.e 70% - 70% -70% 70% $equal_count =3
  837. $i = 0;
  838. $group_cant = 0;
  839. $equal_count = 0;
  840. // This is the case if the user does not select any question
  841. if ($count_result > 0) {
  842. // Count the number of scores equal to the first
  843. while (1) {
  844. if ($result[$i]['value'] == $result[$i + 1]['value']) {
  845. $equal_count++;
  846. } else {
  847. break;
  848. }
  849. $i++;
  850. }
  851. } else {
  852. // We force the exit of the survey undeterminated
  853. $equal_count = 10;
  854. }
  855. // If we have only 3 or less equal scores (i.e. 0,1 or 2 equalities), then we can use the three first groups
  856. if ($equal_count < 4) {
  857. // If there is one or less score equalities
  858. if ($equal_count === 0 || $equal_count === 1) {
  859. // i.e 70% - 70% -60% - 60% $equal_count = 1 we only get the first 2 options
  860. if (($result[0]['value'] == $result[1]['value']) &&
  861. ($result[2]['value'] == $result[3]['value'])
  862. ) {
  863. $group_cant = 1;
  864. } elseif (($result[0]['value'] != $result[1]['value']) &&
  865. ($result[1]['value'] == $result[2]['value']) && ($result[2]['value'] == $result[3]['value'])
  866. ) {
  867. // i.e 70% - 70% -0% - 0% - $equal_count = 0 we only get the first 2 options
  868. /* elseif (($result[0]['value'] == $result[1]['value']) && ($result[1]['value'] != $result[2]['value'])) {
  869. $group_cant = 0;
  870. } */
  871. /*
  872. // i.e 70% - 70% -60% - 60% $equal_count = 0 we only get the first 2 options
  873. elseif (($result[0]['value'] == $result[1]['value']) && ($result[2]['value'] == $result[3]['value'])) {
  874. $group_cant = 0;
  875. } */
  876. // i.e. 80% - 70% - 70% - 70%
  877. $group_cant = 0;
  878. } else {
  879. // i.e. 80% - 70% - 70% - 50
  880. // i.e. 80% - 80% - 70% - 50
  881. // By default we choose the highest 3
  882. $group_cant = 2;
  883. }
  884. } else {
  885. // If there are two score equalities
  886. $group_cant = $equal_count;
  887. }
  888. //@todo Translate these comments.
  889. // conditional_status
  890. // 0 no determinado
  891. // 1 determinado
  892. // 2 un solo valor
  893. // 3 valores iguales
  894. if ($group_cant > 0) {
  895. //echo '$equal_count'.$group_cant;
  896. // We only get highest 3
  897. $secondary = '';
  898. $combi = '';
  899. for ($i = 0; $i <= $group_cant; $i++) {
  900. $group1 = $groups[$i];
  901. $group2 = $groups[$i + 1];
  902. // Here we made all the posibilities with the 3 groups
  903. if ($group_cant == 2 && $i == $group_cant) {
  904. $group2 = $groups[0];
  905. $secondary .= " OR ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  906. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  907. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  908. } else {
  909. if ($i != 0) {
  910. $secondary .= " OR ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  911. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  912. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  913. } else {
  914. $secondary .= " ( survey_group_sec1 = '$group1' AND survey_group_sec2 = '$group2') ";
  915. $secondary .= " OR ( survey_group_sec1 = '$group2' AND survey_group_sec2 = '$group1' ) ";
  916. $combi .= $group1.' - '.$group2." or ".$group2.' - '.$group1.'<br />';
  917. }
  918. }
  919. }
  920. // Create the new select with the questions from the secondary phase
  921. if (empty($_SESSION['page_questions_sec']) &&
  922. !is_array($_SESSION['page_questions_sec']) &&
  923. count($_SESSION['page_questions_sec'] == 0)
  924. ) {
  925. $sql = "SELECT * FROM $table_survey_question
  926. WHERE
  927. c_id = $course_id AND
  928. survey_id = '".$my_survey_id."' AND
  929. ($secondary )
  930. ORDER BY sort ASC";
  931. $result = Database::query($sql);
  932. $counter = 0;
  933. while ($row = Database::fetch_array($result, 'ASSOC')) {
  934. if ($survey_data['one_question_per_page'] == 1) {
  935. $paged_questions_sec[$counter][] = $row['question_id'];
  936. $counter++;
  937. } elseif ($row['type'] == 'pagebreak') {
  938. $counter++;
  939. } else {
  940. // ids from question of the current survey
  941. $paged_questions_sec[$counter][] = $row['question_id'];
  942. }
  943. }
  944. Session::write('page_questions_sec', $paged_questions_sec);
  945. } else {
  946. $paged_questions_sec = Session::read('page_questions_sec');
  947. }
  948. $paged_questions = Session::read('paged_questions'); // For the sake of pages counting
  949. if ($shuffle == '') {
  950. $shuffle = ' BY survey_question.sort, survey_question_option.sort ASC ';
  951. }
  952. $val = (int) $_POST['personality'];
  953. if (is_array($paged_questions_sec)) {
  954. $sql = "SELECT
  955. survey_question.survey_group_sec1,
  956. survey_question.survey_group_sec2,
  957. survey_question.survey_group_pri,
  958. survey_question.question_id,
  959. survey_question.survey_id,
  960. survey_question.survey_question,
  961. survey_question.display,
  962. survey_question.sort,
  963. survey_question.type,
  964. survey_question.max_value,
  965. survey_question_option.question_option_id,
  966. survey_question_option.option_text,
  967. survey_question_option.sort as option_sort
  968. FROM $table_survey_question survey_question
  969. LEFT JOIN $table_survey_question_option survey_question_option
  970. ON survey_question.question_id = survey_question_option.question_id AND
  971. survey_question_option.c_id = $course_id
  972. WHERE
  973. survey_question NOT LIKE '%{{%' AND
  974. survey_question.survey_id = '".$my_survey_id."' AND
  975. survey_question.c_id = $course_id AND
  976. survey_question.question_id IN (".implode(',', $paged_questions_sec[$val]).")
  977. ORDER $shuffle ";
  978. $result = Database::query($sql);
  979. $question_counter_max = Database::num_rows($result);
  980. $counter = 0;
  981. $limit = 0;
  982. $questions = [];
  983. while ($row = Database::fetch_array($result, 'ASSOC')) {
  984. // If the type is not a pagebreak we store it in the $questions array
  985. if ($row['type'] != 'pagebreak') {
  986. $questions[$row['sort']]['question_id'] = $row['question_id'];
  987. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  988. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  989. $questions[$row['sort']]['display'] = $row['display'];
  990. $questions[$row['sort']]['type'] = $row['type'];
  991. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  992. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  993. // Personality params
  994. $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
  995. $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
  996. $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
  997. $questions[$row['sort']]['sort'] = $row['sort'];
  998. } else {
  999. // If the type is a pagebreak we are finished loading the questions for this page
  1000. break;
  1001. }
  1002. $counter++;
  1003. }
  1004. } else {
  1005. echo get_lang('SurveyUndetermined');
  1006. }
  1007. } else {
  1008. echo get_lang('SurveyUndetermined');
  1009. }
  1010. } else {
  1011. echo get_lang('SurveyUndetermined');
  1012. }
  1013. } else {
  1014. // We need this variable only in the 2nd set of questions when personality is set.
  1015. Session::erase('page_questions_sec');
  1016. $paged_questions_sec = [];
  1017. // Only the questions from the basic group
  1018. // the 50 questions A B C D E F G
  1019. $order_sql = $shuffle;
  1020. if ($shuffle == '') {
  1021. $order_sql = ' BY question_id ';
  1022. }
  1023. if (empty($_SESSION['paged_questions'])) {
  1024. $sql = "SELECT * FROM $table_survey_question
  1025. WHERE
  1026. c_id = $course_id AND
  1027. survey_id = '".intval($survey_invitation['survey_id'])."' AND
  1028. survey_group_sec1='0' AND
  1029. survey_group_sec2='0'
  1030. ORDER ".$order_sql." ";
  1031. $result = Database::query($sql);
  1032. $counter = 0;
  1033. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1034. if ($survey_data['one_question_per_page'] == 1) {
  1035. $paged_questions[$counter][] = $row['question_id'];
  1036. $counter++;
  1037. } else {
  1038. if ($row['type'] == 'pagebreak') {
  1039. $counter++;
  1040. } else {
  1041. // ids from question of the current survey
  1042. $paged_questions[$counter][] = $row['question_id'];
  1043. }
  1044. }
  1045. }
  1046. Session::write('paged_questions', $paged_questions);
  1047. } else {
  1048. $paged_questions = Session::read('paged_questions');
  1049. }
  1050. $order_sql = $shuffle;
  1051. if ($shuffle == '') {
  1052. $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
  1053. }
  1054. $val = $_GET['show'];
  1055. $result = null;
  1056. if ($val != '') {
  1057. $imploded = Database::escape_string(implode(',', $paged_questions[$val]));
  1058. if ($imploded != '') {
  1059. // The answers are always in the same order NO shuffle
  1060. $order_sql = ' BY survey_question.sort, survey_question_option.sort ASC ';
  1061. $sql = "SELECT
  1062. survey_question.survey_group_sec1,
  1063. survey_question.survey_group_sec2,
  1064. survey_question.survey_group_pri,
  1065. survey_question.question_id,
  1066. survey_question.survey_id,
  1067. survey_question.survey_question,
  1068. survey_question.display,
  1069. survey_question.sort,
  1070. survey_question.type,
  1071. survey_question.max_value,
  1072. survey_question_option.question_option_id,
  1073. survey_question_option.option_text,
  1074. survey_question_option.sort as option_sort
  1075. ".($allowRequiredSurveyQuestions ? ', survey_question.is_required' : '')."
  1076. FROM $table_survey_question survey_question
  1077. LEFT JOIN $table_survey_question_option survey_question_option
  1078. ON survey_question.question_id = survey_question_option.question_id AND
  1079. survey_question_option.c_id = $course_id
  1080. WHERE
  1081. survey_question NOT LIKE '%{{%' AND
  1082. survey_question.survey_id = '".intval($survey_invitation['survey_id'])."' AND
  1083. survey_question.c_id = $course_id AND
  1084. survey_question.question_id IN (".$imploded.")
  1085. ORDER $order_sql ";
  1086. $result = Database::query($sql);
  1087. $question_counter_max = Database :: num_rows($result);
  1088. }
  1089. }
  1090. if (!is_null($result)) {
  1091. $counter = 0;
  1092. $limit = 0;
  1093. $questions = [];
  1094. while ($row = Database :: fetch_array($result, 'ASSOC')) {
  1095. // If the type is not a pagebreak we store it in the $questions array
  1096. if ($row['type'] != 'pagebreak') {
  1097. $questions[$row['sort']]['question_id'] = $row['question_id'];
  1098. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  1099. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  1100. $questions[$row['sort']]['display'] = $row['display'];
  1101. $questions[$row['sort']]['type'] = $row['type'];
  1102. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  1103. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  1104. $questions[$row['sort']]['is_required'] = $allowRequiredSurveyQuestions && $row['is_required'];
  1105. // Personality params
  1106. $questions[$row['sort']]['survey_group_sec1'] = $row['survey_group_sec1'];
  1107. $questions[$row['sort']]['survey_group_sec2'] = $row['survey_group_sec2'];
  1108. $questions[$row['sort']]['survey_group_pri'] = $row['survey_group_pri'];
  1109. $questions[$row['sort']]['sort'] = $row['sort'];
  1110. } else {
  1111. // If the type is a page break we are finished loading the questions for this page
  1112. //break;
  1113. }
  1114. $counter++;
  1115. }
  1116. }
  1117. }
  1118. } else { // In case it's another type than 0 or 1
  1119. echo get_lang('ErrorSurveyTypeUnknown');
  1120. }
  1121. }
  1122. $numberOfPages = SurveyManager::getCountPages($survey_data);
  1123. // Displaying the form with the questions
  1124. $show = 0;
  1125. if (isset($_GET['show']) && $_GET['show'] != '') {
  1126. $show = (int) $_GET['show'] + 1;
  1127. }
  1128. $displayFinishButton = true;
  1129. if (isset($_GET['show']) && $_GET['show'] != '') {
  1130. $pagesIndexes = array_keys($paged_questions);
  1131. $pagesIndexes[] = count($pagesIndexes);
  1132. if (end($pagesIndexes) <= $show - 1 && empty($_POST)) {
  1133. $displayFinishButton = false;
  1134. }
  1135. }
  1136. // Displaying the form with the questions
  1137. $personality = 0;
  1138. if (isset($_POST['personality'])) {
  1139. $personality = (int) $_POST['personality'] + 1;
  1140. }
  1141. // Displaying the form with the questions
  1142. $g_c = isset($_GET['course']) ? Security::remove_XSS($_GET['course']) : '';
  1143. $g_ic = isset($_GET['invitationcode']) ? Security::remove_XSS($_GET['invitationcode']) : '';
  1144. $g_cr = isset($_GET['cidReq']) ? Security::remove_XSS($_GET['cidReq']) : '';
  1145. $p_l = isset($_POST['language']) ? Security::remove_XSS($_POST['language']) : '';
  1146. $add_parameters = isset($_GET['user_id']) ? '&user_id='.intval($_GET['user_id']) : '';
  1147. $url = api_get_self().'?cidReq='.$courseInfo['code'].
  1148. '&id_session='.$sessionId.
  1149. $add_parameters.
  1150. '&course='.$g_c.
  1151. '&invitationcode='.$g_ic.
  1152. '&show='.$show;
  1153. $form = new FormValidator(
  1154. 'question',
  1155. 'post',
  1156. $url,
  1157. null,
  1158. null,
  1159. FormValidator::LAYOUT_INLINE
  1160. );
  1161. $form->addHidden('language', $p_l);
  1162. if (isset($questions) && is_array($questions)) {
  1163. $originalShow = isset($_GET['show']) ? (int) $_GET['show'] : 0;
  1164. $questionCounter = 1;
  1165. if (!empty($originalShow)) {
  1166. $before = 0;
  1167. foreach ($paged_questions as $keyQuestion => $list) {
  1168. if ($originalShow > $keyQuestion) {
  1169. $before += count($list);
  1170. }
  1171. }
  1172. $questionCounter = $before + 1;
  1173. }
  1174. foreach ($questions as $key => &$question) {
  1175. $ch_type = 'ch_'.$question['type'];
  1176. $questionNumber = $questionCounter;
  1177. $display = new $ch_type();
  1178. // @todo move this in a function.
  1179. $form->addHtml('<div class="survey_question '.$ch_type.'">');
  1180. $form->addHtml('<div style="float:left; font-weight: bold; margin-right: 5px;"> '.$questionNumber.'. </div>');
  1181. $form->addHtml('<div>'.Security::remove_XSS($question['survey_question']).'</div> ');
  1182. $userAnswerData = SurveyUtil::get_answers_of_question_by_user($question['survey_id'], $question['question_id']);
  1183. $finalAnswer = null;
  1184. if (!empty($userAnswerData[$user_id])) {
  1185. $userAnswer = $userAnswerData[$user_id];
  1186. switch ($question['type']) {
  1187. case 'score':
  1188. $finalAnswer = [];
  1189. foreach ($userAnswer as $userChoice) {
  1190. list($choiceId, $choiceValue) = explode('*', $userChoice);
  1191. $finalAnswer[$choiceId] = $choiceValue;
  1192. }
  1193. break;
  1194. case 'percentage':
  1195. list($choiceId, $choiceValue) = explode('*', current($userAnswer));
  1196. $finalAnswer = $choiceId;
  1197. break;
  1198. default:
  1199. $finalAnswer = $userAnswer;
  1200. break;
  1201. }
  1202. }
  1203. $display->render($form, $question, $finalAnswer);
  1204. $form->addHtml('</div>');
  1205. $questionCounter++;
  1206. }
  1207. }
  1208. $form->addHtml('<div class="start-survey">');
  1209. if ($survey_data['survey_type'] == '0') {
  1210. if ($survey_data['show_form_profile'] == 0) {
  1211. // The normal survey as always
  1212. if ($show < $numberOfPages) {
  1213. if ($show == 0) {
  1214. $form->addButton(
  1215. 'next_survey_page',
  1216. get_lang('StartSurvey'),
  1217. 'arrow-right',
  1218. 'success'
  1219. );
  1220. } else {
  1221. $form->addButton(
  1222. 'next_survey_page',
  1223. get_lang('Next'),
  1224. 'arrow-right',
  1225. 'success'
  1226. );
  1227. }
  1228. }
  1229. if ($show >= $numberOfPages && $displayFinishButton) {
  1230. $form->addButton(
  1231. 'finish_survey',
  1232. get_lang('FinishSurvey'),
  1233. 'arrow-right',
  1234. 'success'
  1235. );
  1236. }
  1237. } else {
  1238. // The normal survey as always but with the form profile
  1239. if (isset($_GET['show'])) {
  1240. $numberOfPages = count($paged_questions);
  1241. if ($show < $numberOfPages) {
  1242. if ($show == 0) {
  1243. $form->addButton(
  1244. 'next_survey_page',
  1245. get_lang('StartSurvey'),
  1246. 'arrow-right',
  1247. 'success'
  1248. );
  1249. } else {
  1250. $form->addButton(
  1251. 'next_survey_page',
  1252. get_lang('Next'),
  1253. 'arrow-right',
  1254. 'success'
  1255. );
  1256. }
  1257. }
  1258. if ($show >= $numberOfPages && $displayFinishButton) {
  1259. $form->addButton(
  1260. 'finish_survey',
  1261. get_lang('FinishSurvey'),
  1262. 'arrow-right',
  1263. 'success'
  1264. );
  1265. }
  1266. }
  1267. }
  1268. } elseif ($survey_data['survey_type'] == '1') {
  1269. // Conditional/personality-test type survey
  1270. if (isset($_GET['show']) || isset($_POST['personality'])) {
  1271. $numberOfPages = count($paged_questions);
  1272. if (!empty($paged_questions_sec) && count($paged_questions_sec) > 0) {
  1273. // In case we're in the second phase, also sum the second group questions
  1274. $numberOfPages += count($paged_questions_sec);
  1275. } else {
  1276. // We need this variable only if personality == 1
  1277. Session::erase('page_questions_sec');
  1278. $paged_questions_sec = [];
  1279. }
  1280. if ($personality == 0) {
  1281. if (($show <= $numberOfPages) || !$_GET['show']) {
  1282. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1283. if ($survey_data['one_question_per_page'] == 0) {
  1284. if ($personality >= 0) {
  1285. $form->addHidden('personality', $personality);
  1286. }
  1287. } else {
  1288. if ($personality > 0) {
  1289. $form->addHidden('personality', $personality);
  1290. }
  1291. }
  1292. if ($numberOfPages == $show) {
  1293. $form->addHidden('personality', $personality);
  1294. }
  1295. }
  1296. }
  1297. if ($show > $numberOfPages && $_GET['show'] && $personality == 0) {
  1298. $form->addHidden('personality', $personality);
  1299. } elseif ($personality > 0) {
  1300. if ($survey_data['one_question_per_page'] == 1) {
  1301. if ($show >= $numberOfPages) {
  1302. $form->addButton('finish_survey', get_lang('FinishSurvey'), 'arrow-right', 'success');
  1303. } else {
  1304. $form->addHidden('personality', $personality);
  1305. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1306. }
  1307. } else {
  1308. // if the personality test hidden input was set.
  1309. $form->addButton('finish_survey', get_lang('FinishSurvey'), 'arrow-right');
  1310. }
  1311. }
  1312. } elseif ($survey_data['form_fields'] == '') {
  1313. // This is the case when the show_profile_form is true but there are not form_fields
  1314. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1315. } elseif (!is_array($user_data)) {
  1316. // If the user is not registered in the platform we do not show the form to update his information
  1317. $form->addButton('next_survey_page', get_lang('Next'), 'arrow-right', 'success');
  1318. }
  1319. }
  1320. $form->addHtml('</div>');
  1321. $form->display();
  1322. Display::display_footer();