surveyUtil.class.php 157 KB

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