survey.lib.php 90 KB

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