fillsurvey.php 61 KB

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