survey.lib.php 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CSurvey;
  4. use Chamilo\CourseBundle\Entity\CSurveyInvitation;
  5. use Chamilo\CourseBundle\Entity\CSurveyQuestion;
  6. use Chamilo\CourseBundle\Entity\CSurveyQuestionOption;
  7. /**
  8. * Class SurveyManager.
  9. *
  10. * @package chamilo.survey
  11. *
  12. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University:
  13. * cleanup, refactoring and rewriting large parts (if not all) of the code
  14. * @author Julio Montoya <gugli100@gmail.com>, Personality Test modification
  15. * and rewriting large parts of the code
  16. * @author cfasanando
  17. *
  18. * @todo move this file to inc/lib
  19. * @todo use consistent naming for the functions (save vs store for instance)
  20. */
  21. class SurveyManager
  22. {
  23. /**
  24. * @param $code
  25. *
  26. * @return string
  27. */
  28. public static function generate_unique_code($code)
  29. {
  30. if (empty($code)) {
  31. return false;
  32. }
  33. $course_id = api_get_course_int_id();
  34. $table = Database::get_course_table(TABLE_SURVEY);
  35. $code = Database::escape_string($code);
  36. $num = 0;
  37. $new_code = $code;
  38. while (true) {
  39. $sql = "SELECT * FROM $table
  40. WHERE code = '$new_code' AND c_id = $course_id";
  41. $result = Database::query($sql);
  42. if (Database::num_rows($result)) {
  43. $num++;
  44. $new_code = $code.$num;
  45. } else {
  46. break;
  47. }
  48. }
  49. return $code.$num;
  50. }
  51. /**
  52. * Deletes all survey invitations of a user.
  53. *
  54. * @param int $user_id
  55. *
  56. * @return bool
  57. * @assert ('') === false
  58. */
  59. public static function delete_all_survey_invitations_by_user($user_id)
  60. {
  61. $user_id = (int) $user_id;
  62. if (empty($user_id)) {
  63. return false;
  64. }
  65. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  66. $table_survey = Database::get_course_table(TABLE_SURVEY);
  67. $sql = "SELECT survey_invitation_id, survey_code
  68. FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
  69. $result = Database::query($sql);
  70. while ($row = Database::fetch_array($result, 'ASSOC')) {
  71. $survey_invitation_id = $row['survey_invitation_id'];
  72. $survey_code = $row['survey_code'];
  73. $sql2 = "DELETE FROM $table_survey_invitation
  74. WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
  75. if (Database::query($sql2)) {
  76. $sql3 = "UPDATE $table_survey SET
  77. invited = invited-1
  78. WHERE c_id <> 0 AND code ='$survey_code'";
  79. Database::query($sql3);
  80. }
  81. }
  82. }
  83. /**
  84. * @param string $course_code
  85. * @param int $session_id
  86. *
  87. * @return array
  88. * @assert ('') === false
  89. */
  90. public static function get_surveys($course_code, $session_id = 0)
  91. {
  92. if (empty($course_code)) {
  93. return false;
  94. }
  95. $course_info = api_get_course_info($course_code);
  96. if (empty($course_info)) {
  97. return false;
  98. }
  99. $sessionCondition = api_get_session_condition($session_id, true, true);
  100. $table = Database::get_course_table(TABLE_SURVEY);
  101. $sql = "SELECT * FROM $table
  102. WHERE c_id = {$course_info['real_id']} $sessionCondition ";
  103. $result = Database::query($sql);
  104. $result = Database::store_result($result, 'ASSOC');
  105. return $result;
  106. }
  107. /**
  108. * Retrieves all the survey information.
  109. *
  110. * @param int $survey_id the id of the survey
  111. * @param bool $shared this parameter determines if
  112. * we have to get the information of a survey from the central (shared) database or from the
  113. * course database
  114. * @param string course code optional
  115. *
  116. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  117. *
  118. * @version February 2007
  119. * @assert ('') === false
  120. *
  121. * @return array
  122. *
  123. * @todo this is the same function as in create_new_survey.php
  124. */
  125. public static function get_survey(
  126. $survey_id,
  127. $shared = 0,
  128. $course_code = '',
  129. $simple_return = false
  130. ) {
  131. $my_course_id = api_get_course_id();
  132. // Table definition
  133. if (!empty($course_code)) {
  134. $my_course_id = $course_code;
  135. } elseif (isset($_GET['course'])) {
  136. $my_course_id = Security::remove_XSS($_GET['course']);
  137. }
  138. $courseInfo = api_get_course_info($my_course_id);
  139. $survey_id = (int) $survey_id;
  140. $table_survey = Database::get_course_table(TABLE_SURVEY);
  141. if ($shared != 0) {
  142. $table_survey = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  143. $sql = "SELECT * FROM $table_survey
  144. WHERE survey_id='".$survey_id."' ";
  145. } else {
  146. if (empty($courseInfo)) {
  147. return [];
  148. }
  149. $sql = "SELECT * FROM $table_survey
  150. WHERE
  151. survey_id='".$survey_id."' AND
  152. c_id = ".$courseInfo['real_id'];
  153. }
  154. $result = Database::query($sql);
  155. $return = [];
  156. if (Database::num_rows($result) > 0) {
  157. $return = Database::fetch_array($result, 'ASSOC');
  158. if ($simple_return) {
  159. return $return;
  160. }
  161. // We do this (temporarily) to have the array match the quickform elements immediately
  162. // idealiter the fields in the db match the quickform fields
  163. $return['survey_code'] = $return['code'];
  164. $return['survey_title'] = $return['title'];
  165. $return['survey_subtitle'] = $return['subtitle'];
  166. $return['survey_language'] = $return['lang'];
  167. $return['start_date'] = $return['avail_from'];
  168. $return['end_date'] = $return['avail_till'];
  169. $return['survey_share'] = $return['is_shared'];
  170. $return['survey_introduction'] = $return['intro'];
  171. $return['survey_thanks'] = $return['surveythanks'];
  172. $return['survey_type'] = $return['survey_type'];
  173. $return['one_question_per_page'] = $return['one_question_per_page'];
  174. $return['show_form_profile'] = $return['show_form_profile'];
  175. $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
  176. $return['shuffle'] = $return['shuffle'];
  177. $return['parent_id'] = $return['parent_id'];
  178. $return['survey_version'] = $return['survey_version'];
  179. $return['anonymous'] = $return['anonymous'];
  180. $return['c_id'] = isset($return['c_id']) ? $return['c_id'] : 0;
  181. $return['session_id'] = isset($return['session_id']) ? $return['session_id'] : 0;
  182. }
  183. return $return;
  184. }
  185. /**
  186. * @param string $code
  187. *
  188. * @return string
  189. */
  190. public static function generateSurveyCode($code)
  191. {
  192. return strtolower(CourseManager::generate_course_code($code));
  193. }
  194. /**
  195. * This function stores a survey in the database.
  196. *
  197. * @param array $values
  198. *
  199. * @return array $return the type of return message that has to be displayed and the message in it
  200. *
  201. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  202. *
  203. * @version February 2007
  204. */
  205. public static function store_survey($values)
  206. {
  207. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  208. $_user = api_get_user_info();
  209. $course_id = api_get_course_int_id();
  210. $session_id = api_get_session_id();
  211. $courseCode = api_get_course_id();
  212. $table_survey = Database::get_course_table(TABLE_SURVEY);
  213. $shared_survey_id = 0;
  214. if (!isset($values['survey_id'])) {
  215. // Check if the code doesn't soon exists in this language
  216. $sql = 'SELECT 1 FROM '.$table_survey.'
  217. WHERE
  218. c_id = '.$course_id.' AND
  219. code = "'.Database::escape_string($values['survey_code']).'" AND
  220. lang = "'.Database::escape_string($values['survey_language']).'"';
  221. $rs = Database::query($sql);
  222. if (Database::num_rows($rs) > 0) {
  223. Display::addFlash(
  224. Display::return_message(
  225. get_lang('This survey code soon exists in this language'),
  226. 'error'
  227. )
  228. );
  229. $return['type'] = 'error';
  230. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  231. return $return;
  232. }
  233. if (!isset($values['anonymous'])) {
  234. $values['anonymous'] = 0;
  235. }
  236. $values['anonymous'] = (int) $values['anonymous'];
  237. $survey = new CSurvey();
  238. $extraParams = [];
  239. if ($values['anonymous'] == 0) {
  240. // Input_name_list
  241. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
  242. $survey->setShowFormProfile($values['show_form_profile']);
  243. if ($values['show_form_profile'] == 1) {
  244. // Input_name_list
  245. $fields = explode(',', $values['input_name_list']);
  246. $field_values = '';
  247. foreach ($fields as &$field) {
  248. if ($field != '') {
  249. if ($values[$field] == '') {
  250. $values[$field] = 0;
  251. }
  252. $field_values .= $field.':'.$values[$field].'@';
  253. }
  254. }
  255. $extraParams['form_fields'] = $field_values;
  256. } else {
  257. $extraParams['form_fields'] = '';
  258. }
  259. $survey->setFormFields($extraParams['form_fields']);
  260. } else {
  261. $survey->setShowFormProfile(0);
  262. $survey->setFormFields(0);
  263. }
  264. $extraParams['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : 0;
  265. $extraParams['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : 0;
  266. if ($values['survey_type'] == 1) {
  267. $survey
  268. ->setSurveyType(1)
  269. ->setShuffle($values['shuffle'])
  270. ->setOneQuestionPerPage($values['one_question_per_page'])
  271. ->setParentId($values['parent_id'])
  272. ;
  273. // Logic for versioning surveys
  274. if (!empty($values['parent_id'])) {
  275. $versionValue = '';
  276. $sql = 'SELECT survey_version
  277. FROM '.$table_survey.'
  278. WHERE
  279. c_id = '.$course_id.' AND
  280. parent_id = '.intval($values['parent_id']).'
  281. ORDER BY survey_version DESC
  282. LIMIT 1';
  283. $rs = Database::query($sql);
  284. if (Database::num_rows($rs) === 0) {
  285. $sql = 'SELECT survey_version FROM '.$table_survey.'
  286. WHERE
  287. c_id = '.$course_id.' AND
  288. survey_id = '.intval($values['parent_id']);
  289. $rs = Database::query($sql);
  290. $getversion = Database::fetch_array($rs, 'ASSOC');
  291. if (empty($getversion['survey_version'])) {
  292. $versionValue = ++$getversion['survey_version'];
  293. } else {
  294. $versionValue = $getversion['survey_version'];
  295. }
  296. } else {
  297. $row = Database::fetch_array($rs, 'ASSOC');
  298. $pos = api_strpos($row['survey_version']);
  299. if ($pos === false) {
  300. $row['survey_version'] = $row['survey_version'] + 1;
  301. $versionValue = $row['survey_version'];
  302. } else {
  303. $getlast = explode('\.', $row['survey_version']);
  304. $lastversion = array_pop($getlast);
  305. $lastversion = $lastversion + 1;
  306. $add = implode('.', $getlast);
  307. if ($add != '') {
  308. $insertnewversion = $add.'.'.$lastversion;
  309. } else {
  310. $insertnewversion = $lastversion;
  311. }
  312. $versionValue = $insertnewversion;
  313. }
  314. }
  315. $survey->setSurveyVersion($versionValue);
  316. }
  317. }
  318. $from = api_get_utc_datetime($values['start_date'].'00:00:00', true, true);
  319. $until = api_get_utc_datetime($values['end_date'].'23:59:59', true, true);
  320. if ($allowSurveyAvailabilityDatetime) {
  321. $from = api_get_utc_datetime($values['start_date'].':00', true, true);
  322. $until = api_get_utc_datetime($values['end_date'].':59', true, true);
  323. }
  324. $survey
  325. ->setCId($course_id)
  326. ->setCode(self::generateSurveyCode($values['survey_code']))
  327. ->setTitle($values['survey_title'])
  328. ->setSubtitle($values['survey_title'])
  329. ->setAuthor($_user['user_id'])
  330. ->setLang($values['survey_language'])
  331. ->setAvailFrom($from)
  332. ->setAvailTill($until)
  333. ->setIsShared($shared_survey_id)
  334. ->setTemplate('template')
  335. ->setIntro($values['survey_introduction'])
  336. ->setSurveyThanks($values['survey_thanks'])
  337. ->setAnonymous($values['anonymous'])
  338. ->setSessionId(api_get_session_id())
  339. ->setVisibleResults($values['visible_results'])
  340. ;
  341. $em = Database::getManager();
  342. $em->persist($survey);
  343. $em->flush();
  344. $survey_id = $survey->getIid();
  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('The survey has been created succesfully'),
  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('This survey code soon exists in this language'),
  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('The survey has been updated succesfully'),
  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. }
  870. return false;
  871. }
  872. /**
  873. * This function retrieves all the information of a question.
  874. *
  875. * @param int $question_id the id of the question
  876. * @param bool $shared
  877. *
  878. * @return array
  879. *
  880. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  881. *
  882. * @version January 2007
  883. *
  884. * @todo one sql call should do the trick
  885. */
  886. public static function get_question($question_id, $shared = false)
  887. {
  888. // Table definitions
  889. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  890. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  891. $course_id = api_get_course_int_id();
  892. $question_id = (int) $question_id;
  893. $sql = "SELECT * FROM $tbl_survey_question
  894. WHERE c_id = $course_id AND question_id='".$question_id."'
  895. ORDER BY `sort` ";
  896. $sqlOption = " SELECT * FROM $table_survey_question_option
  897. WHERE c_id = $course_id AND question_id='".$question_id."'
  898. ORDER BY `sort` ";
  899. if ($shared) {
  900. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  901. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  902. $sql = "SELECT * FROM $tbl_survey_question
  903. WHERE question_id='".$question_id."'
  904. ORDER BY `sort` ";
  905. $sqlOption = "SELECT * FROM $table_survey_question_option
  906. WHERE question_id='".$question_id."'
  907. ORDER BY `sort` ";
  908. }
  909. // Getting the information of the question
  910. $result = Database::query($sql);
  911. $row = Database::fetch_array($result, 'ASSOC');
  912. $return['survey_id'] = $row['survey_id'];
  913. $return['question_id'] = $row['question_id'];
  914. $return['type'] = $row['type'];
  915. $return['question'] = $row['survey_question'];
  916. $return['horizontalvertical'] = $row['display'];
  917. $return['shared_question_id'] = $row['shared_question_id'];
  918. $return['maximum_score'] = $row['max_value'];
  919. $return['is_required'] = api_get_configuration_value('allow_required_survey_questions')
  920. ? $row['is_required']
  921. : false;
  922. if ($row['survey_group_pri'] != 0) {
  923. $return['assigned'] = $row['survey_group_pri'];
  924. $return['choose'] = 1;
  925. } else {
  926. $return['assigned1'] = $row['survey_group_sec1'];
  927. $return['assigned2'] = $row['survey_group_sec2'];
  928. $return['choose'] = 2;
  929. }
  930. // Getting the information of the question options
  931. $result = Database::query($sqlOption);
  932. while ($row = Database::fetch_array($result, 'ASSOC')) {
  933. /** @todo this should be renamed to options instead of answers */
  934. $return['answers'][] = $row['option_text'];
  935. $return['values'][] = $row['value'];
  936. /** @todo this can be done more elegantly (used in reporting) */
  937. $return['answersid'][] = $row['question_option_id'];
  938. }
  939. return $return;
  940. }
  941. /**
  942. * This function gets all the question of any given survey.
  943. *
  944. * @param int $surveyId the id of the survey
  945. * @param int $courseId
  946. *
  947. * @return array containing all the questions of the survey
  948. *
  949. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  950. *
  951. * @version February 2007
  952. *
  953. * @todo one sql call should do the trick
  954. */
  955. public static function get_questions($surveyId, $courseId = 0)
  956. {
  957. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  958. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  959. $courseId = (int) $courseId;
  960. $surveyId = (int) $surveyId;
  961. if (empty($courseId)) {
  962. $courseId = api_get_course_int_id();
  963. }
  964. // Getting the information of the question
  965. $sql = "SELECT * FROM $tbl_survey_question
  966. WHERE c_id = $courseId AND survey_id='".$surveyId."'";
  967. $result = Database::query($sql);
  968. $return = [];
  969. while ($row = Database::fetch_array($result, 'ASSOC')) {
  970. $return[$row['question_id']]['survey_id'] = $row['survey_id'];
  971. $return[$row['question_id']]['question_id'] = $row['question_id'];
  972. $return[$row['question_id']]['type'] = $row['type'];
  973. $return[$row['question_id']]['question'] = $row['survey_question'];
  974. $return[$row['question_id']]['horizontalvertical'] = $row['display'];
  975. $return[$row['question_id']]['maximum_score'] = $row['max_value'];
  976. $return[$row['question_id']]['sort'] = $row['sort'];
  977. $return[$row['question_id']]['survey_question_comment'] = $row['survey_question_comment'];
  978. }
  979. // Getting the information of the question options
  980. $sql = "SELECT * FROM $table_survey_question_option
  981. WHERE c_id = $courseId AND survey_id='".$surveyId."'";
  982. $result = Database::query($sql);
  983. while ($row = Database::fetch_array($result, 'ASSOC')) {
  984. $return[$row['question_id']]['answers'][] = $row['option_text'];
  985. }
  986. return $return;
  987. }
  988. /**
  989. * This function saves a question in the database.
  990. * This can be either an update of an existing survey or storing a new survey.
  991. *
  992. * @param array $survey_data
  993. * @param array $form_content all the information of the form
  994. *
  995. * @return string
  996. *
  997. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  998. *
  999. * @version January 2007
  1000. */
  1001. public static function save_question($survey_data, $form_content)
  1002. {
  1003. $return_message = '';
  1004. if (strlen($form_content['question']) > 1) {
  1005. // Checks length of the question
  1006. $empty_answer = false;
  1007. if ($survey_data['survey_type'] == 1) {
  1008. if (empty($form_content['choose'])) {
  1009. $return_message = 'PleaseChooseACondition';
  1010. return $return_message;
  1011. }
  1012. if (($form_content['choose'] == 2) &&
  1013. ($form_content['assigned1'] == $form_content['assigned2'])
  1014. ) {
  1015. $return_message = 'ChooseDifferentCategories';
  1016. return $return_message;
  1017. }
  1018. }
  1019. if ($form_content['type'] != 'percentage') {
  1020. if (isset($form_content['answers'])) {
  1021. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1022. if (strlen($form_content['answers'][$i]) < 1) {
  1023. $empty_answer = true;
  1024. break;
  1025. }
  1026. }
  1027. }
  1028. }
  1029. if ($form_content['type'] == 'score') {
  1030. if (strlen($form_content['maximum_score']) < 1) {
  1031. $empty_answer = true;
  1032. }
  1033. }
  1034. $course_id = api_get_course_int_id();
  1035. if (!$empty_answer) {
  1036. // Table definitions
  1037. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1038. // Getting all the information of the survey
  1039. $survey_data = self::get_survey($form_content['survey_id']);
  1040. // Storing the question in the shared database
  1041. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1042. $shared_question_id = self::save_shared_question($form_content, $survey_data);
  1043. $form_content['shared_question_id'] = $shared_question_id;
  1044. }
  1045. // Storing a new question
  1046. if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
  1047. // Finding the max sort order of the questions in the given survey
  1048. $sql = "SELECT max(sort) AS max_sort
  1049. FROM $tbl_survey_question
  1050. WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
  1051. $result = Database::query($sql);
  1052. $row = Database::fetch_array($result, 'ASSOC');
  1053. $max_sort = $row['max_sort'];
  1054. $question = new CSurveyQuestion();
  1055. // Some variables defined for survey-test type
  1056. $extraParams = [];
  1057. if (isset($_POST['choose'])) {
  1058. if ($_POST['choose'] == 1) {
  1059. $question->setSurveyGroupPri($_POST['assigned']);
  1060. } elseif ($_POST['choose'] == 2) {
  1061. $question->setSurveyGroupSec1($_POST['assigned1']);
  1062. $question->setSurveyGroupSec2($_POST['assigned2']);
  1063. }
  1064. }
  1065. $question
  1066. ->setSurveyQuestionComment($form_content['question_comment'] ?? '')
  1067. ->setMaxValue($form_content['maximum_score'] ?? 0)
  1068. ->setDisplay($form_content['horizontalvertical'] ?? '')
  1069. ->setCId($course_id)
  1070. ->setSurveyId($form_content['survey_id'])
  1071. ->setSurveyQuestion($form_content['question'])
  1072. ->setType($form_content['type'])
  1073. ->setSort($max_sort + 1)
  1074. ->setSharedQuestionId($form_content['shared_question_id'])
  1075. ;
  1076. if (api_get_configuration_value('allow_required_survey_questions')) {
  1077. $question->setIsMandatory(isset($form_content['is_required']));
  1078. }
  1079. $em = Database::getManager();
  1080. $em->persist($question);
  1081. $em->flush();
  1082. $question_id = $question->getIid();
  1083. if ($question_id) {
  1084. $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
  1085. WHERE iid = $question_id";
  1086. Database::query($sql);
  1087. $form_content['question_id'] = $question_id;
  1088. $return_message = 'QuestionAdded';
  1089. }
  1090. } else {
  1091. // Updating an existing question
  1092. $extraParams = [];
  1093. if (isset($_POST['choose'])) {
  1094. if ($_POST['choose'] == 1) {
  1095. $extraParams['survey_group_pri'] = $_POST['assigned'];
  1096. $extraParams['survey_group_sec1'] = 0;
  1097. $extraParams['survey_group_sec2'] = 0;
  1098. } elseif ($_POST['choose'] == 2) {
  1099. $extraParams['survey_group_pri'] = 0;
  1100. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  1101. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  1102. }
  1103. }
  1104. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
  1105. $questionComment = isset($form_content['question_comment'])
  1106. ? $form_content['question_comment']
  1107. : null;
  1108. // Adding the question to the survey_question table
  1109. $params = [
  1110. 'survey_question' => $form_content['question'],
  1111. 'survey_question_comment' => $questionComment,
  1112. 'display' => $form_content['horizontalvertical'],
  1113. ];
  1114. if (api_get_configuration_value('allow_required_survey_questions')) {
  1115. $params['is_required'] = isset($form_content['is_required']);
  1116. }
  1117. $params = array_merge($params, $extraParams);
  1118. Database::update(
  1119. $tbl_survey_question,
  1120. $params,
  1121. [
  1122. 'c_id = ? AND question_id = ?' => [
  1123. $course_id,
  1124. $form_content['question_id'],
  1125. ],
  1126. ]
  1127. );
  1128. $return_message = 'QuestionUpdated';
  1129. }
  1130. if (!empty($form_content['survey_id'])) {
  1131. //Updating survey
  1132. api_item_property_update(
  1133. api_get_course_info(),
  1134. TOOL_SURVEY,
  1135. $form_content['survey_id'],
  1136. 'SurveyUpdated',
  1137. api_get_user_id()
  1138. );
  1139. }
  1140. // Storing the options of the question
  1141. self::save_question_options($form_content, $survey_data);
  1142. } else {
  1143. $return_message = 'PleasFillAllAnswer';
  1144. }
  1145. } else {
  1146. $return_message = 'PleaseEnterAQuestion';
  1147. }
  1148. if (!empty($return_message)) {
  1149. Display::addFlash(Display::return_message(get_lang($return_message)));
  1150. }
  1151. return $return_message;
  1152. }
  1153. /**
  1154. * This function saves the question in the shared database.
  1155. *
  1156. * @param array $form_content all the information of the form
  1157. * @param array $survey_data all the information of the survey
  1158. *
  1159. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1160. *
  1161. * @version February 2007
  1162. *
  1163. * @return int
  1164. *
  1165. * @todo editing of a shared question
  1166. */
  1167. public function save_shared_question($form_content, $survey_data)
  1168. {
  1169. $_course = api_get_course_info();
  1170. // Table definitions
  1171. $tbl_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1172. // Storing a new question
  1173. if ($form_content['shared_question_id'] == '' ||
  1174. !is_numeric($form_content['shared_question_id'])
  1175. ) {
  1176. // Finding the max sort order of the questions in the given survey
  1177. $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
  1178. WHERE survey_id='".intval($survey_data['survey_share'])."'
  1179. AND code='".Database::escape_string($_course['id'])."'";
  1180. $result = Database::query($sql);
  1181. $row = Database::fetch_array($result, 'ASSOC');
  1182. $max_sort = $row['max_sort'];
  1183. // Adding the question to the survey_question table
  1184. $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
  1185. '".Database::escape_string($survey_data['survey_share'])."',
  1186. '".Database::escape_string($form_content['question'])."',
  1187. '".Database::escape_string($form_content['question_comment'])."',
  1188. '".Database::escape_string($form_content['type'])."',
  1189. '".Database::escape_string($form_content['horizontalvertical'])."',
  1190. '".Database::escape_string($max_sort + 1)."',
  1191. '".Database::escape_string($_course['id'])."')";
  1192. Database::query($sql);
  1193. $shared_question_id = Database::insert_id();
  1194. } else {
  1195. // Updating an existing question
  1196. // adding the question to the survey_question table
  1197. $sql = "UPDATE $tbl_survey_question SET
  1198. survey_question = '".Database::escape_string($form_content['question'])."',
  1199. survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
  1200. display = '".Database::escape_string($form_content['horizontalvertical'])."'
  1201. WHERE
  1202. question_id = '".intval($form_content['shared_question_id'])."' AND
  1203. code = '".Database::escape_string($_course['id'])."'";
  1204. Database::query($sql);
  1205. $shared_question_id = $form_content['shared_question_id'];
  1206. }
  1207. return $shared_question_id;
  1208. }
  1209. /**
  1210. * This functions moves a question of a survey up or down.
  1211. *
  1212. * @param string $direction
  1213. * @param int $survey_question_id
  1214. * @param int $survey_id
  1215. *
  1216. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1217. *
  1218. * @version January 2007
  1219. */
  1220. public static function move_survey_question(
  1221. $direction,
  1222. $survey_question_id,
  1223. $survey_id
  1224. ) {
  1225. // Table definition
  1226. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1227. $course_id = api_get_course_int_id();
  1228. if ($direction == 'moveup') {
  1229. $sort = 'DESC';
  1230. }
  1231. if ($direction == 'movedown') {
  1232. $sort = 'ASC';
  1233. }
  1234. $survey_id = (int) $survey_id;
  1235. // Finding the two questions that needs to be swapped
  1236. $sql = "SELECT * FROM $table_survey_question
  1237. WHERE c_id = $course_id AND survey_id='".$survey_id."'
  1238. ORDER BY sort $sort";
  1239. $result = Database::query($sql);
  1240. $found = false;
  1241. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1242. if ($found) {
  1243. $question_id_two = $row['question_id'];
  1244. $question_sort_two = $row['sort'];
  1245. $found = false;
  1246. }
  1247. if ($row['question_id'] == $survey_question_id) {
  1248. $found = true;
  1249. $question_id_one = $row['question_id'];
  1250. $question_sort_one = $row['sort'];
  1251. }
  1252. }
  1253. $sql = "UPDATE $table_survey_question
  1254. SET sort = '".Database::escape_string($question_sort_two)."'
  1255. WHERE c_id = $course_id AND question_id='".intval($question_id_one)."'";
  1256. Database::query($sql);
  1257. $sql = "UPDATE $table_survey_question
  1258. SET sort = '".Database::escape_string($question_sort_one)."'
  1259. WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
  1260. Database::query($sql);
  1261. }
  1262. /**
  1263. * This function deletes all the questions of a given survey
  1264. * This function is normally only called when a survey is deleted.
  1265. *
  1266. * @param int $survey_id the id of the survey that has to be deleted
  1267. *
  1268. * @return bool
  1269. *
  1270. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1271. *
  1272. * @version January 2007
  1273. */
  1274. public static function delete_all_survey_questions($survey_id, $shared = false)
  1275. {
  1276. $course_id = api_get_course_int_id();
  1277. $survey_id = (int) $survey_id;
  1278. // Table definitions
  1279. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1280. $course_condition = " c_id = $course_id AND ";
  1281. if ($shared) {
  1282. $course_condition = '';
  1283. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1284. }
  1285. $sql = "DELETE FROM $table_survey_question
  1286. WHERE $course_condition survey_id = '".$survey_id."'";
  1287. // Deleting the survey questions
  1288. Database::query($sql);
  1289. // Deleting all the options of the questions of the survey
  1290. self::delete_all_survey_questions_options($survey_id, $shared);
  1291. // Deleting all the answers on this survey
  1292. self::delete_all_survey_answers($survey_id);
  1293. return true;
  1294. }
  1295. /**
  1296. * This function deletes a survey question and all its options.
  1297. *
  1298. * @param int $survey_id the id of the survey
  1299. * @param int $question_id the id of the question
  1300. * @param bool $shared
  1301. *
  1302. * @todo also delete the answers to this question
  1303. *
  1304. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1305. *
  1306. * @version March 2007
  1307. */
  1308. public static function delete_survey_question($survey_id, $question_id, $shared = false)
  1309. {
  1310. $survey_id = (int) $survey_id;
  1311. $question_id = (int) $question_id;
  1312. $course_id = api_get_course_int_id();
  1313. if ($shared) {
  1314. self::delete_shared_survey_question($survey_id, $question_id);
  1315. }
  1316. // Table definitions
  1317. $table = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1318. // Deleting the survey questions
  1319. $sql = "DELETE FROM $table
  1320. WHERE
  1321. c_id = $course_id AND
  1322. survey_id='".$survey_id."' AND
  1323. question_id='".$question_id."'";
  1324. Database::query($sql);
  1325. // Deleting the options of the question of the survey
  1326. self::delete_survey_question_option($survey_id, $question_id, $shared);
  1327. }
  1328. /**
  1329. * This function deletes a shared survey question from the main database and all its options.
  1330. *
  1331. * @param int $question_id the id of the question
  1332. *
  1333. * @todo delete all the options of this question
  1334. *
  1335. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1336. *
  1337. * @version March 2007
  1338. */
  1339. public static function delete_shared_survey_question($survey_id, $question_id)
  1340. {
  1341. // Table definitions
  1342. $table_survey_question = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1343. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1344. // First we have to get the shared_question_id
  1345. $question_data = self::get_question($question_id);
  1346. // Deleting the survey questions
  1347. $sql = "DELETE FROM $table_survey_question
  1348. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1349. Database::query($sql);
  1350. // Deleting the options of the question of the survey question
  1351. $sql = "DELETE FROM $table_survey_question_option
  1352. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1353. Database::query($sql);
  1354. }
  1355. /**
  1356. * This function stores the options of the questions in the table.
  1357. *
  1358. * @param array $form_content
  1359. *
  1360. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1361. *
  1362. * @version January 2007
  1363. *
  1364. * @todo writing the update statement when editing a question
  1365. */
  1366. public static function save_question_options($form_content, $survey_data)
  1367. {
  1368. $course_id = api_get_course_int_id();
  1369. // A percentage question type has options 1 -> 100
  1370. if ($form_content['type'] === 'percentage') {
  1371. for ($i = 1; $i < 101; $i++) {
  1372. $form_content['answers'][] = $i;
  1373. }
  1374. }
  1375. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1376. self::save_shared_question_options($form_content, $survey_data);
  1377. }
  1378. // Table definition
  1379. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1380. // We are editing a question so we first have to remove all the existing options from the database
  1381. if (is_numeric($form_content['question_id'])) {
  1382. $sql = "DELETE FROM $table_survey_question_option
  1383. WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
  1384. Database::query($sql);
  1385. }
  1386. $counter = 1;
  1387. $em = Database::getManager();
  1388. if (isset($form_content['answers']) && is_array($form_content['answers'])) {
  1389. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1390. $values = isset($form_content['values']) ? $form_content['values'][$i] : 0;
  1391. $option = new CSurveyQuestionOption();
  1392. $option
  1393. ->setCId($course_id)
  1394. ->setQuestionId($form_content['question_id'])
  1395. ->setSurveyId($form_content['survey_id'])
  1396. ->setOptionText($form_content['answers'][$i])
  1397. ->setValue($values)
  1398. ->setSort($counter)
  1399. ;
  1400. $em->persist($option);
  1401. $em->flush();
  1402. $insertId = $option->getIid();
  1403. if ($insertId) {
  1404. $sql = "UPDATE $table_survey_question_option
  1405. SET question_option_id = $insertId
  1406. WHERE iid = $insertId";
  1407. Database::query($sql);
  1408. $counter++;
  1409. }
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * This function stores the options of the questions in the shared table.
  1415. *
  1416. * @param array $form_content
  1417. *
  1418. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1419. *
  1420. * @version February 2007
  1421. *
  1422. * @todo writing the update statement when editing a question
  1423. */
  1424. public function save_shared_question_options($form_content, $survey_data)
  1425. {
  1426. if (is_array($form_content) && is_array($form_content['answers'])) {
  1427. // Table definition
  1428. $table = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1429. // We are editing a question so we first have to remove all the existing options from the database
  1430. $sql = "DELETE FROM $table
  1431. WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
  1432. Database::query($sql);
  1433. $counter = 1;
  1434. foreach ($form_content['answers'] as &$answer) {
  1435. $params = [
  1436. 'question_id' => $form_content['shared_question_id'],
  1437. 'survey_id' => $survey_data['is_shared'],
  1438. 'option_text' => $answer,
  1439. 'sort' => $counter,
  1440. ];
  1441. Database::insert($table, $params);
  1442. $counter++;
  1443. }
  1444. }
  1445. }
  1446. /**
  1447. * This function deletes all the options of the questions of a given survey
  1448. * This function is normally only called when a survey is deleted.
  1449. *
  1450. * @param int $survey_id the id of the survey that has to be deleted
  1451. *
  1452. * @return true
  1453. *
  1454. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1455. *
  1456. * @version January 2007
  1457. */
  1458. public static function delete_all_survey_questions_options($survey_id, $shared = false)
  1459. {
  1460. // Table definitions
  1461. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1462. $course_id = api_get_course_int_id();
  1463. $course_condition = " c_id = $course_id AND ";
  1464. if ($shared) {
  1465. $course_condition = '';
  1466. $table_survey_question_option = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1467. }
  1468. $sql = "DELETE FROM $table_survey_question_option
  1469. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1470. // Deleting the options of the survey questions
  1471. Database::query($sql);
  1472. return true;
  1473. }
  1474. /**
  1475. * This function deletes the options of a given question.
  1476. *
  1477. * @param int $survey_id
  1478. * @param int $question_id
  1479. * @param bool $shared
  1480. *
  1481. * @return bool
  1482. *
  1483. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1484. * @author Julio Montoya
  1485. *
  1486. * @version March 2007
  1487. */
  1488. public static function delete_survey_question_option(
  1489. $survey_id,
  1490. $question_id,
  1491. $shared = false
  1492. ) {
  1493. $course_id = api_get_course_int_id();
  1494. $course_condition = " c_id = $course_id AND ";
  1495. // Table definitions
  1496. $table = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1497. if ($shared) {
  1498. $course_condition = '';
  1499. $table = Database::get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1500. }
  1501. // Deleting the options of the survey questions
  1502. $sql = "DELETE FROM $table
  1503. WHERE
  1504. $course_condition survey_id='".intval($survey_id)."' AND
  1505. question_id='".intval($question_id)."'";
  1506. Database::query($sql);
  1507. return true;
  1508. }
  1509. /**
  1510. * SURVEY ANSWERS FUNCTIONS.
  1511. */
  1512. /**
  1513. * This function deletes all the answers anyone has given on this survey
  1514. * This function is normally only called when a survey is deleted.
  1515. *
  1516. * @param $survey_id the id of the survey that has to be deleted
  1517. *
  1518. * @return true
  1519. *
  1520. * @todo write the function
  1521. *
  1522. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1523. *
  1524. * @version January 2007,december 2008
  1525. */
  1526. public static function delete_all_survey_answers($survey_id)
  1527. {
  1528. $course_id = api_get_course_int_id();
  1529. $table = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1530. $survey_id = (int) $survey_id;
  1531. $sql = "DELETE FROM $table
  1532. WHERE c_id = $course_id AND survey_id = $survey_id";
  1533. Database::query($sql);
  1534. return true;
  1535. }
  1536. /**
  1537. * @param int $user_id
  1538. * @param int $survey_id
  1539. * @param int $course_id
  1540. *
  1541. * @return bool
  1542. */
  1543. public static function is_user_filled_survey($user_id, $survey_id, $course_id)
  1544. {
  1545. $table = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1546. $user_id = (int) $user_id;
  1547. $course_id = (int) $course_id;
  1548. $survey_id = (int) $survey_id;
  1549. $sql = "SELECT DISTINCT user
  1550. FROM $table
  1551. WHERE
  1552. c_id = $course_id AND
  1553. user = $user_id AND
  1554. survey_id = $survey_id";
  1555. $result = Database::query($sql);
  1556. if (Database::num_rows($result)) {
  1557. return true;
  1558. }
  1559. return false;
  1560. }
  1561. /**
  1562. * This function gets all the persons who have filled the survey.
  1563. *
  1564. * @param int $survey_id
  1565. *
  1566. * @return array
  1567. *
  1568. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1569. *
  1570. * @version February 2007
  1571. */
  1572. public static function get_people_who_filled_survey(
  1573. $survey_id,
  1574. $all_user_info = false,
  1575. $course_id = null
  1576. ) {
  1577. // Database table definition
  1578. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1579. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1580. // Variable initialisation
  1581. $return = [];
  1582. if (empty($course_id)) {
  1583. $course_id = api_get_course_int_id();
  1584. } else {
  1585. $course_id = (int) $course_id;
  1586. }
  1587. $survey_id = (int) $survey_id;
  1588. if ($all_user_info) {
  1589. $order_clause = api_sort_by_first_name()
  1590. ? ' ORDER BY user.firstname, user.lastname'
  1591. : ' ORDER BY user.lastname, user.firstname';
  1592. $sql = "SELECT DISTINCT
  1593. answered_user.user as invited_user,
  1594. user.firstname,
  1595. user.lastname,
  1596. user.user_id
  1597. FROM $table_survey_answer answered_user
  1598. LEFT JOIN $table_user as user ON answered_user.user = user.user_id
  1599. WHERE
  1600. answered_user.c_id = $course_id AND
  1601. survey_id= '".$survey_id."' ".
  1602. $order_clause;
  1603. } else {
  1604. $sql = "SELECT DISTINCT user FROM $table_survey_answer
  1605. WHERE c_id = $course_id AND survey_id= '".$survey_id."' ";
  1606. if (api_get_configuration_value('survey_anonymous_show_answered')) {
  1607. $tblInvitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  1608. $tblSurvey = Database::get_course_table(TABLE_SURVEY);
  1609. $sql = "SELECT i.user FROM $tblInvitation i
  1610. INNER JOIN $tblSurvey s
  1611. ON i.survey_code = s.code
  1612. AND i.c_id = s.c_id
  1613. AND i.session_id = s.session_id
  1614. WHERE i.answered IS TRUE AND s.iid = $survey_id";
  1615. }
  1616. }
  1617. $res = Database::query($sql);
  1618. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1619. if ($all_user_info) {
  1620. $userInfo = api_get_user_info($row['user_id']);
  1621. $row['user_info'] = $userInfo;
  1622. $return[] = $row;
  1623. } else {
  1624. $return[] = $row['user'];
  1625. }
  1626. }
  1627. return $return;
  1628. }
  1629. /**
  1630. * @return bool
  1631. */
  1632. public static function survey_generation_hash_available()
  1633. {
  1634. if (extension_loaded('mcrypt')) {
  1635. return true;
  1636. }
  1637. return false;
  1638. }
  1639. /**
  1640. * @param int $survey_id
  1641. * @param int $course_id
  1642. * @param int $session_id
  1643. * @param int $group_id
  1644. *
  1645. * @return string
  1646. */
  1647. public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
  1648. {
  1649. $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
  1650. return $hash;
  1651. }
  1652. /**
  1653. * @param int $survey_id
  1654. * @param int $course_id
  1655. * @param int $session_id
  1656. * @param int $group_id
  1657. * @param string $hash
  1658. *
  1659. * @return bool
  1660. */
  1661. public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
  1662. {
  1663. $generatedHash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
  1664. if ($generatedHash == $hash) {
  1665. return true;
  1666. }
  1667. return false;
  1668. }
  1669. /**
  1670. * @param int $survey_id
  1671. * @param int $course_id
  1672. * @param int $session_id
  1673. * @param int $group_id
  1674. *
  1675. * @return string
  1676. */
  1677. public static function generate_survey_link(
  1678. $survey_id,
  1679. $course_id,
  1680. $session_id,
  1681. $group_id
  1682. ) {
  1683. $code = self::generate_survey_hash(
  1684. $survey_id,
  1685. $course_id,
  1686. $session_id,
  1687. $group_id
  1688. );
  1689. return api_get_path(WEB_CODE_PATH).'survey/link.php?h='.$code.'&i='.$survey_id.'&c='.intval($course_id).'&s='
  1690. .intval($session_id).'&g='.$group_id;
  1691. }
  1692. /**
  1693. * Check if the current user has mandatory surveys no-answered
  1694. * and redirect to fill the first found survey.
  1695. */
  1696. public static function protectByMandatory()
  1697. {
  1698. if (strpos($_SERVER['SCRIPT_NAME'], 'fillsurvey.php') !== false) {
  1699. return;
  1700. }
  1701. $userId = api_get_user_id();
  1702. $courseId = api_get_course_int_id();
  1703. $sessionId = api_get_session_id();
  1704. if (!$userId) {
  1705. return;
  1706. }
  1707. if (!$courseId) {
  1708. return;
  1709. }
  1710. try {
  1711. /** @var CSurveyInvitation $invitation */
  1712. $invitation = Database::getManager()
  1713. ->createQuery("
  1714. SELECT i FROM ChamiloCourseBundle:CSurveyInvitation i
  1715. INNER JOIN ChamiloCourseBundle:CSurvey s
  1716. WITH (s.code = i.surveyCode AND s.cId = i.cId AND s.sessionId = i.sessionId)
  1717. INNER JOIN ChamiloCoreBundle:ExtraFieldValues efv WITH efv.itemId = s.iid
  1718. INNER JOIN ChamiloCoreBundle:ExtraField ef WITH efv.field = ef.id
  1719. WHERE
  1720. i.answered = 0 AND
  1721. i.cId = :course AND
  1722. i.user = :user AND
  1723. i.sessionId = :session AND
  1724. :now BETWEEN s.availFrom AND s.availTill AND
  1725. ef.variable = :variable AND
  1726. efv.value = 1 AND
  1727. s.surveyType != 3
  1728. ORDER BY s.availTill ASC
  1729. ")
  1730. ->setMaxResults(1)
  1731. ->setParameters([
  1732. 'course' => $courseId,
  1733. 'user' => $userId,
  1734. 'session' => $sessionId,
  1735. 'now' => new DateTime('UTC', new DateTimeZone('UTC')),
  1736. 'variable' => 'is_mandatory',
  1737. ])
  1738. ->getSingleResult();
  1739. } catch (Exception $e) {
  1740. $invitation = null;
  1741. }
  1742. if (!$invitation) {
  1743. return;
  1744. }
  1745. Display::addFlash(
  1746. Display::return_message(get_lang('A mandatory survey is waiting your answer. To enter the course, you must first complete the survey.'), 'warning')
  1747. );
  1748. $url = SurveyUtil::generateFillSurveyLink(
  1749. $invitation->getInvitationCode(),
  1750. api_get_course_info(),
  1751. api_get_session_id()
  1752. );
  1753. header('Location: '.$url);
  1754. exit;
  1755. }
  1756. /**
  1757. * This function empty surveys (invitations and answers).
  1758. *
  1759. * @param int $surveyId id of the survey to empty
  1760. *
  1761. * @return bool
  1762. */
  1763. public static function emptySurveyFromId($surveyId)
  1764. {
  1765. // Database table definitions
  1766. $surveyInvitationTable = Database:: get_course_table(TABLE_SURVEY_INVITATION);
  1767. $surveyAnswerTable = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  1768. $surveyTable = Database:: get_course_table(TABLE_SURVEY);
  1769. $surveyId = (int) $surveyId;
  1770. $surveyData = self::get_survey($surveyId);
  1771. if (empty($surveyData)) {
  1772. return false;
  1773. }
  1774. $surveyCode = $surveyData['survey_code'];
  1775. $courseId = (int) $surveyData['c_id'];
  1776. $sessionId = (int) $surveyData['session_id'];
  1777. $sql = "DELETE FROM $surveyInvitationTable
  1778. WHERE session_id = $sessionId AND c_id = $courseId AND survey_code = '$surveyCode' ";
  1779. Database::query($sql);
  1780. $sql = "DELETE FROM $surveyAnswerTable
  1781. WHERE survey_id = $surveyId AND c_id = $courseId ";
  1782. Database::query($sql);
  1783. $sql = "UPDATE $surveyTable
  1784. SET invited = 0, answered = 0
  1785. WHERE survey_id = $surveyId AND c_id = $courseId AND session_id = $sessionId ";
  1786. Database::query($sql);
  1787. return true;
  1788. }
  1789. /**
  1790. * This function copy survey specifying course id and session id where will be copied.
  1791. *
  1792. * @param int $surveyId
  1793. * @param int $targetCourseId target course id
  1794. * @param int $targetSessionId target session id
  1795. *
  1796. * @return bool|int when fails or return the new survey id
  1797. */
  1798. public static function copySurveySession($surveyId, $targetCourseId, $targetSessionId)
  1799. {
  1800. // Database table definitions
  1801. $surveyTable = Database::get_course_table(TABLE_SURVEY);
  1802. $surveyQuestionGroupTable = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  1803. $surveyQuestionTable = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1804. $surveyOptionsTable = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1805. $surveyId = (int) $surveyId;
  1806. $targetCourseId = (int) $targetCourseId;
  1807. $targetSessionId = (int) $targetSessionId;
  1808. $surveyData = self::get_survey($surveyId, 0, '', true);
  1809. if (empty($surveyData) || empty($targetCourseId)) {
  1810. return false;
  1811. }
  1812. $originalCourseId = $surveyData['c_id'];
  1813. $originalSessionId = $surveyData['session_id'];
  1814. $surveyData['code'] = self::generate_unique_code($surveyData['code']);
  1815. $surveyData['c_id'] = $targetCourseId;
  1816. $surveyData['session_id'] = $targetSessionId;
  1817. // Add a "Copy" suffix if copied inside the same course
  1818. if ($targetCourseId == $originalCourseId) {
  1819. $surveyData['title'] = $surveyData['title'].' '.get_lang('Copy');
  1820. }
  1821. unset($surveyData['iid']);
  1822. unset($surveyData['id']);
  1823. $newSurveyId = Database::insert($surveyTable, $surveyData);
  1824. if ($newSurveyId) {
  1825. $sql = "UPDATE $surveyTable SET survey_id = $newSurveyId
  1826. WHERE iid = $newSurveyId";
  1827. Database::query($sql);
  1828. $sql = "SELECT * FROM $surveyQuestionGroupTable
  1829. WHERE survey_id = $surveyId AND c_id = $originalCourseId ";
  1830. $res = Database::query($sql);
  1831. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1832. $params = [
  1833. 'c_id' => $targetCourseId,
  1834. 'name' => $row['name'],
  1835. 'description' => $row['description'],
  1836. 'survey_id' => $newSurveyId,
  1837. ];
  1838. $insertId = Database::insert($surveyQuestionGroupTable, $params);
  1839. if ($insertId) {
  1840. $sql = "UPDATE $surveyQuestionGroupTable SET id = iid WHERE iid = $insertId";
  1841. Database::query($sql);
  1842. $group_id[$row['id']] = $insertId;
  1843. }
  1844. }
  1845. // Get questions
  1846. $sql = "SELECT * FROM $surveyQuestionTable
  1847. WHERE survey_id = $surveyId AND c_id = $originalCourseId";
  1848. $res = Database::query($sql);
  1849. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1850. $params = [
  1851. 'c_id' => $targetCourseId,
  1852. 'survey_id' => $newSurveyId,
  1853. 'survey_question' => $row['survey_question'],
  1854. 'survey_question_comment' => $row['survey_question_comment'],
  1855. 'type' => $row['type'],
  1856. 'display' => $row['display'],
  1857. 'sort' => $row['sort'],
  1858. 'shared_question_id' => $row['shared_question_id'],
  1859. 'max_value' => $row['max_value'],
  1860. 'survey_group_pri' => $row['survey_group_pri'],
  1861. 'survey_group_sec1' => $row['survey_group_sec1'],
  1862. 'survey_group_sec2' => $row['survey_group_sec2'],
  1863. ];
  1864. if (api_get_configuration_value('allow_required_survey_questions')) {
  1865. if (isset($row['is_required'])) {
  1866. $params['is_required'] = $row['is_required'];
  1867. }
  1868. }
  1869. $insertId = Database::insert($surveyQuestionTable, $params);
  1870. if ($insertId) {
  1871. $sql = "UPDATE $surveyQuestionTable
  1872. SET question_id = iid
  1873. WHERE iid = $insertId";
  1874. Database::query($sql);
  1875. $question_id[$row['question_id']] = $insertId;
  1876. }
  1877. }
  1878. // Get questions options
  1879. $sql = "SELECT * FROM $surveyOptionsTable
  1880. WHERE survey_id = $surveyId AND c_id = $originalCourseId";
  1881. $res = Database::query($sql);
  1882. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1883. $params = [
  1884. 'c_id' => $targetCourseId,
  1885. 'question_id' => $question_id[$row['question_id']],
  1886. 'survey_id' => $newSurveyId,
  1887. 'option_text' => $row['option_text'],
  1888. 'sort' => $row['sort'],
  1889. 'value' => $row['value'],
  1890. ];
  1891. $insertId = Database::insert($surveyOptionsTable, $params);
  1892. if ($insertId) {
  1893. $sql = "UPDATE $surveyOptionsTable SET question_option_id = $insertId WHERE iid = $insertId";
  1894. Database::query($sql);
  1895. }
  1896. }
  1897. return $newSurveyId;
  1898. }
  1899. return false;
  1900. }
  1901. /**
  1902. * @param array $surveyData
  1903. *
  1904. * @return bool
  1905. */
  1906. public static function removeMultiplicateQuestions($surveyData)
  1907. {
  1908. if (empty($surveyData)) {
  1909. return false;
  1910. }
  1911. $surveyId = $surveyData['survey_id'];
  1912. $courseId = $surveyData['c_id'];
  1913. if (empty($surveyId) || empty($courseId)) {
  1914. return false;
  1915. }
  1916. $questions = self::get_questions($surveyId);
  1917. foreach ($questions as $question) {
  1918. // Questions marked with "geneated" were created using the "multiplicate" feature.
  1919. if ($question['survey_question_comment'] === 'generated') {
  1920. self::delete_survey_question($surveyId, $question['question_id']);
  1921. }
  1922. }
  1923. }
  1924. /**
  1925. * @param array $surveyData
  1926. *
  1927. * @return bool
  1928. */
  1929. public static function multiplicateQuestions($surveyData)
  1930. {
  1931. if (empty($surveyData)) {
  1932. return false;
  1933. }
  1934. $surveyId = $surveyData['survey_id'];
  1935. $courseId = $surveyData['c_id'];
  1936. if (empty($surveyId) || empty($courseId)) {
  1937. return false;
  1938. }
  1939. $questions = self::get_questions($surveyId);
  1940. $obj = new UserGroup();
  1941. $options['where'] = [' usergroup.course_id = ? ' => $courseId];
  1942. $classList = $obj->getUserGroupInCourse($options);
  1943. $classTag = '{{class_name}}';
  1944. $studentTag = '{{student_full_name}}';
  1945. $classCounter = 0;
  1946. foreach ($classList as $class) {
  1947. $className = $class['name'];
  1948. foreach ($questions as $question) {
  1949. $users = $obj->get_users_by_usergroup($class['id']);
  1950. if (empty($users)) {
  1951. continue;
  1952. }
  1953. $text = $question['question'];
  1954. if (strpos($text, $classTag) !== false) {
  1955. $replacedText = str_replace($classTag, $className, $text);
  1956. $values = [
  1957. 'c_id' => $courseId,
  1958. 'question_comment' => 'generated',
  1959. 'type' => $question['type'],
  1960. 'display' => $question['horizontalvertical'],
  1961. 'question' => $replacedText,
  1962. 'survey_id' => $surveyId,
  1963. 'question_id' => 0,
  1964. 'shared_question_id' => 0,
  1965. ];
  1966. self::save_question($surveyData, $values);
  1967. $classCounter++;
  1968. continue;
  1969. }
  1970. foreach ($users as $userId) {
  1971. $userInfo = api_get_user_info($userId);
  1972. if (strpos($text, $studentTag) !== false) {
  1973. $replacedText = str_replace($studentTag, $userInfo['complete_name'], $text);
  1974. $values = [
  1975. 'c_id' => $courseId,
  1976. 'question_comment' => 'generated',
  1977. 'type' => $question['type'],
  1978. 'display' => $question['horizontalvertical'],
  1979. 'maximum_score' => $question['maximum_score'],
  1980. 'question' => $replacedText,
  1981. 'survey_id' => $surveyId,
  1982. 'question_id' => 0,
  1983. 'shared_question_id' => 0,
  1984. ];
  1985. $answers = [];
  1986. if (!empty($question['answers'])) {
  1987. foreach ($question['answers'] as $answer) {
  1988. $replacedText = str_replace($studentTag, $userInfo['complete_name'], $answer);
  1989. $answers[] = $replacedText;
  1990. }
  1991. }
  1992. $values['answers'] = $answers;
  1993. self::save_question($surveyData, $values);
  1994. }
  1995. }
  1996. if ($classCounter < count($classList)) {
  1997. // Add end page
  1998. $values = [
  1999. 'c_id' => $courseId,
  2000. 'question_comment' => 'generated',
  2001. 'type' => 'pagebreak',
  2002. 'display' => 'horizontal',
  2003. 'question' => get_lang('Question for next class'),
  2004. 'survey_id' => $surveyId,
  2005. 'question_id' => 0,
  2006. 'shared_question_id' => 0,
  2007. ];
  2008. self::save_question($surveyData, $values);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. /**
  2014. * @param array $survey
  2015. *
  2016. * @return int
  2017. */
  2018. public static function getCountPages($survey)
  2019. {
  2020. if (empty($survey) || !isset($survey['iid'])) {
  2021. return 0;
  2022. }
  2023. $courseId = $survey['c_id'];
  2024. $surveyId = $survey['survey_id'];
  2025. $table = Database::get_course_table(TABLE_SURVEY_QUESTION);
  2026. // pagebreak
  2027. $sql = "SELECT COUNT(iid) FROM $table
  2028. WHERE
  2029. survey_question NOT LIKE '%{{%' AND
  2030. type = 'pagebreak' AND
  2031. c_id = $courseId AND
  2032. survey_id = $surveyId";
  2033. $result = Database::query($sql);
  2034. $numberPageBreaks = Database::result($result, 0, 0);
  2035. // No pagebreak
  2036. $sql = "SELECT COUNT(iid) FROM $table
  2037. WHERE
  2038. survey_question NOT LIKE '%{{%' AND
  2039. type != 'pagebreak' AND
  2040. c_id = $courseId AND
  2041. survey_id = $surveyId";
  2042. $result = Database::query($sql);
  2043. $countOfQuestions = Database::result($result, 0, 0);
  2044. if ($survey['one_question_per_page'] == 1) {
  2045. if (!empty($countOfQuestions)) {
  2046. return $countOfQuestions;
  2047. }
  2048. return 1;
  2049. }
  2050. if (empty($numberPageBreaks)) {
  2051. return 1;
  2052. }
  2053. return $numberPageBreaks + 1;
  2054. }
  2055. /**
  2056. * Check whether this survey has ended. If so, display message and exit rhis script.
  2057. *
  2058. * @param array $surveyData Survey data
  2059. */
  2060. public static function checkTimeAvailability($surveyData)
  2061. {
  2062. if (empty($surveyData)) {
  2063. api_not_allowed(true);
  2064. }
  2065. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  2066. $utcZone = new DateTimeZone('UTC');
  2067. $startDate = new DateTime($surveyData['start_date'], $utcZone);
  2068. $endDate = new DateTime($surveyData['end_date'], $utcZone);
  2069. $currentDate = new DateTime('now', $utcZone);
  2070. if (!$allowSurveyAvailabilityDatetime) {
  2071. $currentDate->modify('today');
  2072. }
  2073. if ($currentDate < $startDate) {
  2074. api_not_allowed(
  2075. true,
  2076. Display:: return_message(
  2077. get_lang('This survey is not yet available. Please try again later. Thank you.'),
  2078. 'warning',
  2079. false
  2080. )
  2081. );
  2082. }
  2083. if ($currentDate > $endDate) {
  2084. api_not_allowed(
  2085. true,
  2086. Display:: return_message(
  2087. get_lang('Sorry, this survey is not available anymore. Thank you for trying.'),
  2088. 'warning',
  2089. false
  2090. )
  2091. );
  2092. }
  2093. }
  2094. /**
  2095. * @param int $userId
  2096. * @param string $surveyCode
  2097. * @param int $courseId
  2098. * @param int $sessionId
  2099. * @param int $groupId
  2100. *
  2101. * @return array|CSurveyInvitation[]
  2102. */
  2103. public static function getUserInvitationsForSurveyInCourse(
  2104. $userId,
  2105. $surveyCode,
  2106. $courseId,
  2107. $sessionId = 0,
  2108. $groupId = 0
  2109. ) {
  2110. $invitationRepo = Database::getManager()->getRepository('ChamiloCourseBundle:CSurveyInvitation');
  2111. $invitations = $invitationRepo->findBy(
  2112. [
  2113. 'user' => $userId,
  2114. 'cId' => $courseId,
  2115. 'sessionId' => $sessionId,
  2116. 'groupId' => $groupId,
  2117. 'surveyCode' => $surveyCode,
  2118. ],
  2119. ['invitationDate' => 'DESC']
  2120. );
  2121. return $invitations;
  2122. }
  2123. /**
  2124. * @param array $userInfo
  2125. * @param int $answered (1 = answered 0 = not answered)
  2126. *
  2127. * @return string
  2128. */
  2129. public static function surveyReport($userInfo, $answered = 0)
  2130. {
  2131. $userId = isset($userInfo['user_id']) ? (int) $userInfo['user_id'] : 0;
  2132. $answered = (int) $answered;
  2133. if (empty($userId)) {
  2134. return '';
  2135. }
  2136. $em = Database::getManager();
  2137. $repo = $em->getRepository('ChamiloCourseBundle:CSurveyInvitation');
  2138. $repoSurvey = $em->getRepository('ChamiloCourseBundle:CSurvey');
  2139. $invitations = $repo->findBy(['user' => $userId, 'answered' => $answered]);
  2140. $mainUrl = api_get_path(WEB_CODE_PATH).'survey/survey.php?';
  2141. $content = '';
  2142. if (empty($answered)) {
  2143. $content .= Display::page_subheader(get_lang('Unanswered'));
  2144. } else {
  2145. $content .= Display::page_subheader(get_lang('Answered'));
  2146. }
  2147. if (!empty($invitations)) {
  2148. $table = new HTML_Table(['class' => 'table']);
  2149. $table->setHeaderContents(0, 0, get_lang('Survey name'));
  2150. $table->setHeaderContents(0, 1, get_lang('Course'));
  2151. if (empty($answered)) {
  2152. $table->setHeaderContents(0, 2, get_lang('Survey').' - '.get_lang('End Date'));
  2153. }
  2154. // Not answered
  2155. /** @var CSurveyInvitation $invitation */
  2156. $row = 1;
  2157. foreach ($invitations as $invitation) {
  2158. $courseId = $invitation->getCId();
  2159. $courseInfo = api_get_course_info_by_id($courseId);
  2160. $courseCode = $courseInfo['code'];
  2161. if (empty($courseInfo)) {
  2162. continue;
  2163. }
  2164. $sessionId = $invitation->getSessionId();
  2165. if (!empty($answered)) {
  2166. // check if user is subscribed to the course/session
  2167. if (empty($sessionId)) {
  2168. $subscribe = CourseManager::is_user_subscribed_in_course($userId, $courseCode);
  2169. } else {
  2170. $subscribe = CourseManager::is_user_subscribed_in_course($userId, $courseCode, true, $sessionId);
  2171. }
  2172. // User is not subscribe skip!
  2173. if (empty($subscribe)) {
  2174. continue;
  2175. }
  2176. }
  2177. $surveyCode = $invitation->getSurveyCode();
  2178. $survey = $repoSurvey->findOneBy([
  2179. 'cId' => $courseId,
  2180. 'sessionId' => $sessionId,
  2181. 'code' => $surveyCode,
  2182. ]);
  2183. if (empty($survey)) {
  2184. continue;
  2185. }
  2186. $url = $mainUrl.'survey_id='.$survey->getSurveyId().'&cidReq='.$courseCode.'&id_session='.$sessionId;
  2187. $title = $survey->getTitle();
  2188. $title = Display::url($title, $url);
  2189. if (!empty($sessionId)) {
  2190. $sessionInfo = api_get_session_info($sessionId);
  2191. $courseInfo['name'] .= ' ('.$sessionInfo['name'].')';
  2192. }
  2193. $surveyData = self::get_survey($survey->getSurveyId(), 0, $courseCode);
  2194. $table->setCellContents($row, 0, $title);
  2195. $table->setCellContents($row, 1, $courseInfo['name']);
  2196. if (empty($answered)) {
  2197. $table->setHeaderContents(
  2198. $row,
  2199. 2,
  2200. api_get_local_time(
  2201. $survey->getAvailTill(),
  2202. null,
  2203. null,
  2204. true,
  2205. false
  2206. )
  2207. );
  2208. }
  2209. if (!empty($answered) && $surveyData['anonymous'] == 0) {
  2210. $answers = SurveyUtil::displayCompleteReport(
  2211. $surveyData,
  2212. $userId,
  2213. false,
  2214. false,
  2215. false
  2216. );
  2217. $table->setCellContents(++$row, 0, $answers);
  2218. $table->setCellContents(++$row, 1, '');
  2219. }
  2220. $row++;
  2221. }
  2222. $content .= $table->toHtml();
  2223. } else {
  2224. $content .= Display::return_message(get_lang('No data available'));
  2225. }
  2226. return $content;
  2227. }
  2228. }