fillsurvey.php 61 KB

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