survey.lib.php 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CSurveyInvitation;
  4. use Doctrine\Common\Collections\Criteria;
  5. /**
  6. * Class SurveyManager
  7. * @package chamilo.survey
  8. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University:
  9. * cleanup, refactoring and rewriting large parts (if not all) of the code
  10. * @author Julio Montoya <gugli100@gmail.com>, Personality Test modification
  11. * and rewriting large parts of the code
  12. * @author cfasanando
  13. * @todo move this file to inc/lib
  14. * @todo use consistent naming for the functions (save vs store for instance)
  15. */
  16. class SurveyManager
  17. {
  18. /**
  19. * @param $code
  20. *
  21. * @return string
  22. */
  23. public static function generate_unique_code($code)
  24. {
  25. if (empty($code)) {
  26. return false;
  27. }
  28. $course_id = api_get_course_int_id();
  29. $table_survey = Database::get_course_table(TABLE_SURVEY);
  30. $code = Database::escape_string($code);
  31. $num = 0;
  32. $new_code = $code;
  33. while (true) {
  34. $sql = "SELECT * FROM $table_survey
  35. WHERE code = '$new_code' AND c_id = $course_id";
  36. $result = Database::query($sql);
  37. if (Database::num_rows($result)) {
  38. $num++;
  39. $new_code = $code.$num;
  40. } else {
  41. break;
  42. }
  43. }
  44. return $code.$num;
  45. }
  46. /**
  47. * Deletes all survey invitations of a user
  48. * @param int $user_id
  49. *
  50. * @return boolean
  51. * @assert ('') === false
  52. */
  53. public static function delete_all_survey_invitations_by_user($user_id)
  54. {
  55. $user_id = intval($user_id);
  56. if (empty($user_id)) {
  57. return false;
  58. }
  59. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  60. $table_survey = Database::get_course_table(TABLE_SURVEY);
  61. $sql = "SELECT survey_invitation_id, survey_code
  62. FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
  63. $result = Database::query($sql);
  64. while ($row = Database::fetch_array($result, 'ASSOC')) {
  65. $survey_invitation_id = $row['survey_invitation_id'];
  66. $survey_code = $row['survey_code'];
  67. $sql2 = "DELETE FROM $table_survey_invitation
  68. WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
  69. if (Database::query($sql2)) {
  70. $sql3 = "UPDATE $table_survey SET
  71. invited = invited-1
  72. WHERE c_id <> 0 AND code ='$survey_code'";
  73. Database::query($sql3);
  74. }
  75. }
  76. }
  77. /**
  78. *
  79. * @param string $course_code
  80. * @param int $session_id
  81. *
  82. * @return array
  83. * @assert ('') === false
  84. */
  85. public static function get_surveys($course_code, $session_id = 0)
  86. {
  87. $table_survey = Database::get_course_table(TABLE_SURVEY);
  88. if (empty($course_code)) {
  89. return false;
  90. }
  91. $course_info = api_get_course_info($course_code);
  92. $session_condition = api_get_session_condition($session_id, true, true);
  93. $sql = "SELECT * FROM $table_survey
  94. WHERE c_id = {$course_info['real_id']} $session_condition ";
  95. $result = Database::query($sql);
  96. $result = Database::store_result($result, 'ASSOC');
  97. return $result;
  98. }
  99. /**
  100. * Retrieves all the survey information
  101. *
  102. * @param integer $survey_id the id of the survey
  103. * @param boolean $shared this parameter determines if
  104. * we have to get the information of a survey from the central (shared) database or from the
  105. * course database
  106. * @param string course code optional
  107. *
  108. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  109. * @version February 2007
  110. * @assert ('') === false
  111. * @return array
  112. *
  113. * @todo this is the same function as in create_new_survey.php
  114. */
  115. public static function get_survey(
  116. $survey_id,
  117. $shared = 0,
  118. $course_code = '',
  119. $simple_return = false
  120. ) {
  121. // Table definition
  122. if (!empty($course_code)) {
  123. $my_course_id = $course_code;
  124. } elseif (isset($_GET['course'])) {
  125. $my_course_id = Security::remove_XSS($_GET['course']);
  126. } else {
  127. $my_course_id = api_get_course_id();
  128. }
  129. $my_course_info = api_get_course_info($my_course_id);
  130. $table_survey = Database::get_course_table(TABLE_SURVEY);
  131. if ($shared != 0) {
  132. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  133. $sql = "SELECT * FROM $table_survey
  134. WHERE survey_id='".intval($survey_id)."' ";
  135. } else {
  136. $sql = "SELECT * FROM $table_survey
  137. WHERE
  138. survey_id='".intval($survey_id)."' AND
  139. c_id = ".$my_course_info['real_id'];
  140. }
  141. $result = Database::query($sql);
  142. $return = array();
  143. if (Database::num_rows($result) > 0) {
  144. $return = Database::fetch_array($result, 'ASSOC');
  145. if ($simple_return) {
  146. return $return;
  147. }
  148. // We do this (temporarily) to have the array match the quickform elements immediately
  149. // idealiter the fields in the db match the quickform fields
  150. $return['survey_code'] = $return['code'];
  151. $return['survey_title'] = $return['title'];
  152. $return['survey_subtitle'] = $return['subtitle'];
  153. $return['survey_language'] = $return['lang'];
  154. $return['start_date'] = $return['avail_from'];
  155. $return['end_date'] = $return['avail_till'];
  156. $return['survey_share'] = $return['is_shared'];
  157. $return['survey_introduction'] = $return['intro'];
  158. $return['survey_thanks'] = $return['surveythanks'];
  159. $return['survey_type'] = $return['survey_type'];
  160. $return['one_question_per_page'] = $return['one_question_per_page'];
  161. $return['show_form_profile'] = $return['show_form_profile'];
  162. $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
  163. $return['shuffle'] = $return['shuffle'];
  164. $return['parent_id'] = $return['parent_id'];
  165. $return['survey_version'] = $return['survey_version'];
  166. $return['anonymous'] = $return['anonymous'];
  167. }
  168. return $return;
  169. }
  170. /**
  171. * This function stores a survey in the database.
  172. *
  173. * @param array $values
  174. *
  175. * @return array $return the type of return message that has to be displayed and the message in it
  176. *
  177. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  178. * @version February 2007
  179. */
  180. public static function store_survey($values)
  181. {
  182. $_user = api_get_user_info();
  183. $course_id = api_get_course_int_id();
  184. $session_id = api_get_session_id();
  185. $courseCode = api_get_course_id();
  186. $table_survey = Database::get_course_table(TABLE_SURVEY);
  187. $shared_survey_id = 0;
  188. if (!isset($values['survey_id'])) {
  189. // Check if the code doesn't soon exists in this language
  190. $sql = 'SELECT 1 FROM '.$table_survey.'
  191. WHERE
  192. c_id = '.$course_id.' AND
  193. code="'.Database::escape_string($values['survey_code']).'" AND
  194. lang="'.Database::escape_string($values['survey_language']).'"';
  195. $rs = Database::query($sql);
  196. if (Database::num_rows($rs) > 0) {
  197. Display::addFlash(
  198. Display::return_message(
  199. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  200. 'error'
  201. )
  202. );
  203. $return['type'] = 'error';
  204. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  205. return $return;
  206. }
  207. if (!isset($values['anonymous'])) {
  208. $values['anonymous'] = 0;
  209. }
  210. $values['anonymous'] = intval($values['anonymous']);
  211. $additional['columns'] = '';
  212. $extraParams = [];
  213. if ($values['anonymous'] == 0) {
  214. // Input_name_list
  215. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
  216. $extraParams['show_form_profile'] = $values['show_form_profile'];
  217. if ($values['show_form_profile'] == 1) {
  218. // Input_name_list
  219. $fields = explode(',', $values['input_name_list']);
  220. $field_values = '';
  221. foreach ($fields as & $field) {
  222. if ($field != '') {
  223. if ($values[$field] == '') {
  224. $values[$field] = 0;
  225. }
  226. $field_values .= $field.':'.$values[$field].'@';
  227. }
  228. }
  229. $extraParams['form_fields'] = $field_values;
  230. } else {
  231. $extraParams['form_fields'] = '';
  232. }
  233. } else {
  234. // Input_name_list
  235. $extraParams['show_form_profile'] = 0;
  236. $extraParams['form_fields'] = '';
  237. }
  238. if ($values['survey_type'] == 1) {
  239. $extraParams['survey_type'] = 1;
  240. $extraParams['shuffle'] = $values['shuffle'];
  241. $extraParams['one_question_per_page'] = $values['one_question_per_page'];
  242. $extraParams['parent_id'] = $values['parent_id'];
  243. // Logic for versioning surveys
  244. if (!empty($values['parent_id'])) {
  245. $versionValue = '';
  246. $sql = 'SELECT survey_version
  247. FROM '.$table_survey.'
  248. WHERE
  249. c_id = '.$course_id.' AND
  250. parent_id = '.intval($values['parent_id']).'
  251. ORDER BY survey_version DESC
  252. LIMIT 1';
  253. $rs = Database::query($sql);
  254. if (Database::num_rows($rs) === 0) {
  255. $sql = 'SELECT survey_version FROM '.$table_survey.'
  256. WHERE
  257. c_id = '.$course_id.' AND
  258. survey_id = '.intval($values['parent_id']);
  259. $rs = Database::query($sql);
  260. $getversion = Database::fetch_array($rs, 'ASSOC');
  261. if (empty($getversion['survey_version'])) {
  262. $versionValue = ++$getversion['survey_version'];
  263. } else {
  264. $versionValue = $getversion['survey_version'];
  265. }
  266. } else {
  267. $row = Database::fetch_array($rs, 'ASSOC');
  268. $pos = api_strpos($row['survey_version']);
  269. if ($pos === false) {
  270. $row['survey_version'] = $row['survey_version'] + 1;
  271. $versionValue = $row['survey_version'];
  272. } else {
  273. $getlast = explode('\.', $row['survey_version']);
  274. $lastversion = array_pop($getlast);
  275. $lastversion = $lastversion + 1;
  276. $add = implode('.', $getlast);
  277. if ($add != '') {
  278. $insertnewversion = $add.'.'.$lastversion;
  279. } else {
  280. $insertnewversion = $lastversion;
  281. }
  282. $versionValue = $insertnewversion;
  283. }
  284. }
  285. $extraParams['survey_version'] = $versionValue;
  286. }
  287. }
  288. $params = [
  289. 'c_id' => $course_id,
  290. 'code' => strtolower(CourseManager::generate_course_code($values['survey_code'])),
  291. 'title' => $values['survey_title'],
  292. 'subtitle' => $values['survey_subtitle'],
  293. 'author' => $_user['user_id'],
  294. 'lang' => $values['survey_language'],
  295. 'avail_from' => $values['start_date'],
  296. 'avail_till' => $values['end_date'],
  297. 'is_shared' => $shared_survey_id,
  298. 'template' => 'template',
  299. 'intro' => $values['survey_introduction'],
  300. 'surveythanks' => $values['survey_thanks'],
  301. 'creation_date' => api_get_utc_datetime(),
  302. 'anonymous' => $values['anonymous'],
  303. 'session_id' => api_get_session_id(),
  304. 'visible_results' => $values['visible_results']
  305. ];
  306. $params = array_merge($params, $extraParams);
  307. $survey_id = Database::insert($table_survey, $params);
  308. if ($survey_id > 0) {
  309. $sql = "UPDATE $table_survey SET survey_id = $survey_id
  310. WHERE iid = $survey_id";
  311. Database::query($sql);
  312. // Insert into item_property
  313. api_item_property_update(
  314. api_get_course_info(),
  315. TOOL_SURVEY,
  316. $survey_id,
  317. 'SurveyAdded',
  318. api_get_user_id()
  319. );
  320. }
  321. if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
  322. self::copy_survey($values['parent_id'], $survey_id);
  323. }
  324. Display::addFlash(
  325. Display::return_message(
  326. get_lang('SurveyCreatedSuccesfully'),
  327. 'success'
  328. )
  329. );
  330. $return['id'] = $survey_id;
  331. } else {
  332. // Check whether the code doesn't soon exists in this language
  333. $sql = 'SELECT 1 FROM '.$table_survey.'
  334. WHERE
  335. c_id = '.$course_id.' AND
  336. code = "'.Database::escape_string($values['survey_code']).'" AND
  337. lang = "'.Database::escape_string($values['survey_language']).'" AND
  338. survey_id !='.intval($values['survey_id']);
  339. $rs = Database::query($sql);
  340. if (Database::num_rows($rs) > 0) {
  341. Display::addFlash(
  342. Display::return_message(
  343. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  344. 'error'
  345. )
  346. );
  347. $return['type'] = 'error';
  348. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  349. return $return;
  350. }
  351. if (!isset($values['anonymous'])
  352. || (isset($values['anonymous']) && $values['anonymous'] == '')
  353. ) {
  354. $values['anonymous'] = 0;
  355. }
  356. $values['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : null;
  357. $values['one_question_per_page'] = isset($values['one_question_per_page'])
  358. ? $values['one_question_per_page']
  359. : null;
  360. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : null;
  361. $extraParams = [];
  362. $extraParams['shuffle'] = $values['shuffle'];
  363. $extraParams['one_question_per_page'] = $values['one_question_per_page'];
  364. $extraParams['shuffle'] = $values['shuffle'];
  365. if ($values['anonymous'] == 0) {
  366. $extraParams['show_form_profile'] = $values['show_form_profile'];
  367. if ($values['show_form_profile'] == 1) {
  368. $fields = explode(',', $values['input_name_list']);
  369. $field_values = '';
  370. foreach ($fields as &$field) {
  371. if ($field != '') {
  372. if (!isset($values[$field]) ||
  373. (isset($values[$field]) && $values[$field] == '')
  374. ) {
  375. $values[$field] = 0;
  376. }
  377. $field_values .= $field.':'.$values[$field].'@';
  378. }
  379. }
  380. $extraParams['form_fields'] = $field_values;
  381. } else {
  382. $extraParams['form_fields'] = '';
  383. }
  384. } else {
  385. $extraParams['show_form_profile'] = 0;
  386. $extraParams['form_fields'] = '';
  387. }
  388. $params = [
  389. 'title' => $values['survey_title'],
  390. 'subtitle' => $values['survey_subtitle'],
  391. 'author' => $_user['user_id'],
  392. 'lang' => $values['survey_language'],
  393. 'avail_from' => $values['start_date'],
  394. 'avail_till' => $values['end_date'],
  395. 'is_shared' => $shared_survey_id,
  396. 'template' => 'template',
  397. 'intro' => $values['survey_introduction'],
  398. 'surveythanks' => $values['survey_thanks'],
  399. 'anonymous' => $values['anonymous'],
  400. 'session_id' => api_get_session_id(),
  401. 'visible_results' => $values['visible_results'],
  402. ];
  403. $params = array_merge($params, $extraParams);
  404. Database::update(
  405. $table_survey,
  406. $params,
  407. [
  408. 'c_id = ? AND survey_id = ?' => [
  409. $course_id,
  410. $values['survey_id'],
  411. ],
  412. ]
  413. );
  414. // Update into item_property (update)
  415. api_item_property_update(
  416. api_get_course_info(),
  417. TOOL_SURVEY,
  418. $values['survey_id'],
  419. 'SurveyUpdated',
  420. api_get_user_id()
  421. );
  422. Display::addFlash(
  423. Display::return_message(
  424. get_lang('SurveyUpdatedSuccesfully'),
  425. 'confirmation'
  426. )
  427. );
  428. $return['id'] = $values['survey_id'];
  429. }
  430. $survey_id = intval($return['id']);
  431. // Gradebook
  432. $gradebook_option = false;
  433. if (isset($values['survey_qualify_gradebook'])) {
  434. $gradebook_option = $values['survey_qualify_gradebook'] > 0;
  435. }
  436. $gradebook_link_type = 8;
  437. $link_info = GradebookUtils::isResourceInCourseGradebook(
  438. $course_id,
  439. $gradebook_link_type,
  440. $survey_id,
  441. $session_id
  442. );
  443. $gradebook_link_id = isset($link_info['id']) ? $link_info['id'] : false;
  444. if ($gradebook_option) {
  445. if ($survey_id > 0) {
  446. $title_gradebook = ''; // Not needed here.
  447. $description_gradebook = ''; // Not needed here.
  448. $survey_weight = floatval($_POST['survey_weight']);
  449. $max_score = 1;
  450. if (!$gradebook_link_id) {
  451. GradebookUtils::add_resource_to_course_gradebook(
  452. $values['category_id'],
  453. $courseCode,
  454. $gradebook_link_type,
  455. $survey_id,
  456. $title_gradebook,
  457. $survey_weight,
  458. $max_score,
  459. $description_gradebook,
  460. 1,
  461. $session_id
  462. );
  463. } else {
  464. GradebookUtils::updateResourceFromCourseGradebook(
  465. $gradebook_link_id,
  466. $course_id,
  467. $survey_weight
  468. );
  469. }
  470. }
  471. } else {
  472. // Delete everything of the gradebook for this $linkId
  473. GradebookUtils::remove_resource_from_course_gradebook($gradebook_link_id);
  474. //comenting this line to correctly return the function msg
  475. //exit;
  476. }
  477. return $return;
  478. }
  479. /**
  480. * This function stores a shared survey in the central database.
  481. *
  482. * @param array $values
  483. * @return array $return the type of return message that has to be displayed and the message in it
  484. *
  485. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  486. * @version February 2007
  487. */
  488. public function store_shared_survey($values)
  489. {
  490. $_user = api_get_user_info();
  491. $_course = api_get_course_info();
  492. // Table definitions
  493. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  494. if (!$values['survey_id'] ||
  495. !is_numeric($values['survey_id']) ||
  496. $values['survey_share']['survey_share'] == 'true'
  497. ) {
  498. $sql = "INSERT INTO $table_survey (code, title, subtitle, author, lang, template, intro, surveythanks, creation_date, course_code) VALUES (
  499. '".Database::escape_string($values['survey_code'])."',
  500. '".Database::escape_string($values['survey_title'])."',
  501. '".Database::escape_string($values['survey_subtitle'])."',
  502. '".intval($_user['user_id'])."',
  503. '".Database::escape_string($values['survey_language'])."',
  504. '".Database::escape_string('template')."',
  505. '".Database::escape_string($values['survey_introduction'])."',
  506. '".Database::escape_string($values['survey_thanks'])."',
  507. '".api_get_utc_datetime()."',
  508. '".$_course['id']."')";
  509. Database::query($sql);
  510. $return = Database::insert_id();
  511. $sql = "UPDATE $table_survey SET survey_id = $return WHERE iid = $return";
  512. Database::query($sql);
  513. } else {
  514. $sql = "UPDATE $table_survey SET
  515. code = '".Database::escape_string($values['survey_code'])."',
  516. title = '".Database::escape_string($values['survey_title'])."',
  517. subtitle = '".Database::escape_string($values['survey_subtitle'])."',
  518. author = '".intval($_user['user_id'])."',
  519. lang = '".Database::escape_string($values['survey_language'])."',
  520. template = '".Database::escape_string('template')."',
  521. intro = '".Database::escape_string($values['survey_introduction'])."',
  522. surveythanks = '".Database::escape_string($values['survey_thanks'])."'
  523. WHERE survey_id = '".Database::escape_string($values['survey_share']['survey_share'])."'";
  524. Database::query($sql);
  525. $return = $values['survey_share']['survey_share'];
  526. }
  527. return $return;
  528. }
  529. /**
  530. * This function deletes a survey (and also all the question in that survey
  531. *
  532. * @param int $survey_id id of the survey that has to be deleted
  533. * @return true
  534. *
  535. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  536. * @version January 2007
  537. */
  538. public static function delete_survey($survey_id, $shared = false, $course_id = '')
  539. {
  540. // Database table definitions
  541. if (empty($course_id)) {
  542. $course_id = api_get_course_int_id();
  543. }
  544. $survey_id = intval($survey_id);
  545. if (empty($survey_id)) {
  546. return false;
  547. }
  548. $course_info = api_get_course_info_by_id($course_id);
  549. $course_id = $course_info['real_id'];
  550. $table_survey = Database::get_course_table(TABLE_SURVEY);
  551. $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  552. if ($shared) {
  553. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  554. // Deleting the survey
  555. $sql = "DELETE FROM $table_survey
  556. WHERE survey_id='".$survey_id."'";
  557. Database::query($sql);
  558. } else {
  559. $sql = "DELETE FROM $table_survey
  560. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  561. Database::query($sql);
  562. }
  563. // Deleting groups of this survey
  564. $sql = "DELETE FROM $table_survey_question_group
  565. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  566. Database::query($sql);
  567. // Deleting the questions of the survey
  568. self::delete_all_survey_questions($survey_id, $shared);
  569. // Update into item_property (delete)
  570. api_item_property_update(
  571. $course_info,
  572. TOOL_SURVEY,
  573. $survey_id,
  574. 'SurveyDeleted',
  575. api_get_user_id()
  576. );
  577. return true;
  578. }
  579. /**
  580. * @param int $survey_id
  581. * @param int $new_survey_id
  582. * @param int $targetCourseId
  583. *
  584. * @return bool
  585. */
  586. public static function copy_survey(
  587. $survey_id,
  588. $new_survey_id = null,
  589. $targetCourseId = null
  590. ) {
  591. $course_id = api_get_course_int_id();
  592. if (!$targetCourseId) {
  593. $targetCourseId = $course_id;
  594. }
  595. // Database table definitions
  596. $table_survey = Database::get_course_table(TABLE_SURVEY);
  597. $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  598. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  599. $table_survey_options = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  600. $survey_id = intval($survey_id);
  601. // Get groups
  602. $survey_data = self::get_survey($survey_id, 0, null, true);
  603. if (empty($survey_data)) {
  604. return true;
  605. }
  606. if (empty($new_survey_id)) {
  607. $params = $survey_data;
  608. $params['code'] = self::generate_unique_code($params['code']);
  609. $params['c_id'] = $targetCourseId;
  610. unset($params['survey_id']);
  611. $params['session_id'] = api_get_session_id();
  612. $params['title'] = $params['title'].' '.get_lang('Copy');
  613. unset($params['iid']);
  614. Database::insert($table_survey, $params);
  615. $new_survey_id = Database::insert_id();
  616. if ($new_survey_id) {
  617. $sql = "UPDATE $table_survey SET survey_id = $new_survey_id
  618. WHERE iid = $new_survey_id";
  619. Database::query($sql);
  620. // Insert into item_property
  621. api_item_property_update(
  622. api_get_course_info(),
  623. TOOL_SURVEY,
  624. $new_survey_id,
  625. 'SurveyAdded',
  626. api_get_user_id()
  627. );
  628. }
  629. } else {
  630. $new_survey_id = intval($new_survey_id);
  631. }
  632. $sql = "SELECT * FROM $table_survey_question_group
  633. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  634. $res = Database::query($sql);
  635. while ($row = Database::fetch_array($res, 'ASSOC')) {
  636. $params = array(
  637. 'c_id' => $targetCourseId,
  638. 'name' => $row['name'],
  639. 'description' => $row['description'],
  640. 'survey_id' => $new_survey_id
  641. );
  642. $insertId = Database::insert($table_survey_question_group, $params);
  643. $sql = "UPDATE $table_survey_question_group SET id = iid
  644. WHERE iid = $insertId";
  645. Database::query($sql);
  646. $group_id[$row['id']] = $insertId;
  647. }
  648. // Get questions
  649. $sql = "SELECT * FROM $table_survey_question
  650. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  651. $res = Database::query($sql);
  652. while ($row = Database::fetch_array($res, 'ASSOC')) {
  653. $params = array(
  654. 'c_id' => $targetCourseId,
  655. 'survey_id' => $new_survey_id,
  656. 'survey_question' => $row['survey_question'],
  657. 'survey_question_comment' => $row['survey_question_comment'],
  658. 'type' => $row['type'],
  659. 'display' => $row['display'],
  660. 'sort' => $row['sort'],
  661. 'shared_question_id' => $row['shared_question_id'],
  662. 'max_value' => $row['max_value'],
  663. 'survey_group_pri' => $row['survey_group_pri'],
  664. 'survey_group_sec1' => $row['survey_group_sec1'],
  665. 'survey_group_sec2' => $row['survey_group_sec2']
  666. );
  667. $insertId = Database::insert($table_survey_question, $params);
  668. $sql = "UPDATE $table_survey_question SET question_id = iid WHERE iid = $insertId";
  669. Database::query($sql);
  670. $question_id[$row['question_id']] = $insertId;
  671. }
  672. // Get questions options
  673. $sql = "SELECT * FROM $table_survey_options
  674. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  675. $res = Database::query($sql);
  676. while ($row = Database::fetch_array($res, 'ASSOC')) {
  677. $params = array(
  678. 'c_id' => $targetCourseId,
  679. 'question_id' => $question_id[$row['question_id']],
  680. 'survey_id' => $new_survey_id,
  681. 'option_text' => $row['option_text'],
  682. 'sort' => $row['sort'],
  683. 'value' => $row['value']
  684. );
  685. $insertId = Database::insert($table_survey_options, $params);
  686. $sql = "UPDATE $table_survey_options SET question_option_id = $insertId
  687. WHERE iid = $insertId";
  688. Database::query($sql);
  689. }
  690. return $new_survey_id;
  691. }
  692. /**
  693. * This function duplicates a survey (and also all the question in that survey
  694. *
  695. * @param int $survey_id id of the survey that has to be duplicated
  696. * @param int $courseId id of the course which survey has to be duplicated
  697. * @return true
  698. *
  699. * @author Eric Marguin <e.marguin@elixir-interactive.com>, Elixir Interactive
  700. * @version October 2007
  701. */
  702. public static function empty_survey($survey_id, $courseId = null)
  703. {
  704. // Database table definitions
  705. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  706. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  707. $table_survey = Database::get_course_table(TABLE_SURVEY);
  708. $course_id = $courseId ? $courseId : api_get_course_int_id();
  709. $datas = self::get_survey($survey_id);
  710. $session_where = '';
  711. if (api_get_session_id() != 0) {
  712. $session_where = ' AND session_id = "'.api_get_session_id().'" ';
  713. }
  714. $sql = 'DELETE FROM '.$table_survey_invitation.'
  715. WHERE
  716. c_id = '.$course_id.' AND
  717. survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
  718. Database::query($sql);
  719. $sql = 'DELETE FROM '.$table_survey_answer.'
  720. WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
  721. Database::query($sql);
  722. $sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0
  723. WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
  724. Database::query($sql);
  725. return true;
  726. }
  727. /**
  728. * This function recalculates the number of people who have taken the survey (=filled at least one question)
  729. *
  730. * @param int $survey_id the id of the survey somebody
  731. * @return true
  732. *
  733. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  734. * @version February 2007
  735. */
  736. public static function update_survey_answered($survey_data, $user, $survey_code)
  737. {
  738. // Database table definitions
  739. $table_survey = Database::get_course_table(TABLE_SURVEY);
  740. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  741. $survey_id = $survey_data['survey_id'];
  742. $course_id = $survey_data['c_id'];
  743. $session_id = $survey_data['session_id'];
  744. // Getting a list with all the people who have filled the survey
  745. $people_filled = self::get_people_who_filled_survey($survey_id, false, $course_id);
  746. $number = intval(count($people_filled));
  747. // Storing this value in the survey table
  748. $sql = "UPDATE $table_survey
  749. SET answered = $number
  750. WHERE
  751. c_id = $course_id AND
  752. survey_id = ".intval($survey_id);
  753. Database::query($sql);
  754. $allow = api_get_configuration_value('survey_answered_at_field');
  755. // Requires DB change:
  756. // ALTER TABLE c_survey_invitation ADD answered_at DATETIME DEFAULT NULL;
  757. $answeredAt = '';
  758. if ($allow) {
  759. $answeredAt = "answered_at = '".api_get_utc_datetime()."',";
  760. }
  761. // Storing that the user has finished the survey.
  762. $sql = "UPDATE $table_survey_invitation
  763. SET $answeredAt
  764. answered = 1
  765. WHERE
  766. c_id = $course_id AND
  767. session_id = $session_id AND
  768. user ='".Database::escape_string($user)."' AND
  769. survey_code='".Database::escape_string($survey_code)."'";
  770. Database::query($sql);
  771. }
  772. /***
  773. * SURVEY QUESTION FUNCTIONS
  774. */
  775. /**
  776. * This function return the "icon" of the question type
  777. *
  778. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  779. * @version February 2007
  780. */
  781. public static function icon_question($type)
  782. {
  783. // the possible question types
  784. $possible_types = array(
  785. 'personality',
  786. 'yesno',
  787. 'multiplechoice',
  788. 'multipleresponse',
  789. 'open',
  790. 'dropdown',
  791. 'comment',
  792. 'pagebreak',
  793. 'percentage',
  794. 'score',
  795. );
  796. // the images array
  797. $icon_question = array(
  798. 'yesno' => 'yesno.png',
  799. 'personality' => 'yesno.png',
  800. 'multiplechoice' => 'mcua.png',
  801. 'multipleresponse' => 'mcma.png',
  802. 'open' => 'open_answer.png',
  803. 'dropdown' => 'dropdown.png',
  804. 'percentage' => 'percentagequestion.png',
  805. 'score' => 'scorequestion.png',
  806. 'comment' => 'commentquestion.png',
  807. 'pagebreak' => 'page_end.png',
  808. );
  809. if (in_array($type, $possible_types)) {
  810. return $icon_question[$type];
  811. } else {
  812. return false;
  813. }
  814. }
  815. /**
  816. * This function retrieves all the information of a question
  817. *
  818. * @param integer $question_id the id of the question
  819. * @return array
  820. *
  821. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  822. * @version January 2007
  823. *
  824. * @todo one sql call should do the trick
  825. */
  826. public static function get_question($question_id, $shared = false)
  827. {
  828. // Table definitions
  829. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  830. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  831. $course_id = api_get_course_int_id();
  832. $sql = "SELECT * FROM $tbl_survey_question
  833. WHERE c_id = $course_id AND question_id='".intval($question_id)."'
  834. ORDER BY `sort` ";
  835. $sqlOption = " SELECT * FROM $table_survey_question_option
  836. WHERE c_id = $course_id AND question_id='".intval($question_id)."'
  837. ORDER BY `sort` ";
  838. if ($shared) {
  839. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  840. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  841. $sql = "SELECT * FROM $tbl_survey_question
  842. WHERE question_id='".intval($question_id)."'
  843. ORDER BY `sort` ";
  844. $sqlOption = "SELECT * FROM $table_survey_question_option
  845. WHERE question_id='".intval($question_id)."'
  846. ORDER BY `sort` ";
  847. }
  848. // Getting the information of the question
  849. $result = Database::query($sql);
  850. $row = Database::fetch_array($result, 'ASSOC');
  851. $return['survey_id'] = $row['survey_id'];
  852. $return['question_id'] = $row['question_id'];
  853. $return['type'] = $row['type'];
  854. $return['question'] = $row['survey_question'];
  855. $return['horizontalvertical'] = $row['display'];
  856. $return['shared_question_id'] = $row['shared_question_id'];
  857. $return['maximum_score'] = $row['max_value'];
  858. $return['is_required'] = api_get_configuration_value('allow_required_survey_questions')
  859. ? $row['is_required']
  860. : false;
  861. if ($row['survey_group_pri'] != 0) {
  862. $return['assigned'] = $row['survey_group_pri'];
  863. $return['choose'] = 1;
  864. } else {
  865. $return['assigned1'] = $row['survey_group_sec1'];
  866. $return['assigned2'] = $row['survey_group_sec2'];
  867. $return['choose'] = 2;
  868. }
  869. // Getting the information of the question options
  870. $result = Database::query($sqlOption);
  871. while ($row = Database::fetch_array($result, 'ASSOC')) {
  872. /** @todo this should be renamed to options instead of answers */
  873. $return['answers'][] = $row['option_text'];
  874. $return['values'][] = $row['value'];
  875. /** @todo this can be done more elegantly (used in reporting) */
  876. $return['answersid'][] = $row['question_option_id'];
  877. }
  878. return $return;
  879. }
  880. /**
  881. * This function gets all the question of any given survey
  882. *
  883. * @param integer $survey_id the id of the survey
  884. * @return array containing all the questions of the survey
  885. *
  886. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  887. * @version February 2007
  888. *
  889. * @todo one sql call should do the trick
  890. */
  891. public static function get_questions($survey_id, $course_id = '')
  892. {
  893. // Table definitions
  894. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  895. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  896. if (empty($course_id)) {
  897. $course_id = api_get_course_int_id();
  898. }
  899. // Getting the information of the question
  900. $sql = "SELECT * FROM $tbl_survey_question
  901. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
  902. $result = Database::query($sql);
  903. $return = array();
  904. while ($row = Database::fetch_array($result, 'ASSOC')) {
  905. $return[$row['question_id']]['survey_id'] = $row['survey_id'];
  906. $return[$row['question_id']]['question_id'] = $row['question_id'];
  907. $return[$row['question_id']]['type'] = $row['type'];
  908. $return[$row['question_id']]['question'] = $row['survey_question'];
  909. $return[$row['question_id']]['horizontalvertical'] = $row['display'];
  910. $return[$row['question_id']]['maximum_score'] = $row['max_value'];
  911. $return[$row['question_id']]['sort'] = $row['sort'];
  912. }
  913. // Getting the information of the question options
  914. $sql = "SELECT * FROM $table_survey_question_option
  915. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
  916. $result = Database::query($sql);
  917. while ($row = Database::fetch_array($result, 'ASSOC')) {
  918. $return[$row['question_id']]['answers'][] = $row['option_text'];
  919. }
  920. return $return;
  921. }
  922. /**
  923. * This function saves a question in the database.
  924. * This can be either an update of an existing survey or storing a new survey
  925. * @param array $survey_data
  926. * @param array $form_content all the information of the form
  927. *
  928. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  929. * @version January 2007
  930. */
  931. public static function save_question($survey_data, $form_content)
  932. {
  933. $return_message = '';
  934. if (strlen($form_content['question']) > 1) {
  935. // Checks length of the question
  936. $empty_answer = false;
  937. if ($survey_data['survey_type'] == 1) {
  938. if (empty($form_content['choose'])) {
  939. $return_message = 'PleaseChooseACondition';
  940. return $return_message;
  941. }
  942. if (($form_content['choose'] == 2) &&
  943. ($form_content['assigned1'] == $form_content['assigned2'])
  944. ) {
  945. $return_message = 'ChooseDifferentCategories';
  946. return $return_message;
  947. }
  948. }
  949. if ($form_content['type'] != 'percentage') {
  950. if (isset($form_content['answers'])) {
  951. for ($i = 0; $i < count($form_content['answers']); $i++) {
  952. if (strlen($form_content['answers'][$i]) < 1) {
  953. $empty_answer = true;
  954. break;
  955. }
  956. }
  957. }
  958. }
  959. if ($form_content['type'] == 'score') {
  960. if (strlen($form_content['maximum_score']) < 1) {
  961. $empty_answer = true;
  962. }
  963. }
  964. $additional = array();
  965. $course_id = api_get_course_int_id();
  966. if (!$empty_answer) {
  967. // Table definitions
  968. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  969. // Getting all the information of the survey
  970. $survey_data = self::get_survey($form_content['survey_id']);
  971. // Storing the question in the shared database
  972. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  973. $shared_question_id = self::save_shared_question($form_content, $survey_data);
  974. $form_content['shared_question_id'] = $shared_question_id;
  975. }
  976. // Storing a new question
  977. if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
  978. // Finding the max sort order of the questions in the given survey
  979. $sql = "SELECT max(sort) AS max_sort
  980. FROM $tbl_survey_question
  981. WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
  982. $result = Database::query($sql);
  983. $row = Database::fetch_array($result, 'ASSOC');
  984. $max_sort = $row['max_sort'];
  985. // Some variables defined for survey-test type
  986. $extraParams = [];
  987. if (isset($_POST['choose'])) {
  988. if ($_POST['choose'] == 1) {
  989. $extraParams['survey_group_pri'] = $_POST['assigned'];
  990. } elseif ($_POST['choose'] == 2) {
  991. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  992. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  993. }
  994. }
  995. $questionComment = isset($form_content['question_comment'])
  996. ? $form_content['question_comment']
  997. : '';
  998. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : '';
  999. $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : '';
  1000. $params = [
  1001. 'c_id' => $course_id,
  1002. 'survey_id' => $form_content['survey_id'],
  1003. 'survey_question' => $form_content['question'],
  1004. 'survey_question_comment' => $questionComment,
  1005. 'type' => $form_content['type'],
  1006. 'display' => $display,
  1007. 'sort' => $max_sort + 1,
  1008. 'shared_question_id' => $form_content['shared_question_id'],
  1009. 'max_value' => $maxScore,
  1010. ];
  1011. if (api_get_configuration_value('allow_required_survey_questions')) {
  1012. $params['is_required'] = isset($form_content['is_required']);
  1013. }
  1014. $params = array_merge($params, $extraParams);
  1015. $question_id = Database::insert($tbl_survey_question, $params);
  1016. if ($question_id) {
  1017. $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
  1018. WHERE iid = $question_id";
  1019. Database::query($sql);
  1020. $form_content['question_id'] = $question_id;
  1021. $return_message = 'QuestionAdded';
  1022. }
  1023. } else {
  1024. // Updating an existing question
  1025. $extraParams = [];
  1026. if (isset($_POST['choose'])) {
  1027. if ($_POST['choose'] == 1) {
  1028. $extraParams['survey_group_pri'] = $_POST['assigned'];
  1029. $extraParams['survey_group_sec1'] = 0;
  1030. $extraParams['survey_group_sec2'] = 0;
  1031. } elseif ($_POST['choose'] == 2) {
  1032. $extraParams['survey_group_pri'] = 0;
  1033. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  1034. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  1035. }
  1036. }
  1037. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
  1038. $questionComment = isset($form_content['question_comment'])
  1039. ? $form_content['question_comment']
  1040. : null;
  1041. // Adding the question to the survey_question table
  1042. $params = [
  1043. 'survey_question' => $form_content['question'],
  1044. 'survey_question_comment' => $questionComment,
  1045. 'display' => $form_content['horizontalvertical'],
  1046. ];
  1047. if (api_get_configuration_value('allow_required_survey_questions')) {
  1048. $params['is_required'] = isset($form_content['is_required']);
  1049. }
  1050. $params = array_merge($params, $extraParams);
  1051. Database::update(
  1052. $tbl_survey_question,
  1053. $params,
  1054. [
  1055. 'c_id = ? AND question_id = ?' => [
  1056. $course_id,
  1057. $form_content['question_id'],
  1058. ],
  1059. ]
  1060. );
  1061. $return_message = 'QuestionUpdated';
  1062. }
  1063. if (!empty($form_content['survey_id'])) {
  1064. //Updating survey
  1065. api_item_property_update(
  1066. api_get_course_info(),
  1067. TOOL_SURVEY,
  1068. $form_content['survey_id'],
  1069. 'SurveyUpdated',
  1070. api_get_user_id()
  1071. );
  1072. }
  1073. // Storing the options of the question
  1074. self::save_question_options($form_content, $survey_data);
  1075. } else {
  1076. $return_message = 'PleasFillAllAnswer';
  1077. }
  1078. } else {
  1079. $return_message = 'PleaseEnterAQuestion';
  1080. }
  1081. if (!empty($return_message)) {
  1082. Display::addFlash(Display::return_message(get_lang($return_message)));
  1083. }
  1084. return $return_message;
  1085. }
  1086. /**
  1087. * This function saves the question in the shared database
  1088. *
  1089. * @param array $form_content all the information of the form
  1090. * @param array $survey_data all the information of the survey
  1091. *
  1092. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1093. * @version February 2007
  1094. * @return int
  1095. *
  1096. * @todo editing of a shared question
  1097. */
  1098. public function save_shared_question($form_content, $survey_data)
  1099. {
  1100. $_course = api_get_course_info();
  1101. // Table definitions
  1102. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1103. // Storing a new question
  1104. if ($form_content['shared_question_id'] == '' ||
  1105. !is_numeric($form_content['shared_question_id'])
  1106. ) {
  1107. // Finding the max sort order of the questions in the given survey
  1108. $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
  1109. WHERE survey_id='".intval($survey_data['survey_share'])."'
  1110. AND code='".Database::escape_string($_course['id'])."'";
  1111. $result = Database::query($sql);
  1112. $row = Database::fetch_array($result, 'ASSOC');
  1113. $max_sort = $row['max_sort'];
  1114. // Adding the question to the survey_question table
  1115. $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
  1116. '".Database::escape_string($survey_data['survey_share'])."',
  1117. '".Database::escape_string($form_content['question'])."',
  1118. '".Database::escape_string($form_content['question_comment'])."',
  1119. '".Database::escape_string($form_content['type'])."',
  1120. '".Database::escape_string($form_content['horizontalvertical'])."',
  1121. '".Database::escape_string($max_sort + 1)."',
  1122. '".Database::escape_string($_course['id'])."')";
  1123. Database::query($sql);
  1124. $shared_question_id = Database::insert_id();
  1125. } else {
  1126. // Updating an existing question
  1127. // adding the question to the survey_question table
  1128. $sql = "UPDATE $tbl_survey_question SET
  1129. survey_question = '".Database::escape_string($form_content['question'])."',
  1130. survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
  1131. display = '".Database::escape_string($form_content['horizontalvertical'])."'
  1132. WHERE
  1133. question_id = '".intval($form_content['shared_question_id'])."' AND
  1134. code = '".Database::escape_string($_course['id'])."'";
  1135. Database::query($sql);
  1136. $shared_question_id = $form_content['shared_question_id'];
  1137. }
  1138. return $shared_question_id;
  1139. }
  1140. /**
  1141. * This functions moves a question of a survey up or down
  1142. *
  1143. * @param string $direction
  1144. * @param integer $survey_question_id
  1145. * @param integer $survey_id
  1146. *
  1147. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1148. * @version January 2007
  1149. */
  1150. public static function move_survey_question(
  1151. $direction,
  1152. $survey_question_id,
  1153. $survey_id
  1154. ) {
  1155. // Table definition
  1156. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1157. $course_id = api_get_course_int_id();
  1158. if ($direction == 'moveup') {
  1159. $sort = 'DESC';
  1160. }
  1161. if ($direction == 'movedown') {
  1162. $sort = 'ASC';
  1163. }
  1164. // Finding the two questions that needs to be swapped
  1165. $sql = "SELECT * FROM $table_survey_question
  1166. WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
  1167. ORDER BY sort $sort";
  1168. $result = Database::query($sql);
  1169. $found = false;
  1170. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1171. if ($found) {
  1172. $question_id_two = $row['question_id'];
  1173. $question_sort_two = $row['sort'];
  1174. $found = false;
  1175. }
  1176. if ($row['question_id'] == $survey_question_id) {
  1177. $found = true;
  1178. $question_id_one = $row['question_id'];
  1179. $question_sort_one = $row['sort'];
  1180. }
  1181. }
  1182. $sql1 = "UPDATE $table_survey_question
  1183. SET sort = '".Database::escape_string($question_sort_two)."'
  1184. WHERE c_id = $course_id AND question_id='".intval($question_id_one)."'";
  1185. Database::query($sql1);
  1186. $sql2 = "UPDATE $table_survey_question
  1187. SET sort = '".Database::escape_string($question_sort_one)."'
  1188. WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
  1189. Database::query($sql2);
  1190. }
  1191. /**
  1192. * This function deletes all the questions of a given survey
  1193. * This function is normally only called when a survey is deleted
  1194. *
  1195. * @param int $survey_id the id of the survey that has to be deleted
  1196. * @return true
  1197. *
  1198. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1199. * @version January 2007
  1200. */
  1201. public static function delete_all_survey_questions($survey_id, $shared = false)
  1202. {
  1203. $course_id = api_get_course_int_id();
  1204. // Table definitions
  1205. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1206. $course_condition = " c_id = $course_id AND ";
  1207. if ($shared) {
  1208. $course_condition = '';
  1209. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1210. }
  1211. $sql = "DELETE FROM $table_survey_question
  1212. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1213. // Deleting the survey questions
  1214. Database::query($sql);
  1215. // Deleting all the options of the questions of the survey
  1216. self::delete_all_survey_questions_options($survey_id, $shared);
  1217. // Deleting all the answers on this survey
  1218. self::delete_all_survey_answers($survey_id);
  1219. }
  1220. /**
  1221. * This function deletes a survey question and all its options
  1222. *
  1223. * @param int $survey_id the id of the survey
  1224. * @param int $question_id the id of the question
  1225. * @param bool $shared
  1226. *
  1227. * @todo also delete the answers to this question
  1228. *
  1229. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1230. * @version March 2007
  1231. */
  1232. public static function delete_survey_question($survey_id, $question_id, $shared = false)
  1233. {
  1234. $course_id = api_get_course_int_id();
  1235. // Table definitions
  1236. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1237. if ($shared) {
  1238. self::delete_shared_survey_question($survey_id, $question_id);
  1239. }
  1240. // Deleting the survey questions
  1241. $sql = "DELETE FROM $table_survey_question
  1242. WHERE
  1243. c_id = $course_id AND
  1244. survey_id='".intval($survey_id)."' AND
  1245. question_id='".intval($question_id)."'";
  1246. Database::query($sql);
  1247. // Deleting the options of the question of the survey
  1248. self::delete_survey_question_option($survey_id, $question_id, $shared);
  1249. }
  1250. /**
  1251. * This function deletes a shared survey question from the main database and all its options
  1252. *
  1253. * @param int $question_id the id of the question
  1254. *
  1255. * @todo delete all the options of this question
  1256. *
  1257. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1258. * @version March 2007
  1259. */
  1260. public static function delete_shared_survey_question($survey_id, $question_id)
  1261. {
  1262. // Table definitions
  1263. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1264. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1265. // First we have to get the shared_question_id
  1266. $question_data = self::get_question($question_id);
  1267. // Deleting the survey questions
  1268. $sql = "DELETE FROM $table_survey_question
  1269. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1270. Database::query($sql);
  1271. // Deleting the options of the question of the survey question
  1272. $sql = "DELETE FROM $table_survey_question_option
  1273. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1274. Database::query($sql);
  1275. }
  1276. /**
  1277. * This function stores the options of the questions in the table
  1278. *
  1279. * @param array $form_content
  1280. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1281. * @version January 2007
  1282. *
  1283. * @todo writing the update statement when editing a question
  1284. */
  1285. public static function save_question_options($form_content, $survey_data)
  1286. {
  1287. $course_id = api_get_course_int_id();
  1288. // A percentage question type has options 1 -> 100
  1289. if ($form_content['type'] == 'percentage') {
  1290. for ($i = 1; $i < 101; $i++) {
  1291. $form_content['answers'][] = $i;
  1292. }
  1293. }
  1294. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1295. self::save_shared_question_options($form_content, $survey_data);
  1296. }
  1297. // Table definition
  1298. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1299. // We are editing a question so we first have to remove all the existing options from the database
  1300. if (is_numeric($form_content['question_id'])) {
  1301. $sql = "DELETE FROM $table_survey_question_option
  1302. WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
  1303. Database::query($sql);
  1304. }
  1305. $counter = 1;
  1306. if (isset($form_content['answers']) && is_array($form_content['answers'])) {
  1307. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1308. $values = isset($form_content['values']) ? $form_content['values'][$i] : '';
  1309. $params = [
  1310. 'c_id' => $course_id,
  1311. 'question_id' => $form_content['question_id'],
  1312. 'survey_id' => $form_content['survey_id'],
  1313. 'option_text' => $form_content['answers'][$i],
  1314. 'value' => $values,
  1315. 'sort' => $counter,
  1316. ];
  1317. $insertId = Database::insert($table_survey_question_option, $params);
  1318. if ($insertId) {
  1319. $sql = "UPDATE $table_survey_question_option
  1320. SET question_option_id = $insertId
  1321. WHERE iid = $insertId";
  1322. Database::query($sql);
  1323. $counter++;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * This function stores the options of the questions in the shared table
  1330. *
  1331. * @param array $form_content
  1332. *
  1333. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1334. * @version February 2007
  1335. *
  1336. * @todo writing the update statement when editing a question
  1337. */
  1338. public function save_shared_question_options($form_content, $survey_data)
  1339. {
  1340. if (is_array($form_content) && is_array($form_content['answers'])) {
  1341. // Table definition
  1342. $table = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1343. // We are editing a question so we first have to remove all the existing options from the database
  1344. $sql = "DELETE FROM $table
  1345. WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
  1346. Database::query($sql);
  1347. $counter = 1;
  1348. foreach ($form_content['answers'] as & $answer) {
  1349. $params = [
  1350. 'question_id' => $form_content['shared_question_id'],
  1351. 'survey_id' => $survey_data['is_shared'],
  1352. 'option_text' => $answer,
  1353. 'sort' => $counter,
  1354. ];
  1355. Database::insert($table, $params);
  1356. $counter++;
  1357. }
  1358. }
  1359. }
  1360. /**
  1361. * This function deletes all the options of the questions of a given survey
  1362. * This function is normally only called when a survey is deleted
  1363. *
  1364. * @param $survey_id the id of the survey that has to be deleted
  1365. * @return true
  1366. *
  1367. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1368. * @version January 2007
  1369. */
  1370. public static function delete_all_survey_questions_options($survey_id, $shared = false)
  1371. {
  1372. // Table definitions
  1373. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1374. $course_id = api_get_course_int_id();
  1375. $course_condition = " c_id = $course_id AND ";
  1376. if ($shared) {
  1377. $course_condition = '';
  1378. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1379. }
  1380. $sql = "DELETE FROM $table_survey_question_option
  1381. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1382. // Deleting the options of the survey questions
  1383. Database::query($sql);
  1384. return true;
  1385. }
  1386. /**
  1387. * This function deletes the options of a given question
  1388. *
  1389. * @param int $survey_id
  1390. * @param int $question_id
  1391. * @param bool $shared
  1392. *
  1393. * @return bool
  1394. *
  1395. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1396. * @author Julio Montoya
  1397. * @version March 2007
  1398. */
  1399. public static function delete_survey_question_option(
  1400. $survey_id,
  1401. $question_id,
  1402. $shared = false
  1403. ) {
  1404. $course_id = api_get_course_int_id();
  1405. $course_condition = " c_id = $course_id AND ";
  1406. // Table definitions
  1407. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1408. if ($shared) {
  1409. $course_condition = '';
  1410. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1411. }
  1412. // Deleting the options of the survey questions
  1413. $sql = "DELETE from $table_survey_question_option
  1414. WHERE
  1415. $course_condition survey_id='".intval($survey_id)."' AND
  1416. question_id='".intval($question_id)."'";
  1417. Database::query($sql);
  1418. return true;
  1419. }
  1420. /**
  1421. * SURVEY ANSWERS FUNCTIONS
  1422. */
  1423. /**
  1424. * This function deletes all the answers anyone has given on this survey
  1425. * This function is normally only called when a survey is deleted
  1426. *
  1427. * @param $survey_id the id of the survey that has to be deleted
  1428. * @return true
  1429. *
  1430. * @todo write the function
  1431. *
  1432. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1433. * @version January 2007,december 2008
  1434. */
  1435. public static function delete_all_survey_answers($survey_id)
  1436. {
  1437. $course_id = api_get_course_int_id();
  1438. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1439. $survey_id = intval($survey_id);
  1440. $sql = "DELETE FROM $table_survey_answer
  1441. WHERE c_id = $course_id AND survey_id=$survey_id";
  1442. Database::query($sql);
  1443. return true;
  1444. }
  1445. /**
  1446. * @param int $user_id
  1447. * @param int $survey_id
  1448. * @param int $course_id
  1449. * @return bool
  1450. */
  1451. public static function is_user_filled_survey($user_id, $survey_id, $course_id)
  1452. {
  1453. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1454. $user_id = intval($user_id);
  1455. $course_id = intval($course_id);
  1456. $survey_id = intval($survey_id);
  1457. $sql = "SELECT DISTINCT user
  1458. FROM $table_survey_answer
  1459. WHERE
  1460. c_id = $course_id AND
  1461. user = $user_id AND
  1462. survey_id = $survey_id";
  1463. $result = Database::query($sql);
  1464. if (Database::num_rows($result)) {
  1465. return true;
  1466. }
  1467. return false;
  1468. }
  1469. /**
  1470. * This function gets all the persons who have filled the survey
  1471. *
  1472. * @param integer $survey_id
  1473. * @return array
  1474. *
  1475. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1476. * @version February 2007
  1477. */
  1478. public static function get_people_who_filled_survey(
  1479. $survey_id,
  1480. $all_user_info = false,
  1481. $course_id = null
  1482. ) {
  1483. // Database table definition
  1484. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1485. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1486. // Variable initialisation
  1487. $return = array();
  1488. if (empty($course_id)) {
  1489. $course_id = api_get_course_int_id();
  1490. } else {
  1491. $course_id = intval($course_id);
  1492. }
  1493. if ($all_user_info) {
  1494. $order_clause = api_sort_by_first_name()
  1495. ? ' ORDER BY user.firstname, user.lastname'
  1496. : ' ORDER BY user.lastname, user.firstname';
  1497. $sql = "SELECT DISTINCT
  1498. answered_user.user as invited_user,
  1499. user.firstname,
  1500. user.lastname,
  1501. user.user_id
  1502. FROM $table_survey_answer answered_user
  1503. LEFT JOIN $table_user as user ON answered_user.user = user.user_id
  1504. WHERE
  1505. answered_user.c_id = $course_id AND
  1506. survey_id= '".Database::escape_string($survey_id)."' ".
  1507. $order_clause;
  1508. } else {
  1509. $sql = "SELECT DISTINCT user FROM $table_survey_answer
  1510. WHERE c_id = $course_id AND survey_id= '".Database::escape_string($survey_id)."' ";
  1511. }
  1512. $res = Database::query($sql);
  1513. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1514. if ($all_user_info) {
  1515. $userInfo = api_get_user_info($row['user_id']);
  1516. $row['user_info'] = $userInfo;
  1517. $return[] = $row;
  1518. } else {
  1519. $return[] = $row['user'];
  1520. }
  1521. }
  1522. return $return;
  1523. }
  1524. /**
  1525. * @return bool
  1526. */
  1527. public static function survey_generation_hash_available()
  1528. {
  1529. if (extension_loaded('mcrypt')) {
  1530. return true;
  1531. }
  1532. return false;
  1533. }
  1534. /**
  1535. * @param int $survey_id
  1536. * @param int $course_id
  1537. * @param int $session_id
  1538. * @param int $group_id
  1539. * @return string
  1540. */
  1541. public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
  1542. {
  1543. $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
  1544. return $hash;
  1545. }
  1546. /**
  1547. * @param int $survey_id
  1548. * @param int $course_id
  1549. * @param int $session_id
  1550. * @param int $group_id
  1551. * @param string $hash
  1552. *
  1553. * @return bool
  1554. */
  1555. public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
  1556. {
  1557. $survey_generated_hash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
  1558. if ($survey_generated_hash == $hash) {
  1559. return true;
  1560. }
  1561. return false;
  1562. }
  1563. /**
  1564. * @param int $survey_id
  1565. * @param int $course_id
  1566. * @param int $session_id
  1567. * @param int $group_id
  1568. *
  1569. * @return string
  1570. */
  1571. public static function generate_survey_link(
  1572. $survey_id,
  1573. $course_id,
  1574. $session_id,
  1575. $group_id
  1576. ) {
  1577. $code = self::generate_survey_hash(
  1578. $survey_id,
  1579. $course_id,
  1580. $session_id,
  1581. $group_id
  1582. );
  1583. return api_get_path(WEB_CODE_PATH).'survey/link.php?h='.$code.'&i='.$survey_id.'&c='.intval($course_id).'&s='
  1584. .intval($session_id).'&g='.$group_id;
  1585. }
  1586. /**
  1587. * Check if the current user has mandatory surveys no-answered
  1588. * and redirect to fill the first found survey
  1589. */
  1590. public static function protectByMandatory()
  1591. {
  1592. if (strpos($_SERVER['SCRIPT_NAME'], 'fillsurvey.php') !== false) {
  1593. return;
  1594. }
  1595. $userId = api_get_user_id();
  1596. $courseId = api_get_course_int_id();
  1597. $sessionId = api_get_session_id();
  1598. if (!$userId) {
  1599. return;
  1600. }
  1601. if (!$courseId) {
  1602. return;
  1603. }
  1604. try {
  1605. /** @var CSurveyInvitation $invitation */
  1606. $invitation = Database::getManager()
  1607. ->createQuery("
  1608. SELECT i FROM ChamiloCourseBundle:CSurveyInvitation i
  1609. INNER JOIN ChamiloCourseBundle:CSurvey s WITH s.code = i.surveyCode
  1610. INNER JOIN ChamiloCoreBundle:ExtraFieldValues efv WITH efv.itemId = s.iid
  1611. INNER JOIN ChamiloCoreBundle:ExtraField ef WITH efv.field = ef.id
  1612. WHERE i.answered = 0
  1613. AND i.cId = :course
  1614. AND i.user = :user
  1615. AND i.sessionId = :session
  1616. AND :now BETWEEN s.availFrom AND s.availTill
  1617. AND ef.variable = :variable
  1618. AND efv.value = 1
  1619. ORDER BY s.availTill ASC
  1620. ")
  1621. ->setMaxResults(1)
  1622. ->setParameters([
  1623. 'course' => $courseId,
  1624. 'user' => $userId,
  1625. 'session' => $sessionId,
  1626. 'now' => new DateTime('UTC', new DateTimeZone('UTC')),
  1627. 'variable' => 'is_mandatory'
  1628. ])
  1629. ->getSingleResult();
  1630. } catch (Exception $e) {
  1631. $invitation = null;
  1632. }
  1633. if (!$invitation) {
  1634. return;
  1635. }
  1636. $urlParams = http_build_query([
  1637. 'course' => api_get_course_id(),
  1638. 'invitationcode' => $invitation->getInvitationCode()
  1639. ]);
  1640. Display::addFlash(
  1641. Display::return_message(get_lang('MandatorySurveyNoAnswered'), 'warning')
  1642. );
  1643. header('Location: '.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?'.$urlParams.'&'.api_get_cidreq());
  1644. exit;
  1645. }
  1646. }