survey.lib.php 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CSurveyInvitation;
  4. /**
  5. * Class SurveyManager.
  6. *
  7. * @package chamilo.survey
  8. *
  9. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University:
  10. * cleanup, refactoring and rewriting large parts (if not all) of the code
  11. * @author Julio Montoya <gugli100@gmail.com>, Personality Test modification
  12. * and rewriting large parts of the code
  13. * @author cfasanando
  14. *
  15. * @todo move this file to inc/lib
  16. * @todo use consistent naming for the functions (save vs store for instance)
  17. */
  18. class SurveyManager
  19. {
  20. /**
  21. * @param $code
  22. *
  23. * @return string
  24. */
  25. public static function generate_unique_code($code)
  26. {
  27. if (empty($code)) {
  28. return false;
  29. }
  30. $course_id = api_get_course_int_id();
  31. $table = Database::get_course_table(TABLE_SURVEY);
  32. $code = Database::escape_string($code);
  33. $num = 0;
  34. $new_code = $code;
  35. while (true) {
  36. $sql = "SELECT * FROM $table
  37. WHERE code = '$new_code' AND c_id = $course_id";
  38. $result = Database::query($sql);
  39. if (Database::num_rows($result)) {
  40. $num++;
  41. $new_code = $code.$num;
  42. } else {
  43. break;
  44. }
  45. }
  46. return $code.$num;
  47. }
  48. /**
  49. * Deletes all survey invitations of a user.
  50. *
  51. * @param int $user_id
  52. *
  53. * @return bool
  54. * @assert ('') === false
  55. */
  56. public static function delete_all_survey_invitations_by_user($user_id)
  57. {
  58. $user_id = (int) $user_id;
  59. if (empty($user_id)) {
  60. return false;
  61. }
  62. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  63. $table_survey = Database::get_course_table(TABLE_SURVEY);
  64. $sql = "SELECT survey_invitation_id, survey_code
  65. FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
  66. $result = Database::query($sql);
  67. while ($row = Database::fetch_array($result, 'ASSOC')) {
  68. $survey_invitation_id = $row['survey_invitation_id'];
  69. $survey_code = $row['survey_code'];
  70. $sql2 = "DELETE FROM $table_survey_invitation
  71. WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
  72. if (Database::query($sql2)) {
  73. $sql3 = "UPDATE $table_survey SET
  74. invited = invited-1
  75. WHERE c_id <> 0 AND code ='$survey_code'";
  76. Database::query($sql3);
  77. }
  78. }
  79. }
  80. /**
  81. * @param string $course_code
  82. * @param int $session_id
  83. *
  84. * @return array
  85. * @assert ('') === false
  86. */
  87. public static function get_surveys($course_code, $session_id = 0)
  88. {
  89. if (empty($course_code)) {
  90. return false;
  91. }
  92. $course_info = api_get_course_info($course_code);
  93. if (empty($course_info)) {
  94. return false;
  95. }
  96. $sessionCondition = api_get_session_condition($session_id, true, true);
  97. $table = Database::get_course_table(TABLE_SURVEY);
  98. $sql = "SELECT * FROM $table
  99. WHERE c_id = {$course_info['real_id']} $sessionCondition ";
  100. $result = Database::query($sql);
  101. $result = Database::store_result($result, 'ASSOC');
  102. return $result;
  103. }
  104. /**
  105. * Retrieves all the survey information.
  106. *
  107. * @param int $survey_id the id of the survey
  108. * @param bool $shared this parameter determines if
  109. * we have to get the information of a survey from the central (shared) database or from the
  110. * course database
  111. * @param string course code optional
  112. *
  113. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  114. *
  115. * @version February 2007
  116. * @assert ('') === false
  117. *
  118. * @return array
  119. *
  120. * @todo this is the same function as in create_new_survey.php
  121. */
  122. public static function get_survey(
  123. $survey_id,
  124. $shared = 0,
  125. $course_code = '',
  126. $simple_return = false
  127. ) {
  128. $my_course_id = api_get_course_id();
  129. // Table definition
  130. if (!empty($course_code)) {
  131. $my_course_id = $course_code;
  132. } elseif (isset($_GET['course'])) {
  133. $my_course_id = Security::remove_XSS($_GET['course']);
  134. }
  135. $courseInfo = api_get_course_info($my_course_id);
  136. $survey_id = (int) $survey_id;
  137. $table_survey = Database::get_course_table(TABLE_SURVEY);
  138. if ($shared != 0) {
  139. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  140. $sql = "SELECT * FROM $table_survey
  141. WHERE survey_id='".$survey_id."' ";
  142. } else {
  143. if (empty($courseInfo)) {
  144. return [];
  145. }
  146. $sql = "SELECT * FROM $table_survey
  147. WHERE
  148. survey_id='".$survey_id."' AND
  149. c_id = ".$courseInfo['real_id'];
  150. }
  151. $result = Database::query($sql);
  152. $return = [];
  153. if (Database::num_rows($result) > 0) {
  154. $return = Database::fetch_array($result, 'ASSOC');
  155. if ($simple_return) {
  156. return $return;
  157. }
  158. // We do this (temporarily) to have the array match the quickform elements immediately
  159. // idealiter the fields in the db match the quickform fields
  160. $return['survey_code'] = $return['code'];
  161. $return['survey_title'] = $return['title'];
  162. $return['survey_subtitle'] = $return['subtitle'];
  163. $return['survey_language'] = $return['lang'];
  164. $return['start_date'] = $return['avail_from'];
  165. $return['end_date'] = $return['avail_till'];
  166. $return['survey_share'] = $return['is_shared'];
  167. $return['survey_introduction'] = $return['intro'];
  168. $return['survey_thanks'] = $return['surveythanks'];
  169. $return['survey_type'] = $return['survey_type'];
  170. $return['one_question_per_page'] = $return['one_question_per_page'];
  171. $return['show_form_profile'] = $return['show_form_profile'];
  172. $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
  173. $return['shuffle'] = $return['shuffle'];
  174. $return['parent_id'] = $return['parent_id'];
  175. $return['survey_version'] = $return['survey_version'];
  176. $return['anonymous'] = $return['anonymous'];
  177. $return['c_id'] = isset($return['c_id']) ? $return['c_id'] : 0;
  178. $return['session_id'] = isset($return['session_id']) ? $return['session_id'] : 0;
  179. }
  180. return $return;
  181. }
  182. /**
  183. * @param string $code
  184. *
  185. * @return string
  186. */
  187. public static function generateSurveyCode($code)
  188. {
  189. return strtolower(CourseManager::generate_course_code($code));
  190. }
  191. /**
  192. * This function stores a survey in the database.
  193. *
  194. * @param array $values
  195. *
  196. * @return array $return the type of return message that has to be displayed and the message in it
  197. *
  198. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  199. *
  200. * @version February 2007
  201. */
  202. public static function store_survey($values)
  203. {
  204. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  205. $_user = api_get_user_info();
  206. $course_id = api_get_course_int_id();
  207. $session_id = api_get_session_id();
  208. $courseCode = api_get_course_id();
  209. $table_survey = Database::get_course_table(TABLE_SURVEY);
  210. $shared_survey_id = 0;
  211. if (!isset($values['survey_id'])) {
  212. // Check if the code doesn't soon exists in this language
  213. $sql = 'SELECT 1 FROM '.$table_survey.'
  214. WHERE
  215. c_id = '.$course_id.' AND
  216. code = "'.Database::escape_string($values['survey_code']).'" AND
  217. lang = "'.Database::escape_string($values['survey_language']).'"';
  218. $rs = Database::query($sql);
  219. if (Database::num_rows($rs) > 0) {
  220. Display::addFlash(
  221. Display::return_message(
  222. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  223. 'error'
  224. )
  225. );
  226. $return['type'] = 'error';
  227. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  228. return $return;
  229. }
  230. if (!isset($values['anonymous'])) {
  231. $values['anonymous'] = 0;
  232. }
  233. $values['anonymous'] = (int) $values['anonymous'];
  234. $extraParams = [];
  235. if ($values['anonymous'] == 0) {
  236. // Input_name_list
  237. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
  238. $extraParams['show_form_profile'] = $values['show_form_profile'];
  239. if ($values['show_form_profile'] == 1) {
  240. // Input_name_list
  241. $fields = explode(',', $values['input_name_list']);
  242. $field_values = '';
  243. foreach ($fields as &$field) {
  244. if ($field != '') {
  245. if ($values[$field] == '') {
  246. $values[$field] = 0;
  247. }
  248. $field_values .= $field.':'.$values[$field].'@';
  249. }
  250. }
  251. $extraParams['form_fields'] = $field_values;
  252. } else {
  253. $extraParams['form_fields'] = '';
  254. }
  255. } else {
  256. // Input_name_list
  257. $extraParams['show_form_profile'] = 0;
  258. $extraParams['form_fields'] = '';
  259. }
  260. $extraParams['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : 0;
  261. $extraParams['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : 0;
  262. if ($values['survey_type'] == 1) {
  263. $extraParams['survey_type'] = 1;
  264. $extraParams['parent_id'] = $values['parent_id'];
  265. // Logic for versioning surveys
  266. if (!empty($values['parent_id'])) {
  267. $versionValue = '';
  268. $sql = 'SELECT survey_version
  269. FROM '.$table_survey.'
  270. WHERE
  271. c_id = '.$course_id.' AND
  272. parent_id = '.intval($values['parent_id']).'
  273. ORDER BY survey_version DESC
  274. LIMIT 1';
  275. $rs = Database::query($sql);
  276. if (Database::num_rows($rs) === 0) {
  277. $sql = 'SELECT survey_version FROM '.$table_survey.'
  278. WHERE
  279. c_id = '.$course_id.' AND
  280. survey_id = '.intval($values['parent_id']);
  281. $rs = Database::query($sql);
  282. $getversion = Database::fetch_array($rs, 'ASSOC');
  283. if (empty($getversion['survey_version'])) {
  284. $versionValue = ++$getversion['survey_version'];
  285. } else {
  286. $versionValue = $getversion['survey_version'];
  287. }
  288. } else {
  289. $row = Database::fetch_array($rs, 'ASSOC');
  290. $pos = api_strpos($row['survey_version']);
  291. if ($pos === false) {
  292. $row['survey_version'] = $row['survey_version'] + 1;
  293. $versionValue = $row['survey_version'];
  294. } else {
  295. $getlast = explode('\.', $row['survey_version']);
  296. $lastversion = array_pop($getlast);
  297. $lastversion = $lastversion + 1;
  298. $add = implode('.', $getlast);
  299. if ($add != '') {
  300. $insertnewversion = $add.'.'.$lastversion;
  301. } else {
  302. $insertnewversion = $lastversion;
  303. }
  304. $versionValue = $insertnewversion;
  305. }
  306. }
  307. $extraParams['survey_version'] = $versionValue;
  308. }
  309. }
  310. $params = [
  311. 'c_id' => $course_id,
  312. 'code' => self::generateSurveyCode($values['survey_code']),
  313. 'title' => $values['survey_title'],
  314. 'subtitle' => $values['survey_subtitle'],
  315. 'author' => $_user['user_id'],
  316. 'lang' => $values['survey_language'],
  317. 'is_shared' => $shared_survey_id,
  318. 'template' => 'template',
  319. 'intro' => $values['survey_introduction'],
  320. 'surveythanks' => $values['survey_thanks'],
  321. 'creation_date' => api_get_utc_datetime(),
  322. 'anonymous' => $values['anonymous'],
  323. 'session_id' => api_get_session_id(),
  324. 'visible_results' => $values['visible_results'],
  325. ];
  326. if (!empty($values['start_date'])) {
  327. if ($allowSurveyAvailabilityDatetime) {
  328. $params['avail_from'] = api_get_utc_datetime($values['start_date'].':00');
  329. } else {
  330. $params['avail_from'] = $values['start_date'];
  331. }
  332. }
  333. if (!empty($values['end_date'])) {
  334. if ($allowSurveyAvailabilityDatetime) {
  335. $params['avail_till'] = api_get_utc_datetime($values['end_date'].':00');
  336. } else {
  337. $params['avail_till'] = $values['end_date'];
  338. }
  339. }
  340. if (isset($values['survey_type']) && !empty($values['survey_type'])) {
  341. $params['survey_type'] = $values['survey_type'];
  342. }
  343. $params = array_merge($params, $extraParams);
  344. $survey_id = Database::insert($table_survey, $params);
  345. if ($survey_id > 0) {
  346. $sql = "UPDATE $table_survey SET survey_id = $survey_id
  347. WHERE iid = $survey_id";
  348. Database::query($sql);
  349. // Insert into item_property
  350. api_item_property_update(
  351. api_get_course_info(),
  352. TOOL_SURVEY,
  353. $survey_id,
  354. 'SurveyAdded',
  355. api_get_user_id()
  356. );
  357. }
  358. if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
  359. self::copy_survey($values['parent_id'], $survey_id);
  360. }
  361. Display::addFlash(
  362. Display::return_message(
  363. get_lang('SurveyCreatedSuccesfully'),
  364. 'success'
  365. )
  366. );
  367. $return['id'] = $survey_id;
  368. } else {
  369. // Check whether the code doesn't soon exists in this language
  370. $sql = 'SELECT 1 FROM '.$table_survey.'
  371. WHERE
  372. c_id = '.$course_id.' AND
  373. code = "'.Database::escape_string($values['survey_code']).'" AND
  374. lang = "'.Database::escape_string($values['survey_language']).'" AND
  375. survey_id !='.intval($values['survey_id']);
  376. $rs = Database::query($sql);
  377. if (Database::num_rows($rs) > 0) {
  378. Display::addFlash(
  379. Display::return_message(
  380. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  381. 'error'
  382. )
  383. );
  384. $return['type'] = 'error';
  385. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  386. return $return;
  387. }
  388. if (!isset($values['anonymous'])
  389. || (isset($values['anonymous']) && $values['anonymous'] == '')
  390. ) {
  391. $values['anonymous'] = 0;
  392. }
  393. $extraParams = [];
  394. $extraParams['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : 0;
  395. $extraParams['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : 0;
  396. if ($values['anonymous'] == 0) {
  397. $extraParams['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
  398. if ($extraParams['show_form_profile'] == 1) {
  399. $fields = explode(',', $values['input_name_list']);
  400. $field_values = '';
  401. foreach ($fields as &$field) {
  402. if ($field != '') {
  403. if (!isset($values[$field]) ||
  404. (isset($values[$field]) && $values[$field] == '')
  405. ) {
  406. $values[$field] = 0;
  407. }
  408. $field_values .= $field.':'.$values[$field].'@';
  409. }
  410. }
  411. $extraParams['form_fields'] = $field_values;
  412. } else {
  413. $extraParams['form_fields'] = '';
  414. }
  415. } else {
  416. $extraParams['show_form_profile'] = 0;
  417. $extraParams['form_fields'] = '';
  418. }
  419. $params = [
  420. 'title' => $values['survey_title'],
  421. 'subtitle' => $values['survey_subtitle'],
  422. 'author' => $_user['user_id'],
  423. 'lang' => $values['survey_language'],
  424. 'avail_from' => $allowSurveyAvailabilityDatetime
  425. ? api_get_utc_datetime($values['start_date'].':00')
  426. : $values['start_date'],
  427. 'avail_till' => $allowSurveyAvailabilityDatetime
  428. ? api_get_utc_datetime($values['end_date'].':59')
  429. : $values['end_date'],
  430. 'is_shared' => $shared_survey_id,
  431. 'template' => 'template',
  432. 'intro' => $values['survey_introduction'],
  433. 'surveythanks' => $values['survey_thanks'],
  434. 'anonymous' => $values['anonymous'],
  435. 'session_id' => api_get_session_id(),
  436. 'visible_results' => $values['visible_results'],
  437. ];
  438. $params = array_merge($params, $extraParams);
  439. Database::update(
  440. $table_survey,
  441. $params,
  442. [
  443. 'c_id = ? AND survey_id = ?' => [
  444. $course_id,
  445. $values['survey_id'],
  446. ],
  447. ]
  448. );
  449. // Update into item_property (update)
  450. api_item_property_update(
  451. api_get_course_info(),
  452. TOOL_SURVEY,
  453. $values['survey_id'],
  454. 'SurveyUpdated',
  455. api_get_user_id()
  456. );
  457. Display::addFlash(
  458. Display::return_message(
  459. get_lang('SurveyUpdatedSuccesfully'),
  460. 'confirmation'
  461. )
  462. );
  463. $return['id'] = $values['survey_id'];
  464. }
  465. $survey_id = (int) $return['id'];
  466. // Gradebook
  467. $gradebook_option = false;
  468. if (isset($values['survey_qualify_gradebook'])) {
  469. $gradebook_option = $values['survey_qualify_gradebook'] > 0;
  470. }
  471. $gradebook_link_type = 8;
  472. $link_info = GradebookUtils::isResourceInCourseGradebook(
  473. $courseCode,
  474. $gradebook_link_type,
  475. $survey_id,
  476. $session_id
  477. );
  478. $gradebook_link_id = isset($link_info['id']) ? $link_info['id'] : false;
  479. if ($gradebook_option) {
  480. if ($survey_id > 0) {
  481. $title_gradebook = ''; // Not needed here.
  482. $description_gradebook = ''; // Not needed here.
  483. $survey_weight = floatval($_POST['survey_weight']);
  484. $max_score = 1;
  485. if (!$gradebook_link_id) {
  486. GradebookUtils::add_resource_to_course_gradebook(
  487. $values['category_id'],
  488. $courseCode,
  489. $gradebook_link_type,
  490. $survey_id,
  491. $title_gradebook,
  492. $survey_weight,
  493. $max_score,
  494. $description_gradebook,
  495. 1,
  496. $session_id
  497. );
  498. } else {
  499. GradebookUtils::updateResourceFromCourseGradebook(
  500. $gradebook_link_id,
  501. $courseCode,
  502. $survey_weight
  503. );
  504. }
  505. }
  506. } else {
  507. // Delete everything of the gradebook for this $linkId
  508. GradebookUtils::remove_resource_from_course_gradebook($gradebook_link_id);
  509. }
  510. return $return;
  511. }
  512. /**
  513. * This function stores a shared survey in the central database.
  514. *
  515. * @param array $values
  516. *
  517. * @return array $return the type of return message that has to be displayed and the message in it
  518. *
  519. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  520. *
  521. * @version February 2007
  522. */
  523. public function store_shared_survey($values)
  524. {
  525. $_user = api_get_user_info();
  526. $_course = api_get_course_info();
  527. // Table definitions
  528. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  529. if (!$values['survey_id'] ||
  530. !is_numeric($values['survey_id']) ||
  531. $values['survey_share']['survey_share'] == 'true'
  532. ) {
  533. $sql = "INSERT INTO $table_survey (code, title, subtitle, author, lang, template, intro, surveythanks, creation_date, course_code) VALUES (
  534. '".Database::escape_string($values['survey_code'])."',
  535. '".Database::escape_string($values['survey_title'])."',
  536. '".Database::escape_string($values['survey_subtitle'])."',
  537. '".intval($_user['user_id'])."',
  538. '".Database::escape_string($values['survey_language'])."',
  539. '".Database::escape_string('template')."',
  540. '".Database::escape_string($values['survey_introduction'])."',
  541. '".Database::escape_string($values['survey_thanks'])."',
  542. '".api_get_utc_datetime()."',
  543. '".$_course['id']."')";
  544. Database::query($sql);
  545. $return = Database::insert_id();
  546. $sql = "UPDATE $table_survey SET survey_id = $return WHERE iid = $return";
  547. Database::query($sql);
  548. } else {
  549. $sql = "UPDATE $table_survey SET
  550. code = '".Database::escape_string($values['survey_code'])."',
  551. title = '".Database::escape_string($values['survey_title'])."',
  552. subtitle = '".Database::escape_string($values['survey_subtitle'])."',
  553. author = '".intval($_user['user_id'])."',
  554. lang = '".Database::escape_string($values['survey_language'])."',
  555. template = '".Database::escape_string('template')."',
  556. intro = '".Database::escape_string($values['survey_introduction'])."',
  557. surveythanks = '".Database::escape_string($values['survey_thanks'])."'
  558. WHERE survey_id = '".Database::escape_string($values['survey_share']['survey_share'])."'";
  559. Database::query($sql);
  560. $return = $values['survey_share']['survey_share'];
  561. }
  562. return $return;
  563. }
  564. /**
  565. * This function deletes a survey (and also all the question in that survey.
  566. *
  567. * @param int $survey_id id of the survey that has to be deleted
  568. * @param bool $shared
  569. * @param int $course_id
  570. *
  571. * @return true
  572. *
  573. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  574. *
  575. * @version January 2007
  576. */
  577. public static function delete_survey($survey_id, $shared = false, $course_id = 0)
  578. {
  579. // Database table definitions
  580. if (empty($course_id)) {
  581. $course_id = api_get_course_int_id();
  582. }
  583. $survey_id = (int) $survey_id;
  584. if (empty($survey_id)) {
  585. return false;
  586. }
  587. $course_info = api_get_course_info_by_id($course_id);
  588. $course_id = $course_info['real_id'];
  589. $table_survey = Database::get_course_table(TABLE_SURVEY);
  590. $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  591. if ($shared) {
  592. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY);
  593. // Deleting the survey
  594. $sql = "DELETE FROM $table_survey
  595. WHERE survey_id='".$survey_id."'";
  596. Database::query($sql);
  597. } else {
  598. $sql = "DELETE FROM $table_survey
  599. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  600. Database::query($sql);
  601. }
  602. // Deleting groups of this survey
  603. $sql = "DELETE FROM $table_survey_question_group
  604. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  605. Database::query($sql);
  606. // Deleting the questions of the survey
  607. self::delete_all_survey_questions($survey_id, $shared);
  608. // Update into item_property (delete)
  609. api_item_property_update(
  610. $course_info,
  611. TOOL_SURVEY,
  612. $survey_id,
  613. 'SurveyDeleted',
  614. api_get_user_id()
  615. );
  616. Skill::deleteSkillsFromItem($survey_id, ITEM_TYPE_SURVEY);
  617. return true;
  618. }
  619. /**
  620. * @param int $survey_id
  621. * @param int $new_survey_id
  622. * @param int $targetCourseId
  623. *
  624. * @return bool
  625. */
  626. public static function copy_survey(
  627. $survey_id,
  628. $new_survey_id = null,
  629. $targetCourseId = null
  630. ) {
  631. $course_id = api_get_course_int_id();
  632. if (!$targetCourseId) {
  633. $targetCourseId = $course_id;
  634. }
  635. // Database table definitions
  636. $table_survey = Database::get_course_table(TABLE_SURVEY);
  637. $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  638. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  639. $table_survey_options = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  640. $survey_id = (int) $survey_id;
  641. // Get groups
  642. $survey_data = self::get_survey($survey_id, 0, null, true);
  643. if (empty($survey_data)) {
  644. return true;
  645. }
  646. if (empty($new_survey_id)) {
  647. $params = $survey_data;
  648. $params['code'] = self::generate_unique_code($params['code']);
  649. $params['c_id'] = $targetCourseId;
  650. unset($params['survey_id']);
  651. $params['session_id'] = api_get_session_id();
  652. $params['title'] = $params['title'].' '.get_lang('Copy');
  653. unset($params['iid']);
  654. $new_survey_id = Database::insert($table_survey, $params);
  655. if ($new_survey_id) {
  656. $sql = "UPDATE $table_survey SET survey_id = $new_survey_id
  657. WHERE iid = $new_survey_id";
  658. Database::query($sql);
  659. // Insert into item_property
  660. api_item_property_update(
  661. api_get_course_info(),
  662. TOOL_SURVEY,
  663. $new_survey_id,
  664. 'SurveyAdded',
  665. api_get_user_id()
  666. );
  667. }
  668. } else {
  669. $new_survey_id = (int) $new_survey_id;
  670. }
  671. $sql = "SELECT * FROM $table_survey_question_group
  672. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  673. $res = Database::query($sql);
  674. while ($row = Database::fetch_array($res, 'ASSOC')) {
  675. $params = [
  676. 'c_id' => $targetCourseId,
  677. 'name' => $row['name'],
  678. 'description' => $row['description'],
  679. 'survey_id' => $new_survey_id,
  680. ];
  681. $insertId = Database::insert($table_survey_question_group, $params);
  682. $sql = "UPDATE $table_survey_question_group SET id = iid
  683. WHERE iid = $insertId";
  684. Database::query($sql);
  685. $group_id[$row['id']] = $insertId;
  686. }
  687. // Get questions
  688. $sql = "SELECT * FROM $table_survey_question
  689. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  690. $res = Database::query($sql);
  691. while ($row = Database::fetch_array($res, 'ASSOC')) {
  692. $params = [
  693. 'c_id' => $targetCourseId,
  694. 'survey_id' => $new_survey_id,
  695. 'survey_question' => $row['survey_question'],
  696. 'survey_question_comment' => $row['survey_question_comment'],
  697. 'type' => $row['type'],
  698. 'display' => $row['display'],
  699. 'sort' => $row['sort'],
  700. 'shared_question_id' => $row['shared_question_id'],
  701. 'max_value' => $row['max_value'],
  702. 'survey_group_pri' => $row['survey_group_pri'],
  703. 'survey_group_sec1' => $row['survey_group_sec1'],
  704. 'survey_group_sec2' => $row['survey_group_sec2'],
  705. ];
  706. if (api_get_configuration_value('allow_required_survey_questions')) {
  707. if (isset($row['is_required'])) {
  708. $params['is_required'] = $row['is_required'];
  709. }
  710. }
  711. $insertId = Database::insert($table_survey_question, $params);
  712. if ($insertId) {
  713. $sql = "UPDATE $table_survey_question SET question_id = iid WHERE iid = $insertId";
  714. Database::query($sql);
  715. $question_id[$row['question_id']] = $insertId;
  716. }
  717. }
  718. // Get questions options
  719. $sql = "SELECT * FROM $table_survey_options
  720. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  721. $res = Database::query($sql);
  722. while ($row = Database::fetch_array($res, 'ASSOC')) {
  723. $params = [
  724. 'c_id' => $targetCourseId,
  725. 'question_id' => $question_id[$row['question_id']],
  726. 'survey_id' => $new_survey_id,
  727. 'option_text' => $row['option_text'],
  728. 'sort' => $row['sort'],
  729. 'value' => $row['value'],
  730. ];
  731. $insertId = Database::insert($table_survey_options, $params);
  732. if ($insertId) {
  733. $sql = "UPDATE $table_survey_options SET question_option_id = $insertId
  734. WHERE iid = $insertId";
  735. Database::query($sql);
  736. }
  737. }
  738. return $new_survey_id;
  739. }
  740. /**
  741. * This function duplicates a survey (and also all the question in that survey.
  742. *
  743. * @param int $surveyId id of the survey that has to be duplicated
  744. * @param int $courseId id of the course which survey has to be duplicated
  745. *
  746. * @return true
  747. *
  748. * @author Eric Marguin <e.marguin@elixir-interactive.com>, Elixir Interactive
  749. *
  750. * @version October 2007
  751. */
  752. public static function empty_survey($surveyId, $courseId = 0)
  753. {
  754. // Database table definitions
  755. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  756. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  757. $table_survey = Database::get_course_table(TABLE_SURVEY);
  758. $courseId = (int) $courseId;
  759. $courseId = empty($courseId) ? api_get_course_int_id() : $courseId;
  760. $surveyId = (int) $surveyId;
  761. $datas = self::get_survey($surveyId);
  762. $session_where = '';
  763. if (api_get_session_id() != 0) {
  764. $session_where = ' AND session_id = "'.api_get_session_id().'" ';
  765. }
  766. $sql = 'DELETE FROM '.$table_survey_invitation.'
  767. WHERE
  768. c_id = '.$courseId.' AND
  769. survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
  770. Database::query($sql);
  771. $sql = 'DELETE FROM '.$table_survey_answer.'
  772. WHERE c_id = '.$courseId.' AND survey_id='.$surveyId;
  773. Database::query($sql);
  774. $sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0
  775. WHERE c_id = '.$courseId.' AND survey_id='.$surveyId;
  776. Database::query($sql);
  777. return true;
  778. }
  779. /**
  780. * This function recalculates the number of people who have taken the survey (=filled at least one question).
  781. *
  782. * @param array $survey_data
  783. * @param array $user
  784. * @param string $survey_code
  785. *
  786. * @return bool
  787. *
  788. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  789. *
  790. * @version February 2007
  791. */
  792. public static function update_survey_answered($survey_data, $user, $survey_code)
  793. {
  794. if (empty($survey_data)) {
  795. return false;
  796. }
  797. // Database table definitions
  798. $table_survey = Database::get_course_table(TABLE_SURVEY);
  799. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  800. $survey_id = (int) $survey_data['survey_id'];
  801. $course_id = (int) $survey_data['c_id'];
  802. $session_id = $survey_data['session_id'];
  803. // Getting a list with all the people who have filled the survey
  804. /*$people_filled = self::get_people_who_filled_survey($survey_id, false, $course_id);
  805. $number = count($people_filled);*/
  806. // Storing this value in the survey table
  807. $sql = "UPDATE $table_survey
  808. SET answered = answered + 1
  809. WHERE
  810. c_id = $course_id AND
  811. survey_id = ".$survey_id;
  812. Database::query($sql);
  813. $allow = api_get_configuration_value('survey_answered_at_field');
  814. // Requires DB change:
  815. // ALTER TABLE c_survey_invitation ADD answered_at DATETIME DEFAULT NULL;
  816. $answeredAt = '';
  817. if ($allow) {
  818. $answeredAt = "answered_at = '".api_get_utc_datetime()."',";
  819. }
  820. // Storing that the user has finished the survey.
  821. $sql = "UPDATE $table_survey_invitation
  822. SET $answeredAt answered = 1
  823. WHERE
  824. c_id = $course_id AND
  825. session_id = $session_id AND
  826. user ='".Database::escape_string($user)."' AND
  827. survey_code='".Database::escape_string($survey_code)."'";
  828. Database::query($sql);
  829. }
  830. /**
  831. * This function return the "icon" of the question type.
  832. *
  833. * @param string $type
  834. *
  835. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  836. *
  837. * @version February 2007
  838. */
  839. public static function icon_question($type)
  840. {
  841. // the possible question types
  842. $possible_types = [
  843. 'personality',
  844. 'yesno',
  845. 'multiplechoice',
  846. 'multipleresponse',
  847. 'open',
  848. 'dropdown',
  849. 'comment',
  850. 'pagebreak',
  851. 'percentage',
  852. 'score',
  853. ];
  854. // the images array
  855. $icon_question = [
  856. 'yesno' => 'yesno.png',
  857. 'personality' => 'yesno.png',
  858. 'multiplechoice' => 'mcua.png',
  859. 'multipleresponse' => 'mcma.png',
  860. 'open' => 'open_answer.png',
  861. 'dropdown' => 'dropdown.png',
  862. 'percentage' => 'percentagequestion.png',
  863. 'score' => 'scorequestion.png',
  864. 'comment' => 'commentquestion.png',
  865. 'pagebreak' => 'page_end.png',
  866. ];
  867. if (in_array($type, $possible_types)) {
  868. return $icon_question[$type];
  869. } else {
  870. return false;
  871. }
  872. }
  873. /**
  874. * This function retrieves all the information of a question.
  875. *
  876. * @param int $question_id the id of the question
  877. * @param bool $shared
  878. *
  879. * @return array
  880. *
  881. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  882. *
  883. * @version January 2007
  884. *
  885. * @todo one sql call should do the trick
  886. */
  887. public static function get_question($question_id, $shared = false)
  888. {
  889. // Table definitions
  890. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  891. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  892. $course_id = api_get_course_int_id();
  893. $question_id = (int) $question_id;
  894. $sql = "SELECT * FROM $tbl_survey_question
  895. WHERE c_id = $course_id AND question_id='".$question_id."'
  896. ORDER BY `sort` ";
  897. $sqlOption = " SELECT * FROM $table_survey_question_option
  898. WHERE c_id = $course_id AND question_id='".$question_id."'
  899. ORDER BY `sort` ";
  900. if ($shared) {
  901. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  902. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  903. $sql = "SELECT * FROM $tbl_survey_question
  904. WHERE question_id='".$question_id."'
  905. ORDER BY `sort` ";
  906. $sqlOption = "SELECT * FROM $table_survey_question_option
  907. WHERE question_id='".$question_id."'
  908. ORDER BY `sort` ";
  909. }
  910. // Getting the information of the question
  911. $result = Database::query($sql);
  912. $row = Database::fetch_array($result, 'ASSOC');
  913. $return['survey_id'] = $row['survey_id'];
  914. $return['question_id'] = $row['question_id'];
  915. $return['type'] = $row['type'];
  916. $return['question'] = $row['survey_question'];
  917. $return['horizontalvertical'] = $row['display'];
  918. $return['shared_question_id'] = $row['shared_question_id'];
  919. $return['maximum_score'] = $row['max_value'];
  920. $return['is_required'] = api_get_configuration_value('allow_required_survey_questions')
  921. ? $row['is_required']
  922. : false;
  923. if ($row['survey_group_pri'] != 0) {
  924. $return['assigned'] = $row['survey_group_pri'];
  925. $return['choose'] = 1;
  926. } else {
  927. $return['assigned1'] = $row['survey_group_sec1'];
  928. $return['assigned2'] = $row['survey_group_sec2'];
  929. $return['choose'] = 2;
  930. }
  931. // Getting the information of the question options
  932. $result = Database::query($sqlOption);
  933. while ($row = Database::fetch_array($result, 'ASSOC')) {
  934. /** @todo this should be renamed to options instead of answers */
  935. $return['answers'][] = $row['option_text'];
  936. $return['values'][] = $row['value'];
  937. /** @todo this can be done more elegantly (used in reporting) */
  938. $return['answersid'][] = $row['question_option_id'];
  939. }
  940. return $return;
  941. }
  942. /**
  943. * This function gets all the question of any given survey.
  944. *
  945. * @param int $surveyId the id of the survey
  946. * @param int $courseId
  947. *
  948. * @return array containing all the questions of the survey
  949. *
  950. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  951. *
  952. * @version February 2007
  953. *
  954. * @todo one sql call should do the trick
  955. */
  956. public static function get_questions($surveyId, $courseId = 0)
  957. {
  958. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  959. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  960. $courseId = (int) $courseId;
  961. $surveyId = (int) $surveyId;
  962. if (empty($courseId)) {
  963. $courseId = api_get_course_int_id();
  964. }
  965. // Getting the information of the question
  966. $sql = "SELECT * FROM $tbl_survey_question
  967. WHERE c_id = $courseId AND survey_id='".$surveyId."'";
  968. $result = Database::query($sql);
  969. $return = [];
  970. while ($row = Database::fetch_array($result, 'ASSOC')) {
  971. $return[$row['question_id']]['survey_id'] = $row['survey_id'];
  972. $return[$row['question_id']]['question_id'] = $row['question_id'];
  973. $return[$row['question_id']]['type'] = $row['type'];
  974. $return[$row['question_id']]['question'] = $row['survey_question'];
  975. $return[$row['question_id']]['horizontalvertical'] = $row['display'];
  976. $return[$row['question_id']]['maximum_score'] = $row['max_value'];
  977. $return[$row['question_id']]['sort'] = $row['sort'];
  978. $return[$row['question_id']]['survey_question_comment'] = $row['survey_question_comment'];
  979. }
  980. // Getting the information of the question options
  981. $sql = "SELECT * FROM $table_survey_question_option
  982. WHERE c_id = $courseId AND survey_id='".$surveyId."'";
  983. $result = Database::query($sql);
  984. while ($row = Database::fetch_array($result, 'ASSOC')) {
  985. $return[$row['question_id']]['answers'][] = $row['option_text'];
  986. }
  987. return $return;
  988. }
  989. /**
  990. * This function saves a question in the database.
  991. * This can be either an update of an existing survey or storing a new survey.
  992. *
  993. * @param array $survey_data
  994. * @param array $form_content all the information of the form
  995. *
  996. * @return string
  997. *
  998. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  999. *
  1000. * @version January 2007
  1001. */
  1002. public static function save_question($survey_data, $form_content)
  1003. {
  1004. $return_message = '';
  1005. if (strlen($form_content['question']) > 1) {
  1006. // Checks length of the question
  1007. $empty_answer = false;
  1008. if ($survey_data['survey_type'] == 1) {
  1009. if (empty($form_content['choose'])) {
  1010. $return_message = 'PleaseChooseACondition';
  1011. return $return_message;
  1012. }
  1013. if (($form_content['choose'] == 2) &&
  1014. ($form_content['assigned1'] == $form_content['assigned2'])
  1015. ) {
  1016. $return_message = 'ChooseDifferentCategories';
  1017. return $return_message;
  1018. }
  1019. }
  1020. if ($form_content['type'] != 'percentage') {
  1021. if (isset($form_content['answers'])) {
  1022. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1023. if (strlen($form_content['answers'][$i]) < 1) {
  1024. $empty_answer = true;
  1025. break;
  1026. }
  1027. }
  1028. }
  1029. }
  1030. if ($form_content['type'] == 'score') {
  1031. if (strlen($form_content['maximum_score']) < 1) {
  1032. $empty_answer = true;
  1033. }
  1034. }
  1035. $course_id = api_get_course_int_id();
  1036. if (!$empty_answer) {
  1037. // Table definitions
  1038. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1039. // Getting all the information of the survey
  1040. $survey_data = self::get_survey($form_content['survey_id']);
  1041. // Storing the question in the shared database
  1042. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1043. $shared_question_id = self::save_shared_question($form_content, $survey_data);
  1044. $form_content['shared_question_id'] = $shared_question_id;
  1045. }
  1046. // Storing a new question
  1047. if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
  1048. // Finding the max sort order of the questions in the given survey
  1049. $sql = "SELECT max(sort) AS max_sort
  1050. FROM $tbl_survey_question
  1051. WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
  1052. $result = Database::query($sql);
  1053. $row = Database::fetch_array($result, 'ASSOC');
  1054. $max_sort = $row['max_sort'];
  1055. // Some variables defined for survey-test type
  1056. $extraParams = [];
  1057. if (isset($_POST['choose'])) {
  1058. if ($_POST['choose'] == 1) {
  1059. $extraParams['survey_group_pri'] = $_POST['assigned'];
  1060. } elseif ($_POST['choose'] == 2) {
  1061. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  1062. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  1063. }
  1064. }
  1065. $questionComment = isset($form_content['question_comment'])
  1066. ? $form_content['question_comment']
  1067. : '';
  1068. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : '';
  1069. $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : '';
  1070. $params = [
  1071. 'c_id' => $course_id,
  1072. 'survey_id' => $form_content['survey_id'],
  1073. 'survey_question' => $form_content['question'],
  1074. 'survey_question_comment' => $questionComment,
  1075. 'type' => $form_content['type'],
  1076. 'display' => $display,
  1077. 'sort' => $max_sort + 1,
  1078. 'shared_question_id' => $form_content['shared_question_id'],
  1079. 'max_value' => $maxScore,
  1080. ];
  1081. if (api_get_configuration_value('allow_required_survey_questions')) {
  1082. $params['is_required'] = isset($form_content['is_required']);
  1083. }
  1084. $params = array_merge($params, $extraParams);
  1085. $question_id = Database::insert($tbl_survey_question, $params);
  1086. if ($question_id) {
  1087. $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
  1088. WHERE iid = $question_id";
  1089. Database::query($sql);
  1090. $form_content['question_id'] = $question_id;
  1091. $return_message = 'QuestionAdded';
  1092. }
  1093. } else {
  1094. // Updating an existing question
  1095. $extraParams = [];
  1096. if (isset($_POST['choose'])) {
  1097. if ($_POST['choose'] == 1) {
  1098. $extraParams['survey_group_pri'] = $_POST['assigned'];
  1099. $extraParams['survey_group_sec1'] = 0;
  1100. $extraParams['survey_group_sec2'] = 0;
  1101. } elseif ($_POST['choose'] == 2) {
  1102. $extraParams['survey_group_pri'] = 0;
  1103. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  1104. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  1105. }
  1106. }
  1107. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
  1108. $questionComment = isset($form_content['question_comment'])
  1109. ? $form_content['question_comment']
  1110. : null;
  1111. // Adding the question to the survey_question table
  1112. $params = [
  1113. 'survey_question' => $form_content['question'],
  1114. 'survey_question_comment' => $questionComment,
  1115. 'display' => $form_content['horizontalvertical'],
  1116. ];
  1117. if (api_get_configuration_value('allow_required_survey_questions')) {
  1118. $params['is_required'] = isset($form_content['is_required']);
  1119. }
  1120. $params = array_merge($params, $extraParams);
  1121. Database::update(
  1122. $tbl_survey_question,
  1123. $params,
  1124. [
  1125. 'c_id = ? AND question_id = ?' => [
  1126. $course_id,
  1127. $form_content['question_id'],
  1128. ],
  1129. ]
  1130. );
  1131. $return_message = 'QuestionUpdated';
  1132. }
  1133. if (!empty($form_content['survey_id'])) {
  1134. //Updating survey
  1135. api_item_property_update(
  1136. api_get_course_info(),
  1137. TOOL_SURVEY,
  1138. $form_content['survey_id'],
  1139. 'SurveyUpdated',
  1140. api_get_user_id()
  1141. );
  1142. }
  1143. // Storing the options of the question
  1144. self::save_question_options($form_content, $survey_data);
  1145. } else {
  1146. $return_message = 'PleasFillAllAnswer';
  1147. }
  1148. } else {
  1149. $return_message = 'PleaseEnterAQuestion';
  1150. }
  1151. if (!empty($return_message)) {
  1152. Display::addFlash(Display::return_message(get_lang($return_message)));
  1153. }
  1154. return $return_message;
  1155. }
  1156. /**
  1157. * This function saves the question in the shared database.
  1158. *
  1159. * @param array $form_content all the information of the form
  1160. * @param array $survey_data all the information of the survey
  1161. *
  1162. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1163. *
  1164. * @version February 2007
  1165. *
  1166. * @return int
  1167. *
  1168. * @todo editing of a shared question
  1169. */
  1170. public function save_shared_question($form_content, $survey_data)
  1171. {
  1172. $_course = api_get_course_info();
  1173. // Table definitions
  1174. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1175. // Storing a new question
  1176. if ($form_content['shared_question_id'] == '' ||
  1177. !is_numeric($form_content['shared_question_id'])
  1178. ) {
  1179. // Finding the max sort order of the questions in the given survey
  1180. $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
  1181. WHERE survey_id='".intval($survey_data['survey_share'])."'
  1182. AND code='".Database::escape_string($_course['id'])."'";
  1183. $result = Database::query($sql);
  1184. $row = Database::fetch_array($result, 'ASSOC');
  1185. $max_sort = $row['max_sort'];
  1186. // Adding the question to the survey_question table
  1187. $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
  1188. '".Database::escape_string($survey_data['survey_share'])."',
  1189. '".Database::escape_string($form_content['question'])."',
  1190. '".Database::escape_string($form_content['question_comment'])."',
  1191. '".Database::escape_string($form_content['type'])."',
  1192. '".Database::escape_string($form_content['horizontalvertical'])."',
  1193. '".Database::escape_string($max_sort + 1)."',
  1194. '".Database::escape_string($_course['id'])."')";
  1195. Database::query($sql);
  1196. $shared_question_id = Database::insert_id();
  1197. } else {
  1198. // Updating an existing question
  1199. // adding the question to the survey_question table
  1200. $sql = "UPDATE $tbl_survey_question SET
  1201. survey_question = '".Database::escape_string($form_content['question'])."',
  1202. survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
  1203. display = '".Database::escape_string($form_content['horizontalvertical'])."'
  1204. WHERE
  1205. question_id = '".intval($form_content['shared_question_id'])."' AND
  1206. code = '".Database::escape_string($_course['id'])."'";
  1207. Database::query($sql);
  1208. $shared_question_id = $form_content['shared_question_id'];
  1209. }
  1210. return $shared_question_id;
  1211. }
  1212. /**
  1213. * This functions moves a question of a survey up or down.
  1214. *
  1215. * @param string $direction
  1216. * @param int $survey_question_id
  1217. * @param int $survey_id
  1218. *
  1219. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1220. *
  1221. * @version January 2007
  1222. */
  1223. public static function move_survey_question(
  1224. $direction,
  1225. $survey_question_id,
  1226. $survey_id
  1227. ) {
  1228. // Table definition
  1229. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1230. $course_id = api_get_course_int_id();
  1231. if ($direction == 'moveup') {
  1232. $sort = 'DESC';
  1233. }
  1234. if ($direction == 'movedown') {
  1235. $sort = 'ASC';
  1236. }
  1237. $survey_id = (int) $survey_id;
  1238. // Finding the two questions that needs to be swapped
  1239. $sql = "SELECT * FROM $table_survey_question
  1240. WHERE c_id = $course_id AND survey_id='".$survey_id."'
  1241. ORDER BY sort $sort";
  1242. $result = Database::query($sql);
  1243. $found = false;
  1244. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1245. if ($found) {
  1246. $question_id_two = $row['question_id'];
  1247. $question_sort_two = $row['sort'];
  1248. $found = false;
  1249. }
  1250. if ($row['question_id'] == $survey_question_id) {
  1251. $found = true;
  1252. $question_id_one = $row['question_id'];
  1253. $question_sort_one = $row['sort'];
  1254. }
  1255. }
  1256. $sql = "UPDATE $table_survey_question
  1257. SET sort = '".Database::escape_string($question_sort_two)."'
  1258. WHERE c_id = $course_id AND question_id='".intval($question_id_one)."'";
  1259. Database::query($sql);
  1260. $sql = "UPDATE $table_survey_question
  1261. SET sort = '".Database::escape_string($question_sort_one)."'
  1262. WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
  1263. Database::query($sql);
  1264. }
  1265. /**
  1266. * This function deletes all the questions of a given survey
  1267. * This function is normally only called when a survey is deleted.
  1268. *
  1269. * @param int $survey_id the id of the survey that has to be deleted
  1270. *
  1271. * @return bool
  1272. *
  1273. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1274. *
  1275. * @version January 2007
  1276. */
  1277. public static function delete_all_survey_questions($survey_id, $shared = false)
  1278. {
  1279. $course_id = api_get_course_int_id();
  1280. $survey_id = (int) $survey_id;
  1281. // Table definitions
  1282. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1283. $course_condition = " c_id = $course_id AND ";
  1284. if ($shared) {
  1285. $course_condition = '';
  1286. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1287. }
  1288. $sql = "DELETE FROM $table_survey_question
  1289. WHERE $course_condition survey_id = '".$survey_id."'";
  1290. // Deleting the survey questions
  1291. Database::query($sql);
  1292. // Deleting all the options of the questions of the survey
  1293. self::delete_all_survey_questions_options($survey_id, $shared);
  1294. // Deleting all the answers on this survey
  1295. self::delete_all_survey_answers($survey_id);
  1296. return true;
  1297. }
  1298. /**
  1299. * This function deletes a survey question and all its options.
  1300. *
  1301. * @param int $survey_id the id of the survey
  1302. * @param int $question_id the id of the question
  1303. * @param bool $shared
  1304. *
  1305. * @todo also delete the answers to this question
  1306. *
  1307. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1308. *
  1309. * @version March 2007
  1310. */
  1311. public static function delete_survey_question($survey_id, $question_id, $shared = false)
  1312. {
  1313. $survey_id = (int) $survey_id;
  1314. $question_id = (int) $question_id;
  1315. $course_id = api_get_course_int_id();
  1316. if ($shared) {
  1317. self::delete_shared_survey_question($survey_id, $question_id);
  1318. }
  1319. // Table definitions
  1320. $table = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1321. // Deleting the survey questions
  1322. $sql = "DELETE FROM $table
  1323. WHERE
  1324. c_id = $course_id AND
  1325. survey_id='".$survey_id."' AND
  1326. question_id='".$question_id."'";
  1327. Database::query($sql);
  1328. // Deleting the options of the question of the survey
  1329. self::delete_survey_question_option($survey_id, $question_id, $shared);
  1330. }
  1331. /**
  1332. * This function deletes a shared survey question from the main database and all its options.
  1333. *
  1334. * @param int $question_id the id of the question
  1335. *
  1336. * @todo delete all the options of this question
  1337. *
  1338. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1339. *
  1340. * @version March 2007
  1341. */
  1342. public static function delete_shared_survey_question($survey_id, $question_id)
  1343. {
  1344. // Table definitions
  1345. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1346. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1347. // First we have to get the shared_question_id
  1348. $question_data = self::get_question($question_id);
  1349. // Deleting the survey questions
  1350. $sql = "DELETE FROM $table_survey_question
  1351. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1352. Database::query($sql);
  1353. // Deleting the options of the question of the survey question
  1354. $sql = "DELETE FROM $table_survey_question_option
  1355. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1356. Database::query($sql);
  1357. }
  1358. /**
  1359. * This function stores the options of the questions in the table.
  1360. *
  1361. * @param array $form_content
  1362. *
  1363. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1364. *
  1365. * @version January 2007
  1366. *
  1367. * @todo writing the update statement when editing a question
  1368. */
  1369. public static function save_question_options($form_content, $survey_data)
  1370. {
  1371. $course_id = api_get_course_int_id();
  1372. // A percentage question type has options 1 -> 100
  1373. if ($form_content['type'] == 'percentage') {
  1374. for ($i = 1; $i < 101; $i++) {
  1375. $form_content['answers'][] = $i;
  1376. }
  1377. }
  1378. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1379. self::save_shared_question_options($form_content, $survey_data);
  1380. }
  1381. // Table definition
  1382. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1383. // We are editing a question so we first have to remove all the existing options from the database
  1384. if (is_numeric($form_content['question_id'])) {
  1385. $sql = "DELETE FROM $table_survey_question_option
  1386. WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
  1387. Database::query($sql);
  1388. }
  1389. $counter = 1;
  1390. if (isset($form_content['answers']) && is_array($form_content['answers'])) {
  1391. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1392. $values = isset($form_content['values']) ? $form_content['values'][$i] : '';
  1393. $params = [
  1394. 'c_id' => $course_id,
  1395. 'question_id' => $form_content['question_id'],
  1396. 'survey_id' => $form_content['survey_id'],
  1397. 'option_text' => $form_content['answers'][$i],
  1398. 'value' => $values,
  1399. 'sort' => $counter,
  1400. ];
  1401. $insertId = Database::insert($table_survey_question_option, $params);
  1402. if ($insertId) {
  1403. $sql = "UPDATE $table_survey_question_option
  1404. SET question_option_id = $insertId
  1405. WHERE iid = $insertId";
  1406. Database::query($sql);
  1407. $counter++;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. /**
  1413. * This function stores the options of the questions in the shared table.
  1414. *
  1415. * @param array $form_content
  1416. *
  1417. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1418. *
  1419. * @version February 2007
  1420. *
  1421. * @todo writing the update statement when editing a question
  1422. */
  1423. public function save_shared_question_options($form_content, $survey_data)
  1424. {
  1425. if (is_array($form_content) && is_array($form_content['answers'])) {
  1426. // Table definition
  1427. $table = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1428. // We are editing a question so we first have to remove all the existing options from the database
  1429. $sql = "DELETE FROM $table
  1430. WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
  1431. Database::query($sql);
  1432. $counter = 1;
  1433. foreach ($form_content['answers'] as &$answer) {
  1434. $params = [
  1435. 'question_id' => $form_content['shared_question_id'],
  1436. 'survey_id' => $survey_data['is_shared'],
  1437. 'option_text' => $answer,
  1438. 'sort' => $counter,
  1439. ];
  1440. Database::insert($table, $params);
  1441. $counter++;
  1442. }
  1443. }
  1444. }
  1445. /**
  1446. * This function deletes all the options of the questions of a given survey
  1447. * This function is normally only called when a survey is deleted.
  1448. *
  1449. * @param int $survey_id the id of the survey that has to be deleted
  1450. *
  1451. * @return true
  1452. *
  1453. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1454. *
  1455. * @version January 2007
  1456. */
  1457. public static function delete_all_survey_questions_options($survey_id, $shared = false)
  1458. {
  1459. // Table definitions
  1460. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1461. $course_id = api_get_course_int_id();
  1462. $course_condition = " c_id = $course_id AND ";
  1463. if ($shared) {
  1464. $course_condition = '';
  1465. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1466. }
  1467. $sql = "DELETE FROM $table_survey_question_option
  1468. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1469. // Deleting the options of the survey questions
  1470. Database::query($sql);
  1471. return true;
  1472. }
  1473. /**
  1474. * This function deletes the options of a given question.
  1475. *
  1476. * @param int $survey_id
  1477. * @param int $question_id
  1478. * @param bool $shared
  1479. *
  1480. * @return bool
  1481. *
  1482. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1483. * @author Julio Montoya
  1484. *
  1485. * @version March 2007
  1486. */
  1487. public static function delete_survey_question_option(
  1488. $survey_id,
  1489. $question_id,
  1490. $shared = false
  1491. ) {
  1492. $course_id = api_get_course_int_id();
  1493. $course_condition = " c_id = $course_id AND ";
  1494. // Table definitions
  1495. $table = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1496. if ($shared) {
  1497. $course_condition = '';
  1498. $table = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1499. }
  1500. // Deleting the options of the survey questions
  1501. $sql = "DELETE FROM $table
  1502. WHERE
  1503. $course_condition survey_id='".intval($survey_id)."' AND
  1504. question_id='".intval($question_id)."'";
  1505. Database::query($sql);
  1506. return true;
  1507. }
  1508. /**
  1509. * SURVEY ANSWERS FUNCTIONS.
  1510. */
  1511. /**
  1512. * This function deletes all the answers anyone has given on this survey
  1513. * This function is normally only called when a survey is deleted.
  1514. *
  1515. * @param $survey_id the id of the survey that has to be deleted
  1516. *
  1517. * @return true
  1518. *
  1519. * @todo write the function
  1520. *
  1521. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1522. *
  1523. * @version January 2007,december 2008
  1524. */
  1525. public static function delete_all_survey_answers($survey_id)
  1526. {
  1527. $course_id = api_get_course_int_id();
  1528. $table = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1529. $survey_id = (int) $survey_id;
  1530. $sql = "DELETE FROM $table
  1531. WHERE c_id = $course_id AND survey_id = $survey_id";
  1532. Database::query($sql);
  1533. return true;
  1534. }
  1535. /**
  1536. * @param int $user_id
  1537. * @param int $survey_id
  1538. * @param int $course_id
  1539. *
  1540. * @return bool
  1541. */
  1542. public static function is_user_filled_survey($user_id, $survey_id, $course_id)
  1543. {
  1544. $table = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1545. $user_id = (int) $user_id;
  1546. $course_id = (int) $course_id;
  1547. $survey_id = (int) $survey_id;
  1548. $sql = "SELECT DISTINCT user
  1549. FROM $table
  1550. WHERE
  1551. c_id = $course_id AND
  1552. user = $user_id AND
  1553. survey_id = $survey_id";
  1554. $result = Database::query($sql);
  1555. if (Database::num_rows($result)) {
  1556. return true;
  1557. }
  1558. return false;
  1559. }
  1560. /**
  1561. * This function gets all the persons who have filled the survey.
  1562. *
  1563. * @param int $survey_id
  1564. *
  1565. * @return array
  1566. *
  1567. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1568. *
  1569. * @version February 2007
  1570. */
  1571. public static function get_people_who_filled_survey(
  1572. $survey_id,
  1573. $all_user_info = false,
  1574. $course_id = null
  1575. ) {
  1576. // Database table definition
  1577. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1578. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1579. // Variable initialisation
  1580. $return = [];
  1581. if (empty($course_id)) {
  1582. $course_id = api_get_course_int_id();
  1583. } else {
  1584. $course_id = (int) $course_id;
  1585. }
  1586. $survey_id = (int) $survey_id;
  1587. if ($all_user_info) {
  1588. $order_clause = api_sort_by_first_name()
  1589. ? ' ORDER BY user.firstname, user.lastname'
  1590. : ' ORDER BY user.lastname, user.firstname';
  1591. $sql = "SELECT DISTINCT
  1592. answered_user.user as invited_user,
  1593. user.firstname,
  1594. user.lastname,
  1595. user.user_id
  1596. FROM $table_survey_answer answered_user
  1597. LEFT JOIN $table_user as user ON answered_user.user = user.user_id
  1598. WHERE
  1599. answered_user.c_id = $course_id AND
  1600. survey_id= '".$survey_id."' ".
  1601. $order_clause;
  1602. } else {
  1603. $sql = "SELECT DISTINCT user FROM $table_survey_answer
  1604. WHERE c_id = $course_id AND survey_id= '".$survey_id."' ";
  1605. if (api_get_configuration_value('survey_anonymous_show_answered')) {
  1606. $tblInvitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  1607. $tblSurvey = Database::get_course_table(TABLE_SURVEY);
  1608. $sql = "SELECT i.user FROM $tblInvitation i
  1609. INNER JOIN $tblSurvey s
  1610. ON i.survey_code = s.code
  1611. AND i.c_id = s.c_id
  1612. AND i.session_id = s.session_id
  1613. WHERE i.answered IS TRUE AND s.iid = $survey_id";
  1614. }
  1615. }
  1616. $res = Database::query($sql);
  1617. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1618. if ($all_user_info) {
  1619. $userInfo = api_get_user_info($row['user_id']);
  1620. $row['user_info'] = $userInfo;
  1621. $return[] = $row;
  1622. } else {
  1623. $return[] = $row['user'];
  1624. }
  1625. }
  1626. return $return;
  1627. }
  1628. /**
  1629. * @return bool
  1630. */
  1631. public static function survey_generation_hash_available()
  1632. {
  1633. if (extension_loaded('mcrypt')) {
  1634. return true;
  1635. }
  1636. return false;
  1637. }
  1638. /**
  1639. * @param int $survey_id
  1640. * @param int $course_id
  1641. * @param int $session_id
  1642. * @param int $group_id
  1643. *
  1644. * @return string
  1645. */
  1646. public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
  1647. {
  1648. $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
  1649. return $hash;
  1650. }
  1651. /**
  1652. * @param int $survey_id
  1653. * @param int $course_id
  1654. * @param int $session_id
  1655. * @param int $group_id
  1656. * @param string $hash
  1657. *
  1658. * @return bool
  1659. */
  1660. public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
  1661. {
  1662. $generatedHash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
  1663. if ($generatedHash == $hash) {
  1664. return true;
  1665. }
  1666. return false;
  1667. }
  1668. /**
  1669. * @param int $survey_id
  1670. * @param int $course_id
  1671. * @param int $session_id
  1672. * @param int $group_id
  1673. *
  1674. * @return string
  1675. */
  1676. public static function generate_survey_link(
  1677. $survey_id,
  1678. $course_id,
  1679. $session_id,
  1680. $group_id
  1681. ) {
  1682. $code = self::generate_survey_hash(
  1683. $survey_id,
  1684. $course_id,
  1685. $session_id,
  1686. $group_id
  1687. );
  1688. return api_get_path(WEB_CODE_PATH).'survey/link.php?h='.$code.'&i='.$survey_id.'&c='.intval($course_id).'&s='
  1689. .intval($session_id).'&g='.$group_id;
  1690. }
  1691. /**
  1692. * Check if the current user has mandatory surveys no-answered
  1693. * and redirect to fill the first found survey.
  1694. */
  1695. public static function protectByMandatory()
  1696. {
  1697. if (strpos($_SERVER['SCRIPT_NAME'], 'fillsurvey.php') !== false) {
  1698. return;
  1699. }
  1700. $userId = api_get_user_id();
  1701. $courseId = api_get_course_int_id();
  1702. $sessionId = api_get_session_id();
  1703. if (!$userId) {
  1704. return;
  1705. }
  1706. if (!$courseId) {
  1707. return;
  1708. }
  1709. try {
  1710. /** @var CSurveyInvitation $invitation */
  1711. $invitation = Database::getManager()
  1712. ->createQuery("
  1713. SELECT i FROM ChamiloCourseBundle:CSurveyInvitation i
  1714. INNER JOIN ChamiloCourseBundle:CSurvey s
  1715. WITH (s.code = i.surveyCode AND s.cId = i.cId AND s.sessionId = i.sessionId)
  1716. INNER JOIN ChamiloCoreBundle:ExtraFieldValues efv WITH efv.itemId = s.iid
  1717. INNER JOIN ChamiloCoreBundle:ExtraField ef WITH efv.field = ef.id
  1718. WHERE
  1719. i.answered = 0 AND
  1720. i.cId = :course AND
  1721. i.user = :user AND
  1722. i.sessionId = :session AND
  1723. :now BETWEEN s.availFrom AND s.availTill AND
  1724. ef.variable = :variable AND
  1725. efv.value = 1 AND
  1726. s.surveyType != 3
  1727. ORDER BY s.availTill ASC
  1728. ")
  1729. ->setMaxResults(1)
  1730. ->setParameters([
  1731. 'course' => $courseId,
  1732. 'user' => $userId,
  1733. 'session' => $sessionId,
  1734. 'now' => new DateTime('UTC', new DateTimeZone('UTC')),
  1735. 'variable' => 'is_mandatory',
  1736. ])
  1737. ->getSingleResult();
  1738. } catch (Exception $e) {
  1739. $invitation = null;
  1740. }
  1741. if (!$invitation) {
  1742. return;
  1743. }
  1744. Display::addFlash(
  1745. Display::return_message(get_lang('MandatorySurveyNoAnswered'), 'warning')
  1746. );
  1747. $url = SurveyUtil::generateFillSurveyLink(
  1748. $invitation->getInvitationCode(),
  1749. api_get_course_info(),
  1750. api_get_session_id()
  1751. );
  1752. header('Location: '.$url);
  1753. exit;
  1754. }
  1755. /**
  1756. * This function empty surveys (invitations and answers).
  1757. *
  1758. * @param int $surveyId id of the survey to empty
  1759. *
  1760. * @return bool
  1761. */
  1762. public static function emptySurveyFromId($surveyId)
  1763. {
  1764. // Database table definitions
  1765. $surveyInvitationTable = Database:: get_course_table(TABLE_SURVEY_INVITATION);
  1766. $surveyAnswerTable = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  1767. $surveyTable = Database:: get_course_table(TABLE_SURVEY);
  1768. $surveyId = (int) $surveyId;
  1769. $surveyData = self::get_survey($surveyId);
  1770. if (empty($surveyData)) {
  1771. return false;
  1772. }
  1773. $surveyCode = $surveyData['survey_code'];
  1774. $courseId = (int) $surveyData['c_id'];
  1775. $sessionId = (int) $surveyData['session_id'];
  1776. $sql = "DELETE FROM $surveyInvitationTable
  1777. WHERE session_id = $sessionId AND c_id = $courseId AND survey_code = '$surveyCode' ";
  1778. Database::query($sql);
  1779. $sql = "DELETE FROM $surveyAnswerTable
  1780. WHERE survey_id = $surveyId AND c_id = $courseId ";
  1781. Database::query($sql);
  1782. $sql = "UPDATE $surveyTable
  1783. SET invited = 0, answered = 0
  1784. WHERE survey_id = $surveyId AND c_id = $courseId AND session_id = $sessionId ";
  1785. Database::query($sql);
  1786. return true;
  1787. }
  1788. /**
  1789. * This function copy survey specifying course id and session id where will be copied.
  1790. *
  1791. * @param int $surveyId
  1792. * @param int $targetCourseId target course id
  1793. * @param int $targetSessionId target session id
  1794. *
  1795. * @return bool|int when fails or return the new survey id
  1796. */
  1797. public static function copySurveySession($surveyId, $targetCourseId, $targetSessionId)
  1798. {
  1799. // Database table definitions
  1800. $surveyTable = Database::get_course_table(TABLE_SURVEY);
  1801. $surveyQuestionGroupTable = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  1802. $surveyQuestionTable = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1803. $surveyOptionsTable = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1804. $surveyId = (int) $surveyId;
  1805. $targetCourseId = (int) $targetCourseId;
  1806. $targetSessionId = (int) $targetSessionId;
  1807. $surveyData = self::get_survey($surveyId, 0, '', true);
  1808. if (empty($surveyData) || empty($targetCourseId)) {
  1809. return false;
  1810. }
  1811. $originalCourseId = $surveyData['c_id'];
  1812. $originalSessionId = $surveyData['session_id'];
  1813. $surveyData['code'] = self::generate_unique_code($surveyData['code']);
  1814. $surveyData['c_id'] = $targetCourseId;
  1815. $surveyData['session_id'] = $targetSessionId;
  1816. // Add a "Copy" suffix if copied inside the same course
  1817. if ($targetCourseId == $originalCourseId) {
  1818. $surveyData['title'] = $surveyData['title'].' '.get_lang('Copy');
  1819. }
  1820. unset($surveyData['iid']);
  1821. unset($surveyData['id']);
  1822. $newSurveyId = Database::insert($surveyTable, $surveyData);
  1823. if ($newSurveyId) {
  1824. $sql = "UPDATE $surveyTable SET survey_id = $newSurveyId
  1825. WHERE iid = $newSurveyId";
  1826. Database::query($sql);
  1827. $sql = "SELECT * FROM $surveyQuestionGroupTable
  1828. WHERE survey_id = $surveyId AND c_id = $originalCourseId ";
  1829. $res = Database::query($sql);
  1830. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1831. $params = [
  1832. 'c_id' => $targetCourseId,
  1833. 'name' => $row['name'],
  1834. 'description' => $row['description'],
  1835. 'survey_id' => $newSurveyId,
  1836. ];
  1837. $insertId = Database::insert($surveyQuestionGroupTable, $params);
  1838. if ($insertId) {
  1839. $sql = "UPDATE $surveyQuestionGroupTable SET id = iid WHERE iid = $insertId";
  1840. Database::query($sql);
  1841. $group_id[$row['id']] = $insertId;
  1842. }
  1843. }
  1844. // Get questions
  1845. $sql = "SELECT * FROM $surveyQuestionTable
  1846. WHERE survey_id = $surveyId AND c_id = $originalCourseId";
  1847. $res = Database::query($sql);
  1848. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1849. $params = [
  1850. 'c_id' => $targetCourseId,
  1851. 'survey_id' => $newSurveyId,
  1852. 'survey_question' => $row['survey_question'],
  1853. 'survey_question_comment' => $row['survey_question_comment'],
  1854. 'type' => $row['type'],
  1855. 'display' => $row['display'],
  1856. 'sort' => $row['sort'],
  1857. 'shared_question_id' => $row['shared_question_id'],
  1858. 'max_value' => $row['max_value'],
  1859. 'survey_group_pri' => $row['survey_group_pri'],
  1860. 'survey_group_sec1' => $row['survey_group_sec1'],
  1861. 'survey_group_sec2' => $row['survey_group_sec2'],
  1862. ];
  1863. if (api_get_configuration_value('allow_required_survey_questions')) {
  1864. if (isset($row['is_required'])) {
  1865. $params['is_required'] = $row['is_required'];
  1866. }
  1867. }
  1868. $insertId = Database::insert($surveyQuestionTable, $params);
  1869. if ($insertId) {
  1870. $sql = "UPDATE $surveyQuestionTable
  1871. SET question_id = iid
  1872. WHERE iid = $insertId";
  1873. Database::query($sql);
  1874. $question_id[$row['question_id']] = $insertId;
  1875. }
  1876. }
  1877. // Get questions options
  1878. $sql = "SELECT * FROM $surveyOptionsTable
  1879. WHERE survey_id = $surveyId AND c_id = $originalCourseId";
  1880. $res = Database::query($sql);
  1881. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1882. $params = [
  1883. 'c_id' => $targetCourseId,
  1884. 'question_id' => $question_id[$row['question_id']],
  1885. 'survey_id' => $newSurveyId,
  1886. 'option_text' => $row['option_text'],
  1887. 'sort' => $row['sort'],
  1888. 'value' => $row['value'],
  1889. ];
  1890. $insertId = Database::insert($surveyOptionsTable, $params);
  1891. if ($insertId) {
  1892. $sql = "UPDATE $surveyOptionsTable SET question_option_id = $insertId WHERE iid = $insertId";
  1893. Database::query($sql);
  1894. }
  1895. }
  1896. return $newSurveyId;
  1897. }
  1898. return false;
  1899. }
  1900. /**
  1901. * @param array $surveyData
  1902. *
  1903. * @return bool
  1904. */
  1905. public static function removeMultiplicateQuestions($surveyData)
  1906. {
  1907. if (empty($surveyData)) {
  1908. return false;
  1909. }
  1910. $surveyId = $surveyData['survey_id'];
  1911. $courseId = $surveyData['c_id'];
  1912. if (empty($surveyId) || empty($courseId)) {
  1913. return false;
  1914. }
  1915. $questions = self::get_questions($surveyId);
  1916. foreach ($questions as $question) {
  1917. // Questions marked with "geneated" were created using the "multiplicate" feature.
  1918. if ($question['survey_question_comment'] === 'generated') {
  1919. self::delete_survey_question($surveyId, $question['question_id']);
  1920. }
  1921. }
  1922. }
  1923. /**
  1924. * @param array $surveyData
  1925. *
  1926. * @return bool
  1927. */
  1928. public static function multiplicateQuestions($surveyData)
  1929. {
  1930. if (empty($surveyData)) {
  1931. return false;
  1932. }
  1933. $surveyId = $surveyData['survey_id'];
  1934. $courseId = $surveyData['c_id'];
  1935. if (empty($surveyId) || empty($courseId)) {
  1936. return false;
  1937. }
  1938. $questions = self::get_questions($surveyId);
  1939. $obj = new UserGroup();
  1940. $options['where'] = [' usergroup.course_id = ? ' => $courseId];
  1941. $classList = $obj->getUserGroupInCourse($options);
  1942. $classTag = '{{class_name}}';
  1943. $studentTag = '{{student_full_name}}';
  1944. $classCounter = 0;
  1945. foreach ($classList as $class) {
  1946. $className = $class['name'];
  1947. foreach ($questions as $question) {
  1948. $users = $obj->get_users_by_usergroup($class['id']);
  1949. if (empty($users)) {
  1950. continue;
  1951. }
  1952. $text = $question['question'];
  1953. if (strpos($text, $classTag) !== false) {
  1954. $replacedText = str_replace($classTag, $className, $text);
  1955. $values = [
  1956. 'c_id' => $courseId,
  1957. 'question_comment' => 'generated',
  1958. 'type' => $question['type'],
  1959. 'display' => $question['horizontalvertical'],
  1960. 'question' => $replacedText,
  1961. 'survey_id' => $surveyId,
  1962. 'question_id' => 0,
  1963. 'shared_question_id' => 0,
  1964. ];
  1965. self::save_question($surveyData, $values);
  1966. $classCounter++;
  1967. continue;
  1968. }
  1969. foreach ($users as $userId) {
  1970. $userInfo = api_get_user_info($userId);
  1971. if (strpos($text, $studentTag) !== false) {
  1972. $replacedText = str_replace($studentTag, $userInfo['complete_name'], $text);
  1973. $values = [
  1974. 'c_id' => $courseId,
  1975. 'question_comment' => 'generated',
  1976. 'type' => $question['type'],
  1977. 'display' => $question['horizontalvertical'],
  1978. 'maximum_score' => $question['maximum_score'],
  1979. 'question' => $replacedText,
  1980. 'survey_id' => $surveyId,
  1981. 'question_id' => 0,
  1982. 'shared_question_id' => 0,
  1983. ];
  1984. $answers = [];
  1985. if (!empty($question['answers'])) {
  1986. foreach ($question['answers'] as $answer) {
  1987. $replacedText = str_replace($studentTag, $userInfo['complete_name'], $answer);
  1988. $answers[] = $replacedText;
  1989. }
  1990. }
  1991. $values['answers'] = $answers;
  1992. self::save_question($surveyData, $values);
  1993. }
  1994. }
  1995. if ($classCounter < count($classList)) {
  1996. // Add end page
  1997. $values = [
  1998. 'c_id' => $courseId,
  1999. 'question_comment' => 'generated',
  2000. 'type' => 'pagebreak',
  2001. 'display' => 'horizontal',
  2002. 'question' => get_lang('QuestionForNextClass'),
  2003. 'survey_id' => $surveyId,
  2004. 'question_id' => 0,
  2005. 'shared_question_id' => 0,
  2006. ];
  2007. self::save_question($surveyData, $values);
  2008. }
  2009. }
  2010. }
  2011. }
  2012. /**
  2013. * @param array $survey
  2014. *
  2015. * @return int
  2016. */
  2017. public static function getCountPages($survey)
  2018. {
  2019. if (empty($survey) || !isset($survey['iid'])) {
  2020. return 0;
  2021. }
  2022. $courseId = $survey['c_id'];
  2023. $surveyId = $survey['survey_id'];
  2024. $table = Database::get_course_table(TABLE_SURVEY_QUESTION);
  2025. // pagebreak
  2026. $sql = "SELECT COUNT(iid) FROM $table
  2027. WHERE
  2028. survey_question NOT LIKE '%{{%' AND
  2029. type = 'pagebreak' AND
  2030. c_id = $courseId AND
  2031. survey_id = $surveyId";
  2032. $result = Database::query($sql);
  2033. $numberPageBreaks = Database::result($result, 0, 0);
  2034. // No pagebreak
  2035. $sql = "SELECT COUNT(iid) FROM $table
  2036. WHERE
  2037. survey_question NOT LIKE '%{{%' AND
  2038. type != 'pagebreak' AND
  2039. c_id = $courseId AND
  2040. survey_id = $surveyId";
  2041. $result = Database::query($sql);
  2042. $countOfQuestions = Database::result($result, 0, 0);
  2043. if ($survey['one_question_per_page'] == 1) {
  2044. if (!empty($countOfQuestions)) {
  2045. return $countOfQuestions;
  2046. }
  2047. return 1;
  2048. }
  2049. if (empty($numberPageBreaks)) {
  2050. return 1;
  2051. }
  2052. return $numberPageBreaks + 1;
  2053. }
  2054. /**
  2055. * Check whether this survey has ended. If so, display message and exit rhis script.
  2056. *
  2057. * @param array $surveyData Survey data
  2058. */
  2059. public static function checkTimeAvailability($surveyData)
  2060. {
  2061. if (empty($surveyData)) {
  2062. api_not_allowed(true);
  2063. }
  2064. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  2065. $utcZone = new DateTimeZone('UTC');
  2066. $startDate = new DateTime($surveyData['start_date'], $utcZone);
  2067. $endDate = new DateTime($surveyData['end_date'], $utcZone);
  2068. $currentDate = new DateTime('now', $utcZone);
  2069. if (!$allowSurveyAvailabilityDatetime) {
  2070. $currentDate->modify('today');
  2071. }
  2072. if ($currentDate < $startDate) {
  2073. api_not_allowed(
  2074. true,
  2075. Display:: return_message(
  2076. get_lang('SurveyNotAvailableYet'),
  2077. 'warning',
  2078. false
  2079. )
  2080. );
  2081. }
  2082. if ($currentDate > $endDate) {
  2083. api_not_allowed(
  2084. true,
  2085. Display:: return_message(
  2086. get_lang('SurveyNotAvailableAnymore'),
  2087. 'warning',
  2088. false
  2089. )
  2090. );
  2091. }
  2092. }
  2093. /**
  2094. * @param int $userId
  2095. * @param string $surveyCode
  2096. * @param int $courseId
  2097. * @param int $sessionId
  2098. * @param int $groupId
  2099. *
  2100. * @return array|CSurveyInvitation[]
  2101. */
  2102. public static function getUserInvitationsForSurveyInCourse(
  2103. $userId,
  2104. $surveyCode,
  2105. $courseId,
  2106. $sessionId = 0,
  2107. $groupId = 0
  2108. ) {
  2109. $invitationRepo = Database::getManager()->getRepository('ChamiloCourseBundle:CSurveyInvitation');
  2110. $invitations = $invitationRepo->findBy(
  2111. [
  2112. 'user' => $userId,
  2113. 'cId' => $courseId,
  2114. 'sessionId' => $sessionId,
  2115. 'groupId' => $groupId,
  2116. 'surveyCode' => $surveyCode,
  2117. ],
  2118. ['invitationDate' => 'DESC']
  2119. );
  2120. return $invitations;
  2121. }
  2122. /**
  2123. * @param array $userInfo
  2124. * @param int $answered (1 = answered 0 = not answered)
  2125. *
  2126. * @return string
  2127. */
  2128. public static function surveyReport($userInfo, $answered = 0)
  2129. {
  2130. $userId = isset($userInfo['user_id']) ? (int) $userInfo['user_id'] : 0;
  2131. $answered = (int) $answered;
  2132. if (empty($userId)) {
  2133. return '';
  2134. }
  2135. $em = Database::getManager();
  2136. $repo = $em->getRepository('ChamiloCourseBundle:CSurveyInvitation');
  2137. $repoSurvey = $em->getRepository('ChamiloCourseBundle:CSurvey');
  2138. $invitations = $repo->findBy(['user' => $userId, 'answered' => $answered]);
  2139. $mainUrl = api_get_path(WEB_CODE_PATH).'survey/survey.php?';
  2140. $content = '';
  2141. if (empty($answered)) {
  2142. $content .= Display::page_subheader(get_lang('Unanswered'));
  2143. } else {
  2144. $content .= Display::page_subheader(get_lang('Answered'));
  2145. }
  2146. if (!empty($invitations)) {
  2147. $table = new HTML_Table(['class' => 'table']);
  2148. $table->setHeaderContents(0, 0, get_lang('SurveyName'));
  2149. $table->setHeaderContents(0, 1, get_lang('Course'));
  2150. if (empty($answered)) {
  2151. $table->setHeaderContents(0, 2, get_lang('Survey').' - '.get_lang('EndDate'));
  2152. }
  2153. // Not answered
  2154. /** @var CSurveyInvitation $invitation */
  2155. $row = 1;
  2156. foreach ($invitations as $invitation) {
  2157. $courseId = $invitation->getCId();
  2158. $courseInfo = api_get_course_info_by_id($courseId);
  2159. $courseCode = $courseInfo['code'];
  2160. if (empty($courseInfo)) {
  2161. continue;
  2162. }
  2163. $sessionId = $invitation->getSessionId();
  2164. if (!empty($answered)) {
  2165. // check if user is subscribed to the course/session
  2166. if (empty($sessionId)) {
  2167. $subscribe = CourseManager::is_user_subscribed_in_course($userId, $courseCode);
  2168. } else {
  2169. $subscribe = CourseManager::is_user_subscribed_in_course($userId, $courseCode, true, $sessionId);
  2170. }
  2171. // User is not subscribe skip!
  2172. if (empty($subscribe)) {
  2173. continue;
  2174. }
  2175. }
  2176. $surveyCode = $invitation->getSurveyCode();
  2177. $survey = $repoSurvey->findOneBy([
  2178. 'cId' => $courseId,
  2179. 'sessionId' => $sessionId,
  2180. 'code' => $surveyCode,
  2181. ]);
  2182. if (empty($survey)) {
  2183. continue;
  2184. }
  2185. $url = $mainUrl.'survey_id='.$survey->getSurveyId().'&cidReq='.$courseCode.'&id_session='.$sessionId;
  2186. $title = $survey->getTitle();
  2187. $title = Display::url($title, $url);
  2188. if (!empty($sessionId)) {
  2189. $sessionInfo = api_get_session_info($sessionId);
  2190. $courseInfo['name'] .= ' ('.$sessionInfo['name'].')';
  2191. }
  2192. $surveyData = self::get_survey($survey->getSurveyId(), 0, $courseCode);
  2193. $table->setCellContents($row, 0, $title);
  2194. $table->setCellContents($row, 1, $courseInfo['name']);
  2195. if (empty($answered)) {
  2196. $table->setHeaderContents(
  2197. $row,
  2198. 2,
  2199. api_get_local_time(
  2200. $survey->getAvailTill(),
  2201. null,
  2202. null,
  2203. true,
  2204. false
  2205. )
  2206. );
  2207. }
  2208. if (!empty($answered) && $surveyData['anonymous'] == 0) {
  2209. $answers = SurveyUtil::displayCompleteReport(
  2210. $surveyData,
  2211. $userId,
  2212. false,
  2213. false,
  2214. false
  2215. );
  2216. $table->setCellContents(++$row, 0, $answers);
  2217. $table->setCellContents(++$row, 1, '');
  2218. }
  2219. $row++;
  2220. }
  2221. $content .= $table->toHtml();
  2222. } else {
  2223. $content .= Display::return_message(get_lang('NoData'));
  2224. }
  2225. return $content;
  2226. }
  2227. }