surveyUtil.class.php 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CSurvey;
  4. use ChamiloSession as Session;
  5. /**
  6. * This class offers a series of general utility functions for survey querying and display.
  7. *
  8. * @package chamilo.survey
  9. */
  10. class SurveyUtil
  11. {
  12. /**
  13. * Checks whether the given survey has a pagebreak question as the first
  14. * or the last question.
  15. * If so, break the current process, displaying an error message.
  16. *
  17. * @param int $survey_id Survey ID (database ID)
  18. * @param bool $continue Optional. Whether to continue the current
  19. * process or exit when breaking condition found. Defaults to true (do not break).
  20. */
  21. public static function check_first_last_question($survey_id, $continue = true)
  22. {
  23. // Table definitions
  24. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  25. $course_id = api_get_course_int_id();
  26. $survey_id = (int) $survey_id;
  27. // Getting the information of the question
  28. $sql = "SELECT * FROM $tbl_survey_question
  29. WHERE c_id = $course_id AND survey_id='".$survey_id."'
  30. ORDER BY sort ASC";
  31. $result = Database::query($sql);
  32. $total = Database::num_rows($result);
  33. $counter = 1;
  34. $error = false;
  35. while ($row = Database::fetch_array($result, 'ASSOC')) {
  36. if ($counter == 1 && $row['type'] == 'pagebreak') {
  37. echo Display::return_message(get_lang('PagebreakNotFirst'), 'error', false);
  38. $error = true;
  39. }
  40. if ($counter == $total && $row['type'] == 'pagebreak') {
  41. echo Display::return_message(get_lang('PagebreakNotLast'), 'error', false);
  42. $error = true;
  43. }
  44. $counter++;
  45. }
  46. if (!$continue && $error) {
  47. Display::display_footer();
  48. exit;
  49. }
  50. }
  51. /**
  52. * This function removes an (or multiple) answer(s) of a user on a question of a survey.
  53. *
  54. * @param mixed The user id or email of the person who fills the survey
  55. * @param int The survey id
  56. * @param int The question id
  57. * @param int The option id
  58. *
  59. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  60. *
  61. * @version January 2007
  62. */
  63. public static function remove_answer($user, $survey_id, $question_id, $course_id)
  64. {
  65. $course_id = intval($course_id);
  66. // table definition
  67. $table = Database::get_course_table(TABLE_SURVEY_ANSWER);
  68. $sql = "DELETE FROM $table
  69. WHERE
  70. c_id = $course_id AND
  71. user = '".Database::escape_string($user)."' AND
  72. survey_id = '".intval($survey_id)."' AND
  73. question_id = '".intval($question_id)."'";
  74. Database::query($sql);
  75. }
  76. /**
  77. * This function stores an answer of a user on a question of a survey.
  78. *
  79. * @param mixed The user id or email of the person who fills the survey
  80. * @param int Survey id
  81. * @param int Question id
  82. * @param int Option id
  83. * @param string Option value
  84. * @param array $survey_data Survey data settings
  85. *
  86. * @return bool False if insufficient data, true otherwise
  87. *
  88. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  89. *
  90. * @version January 2007
  91. */
  92. public static function store_answer(
  93. $user,
  94. $survey_id,
  95. $question_id,
  96. $option_id,
  97. $option_value,
  98. $survey_data
  99. ) {
  100. // If the question_id is empty, don't store an answer
  101. if (empty($question_id)) {
  102. return false;
  103. }
  104. // Table definition
  105. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  106. // Make the survey anonymous
  107. if ($survey_data['anonymous'] == 1) {
  108. $surveyUser = Session::read('surveyuser');
  109. if (empty($surveyUser)) {
  110. $user = md5($user.time());
  111. Session::write('surveyuser', $user);
  112. } else {
  113. $user = Session::read('surveyuser');
  114. }
  115. }
  116. $course_id = $survey_data['c_id'];
  117. $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
  118. $course_id,
  119. '".Database::escape_string($user)."',
  120. '".Database::escape_string($survey_id)."',
  121. '".Database::escape_string($question_id)."',
  122. '".Database::escape_string($option_id)."',
  123. '".Database::escape_string($option_value)."'
  124. )";
  125. Database::query($sql);
  126. $insertId = Database::insert_id();
  127. $sql = "UPDATE $table_survey_answer SET answer_id = $insertId
  128. WHERE iid = $insertId";
  129. Database::query($sql);
  130. return true;
  131. }
  132. /**
  133. * This function checks the parameters that are used in this page.
  134. *
  135. * @return string $people_filled The header, an error and the footer if any parameter fails, else it returns true
  136. *
  137. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  138. *
  139. * @version February 2007
  140. */
  141. public static function check_parameters($people_filled)
  142. {
  143. $error = false;
  144. // Getting the survey data
  145. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  146. // $_GET['survey_id'] has to be numeric
  147. if (!is_numeric($_GET['survey_id'])) {
  148. $error = get_lang('IllegalSurveyId');
  149. }
  150. // $_GET['action']
  151. $allowed_actions = [
  152. 'overview',
  153. 'questionreport',
  154. 'userreport',
  155. 'comparativereport',
  156. 'completereport',
  157. 'deleteuserreport',
  158. ];
  159. if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
  160. $error = get_lang('ActionNotAllowed');
  161. }
  162. // User report
  163. if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
  164. if ($survey_data['anonymous'] == 0) {
  165. foreach ($people_filled as $key => &$value) {
  166. $people_filled_userids[] = $value['invited_user'];
  167. }
  168. } else {
  169. $people_filled_userids = $people_filled;
  170. }
  171. if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
  172. $error = get_lang('UnknowUser');
  173. }
  174. }
  175. // Question report
  176. if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
  177. if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
  178. $error = get_lang('UnknowQuestion');
  179. }
  180. }
  181. if ($error) {
  182. $tool_name = get_lang('Reporting');
  183. Display::addFlash(
  184. Display::return_message(
  185. get_lang('Error').': '.$error,
  186. 'error',
  187. false
  188. )
  189. );
  190. Display::display_header($tool_name);
  191. Display::display_footer();
  192. exit;
  193. } else {
  194. return true;
  195. }
  196. }
  197. /**
  198. * This function deals with the action handling.
  199. *
  200. * @param array $survey_data
  201. * @param array $people_filled
  202. *
  203. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  204. *
  205. * @version February 2007
  206. */
  207. public static function handle_reporting_actions($survey_data, $people_filled)
  208. {
  209. $action = isset($_GET['action']) ? $_GET['action'] : '';
  210. // Getting the number of question
  211. $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
  212. // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
  213. $my_temp_questions_data = $temp_questions_data == null ? [] : $temp_questions_data;
  214. $questions_data = [];
  215. foreach ($my_temp_questions_data as $key => &$value) {
  216. if ($value['type'] != 'pagebreak') {
  217. $questions_data[$value['sort']] = $value;
  218. }
  219. }
  220. // Counting the number of questions that are relevant for the reporting
  221. $survey_data['number_of_questions'] = count($questions_data);
  222. switch ($action) {
  223. case 'questionreport':
  224. self::display_question_report($survey_data);
  225. break;
  226. case 'userreport':
  227. self::displayUserReport($survey_data, $people_filled);
  228. break;
  229. case 'comparativereport':
  230. self::display_comparative_report();
  231. break;
  232. case 'completereport':
  233. echo self::displayCompleteReport($survey_data);
  234. break;
  235. case 'deleteuserreport':
  236. self::delete_user_report($_GET['survey_id'], $_GET['user']);
  237. break;
  238. }
  239. }
  240. /**
  241. * This function deletes the report of an user who wants to retake the survey.
  242. *
  243. * @param int $survey_id
  244. * @param int $user_id
  245. *
  246. * @author Christian Fasanando Flores <christian.fasanando@dokeos.com>
  247. *
  248. * @version November 2008
  249. */
  250. public static function delete_user_report($survey_id, $user_id)
  251. {
  252. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  253. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  254. $table_survey = Database::get_course_table(TABLE_SURVEY);
  255. $course_id = api_get_course_int_id();
  256. $survey_id = (int) $survey_id;
  257. $user_id = Database::escape_string($user_id);
  258. if (!empty($survey_id) && !empty($user_id)) {
  259. // delete data from survey_answer by user_id and survey_id
  260. $sql = "DELETE FROM $table_survey_answer
  261. WHERE c_id = $course_id AND survey_id = '".$survey_id."' AND user = '".$user_id."'";
  262. Database::query($sql);
  263. // update field answered from survey_invitation by user_id and survey_id
  264. $sql = "UPDATE $table_survey_invitation SET answered = '0'
  265. WHERE
  266. c_id = $course_id AND
  267. survey_code = (
  268. SELECT code FROM $table_survey
  269. WHERE
  270. c_id = $course_id AND
  271. survey_id = '".$survey_id."'
  272. ) AND
  273. user = '".$user_id."'";
  274. $result = Database::query($sql);
  275. }
  276. if ($result !== false) {
  277. $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
  278. <a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='
  279. .$survey_id.'">'.
  280. get_lang('GoBack').'</a>';
  281. echo Display::return_message($message, 'confirmation', false);
  282. }
  283. }
  284. /**
  285. * @param array $survey_data
  286. * @param array $people_filled
  287. *
  288. * @return string
  289. */
  290. public static function displayUserReportForm($survey_data, $people_filled)
  291. {
  292. $surveyId = $survey_data['survey_id'];
  293. if (empty($survey_data)) {
  294. return '';
  295. }
  296. // Step 1: selection of the user
  297. echo "<script>
  298. function jumpMenu(targ,selObj,restore) {
  299. eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
  300. if (restore) selObj.selectedIndex=0;
  301. }
  302. </script>";
  303. echo get_lang('SelectUserWhoFilledSurvey').'<br />';
  304. echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
  305. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='
  306. .Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'">'
  307. .get_lang('SelectUser').'</option>';
  308. foreach ($people_filled as $key => &$person) {
  309. if ($survey_data['anonymous'] == 0) {
  310. $name = $person['user_info']['complete_name_with_username'];
  311. $id = $person['user_id'];
  312. if ($id == '') {
  313. $id = $person['invited_user'];
  314. $name = $person['invited_user'];
  315. }
  316. } else {
  317. $name = get_lang('Anonymous').' '.($key + 1);
  318. $id = $person;
  319. }
  320. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='
  321. .Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&user='
  322. .Security::remove_XSS($id).'&'.api_get_cidreq().'" ';
  323. if (isset($_GET['user']) && $_GET['user'] == $id) {
  324. echo 'selected="selected"';
  325. }
  326. echo '>'.$name.'</option>';
  327. }
  328. echo '</select>';
  329. }
  330. /**
  331. * @param int $userId
  332. * @param array $survey_data
  333. * @param bool $addMessage
  334. */
  335. public static function displayUserReportAnswers($userId, $survey_data, $addMessage = true)
  336. {
  337. // Database table definitions
  338. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  339. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  340. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  341. $course_id = (int) $survey_data['c_id'];
  342. $surveyId = (int) $survey_data['survey_id'];
  343. $userId = Database::escape_string($userId);
  344. $content = '';
  345. // Step 2: displaying the survey and the answer of the selected users
  346. if (!empty($userId)) {
  347. if ($addMessage) {
  348. $content .= Display::return_message(
  349. get_lang('AllQuestionsOnOnePage'),
  350. 'normal',
  351. false
  352. );
  353. }
  354. // Getting all the questions and options
  355. $sql = "SELECT
  356. survey_question.question_id,
  357. survey_question.survey_id,
  358. survey_question.survey_question,
  359. survey_question.display,
  360. survey_question.max_value,
  361. survey_question.sort,
  362. survey_question.type,
  363. survey_question_option.question_option_id,
  364. survey_question_option.option_text,
  365. survey_question_option.sort as option_sort
  366. FROM $table_survey_question survey_question
  367. LEFT JOIN $table_survey_question_option survey_question_option
  368. ON
  369. survey_question.question_id = survey_question_option.question_id AND
  370. survey_question_option.c_id = $course_id
  371. WHERE
  372. survey_question NOT LIKE '%{{%' AND
  373. survey_question.survey_id = '".$surveyId."' AND
  374. survey_question.c_id = $course_id
  375. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  376. $result = Database::query($sql);
  377. while ($row = Database::fetch_array($result, 'ASSOC')) {
  378. if ($row['type'] != 'pagebreak') {
  379. $questions[$row['sort']]['question_id'] = $row['question_id'];
  380. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  381. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  382. $questions[$row['sort']]['display'] = $row['display'];
  383. $questions[$row['sort']]['type'] = $row['type'];
  384. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  385. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  386. }
  387. }
  388. // Getting all the answers of the user
  389. $sql = "SELECT * FROM $table_survey_answer
  390. WHERE
  391. c_id = $course_id AND
  392. survey_id = '".$surveyId."' AND
  393. user = '".$userId."'";
  394. $result = Database::query($sql);
  395. while ($row = Database::fetch_array($result, 'ASSOC')) {
  396. $answers[$row['question_id']][] = $row['option_id'];
  397. $all_answers[$row['question_id']][] = $row;
  398. }
  399. // Displaying all the questions
  400. foreach ($questions as &$question) {
  401. // If the question type is a scoring then we have to format the answers differently
  402. switch ($question['type']) {
  403. case 'score':
  404. $finalAnswer = [];
  405. if (is_array($question) && is_array($all_answers)) {
  406. foreach ($all_answers[$question['question_id']] as $key => &$answer_array) {
  407. $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
  408. }
  409. }
  410. break;
  411. case 'multipleresponse':
  412. $finalAnswer = isset($answers[$question['question_id']])
  413. ? $answers[$question['question_id']]
  414. : '';
  415. break;
  416. default:
  417. $finalAnswer = '';
  418. if (isset($all_answers[$question['question_id']])) {
  419. $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
  420. }
  421. break;
  422. }
  423. $ch_type = 'ch_'.$question['type'];
  424. if (class_exists($ch_type)) {
  425. /** @var survey_question $display */
  426. $display = new $ch_type();
  427. $url = api_get_self();
  428. $form = new FormValidator('question', 'post', $url);
  429. $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
  430. $form->addHtml($question['survey_question']);
  431. $display->render($form, $question, $finalAnswer);
  432. $form->addHtml('</div></div>');
  433. $content .= $form->returnForm();
  434. }
  435. }
  436. }
  437. return $content;
  438. }
  439. /**
  440. * This function displays the user report which is basically nothing more
  441. * than a one-page display of all the questions
  442. * of the survey that is filled with the answers of the person who filled the survey.
  443. *
  444. * @return string html code of the one-page survey with the answers of the selected user
  445. *
  446. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  447. *
  448. * @version February 2007 - Updated March 2008
  449. */
  450. public static function displayUserReport($survey_data, $people_filled, $addActionBar = true)
  451. {
  452. if (empty($survey_data)) {
  453. return '';
  454. }
  455. $surveyId = $survey_data['survey_id'];
  456. $reportingUrl = api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq();
  457. // Actions bar
  458. if ($addActionBar) {
  459. echo '<div class="actions">';
  460. echo '<a href="'.$reportingUrl.'">'.
  461. Display::return_icon(
  462. 'back.png',
  463. get_lang('BackTo').' '.get_lang('ReportingOverview'),
  464. '',
  465. ICON_SIZE_MEDIUM
  466. )
  467. .'</a>';
  468. if (isset($_GET['user'])) {
  469. if (api_is_allowed_to_edit()) {
  470. // The delete link
  471. echo '<a href="'.$reportingUrl.'&action=deleteuserreport&user='.Security::remove_XSS($_GET['user']).'" >'.
  472. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_MEDIUM).'</a>';
  473. }
  474. // Export the user report
  475. echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'
  476. .Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM).'</a> ';
  477. echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'
  478. .Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), '', ICON_SIZE_MEDIUM).'</a> ';
  479. echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='
  480. .Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='
  481. .Security::remove_XSS($_GET['user']).'">';
  482. echo '<input type="hidden" name="export_report" value="export_report">';
  483. echo '<input type="hidden" name="export_format" value="csv">';
  484. echo '</form>';
  485. echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='
  486. .Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='
  487. .Security::remove_XSS($_GET['user']).'">';
  488. echo '<input type="hidden" name="export_report" value="export_report">';
  489. echo '<input type="hidden" name="export_format" value="xls">';
  490. echo '</form>';
  491. echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='
  492. .Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
  493. }
  494. echo '</div>';
  495. }
  496. echo self::displayUserReportForm($survey_data, $people_filled);
  497. if (isset($_GET['user'])) {
  498. echo self::displayUserReportAnswers($_GET['user'], $survey_data);
  499. }
  500. }
  501. /**
  502. * This function displays the report by question.
  503. *
  504. * It displays a table with all the options of the question and the number of users who have answered positively on
  505. * the option. The number of users who answered positive on a given option is expressed in an absolute number, in a
  506. * percentage of the total and graphically using bars By clicking on the absolute number you get a list with the
  507. * persons who have answered this. You can then click on the name of the person and you will then go to the report
  508. * by user where you see all the answers of that user.
  509. *
  510. * @param array All the survey data
  511. *
  512. * @return string html code that displays the report by question
  513. *
  514. * @todo allow switching between horizontal and vertical.
  515. * @todo multiple response: percentage are probably not OK
  516. * @todo the question and option text have to be shortened and should expand when the user clicks on it.
  517. * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
  518. *
  519. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  520. *
  521. * @version February 2007 - Updated March 2008
  522. */
  523. public static function display_question_report($survey_data)
  524. {
  525. $singlePage = isset($_GET['single_page']) ? (int) $_GET['single_page'] : 0;
  526. // Determining the offset of the sql statement (the n-th question of the survey)
  527. $offset = !isset($_GET['question']) ? 0 : (int) $_GET['question'];
  528. $currentQuestion = isset($_GET['question']) ? (int) $_GET['question'] : 0;
  529. $surveyId = (int) $_GET['survey_id'];
  530. $action = Security::remove_XSS($_GET['action']);
  531. $course_id = api_get_course_int_id();
  532. // Database table definitions
  533. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  534. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  535. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  536. $questions = [];
  537. echo '<div class="actions">';
  538. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
  539. Display::return_icon(
  540. 'back.png',
  541. get_lang('BackTo').' '.get_lang('ReportingOverview'),
  542. '',
  543. ICON_SIZE_MEDIUM
  544. ).'</a>';
  545. echo '</div>';
  546. if ($survey_data['number_of_questions'] > 0) {
  547. $limitStatement = null;
  548. if (!$singlePage) {
  549. echo '<div id="question_report_questionnumbers" class="pagination">';
  550. if ($currentQuestion != 0) {
  551. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&'
  552. .api_get_cidreq().'&survey_id='.$surveyId.'&question='.($offset - 1).'">'
  553. .get_lang('PreviousQuestion').'</a></li>';
  554. }
  555. for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
  556. if ($offset != $i - 1) {
  557. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&'
  558. .api_get_cidreq().'&survey_id='.$surveyId.'&question='.($i - 1).'">'.$i.'</a></li>';
  559. } else {
  560. echo '<li class="disabled"s><a href="#">'.$i.'</a></li>';
  561. }
  562. }
  563. if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
  564. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&'
  565. .api_get_cidreq().'&survey_id='.$surveyId.'&question='.($offset + 1).'">'
  566. .get_lang('NextQuestion').'</li></a>';
  567. }
  568. echo '</ul>';
  569. echo '</div>';
  570. $limitStatement = " LIMIT $offset, 1";
  571. }
  572. // Getting the question information
  573. $sql = "SELECT * FROM $table_survey_question
  574. WHERE
  575. c_id = $course_id AND
  576. survey_id='".$surveyId."' AND
  577. survey_question NOT LIKE '%{{%' AND
  578. type <>'pagebreak'
  579. ORDER BY sort ASC
  580. $limitStatement";
  581. $result = Database::query($sql);
  582. while ($row = Database::fetch_array($result)) {
  583. $questions[$row['question_id']] = $row;
  584. }
  585. }
  586. foreach ($questions as $question) {
  587. $chartData = [];
  588. $options = [];
  589. $questionId = (int) $question['question_id'];
  590. echo '<div class="title-question">';
  591. echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
  592. echo '</div>';
  593. if ($question['type'] == 'score') {
  594. /** @todo This function should return the options as this is needed further in the code */
  595. $options = self::display_question_report_score($survey_data, $question, $offset);
  596. } elseif ($question['type'] == 'open' || $question['type'] == 'comment') {
  597. /** @todo Also get the user who has answered this */
  598. $sql = "SELECT * FROM $table_survey_answer
  599. WHERE
  600. c_id = $course_id AND
  601. survey_id='".$surveyId."' AND
  602. question_id = '".$questionId."'";
  603. $result = Database::query($sql);
  604. while ($row = Database::fetch_array($result, 'ASSOC')) {
  605. echo $row['option_id'].'<hr noshade="noshade" size="1" />';
  606. }
  607. } else {
  608. // Getting the options ORDER BY sort ASC
  609. $sql = "SELECT * FROM $table_survey_question_option
  610. WHERE
  611. c_id = $course_id AND
  612. survey_id='".$surveyId."'
  613. AND question_id = '".$questionId."'
  614. ORDER BY sort ASC";
  615. $result = Database::query($sql);
  616. while ($row = Database::fetch_array($result, 'ASSOC')) {
  617. $options[$row['question_option_id']] = $row;
  618. }
  619. // Getting the answers
  620. $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
  621. WHERE
  622. c_id = $course_id AND
  623. survey_id='".$surveyId."'
  624. AND question_id = '".$questionId."'
  625. GROUP BY option_id, value";
  626. $result = Database::query($sql);
  627. $number_of_answers = [];
  628. $data = [];
  629. while ($row = Database::fetch_array($result, 'ASSOC')) {
  630. if (!isset($number_of_answers[$row['question_id']])) {
  631. $number_of_answers[$row['question_id']] = 0;
  632. }
  633. $number_of_answers[$row['question_id']] += $row['total'];
  634. $data[$row['option_id']] = $row;
  635. }
  636. foreach ($options as $option) {
  637. $optionText = strip_tags($option['option_text']);
  638. $optionText = html_entity_decode($optionText);
  639. $votes = isset($data[$option['question_option_id']]['total']) ?
  640. $data[$option['question_option_id']]['total'] : '0';
  641. array_push($chartData, ['option' => $optionText, 'votes' => $votes]);
  642. }
  643. $chartContainerId = 'chartContainer'.$question['question_id'];
  644. echo '<div id="'.$chartContainerId.'" class="col-md-12">';
  645. echo self::drawChart($chartData, false, $chartContainerId);
  646. // displaying the table: headers
  647. echo '<table class="display-survey table">';
  648. echo ' <tr>';
  649. echo ' <th>&nbsp;</th>';
  650. echo ' <th>'.get_lang('AbsoluteTotal').'</th>';
  651. echo ' <th>'.get_lang('Percentage').'</th>';
  652. echo ' <th>'.get_lang('VisualRepresentation').'</th>';
  653. echo ' <tr>';
  654. // Displaying the table: the content
  655. if (is_array($options)) {
  656. foreach ($options as $key => &$value) {
  657. $absolute_number = null;
  658. if (isset($data[$value['question_option_id']])) {
  659. $absolute_number = $data[$value['question_option_id']]['total'];
  660. }
  661. if ($question['type'] == 'percentage' && empty($absolute_number)) {
  662. continue;
  663. }
  664. $number_of_answers[$option['question_id']] = isset($number_of_answers[$option['question_id']])
  665. ? $number_of_answers[$option['question_id']]
  666. : 0;
  667. if ($number_of_answers[$option['question_id']] == 0) {
  668. $answers_number = 0;
  669. } else {
  670. $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
  671. }
  672. echo ' <tr>';
  673. echo ' <td class="center">'.$value['option_text'].'</td>';
  674. echo ' <td class="center">';
  675. if ($absolute_number != 0) {
  676. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action
  677. .'&survey_id='.$surveyId.'&question='.$offset.'&viewoption='
  678. .$value['question_option_id'].'">'.$absolute_number.'</a>';
  679. } else {
  680. echo '0';
  681. }
  682. echo ' </td>';
  683. echo ' <td class="center">'.round($answers_number, 2).' %</td>';
  684. echo ' <td class="center">';
  685. $size = $answers_number * 2;
  686. if ($size > 0) {
  687. echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'
  688. .$size.'px">&nbsp;</div>';
  689. } else {
  690. echo '<div style="text-align: left;">'.get_lang("NoDataAvailable").'</div>';
  691. }
  692. echo ' </td>';
  693. echo ' </tr>';
  694. }
  695. }
  696. $optionResult = '';
  697. if (isset($option['question_id']) && isset($number_of_answers[$option['question_id']])) {
  698. if ($number_of_answers[$option['question_id']] == 0) {
  699. $optionResult = '0';
  700. } else {
  701. $optionResult = $number_of_answers[$option['question_id']];
  702. }
  703. }
  704. // displaying the table: footer (totals)
  705. echo ' <tr>';
  706. echo ' <td class="total"><b>'.get_lang('Total').'</b></td>';
  707. echo ' <td class="total"><b>'.$optionResult.'</b></td>';
  708. echo ' <td class="total">&nbsp;</td>';
  709. echo ' <td class="total">&nbsp;</td>';
  710. echo ' </tr>';
  711. echo '</table>';
  712. echo '</div>';
  713. }
  714. }
  715. if (isset($_GET['viewoption'])) {
  716. echo '<div class="answered-people">';
  717. echo '<h4>'.get_lang('PeopleWhoAnswered').': '
  718. .strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
  719. if (is_numeric($_GET['value'])) {
  720. $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
  721. }
  722. $sql = "SELECT user FROM $table_survey_answer
  723. WHERE
  724. c_id = $course_id AND
  725. option_id = '".Database::escape_string($_GET['viewoption'])."'
  726. $sql_restriction";
  727. $result = Database::query($sql);
  728. echo '<ul>';
  729. while ($row = Database::fetch_array($result, 'ASSOC')) {
  730. $user_info = api_get_user_info($row['user']);
  731. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='
  732. .$surveyId.'&user='.$row['user'].'">'
  733. .$user_info['complete_name_with_username']
  734. .'</a></li>';
  735. }
  736. echo '</ul>';
  737. echo '</div>';
  738. }
  739. }
  740. /**
  741. * Display score data about a survey question.
  742. *
  743. * @param array Question info
  744. * @param int The offset of results shown
  745. */
  746. public static function display_question_report_score($survey_data, $question, $offset)
  747. {
  748. // Database table definitions
  749. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  750. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  751. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  752. $course_id = api_get_course_int_id();
  753. // Getting the options
  754. $sql = "SELECT * FROM $table_survey_question_option
  755. WHERE
  756. c_id = $course_id AND
  757. survey_id='".intval($_GET['survey_id'])."' AND
  758. question_id = '".intval($question['question_id'])."'
  759. ORDER BY sort ASC";
  760. $result = Database::query($sql);
  761. while ($row = Database::fetch_array($result)) {
  762. $options[$row['question_option_id']] = $row;
  763. }
  764. // Getting the answers
  765. $sql = "SELECT *, count(answer_id) as total
  766. FROM $table_survey_answer
  767. WHERE
  768. c_id = $course_id AND
  769. survey_id='".intval($_GET['survey_id'])."' AND
  770. question_id = '".Database::escape_string($question['question_id'])."'
  771. GROUP BY option_id, value";
  772. $result = Database::query($sql);
  773. $number_of_answers = 0;
  774. while ($row = Database::fetch_array($result)) {
  775. $number_of_answers += $row['total'];
  776. $data[$row['option_id']][$row['value']] = $row;
  777. }
  778. $chartData = [];
  779. foreach ($options as $option) {
  780. $optionText = strip_tags($option['option_text']);
  781. $optionText = html_entity_decode($optionText);
  782. for ($i = 1; $i <= $question['max_value']; $i++) {
  783. $votes = $data[$option['question_option_id']][$i]['total'];
  784. if (empty($votes)) {
  785. $votes = '0';
  786. }
  787. array_push(
  788. $chartData,
  789. [
  790. 'serie' => $optionText,
  791. 'option' => $i,
  792. 'votes' => $votes,
  793. ]
  794. );
  795. }
  796. }
  797. echo '<div id="chartContainer" class="col-md-12">';
  798. echo self::drawChart($chartData, true);
  799. echo '</div>';
  800. // Displaying the table: headers
  801. echo '<table class="data_table">';
  802. echo ' <tr>';
  803. echo ' <th>&nbsp;</th>';
  804. echo ' <th>'.get_lang('Score').'</th>';
  805. echo ' <th>'.get_lang('AbsoluteTotal').'</th>';
  806. echo ' <th>'.get_lang('Percentage').'</th>';
  807. echo ' <th>'.get_lang('VisualRepresentation').'</th>';
  808. echo ' <tr>';
  809. // Displaying the table: the content
  810. foreach ($options as $key => &$value) {
  811. for ($i = 1; $i <= $question['max_value']; $i++) {
  812. $absolute_number = $data[$value['question_option_id']][$i]['total'];
  813. echo ' <tr>';
  814. echo ' <td>'.$value['option_text'].'</td>';
  815. echo ' <td>'.$i.'</td>';
  816. echo ' <td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action
  817. .'&survey_id='.intval($_GET['survey_id']).'&question='.Security::remove_XSS($offset)
  818. .'&viewoption='.$value['question_option_id'].'&value='.$i.'">'.$absolute_number.'</a></td>';
  819. echo ' <td>'.round($absolute_number / $number_of_answers * 100, 2).' %</td>';
  820. echo ' <td>';
  821. $size = ($absolute_number / $number_of_answers * 100 * 2);
  822. if ($size > 0) {
  823. echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
  824. }
  825. echo ' </td>';
  826. echo ' </tr>';
  827. }
  828. }
  829. // Displaying the table: footer (totals)
  830. echo ' <tr>';
  831. echo ' <td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
  832. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  833. echo ' <td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
  834. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  835. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  836. echo ' </tr>';
  837. echo '</table>';
  838. }
  839. /**
  840. * This functions displays the complete reporting.
  841. *
  842. * @param array $survey_data
  843. * @param int $userId
  844. * @param bool $addActionBar
  845. * @param bool $addFilters
  846. * @param bool $addExtraFields
  847. *
  848. * @return string
  849. */
  850. public static function displayCompleteReport(
  851. $survey_data,
  852. $userId = 0,
  853. $addActionBar = true,
  854. $addFilters = true,
  855. $addExtraFields = true
  856. ) {
  857. // Database table definitions
  858. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  859. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  860. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  861. $surveyId = (int) $survey_data['survey_id'];
  862. $course_id = (int) $survey_data['c_id'];
  863. if (empty($surveyId) || empty($course_id)) {
  864. return '';
  865. }
  866. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  867. $content = '';
  868. if ($addActionBar) {
  869. $content .= '<div class="actions">';
  870. $content .= '<a
  871. href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'
  872. .Display::return_icon(
  873. 'back.png',
  874. get_lang('BackTo').' '.get_lang('ReportingOverview'),
  875. [],
  876. ICON_SIZE_MEDIUM
  877. )
  878. .'</a>';
  879. $content .= '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">'
  880. .Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM).'</a>';
  881. $content .= '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">'
  882. .Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), '', ICON_SIZE_MEDIUM).'</a>';
  883. $content .= '</div>';
  884. // The form
  885. $content .= '<form id="form1a" name="form1a" method="post" action="'.api_get_self(
  886. ).'?action='.$action.'&survey_id='
  887. .$surveyId.'&'.api_get_cidreq().'">';
  888. $content .= '<input type="hidden" name="export_report" value="export_report">';
  889. $content .= '<input type="hidden" name="export_format" value="csv">';
  890. $content .= '</form>';
  891. $content .= '<form id="form1b" name="form1b" method="post" action="'.api_get_self(
  892. ).'?action='.$action.'&survey_id='
  893. .$surveyId.'&'.api_get_cidreq().'">';
  894. $content .= '<input type="hidden" name="export_report" value="export_report">';
  895. $content .= '<input type="hidden" name="export_format" value="xls">';
  896. $content .= '</form>';
  897. }
  898. $content .= '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='
  899. .$surveyId.'&'.api_get_cidreq().'">';
  900. // The table
  901. $content .= '<br /><table class="data_table" border="1">';
  902. // Getting the number of options per question
  903. $content .= ' <tr>';
  904. $content .= ' <th>';
  905. if ($addFilters) {
  906. if ((isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  907. (isset($_POST['export_report']) && $_POST['export_report'])
  908. ) {
  909. $content .= '<button class="cancel"
  910. type="submit"
  911. name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.
  912. get_lang('ResetQuestionFilter').'</button>';
  913. }
  914. $content .= '<button
  915. class = "save"
  916. type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.
  917. get_lang('SubmitQuestionFilter').'</button>';
  918. $content .= '</th>';
  919. }
  920. $display_extra_user_fields = false;
  921. if ($addExtraFields) {
  922. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  923. isset($_POST['export_report']) && $_POST['export_report']) ||
  924. !empty($_POST['fields_filter'])
  925. ) {
  926. // Show user fields section with a big th colspan that spans over all fields
  927. $extra_user_fields = UserManager::get_extra_fields(
  928. 0,
  929. 0,
  930. 5,
  931. 'ASC',
  932. false,
  933. true
  934. );
  935. $num = count($extra_user_fields);
  936. if ($num > 0) {
  937. $content .= '<th '.($num > 0 ? ' colspan="'.$num.'"' : '').'>';
  938. $content .= '<label>';
  939. if ($addFilters) {
  940. $content .= '<input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
  941. }
  942. $content .= get_lang('UserFields');
  943. $content .= '</label>';
  944. $content .= '</th>';
  945. $display_extra_user_fields = true;
  946. }
  947. }
  948. }
  949. $sql = "SELECT
  950. q.question_id,
  951. q.type,
  952. q.survey_question,
  953. count(o.question_option_id) as number_of_options
  954. FROM $table_survey_question q
  955. LEFT JOIN $table_survey_question_option o
  956. ON q.question_id = o.question_id AND q.c_id = o.c_id
  957. WHERE
  958. survey_question NOT LIKE '%{{%' AND
  959. q.survey_id = '".$surveyId."' AND
  960. q.c_id = $course_id
  961. GROUP BY q.question_id
  962. ORDER BY q.sort ASC";
  963. $result = Database::query($sql);
  964. $questions = [];
  965. while ($row = Database::fetch_array($result)) {
  966. // We show the questions if
  967. // 1. there is no question filter and the export button has not been clicked
  968. // 2. there is a quesiton filter but the question is selected for display
  969. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  970. (is_array($_POST['questions_filter']) &&
  971. in_array($row['question_id'], $_POST['questions_filter']))
  972. ) {
  973. // We do not show comment and pagebreak question types
  974. if ($row['type'] != 'pagebreak') {
  975. $content .= ' <th';
  976. if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
  977. $content .= ' colspan="'.$row['number_of_options'].'"';
  978. }
  979. $content .= '>';
  980. $content .= '<label>';
  981. if ($addFilters) {
  982. $content .= '<input
  983. type="checkbox"
  984. name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/>';
  985. }
  986. $content .= $row['survey_question'];
  987. $content .= '</label>';
  988. $content .= '</th>';
  989. }
  990. // No column at all if it's not a question
  991. }
  992. $questions[$row['question_id']] = $row;
  993. }
  994. $content .= ' </tr>';
  995. // Getting all the questions and options
  996. $content .= ' <tr>';
  997. $content .= ' <th>&nbsp;</th>'; // the user column
  998. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  999. isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])
  1000. ) {
  1001. if ($addExtraFields) {
  1002. // show the fields names for user fields
  1003. foreach ($extra_user_fields as &$field) {
  1004. $content .= '<th>'.$field[3].'</th>';
  1005. }
  1006. }
  1007. }
  1008. // cells with option (none for open question)
  1009. $sql = "SELECT
  1010. sq.question_id,
  1011. sq.survey_id,
  1012. sq.survey_question,
  1013. sq.display,
  1014. sq.sort,
  1015. sq.type,
  1016. sqo.question_option_id,
  1017. sqo.option_text,
  1018. sqo.sort as option_sort
  1019. FROM $table_survey_question sq
  1020. LEFT JOIN $table_survey_question_option sqo
  1021. ON sq.question_id = sqo.question_id AND sq.c_id = sqo.c_id
  1022. WHERE
  1023. survey_question NOT LIKE '%{{%' AND
  1024. sq.survey_id = '".$surveyId."' AND
  1025. sq.c_id = $course_id
  1026. ORDER BY sq.sort ASC, sqo.sort ASC";
  1027. $result = Database::query($sql);
  1028. $display_percentage_header = 1;
  1029. $possible_answers = [];
  1030. // in order to display only once the cell option (and not 100 times)
  1031. while ($row = Database::fetch_array($result)) {
  1032. // We show the options if
  1033. // 1. there is no question filter and the export button has not been clicked
  1034. // 2. there is a question filter but the question is selected for display
  1035. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  1036. (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
  1037. ) {
  1038. // we do not show comment and pagebreak question types
  1039. if ($row['type'] == 'open' || $row['type'] == 'comment') {
  1040. $content .= '<th>&nbsp;-&nbsp;</th>';
  1041. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1042. $display_percentage_header = 1;
  1043. } elseif ($row['type'] == 'percentage' && $display_percentage_header) {
  1044. $content .= '<th>&nbsp;%&nbsp;</th>';
  1045. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1046. $display_percentage_header = 0;
  1047. } elseif ($row['type'] == 'percentage') {
  1048. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1049. } elseif ($row['type'] != 'pagebreak' && $row['type'] != 'percentage') {
  1050. $content .= '<th>';
  1051. $content .= $row['option_text'];
  1052. $content .= '</th>';
  1053. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1054. $display_percentage_header = 1;
  1055. }
  1056. }
  1057. }
  1058. $content .= ' </tr>';
  1059. $userCondition = '';
  1060. if (!empty($userId)) {
  1061. $userId = (int) $userId;
  1062. $userCondition = " AND user = $userId ";
  1063. }
  1064. // Getting all the answers of the users
  1065. $old_user = '';
  1066. $answers_of_user = [];
  1067. $sql = "SELECT * FROM $table_survey_answer
  1068. WHERE
  1069. c_id = $course_id AND
  1070. survey_id = $surveyId
  1071. $userCondition
  1072. ORDER BY answer_id, user ASC";
  1073. $result = Database::query($sql);
  1074. $i = 1;
  1075. while ($row = Database::fetch_array($result)) {
  1076. if ($old_user != $row['user'] && $old_user != '') {
  1077. $userParam = $old_user;
  1078. if ($survey_data['anonymous'] != 0) {
  1079. $userParam = $i;
  1080. $i++;
  1081. }
  1082. $content .= self::display_complete_report_row(
  1083. $survey_data,
  1084. $possible_answers,
  1085. $answers_of_user,
  1086. $userParam,
  1087. $questions,
  1088. $display_extra_user_fields
  1089. );
  1090. $answers_of_user = [];
  1091. }
  1092. if (isset($questions[$row['question_id']]) &&
  1093. $questions[$row['question_id']]['type'] != 'open' &&
  1094. $questions[$row['question_id']]['type'] != 'comment'
  1095. ) {
  1096. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  1097. } else {
  1098. $answers_of_user[$row['question_id']][0] = $row;
  1099. }
  1100. $old_user = $row['user'];
  1101. }
  1102. $userParam = $old_user;
  1103. if ($survey_data['anonymous'] != 0) {
  1104. $userParam = $i;
  1105. $i++;
  1106. }
  1107. $content .= self::display_complete_report_row(
  1108. $survey_data,
  1109. $possible_answers,
  1110. $answers_of_user,
  1111. $userParam,
  1112. $questions,
  1113. $display_extra_user_fields
  1114. );
  1115. // This is to display the last user
  1116. $content .= '</table>';
  1117. $content .= '</form>';
  1118. return $content;
  1119. }
  1120. /**
  1121. * Return user answers in a row.
  1122. *
  1123. * @param $survey_data
  1124. * @param $possible_options
  1125. * @param $answers_of_user
  1126. * @param $user
  1127. * @param $questions
  1128. * @param bool $display_extra_user_fields
  1129. *
  1130. * @return string
  1131. */
  1132. public static function display_complete_report_row(
  1133. $survey_data,
  1134. $possible_options,
  1135. $answers_of_user,
  1136. $user,
  1137. $questions,
  1138. $display_extra_user_fields = false
  1139. ) {
  1140. $user = Security::remove_XSS($user);
  1141. $surveyId = (int) $survey_data['survey_id'];
  1142. if (empty($surveyId)) {
  1143. return '';
  1144. }
  1145. $content = '<tr>';
  1146. $url = api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq();
  1147. if ($survey_data['anonymous'] == 0) {
  1148. if (intval($user) !== 0) {
  1149. $userInfo = api_get_user_info($user);
  1150. $user_displayed = '-';
  1151. if (!empty($userInfo)) {
  1152. $user_displayed = $userInfo['complete_name_with_username'];
  1153. }
  1154. $content .= '<th>
  1155. <a href="'.$url.'&action=userreport&user='.$user.'">'
  1156. .$user_displayed.'</a>
  1157. </th>'; // the user column
  1158. } else {
  1159. $content .= '<th>'.$user.'</th>'; // the user column
  1160. }
  1161. } else {
  1162. $content .= '<th>'.get_lang('Anonymous').' '.$user.'</th>';
  1163. }
  1164. if ($display_extra_user_fields) {
  1165. // Show user fields data, if any, for this user
  1166. $user_fields_values = UserManager::get_extra_user_data(
  1167. $user,
  1168. false,
  1169. false,
  1170. false,
  1171. true
  1172. );
  1173. foreach ($user_fields_values as &$value) {
  1174. $content .= '<td align="center">'.$value.'</td>';
  1175. }
  1176. }
  1177. if (is_array($possible_options)) {
  1178. foreach ($possible_options as $question_id => &$possible_option) {
  1179. if ($questions[$question_id]['type'] == 'open' || $questions[$question_id]['type'] == 'comment') {
  1180. $content .= '<td align="center">';
  1181. if (isset($answers_of_user[$question_id]) && isset($answers_of_user[$question_id]['0'])) {
  1182. $content .= $answers_of_user[$question_id]['0']['option_id'];
  1183. }
  1184. $content .= '</td>';
  1185. } else {
  1186. foreach ($possible_option as $option_id => &$value) {
  1187. if ($questions[$question_id]['type'] == 'percentage') {
  1188. if (!empty($answers_of_user[$question_id][$option_id])) {
  1189. $content .= "<td align='center'>";
  1190. $content .= $answers_of_user[$question_id][$option_id]['value'];
  1191. $content .= "</td>";
  1192. }
  1193. } else {
  1194. $content .= '<td align="center">';
  1195. if (!empty($answers_of_user[$question_id][$option_id])) {
  1196. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  1197. $content .= $answers_of_user[$question_id][$option_id]['value'];
  1198. } else {
  1199. $content .= 'v';
  1200. }
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. $content .= '</tr>';
  1208. return $content;
  1209. }
  1210. /**
  1211. * Quite similar to display_complete_report(), returns an HTML string
  1212. * that can be used in a csv file.
  1213. *
  1214. * @todo consider merging this function with display_complete_report
  1215. *
  1216. * @return string The contents of a csv file
  1217. *
  1218. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1219. *
  1220. * @version February 2007
  1221. */
  1222. public static function export_complete_report($survey_data, $user_id = 0)
  1223. {
  1224. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  1225. if (empty($surveyId)) {
  1226. return false;
  1227. }
  1228. $course_id = api_get_course_int_id();
  1229. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1230. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1231. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1232. // The first column
  1233. $return = ';';
  1234. // Show extra fields blank space (enough for extra fields on next line)
  1235. $extra_user_fields = UserManager::get_extra_fields(
  1236. 0,
  1237. 0,
  1238. 5,
  1239. 'ASC',
  1240. false,
  1241. true
  1242. );
  1243. $num = count($extra_user_fields);
  1244. $return .= str_repeat(';', $num);
  1245. $sql = "SELECT
  1246. questions.question_id,
  1247. questions.type,
  1248. questions.survey_question,
  1249. count(options.question_option_id) as number_of_options
  1250. FROM $table_survey_question questions
  1251. LEFT JOIN $table_survey_question_option options
  1252. ON
  1253. questions.question_id = options.question_id AND
  1254. options.c_id = questions.c_id
  1255. WHERE
  1256. survey_question NOT LIKE '%{{%' AND
  1257. questions.type <> 'pagebreak' AND
  1258. questions.survey_id = $surveyId AND
  1259. questions.c_id = $course_id
  1260. GROUP BY questions.question_id
  1261. ORDER BY questions.sort ASC";
  1262. $result = Database::query($sql);
  1263. while ($row = Database::fetch_array($result)) {
  1264. // We show the questions if
  1265. // 1. there is no question filter and the export button has not been clicked
  1266. // 2. there is a quesiton filter but the question is selected for display
  1267. if (!(isset($_POST['submit_question_filter'])) ||
  1268. (isset($_POST['submit_question_filter']) &&
  1269. is_array($_POST['questions_filter']) &&
  1270. in_array($row['question_id'], $_POST['questions_filter']))
  1271. ) {
  1272. if ($row['number_of_options'] == 0) {
  1273. $return .= str_replace(
  1274. "\r\n",
  1275. ' ',
  1276. api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)
  1277. )
  1278. .';';
  1279. } else {
  1280. for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
  1281. $return .= str_replace(
  1282. "\r\n",
  1283. ' ',
  1284. api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)
  1285. )
  1286. .';';
  1287. }
  1288. }
  1289. }
  1290. }
  1291. $return .= "\n";
  1292. // Getting all the questions and options
  1293. $return .= ';';
  1294. // Show the fields names for user fields
  1295. if (!empty($extra_user_fields)) {
  1296. foreach ($extra_user_fields as &$field) {
  1297. $return .= '"'
  1298. .str_replace(
  1299. "\r\n",
  1300. ' ',
  1301. api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
  1302. )
  1303. .'";';
  1304. }
  1305. }
  1306. $sql = "SELECT DISTINCT
  1307. survey_question.question_id,
  1308. survey_question.survey_id,
  1309. survey_question.survey_question,
  1310. survey_question.display,
  1311. survey_question.sort,
  1312. survey_question.type,
  1313. survey_question_option.question_option_id,
  1314. survey_question_option.option_text,
  1315. survey_question_option.sort as option_sort
  1316. FROM $table_survey_question survey_question
  1317. LEFT JOIN $table_survey_question_option survey_question_option
  1318. ON
  1319. survey_question.question_id = survey_question_option.question_id AND
  1320. survey_question_option.c_id = survey_question.c_id
  1321. WHERE
  1322. survey_question NOT LIKE '%{{%' AND
  1323. survey_question.type <> 'pagebreak' AND
  1324. survey_question.survey_id = $surveyId AND
  1325. survey_question.c_id = $course_id
  1326. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  1327. $result = Database::query($sql);
  1328. $possible_answers = [];
  1329. $possible_answers_type = [];
  1330. while ($row = Database::fetch_array($result)) {
  1331. // We show the options if
  1332. // 1. there is no question filter and the export button has not been clicked
  1333. // 2. there is a question filter but the question is selected for display
  1334. if (!(isset($_POST['submit_question_filter'])) || (
  1335. is_array($_POST['questions_filter']) &&
  1336. in_array($row['question_id'], $_POST['questions_filter'])
  1337. )
  1338. ) {
  1339. $row['option_text'] = str_replace(["\r", "\n"], ['', ''], $row['option_text']);
  1340. $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
  1341. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1342. $possible_answers_type[$row['question_id']] = $row['type'];
  1343. }
  1344. }
  1345. $return .= "\n";
  1346. // Getting all the answers of the users
  1347. $old_user = '';
  1348. $answers_of_user = [];
  1349. $sql = "SELECT * FROM $table_survey_answer
  1350. WHERE
  1351. c_id = $course_id AND
  1352. survey_id='".$surveyId."'
  1353. ";
  1354. if ($user_id != 0) {
  1355. $sql .= "AND user='".Database::escape_string($user_id)."' ";
  1356. }
  1357. $sql .= ' ORDER BY user ASC ';
  1358. $questionIdList = array_keys($possible_answers_type);
  1359. $open_question_iterator = 1;
  1360. $result = Database::query($sql);
  1361. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1362. if (!in_array($row['question_id'], $questionIdList)) {
  1363. continue;
  1364. }
  1365. if ($old_user != $row['user'] && $old_user != '') {
  1366. $return .= self::export_complete_report_row(
  1367. $survey_data,
  1368. $possible_answers,
  1369. $answers_of_user,
  1370. $old_user,
  1371. true
  1372. );
  1373. $answers_of_user = [];
  1374. }
  1375. if ($possible_answers_type[$row['question_id']] == 'open' ||
  1376. $possible_answers_type[$row['question_id']] == 'comment'
  1377. ) {
  1378. $temp_id = 'open'.$open_question_iterator;
  1379. $answers_of_user[$row['question_id']][$temp_id] = $row;
  1380. $open_question_iterator++;
  1381. } else {
  1382. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  1383. }
  1384. $old_user = $row['user'];
  1385. }
  1386. // This is to display the last user
  1387. $return .= self::export_complete_report_row(
  1388. $survey_data,
  1389. $possible_answers,
  1390. $answers_of_user,
  1391. $old_user,
  1392. true
  1393. );
  1394. return $return;
  1395. }
  1396. /**
  1397. * Add a line to the csv file.
  1398. *
  1399. * @param array Possible answers
  1400. * @param array User's answers
  1401. * @param mixed User ID or user details as string - Used as a string in the result string
  1402. * @param bool Whether to display user fields or not
  1403. *
  1404. * @return string One line of the csv file
  1405. *
  1406. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1407. *
  1408. * @version February 2007
  1409. */
  1410. public static function export_complete_report_row(
  1411. $survey_data,
  1412. $possible_options,
  1413. $answers_of_user,
  1414. $user,
  1415. $display_extra_user_fields = false
  1416. ) {
  1417. $return = '';
  1418. if ($survey_data['anonymous'] == 0) {
  1419. if (intval($user) !== 0) {
  1420. $userInfo = api_get_user_info($user);
  1421. if (!empty($userInfo)) {
  1422. $user_displayed = $userInfo['complete_name_with_username'];
  1423. } else {
  1424. $user_displayed = '-';
  1425. }
  1426. $return .= $user_displayed.';';
  1427. } else {
  1428. $return .= $user.';';
  1429. }
  1430. } else {
  1431. $return .= '-;'; // The user column
  1432. }
  1433. if ($display_extra_user_fields) {
  1434. // Show user fields data, if any, for this user
  1435. $user_fields_values = UserManager::get_extra_user_data(
  1436. $user,
  1437. false,
  1438. false,
  1439. false,
  1440. true
  1441. );
  1442. foreach ($user_fields_values as &$value) {
  1443. $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
  1444. }
  1445. }
  1446. if (is_array($possible_options)) {
  1447. foreach ($possible_options as $question_id => $possible_option) {
  1448. if (is_array($possible_option) && count($possible_option) > 0) {
  1449. foreach ($possible_option as $option_id => &$value) {
  1450. $my_answer_of_user = !isset($answers_of_user[$question_id]) || isset($answers_of_user[$question_id]) && $answers_of_user[$question_id] == null ? [] : $answers_of_user[$question_id];
  1451. $key = array_keys($my_answer_of_user);
  1452. if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
  1453. $return .= '"'.
  1454. str_replace(
  1455. '"',
  1456. '""',
  1457. api_html_entity_decode(
  1458. strip_tags(
  1459. $answers_of_user[$question_id][$key[0]]['option_id']
  1460. ),
  1461. ENT_QUOTES
  1462. )
  1463. ).
  1464. '"';
  1465. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  1466. //$return .= 'v';
  1467. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  1468. $return .= $answers_of_user[$question_id][$option_id]['value'];
  1469. } else {
  1470. $return .= 'v';
  1471. }
  1472. }
  1473. $return .= ';';
  1474. }
  1475. }
  1476. }
  1477. }
  1478. $return .= "\n";
  1479. return $return;
  1480. }
  1481. /**
  1482. * Quite similar to display_complete_report(), returns an HTML string
  1483. * that can be used in a csv file.
  1484. *
  1485. * @todo consider merging this function with display_complete_report
  1486. *
  1487. * @return string The contents of a csv file
  1488. *
  1489. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1490. *
  1491. * @version February 2007
  1492. */
  1493. public static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
  1494. {
  1495. $course_id = api_get_course_int_id();
  1496. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  1497. if (empty($course_id) || empty($surveyId)) {
  1498. return false;
  1499. }
  1500. $spreadsheet = new PHPExcel();
  1501. $spreadsheet->setActiveSheetIndex(0);
  1502. $worksheet = $spreadsheet->getActiveSheet();
  1503. $line = 1;
  1504. $column = 1; // Skip the first column (row titles)
  1505. // Show extra fields blank space (enough for extra fields on next line)
  1506. // Show user fields section with a big th colspan that spans over all fields
  1507. $extra_user_fields = UserManager::get_extra_fields(
  1508. 0,
  1509. 0,
  1510. 5,
  1511. 'ASC',
  1512. false,
  1513. true
  1514. );
  1515. $num = count($extra_user_fields);
  1516. for ($i = 0; $i < $num; $i++) {
  1517. $worksheet->setCellValueByColumnAndRow($column, $line, '');
  1518. $column++;
  1519. }
  1520. $display_extra_user_fields = true;
  1521. // Database table definitions
  1522. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1523. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1524. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1525. // First line (questions)
  1526. $sql = "SELECT
  1527. questions.question_id,
  1528. questions.type,
  1529. questions.survey_question,
  1530. count(options.question_option_id) as number_of_options
  1531. FROM $table_survey_question questions
  1532. LEFT JOIN $table_survey_question_option options
  1533. ON
  1534. questions.question_id = options.question_id AND
  1535. options.c_id = questions.c_id
  1536. WHERE
  1537. survey_question NOT LIKE '%{{%' AND
  1538. questions.type <> 'pagebreak' AND
  1539. questions.survey_id = $surveyId AND
  1540. questions.c_id = $course_id
  1541. GROUP BY questions.question_id
  1542. ORDER BY questions.sort ASC";
  1543. $result = Database::query($sql);
  1544. while ($row = Database::fetch_array($result)) {
  1545. // We show the questions if
  1546. // 1. there is no question filter and the export button has not been clicked
  1547. // 2. there is a quesiton filter but the question is selected for display
  1548. if (!(isset($_POST['submit_question_filter'])) ||
  1549. (isset($_POST['submit_question_filter']) && is_array($_POST['questions_filter']) &&
  1550. in_array($row['question_id'], $_POST['questions_filter']))
  1551. ) {
  1552. if ($row['number_of_options'] == 0 &&
  1553. ($row['type'] == 'open' || $row['type'] == 'comment')
  1554. ) {
  1555. $worksheet->setCellValueByColumnAndRow(
  1556. $column,
  1557. $line,
  1558. api_html_entity_decode(
  1559. strip_tags($row['survey_question']),
  1560. ENT_QUOTES
  1561. )
  1562. );
  1563. $column++;
  1564. } else {
  1565. for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
  1566. $worksheet->setCellValueByColumnAndRow(
  1567. $column,
  1568. $line,
  1569. api_html_entity_decode(
  1570. strip_tags($row['survey_question']),
  1571. ENT_QUOTES
  1572. )
  1573. );
  1574. $column++;
  1575. }
  1576. }
  1577. }
  1578. }
  1579. $line++;
  1580. $column = 1;
  1581. // Show extra field values
  1582. if ($display_extra_user_fields) {
  1583. // Show the fields names for user fields
  1584. foreach ($extra_user_fields as &$field) {
  1585. $worksheet->setCellValueByColumnAndRow(
  1586. $column,
  1587. $line,
  1588. api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
  1589. );
  1590. $column++;
  1591. }
  1592. }
  1593. // Getting all the questions and options (second line)
  1594. $sql = "SELECT
  1595. survey_question.question_id,
  1596. survey_question.survey_id,
  1597. survey_question.survey_question,
  1598. survey_question.display,
  1599. survey_question.sort,
  1600. survey_question.type,
  1601. survey_question_option.question_option_id,
  1602. survey_question_option.option_text,
  1603. survey_question_option.sort as option_sort
  1604. FROM $table_survey_question survey_question
  1605. LEFT JOIN $table_survey_question_option survey_question_option
  1606. ON
  1607. survey_question.question_id = survey_question_option.question_id AND
  1608. survey_question_option.c_id = survey_question.c_id
  1609. WHERE
  1610. survey_question NOT LIKE '%{{%' AND
  1611. survey_question.type <> 'pagebreak' AND
  1612. survey_question.survey_id = $surveyId AND
  1613. survey_question.c_id = $course_id
  1614. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  1615. $result = Database::query($sql);
  1616. $possible_answers = [];
  1617. $possible_answers_type = [];
  1618. while ($row = Database::fetch_array($result)) {
  1619. // We show the options if
  1620. // 1. there is no question filter and the export button has not been clicked
  1621. // 2. there is a quesiton filter but the question is selected for display
  1622. if (!isset($_POST['submit_question_filter']) ||
  1623. (isset($_POST['questions_filter']) && is_array($_POST['questions_filter']) &&
  1624. in_array($row['question_id'], $_POST['questions_filter']))
  1625. ) {
  1626. $worksheet->setCellValueByColumnAndRow(
  1627. $column,
  1628. $line,
  1629. api_html_entity_decode(
  1630. strip_tags($row['option_text']),
  1631. ENT_QUOTES
  1632. )
  1633. );
  1634. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1635. $possible_answers_type[$row['question_id']] = $row['type'];
  1636. $column++;
  1637. }
  1638. }
  1639. // Getting all the answers of the users
  1640. $line++;
  1641. $column = 0;
  1642. $old_user = '';
  1643. $answers_of_user = [];
  1644. $sql = "SELECT * FROM $table_survey_answer
  1645. WHERE c_id = $course_id AND survey_id = $surveyId";
  1646. if ($user_id != 0) {
  1647. $sql .= " AND user='".intval($user_id)."' ";
  1648. }
  1649. $sql .= ' ORDER BY user ASC';
  1650. $open_question_iterator = 1;
  1651. $result = Database::query($sql);
  1652. while ($row = Database::fetch_array($result)) {
  1653. if ($old_user != $row['user'] && $old_user != '') {
  1654. $return = self::export_complete_report_row_xls(
  1655. $survey_data,
  1656. $possible_answers,
  1657. $answers_of_user,
  1658. $old_user,
  1659. true
  1660. );
  1661. foreach ($return as $elem) {
  1662. $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
  1663. $column++;
  1664. }
  1665. $answers_of_user = [];
  1666. $line++;
  1667. $column = 0;
  1668. }
  1669. if ($possible_answers_type[$row['question_id']] == 'open' ||
  1670. $possible_answers_type[$row['question_id']] == 'comment'
  1671. ) {
  1672. $temp_id = 'open'.$open_question_iterator;
  1673. $answers_of_user[$row['question_id']][$temp_id] = $row;
  1674. $open_question_iterator++;
  1675. } else {
  1676. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  1677. }
  1678. $old_user = $row['user'];
  1679. }
  1680. $return = self::export_complete_report_row_xls(
  1681. $survey_data,
  1682. $possible_answers,
  1683. $answers_of_user,
  1684. $old_user,
  1685. true
  1686. );
  1687. // this is to display the last user
  1688. foreach ($return as $elem) {
  1689. $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
  1690. $column++;
  1691. }
  1692. $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
  1693. $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
  1694. $writer->save($file);
  1695. DocumentManager::file_send_for_download($file, true, $filename);
  1696. return null;
  1697. }
  1698. /**
  1699. * Add a line to the csv file.
  1700. *
  1701. * @param array Possible answers
  1702. * @param array User's answers
  1703. * @param mixed User ID or user details as string - Used as a string in the result string
  1704. * @param bool Whether to display user fields or not
  1705. *
  1706. * @return string One line of the csv file
  1707. */
  1708. public static function export_complete_report_row_xls(
  1709. $survey_data,
  1710. $possible_options,
  1711. $answers_of_user,
  1712. $user,
  1713. $display_extra_user_fields = false
  1714. ) {
  1715. $return = [];
  1716. if ($survey_data['anonymous'] == 0) {
  1717. if (intval($user) !== 0) {
  1718. $userInfo = api_get_user_info($user);
  1719. if ($userInfo) {
  1720. $user_displayed = $userInfo['complete_name_with_username'];
  1721. } else {
  1722. $user_displayed = '-';
  1723. }
  1724. $return[] = $user_displayed;
  1725. } else {
  1726. $return[] = $user;
  1727. }
  1728. } else {
  1729. $return[] = '-'; // The user column
  1730. }
  1731. if ($display_extra_user_fields) {
  1732. //show user fields data, if any, for this user
  1733. $user_fields_values = UserManager::get_extra_user_data(
  1734. $user,
  1735. false,
  1736. false,
  1737. false,
  1738. true
  1739. );
  1740. foreach ($user_fields_values as $value) {
  1741. $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
  1742. }
  1743. }
  1744. if (is_array($possible_options)) {
  1745. foreach ($possible_options as $question_id => &$possible_option) {
  1746. if (is_array($possible_option) && count($possible_option) > 0) {
  1747. foreach ($possible_option as $option_id => &$value) {
  1748. $my_answers_of_user = isset($answers_of_user[$question_id])
  1749. ? $answers_of_user[$question_id]
  1750. : [];
  1751. $key = array_keys($my_answers_of_user);
  1752. if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
  1753. $return[] = api_html_entity_decode(
  1754. strip_tags($answers_of_user[$question_id][$key[0]]['option_id']),
  1755. ENT_QUOTES
  1756. );
  1757. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  1758. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  1759. $return[] = $answers_of_user[$question_id][$option_id]['value'];
  1760. } else {
  1761. $return[] = 'v';
  1762. }
  1763. } else {
  1764. $return[] = '';
  1765. }
  1766. }
  1767. }
  1768. }
  1769. }
  1770. return $return;
  1771. }
  1772. /**
  1773. * This function displays the comparative report which
  1774. * allows you to compare two questions
  1775. * A comparative report creates a table where one question
  1776. * is on the x axis and a second question is on the y axis.
  1777. * In the intersection is the number of people who have
  1778. * answered positive on both options.
  1779. *
  1780. * @return string HTML code
  1781. *
  1782. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1783. *
  1784. * @version February 2007
  1785. */
  1786. public static function display_comparative_report()
  1787. {
  1788. // Allowed question types for comparative report
  1789. $allowed_question_types = [
  1790. 'yesno',
  1791. 'multiplechoice',
  1792. 'multipleresponse',
  1793. 'dropdown',
  1794. 'percentage',
  1795. 'score',
  1796. ];
  1797. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  1798. // Getting all the questions
  1799. $questions = SurveyManager::get_questions($surveyId);
  1800. // Actions bar
  1801. echo '<div class="actions">';
  1802. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq()
  1803. .'">'
  1804. .Display::return_icon(
  1805. 'back.png',
  1806. get_lang('BackTo').' '.get_lang('ReportingOverview'),
  1807. [],
  1808. ICON_SIZE_MEDIUM
  1809. )
  1810. .'</a>';
  1811. echo '</div>';
  1812. // Displaying an information message that only the questions with predefined answers can be used in a comparative report
  1813. echo Display::return_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), 'normal', false);
  1814. $xAxis = isset($_GET['xaxis']) ? Security::remove_XSS($_GET['xaxis']) : '';
  1815. $yAxis = isset($_GET['yaxis']) ? Security::remove_XSS($_GET['yaxis']) : '';
  1816. $url = api_get_self().'?'.api_get_cidreq().'&action='.Security::remove_XSS($_GET['action'])
  1817. .'&survey_id='.$surveyId.'&xaxis='.$xAxis.'&y='.$yAxis;
  1818. $form = new FormValidator('compare', 'get', $url);
  1819. $form->addHidden('action', Security::remove_XSS($_GET['action']));
  1820. $form->addHidden('survey_id', $surveyId);
  1821. $optionsX = ['----'];
  1822. $optionsY = ['----'];
  1823. $defaults = [];
  1824. foreach ($questions as $key => &$question) {
  1825. // Ignored tagged questions
  1826. if ($question) {
  1827. if (strpos($question['question'], '{{') !== false) {
  1828. $question = null;
  1829. continue;
  1830. }
  1831. }
  1832. if (is_array($allowed_question_types)) {
  1833. if (in_array($question['type'], $allowed_question_types)) {
  1834. if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
  1835. $defaults['xaxis'] = $question['question_id'];
  1836. }
  1837. if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
  1838. $defaults['yaxis'] = $question['question_id'];
  1839. }
  1840. $optionsX[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 90);
  1841. $optionsY[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 90);
  1842. }
  1843. }
  1844. }
  1845. $form->addSelect('xaxis', get_lang('SelectXAxis'), $optionsX);
  1846. $form->addSelect('yaxis', get_lang('SelectYAxis'), $optionsY);
  1847. $form->addButtonSearch(get_lang('CompareQuestions'));
  1848. $form->setDefaults($defaults);
  1849. $form->display();
  1850. // Getting all the information of the x axis
  1851. if (is_numeric($xAxis)) {
  1852. $question_x = SurveyManager::get_question($xAxis);
  1853. }
  1854. // Getting all the information of the y axis
  1855. if (is_numeric($yAxis)) {
  1856. $question_y = SurveyManager::get_question($yAxis);
  1857. }
  1858. if (is_numeric($xAxis) && is_numeric($yAxis)) {
  1859. // Getting the answers of the two questions
  1860. $answers_x = self::get_answers_of_question_by_user($surveyId, $xAxis);
  1861. $answers_y = self::get_answers_of_question_by_user($surveyId, $yAxis);
  1862. // Displaying the table
  1863. $tableHtml = '<table border="1" class="data_table">';
  1864. $xOptions = [];
  1865. // The header
  1866. $tableHtml .= '<tr>';
  1867. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1868. if ($ii == 0) {
  1869. $tableHtml .= '<th>&nbsp;</th>';
  1870. } else {
  1871. if ($question_x['type'] == 'score') {
  1872. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1873. $tableHtml .= '<th>'.$question_x['answers'][($ii - 1)].'<br />'.$x.'</th>';
  1874. }
  1875. $x = '';
  1876. } else {
  1877. $tableHtml .= '<th>'.$question_x['answers'][($ii - 1)].'</th>';
  1878. }
  1879. $optionText = strip_tags($question_x['answers'][$ii - 1]);
  1880. $optionText = html_entity_decode($optionText);
  1881. array_push($xOptions, trim($optionText));
  1882. }
  1883. }
  1884. $tableHtml .= '</tr>';
  1885. $chartData = [];
  1886. // The main part
  1887. for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
  1888. $currentYQuestion = strip_tags($question_y['answers'][$ij]);
  1889. $currentYQuestion = html_entity_decode($currentYQuestion);
  1890. // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
  1891. if ($question_y['type'] == 'score') {
  1892. for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
  1893. $tableHtml .= '<tr>';
  1894. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1895. if ($question_x['type'] == 'score') {
  1896. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1897. if ($ii == 0) {
  1898. $tableHtml .= '<th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
  1899. break;
  1900. } else {
  1901. $tableHtml .= '<td align="center">';
  1902. $votes = self::comparative_check(
  1903. $answers_x,
  1904. $answers_y,
  1905. $question_x['answersid'][($ii - 1)],
  1906. $question_y['answersid'][($ij)],
  1907. $x,
  1908. $y
  1909. );
  1910. $tableHtml .= $votes;
  1911. array_push(
  1912. $chartData,
  1913. [
  1914. 'serie' => [$currentYQuestion, $xOptions[$ii - 1]],
  1915. 'option' => $x,
  1916. 'votes' => $votes,
  1917. ]
  1918. );
  1919. $tableHtml .= '</td>';
  1920. }
  1921. }
  1922. } else {
  1923. if ($ii == 0) {
  1924. $tableHtml .= '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
  1925. } else {
  1926. $tableHtml .= '<td align="center">';
  1927. $votes = self::comparative_check(
  1928. $answers_x,
  1929. $answers_y,
  1930. $question_x['answersid'][($ii - 1)],
  1931. $question_y['answersid'][($ij)],
  1932. 0,
  1933. $y
  1934. );
  1935. $tableHtml .= $votes;
  1936. array_push(
  1937. $chartData,
  1938. [
  1939. 'serie' => [$currentYQuestion, $xOptions[$ii - 1]],
  1940. 'option' => $y,
  1941. 'votes' => $votes,
  1942. ]
  1943. );
  1944. $tableHtml .= '</td>';
  1945. }
  1946. }
  1947. }
  1948. $tableHtml .= '</tr>';
  1949. }
  1950. } else {
  1951. // The Y axis is NOT a score question type so the number of rows = the number of options
  1952. $tableHtml .= '<tr>';
  1953. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1954. if ($question_x['type'] == 'score') {
  1955. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1956. if ($ii == 0) {
  1957. $tableHtml .= '<th>'.$question_y['answers'][$ij].'</th>';
  1958. break;
  1959. } else {
  1960. $tableHtml .= '<td align="center">';
  1961. $votes = self::comparative_check(
  1962. $answers_x,
  1963. $answers_y,
  1964. $question_x['answersid'][($ii - 1)],
  1965. $question_y['answersid'][($ij)],
  1966. $x,
  1967. 0
  1968. );
  1969. $tableHtml .= $votes;
  1970. array_push(
  1971. $chartData,
  1972. [
  1973. 'serie' => [$currentYQuestion, $xOptions[$ii - 1]],
  1974. 'option' => $x,
  1975. 'votes' => $votes,
  1976. ]
  1977. );
  1978. $tableHtml .= '</td>';
  1979. }
  1980. }
  1981. } else {
  1982. if ($ii == 0) {
  1983. $tableHtml .= '<th>'.$question_y['answers'][($ij)].'</th>';
  1984. } else {
  1985. $tableHtml .= '<td align="center">';
  1986. $votes = self::comparative_check(
  1987. $answers_x,
  1988. $answers_y,
  1989. $question_x['answersid'][($ii - 1)],
  1990. $question_y['answersid'][($ij)]
  1991. );
  1992. $tableHtml .= $votes;
  1993. array_push(
  1994. $chartData,
  1995. [
  1996. 'serie' => $xOptions[$ii - 1],
  1997. 'option' => $currentYQuestion,
  1998. 'votes' => $votes,
  1999. ]
  2000. );
  2001. $tableHtml .= '</td>';
  2002. }
  2003. }
  2004. }
  2005. $tableHtml .= '</tr>';
  2006. }
  2007. }
  2008. $tableHtml .= '</table>';
  2009. echo '<div id="chartContainer" class="col-md-12">';
  2010. echo self::drawChart($chartData, true);
  2011. echo '</div>';
  2012. echo $tableHtml;
  2013. }
  2014. }
  2015. /**
  2016. * Get all the answers of a question grouped by user.
  2017. *
  2018. * @param int $survey_id Survey ID
  2019. * @param int $question_id Question ID
  2020. *
  2021. * @return array Array containing all answers of all users, grouped by user
  2022. *
  2023. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2024. *
  2025. * @version February 2007 - Updated March 2008
  2026. */
  2027. public static function get_answers_of_question_by_user($survey_id, $question_id)
  2028. {
  2029. $course_id = api_get_course_int_id();
  2030. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  2031. $sql = "SELECT * FROM $table_survey_answer
  2032. WHERE
  2033. c_id = $course_id AND
  2034. survey_id='".intval($survey_id)."' AND
  2035. question_id='".intval($question_id)."'
  2036. ORDER BY USER ASC";
  2037. $result = Database::query($sql);
  2038. $return = [];
  2039. while ($row = Database::fetch_array($result)) {
  2040. if ($row['value'] == 0) {
  2041. $return[$row['user']][] = $row['option_id'];
  2042. } else {
  2043. $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
  2044. }
  2045. }
  2046. return $return;
  2047. }
  2048. /**
  2049. * Count the number of users who answer positively on both options.
  2050. *
  2051. * @param array All answers of the x axis
  2052. * @param array All answers of the y axis
  2053. * @param int x axis value (= the option_id of the first question)
  2054. * @param int y axis value (= the option_id of the second question)
  2055. *
  2056. * @return int Number of users who have answered positively to both options
  2057. *
  2058. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2059. *
  2060. * @version February 2007
  2061. */
  2062. public static function comparative_check(
  2063. $answers_x,
  2064. $answers_y,
  2065. $option_x,
  2066. $option_y,
  2067. $value_x = 0,
  2068. $value_y = 0
  2069. ) {
  2070. if ($value_x == 0) {
  2071. $check_x = $option_x;
  2072. } else {
  2073. $check_x = $option_x.'*'.$value_x;
  2074. }
  2075. if ($value_y == 0) {
  2076. $check_y = $option_y;
  2077. } else {
  2078. $check_y = $option_y.'*'.$value_y;
  2079. }
  2080. $counter = 0;
  2081. if (is_array($answers_x)) {
  2082. foreach ($answers_x as $user => &$answers) {
  2083. // Check if the user has given $option_x as answer
  2084. if (in_array($check_x, $answers)) {
  2085. // Check if the user has given $option_y as an answer
  2086. if (!is_null($answers_y[$user]) &&
  2087. in_array($check_y, $answers_y[$user])
  2088. ) {
  2089. $counter++;
  2090. }
  2091. }
  2092. }
  2093. }
  2094. return $counter;
  2095. }
  2096. /**
  2097. * Save the invitation mail.
  2098. *
  2099. * @param string Text of the e-mail
  2100. * @param int Whether the mail contents are for invite mail (0, default) or reminder mail (1)
  2101. *
  2102. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2103. *
  2104. * @version January 2007
  2105. */
  2106. public static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
  2107. {
  2108. $course_id = api_get_course_int_id();
  2109. // Database table definition
  2110. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2111. // Reminder or not
  2112. if ($reminder == 0) {
  2113. $mail_field = 'invite_mail';
  2114. } else {
  2115. $mail_field = 'reminder_mail';
  2116. }
  2117. $sql = "UPDATE $table_survey SET
  2118. mail_subject='".Database::escape_string($mail_subject)."',
  2119. $mail_field = '".Database::escape_string($mailtext)."'
  2120. WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
  2121. Database::query($sql);
  2122. }
  2123. /**
  2124. * This function saves all the invitations of course users
  2125. * and additional users in the database
  2126. * and sends the invitations by email.
  2127. *
  2128. * @param $users_array Users $array array can be both a list of course uids AND a list of additional emailaddresses
  2129. * @param $invitation_title Title $string of the invitation, used as the title of the mail
  2130. * @param $invitation_text Text $string of the invitation, used as the text of the mail.
  2131. * The text has to contain a **link** string or this will automatically be added to the end
  2132. * @param int $reminder
  2133. * @param bool $sendmail
  2134. * @param int $remindUnAnswered
  2135. * @param bool $isAdditionalEmail
  2136. * @param bool $hideLink
  2137. *
  2138. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2139. * @author Julio Montoya - Adding auto-generated link support
  2140. *
  2141. * @version January 2007
  2142. */
  2143. public static function saveInvitations(
  2144. $users_array,
  2145. $invitation_title,
  2146. $invitation_text,
  2147. $reminder = 0,
  2148. $sendmail = false,
  2149. $remindUnAnswered = 0,
  2150. $isAdditionalEmail = false,
  2151. $hideLink = false
  2152. ) {
  2153. if (!is_array($users_array)) {
  2154. // Should not happen
  2155. return 0;
  2156. }
  2157. // Getting the survey information
  2158. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  2159. $survey_invitations = self::get_invitations($survey_data['survey_code']);
  2160. $already_invited = self::get_invited_users($survey_data['code']);
  2161. // Remind unanswered is a special version of remind all reminder
  2162. $exclude_users = [];
  2163. if ($remindUnAnswered == 1) {
  2164. // Remind only unanswered users
  2165. $reminder = 1;
  2166. $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
  2167. }
  2168. $counter = 0; // Nr of invitations "sent" (if sendmail option)
  2169. $course_id = api_get_course_int_id();
  2170. $session_id = api_get_session_id();
  2171. if ($isAdditionalEmail == false) {
  2172. $result = CourseManager::separateUsersGroups($users_array);
  2173. $groupList = $result['groups'];
  2174. $users_array = $result['users'];
  2175. foreach ($groupList as $groupId) {
  2176. $userGroupList = GroupManager::getStudents($groupId, true);
  2177. $userGroupIdList = array_column($userGroupList, 'user_id');
  2178. $users_array = array_merge($users_array, $userGroupIdList);
  2179. $params = [
  2180. 'c_id' => $course_id,
  2181. 'session_id' => $session_id,
  2182. 'group_id' => $groupId,
  2183. 'survey_code' => $survey_data['code'],
  2184. ];
  2185. $invitationExists = self::invitationExists(
  2186. $course_id,
  2187. $session_id,
  2188. $groupId,
  2189. $survey_data['code']
  2190. );
  2191. if (empty($invitationExists)) {
  2192. self::save_invitation($params);
  2193. }
  2194. }
  2195. }
  2196. $users_array = array_unique($users_array);
  2197. foreach ($users_array as $key => $value) {
  2198. if (!isset($value) || $value == '') {
  2199. continue;
  2200. }
  2201. // Skip user if reminding only unanswered people
  2202. if (in_array($value, $exclude_users)) {
  2203. continue;
  2204. }
  2205. // Get the unique invitation code if we already have it
  2206. if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
  2207. $invitation_code = $survey_invitations[$value]['invitation_code'];
  2208. } else {
  2209. $invitation_code = md5($value.microtime());
  2210. }
  2211. $new_user = false; // User not already invited
  2212. // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
  2213. $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users'])
  2214. ? explode(';', $already_invited['additional_users'])
  2215. : [];
  2216. $my_alredy_invited = $already_invited['course_users'] == null ? [] : $already_invited['course_users'];
  2217. if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
  2218. (!is_numeric($value) && !in_array($value, $addit_users_array))
  2219. ) {
  2220. $new_user = true;
  2221. if (!array_key_exists($value, $survey_invitations)) {
  2222. $params = [
  2223. 'c_id' => $course_id,
  2224. 'session_id' => $session_id,
  2225. 'user' => $value,
  2226. 'survey_code' => $survey_data['code'],
  2227. 'invitation_code' => $invitation_code,
  2228. 'invitation_date' => api_get_utc_datetime(),
  2229. ];
  2230. self::save_invitation($params);
  2231. }
  2232. }
  2233. // Send the email if checkboxed
  2234. if (($new_user || $reminder == 1) && $sendmail) {
  2235. // Make a change for absolute url
  2236. if (isset($invitation_text)) {
  2237. $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
  2238. $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
  2239. $invitation_text = trim(stripslashes($invitation_text));
  2240. }
  2241. self::send_invitation_mail(
  2242. $value,
  2243. $invitation_code,
  2244. $invitation_title,
  2245. $invitation_text,
  2246. $hideLink
  2247. );
  2248. $counter++;
  2249. }
  2250. }
  2251. return $counter; // Number of invitations sent
  2252. }
  2253. /**
  2254. * @param $params
  2255. *
  2256. * @return bool|int
  2257. */
  2258. public static function save_invitation($params)
  2259. {
  2260. // Database table to store the invitations data
  2261. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2262. if (!empty($params['c_id']) &&
  2263. (!empty($params['user']) || !empty($params['group_id'])) &&
  2264. !empty($params['survey_code'])
  2265. ) {
  2266. $insertId = Database::insert($table, $params);
  2267. if ($insertId) {
  2268. $sql = "UPDATE $table
  2269. SET survey_invitation_id = $insertId
  2270. WHERE iid = $insertId";
  2271. Database::query($sql);
  2272. }
  2273. return $insertId;
  2274. }
  2275. return false;
  2276. }
  2277. /**
  2278. * @param int $courseId
  2279. * @param int $sessionId
  2280. * @param int $groupId
  2281. * @param string $surveyCode
  2282. *
  2283. * @return int
  2284. */
  2285. public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
  2286. {
  2287. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2288. $courseId = (int) $courseId;
  2289. $sessionId = (int) $sessionId;
  2290. $groupId = (int) $groupId;
  2291. $surveyCode = Database::escape_string($surveyCode);
  2292. $sql = "SELECT survey_invitation_id FROM $table
  2293. WHERE
  2294. c_id = $courseId AND
  2295. session_id = $sessionId AND
  2296. group_id = $groupId AND
  2297. survey_code = '$surveyCode'
  2298. ";
  2299. $result = Database::query($sql);
  2300. return Database::num_rows($result);
  2301. }
  2302. /**
  2303. * Send the invitation by mail.
  2304. *
  2305. * @param int invitedUser - the userId (course user) or emailaddress of additional user
  2306. * $param string $invitation_code - the unique invitation code for the URL
  2307. */
  2308. public static function send_invitation_mail(
  2309. $invitedUser,
  2310. $invitation_code,
  2311. $invitation_title,
  2312. $invitation_text,
  2313. $hideLink = false
  2314. ) {
  2315. $_user = api_get_user_info();
  2316. $_course = api_get_course_info();
  2317. $sessionId = api_get_session_id();
  2318. // Replacing the **link** part with a valid link for the user
  2319. $link = self::generateFillSurveyLink($invitation_code, $_course, $sessionId);
  2320. if ($hideLink) {
  2321. $full_invitation_text = str_replace('**link**', '', $invitation_text);
  2322. } else {
  2323. $text_link = '<a href="'.$link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n"
  2324. .get_lang('OrCopyPasteTheFollowingUrl')." <br /> \r\n <br /> \r\n ".$link;
  2325. $replace_count = 0;
  2326. $full_invitation_text = api_str_ireplace('**link**', $text_link, $invitation_text, $replace_count);
  2327. if ($replace_count < 1) {
  2328. $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
  2329. }
  2330. }
  2331. // Sending the mail
  2332. $sender_name = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
  2333. $sender_email = $_user['mail'];
  2334. $sender_user_id = api_get_user_id();
  2335. $replyto = [];
  2336. if (api_get_setting('survey_email_sender_noreply') == 'noreply') {
  2337. $noreply = api_get_setting('noreply_email_address');
  2338. if (!empty($noreply)) {
  2339. $replyto['Reply-to'] = $noreply;
  2340. $sender_name = $noreply;
  2341. $sender_email = $noreply;
  2342. $sender_user_id = null;
  2343. }
  2344. }
  2345. // Optionally: finding the e-mail of the course user
  2346. if (is_numeric($invitedUser)) {
  2347. MessageManager::send_message(
  2348. $invitedUser,
  2349. $invitation_title,
  2350. $full_invitation_text,
  2351. [],
  2352. [],
  2353. null,
  2354. null,
  2355. null,
  2356. null,
  2357. $sender_user_id,
  2358. true
  2359. );
  2360. } else {
  2361. @api_mail_html(
  2362. '',
  2363. $invitedUser,
  2364. $invitation_title,
  2365. $full_invitation_text,
  2366. $sender_name,
  2367. $sender_email,
  2368. $replyto
  2369. );
  2370. }
  2371. }
  2372. /**
  2373. * This function recalculates the number of users who have been invited and updates the survey table with this
  2374. * value.
  2375. *
  2376. * @param string Survey code
  2377. * @param int $courseId
  2378. * @param int $sessionId
  2379. *
  2380. * @return int
  2381. *
  2382. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2383. *
  2384. * @version January 2007
  2385. */
  2386. public static function update_count_invited($survey_code, $courseId = 0, $sessionId = 0)
  2387. {
  2388. $survey_code = Database::escape_string($survey_code);
  2389. $courseId = (int) $courseId;
  2390. $sessionId = (int) $sessionId;
  2391. $courseId = $courseId ?: api_get_course_int_id();
  2392. $sessionId = $sessionId ?: api_get_session_id();
  2393. $sessionCondition = api_get_session_condition($sessionId);
  2394. // Database table definition
  2395. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2396. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2397. // Counting the number of people that are invited
  2398. $sql = "SELECT count(user) as total
  2399. FROM $table_survey_invitation
  2400. WHERE
  2401. c_id = $courseId AND
  2402. survey_code = '".$survey_code."' AND
  2403. user <> ''
  2404. $sessionCondition
  2405. ";
  2406. $result = Database::query($sql);
  2407. $row = Database::fetch_array($result);
  2408. $total_invited = $row['total'];
  2409. // Updating the field in the survey table
  2410. $sql = "UPDATE $table_survey
  2411. SET invited = '".Database::escape_string($total_invited)."'
  2412. WHERE
  2413. c_id = $courseId AND
  2414. code = '".$survey_code."'
  2415. $sessionCondition
  2416. ";
  2417. Database::query($sql);
  2418. return $total_invited;
  2419. }
  2420. /**
  2421. * This function gets all the invited users for a given survey code.
  2422. *
  2423. * @param string Survey code
  2424. * @param string optional - course database
  2425. *
  2426. * @return array Array containing the course users and additional users (non course users)
  2427. *
  2428. * @todo consider making $defaults['additional_users'] also an array
  2429. *
  2430. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2431. * @author Julio Montoya, adding c_id fixes - Dec 2012
  2432. *
  2433. * @version January 2007
  2434. */
  2435. public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
  2436. {
  2437. $session_id = (int) $session_id;
  2438. $survey_code = Database::escape_string($survey_code);
  2439. $course_code = Database::escape_string($course_code);
  2440. $course_id = api_get_course_int_id();
  2441. if (!empty($course_code)) {
  2442. $course_info = api_get_course_info($course_code);
  2443. if ($course_info) {
  2444. $course_id = $course_info['real_id'];
  2445. }
  2446. }
  2447. if (empty($session_id)) {
  2448. $session_id = api_get_session_id();
  2449. }
  2450. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2451. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2452. // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
  2453. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
  2454. $sql = "SELECT user, group_id
  2455. FROM $table_survey_invitation as table_invitation
  2456. WHERE
  2457. table_invitation.c_id = $course_id AND
  2458. survey_code='".$survey_code."' AND
  2459. session_id = $session_id
  2460. ";
  2461. $defaults = [];
  2462. $defaults['course_users'] = [];
  2463. $defaults['additional_users'] = []; // Textarea
  2464. $defaults['users'] = []; // user and groups
  2465. $result = Database::query($sql);
  2466. while ($row = Database::fetch_array($result)) {
  2467. if (is_numeric($row['user'])) {
  2468. $defaults['course_users'][] = $row['user'];
  2469. $defaults['users'][] = 'USER:'.$row['user'];
  2470. } else {
  2471. if (!empty($row['user'])) {
  2472. $defaults['additional_users'][] = $row['user'];
  2473. }
  2474. }
  2475. if (isset($row['group_id']) && !empty($row['group_id'])) {
  2476. $defaults['users'][] = 'GROUP:'.$row['group_id'];
  2477. }
  2478. }
  2479. if (!empty($defaults['course_users'])) {
  2480. $user_ids = implode("','", $defaults['course_users']);
  2481. $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
  2482. $result = Database::query($sql);
  2483. $fixed_users = [];
  2484. while ($row = Database::fetch_array($result)) {
  2485. $fixed_users[] = $row['user_id'];
  2486. }
  2487. $defaults['course_users'] = $fixed_users;
  2488. }
  2489. if (!empty($defaults['additional_users'])) {
  2490. $defaults['additional_users'] = implode(';', $defaults['additional_users']);
  2491. }
  2492. return $defaults;
  2493. }
  2494. /**
  2495. * Get all the invitations.
  2496. *
  2497. * @param string Survey code
  2498. *
  2499. * @return array Database rows matching the survey code
  2500. *
  2501. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2502. *
  2503. * @version September 2007
  2504. */
  2505. public static function get_invitations($survey_code)
  2506. {
  2507. $course_id = api_get_course_int_id();
  2508. $sessionId = api_get_session_id();
  2509. // Database table definition
  2510. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2511. $sql = "SELECT * FROM $table_survey_invitation
  2512. WHERE
  2513. c_id = $course_id AND
  2514. session_id = $sessionId AND
  2515. survey_code = '".Database::escape_string($survey_code)."'";
  2516. $result = Database::query($sql);
  2517. $return = [];
  2518. while ($row = Database::fetch_array($result)) {
  2519. $return[$row['user']] = $row;
  2520. }
  2521. return $return;
  2522. }
  2523. /**
  2524. * This function displays the form for searching a survey.
  2525. *
  2526. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2527. *
  2528. * @version January 2007
  2529. *
  2530. * @todo consider moving this to surveymanager.inc.lib.php
  2531. */
  2532. public static function display_survey_search_form()
  2533. {
  2534. $url = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced&'.api_get_cidreq();
  2535. $form = new FormValidator('search', 'get', $url);
  2536. $form->addHeader(get_lang('SearchASurvey'));
  2537. $form->addText('keyword_title', get_lang('Title'));
  2538. $form->addText('keyword_code', get_lang('Code'));
  2539. $form->addSelectLanguage('keyword_language', get_lang('Language'));
  2540. $form->addHidden('cidReq', api_get_course_id());
  2541. $form->addButtonSearch(get_lang('Search'), 'do_search');
  2542. $form->display();
  2543. }
  2544. /**
  2545. * Show table only visible by DRH users.
  2546. */
  2547. public static function displaySurveyListForDrh()
  2548. {
  2549. $parameters = [];
  2550. $parameters['cidReq'] = api_get_course_id();
  2551. // Create a sortable table with survey-data
  2552. $table = new SortableTable(
  2553. 'surveys',
  2554. 'get_number_of_surveys',
  2555. 'get_survey_data_drh',
  2556. 2
  2557. );
  2558. $table->set_additional_parameters($parameters);
  2559. $table->set_header(0, '', false);
  2560. $table->set_header(1, get_lang('SurveyName'));
  2561. $table->set_header(2, get_lang('SurveyCode'));
  2562. $table->set_header(3, get_lang('NumberOfQuestions'));
  2563. $table->set_header(4, get_lang('Author'));
  2564. $table->set_header(5, get_lang('AvailableFrom'));
  2565. $table->set_header(6, get_lang('AvailableUntil'));
  2566. $table->set_header(7, get_lang('Invite'));
  2567. $table->set_header(8, get_lang('Anonymous'));
  2568. if (api_get_configuration_value('allow_mandatory_survey')) {
  2569. $table->set_header(9, get_lang('IsMandatory'));
  2570. $table->set_header(10, get_lang('Modify'), false, 'width="150"');
  2571. $table->set_column_filter(9, 'anonymous_filter');
  2572. $table->set_column_filter(10, 'modify_filter_drh');
  2573. } else {
  2574. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  2575. $table->set_column_filter(9, 'modify_filter_drh');
  2576. }
  2577. $table->set_column_filter(8, 'anonymous_filter');
  2578. $table->display();
  2579. }
  2580. /**
  2581. * This function displays the sortable table with all the surveys.
  2582. *
  2583. *
  2584. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2585. *
  2586. * @version January 2007
  2587. */
  2588. public static function display_survey_list()
  2589. {
  2590. $parameters = [];
  2591. $parameters['cidReq'] = api_get_course_id();
  2592. if (isset($_GET['do_search']) && $_GET['do_search']) {
  2593. $message = get_lang('DisplaySearchResults').'<br />';
  2594. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  2595. echo Display::return_message($message, 'normal', false);
  2596. }
  2597. // Create a sortable table with survey-data
  2598. $table = new SortableTable(
  2599. 'surveys',
  2600. 'get_number_of_surveys',
  2601. 'get_survey_data',
  2602. 2
  2603. );
  2604. $table->set_additional_parameters($parameters);
  2605. $table->set_header(0, '', false);
  2606. $table->set_header(1, get_lang('SurveyName'));
  2607. $table->set_header(2, get_lang('SurveyCode'));
  2608. $table->set_header(3, get_lang('NumberOfQuestions'));
  2609. $table->set_header(4, get_lang('Author'));
  2610. //$table->set_header(5, get_lang('Language'));
  2611. //$table->set_header(6, get_lang('Shared'));
  2612. $table->set_header(5, get_lang('AvailableFrom'));
  2613. $table->set_header(6, get_lang('AvailableUntil'));
  2614. $table->set_header(7, get_lang('Invite'));
  2615. $table->set_header(8, get_lang('Anonymous'));
  2616. if (api_get_configuration_value('allow_mandatory_survey')) {
  2617. $table->set_header(9, get_lang('IsMandatory'));
  2618. $table->set_header(10, get_lang('Modify'), false, 'width="150"');
  2619. $table->set_column_filter(8, 'anonymous_filter');
  2620. $table->set_column_filter(10, 'modify_filter');
  2621. } else {
  2622. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  2623. $table->set_column_filter(9, 'modify_filter');
  2624. }
  2625. $table->set_column_filter(8, 'anonymous_filter');
  2626. $table->set_form_actions(['delete' => get_lang('DeleteSurvey')]);
  2627. $table->display();
  2628. }
  2629. /**
  2630. * Survey list for coach.
  2631. */
  2632. public static function display_survey_list_for_coach()
  2633. {
  2634. $parameters = [];
  2635. $parameters['cidReq'] = api_get_course_id();
  2636. if (isset($_GET['do_search'])) {
  2637. $message = get_lang('DisplaySearchResults').'<br />';
  2638. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  2639. echo Display::return_message($message, 'normal', false);
  2640. }
  2641. // Create a sortable table with survey-data
  2642. $table = new SortableTable(
  2643. 'surveys_coach',
  2644. 'get_number_of_surveys_for_coach',
  2645. 'get_survey_data_for_coach',
  2646. 2
  2647. );
  2648. $table->set_additional_parameters($parameters);
  2649. $table->set_header(0, '', false);
  2650. $table->set_header(1, get_lang('SurveyName'));
  2651. $table->set_header(2, get_lang('SurveyCode'));
  2652. $table->set_header(3, get_lang('NumberOfQuestions'));
  2653. $table->set_header(4, get_lang('Author'));
  2654. $table->set_header(5, get_lang('AvailableFrom'));
  2655. $table->set_header(6, get_lang('AvailableUntil'));
  2656. $table->set_header(7, get_lang('Invite'));
  2657. $table->set_header(8, get_lang('Anonymous'));
  2658. if (api_get_configuration_value('allow_mandatory_survey')) {
  2659. $table->set_header(9, get_lang('Modify'), false, 'width="130"');
  2660. $table->set_header(10, get_lang('Modify'), false, 'width="130"');
  2661. $table->set_column_filter(8, 'anonymous_filter');
  2662. $table->set_column_filter(10, 'modify_filter_for_coach');
  2663. } else {
  2664. $table->set_header(9, get_lang('Modify'), false, 'width="130"');
  2665. $table->set_column_filter(9, 'modify_filter_for_coach');
  2666. }
  2667. $table->set_column_filter(8, 'anonymous_filter');
  2668. $table->display();
  2669. }
  2670. /**
  2671. * Check if the hide_survey_edition configurations setting is enabled.
  2672. *
  2673. * @param string $surveyCode
  2674. *
  2675. * @return bool
  2676. */
  2677. public static function checkHideEditionToolsByCode($surveyCode)
  2678. {
  2679. $hideSurveyEdition = api_get_configuration_value('hide_survey_edition');
  2680. if (false === $hideSurveyEdition) {
  2681. return false;
  2682. }
  2683. if ('*' === $hideSurveyEdition['codes']) {
  2684. return true;
  2685. }
  2686. if (in_array($surveyCode, $hideSurveyEdition['codes'])) {
  2687. return true;
  2688. }
  2689. return false;
  2690. }
  2691. /**
  2692. * This function changes the modify column of the sortable table.
  2693. *
  2694. * @param int $survey_id the id of the survey
  2695. * @param bool $drh
  2696. *
  2697. * @throws \Doctrine\ORM\ORMException
  2698. * @throws \Doctrine\ORM\OptimisticLockException
  2699. * @throws \Doctrine\ORM\TransactionRequiredException
  2700. *
  2701. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2702. *
  2703. * @return string html code that are the actions that can be performed on any survey
  2704. *
  2705. * @version January 2007
  2706. */
  2707. public static function modify_filter($survey_id, $drh = false)
  2708. {
  2709. /** @var CSurvey $survey */
  2710. $survey = Database::getManager()->find('ChamiloCourseBundle:CSurvey', $survey_id);
  2711. $hideSurveyEdition = self::checkHideEditionToolsByCode($survey->getCode());
  2712. if ($hideSurveyEdition) {
  2713. return '';
  2714. }
  2715. if (empty($survey)) {
  2716. return '';
  2717. }
  2718. $survey_id = $survey->getSurveyId();
  2719. $actions = [];
  2720. $hideReportingButton = api_get_configuration_value('hide_survey_reporting_button');
  2721. $codePath = api_get_path(WEB_CODE_PATH);
  2722. $params = [];
  2723. parse_str(api_get_cidreq(), $params);
  2724. $reportingLink = Display::url(
  2725. Display::return_icon('statistics.png', get_lang('Reporting')),
  2726. $codePath.'survey/reporting.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2727. );
  2728. if ($drh) {
  2729. return $hideReportingButton ? '-' : $reportingLink;
  2730. }
  2731. $type = $survey->getSurveyType();
  2732. // Coach can see that only if the survey is in his session
  2733. if (api_is_allowed_to_edit() ||
  2734. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  2735. ) {
  2736. $editUrl = $codePath.'survey/create_new_survey.php?'.
  2737. http_build_query($params + ['action' => 'edit', 'survey_id' => $survey_id]);
  2738. if ($survey->getSurveyType() == 3) {
  2739. $editUrl = $codePath.'survey/edit_meeting.php?'.
  2740. http_build_query($params + ['action' => 'edit', 'survey_id' => $survey_id]);
  2741. }
  2742. $actions[] = Display::url(
  2743. Display::return_icon('edit.png', get_lang('Edit')),
  2744. $editUrl
  2745. );
  2746. if (SurveyManager::survey_generation_hash_available()) {
  2747. $actions[] = Display::url(
  2748. Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink')),
  2749. $codePath.'survey/generate_link.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2750. );
  2751. }
  2752. if ($type != 3) {
  2753. $actions[] = Display::url(
  2754. Display::return_icon('backup.png', get_lang('CopySurvey')),
  2755. $codePath.'survey/copy_survey.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2756. );
  2757. $actions[] = Display::url(
  2758. Display::return_icon('copy.png', get_lang('DuplicateSurvey')),
  2759. $codePath.'survey/survey_list.php?'
  2760. .http_build_query($params + ['action' => 'copy_survey', 'survey_id' => $survey_id])
  2761. );
  2762. $actions[] = Display::url(
  2763. Display::return_icon('multiplicate_survey.png', get_lang('MultiplicateQuestions')),
  2764. $codePath.'survey/survey_list.php?'
  2765. .http_build_query($params + ['action' => 'multiplicate', 'survey_id' => $survey_id])
  2766. );
  2767. $actions[] = Display::url(
  2768. Display::return_icon('multiplicate_survey_na.png', get_lang('RemoveMultiplicateQuestions')),
  2769. $codePath.'survey/survey_list.php?'
  2770. .http_build_query($params + ['action' => 'remove_multiplicate', 'survey_id' => $survey_id])
  2771. );
  2772. $warning = addslashes(api_htmlentities(get_lang('EmptySurvey').'?', ENT_QUOTES));
  2773. $actions[] = Display::url(
  2774. Display::return_icon('clean.png', get_lang('EmptySurvey')),
  2775. $codePath.'survey/survey_list.php?'
  2776. .http_build_query($params + ['action' => 'empty', 'survey_id' => $survey_id]),
  2777. [
  2778. 'onclick' => "javascript: if (!confirm('".$warning."')) return false;",
  2779. ]
  2780. );
  2781. }
  2782. }
  2783. if ($type != 3) {
  2784. $actions[] = Display::url(
  2785. Display::return_icon('preview_view.png', get_lang('Preview')),
  2786. $codePath.'survey/preview.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2787. );
  2788. }
  2789. $actions[] = Display::url(
  2790. Display::return_icon('mail_send.png', get_lang('Publish')),
  2791. $codePath.'survey/survey_invite.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2792. );
  2793. if ($type != 3) {
  2794. $actions[] = $hideReportingButton ? null : $reportingLink;
  2795. }
  2796. if (api_is_allowed_to_edit() ||
  2797. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  2798. ) {
  2799. $actions[] = self::getAdditionalTeacherActions($survey_id);
  2800. $warning = addslashes(api_htmlentities(get_lang('DeleteSurvey').'?', ENT_QUOTES));
  2801. $actions[] = Display::url(
  2802. Display::return_icon('delete.png', get_lang('Delete')),
  2803. $codePath.'survey/survey_list.php?'
  2804. .http_build_query($params + ['action' => 'delete', 'survey_id' => $survey_id]),
  2805. [
  2806. 'onclick' => "javascript: if (!confirm('".$warning."')) return false;",
  2807. ]
  2808. );
  2809. }
  2810. return implode(PHP_EOL, $actions);
  2811. }
  2812. /**
  2813. * Get the additional actions added in survey_additional_teacher_modify_actions configuration.
  2814. *
  2815. * @param int $surveyId
  2816. * @param int $iconSize
  2817. *
  2818. * @return string
  2819. */
  2820. public static function getAdditionalTeacherActions($surveyId, $iconSize = ICON_SIZE_SMALL)
  2821. {
  2822. $additionalActions = api_get_configuration_value('survey_additional_teacher_modify_actions') ?: [];
  2823. if (empty($additionalActions)) {
  2824. return '';
  2825. }
  2826. $actions = [];
  2827. foreach ($additionalActions as $additionalAction) {
  2828. $actions[] = call_user_func(
  2829. $additionalAction,
  2830. ['survey_id' => $surveyId, 'icon_size' => $iconSize]
  2831. );
  2832. }
  2833. return implode(PHP_EOL, $actions);
  2834. }
  2835. /**
  2836. * @param int $survey_id
  2837. *
  2838. * @return string
  2839. */
  2840. public static function modify_filter_for_coach($survey_id)
  2841. {
  2842. $survey_id = (int) $survey_id;
  2843. $actions = [];
  2844. $codePath = api_get_path(WEB_CODE_PATH);
  2845. $params = [];
  2846. parse_str(api_get_cidreq(), $params);
  2847. $actions[] = Display::url(
  2848. Display::return_icon('preview_view.png', get_lang('Preview')),
  2849. $codePath.'survey/preview.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2850. );
  2851. $actions[] = Display::url(
  2852. Display::return_icon('mail_send.png', get_lang('Publish')),
  2853. $codePath.'survey/survey_invite.php?'.http_build_query($params + ['survey_id' => $survey_id])
  2854. );
  2855. $warning = addslashes(api_htmlentities(get_lang('EmptySurvey').'?', ENT_QUOTES));
  2856. $actions[] = Display::url(
  2857. Display::return_icon('clean.png', get_lang('EmptySurvey')),
  2858. $codePath.'survey/survey_list.php?'
  2859. .http_build_query($params + ['action' => 'empty', 'survey_id' => $survey_id]),
  2860. [
  2861. 'onclick' => "javascript: if(!confirm('".$warning."')) return false;",
  2862. ]
  2863. );
  2864. return implode(PHP_EOL, $actions);
  2865. }
  2866. /**
  2867. * Returns "yes" when given parameter is one, "no" for any other value.
  2868. *
  2869. * @param int Whether anonymous or not
  2870. *
  2871. * @return string "Yes" or "No" in the current language
  2872. */
  2873. public static function anonymous_filter($anonymous)
  2874. {
  2875. if ($anonymous == 1) {
  2876. return get_lang('Yes');
  2877. } else {
  2878. return get_lang('No');
  2879. }
  2880. }
  2881. /**
  2882. * This function handles the search restriction for the SQL statements.
  2883. *
  2884. * @return string Part of a SQL statement or false on error
  2885. *
  2886. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2887. *
  2888. * @version January 2007
  2889. */
  2890. public static function survey_search_restriction()
  2891. {
  2892. if (isset($_GET['do_search'])) {
  2893. if ($_GET['keyword_title'] != '') {
  2894. $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
  2895. }
  2896. if ($_GET['keyword_code'] != '') {
  2897. $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
  2898. }
  2899. if ($_GET['keyword_language'] != '%') {
  2900. $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
  2901. }
  2902. $my_search_term = ($search_term == null) ? [] : $search_term;
  2903. $search_restriction = implode(' AND ', $my_search_term);
  2904. return $search_restriction;
  2905. } else {
  2906. return false;
  2907. }
  2908. }
  2909. /**
  2910. * This function calculates the total number of surveys.
  2911. *
  2912. * @return int Total number of surveys
  2913. *
  2914. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2915. *
  2916. * @version January 2007
  2917. */
  2918. public static function get_number_of_surveys()
  2919. {
  2920. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2921. $course_id = api_get_course_int_id();
  2922. $search_restriction = self::survey_search_restriction();
  2923. if ($search_restriction) {
  2924. $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
  2925. } else {
  2926. $search_restriction = "WHERE c_id = $course_id";
  2927. }
  2928. $sql = "SELECT count(survey_id) AS total_number_of_items
  2929. FROM $table_survey $search_restriction";
  2930. $res = Database::query($sql);
  2931. $obj = Database::fetch_object($res);
  2932. return $obj->total_number_of_items;
  2933. }
  2934. /**
  2935. * @return int
  2936. */
  2937. public static function get_number_of_surveys_for_coach()
  2938. {
  2939. $survey_tree = new SurveyTree();
  2940. return count($survey_tree->surveylist);
  2941. }
  2942. /**
  2943. * This function gets all the survey data that is to be displayed in the sortable table.
  2944. *
  2945. * @param int $from
  2946. * @param int $number_of_items
  2947. * @param int $column
  2948. * @param string $direction
  2949. * @param bool $isDrh
  2950. *
  2951. * @return array
  2952. *
  2953. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2954. * @author Julio Montoya <gugli100@gmail.com>, Beeznest - Adding intvals
  2955. *
  2956. * @version January 2007
  2957. */
  2958. public static function get_survey_data(
  2959. $from,
  2960. $number_of_items,
  2961. $column,
  2962. $direction,
  2963. $isDrh = false
  2964. ) {
  2965. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2966. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2967. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  2968. $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
  2969. $_user = api_get_user_info();
  2970. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  2971. // Searching
  2972. $search_restriction = self::survey_search_restriction();
  2973. if ($search_restriction) {
  2974. $search_restriction = ' AND '.$search_restriction;
  2975. }
  2976. $from = (int) $from;
  2977. $number_of_items = (int) $number_of_items;
  2978. $column = (int) $column;
  2979. if (!in_array(strtolower($direction), ['asc', 'desc'])) {
  2980. $direction = 'asc';
  2981. }
  2982. // Condition for the session
  2983. $session_id = api_get_session_id();
  2984. $condition_session = api_get_session_condition($session_id);
  2985. $course_id = api_get_course_int_id();
  2986. $sql = "
  2987. SELECT
  2988. survey.survey_id AS col0,
  2989. survey.title AS col1,
  2990. survey.code AS col2,
  2991. count(survey_question.question_id) AS col3, "
  2992. .(api_is_western_name_order()
  2993. ? "CONCAT(user.firstname, ' ', user.lastname)"
  2994. : "CONCAT(user.lastname, ' ', user.firstname)")
  2995. ." AS col4,
  2996. survey.avail_from AS col5,
  2997. survey.avail_till AS col6,
  2998. survey.invited AS col7,
  2999. survey.anonymous AS col8,
  3000. survey.iid AS col9,
  3001. survey.session_id AS session_id,
  3002. survey.answered,
  3003. survey.invited,
  3004. survey.survey_type
  3005. FROM $table_survey survey
  3006. LEFT JOIN $table_survey_question survey_question
  3007. ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
  3008. LEFT JOIN $table_user user
  3009. ON (survey.author = user.user_id)
  3010. WHERE survey.c_id = $course_id
  3011. $search_restriction
  3012. $condition_session
  3013. GROUP BY survey.survey_id
  3014. ORDER BY col$column $direction
  3015. LIMIT $from,$number_of_items
  3016. ";
  3017. $res = Database::query($sql);
  3018. $surveys = [];
  3019. $array = [];
  3020. $efv = new ExtraFieldValue('survey');
  3021. while ($survey = Database::fetch_array($res)) {
  3022. $array[0] = $survey[0];
  3023. if (self::checkHideEditionToolsByCode($survey['col2'])) {
  3024. $array[1] = $survey[1];
  3025. } else {
  3026. // Doodle
  3027. if ($survey['survey_type'] == 3) {
  3028. $array[1] = Display::url(
  3029. $survey[1],
  3030. api_get_path(WEB_CODE_PATH).'survey/meeting.php?survey_id='.$survey[0].'&'.api_get_cidreq()
  3031. );
  3032. } else {
  3033. $array[1] = Display::url(
  3034. $survey[1],
  3035. api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
  3036. );
  3037. }
  3038. }
  3039. // Validation when belonging to a session
  3040. $session_img = api_get_session_image($survey['session_id'], $_user['status']);
  3041. $array[2] = $survey[2].$session_img;
  3042. $array[3] = $survey[3];
  3043. $array[4] = $survey[4];
  3044. // Dates
  3045. $array[5] = '';
  3046. if (!empty($survey[5]) && $survey[5] !== '0000-00-00' && $survey[5] !== '0000-00-00 00:00:00') {
  3047. $array[5] = api_convert_and_format_date(
  3048. $survey[5],
  3049. $allowSurveyAvailabilityDatetime ? DATE_TIME_FORMAT_LONG : DATE_FORMAT_LONG
  3050. );
  3051. }
  3052. $array[6] = '';
  3053. if (!empty($survey[6]) && $survey[6] !== '0000-00-00' && $survey[6] !== '0000-00-00 00:00:00') {
  3054. $array[6] = api_convert_and_format_date(
  3055. $survey[6],
  3056. $allowSurveyAvailabilityDatetime ? DATE_TIME_FORMAT_LONG : DATE_FORMAT_LONG
  3057. );
  3058. }
  3059. $array[7] =
  3060. Display::url(
  3061. $survey['answered'],
  3062. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'
  3063. .api_get_cidreq()
  3064. ).' / '.
  3065. Display::url(
  3066. $survey['invited'],
  3067. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'
  3068. .api_get_cidreq()
  3069. );
  3070. // Anon
  3071. $array[8] = $survey['col8'];
  3072. if ($mandatoryAllowed) {
  3073. $efvMandatory = $efv->get_values_by_handler_and_field_variable(
  3074. $survey[9],
  3075. 'is_mandatory'
  3076. );
  3077. $array[9] = $efvMandatory ? $efvMandatory['value'] : 0;
  3078. // Survey id
  3079. $array[10] = $survey['col9'];
  3080. } else {
  3081. // Survey id
  3082. $array[9] = $survey['col9'];
  3083. }
  3084. if ($isDrh) {
  3085. $array[1] = $survey[1];
  3086. $array[7] = strip_tags($array[7]);
  3087. }
  3088. $surveys[] = $array;
  3089. }
  3090. return $surveys;
  3091. }
  3092. /**
  3093. * @param $from
  3094. * @param $number_of_items
  3095. * @param $column
  3096. * @param $direction
  3097. *
  3098. * @return array
  3099. */
  3100. public static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
  3101. {
  3102. $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
  3103. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  3104. $survey_tree = new SurveyTree();
  3105. $last_version_surveys = $survey_tree->surveylist;
  3106. $list = [];
  3107. foreach ($last_version_surveys as &$survey) {
  3108. $list[] = $survey['id'];
  3109. }
  3110. if (count($list) > 0) {
  3111. $list_condition = " AND survey.survey_id IN (".implode(',', $list).") ";
  3112. } else {
  3113. $list_condition = '';
  3114. }
  3115. $from = (int) $from;
  3116. $number_of_items = (int) $number_of_items;
  3117. $column = (int) $column;
  3118. if (!in_array(strtolower($direction), ['asc', 'desc'])) {
  3119. $direction = 'asc';
  3120. }
  3121. $table_survey = Database::get_course_table(TABLE_SURVEY);
  3122. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  3123. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  3124. $course_id = api_get_course_int_id();
  3125. $efv = new ExtraFieldValue('survey');
  3126. $sql = "
  3127. SELECT
  3128. survey.survey_id AS col0,
  3129. survey.title AS col1,
  3130. survey.code AS col2,
  3131. count(survey_question.question_id) AS col3,
  3132. "
  3133. .(api_is_western_name_order()
  3134. ? "CONCAT(user.firstname, ' ', user.lastname)"
  3135. : "CONCAT(user.lastname, ' ', user.firstname)")
  3136. ." AS col4,
  3137. survey.avail_from AS col5,
  3138. survey.avail_till AS col6,
  3139. CONCAT('<a href=\"survey_invitation.php?view=answered&survey_id=',survey.survey_id,'\">',survey.answered,'</a> / <a href=\"survey_invitation.php?view=invited&survey_id=',survey.survey_id,'\">',survey.invited, '</a>') AS col7,
  3140. survey.anonymous AS col8,
  3141. survey.survey_id AS col9
  3142. FROM $table_survey survey
  3143. LEFT JOIN $table_survey_question survey_question
  3144. ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id),
  3145. $table_user user
  3146. WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition
  3147. ";
  3148. $sql .= ' GROUP BY survey.survey_id';
  3149. $sql .= " ORDER BY col$column $direction ";
  3150. $sql .= " LIMIT $from,$number_of_items";
  3151. $res = Database::query($sql);
  3152. $surveys = [];
  3153. while ($survey = Database::fetch_array($res)) {
  3154. $survey['col5'] = api_convert_and_format_date(
  3155. $survey['col5'],
  3156. $allowSurveyAvailabilityDatetime ? DATE_TIME_FORMAT_LONG : DATE_FORMAT_LONG
  3157. );
  3158. $survey['col6'] = api_convert_and_format_date(
  3159. $survey['col6'],
  3160. $allowSurveyAvailabilityDatetime ? DATE_TIME_FORMAT_LONG : DATE_FORMAT_LONG
  3161. );
  3162. if ($mandatoryAllowed) {
  3163. $survey['col10'] = $survey['col9'];
  3164. $efvMandatory = $efv->get_values_by_handler_and_field_variable(
  3165. $survey['col9'],
  3166. 'is_mandatory'
  3167. );
  3168. $survey['col9'] = $efvMandatory['value'];
  3169. }
  3170. $surveys[] = $survey;
  3171. }
  3172. return $surveys;
  3173. }
  3174. /**
  3175. * Display all the active surveys for the given course user.
  3176. *
  3177. * @param int $user_id
  3178. *
  3179. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3180. *
  3181. * @version April 2007
  3182. */
  3183. public static function getSurveyList($user_id)
  3184. {
  3185. $_course = api_get_course_info();
  3186. $course_id = $_course['real_id'];
  3187. $user_id = (int) $user_id;
  3188. $sessionId = api_get_session_id();
  3189. $mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
  3190. $allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
  3191. // Database table definitions
  3192. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  3193. $table_survey = Database::get_course_table(TABLE_SURVEY);
  3194. echo '<table id="list-survey" class="table ">';
  3195. echo '<thead>';
  3196. echo '<tr>';
  3197. echo ' <th>'.get_lang('SurveyName').'</th>';
  3198. echo ' <th class="text-center">'.get_lang('Anonymous').'</th>';
  3199. if ($mandatoryAllowed) {
  3200. echo '<th class="text-center">'.get_lang('IsMandatory').'</th>';
  3201. }
  3202. echo '</tr>';
  3203. echo '</thead>';
  3204. echo '<tbody>';
  3205. /** @var \DateTime $now */
  3206. $now = api_get_utc_datetime(null, false, true);
  3207. $filterDate = $allowSurveyAvailabilityDatetime ? $now->format('Y-m-d H:i') : $now->format('Y-m-d');
  3208. $sql = "SELECT survey_invitation.answered,
  3209. survey_invitation.invitation_code,
  3210. survey_invitation.session_id,
  3211. survey.title,
  3212. survey.visible_results,
  3213. survey.survey_id,
  3214. survey.anonymous
  3215. FROM $table_survey survey
  3216. INNER JOIN
  3217. $table_survey_invitation survey_invitation
  3218. ON (
  3219. survey.code = survey_invitation.survey_code AND
  3220. survey.c_id = survey_invitation.c_id AND
  3221. survey.session_id = survey_invitation.session_id
  3222. )
  3223. WHERE
  3224. survey_invitation.user = $user_id AND
  3225. survey.avail_from <= '$filterDate' AND
  3226. survey.avail_till >= '$filterDate' AND
  3227. survey.c_id = $course_id AND
  3228. survey.session_id = $sessionId AND
  3229. survey_invitation.c_id = $course_id
  3230. ";
  3231. $result = Database::query($sql);
  3232. $efv = new ExtraFieldValue('survey');
  3233. $surveyIds = [];
  3234. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3235. if (in_array($row['survey_id'], $surveyIds)) {
  3236. continue;
  3237. }
  3238. echo '<tr>';
  3239. if ($row['answered'] == 0) {
  3240. echo '<td>';
  3241. echo Display::return_icon(
  3242. 'statistics.png',
  3243. get_lang('CreateNewSurvey'),
  3244. [],
  3245. ICON_SIZE_TINY
  3246. );
  3247. $url = self::generateFillSurveyLink($row['invitation_code'], $_course, $row['session_id']);
  3248. echo '<a href="'.$url.'">
  3249. '.$row['title']
  3250. .'</a></td>';
  3251. } else {
  3252. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  3253. $user_id,
  3254. $_course
  3255. );
  3256. $icon = Display::return_icon(
  3257. 'statistics_na.png',
  3258. get_lang('Survey'),
  3259. [],
  3260. ICON_SIZE_TINY
  3261. );
  3262. $showLink = (!api_is_allowed_to_edit(false, true) || $isDrhOfCourse)
  3263. && $row['visible_results'] != SURVEY_VISIBLE_TUTOR;
  3264. echo '<td>';
  3265. echo $showLink
  3266. ? Display::url(
  3267. $icon.PHP_EOL.$row['title'],
  3268. api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&'.http_build_query([
  3269. 'action' => 'questionreport',
  3270. 'survey_id' => $row['survey_id'],
  3271. ])
  3272. )
  3273. : $icon.PHP_EOL.$row['title'];
  3274. echo '</td>';
  3275. }
  3276. echo '<td class="text-center">';
  3277. echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
  3278. echo '</td>';
  3279. if ($mandatoryAllowed) {
  3280. $efvMandatory = $efv->get_values_by_handler_and_field_variable(
  3281. $row['survey_id'],
  3282. 'is_mandatory'
  3283. );
  3284. echo '<td class="text-center">'.($efvMandatory['value'] ? get_lang('Yes') : get_lang('No')).'</td>';
  3285. }
  3286. echo '</tr>';
  3287. $surveyIds[] = $row['survey_id'];
  3288. }
  3289. echo '</tbody>';
  3290. echo '</table>';
  3291. }
  3292. /**
  3293. * Creates a multi array with the user fields that we can show.
  3294. * We look the visibility with the api_get_setting function
  3295. * The username is always NOT able to change it.
  3296. *
  3297. * @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification
  3298. *
  3299. * @return array array[value_name][name], array[value_name][visibilty]
  3300. */
  3301. public static function make_field_list()
  3302. {
  3303. // LAST NAME and FIRST NAME
  3304. $field_list_array = [];
  3305. $field_list_array['lastname']['name'] = get_lang('LastName');
  3306. $field_list_array['firstname']['name'] = get_lang('FirstName');
  3307. if (api_get_setting('profile', 'name') != 'true') {
  3308. $field_list_array['firstname']['visibility'] = 0;
  3309. $field_list_array['lastname']['visibility'] = 0;
  3310. } else {
  3311. $field_list_array['firstname']['visibility'] = 1;
  3312. $field_list_array['lastname']['visibility'] = 1;
  3313. }
  3314. $field_list_array['username']['name'] = get_lang('Username');
  3315. $field_list_array['username']['visibility'] = 0;
  3316. // OFFICIAL CODE
  3317. $field_list_array['official_code']['name'] = get_lang('OfficialCode');
  3318. if (api_get_setting('profile', 'officialcode') != 'true') {
  3319. $field_list_array['official_code']['visibility'] = 1;
  3320. } else {
  3321. $field_list_array['official_code']['visibility'] = 0;
  3322. }
  3323. // EMAIL
  3324. $field_list_array['email']['name'] = get_lang('Email');
  3325. if (api_get_setting('profile', 'email') != 'true') {
  3326. $field_list_array['email']['visibility'] = 1;
  3327. } else {
  3328. $field_list_array['email']['visibility'] = 0;
  3329. }
  3330. // PHONE
  3331. $field_list_array['phone']['name'] = get_lang('Phone');
  3332. if (api_get_setting('profile', 'phone') != 'true') {
  3333. $field_list_array['phone']['visibility'] = 0;
  3334. } else {
  3335. $field_list_array['phone']['visibility'] = 1;
  3336. }
  3337. // LANGUAGE
  3338. $field_list_array['language']['name'] = get_lang('Language');
  3339. if (api_get_setting('profile', 'language') != 'true') {
  3340. $field_list_array['language']['visibility'] = 0;
  3341. } else {
  3342. $field_list_array['language']['visibility'] = 1;
  3343. }
  3344. // EXTRA FIELDS
  3345. $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  3346. foreach ($extra as $id => $field_details) {
  3347. if ($field_details[6] == 0) {
  3348. continue;
  3349. }
  3350. switch ($field_details[2]) {
  3351. case UserManager::USER_FIELD_TYPE_TEXT:
  3352. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3353. if ($field_details[7] == 0) {
  3354. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3355. } else {
  3356. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3357. }
  3358. break;
  3359. case UserManager::USER_FIELD_TYPE_TEXTAREA:
  3360. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3361. if ($field_details[7] == 0) {
  3362. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3363. } else {
  3364. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3365. }
  3366. break;
  3367. case UserManager::USER_FIELD_TYPE_RADIO:
  3368. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3369. if ($field_details[7] == 0) {
  3370. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3371. } else {
  3372. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3373. }
  3374. break;
  3375. case UserManager::USER_FIELD_TYPE_SELECT:
  3376. $get_lang_variables = false;
  3377. if (in_array(
  3378. $field_details[1],
  3379. ['mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message']
  3380. )
  3381. ) {
  3382. $get_lang_variables = true;
  3383. }
  3384. if ($get_lang_variables) {
  3385. $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
  3386. } else {
  3387. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3388. }
  3389. if ($field_details[7] == 0) {
  3390. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3391. } else {
  3392. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3393. }
  3394. break;
  3395. case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
  3396. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3397. if ($field_details[7] == 0) {
  3398. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3399. } else {
  3400. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3401. }
  3402. break;
  3403. case UserManager::USER_FIELD_TYPE_DATE:
  3404. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3405. if ($field_details[7] == 0) {
  3406. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3407. } else {
  3408. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3409. }
  3410. break;
  3411. case UserManager::USER_FIELD_TYPE_DATETIME:
  3412. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3413. if ($field_details[7] == 0) {
  3414. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3415. } else {
  3416. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3417. }
  3418. break;
  3419. case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
  3420. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  3421. if ($field_details[7] == 0) {
  3422. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  3423. } else {
  3424. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  3425. }
  3426. break;
  3427. case UserManager::USER_FIELD_TYPE_DIVIDER:
  3428. //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
  3429. break;
  3430. }
  3431. }
  3432. return $field_list_array;
  3433. }
  3434. /**
  3435. * @author Isaac Flores Paz <florespaz@bidsoftperu.com>
  3436. *
  3437. * @param int $user_id User ID
  3438. * @param string $survey_code
  3439. * @param int $user_answer User in survey answer table (user id or anonymous)
  3440. *
  3441. * @return bool
  3442. */
  3443. public static function show_link_available($user_id, $survey_code, $user_answer)
  3444. {
  3445. $table_survey = Database::get_course_table(TABLE_SURVEY);
  3446. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  3447. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  3448. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  3449. $survey_code = Database::escape_string($survey_code);
  3450. $user_id = (int) $user_id;
  3451. $user_answer = Database::escape_string($user_answer);
  3452. $course_id = api_get_course_int_id();
  3453. $sql = 'SELECT COUNT(*) as count
  3454. FROM '.$table_survey_invitation.'
  3455. WHERE
  3456. user='.$user_id.' AND
  3457. survey_code="'.$survey_code.'" AND
  3458. answered="1" AND
  3459. c_id = '.$course_id;
  3460. $sql2 = 'SELECT COUNT(*) as count
  3461. FROM '.$table_survey.' s
  3462. INNER JOIN '.$table_survey_question.' q
  3463. ON s.survey_id=q.survey_id AND s.c_id = q.c_id
  3464. WHERE
  3465. s.code="'.$survey_code.'" AND
  3466. q.type NOT IN("pagebreak","comment") AND
  3467. s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
  3468. $sql3 = 'SELECT COUNT(DISTINCT question_id) as count
  3469. FROM '.$table_survey_answer.'
  3470. WHERE survey_id=(
  3471. SELECT survey_id FROM '.$table_survey.'
  3472. WHERE
  3473. code = "'.$survey_code.'" AND
  3474. c_id = '.$course_id.'
  3475. ) AND
  3476. user="'.$user_answer.'" AND
  3477. c_id = '.$course_id;
  3478. $result = Database::query($sql);
  3479. $result2 = Database::query($sql2);
  3480. $result3 = Database::query($sql3);
  3481. $row = Database::fetch_array($result, 'ASSOC');
  3482. $row2 = Database::fetch_array($result2, 'ASSOC');
  3483. $row3 = Database::fetch_array($result3, 'ASSOC');
  3484. if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
  3485. return true;
  3486. } else {
  3487. return false;
  3488. }
  3489. }
  3490. /**
  3491. * Display survey question chart.
  3492. *
  3493. * @param array $chartData
  3494. * @param bool $hasSerie Tells if the chart has a serie. False by default
  3495. * @param string $chartContainerId
  3496. *
  3497. * @return string (direct output)
  3498. */
  3499. public static function drawChart(
  3500. $chartData,
  3501. $hasSerie = false,
  3502. $chartContainerId = 'chartContainer'
  3503. ) {
  3504. $htmlChart = '';
  3505. if (api_browser_support('svg')) {
  3506. $htmlChart .= api_get_js('d3/d3.v3.5.4.min.js');
  3507. $htmlChart .= api_get_js('dimple.v2.1.2.min.js').'
  3508. <script>
  3509. var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
  3510. var data = [';
  3511. $serie = [];
  3512. $order = [];
  3513. foreach ($chartData as $chartDataElement) {
  3514. $htmlChart .= '{"';
  3515. if (!$hasSerie) {
  3516. $htmlChart .= get_lang("Option").'":"'.$chartDataElement['option'].'", "';
  3517. array_push($order, $chartDataElement['option']);
  3518. } else {
  3519. if (!is_array($chartDataElement['serie'])) {
  3520. $htmlChart .= get_lang("Option").'":"'.$chartDataElement['serie'].'", "'.
  3521. get_lang("Score").'":"'.$chartDataElement['option'].'", "';
  3522. array_push($serie, $chartDataElement['serie']);
  3523. } else {
  3524. $htmlChart .= get_lang("Serie").'":"'.$chartDataElement['serie'][0].'", "'.
  3525. get_lang("Option").'":"'.$chartDataElement['serie'][1].'", "'.
  3526. get_lang("Score").'":"'.$chartDataElement['option'].'", "';
  3527. }
  3528. }
  3529. $htmlChart .= get_lang("Votes").'":"'.$chartDataElement['votes'].
  3530. '"},';
  3531. }
  3532. rtrim($htmlChart, ",");
  3533. $htmlChart .= '];
  3534. var myChart = new dimple.chart(svg, data);
  3535. myChart.addMeasureAxis("y", "'.get_lang("Votes").'");';
  3536. if (!$hasSerie) {
  3537. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "'.get_lang("Option").'");
  3538. xAxisCategory.addOrderRule('.json_encode($order).');
  3539. myChart.addSeries("'.get_lang("Option").'", dimple.plot.bar);';
  3540. } else {
  3541. if (!is_array($chartDataElement['serie'])) {
  3542. $serie = array_values(array_unique($serie));
  3543. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'
  3544. .get_lang("Score").'"]);
  3545. xAxisCategory.addOrderRule('.json_encode($serie).');
  3546. xAxisCategory.addGroupOrderRule("'.get_lang("Score").'");
  3547. myChart.addSeries("'.get_lang("Option").'", dimple.plot.bar);';
  3548. } else {
  3549. $htmlChart .= 'myChart.addCategoryAxis("x", ["'.get_lang("Option").'","'.get_lang("Score").'"]);
  3550. myChart.addSeries("'.get_lang("Serie").'", dimple.plot.bar);';
  3551. }
  3552. }
  3553. $htmlChart .= 'myChart.draw();
  3554. </script>';
  3555. }
  3556. return $htmlChart;
  3557. }
  3558. /**
  3559. * Set a flag to the current survey as answered by the current user.
  3560. *
  3561. * @param string $surveyCode The survey code
  3562. * @param int $courseId The course ID
  3563. */
  3564. public static function flagSurveyAsAnswered($surveyCode, $courseId)
  3565. {
  3566. $currentUserId = api_get_user_id();
  3567. $flag = sprintf('%s-%s-%d', $courseId, $surveyCode, $currentUserId);
  3568. if (!isset($_SESSION['filled_surveys'])) {
  3569. $_SESSION['filled_surveys'] = [];
  3570. }
  3571. $_SESSION['filled_surveys'][] = $flag;
  3572. }
  3573. /**
  3574. * Check whether a survey was answered by the current user.
  3575. *
  3576. * @param string $surveyCode The survey code
  3577. * @param int $courseId The course ID
  3578. *
  3579. * @return bool
  3580. */
  3581. public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
  3582. {
  3583. $currentUserId = api_get_user_id();
  3584. $flagToCheck = sprintf('%s-%s-%d', $courseId, $surveyCode, $currentUserId);
  3585. if (!isset($_SESSION['filled_surveys'])) {
  3586. return false;
  3587. }
  3588. if (!is_array($_SESSION['filled_surveys'])) {
  3589. return false;
  3590. }
  3591. foreach ($_SESSION['filled_surveys'] as $flag) {
  3592. if ($flagToCheck != $flag) {
  3593. continue;
  3594. }
  3595. return true;
  3596. }
  3597. return false;
  3598. }
  3599. /**
  3600. * Check if the current survey has answers.
  3601. *
  3602. * @param int $surveyId
  3603. *
  3604. * @return bool return true if the survey has answers, false otherwise
  3605. */
  3606. public static function checkIfSurveyHasAnswers($surveyId)
  3607. {
  3608. $tableSurveyAnswer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  3609. $courseId = api_get_course_int_id();
  3610. $surveyId = (int) $surveyId;
  3611. if (empty($courseId) || empty($surveyId)) {
  3612. return false;
  3613. }
  3614. $sql = "SELECT * FROM $tableSurveyAnswer
  3615. WHERE
  3616. c_id = $courseId AND
  3617. survey_id = '".$surveyId."'
  3618. ORDER BY answer_id, user ASC";
  3619. $result = Database::query($sql);
  3620. $response = Database::affected_rows($result);
  3621. return $response > 0;
  3622. }
  3623. /**
  3624. * Get the pending surveys for a user.
  3625. *
  3626. * @param int $userId
  3627. *
  3628. * @return array
  3629. */
  3630. public static function getUserPendingInvitations($userId)
  3631. {
  3632. $now = api_get_utc_datetime(null, false, true);
  3633. $dql = "
  3634. SELECT s, si FROM ChamiloCourseBundle:CSurvey s
  3635. INNER JOIN ChamiloCourseBundle:CSurveyInvitation si
  3636. WITH (s.code = si.surveyCode AND s.cId = si.cId AND s.sessionId = si.sessionId )
  3637. WHERE
  3638. si.user = :user_id AND
  3639. s.availFrom <= :now AND
  3640. s.availTill >= :now AND
  3641. si.answered = 0
  3642. ORDER BY s.availTill ASC
  3643. ";
  3644. $pendingSurveys = Database::getManager()
  3645. ->createQuery($dql)
  3646. ->setParameters(['user_id' => $userId, 'now' => $now->format('Y-m-d')])
  3647. ->getResult();
  3648. return $pendingSurveys;
  3649. }
  3650. /**
  3651. * @param string $surveyCode
  3652. * @param int $courseId
  3653. * @param int $sessionId
  3654. *
  3655. * @return array
  3656. */
  3657. public static function getSentInvitations($surveyCode, $courseId, $sessionId = 0)
  3658. {
  3659. $tblUser = Database::get_main_table(TABLE_MAIN_USER);
  3660. $tblSurveyInvitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  3661. $sessionCondition = api_get_session_condition($sessionId);
  3662. $surveyCode = Database::escape_string($surveyCode);
  3663. $courseId = (int) $courseId;
  3664. $sql = "SELECT survey_invitation.*, user.firstname, user.lastname, user.email
  3665. FROM $tblSurveyInvitation survey_invitation
  3666. LEFT JOIN $tblUser user
  3667. ON (survey_invitation.user = user.id AND survey_invitation.c_id = $courseId)
  3668. WHERE
  3669. survey_invitation.survey_code = '$surveyCode'
  3670. AND survey_invitation.c_id = $courseId
  3671. $sessionCondition";
  3672. $query = Database::query($sql);
  3673. return Database::store_result($query);
  3674. }
  3675. /**
  3676. * @param string $code invitation code
  3677. * @param array $courseInfo
  3678. * @param int $sessionId
  3679. * @param string $surveyCode
  3680. *
  3681. * @return string
  3682. */
  3683. public static function generateFillSurveyLink($code, $courseInfo, $sessionId, $surveyCode = '')
  3684. {
  3685. $code = Security::remove_XSS($code);
  3686. $sessionId = (int) $sessionId;
  3687. if (empty($courseInfo)) {
  3688. return '';
  3689. }
  3690. $params = [
  3691. 'invitationcode' => $code,
  3692. 'cidReq' => $courseInfo['code'],
  3693. 'course' => $courseInfo['code'],
  3694. 'id_session' => $sessionId,
  3695. ];
  3696. if (!empty($surveyCode)) {
  3697. $params['scode'] = Security::remove_XSS($surveyCode);
  3698. }
  3699. return api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?'.http_build_query($params);
  3700. }
  3701. }