survey.lib.php 209 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class SurveyManager
  5. * @package chamilo.survey
  6. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University:
  7. * cleanup, refactoring and rewriting large parts (if not all) of the code
  8. * @author Julio Montoya <gugli100@gmail.com>, Personality Test modification
  9. * and rewriting large parts of the code
  10. * @author cfasanando
  11. * @todo move this file to inc/lib
  12. * @todo use consistent naming for the functions (save vs store for instance)
  13. */
  14. class SurveyManager
  15. {
  16. /**
  17. * @param $code
  18. *
  19. * @return string
  20. */
  21. public static function generate_unique_code($code)
  22. {
  23. if (empty($code)) {
  24. return false;
  25. }
  26. $course_id = api_get_course_int_id();
  27. $table_survey = Database::get_course_table(TABLE_SURVEY);
  28. $code = Database::escape_string($code);
  29. $num = 0;
  30. $new_code = $code;
  31. while (true) {
  32. $sql = "SELECT * FROM $table_survey
  33. WHERE code = '$new_code' AND c_id = $course_id";
  34. $result = Database::query($sql);
  35. if (Database::num_rows($result)) {
  36. $num++;
  37. $new_code = $code . $num;
  38. } else {
  39. break;
  40. }
  41. }
  42. return $code.$num;
  43. }
  44. /**
  45. * Deletes all survey invitations of a user
  46. * @param int $user_id
  47. *
  48. * @return boolean
  49. * @assert ('') === false
  50. */
  51. public static function delete_all_survey_invitations_by_user($user_id)
  52. {
  53. $user_id = intval($user_id);
  54. if (empty($user_id)) {
  55. return false;
  56. }
  57. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  58. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  59. $sql = "SELECT survey_invitation_id, survey_code
  60. FROM $table_survey_invitation WHERE user = '$user_id' AND c_id <> 0 ";
  61. $result = Database::query($sql);
  62. while ($row = Database::fetch_array($result ,'ASSOC')){
  63. $survey_invitation_id = $row['survey_invitation_id'];
  64. $survey_code = $row['survey_code'];
  65. $sql2 = "DELETE FROM $table_survey_invitation
  66. WHERE survey_invitation_id = '$survey_invitation_id' AND c_id <> 0";
  67. if (Database::query($sql2)) {
  68. $sql3 = "UPDATE $table_survey SET
  69. invited = invited-1
  70. WHERE c_id <> 0 AND code ='$survey_code'";
  71. Database::query($sql3);
  72. }
  73. }
  74. }
  75. /**
  76. *
  77. * @param string $course_code
  78. * @param int $session_id
  79. * @return type
  80. * @assert ('') === false
  81. */
  82. public static function get_surveys($course_code, $session_id = 0)
  83. {
  84. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  85. if (empty($course_code)) {
  86. return false;
  87. }
  88. $course_info = api_get_course_info($course_code);
  89. $session_condition = api_get_session_condition($session_id, true, true);
  90. $sql = "SELECT * FROM $table_survey
  91. WHERE c_id = {$course_info['real_id']} $session_condition ";
  92. $result = Database::query($sql);
  93. $result = Database::store_result($result, 'ASSOC');
  94. return $result;
  95. }
  96. /**
  97. * Retrieves all the survey information
  98. *
  99. * @param integer $survey_id the id of the survey
  100. * @param boolean $shared this parameter determines if
  101. * we have to get the information of a survey from the central (shared) database or from the
  102. * course database
  103. * @param string course code optional
  104. *
  105. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  106. * @version February 2007
  107. * @assert ('') === false
  108. *
  109. * @todo this is the same function as in create_new_survey.php
  110. */
  111. public static function get_survey($survey_id, $shared = 0, $course_code = '', $simple_return = false)
  112. {
  113. // Table definition
  114. if (!empty($course_code)) {
  115. $my_course_id = $course_code;
  116. } else if (isset($_GET['course'])) {
  117. $my_course_id = Security::remove_XSS($_GET['course']);
  118. } else {
  119. $my_course_id = api_get_course_id();
  120. }
  121. $my_course_info = api_get_course_info($my_course_id);
  122. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  123. if ($shared != 0) {
  124. $table_survey = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  125. $sql = "SELECT * FROM $table_survey
  126. WHERE survey_id='".intval($survey_id)."' ";
  127. } else {
  128. $sql = "SELECT * FROM $table_survey
  129. WHERE
  130. survey_id='".intval($survey_id)."' AND
  131. c_id = ".$my_course_info['real_id'];
  132. }
  133. $result = Database::query($sql);
  134. $return = array();
  135. if (Database::num_rows($result)> 0) {
  136. $return = Database::fetch_array($result,'ASSOC');
  137. if ($simple_return) {
  138. return $return;
  139. }
  140. // We do this (temporarily) to have the array match the quickform elements immediately
  141. // idealiter the fields in the db match the quickform fields
  142. $return['survey_code'] = $return['code'];
  143. $return['survey_title'] = $return['title'];
  144. $return['survey_subtitle'] = $return['subtitle'];
  145. $return['survey_language'] = $return['lang'];
  146. $return['start_date'] = $return['avail_from'];
  147. $return['end_date'] = $return['avail_till'];
  148. $return['survey_share'] = $return['is_shared'];
  149. $return['survey_introduction'] = $return['intro'];
  150. $return['survey_thanks'] = $return['surveythanks'];
  151. $return['survey_type'] = $return['survey_type'];
  152. $return['one_question_per_page'] = $return['one_question_per_page'];
  153. $return['show_form_profile'] = $return['show_form_profile'];
  154. $return['input_name_list'] = isset($return['input_name_list']) ? $return['input_name_list'] : null;
  155. $return['shuffle'] = $return['shuffle'];
  156. $return['parent_id'] = $return['parent_id'];
  157. $return['survey_version'] = $return['survey_version'];
  158. $return['anonymous'] = $return['anonymous'];
  159. }
  160. return $return;
  161. }
  162. /**
  163. * This function stores a survey in the database.
  164. *
  165. * @param array $values
  166. *
  167. * @return array $return the type of return message that has to be displayed and the message in it
  168. *
  169. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  170. * @version February 2007
  171. */
  172. public static function store_survey($values)
  173. {
  174. $_user = api_get_user_info();
  175. $course_id = api_get_course_int_id();
  176. $session_id = api_get_session_id();
  177. $courseCode = api_get_course_id();
  178. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  179. $shared_survey_id = 0;
  180. if (!isset($values['survey_id'])) {
  181. // Check if the code doesn't soon exists in this language
  182. $sql = 'SELECT 1 FROM '.$table_survey.'
  183. WHERE
  184. c_id = '.$course_id.' AND
  185. code="'.Database::escape_string($values['survey_code']).'" AND
  186. lang="'.Database::escape_string($values['survey_language']).'"';
  187. $rs = Database::query($sql);
  188. if (Database::num_rows($rs) > 0) {
  189. Display::addFlash(
  190. Display::return_message(
  191. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  192. 'error'
  193. )
  194. );
  195. $return['type'] = 'error';
  196. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  197. return $return;
  198. }
  199. if (!isset($values['anonymous'])) {
  200. $values['anonymous'] = 0;
  201. }
  202. $values['anonymous'] = intval($values['anonymous']);
  203. $additional['columns'] = '';
  204. $extraParams = [];
  205. if ($values['anonymous'] == 0) {
  206. // Input_name_list
  207. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : 0;
  208. $extraParams['show_form_profile'] = $values['show_form_profile'];
  209. if ($values['show_form_profile'] == 1) {
  210. // Input_name_list
  211. $fields = explode(',', $values['input_name_list']);
  212. $field_values = '';
  213. foreach ($fields as & $field) {
  214. if ($field != '') {
  215. if ($values[$field] == '') {
  216. $values[$field] = 0;
  217. }
  218. $field_values.= $field.':'.$values[$field].'@';
  219. }
  220. }
  221. $extraParams['form_fields'] = $field_values;
  222. } else {
  223. $extraParams['form_fields'] = '';
  224. }
  225. } else {
  226. // Input_name_list
  227. $extraParams['show_form_profile'] = 0;
  228. $extraParams['form_fields'] = '';
  229. }
  230. if ($values['survey_type'] == 1) {
  231. $extraParams['survey_type'] = 1;
  232. $extraParams['shuffle'] = $values['shuffle'];
  233. $extraParams['one_question_per_page'] = $values['one_question_per_page'];
  234. $extraParams['parent_id'] = $values['parent_id'];
  235. // Logic for versioning surveys
  236. if (!empty($values['parent_id'])) {
  237. $versionValue = '';
  238. $sql = 'SELECT survey_version
  239. FROM '.$table_survey.'
  240. WHERE
  241. c_id = '.$course_id.' AND
  242. parent_id = '.intval($values['parent_id']).'
  243. ORDER BY survey_version DESC
  244. LIMIT 1';
  245. $rs = Database::query($sql);
  246. if (Database::num_rows($rs) === 0) {
  247. $sql = 'SELECT survey_version FROM '.$table_survey.'
  248. WHERE
  249. c_id = '.$course_id.' AND
  250. survey_id = '.intval($values['parent_id']);
  251. $rs = Database::query($sql);
  252. $getversion = Database::fetch_array($rs, 'ASSOC');
  253. if (empty($getversion['survey_version'])) {
  254. $versionValue = ++$getversion['survey_version'];
  255. } else {
  256. $versionValue = $getversion['survey_version'];
  257. }
  258. } else {
  259. $row = Database::fetch_array($rs, 'ASSOC');
  260. $pos = api_strpos($row['survey_version']);
  261. if ($pos === false) {
  262. $row['survey_version'] = $row['survey_version'] + 1;
  263. $versionValue = $row['survey_version'];
  264. } else {
  265. $getlast = explode('\.', $row['survey_version']);
  266. $lastversion = array_pop($getlast);
  267. $lastversion = $lastversion + 1;
  268. $add = implode('.', $getlast);
  269. if ($add != '') {
  270. $insertnewversion = $add.'.'.$lastversion;
  271. } else {
  272. $insertnewversion = $lastversion;
  273. }
  274. $versionValue = $insertnewversion;
  275. }
  276. }
  277. $extraParams['survey_version'] = $versionValue;
  278. }
  279. }
  280. $params = [
  281. 'c_id' => $course_id,
  282. 'code' => strtolower(CourseManager::generate_course_code($values['survey_code'])),
  283. 'title' => $values['survey_title'],
  284. 'subtitle' => $values['survey_subtitle'],
  285. 'author' => $_user['user_id'],
  286. 'lang' => $values['survey_language'],
  287. 'avail_from' => $values['start_date'],
  288. 'avail_till' => $values['end_date'],
  289. 'is_shared' => $shared_survey_id,
  290. 'template' => 'template',
  291. 'intro' => $values['survey_introduction'],
  292. 'surveythanks' => $values['survey_thanks'],
  293. 'creation_date' => api_get_utc_datetime(),
  294. 'anonymous' => $values['anonymous'],
  295. 'session_id' => api_get_session_id(),
  296. 'visible_results' => $values['visible_results']
  297. ];
  298. $params = array_merge($params, $extraParams);
  299. $survey_id = Database::insert($table_survey, $params);
  300. if ($survey_id > 0) {
  301. $sql = "UPDATE $table_survey SET survey_id = $survey_id
  302. WHERE iid = $survey_id";
  303. Database::query($sql);
  304. // Insert into item_property
  305. api_item_property_update(
  306. api_get_course_info(),
  307. TOOL_SURVEY,
  308. $survey_id,
  309. 'SurveyAdded',
  310. api_get_user_id()
  311. );
  312. }
  313. if ($values['survey_type'] == 1 && !empty($values['parent_id'])) {
  314. SurveyManager::copy_survey($values['parent_id'], $survey_id);
  315. }
  316. Display::addFlash(
  317. Display::return_message(
  318. get_lang('SurveyCreatedSuccesfully'),
  319. 'success'
  320. )
  321. );
  322. $return['id'] = $survey_id;
  323. } else {
  324. // Check whether the code doesn't soon exists in this language
  325. $sql = 'SELECT 1 FROM '.$table_survey.'
  326. WHERE
  327. c_id = '.$course_id.' AND
  328. code = "'.Database::escape_string($values['survey_code']).'" AND
  329. lang = "'.Database::escape_string($values['survey_language']).'" AND
  330. survey_id !='.intval($values['survey_id']);
  331. $rs = Database::query($sql);
  332. if (Database::num_rows($rs) > 0) {
  333. Display::addFlash(
  334. Display::return_message(
  335. get_lang('ThisSurveyCodeSoonExistsInThisLanguage'),
  336. 'error'
  337. )
  338. );
  339. $return['type'] = 'error';
  340. $return['id'] = isset($values['survey_id']) ? $values['survey_id'] : 0;
  341. return $return;
  342. }
  343. if (!isset($values['anonymous']) ||
  344. (isset($values['anonymous']) && $values['anonymous'] == '')
  345. ) {
  346. $values['anonymous'] = 0;
  347. }
  348. $values['shuffle'] = isset($values['shuffle']) ? $values['shuffle'] : null;
  349. $values['one_question_per_page'] = isset($values['one_question_per_page']) ? $values['one_question_per_page'] : null;
  350. $values['show_form_profile'] = isset($values['show_form_profile']) ? $values['show_form_profile'] : null;
  351. $extraParams = [];
  352. $extraParams['shuffle'] = $values['shuffle'];
  353. $extraParams['one_question_per_page'] = $values['one_question_per_page'];
  354. $extraParams['shuffle'] = $values['shuffle'];
  355. if ($values['anonymous'] == 0) {
  356. $extraParams['show_form_profile'] = $values['show_form_profile'];
  357. if ($values['show_form_profile'] == 1) {
  358. $fields = explode(',',$values['input_name_list']);
  359. $field_values = '';
  360. foreach ($fields as &$field) {
  361. if ($field != '') {
  362. if (!isset($values[$field]) ||
  363. (isset($values[$field]) && $values[$field] == '')
  364. ) {
  365. $values[$field] = 0;
  366. }
  367. $field_values.= $field.':'.$values[$field].'@';
  368. }
  369. }
  370. $extraParams['form_fields'] = $field_values;
  371. } else {
  372. $extraParams['form_fields'] = '';
  373. }
  374. } else {
  375. $extraParams['show_form_profile'] = 0;
  376. $extraParams['form_fields'] = '';
  377. }
  378. $params = [
  379. 'title' => $values['survey_title'],
  380. 'subtitle' => $values['survey_subtitle'],
  381. 'author' => $_user['user_id'],
  382. 'lang' => $values['survey_language'],
  383. 'avail_from' => $values['start_date'],
  384. 'avail_till' => $values['end_date'],
  385. 'is_shared' => $shared_survey_id,
  386. 'template' => 'template',
  387. 'intro' => $values['survey_introduction'],
  388. 'surveythanks' => $values['survey_thanks'],
  389. 'anonymous' => $values['anonymous'],
  390. 'session_id' => api_get_session_id(),
  391. 'visible_results' => $values['visible_results'],
  392. ];
  393. $params = array_merge($params, $extraParams);
  394. Database::update(
  395. $table_survey,
  396. $params,
  397. [
  398. 'c_id = ? AND survey_id = ?' => [
  399. $course_id,
  400. $values['survey_id'],
  401. ],
  402. ]
  403. );
  404. // Update into item_property (update)
  405. api_item_property_update(
  406. api_get_course_info(),
  407. TOOL_SURVEY,
  408. $values['survey_id'],
  409. 'SurveyUpdated',
  410. api_get_user_id()
  411. );
  412. Display::addFlash(
  413. Display::return_message(
  414. get_lang('SurveyUpdatedSuccesfully'),
  415. 'confirmation'
  416. )
  417. );
  418. $return['id'] = $values['survey_id'];
  419. }
  420. $survey_id = intval($return['id']);
  421. // Gradebook
  422. $gradebook_option = false;
  423. if (isset($values['survey_qualify_gradebook'])) {
  424. $gradebook_option = $values['survey_qualify_gradebook'] > 0;
  425. }
  426. $gradebook_link_type = 8;
  427. $link_info = GradebookUtils::is_resource_in_course_gradebook(
  428. $courseCode,
  429. $gradebook_link_type,
  430. $survey_id,
  431. $session_id
  432. );
  433. $gradebook_link_id = $link_info ? $link_info->getId() : false;
  434. if ($gradebook_option) {
  435. if ($survey_id > 0) {
  436. $title_gradebook = ''; // Not needed here.
  437. $description_gradebook = ''; // Not needed here.
  438. $survey_weight = floatval($_POST['survey_weight']);
  439. $max_score = 1;
  440. if (!$gradebook_link_id) {
  441. GradebookUtils::add_resource_to_course_gradebook(
  442. $values['category_id'],
  443. $courseCode,
  444. $gradebook_link_type,
  445. $survey_id,
  446. $title_gradebook,
  447. $survey_weight,
  448. $max_score,
  449. $description_gradebook,
  450. 1,
  451. $session_id
  452. );
  453. } else {
  454. GradebookUtils::update_resource_from_course_gradebook(
  455. $gradebook_link_id,
  456. $courseCode,
  457. $survey_weight
  458. );
  459. }
  460. }
  461. } else {
  462. // Delete everything of the gradebook for this $linkId
  463. GradebookUtils::remove_resource_from_course_gradebook($gradebook_link_id);
  464. //comenting this line to correctly return the function msg
  465. //exit;
  466. }
  467. return $return;
  468. }
  469. /**
  470. * This function stores a shared survey in the central database.
  471. *
  472. * @param array $values
  473. * @return array $return the type of return message that has to be displayed and the message in it
  474. *
  475. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  476. * @version February 2007
  477. */
  478. public function store_shared_survey($values)
  479. {
  480. $em = Database::getManager();
  481. $_user = api_get_user_info();
  482. $course = $em->find('ChamiloCoreBundle:Course', api_get_course_int_id());
  483. if (!$values['survey_id'] ||
  484. !is_numeric($values['survey_id']) ||
  485. $values['survey_share']['survey_share'] == 'true'
  486. ) {
  487. $creationDate = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  488. $sharedSurvey = new \Chamilo\CoreBundle\Entity\SharedSurvey();
  489. $sharedSurvey
  490. ->setCode($values['survey_code'])
  491. ->setTitle($values['survey_title'])
  492. ->setSubtitle($values['survey_subtitle'])
  493. ->setAuthor(intval($_user['user_id']))
  494. ->setLang($values['survey_language'])
  495. ->setTemplate('template')
  496. ->setIntro($values['survey_introduction'])
  497. ->setSurveythanks($values['survey_thanks'])
  498. ->setCreationDate($creationDate)
  499. ->setCourse($course);
  500. $em->persist($sharedSurvey);
  501. $em->flush();
  502. $return = $sharedSurvey->getSurveyId();
  503. } else {
  504. $sharedSurvey = $em->find('ChamiloCoreBundle:SharedSurvey', $values['survey_share']['survey_share']);
  505. $sharedSurvey
  506. ->setCode($values['survey_code'])
  507. ->setTitle($values['survey_title'])
  508. ->setSubtitle($values['survey_subtitle'])
  509. ->setAuthor(intval($_user['user_id']))
  510. ->setLang($values['survey_language'])
  511. ->setTemplate('template')
  512. ->setIntro($values['survey_introduction'])
  513. ->setSurveythanks($values['survey_thanks']);
  514. $em->persist($sharedSurvey);
  515. $em->flush();
  516. $return = $values['survey_share']['survey_share'];
  517. }
  518. return $return;
  519. }
  520. /**
  521. * This function deletes a survey (and also all the question in that survey
  522. *
  523. * @param int $survey_id id of the survey that has to be deleted
  524. * @return true
  525. *
  526. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  527. * @version January 2007
  528. */
  529. public static function delete_survey($survey_id, $shared = false, $course_id = '')
  530. {
  531. // Database table definitions
  532. if (empty($course_id)) {
  533. $course_id = api_get_course_int_id();
  534. }
  535. $survey_id = intval($survey_id);
  536. if (empty($survey_id)) {
  537. return false;
  538. }
  539. $em = Database::getManager();
  540. $course_info = api_get_course_info_by_id($course_id);
  541. $course_id = $course_info['real_id'];
  542. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  543. $table_survey_question_group = Database :: get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  544. if ($shared) {
  545. // Deleting the survey
  546. $sharedSurvey = $em->find('ChamiloCoreBundle:SharedSurvey', $survey_id);
  547. if ($sharedSurvey) {
  548. $em->remove($sharedSurvey);
  549. $em->flush();
  550. }
  551. } else {
  552. $sql = "DELETE FROM $table_survey
  553. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  554. Database::query($sql);
  555. }
  556. // Deleting groups of this survey
  557. $sql = "DELETE FROM $table_survey_question_group
  558. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  559. Database::query($sql);
  560. // Deleting the questions of the survey
  561. SurveyManager::delete_all_survey_questions($survey_id, $shared);
  562. // Update into item_property (delete)
  563. api_item_property_update(
  564. $course_info,
  565. TOOL_SURVEY,
  566. $survey_id,
  567. 'SurveyDeleted',
  568. api_get_user_id()
  569. );
  570. return true;
  571. }
  572. /**
  573. * @param int $survey_id
  574. * @param int $new_survey_id
  575. * @param int $targetCourseId
  576. *
  577. * @return bool
  578. */
  579. public static function copy_survey($survey_id, $new_survey_id = null, $targetCourseId = null)
  580. {
  581. $course_id = api_get_course_int_id();
  582. if (!$targetCourseId) {
  583. $targetCourseId = $course_id;
  584. }
  585. // Database table definitions
  586. $table_survey = Database::get_course_table(TABLE_SURVEY);
  587. $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
  588. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  589. $table_survey_options = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  590. $survey_id = intval($survey_id);
  591. // Get groups
  592. $survey_data = self::get_survey($survey_id, 0, null, true);
  593. if (empty($survey_data)) {
  594. return true;
  595. }
  596. if (empty($new_survey_id)) {
  597. $params = $survey_data;
  598. $params['code'] = self::generate_unique_code($params['code']);
  599. $params['c_id'] = $targetCourseId;
  600. unset($params['survey_id']);
  601. $params['session_id'] = api_get_session_id();
  602. $params['title'] = $params['title'] . ' ' . get_lang('Copy');
  603. unset($params['iid']);
  604. Database::insert($table_survey, $params);
  605. $new_survey_id = Database::insert_id();
  606. if ($new_survey_id) {
  607. $sql = "UPDATE $table_survey SET survey_id = $new_survey_id
  608. WHERE iid = $new_survey_id";
  609. Database::query($sql);
  610. // Insert into item_property
  611. api_item_property_update(
  612. api_get_course_info(),
  613. TOOL_SURVEY,
  614. $new_survey_id,
  615. 'SurveyAdded',
  616. api_get_user_id()
  617. );
  618. }
  619. } else {
  620. $new_survey_id = intval($new_survey_id);
  621. }
  622. $sql = "SELECT * FROM $table_survey_question_group
  623. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  624. $res = Database::query($sql);
  625. while($row = Database::fetch_array($res, 'ASSOC')) {
  626. $params = array(
  627. 'c_id' => $targetCourseId,
  628. 'name' => $row['name'],
  629. 'description' => $row['description'],
  630. 'survey_id' => $new_survey_id
  631. );
  632. $insertId = Database::insert($table_survey_question_group, $params);
  633. $sql = "UPDATE $table_survey_question_group SET id = iid
  634. WHERE iid = $insertId";
  635. Database::query($sql);
  636. $group_id[$row['id']] = $insertId;
  637. }
  638. // Get questions
  639. $sql = "SELECT * FROM $table_survey_question
  640. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  641. $res = Database::query($sql);
  642. while ($row = Database::fetch_array($res, 'ASSOC')) {
  643. $params = array(
  644. 'c_id' => $targetCourseId,
  645. 'survey_id' => $new_survey_id,
  646. 'survey_question' => $row['survey_question'],
  647. 'survey_question_comment' => $row['survey_question_comment'],
  648. 'type' => $row['type'],
  649. 'display' => $row['display'],
  650. 'sort' => $row['sort'],
  651. 'shared_question_id' => $row['shared_question_id'],
  652. 'max_value' => $row['max_value'],
  653. 'survey_group_pri' => $row['survey_group_pri'],
  654. 'survey_group_sec1' => $row['survey_group_sec1'],
  655. 'survey_group_sec2' => $row['survey_group_sec2']
  656. );
  657. $insertId = Database::insert($table_survey_question, $params);
  658. $sql = "UPDATE $table_survey_question SET question_id = iid WHERE iid = $insertId";
  659. Database::query($sql);
  660. $question_id[$row['question_id']] = $insertId;
  661. }
  662. // Get questions options
  663. $sql = "SELECT * FROM $table_survey_options
  664. WHERE c_id = $course_id AND survey_id='".$survey_id."'";
  665. $res = Database::query($sql);
  666. while ($row = Database::fetch_array($res ,'ASSOC')) {
  667. $params = array(
  668. 'c_id' => $targetCourseId,
  669. 'question_id' => $question_id[$row['question_id']],
  670. 'survey_id' => $new_survey_id,
  671. 'option_text' => $row['option_text'],
  672. 'sort' => $row['sort'],
  673. 'value' => $row['value']
  674. );
  675. $insertId = Database::insert($table_survey_options, $params);
  676. $sql = "UPDATE $table_survey_options SET question_option_id = $insertId
  677. WHERE iid = $insertId";
  678. Database::query($sql);
  679. }
  680. return $new_survey_id;
  681. }
  682. /**
  683. * This function duplicates a survey (and also all the question in that survey
  684. *
  685. * @param int $survey_id id of the survey that has to be duplicated
  686. * @param int $courseId id of the course which survey has to be duplicated
  687. * @return true
  688. *
  689. * @author Eric Marguin <e.marguin@elixir-interactive.com>, Elixir Interactive
  690. * @version October 2007
  691. */
  692. public static function empty_survey($survey_id, $courseId = null)
  693. {
  694. // Database table definitions
  695. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  696. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  697. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  698. $course_id = $courseId ? $courseId : api_get_course_int_id();
  699. $datas = SurveyManager::get_survey($survey_id);
  700. $session_where = '';
  701. if (api_get_session_id() != 0) {
  702. $session_where = ' AND session_id = "'.api_get_session_id().'" ';
  703. }
  704. $sql = 'DELETE FROM '.$table_survey_invitation.'
  705. WHERE
  706. c_id = '.$course_id.' AND
  707. survey_code = "'.Database::escape_string($datas['code']).'" '.$session_where.' ';
  708. Database::query($sql);
  709. $sql = 'DELETE FROM '.$table_survey_answer.'
  710. WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
  711. Database::query($sql);
  712. $sql = 'UPDATE '.$table_survey.' SET invited=0, answered=0
  713. WHERE c_id = '.$course_id.' AND survey_id='.intval($survey_id);
  714. Database::query($sql);
  715. return true;
  716. }
  717. /**
  718. * This function recalculates the number of people who have taken the survey (=filled at least one question)
  719. *
  720. * @param int $survey_id the id of the survey somebody
  721. * @return true
  722. *
  723. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  724. * @version February 2007
  725. */
  726. public static function update_survey_answered($survey_data, $user, $survey_code)
  727. {
  728. // Database table definitions
  729. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  730. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  731. $survey_id = $survey_data['survey_id'];
  732. $course_id = $survey_data['c_id'];
  733. $session_id = $survey_data['session_id'];
  734. // Getting a list with all the people who have filled the survey
  735. $people_filled = SurveyManager::get_people_who_filled_survey($survey_id, false, $course_id);
  736. $number = intval(count($people_filled));
  737. // Storing this value in the survey table
  738. $sql = "UPDATE $table_survey
  739. SET answered = $number
  740. WHERE
  741. c_id = $course_id AND
  742. survey_id = ".intval($survey_id);
  743. Database::query($sql);
  744. // Storing that the user has finished the survey.
  745. $sql = "UPDATE $table_survey_invitation SET answered='1'
  746. WHERE
  747. c_id = $course_id AND
  748. session_id='".$session_id."' AND
  749. user='".Database::escape_string($user)."' AND
  750. survey_code='".Database::escape_string($survey_code)."'";
  751. Database::query($sql);
  752. }
  753. /***
  754. * SURVEY QUESTION FUNCTIONS
  755. */
  756. /**
  757. * This function return the "icon" of the question type
  758. *
  759. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  760. * @version February 2007
  761. */
  762. public static function icon_question($type)
  763. {
  764. // the possible question types
  765. $possible_types = array(
  766. 'personality',
  767. 'yesno',
  768. 'multiplechoice',
  769. 'multipleresponse',
  770. 'open',
  771. 'dropdown',
  772. 'comment',
  773. 'pagebreak',
  774. 'percentage',
  775. 'score',
  776. );
  777. // the images array
  778. $icon_question = array(
  779. 'yesno' => 'yesno.png',
  780. 'personality' => 'yesno.png',
  781. 'multiplechoice' => 'mcua.png',
  782. 'multipleresponse' => 'mcma.png',
  783. 'open' => 'open_answer.png',
  784. 'dropdown' => 'dropdown.png',
  785. 'percentage' => 'percentagequestion.png',
  786. 'score' => 'scorequestion.png',
  787. 'comment' => 'commentquestion.png',
  788. 'pagebreak' => 'page_end.png',
  789. );
  790. if (in_array($type, $possible_types)) {
  791. return $icon_question[$type];
  792. } else {
  793. return false;
  794. }
  795. }
  796. /**
  797. * This function retrieves all the information of a question
  798. *
  799. * @param integer $question_id the id of the question
  800. * @return array
  801. *
  802. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  803. * @version January 2007
  804. *
  805. * @todo one sql call should do the trick
  806. */
  807. public static function get_question($question_id, $shared = false)
  808. {
  809. // Table definitions
  810. $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  811. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  812. $course_id = api_get_course_int_id();
  813. $sql = "SELECT * FROM $tbl_survey_question
  814. WHERE c_id = $course_id AND question_id='".intval($question_id)."'
  815. ORDER BY `sort` ";
  816. $sqlOption = " SELECT * FROM $table_survey_question_option
  817. WHERE c_id = $course_id AND question_id='".intval($question_id)."'
  818. ORDER BY `sort` ";
  819. if ($shared) {
  820. $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  821. $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  822. $sql = "SELECT * FROM $tbl_survey_question
  823. WHERE question_id='".intval($question_id)."'
  824. ORDER BY `sort` ";
  825. $sqlOption = "SELECT * FROM $table_survey_question_option
  826. WHERE question_id='".intval($question_id)."'
  827. ORDER BY `sort` ";
  828. }
  829. // Getting the information of the question
  830. $result = Database::query($sql);
  831. $row = Database::fetch_array($result,'ASSOC');
  832. $return['survey_id'] = $row['survey_id'];
  833. $return['question_id'] = $row['question_id'];
  834. $return['type'] = $row['type'];
  835. $return['question'] = $row['survey_question'];
  836. $return['horizontalvertical'] = $row['display'];
  837. $return['shared_question_id'] = $row['shared_question_id'];
  838. $return['maximum_score'] = $row['max_value'];
  839. if ($row['survey_group_pri'] != 0) {
  840. $return['assigned'] = $row['survey_group_pri'];
  841. $return['choose'] = 1;
  842. } else {
  843. $return['assigned1'] = $row['survey_group_sec1'];
  844. $return['assigned2'] = $row['survey_group_sec2'];
  845. $return['choose'] = 2;
  846. }
  847. // Getting the information of the question options
  848. $result = Database::query($sqlOption);
  849. while ($row = Database::fetch_array($result, 'ASSOC')) {
  850. /** @todo this should be renamed to options instead of answers */
  851. $return['answers'][] = $row['option_text'];
  852. $return['values'][] = $row['value'];
  853. /** @todo this can be done more elegantly (used in reporting) */
  854. $return['answersid'][] = $row['question_option_id'];
  855. }
  856. return $return;
  857. }
  858. /**
  859. * This function gets all the question of any given survey
  860. *
  861. * @param integer $survey_id the id of the survey
  862. * @return array containing all the questions of the survey
  863. *
  864. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  865. * @version February 2007
  866. *
  867. * @todo one sql call should do the trick
  868. */
  869. public static function get_questions($survey_id, $course_id = '')
  870. {
  871. // Table definitions
  872. $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  873. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  874. if (empty($course_id)) {
  875. $course_id = api_get_course_int_id();
  876. }
  877. $return = array();
  878. // Getting the information of the question
  879. $sql = "SELECT * FROM $tbl_survey_question
  880. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
  881. $result = Database::query($sql);
  882. $return = array();
  883. while ($row = Database::fetch_array($result, 'ASSOC')) {
  884. $return[$row['question_id']]['survey_id'] = $row['survey_id'];
  885. $return[$row['question_id']]['question_id'] = $row['question_id'];
  886. $return[$row['question_id']]['type'] = $row['type'];
  887. $return[$row['question_id']]['question'] = $row['survey_question'];
  888. $return[$row['question_id']]['horizontalvertical'] = $row['display'];
  889. $return[$row['question_id']]['maximum_score'] = $row['max_value'];
  890. $return[$row['question_id']]['sort'] = $row['sort'];
  891. }
  892. // Getting the information of the question options
  893. $sql = "SELECT * FROM $table_survey_question_option
  894. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'";
  895. $result = Database::query($sql);
  896. while ($row = Database::fetch_array($result, 'ASSOC')) {
  897. $return[$row['question_id']]['answers'][] = $row['option_text'];
  898. }
  899. return $return;
  900. }
  901. /**
  902. * This function saves a question in the database.
  903. * This can be either an update of an existing survey or storing a new survey
  904. * @param array $survey_data
  905. * @param array $form_content all the information of the form
  906. *
  907. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  908. * @version January 2007
  909. */
  910. public static function save_question($survey_data, $form_content)
  911. {
  912. $return_message = '';
  913. if (strlen($form_content['question']) > 1) {
  914. // Checks length of the question
  915. $empty_answer = false;
  916. if ($survey_data['survey_type'] == 1) {
  917. if (empty($form_content['choose'])) {
  918. $return_message = 'PleaseChooseACondition';
  919. return $return_message;
  920. }
  921. if (($form_content['choose'] == 2) &&
  922. ($form_content['assigned1'] == $form_content['assigned2'])
  923. ) {
  924. $return_message = 'ChooseDifferentCategories';
  925. return $return_message;
  926. }
  927. }
  928. if ($form_content['type'] != 'percentage') {
  929. if (isset($form_content['answers'])) {
  930. for ($i = 0; $i < count($form_content['answers']); $i++) {
  931. if (strlen($form_content['answers'][$i]) < 1) {
  932. $empty_answer = true;
  933. break;
  934. }
  935. }
  936. }
  937. }
  938. if ($form_content['type'] == 'score') {
  939. if (strlen($form_content['maximum_score']) < 1) {
  940. $empty_answer = true;
  941. }
  942. }
  943. $additional = array();
  944. $course_id = api_get_course_int_id();
  945. if (!$empty_answer) {
  946. // Table definitions
  947. $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  948. // Getting all the information of the survey
  949. $survey_data = SurveyManager::get_survey($form_content['survey_id']);
  950. // Storing the question in the shared database
  951. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  952. $shared_question_id = SurveyManager::save_shared_question($form_content, $survey_data);
  953. $form_content['shared_question_id'] = $shared_question_id;
  954. }
  955. // Storing a new question
  956. if ($form_content['question_id'] == '' || !is_numeric($form_content['question_id'])) {
  957. // Finding the max sort order of the questions in the given survey
  958. $sql = "SELECT max(sort) AS max_sort
  959. FROM $tbl_survey_question
  960. WHERE c_id = $course_id AND survey_id='".intval($form_content['survey_id'])."'";
  961. $result = Database::query($sql);
  962. $row = Database::fetch_array($result,'ASSOC');
  963. $max_sort = $row['max_sort'];
  964. // Some variables defined for survey-test type
  965. $extraParams = [];
  966. if (isset($_POST['choose'])) {
  967. if ($_POST['choose'] == 1) {
  968. $extraParams['survey_group_pri'] = $_POST['assigned'];
  969. } elseif ($_POST['choose'] == 2) {
  970. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  971. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  972. }
  973. }
  974. $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : '';
  975. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : '';
  976. $display = isset($form_content['horizontalvertical']) ? $form_content['horizontalvertical'] : '';
  977. $params = [
  978. 'c_id' => $course_id,
  979. 'survey_id' => $form_content['survey_id'],
  980. 'survey_question' => $form_content['question'],
  981. 'survey_question_comment' => $questionComment,
  982. 'type' => $form_content['type'],
  983. 'display' => $display,
  984. 'sort' => $max_sort + 1,
  985. 'shared_question_id' => $form_content['shared_question_id'],
  986. 'max_value' => $maxScore,
  987. ];
  988. $params = array_merge($params, $extraParams);
  989. $question_id = Database::insert($tbl_survey_question, $params);
  990. if ($question_id) {
  991. $sql = "UPDATE $tbl_survey_question SET question_id = $question_id
  992. WHERE iid = $question_id";
  993. Database::query($sql);
  994. $form_content['question_id'] = $question_id;
  995. $return_message = 'QuestionAdded';
  996. }
  997. } else {
  998. // Updating an existing question
  999. $extraParams = [];
  1000. if (isset($_POST['choose'])) {
  1001. if ($_POST['choose'] == 1) {
  1002. $extraParams['survey_group_pri'] = $_POST['assigned'];
  1003. $extraParams['survey_group_sec1'] = 0;
  1004. $extraParams['survey_group_sec2'] = 0;
  1005. } elseif ($_POST['choose'] == 2) {
  1006. $extraParams['survey_group_pri'] = 0;
  1007. $extraParams['survey_group_sec1'] = $_POST['assigned1'];
  1008. $extraParams['survey_group_sec2'] = $_POST['assigned2'];
  1009. }
  1010. }
  1011. $maxScore = isset($form_content['maximum_score']) ? $form_content['maximum_score'] : null;
  1012. $questionComment = isset($form_content['question_comment']) ? $form_content['question_comment'] : null;
  1013. // Adding the question to the survey_question table
  1014. $params = [
  1015. 'survey_question' => $form_content['question'],
  1016. 'survey_question_comment' => $questionComment,
  1017. 'display' => $form_content['horizontalvertical'],
  1018. ];
  1019. $params = array_merge($params, $extraParams);
  1020. Database::update(
  1021. $tbl_survey_question,
  1022. $params,
  1023. [
  1024. 'c_id = ? AND question_id = ?' => [
  1025. $course_id,
  1026. $form_content['question_id'],
  1027. ],
  1028. ]
  1029. );
  1030. $return_message = 'QuestionUpdated';
  1031. }
  1032. if (!empty($form_content['survey_id'])) {
  1033. //Updating survey
  1034. api_item_property_update(
  1035. api_get_course_info(),
  1036. TOOL_SURVEY,
  1037. $form_content['survey_id'],
  1038. 'SurveyUpdated',
  1039. api_get_user_id()
  1040. );
  1041. }
  1042. // Storing the options of the question
  1043. SurveyManager::save_question_options($form_content, $survey_data);
  1044. } else {
  1045. $return_message = 'PleasFillAllAnswer';
  1046. }
  1047. } else {
  1048. $return_message = 'PleaseEnterAQuestion';
  1049. }
  1050. if (!empty($return_message)) {
  1051. Display::addFlash(Display::return_message(get_lang($return_message)));
  1052. }
  1053. return $return_message;
  1054. }
  1055. /**
  1056. * This function saves the question in the shared database
  1057. *
  1058. * @param array $form_content all the information of the form
  1059. * @param array $survey_data all the information of the survey
  1060. *
  1061. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1062. * @version February 2007
  1063. *
  1064. * @todo editing of a shared question
  1065. */
  1066. public function save_shared_question($form_content, $survey_data)
  1067. {
  1068. $_course = api_get_course_info();
  1069. // Table definitions
  1070. $tbl_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1071. // Storing a new question
  1072. if ($form_content['shared_question_id'] == '' ||
  1073. !is_numeric($form_content['shared_question_id'])
  1074. ) {
  1075. // Finding the max sort order of the questions in the given survey
  1076. $sql = "SELECT max(sort) AS max_sort FROM $tbl_survey_question
  1077. WHERE survey_id='".intval($survey_data['survey_share'])."'
  1078. AND code='".Database::escape_string($_course['id'])."'";
  1079. $result = Database::query($sql);
  1080. $row = Database::fetch_array($result,'ASSOC');
  1081. $max_sort = $row['max_sort'];
  1082. // Adding the question to the survey_question table
  1083. $sql = "INSERT INTO $tbl_survey_question (survey_id, survey_question, survey_question_comment, type, display, sort, code) VALUES (
  1084. '".Database::escape_string($survey_data['survey_share'])."',
  1085. '".Database::escape_string($form_content['question'])."',
  1086. '".Database::escape_string($form_content['question_comment'])."',
  1087. '".Database::escape_string($form_content['type'])."',
  1088. '".Database::escape_string($form_content['horizontalvertical'])."',
  1089. '".Database::escape_string($max_sort+1)."',
  1090. '".Database::escape_string($_course['id'])."')";
  1091. Database::query($sql);
  1092. $shared_question_id = Database::insert_id();
  1093. } else {
  1094. // Updating an existing question
  1095. // adding the question to the survey_question table
  1096. $sql = "UPDATE $tbl_survey_question SET
  1097. survey_question = '".Database::escape_string($form_content['question'])."',
  1098. survey_question_comment = '".Database::escape_string($form_content['question_comment'])."',
  1099. display = '".Database::escape_string($form_content['horizontalvertical'])."'
  1100. WHERE
  1101. question_id = '".intval($form_content['shared_question_id'])."' AND
  1102. code = '".Database::escape_string($_course['id'])."'";
  1103. Database::query($sql);
  1104. $shared_question_id = $form_content['shared_question_id'];
  1105. }
  1106. return $shared_question_id;
  1107. }
  1108. /**
  1109. * This functions moves a question of a survey up or down
  1110. *
  1111. * @param string $direction
  1112. * @param integer $survey_question_id
  1113. * @param integer $survey_id
  1114. *
  1115. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1116. * @version January 2007
  1117. */
  1118. public static function move_survey_question($direction, $survey_question_id, $survey_id)
  1119. {
  1120. // Table definition
  1121. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1122. $course_id = api_get_course_int_id();
  1123. if ($direction == 'moveup') {
  1124. $sort = 'DESC';
  1125. }
  1126. if ($direction == 'movedown') {
  1127. $sort = 'ASC';
  1128. }
  1129. // Finding the two questions that needs to be swapped
  1130. $sql = "SELECT * FROM $table_survey_question
  1131. WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
  1132. ORDER BY sort $sort";
  1133. $result = Database::query($sql);
  1134. $found = false;
  1135. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1136. if ($found) {
  1137. $question_id_two = $row['question_id'];
  1138. $question_sort_two = $row['sort'];
  1139. $found = false;
  1140. }
  1141. if ($row['question_id'] == $survey_question_id) {
  1142. $found = true;
  1143. $question_id_one = $row['question_id'];
  1144. $question_sort_one = $row['sort'];
  1145. }
  1146. }
  1147. $sql1 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_two)."'
  1148. WHERE c_id = $course_id AND question_id='".intval($question_id_one)."'";
  1149. Database::query($sql1);
  1150. $sql2 = "UPDATE $table_survey_question SET sort = '".Database::escape_string($question_sort_one)."'
  1151. WHERE c_id = $course_id AND question_id='".intval($question_id_two)."'";
  1152. Database::query($sql2);
  1153. }
  1154. /**
  1155. * This function deletes all the questions of a given survey
  1156. * This function is normally only called when a survey is deleted
  1157. *
  1158. * @param int $survey_id the id of the survey that has to be deleted
  1159. * @return true
  1160. *
  1161. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1162. * @version January 2007
  1163. */
  1164. public static function delete_all_survey_questions($survey_id, $shared = false)
  1165. {
  1166. $course_id = api_get_course_int_id();
  1167. // Table definitions
  1168. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1169. $course_condition = " c_id = $course_id AND ";
  1170. if ($shared) {
  1171. $course_condition = "";
  1172. $table_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1173. }
  1174. $sql = "DELETE FROM $table_survey_question
  1175. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1176. // Deleting the survey questions
  1177. Database::query($sql);
  1178. // Deleting all the options of the questions of the survey
  1179. SurveyManager::delete_all_survey_questions_options($survey_id, $shared);
  1180. // Deleting all the answers on this survey
  1181. SurveyManager::delete_all_survey_answers($survey_id);
  1182. }
  1183. /**
  1184. * This function deletes a survey question and all its options
  1185. *
  1186. * @param integer $survey_id the id of the survey
  1187. * @param integer $question_id the id of the question
  1188. * @param integer $shared
  1189. *
  1190. * @todo also delete the answers to this question
  1191. *
  1192. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1193. * @version March 2007
  1194. */
  1195. public static function delete_survey_question($survey_id, $question_id, $shared = false)
  1196. {
  1197. $course_id = api_get_course_int_id();
  1198. // Table definitions
  1199. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1200. if ($shared) {
  1201. SurveyManager::delete_shared_survey_question($survey_id, $question_id);
  1202. }
  1203. // Deleting the survey questions
  1204. $sql = "DELETE FROM $table_survey_question
  1205. WHERE
  1206. c_id = $course_id AND
  1207. survey_id='".intval($survey_id)."' AND
  1208. question_id='".intval($question_id)."'";
  1209. Database::query($sql);
  1210. // Deleting the options of the question of the survey
  1211. SurveyManager::delete_survey_question_option($survey_id, $question_id, $shared);
  1212. }
  1213. /**
  1214. * This function deletes a shared survey question from the main database and all its options
  1215. *
  1216. * @param int $question_id the id of the question
  1217. * @param int $shared
  1218. *
  1219. * @todo delete all the options of this question
  1220. *
  1221. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1222. * @version March 2007
  1223. */
  1224. public static function delete_shared_survey_question($survey_id, $question_id)
  1225. {
  1226. // Table definitions
  1227. $table_survey_question = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION);
  1228. $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1229. // First we have to get the shared_question_id
  1230. $question_data = SurveyManager::get_question($question_id);
  1231. // Deleting the survey questions
  1232. $sql = "DELETE FROM $table_survey_question
  1233. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1234. Database::query($sql);
  1235. // Deleting the options of the question of the survey question
  1236. $sql = "DELETE FROM $table_survey_question_option
  1237. WHERE question_id='".intval($question_data['shared_question_id'])."'";
  1238. Database::query($sql);
  1239. }
  1240. /**
  1241. * This function stores the options of the questions in the table
  1242. *
  1243. * @param array $form_content
  1244. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1245. * @version January 2007
  1246. *
  1247. * @todo writing the update statement when editing a question
  1248. */
  1249. public static function save_question_options($form_content, $survey_data)
  1250. {
  1251. $course_id = api_get_course_int_id();
  1252. // A percentage question type has options 1 -> 100
  1253. if ($form_content['type'] == 'percentage') {
  1254. for($i = 1; $i < 101; $i++) {
  1255. $form_content['answers'][] = $i;
  1256. }
  1257. }
  1258. if (is_numeric($survey_data['survey_share']) && $survey_data['survey_share'] != 0) {
  1259. SurveyManager::save_shared_question_options($form_content, $survey_data);
  1260. }
  1261. // Table definition
  1262. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1263. // We are editing a question so we first have to remove all the existing options from the database
  1264. if (is_numeric($form_content['question_id'])) {
  1265. $sql = "DELETE FROM $table_survey_question_option
  1266. WHERE c_id = $course_id AND question_id = '".intval($form_content['question_id'])."'";
  1267. Database::query($sql);
  1268. }
  1269. $counter = 1;
  1270. if (isset($form_content['answers']) && is_array($form_content['answers'])) {
  1271. for ($i = 0; $i < count($form_content['answers']); $i++) {
  1272. $values = isset($form_content['values']) ? $form_content['values'][$i] : '';
  1273. $params = [
  1274. 'c_id' => $course_id,
  1275. 'question_id' => $form_content['question_id'],
  1276. 'survey_id' => $form_content['survey_id'],
  1277. 'option_text' => $form_content['answers'][$i],
  1278. 'value' => $values,
  1279. 'sort' => $counter,
  1280. ];
  1281. $insertId = Database::insert($table_survey_question_option, $params);
  1282. if ($insertId) {
  1283. $sql = "UPDATE $table_survey_question_option
  1284. SET question_option_id = $insertId
  1285. WHERE iid = $insertId";
  1286. Database::query($sql);
  1287. $counter++;
  1288. }
  1289. }
  1290. }
  1291. }
  1292. /**
  1293. * This function stores the options of the questions in the shared table
  1294. *
  1295. * @param array $form_content
  1296. *
  1297. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1298. * @version February 2007
  1299. *
  1300. * @todo writing the update statement when editing a question
  1301. */
  1302. public function save_shared_question_options($form_content, $survey_data)
  1303. {
  1304. if (is_array($form_content) && is_array($form_content['answers'])) {
  1305. // Table definition
  1306. $table = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1307. // We are editing a question so we first have to remove all the existing options from the database
  1308. $sql = "DELETE FROM $table
  1309. WHERE question_id = '".Database::escape_string($form_content['shared_question_id'])."'";
  1310. Database::query($sql);
  1311. $counter = 1;
  1312. foreach ($form_content['answers'] as & $answer) {
  1313. $params = [
  1314. 'question_id' => $form_content['shared_question_id'],
  1315. 'survey_id' => $survey_data['is_shared'],
  1316. 'option_text' => $answer,
  1317. 'sort' => $counter,
  1318. ];
  1319. Database::insert($table, $params);
  1320. $counter++;
  1321. }
  1322. }
  1323. }
  1324. /**
  1325. * This function deletes all the options of the questions of a given survey
  1326. * This function is normally only called when a survey is deleted
  1327. *
  1328. * @param $survey_id the id of the survey that has to be deleted
  1329. * @return true
  1330. *
  1331. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1332. * @version January 2007
  1333. */
  1334. public static function delete_all_survey_questions_options($survey_id, $shared = false)
  1335. {
  1336. // Table definitions
  1337. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1338. $course_id = api_get_course_int_id();
  1339. $course_condition = " c_id = $course_id AND ";
  1340. if ($shared) {
  1341. $course_condition = "";
  1342. $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1343. }
  1344. $sql = "DELETE FROM $table_survey_question_option
  1345. WHERE $course_condition survey_id='".intval($survey_id)."'";
  1346. // Deleting the options of the survey questions
  1347. Database::query($sql);
  1348. return true;
  1349. }
  1350. /**
  1351. * This function deletes the options of a given question
  1352. *
  1353. * @param int $survey_id
  1354. * @param int $question_id
  1355. * @param int $shared
  1356. *
  1357. * @return bool
  1358. *
  1359. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1360. * @author Julio Montoya
  1361. * @version March 2007
  1362. */
  1363. public static function delete_survey_question_option($survey_id, $question_id, $shared = false)
  1364. {
  1365. $course_id = api_get_course_int_id();
  1366. $course_condition = " c_id = $course_id AND ";
  1367. // Table definitions
  1368. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1369. if ($shared) {
  1370. $course_condition = "";
  1371. $table_survey_question_option = Database :: get_main_table(TABLE_MAIN_SHARED_SURVEY_QUESTION_OPTION);
  1372. }
  1373. // Deleting the options of the survey questions
  1374. $sql = "DELETE from $table_survey_question_option
  1375. WHERE
  1376. $course_condition survey_id='".intval($survey_id)."' AND
  1377. question_id='".intval($question_id)."'";
  1378. Database::query($sql);
  1379. return true;
  1380. }
  1381. /**
  1382. * SURVEY ANSWERS FUNCTIONS
  1383. */
  1384. /**
  1385. * This function deletes all the answers anyone has given on this survey
  1386. * This function is normally only called when a survey is deleted
  1387. *
  1388. * @param $survey_id the id of the survey that has to be deleted
  1389. * @return true
  1390. *
  1391. * @todo write the function
  1392. *
  1393. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1394. * @version January 2007,december 2008
  1395. */
  1396. public static function delete_all_survey_answers($survey_id)
  1397. {
  1398. $course_id = api_get_course_int_id();
  1399. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1400. $survey_id = intval($survey_id);
  1401. Database::query("DELETE FROM $table_survey_answer WHERE c_id = $course_id AND survey_id=$survey_id");
  1402. return true;
  1403. }
  1404. /**
  1405. * @param int $user_id
  1406. * @param int $survey_id
  1407. * @param int $course_id
  1408. * @return bool
  1409. */
  1410. public static function is_user_filled_survey($user_id, $survey_id, $course_id)
  1411. {
  1412. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1413. $user_id = intval($user_id);
  1414. $course_id = intval($course_id);
  1415. $survey_id = intval($survey_id);
  1416. $sql = "SELECT DISTINCT user FROM $table_survey_answer
  1417. WHERE
  1418. c_id = $course_id AND
  1419. user = $user_id AND
  1420. survey_id = $survey_id";
  1421. $result = Database::query($sql);
  1422. if (Database::num_rows($result)) {
  1423. return true;
  1424. }
  1425. return false;
  1426. }
  1427. /**
  1428. * This function gets all the persons who have filled the survey
  1429. *
  1430. * @param integer $survey_id
  1431. * @return array
  1432. *
  1433. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1434. * @version February 2007
  1435. */
  1436. public static function get_people_who_filled_survey($survey_id, $all_user_info = false, $course_id = null)
  1437. {
  1438. // Database table definition
  1439. $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  1440. $table_user = Database:: get_main_table(TABLE_MAIN_USER);
  1441. // Variable initialisation
  1442. $return = array();
  1443. if (empty($course_id)) {
  1444. $course_id = api_get_course_int_id();
  1445. } else {
  1446. $course_id = intval($course_id);
  1447. }
  1448. if ($all_user_info) {
  1449. $order_clause = api_sort_by_first_name() ? ' ORDER BY user.firstname, user.lastname' : ' ORDER BY user.lastname, user.firstname';
  1450. $sql = "SELECT DISTINCT
  1451. answered_user.user as invited_user, user.firstname, user.lastname, user.user_id
  1452. FROM $table_survey_answer answered_user
  1453. LEFT JOIN $table_user as user ON answered_user.user = user.user_id
  1454. WHERE
  1455. answered_user.c_id = $course_id AND
  1456. survey_id= '".Database::escape_string($survey_id)."' ".
  1457. $order_clause;
  1458. } else {
  1459. $sql = "SELECT DISTINCT user FROM $table_survey_answer
  1460. WHERE c_id = $course_id AND survey_id= '".Database::escape_string($survey_id)."' ";
  1461. }
  1462. $res = Database::query($sql);
  1463. while ($row = Database::fetch_array($res, 'ASSOC')) {
  1464. if ($all_user_info) {
  1465. $return[] = $row;
  1466. } else {
  1467. $return[] = $row['user'];
  1468. }
  1469. }
  1470. return $return;
  1471. }
  1472. public static function survey_generation_hash_available()
  1473. {
  1474. if (extension_loaded('mcrypt')) {
  1475. return true;
  1476. }
  1477. return false;
  1478. }
  1479. public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
  1480. {
  1481. $hash = hash('sha512', api_get_security_key().'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id);
  1482. return $hash;
  1483. }
  1484. public static function validate_survey_hash($survey_id, $course_id, $session_id, $group_id, $hash)
  1485. {
  1486. $survey_generated_hash = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
  1487. if ($survey_generated_hash == $hash) {
  1488. return true;
  1489. }
  1490. return false;
  1491. }
  1492. public static function generate_survey_link($survey_id, $course_id, $session_id, $group_id)
  1493. {
  1494. $code = self::generate_survey_hash($survey_id, $course_id, $session_id, $group_id);
  1495. return api_get_path(WEB_CODE_PATH).'survey/link.php?h='.$code.'&i='.$survey_id.'&c='.intval($course_id).'&s='.intval($session_id).'&g='.$group_id;
  1496. }
  1497. }
  1498. /**
  1499. * This class offers a series of general utility functions for survey querying and display
  1500. * @package chamilo.survey
  1501. */
  1502. class SurveyUtil
  1503. {
  1504. /**
  1505. * Checks whether the given survey has a pagebreak question as the first or the last question.
  1506. * If so, break the current process, displaying an error message
  1507. * @param integer Survey ID (database ID)
  1508. * @param boolean Optional. Whether to continue the current process or exit when breaking condition found. Defaults to true (do not break).
  1509. * @return void
  1510. */
  1511. static function check_first_last_question($survey_id, $continue = true)
  1512. {
  1513. // Table definitions
  1514. $tbl_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1515. $course_id = api_get_course_int_id();
  1516. // Getting the information of the question
  1517. $sql = "SELECT * FROM $tbl_survey_question
  1518. WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
  1519. ORDER BY sort ASC";
  1520. $result = Database::query($sql);
  1521. $total = Database::num_rows($result);
  1522. $counter = 1;
  1523. $error = false;
  1524. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1525. if ($counter == 1 && $row['type'] == 'pagebreak') {
  1526. Display::display_error_message(get_lang('PagebreakNotFirst'), false);
  1527. $error = true;
  1528. }
  1529. if ($counter == $total && $row['type'] == 'pagebreak') {
  1530. Display::display_error_message(get_lang('PagebreakNotLast'), false);
  1531. $error = true;
  1532. }
  1533. $counter++;
  1534. }
  1535. if (!$continue && $error) {
  1536. Display::display_footer();
  1537. exit;
  1538. }
  1539. }
  1540. /**
  1541. * This function removes an (or multiple) answer(s) of a user on a question of a survey
  1542. *
  1543. * @param mixed The user id or email of the person who fills the survey
  1544. * @param integer The survey id
  1545. * @param integer The question id
  1546. * @param integer The option id
  1547. *
  1548. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1549. * @version January 2007
  1550. */
  1551. static function remove_answer($user, $survey_id, $question_id, $course_id) {
  1552. $course_id = intval($course_id);
  1553. // table definition
  1554. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1555. $sql = "DELETE FROM $table_survey_answer
  1556. WHERE
  1557. c_id = $course_id AND
  1558. user = '".Database::escape_string($user)."' AND
  1559. survey_id = '".intval($survey_id)."' AND
  1560. question_id = '".intval($question_id)."'";
  1561. Database::query($sql);
  1562. }
  1563. /**
  1564. * This function stores an answer of a user on a question of a survey
  1565. *
  1566. * @param mixed The user id or email of the person who fills the survey
  1567. * @param integer Survey id
  1568. * @param integer Question id
  1569. * @param integer Option id
  1570. * @param string Option value
  1571. * @param array Survey data settings
  1572. *
  1573. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1574. * @version January 2007
  1575. */
  1576. static function store_answer($user, $survey_id, $question_id, $option_id, $option_value, $survey_data)
  1577. {
  1578. // Table definition
  1579. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1580. // Make the survey anonymous
  1581. if ($survey_data['anonymous'] == 1) {
  1582. if (!isset($_SESSION['surveyuser'])) {
  1583. $user = md5($user.time());
  1584. $_SESSION['surveyuser'] = $user;
  1585. } else {
  1586. $user = $_SESSION['surveyuser'];
  1587. }
  1588. }
  1589. $course_id = $survey_data['c_id'];
  1590. $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
  1591. $course_id,
  1592. '".Database::escape_string($user)."',
  1593. '".Database::escape_string($survey_id)."',
  1594. '".Database::escape_string($question_id)."',
  1595. '".Database::escape_string($option_id)."',
  1596. '".Database::escape_string($option_value)."'
  1597. )";
  1598. Database::query($sql);
  1599. $insertId = Database::insert_id();
  1600. $sql = "UPDATE $table_survey_answer SET answer_id = $insertId WHERE iid = $insertId";
  1601. Database::query($sql);
  1602. }
  1603. /**
  1604. * This function checks the parameters that are used in this page
  1605. *
  1606. * @return string The header, an error and the footer if any parameter fails, else it returns true
  1607. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1608. * @version February 2007
  1609. */
  1610. static function check_parameters($people_filled)
  1611. {
  1612. $error = false;
  1613. // Getting the survey data
  1614. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  1615. // $_GET['survey_id'] has to be numeric
  1616. if (!is_numeric($_GET['survey_id'])) {
  1617. $error = get_lang('IllegalSurveyId');
  1618. }
  1619. // $_GET['action']
  1620. $allowed_actions = array(
  1621. 'overview',
  1622. 'questionreport',
  1623. 'userreport',
  1624. 'comparativereport',
  1625. 'completereport',
  1626. 'deleteuserreport'
  1627. );
  1628. if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
  1629. $error = get_lang('ActionNotAllowed');
  1630. }
  1631. // User report
  1632. if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
  1633. if ($survey_data['anonymous'] == 0) {
  1634. foreach ($people_filled as $key => & $value) {
  1635. $people_filled_userids[] = $value['invited_user'];
  1636. }
  1637. } else {
  1638. $people_filled_userids = $people_filled;
  1639. }
  1640. if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
  1641. $error = get_lang('UnknowUser');
  1642. }
  1643. }
  1644. // Question report
  1645. if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
  1646. if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
  1647. $error = get_lang('UnknowQuestion');
  1648. }
  1649. }
  1650. if ($error) {
  1651. $tool_name = get_lang('Reporting');
  1652. Display::display_header($tool_name);
  1653. Display::display_error_message(get_lang('Error').': '.$error, false);
  1654. Display::display_footer();
  1655. exit;
  1656. } else {
  1657. return true;
  1658. }
  1659. }
  1660. /**
  1661. * This function deals with the action handling
  1662. * @return void
  1663. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1664. * @version February 2007
  1665. */
  1666. public static function handle_reporting_actions($survey_data, $people_filled)
  1667. {
  1668. $action = isset($_GET['action']) ? $_GET['action'] : null;
  1669. // Getting the number of question
  1670. $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
  1671. // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
  1672. $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
  1673. $questions_data = array();
  1674. foreach ($my_temp_questions_data as $key => & $value) {
  1675. if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
  1676. $questions_data[$value['sort']] = $value;
  1677. }
  1678. }
  1679. // Counting the number of questions that are relevant for the reporting
  1680. $survey_data['number_of_questions'] = count($questions_data);
  1681. if ($action == 'questionreport') {
  1682. SurveyUtil::display_question_report($survey_data);
  1683. }
  1684. if ($action == 'userreport') {
  1685. SurveyUtil::display_user_report($people_filled, $survey_data);
  1686. }
  1687. if ($action == 'comparativereport') {
  1688. SurveyUtil::display_comparative_report();
  1689. }
  1690. if ($action == 'completereport') {
  1691. SurveyUtil::display_complete_report($survey_data);
  1692. }
  1693. if ($action == 'deleteuserreport') {
  1694. SurveyUtil::delete_user_report($_GET['survey_id'], $_GET['user']);
  1695. }
  1696. }
  1697. /**
  1698. * This function deletes the report of an user who wants to retake the survey
  1699. * @param integer survey_id
  1700. * @param integer user_id
  1701. * @return void
  1702. * @author Christian Fasanando Flores <christian.fasanando@dokeos.com>
  1703. * @version November 2008
  1704. */
  1705. function delete_user_report($survey_id, $user_id)
  1706. {
  1707. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1708. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  1709. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  1710. $course_id = api_get_course_int_id();
  1711. if (!empty($survey_id) && !empty($user_id)) {
  1712. // delete data from survey_answer by user_id and survey_id
  1713. $sql = "DELETE FROM $table_survey_answer
  1714. WHERE c_id = $course_id AND survey_id = '".(int)$survey_id."' AND user = '".(int)$user_id."'";
  1715. Database::query($sql);
  1716. // update field answered from survey_invitation by user_id and survey_id
  1717. $sql = "UPDATE $table_survey_invitation SET answered = '0'
  1718. WHERE
  1719. c_id = $course_id AND
  1720. survey_code = (
  1721. SELECT code FROM $table_survey
  1722. WHERE
  1723. c_id = $course_id AND
  1724. survey_id = '".(int)$survey_id."'
  1725. ) AND
  1726. user = '".(int)$user_id."'";
  1727. $result = Database::query($sql);
  1728. }
  1729. if ($result !== false) {
  1730. $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
  1731. <a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.Security::remove_XSS($survey_id).'">'.get_lang('GoBack').'</a>';
  1732. Display::display_confirmation_message($message, false);
  1733. }
  1734. }
  1735. /**
  1736. * This function displays the user report which is basically nothing more
  1737. * than a one-page display of all the questions
  1738. * of the survey that is filled with the answers of the person who filled the survey.
  1739. *
  1740. * @return string html code of the one-page survey with the answers of the selected user
  1741. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1742. * @version February 2007 - Updated March 2008
  1743. */
  1744. public static function display_user_report($people_filled, $survey_data)
  1745. {
  1746. // Database table definitions
  1747. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1748. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1749. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1750. // Actions bar
  1751. echo '<div class="actions">';
  1752. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">'.
  1753. Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  1754. if (isset($_GET['user'])) {
  1755. if (api_is_allowed_to_edit()) {
  1756. // The delete link
  1757. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=deleteuserreport&survey_id='.intval($_GET['survey_id']).'&user='.Security::remove_XSS($_GET['user']).'&'.api_get_cidreq().'" >'.
  1758. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
  1759. }
  1760. // Export the user report
  1761. echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
  1762. Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
  1763. echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
  1764. Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
  1765. echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'&'.api_get_cidreq().'">';
  1766. echo '<input type="hidden" name="export_report" value="export_report">';
  1767. echo '<input type="hidden" name="export_format" value="csv">';
  1768. echo '</form>';
  1769. echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&user_id='.Security::remove_XSS($_GET['user']).'&'.api_get_cidreq().'">';
  1770. echo '<input type="hidden" name="export_report" value="export_report">';
  1771. echo '<input type="hidden" name="export_format" value="xls">';
  1772. echo '</form>';
  1773. echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">';
  1774. }
  1775. echo '</div>';
  1776. // Step 1: selection of the user
  1777. echo "<script>
  1778. function jumpMenu(targ,selObj,restore) {
  1779. eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
  1780. if (restore) selObj.selectedIndex=0;
  1781. }
  1782. </script>";
  1783. echo get_lang('SelectUserWhoFilledSurvey').'<br />';
  1784. echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
  1785. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.get_lang('SelectUser').'</option>';
  1786. foreach ($people_filled as $key => & $person) {
  1787. if ($survey_data['anonymous'] == 0) {
  1788. $name = api_get_person_name($person['firstname'], $person['lastname']);
  1789. $id = $person['user_id'];
  1790. if ($id == '') {
  1791. $id = $person['invited_user'];
  1792. $name = $person['invited_user'];
  1793. }
  1794. } else {
  1795. $name = get_lang('Anonymous') . ' ' . ($key + 1);
  1796. $id = $person;
  1797. }
  1798. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.Security::remove_XSS($id).'" ';
  1799. if (isset($_GET['user']) && $_GET['user'] == $id) {
  1800. echo 'selected="selected"';
  1801. }
  1802. echo '>'.$name.'</option>';
  1803. }
  1804. echo '</select>';
  1805. $course_id = api_get_course_int_id();
  1806. // Step 2: displaying the survey and the answer of the selected users
  1807. if (isset($_GET['user'])) {
  1808. Display::display_normal_message(
  1809. get_lang('AllQuestionsOnOnePage'),
  1810. false
  1811. );
  1812. // Getting all the questions and options
  1813. $sql = "SELECT
  1814. survey_question.question_id,
  1815. survey_question.survey_id,
  1816. survey_question.survey_question,
  1817. survey_question.display,
  1818. survey_question.max_value,
  1819. survey_question.sort,
  1820. survey_question.type,
  1821. survey_question_option.question_option_id,
  1822. survey_question_option.option_text,
  1823. survey_question_option.sort as option_sort
  1824. FROM $table_survey_question survey_question
  1825. LEFT JOIN $table_survey_question_option survey_question_option
  1826. ON
  1827. survey_question.question_id = survey_question_option.question_id AND
  1828. survey_question_option.c_id = $course_id
  1829. WHERE
  1830. survey_question.survey_id = '".Database::escape_string(
  1831. $_GET['survey_id']
  1832. )."' AND
  1833. survey_question.c_id = $course_id
  1834. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  1835. $result = Database::query($sql);
  1836. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1837. if ($row['type'] != 'pagebreak') {
  1838. $questions[$row['sort']]['question_id'] = $row['question_id'];
  1839. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  1840. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  1841. $questions[$row['sort']]['display'] = $row['display'];
  1842. $questions[$row['sort']]['type'] = $row['type'];
  1843. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  1844. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  1845. }
  1846. }
  1847. // Getting all the answers of the user
  1848. $sql = "SELECT * FROM $table_survey_answer
  1849. WHERE
  1850. c_id = $course_id AND
  1851. survey_id = '".intval($_GET['survey_id'])."' AND
  1852. user = '".Database::escape_string($_GET['user'])."'";
  1853. $result = Database::query($sql);
  1854. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1855. $answers[$row['question_id']][] = $row['option_id'];
  1856. $all_answers[$row['question_id']][] = $row;
  1857. }
  1858. // Displaying all the questions
  1859. foreach ($questions as & $question) {
  1860. // If the question type is a scoring then we have to format the answers differently
  1861. switch ($question['type']) {
  1862. case 'score':
  1863. $finalAnswer = array();
  1864. if (is_array($question) && is_array($all_answers)) {
  1865. foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
  1866. $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
  1867. }
  1868. }
  1869. break;
  1870. case 'multipleresponse':
  1871. $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
  1872. break;
  1873. default:
  1874. $finalAnswer = '';
  1875. if (isset($all_answers[$question['question_id']])) {
  1876. $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
  1877. }
  1878. break;
  1879. }
  1880. $ch_type = 'ch_'.$question['type'];
  1881. /** @var survey_question $display */
  1882. $display = new $ch_type;
  1883. $url = api_get_self();
  1884. $form = new FormValidator('question', 'post', $url);
  1885. $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
  1886. $form->addHtml($question['survey_question']);
  1887. $display->render($form, $question, $finalAnswer);
  1888. $form->addHtml('</div></div>');
  1889. $form->display();
  1890. }
  1891. }
  1892. }
  1893. /**
  1894. * This function displays the report by question.
  1895. *
  1896. * It displays a table with all the options of the question and the number of users who have answered positively on the option.
  1897. * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
  1898. * and graphically using bars
  1899. * By clicking on the absolute number you get a list with the persons who have answered this.
  1900. * You can then click on the name of the person and you will then go to the report by user where you see all the
  1901. * answers of that user.
  1902. *
  1903. * @param array All the survey data
  1904. * @return string html code that displays the report by question
  1905. * @todo allow switching between horizontal and vertical.
  1906. * @todo multiple response: percentage are probably not OK
  1907. * @todo the question and option text have to be shortened and should expand when the user clicks on it.
  1908. * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
  1909. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1910. * @version February 2007 - Updated March 2008
  1911. */
  1912. public static function display_question_report($survey_data)
  1913. {
  1914. $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
  1915. $course_id = api_get_course_int_id();
  1916. // Database table definitions
  1917. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  1918. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1919. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  1920. // Determining the offset of the sql statement (the n-th question of the survey)
  1921. $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
  1922. $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
  1923. $questions = array();
  1924. $surveyId = intval($_GET['survey_id']);
  1925. $action = Security::remove_XSS($_GET['action']);
  1926. echo '<div class="actions">';
  1927. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
  1928. Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'), '', ICON_SIZE_MEDIUM).'</a>';
  1929. echo '</div>';
  1930. if ($survey_data['number_of_questions'] > 0) {
  1931. $limitStatement = null;
  1932. if (!$singlePage) {
  1933. echo '<div id="question_report_questionnumbers" class="pagination">';
  1934. /* echo '<ul><li class="disabled"><a href="#">'.get_lang('Question').'</a></li>'; */
  1935. if ($currentQuestion != 0) {
  1936. echo '<li><a href="' . api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset - 1) . '">' . get_lang('PreviousQuestion') . '</a></li>';
  1937. }
  1938. for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
  1939. if ($offset != $i - 1) {
  1940. echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($i - 1) . '">' . $i . '</a></li>';
  1941. } else {
  1942. echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
  1943. }
  1944. /*if ($i < $survey_data['number_of_questions']) {
  1945. echo ' | ';
  1946. }*/
  1947. }
  1948. if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
  1949. echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset + 1) . '">' . get_lang('NextQuestion') . '</li></a>';
  1950. }
  1951. echo '</ul>';
  1952. echo '</div>';
  1953. $limitStatement = " LIMIT $offset, 1";
  1954. }
  1955. // Getting the question information
  1956. $sql = "SELECT * FROM $table_survey_question
  1957. WHERE
  1958. c_id = $course_id AND
  1959. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  1960. type<>'pagebreak' AND type<>'comment'
  1961. ORDER BY sort ASC
  1962. $limitStatement";
  1963. $result = Database::query($sql);
  1964. //$question = Database::fetch_array($result);
  1965. while ($row = Database::fetch_array($result)) {
  1966. $questions[$row['question_id']] = $row;
  1967. }
  1968. // Navigate through the questions (next and previous)
  1969. /*if ($currentQuestion != 0 ) {
  1970. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&'.api_get_cidreq().'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset-1).'">'.
  1971. Display::return_icon('action_prev.png', get_lang('PreviousQuestion'), array('align' => 'middle')).' '.get_lang('PreviousQuestion').'</a> ';
  1972. } else {
  1973. echo Display::return_icon('action_prev.png', get_lang('PreviousQuestion'), array('align' => 'middle')).' '.get_lang('PreviousQuestion').' ';
  1974. }
  1975. echo ' | ';
  1976. if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
  1977. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&'.api_get_cidreq().'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset+1).'">'.get_lang('NextQuestion').' '.Display::return_icon('action_next.png', get_lang('NextQuestion'), array('align' => 'middle')).'</a>';
  1978. } else {
  1979. echo get_lang('NextQuestion').' '.Display::return_icon('action_next.png', get_lang('NextQuestion'), array('align' => 'middle'));
  1980. }*/
  1981. }
  1982. foreach ($questions as $question) {
  1983. $chartData = array();
  1984. $options = array();
  1985. echo '<div class="title-question">';
  1986. echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
  1987. echo '</div>';
  1988. if ($question['type'] == 'score') {
  1989. /** @todo This function should return the options as this is needed further in the code */
  1990. $options = SurveyUtil::display_question_report_score($survey_data, $question, $offset);
  1991. } elseif ($question['type'] == 'open') {
  1992. /** @todo Also get the user who has answered this */
  1993. $sql = "SELECT * FROM $table_survey_answer
  1994. WHERE
  1995. c_id = $course_id AND
  1996. survey_id='" . intval($_GET['survey_id']) . "' AND
  1997. question_id = '" . intval($question['question_id']) . "'";
  1998. $result = Database::query($sql);
  1999. while ($row = Database::fetch_array($result)) {
  2000. echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
  2001. }
  2002. } else {
  2003. // Getting the options ORDER BY sort ASC
  2004. $sql = "SELECT * FROM $table_survey_question_option
  2005. WHERE
  2006. c_id = $course_id AND
  2007. survey_id='" . intval($_GET['survey_id']) . "'
  2008. AND question_id = '" . intval($question['question_id']) . "'
  2009. ORDER BY sort ASC";
  2010. $result = Database::query($sql);
  2011. while ($row = Database::fetch_array($result)) {
  2012. $options[$row['question_option_id']] = $row;
  2013. }
  2014. // Getting the answers
  2015. $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
  2016. WHERE
  2017. c_id = $course_id AND
  2018. survey_id='" . intval($_GET['survey_id']) . "'
  2019. AND question_id = '" . intval($question['question_id']) . "'
  2020. GROUP BY option_id, value";
  2021. $result = Database::query($sql);
  2022. $number_of_answers = array();
  2023. $data = array();
  2024. while ($row = Database::fetch_array($result)) {
  2025. if (!isset($number_of_answers[$row['question_id']])) {
  2026. $number_of_answers[$row['question_id']] = 0;
  2027. }
  2028. $number_of_answers[$row['question_id']] += $row['total'];
  2029. $data[$row['option_id']] = $row;
  2030. }
  2031. foreach ($options as $option) {
  2032. $optionText = strip_tags($option['option_text']);
  2033. $optionText = html_entity_decode($optionText);
  2034. $votes = isset($data[$option['question_option_id']]['total']) ?
  2035. $data[$option['question_option_id']]['total'] :
  2036. '0';
  2037. array_push($chartData, array('option' => $optionText, 'votes' => $votes));
  2038. }
  2039. $chartContainerId = 'chartContainer'.$question['question_id'];
  2040. echo '<div id="'.$chartContainerId.'" class="col-md-12">';
  2041. echo self::drawChart($chartData, false, $chartContainerId);
  2042. // displaying the table: headers
  2043. echo '<table class="display-survey table">';
  2044. echo ' <tr>';
  2045. echo ' <th>&nbsp;</th>';
  2046. echo ' <th>' . get_lang('AbsoluteTotal') . '</th>';
  2047. echo ' <th>' . get_lang('Percentage') . '</th>';
  2048. echo ' <th>' . get_lang('VisualRepresentation') . '</th>';
  2049. echo ' <tr>';
  2050. // Displaying the table: the content
  2051. if (is_array($options)) {
  2052. foreach ($options as $key => & $value) {
  2053. $absolute_number = null;
  2054. if (isset($data[$value['question_option_id']])) {
  2055. $absolute_number = $data[$value['question_option_id']]['total'];
  2056. }
  2057. if ($question['type'] == 'percentage' && empty($absolute_number)) {
  2058. continue;
  2059. }
  2060. if ($number_of_answers[$option['question_id']] == 0) {
  2061. $answers_number = 0;
  2062. } else {
  2063. $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
  2064. }
  2065. echo ' <tr>';
  2066. echo ' <td class="center">' . $value['option_text'] . '</td>';
  2067. echo ' <td class="center">';
  2068. if ($absolute_number != 0) {
  2069. echo '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&survey_id=' . $surveyId . '&question=' . $offset . '&viewoption=' . $value['question_option_id'] . '">' . $absolute_number . '</a>';
  2070. } else {
  2071. echo '0';
  2072. }
  2073. echo ' </td>';
  2074. echo ' <td class="center">' . round($answers_number, 2) . ' %</td>';
  2075. echo ' <td class="center">';
  2076. $size = $answers_number * 2;
  2077. if ($size > 0) {
  2078. echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
  2079. } else {
  2080. echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
  2081. }
  2082. echo ' </td>';
  2083. echo ' </tr>';
  2084. }
  2085. }
  2086. // displaying the table: footer (totals)
  2087. echo ' <tr>';
  2088. echo ' <td class="total"><b>' . get_lang('Total') . '</b></td>';
  2089. echo ' <td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
  2090. echo ' <td class="total">&nbsp;</td>';
  2091. echo ' <td class="total">&nbsp;</td>';
  2092. echo ' </tr>';
  2093. echo '</table>';
  2094. echo '</div>';
  2095. }
  2096. }
  2097. if (isset($_GET['viewoption'])) {
  2098. echo '<div class="answered-people">';
  2099. echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
  2100. if (is_numeric($_GET['value'])) {
  2101. $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
  2102. }
  2103. $sql = "SELECT user FROM $table_survey_answer
  2104. WHERE
  2105. c_id = $course_id AND
  2106. option_id = '".Database::escape_string($_GET['viewoption'])."'
  2107. $sql_restriction";
  2108. $result = Database::query($sql);
  2109. echo '<ul>';
  2110. while ($row = Database::fetch_array($result)) {
  2111. $user_info = api_get_user_info($row['user']);
  2112. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.$surveyId.'&user='.$row['user'].'">'.$user_info['complete_name'].'</a></li>';
  2113. }
  2114. echo '</ul>';
  2115. echo '</div>';
  2116. }
  2117. }
  2118. /**
  2119. * Display score data about a survey question
  2120. * @param array Question info
  2121. * @param integer The offset of results shown
  2122. * @return void (direct output)
  2123. */
  2124. public static function display_question_report_score($survey_data, $question, $offset)
  2125. {
  2126. // Database table definitions
  2127. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  2128. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  2129. $course_id = api_get_course_int_id();
  2130. // Getting the options
  2131. $sql = "SELECT * FROM $table_survey_question_option
  2132. WHERE
  2133. c_id = $course_id AND
  2134. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  2135. question_id = '".Database::escape_string($question['question_id'])."'
  2136. ORDER BY sort ASC";
  2137. $result = Database::query($sql);
  2138. while ($row = Database::fetch_array($result)) {
  2139. $options[$row['question_option_id']] = $row;
  2140. }
  2141. // Getting the answers
  2142. $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
  2143. WHERE
  2144. c_id = $course_id AND
  2145. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  2146. question_id = '".Database::escape_string($question['question_id'])."'
  2147. GROUP BY option_id, value";
  2148. $result = Database::query($sql);
  2149. $number_of_answers = 0;
  2150. while ($row = Database::fetch_array($result)) {
  2151. $number_of_answers += $row['total'];
  2152. $data[$row['option_id']][$row['value']] = $row;
  2153. }
  2154. $chartData = array();
  2155. foreach ($options as $option) {
  2156. $optionText = strip_tags($option['option_text']);
  2157. $optionText = html_entity_decode($optionText);
  2158. for ($i = 1; $i <= $question['max_value']; $i++) {
  2159. $votes = $data[$option['question_option_id']][$i]['total'];
  2160. if (empty($votes)) {
  2161. $votes = '0';
  2162. }
  2163. array_push(
  2164. $chartData,
  2165. array(
  2166. 'serie' => $optionText,
  2167. 'option' => $i,
  2168. 'votes' => $votes
  2169. )
  2170. );
  2171. }
  2172. }
  2173. echo '<div id="chartContainer" class="col-md-12">';
  2174. echo self::drawChart($chartData, true);
  2175. echo '</div>';
  2176. // Displaying the table: headers
  2177. echo '<table class="data_table">';
  2178. echo ' <tr>';
  2179. echo ' <th>&nbsp;</th>';
  2180. echo ' <th>'.get_lang('Score').'</th>';
  2181. echo ' <th>'.get_lang('AbsoluteTotal').'</th>';
  2182. echo ' <th>'.get_lang('Percentage').'</th>';
  2183. echo ' <th>'.get_lang('VisualRepresentation').'</th>';
  2184. echo ' <tr>';
  2185. // Displaying the table: the content
  2186. foreach ($options as $key => & $value) {
  2187. for ($i = 1; $i <= $question['max_value']; $i++) {
  2188. $absolute_number = $data[$value['question_option_id']][$i]['total'];
  2189. echo ' <tr>';
  2190. echo ' <td>'.$value['option_text'].'</td>';
  2191. echo ' <td>'.$i.'</td>';
  2192. echo ' <td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset).'&viewoption='.$value['question_option_id'].'&value='.$i.'">'.$absolute_number.'</a></td>';
  2193. echo ' <td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
  2194. echo ' <td>';
  2195. $size = ($absolute_number/$number_of_answers*100*2);
  2196. if ($size > 0) {
  2197. echo ' <div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
  2198. }
  2199. echo ' </td>';
  2200. echo ' </tr>';
  2201. }
  2202. }
  2203. // Displaying the table: footer (totals)
  2204. echo ' <tr>';
  2205. echo ' <td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
  2206. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  2207. echo ' <td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
  2208. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  2209. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  2210. echo ' </tr>';
  2211. echo '</table>';
  2212. }
  2213. /**
  2214. * This functions displays the complete reporting
  2215. * @return string HTML code
  2216. * @todo open questions are not in the complete report yet.
  2217. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2218. * @version February 2007
  2219. */
  2220. public static function display_complete_report($survey_data)
  2221. {
  2222. // Database table definitions
  2223. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  2224. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  2225. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  2226. // Actions bar
  2227. echo '<div class="actions">';
  2228. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">
  2229. '.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'), '', ICON_SIZE_MEDIUM).'</a>';
  2230. echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
  2231. '.Display::return_icon('export_csv.png', get_lang('ExportAsCSV'), '', ICON_SIZE_MEDIUM).'</a>';
  2232. echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
  2233. '.Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), '', ICON_SIZE_MEDIUM).'</a>';
  2234. echo '</div>';
  2235. // The form
  2236. echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">';
  2237. echo '<input type="hidden" name="export_report" value="export_report">';
  2238. echo '<input type="hidden" name="export_format" value="csv">';
  2239. echo '</form>';
  2240. echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">';
  2241. echo '<input type="hidden" name="export_report" value="export_report">';
  2242. echo '<input type="hidden" name="export_format" value="xls">';
  2243. echo '</form>';
  2244. echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">';
  2245. // The table
  2246. echo '<br /><table class="data_table" border="1">';
  2247. // Getting the number of options per question
  2248. echo ' <tr>';
  2249. echo ' <th>';
  2250. if (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  2251. isset($_POST['export_report']) && $_POST['export_report']) {
  2252. echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
  2253. }
  2254. echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
  2255. echo '</th>';
  2256. $display_extra_user_fields = false;
  2257. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  2258. isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
  2259. // Show user fields section with a big th colspan that spans over all fields
  2260. $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
  2261. $num = count($extra_user_fields);
  2262. if ($num > 0 ) {
  2263. echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
  2264. echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
  2265. echo get_lang('UserFields');
  2266. echo '</label>';
  2267. echo '</th>';
  2268. $display_extra_user_fields = true;
  2269. }
  2270. }
  2271. $course_id = api_get_course_int_id();
  2272. // Get all the questions ordered by the "sort" column
  2273. // <hub> modify the query to display open questions too
  2274. // $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
  2275. // FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
  2276. // ON q.question_id = o.question_id
  2277. // WHERE q.question_id = o.question_id
  2278. // AND q.survey_id = '".Database::escape_string($_GET['survey_id'])."'
  2279. // GROUP BY q.question_id
  2280. // ORDER BY q.sort ASC";
  2281. $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
  2282. FROM $table_survey_question q LEFT JOIN $table_survey_question_option o
  2283. ON q.question_id = o.question_id
  2284. WHERE q.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
  2285. q.c_id = $course_id AND
  2286. o.c_id = $course_id
  2287. GROUP BY q.question_id
  2288. ORDER BY q.sort ASC";
  2289. // </hub>
  2290. $result = Database::query($sql);
  2291. while ($row = Database::fetch_array($result)) {
  2292. // We show the questions if
  2293. // 1. there is no question filter and the export button has not been clicked
  2294. // 2. there is a quesiton filter but the question is selected for display
  2295. //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
  2296. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  2297. (is_array($_POST['questions_filter']) &&
  2298. in_array($row['question_id'], $_POST['questions_filter']))) {
  2299. // We do not show comment and pagebreak question types
  2300. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  2301. echo ' <th';
  2302. // <hub> modified tst to include percentage
  2303. if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
  2304. // </hub>
  2305. echo ' colspan="'.$row['number_of_options'].'"';
  2306. }
  2307. echo '>';
  2308. echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
  2309. echo $row['survey_question'];
  2310. echo '</label>';
  2311. echo '</th>';
  2312. }
  2313. // No column at all if it's not a question
  2314. }
  2315. $questions[$row['question_id']] = $row;
  2316. }
  2317. echo ' </tr>';
  2318. // Getting all the questions and options
  2319. echo ' <tr>';
  2320. echo ' <th>&nbsp;</th>'; // the user column
  2321. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  2322. isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
  2323. //show the fields names for user fields
  2324. foreach($extra_user_fields as & $field) {
  2325. echo '<th>'.$field[3].'</th>';
  2326. }
  2327. }
  2328. // cells with option (none for open question)
  2329. $sql = "SELECT sq.question_id, sq.survey_id,
  2330. sq.survey_question, sq.display,
  2331. sq.sort, sq.type, sqo.question_option_id,
  2332. sqo.option_text, sqo.sort as option_sort
  2333. FROM $table_survey_question sq
  2334. LEFT JOIN $table_survey_question_option sqo
  2335. ON sq.question_id = sqo.question_id
  2336. WHERE
  2337. sq.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
  2338. sq.c_id = $course_id AND
  2339. sqo.c_id = $course_id
  2340. ORDER BY sq.sort ASC, sqo.sort ASC";
  2341. $result = Database::query($sql);
  2342. $display_percentage_header = 1; // in order to display only once the cell option (and not 100 times)
  2343. while ($row = Database::fetch_array($result)) {
  2344. // We show the options if
  2345. // 1. there is no question filter and the export button has not been clicked
  2346. // 2. there is a question filter but the question is selected for display
  2347. //if (!($_POST['submit_question_filter'] || $_POST['export_report']) || in_array($row['question_id'], $_POST['questions_filter'])) {
  2348. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  2349. (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
  2350. ) {
  2351. // <hub> modif 05-05-2010
  2352. // we do not show comment and pagebreak question types
  2353. if ($row['type'] == 'open') {
  2354. echo '<th>&nbsp;-&nbsp;</th>';
  2355. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2356. $display_percentage_header = 1;
  2357. } else if ($row['type'] == 'percentage' && $display_percentage_header) {
  2358. echo '<th>&nbsp;%&nbsp;</th>';
  2359. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2360. $display_percentage_header = 0;
  2361. } else if ($row['type'] == 'percentage') {
  2362. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2363. } else if ($row['type'] <> 'comment' AND $row['type'] <> 'pagebreak' AND $row['type'] <> 'percentage') {
  2364. echo '<th>';
  2365. echo $row['option_text'];
  2366. echo '</th>';
  2367. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2368. $display_percentage_header = 1;
  2369. }
  2370. //no column at all if the question was not a question
  2371. // </hub>
  2372. }
  2373. }
  2374. echo ' </tr>';
  2375. // Getting all the answers of the users
  2376. $old_user = '';
  2377. $answers_of_user = array();
  2378. $sql = "SELECT * FROM $table_survey_answer
  2379. WHERE
  2380. c_id = $course_id AND
  2381. survey_id='".intval($_GET['survey_id'])."'
  2382. ORDER BY user ASC";
  2383. $result = Database::query($sql);
  2384. $i = 1;
  2385. while ($row = Database::fetch_array($result)) {
  2386. if ($old_user != $row['user'] && $old_user != '') {
  2387. $userParam = $old_user;
  2388. if ($survey_data['anonymous'] != 0) {
  2389. $userParam = $i;
  2390. $i++;
  2391. }
  2392. SurveyUtil::display_complete_report_row(
  2393. $survey_data,
  2394. $possible_answers,
  2395. $answers_of_user,
  2396. $userParam,
  2397. $questions,
  2398. $display_extra_user_fields
  2399. );
  2400. $answers_of_user=array();
  2401. }
  2402. if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
  2403. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  2404. } else {
  2405. $answers_of_user[$row['question_id']][0] = $row;
  2406. }
  2407. $old_user = $row['user'];
  2408. }
  2409. $userParam = $old_user;
  2410. if ($survey_data['anonymous'] != 0) {
  2411. $userParam = $i;
  2412. $i++;
  2413. }
  2414. SurveyUtil::display_complete_report_row(
  2415. $survey_data,
  2416. $possible_answers,
  2417. $answers_of_user,
  2418. $userParam,
  2419. $questions,
  2420. $display_extra_user_fields
  2421. );
  2422. // This is to display the last user
  2423. echo '</table>';
  2424. echo '</form>';
  2425. }
  2426. /**
  2427. * This function displays a row (= a user and his/her answers) in the table of the complete report.
  2428. *
  2429. * @param array $survey_data
  2430. * @param array Possible options
  2431. * @param array User answers
  2432. * @param mixed User ID or user details string
  2433. * @param boolean Whether to show extra user fields or not
  2434. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2435. * @version February 2007 - Updated March 2008
  2436. */
  2437. static function display_complete_report_row(
  2438. $survey_data,
  2439. $possible_options,
  2440. $answers_of_user,
  2441. $user,
  2442. $questions,
  2443. $display_extra_user_fields = false
  2444. ) {
  2445. $user = Security::remove_XSS($user);
  2446. echo '<tr>';
  2447. if ($survey_data['anonymous'] == 0) {
  2448. if (intval($user) !== 0) {
  2449. $userInfo = api_get_user_info($user);
  2450. if (!empty($userInfo)) {
  2451. $user_displayed = $userInfo['complete_name'];
  2452. } else {
  2453. $user_displayed = '-';
  2454. }
  2455. echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
  2456. $user_displayed.'</a></th>'; // the user column
  2457. } else {
  2458. echo '<th>'.$user.'</th>'; // the user column
  2459. }
  2460. } else {
  2461. echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
  2462. }
  2463. if ($display_extra_user_fields) {
  2464. // Show user fields data, if any, for this user
  2465. $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
  2466. foreach ($user_fields_values as & $value) {
  2467. echo '<td align="center">'.$value.'</td>';
  2468. }
  2469. }
  2470. if (is_array($possible_options)) {
  2471. // <hub> modified to display open answers and percentage
  2472. foreach ($possible_options as $question_id => & $possible_option) {
  2473. if ($questions[$question_id]['type'] == 'open') {
  2474. echo '<td align="center">';
  2475. echo $answers_of_user[$question_id]['0']['option_id'];
  2476. echo '</td>';
  2477. } else {
  2478. foreach ($possible_option as $option_id => & $value) {
  2479. if ($questions[$question_id]['type'] == 'percentage') {
  2480. if (!empty($answers_of_user[$question_id][$option_id])) {
  2481. echo "<td align='center'>";
  2482. echo $answers_of_user[$question_id][$option_id]['value'];
  2483. echo "</td>";
  2484. }
  2485. }
  2486. else {
  2487. echo '<td align="center">';
  2488. if (!empty($answers_of_user[$question_id][$option_id])) {
  2489. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  2490. echo $answers_of_user[$question_id][$option_id]['value'];
  2491. }
  2492. else {
  2493. echo 'v';
  2494. }
  2495. }
  2496. } // </hub>
  2497. }
  2498. }
  2499. }
  2500. }
  2501. echo '</tr>';
  2502. }
  2503. /**
  2504. * Quite similar to display_complete_report(), returns an HTML string
  2505. * that can be used in a csv file
  2506. * @todo consider merging this function with display_complete_report
  2507. * @return string The contents of a csv file
  2508. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2509. * @version February 2007
  2510. */
  2511. public static function export_complete_report($survey_data, $user_id = 0)
  2512. {
  2513. // Database table definitions
  2514. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  2515. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  2516. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  2517. // The first column
  2518. $return = ';';
  2519. // Show extra fields blank space (enough for extra fields on next line)
  2520. $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
  2521. $num = count($extra_user_fields);
  2522. $return .= str_repeat(';', $num);
  2523. $course_id = api_get_course_int_id();
  2524. $sql = "SELECT
  2525. questions.question_id,
  2526. questions.type,
  2527. questions.survey_question,
  2528. count(options.question_option_id) as number_of_options
  2529. FROM $table_survey_question questions
  2530. LEFT JOIN $table_survey_question_option options
  2531. ON questions.question_id = options.question_id AND options.c_id = $course_id
  2532. WHERE
  2533. questions.survey_id = '".intval($_GET['survey_id'])."' AND
  2534. questions.c_id = $course_id
  2535. GROUP BY questions.question_id
  2536. ORDER BY questions.sort ASC";
  2537. $result = Database::query($sql);
  2538. while ($row = Database::fetch_array($result)) {
  2539. // We show the questions if
  2540. // 1. there is no question filter and the export button has not been clicked
  2541. // 2. there is a quesiton filter but the question is selected for display
  2542. if (!($_POST['submit_question_filter']) ||
  2543. (is_array($_POST['questions_filter']) &&
  2544. in_array($row['question_id'], $_POST['questions_filter']))
  2545. ) {
  2546. // We do not show comment and pagebreak question types
  2547. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  2548. if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
  2549. $return .= str_replace("\r\n",' ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
  2550. } else {
  2551. for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
  2552. $return .= str_replace("\r\n",' ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
  2553. }
  2554. }
  2555. }
  2556. }
  2557. }
  2558. $return .= "\n";
  2559. // Getting all the questions and options
  2560. $return .= ';';
  2561. // Show the fields names for user fields
  2562. if (!empty($extra_user_fields)) {
  2563. foreach ($extra_user_fields as & $field) {
  2564. $return .= '"'.str_replace("\r\n",' ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
  2565. }
  2566. }
  2567. $sql = "SELECT
  2568. survey_question.question_id,
  2569. survey_question.survey_id,
  2570. survey_question.survey_question,
  2571. survey_question.display,
  2572. survey_question.sort,
  2573. survey_question.type,
  2574. survey_question_option.question_option_id,
  2575. survey_question_option.option_text,
  2576. survey_question_option.sort as option_sort
  2577. FROM $table_survey_question survey_question
  2578. LEFT JOIN $table_survey_question_option survey_question_option
  2579. ON
  2580. survey_question.question_id = survey_question_option.question_id AND
  2581. survey_question_option.c_id = $course_id
  2582. WHERE
  2583. survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
  2584. survey_question.c_id = $course_id
  2585. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  2586. $result = Database::query($sql);
  2587. $possible_answers = array();
  2588. $possible_answers_type = array();
  2589. while ($row = Database::fetch_array($result)) {
  2590. // We show the options if
  2591. // 1. there is no question filter and the export button has not been clicked
  2592. // 2. there is a quesiton filter but the question is selected for display
  2593. if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
  2594. in_array($row['question_id'], $_POST['questions_filter']))
  2595. ) {
  2596. // We do not show comment and pagebreak question types
  2597. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  2598. $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
  2599. $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
  2600. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2601. $possible_answers_type[$row['question_id']] = $row['type'];
  2602. }
  2603. }
  2604. }
  2605. $return .= "\n";
  2606. // Getting all the answers of the users
  2607. $old_user = '';
  2608. $answers_of_user = array();
  2609. $sql = "SELECT * FROM $table_survey_answer
  2610. WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
  2611. if ($user_id != 0) {
  2612. $sql .= "AND user='".Database::escape_string($user_id)."' ";
  2613. }
  2614. $sql .= "ORDER BY user ASC";
  2615. $open_question_iterator = 1;
  2616. $result = Database::query($sql);
  2617. while ($row = Database::fetch_array($result)) {
  2618. if ($old_user != $row['user'] && $old_user != '') {
  2619. $return .= SurveyUtil::export_complete_report_row(
  2620. $survey_data,
  2621. $possible_answers,
  2622. $answers_of_user,
  2623. $old_user,
  2624. true
  2625. );
  2626. $answers_of_user=array();
  2627. }
  2628. if($possible_answers_type[$row['question_id']] == 'open') {
  2629. $temp_id = 'open'.$open_question_iterator;
  2630. $answers_of_user[$row['question_id']][$temp_id] = $row;
  2631. $open_question_iterator++;
  2632. } else {
  2633. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  2634. }
  2635. $old_user = $row['user'];
  2636. }
  2637. // This is to display the last user
  2638. $return .= SurveyUtil::export_complete_report_row(
  2639. $survey_data,
  2640. $possible_answers,
  2641. $answers_of_user,
  2642. $old_user,
  2643. true
  2644. );
  2645. return $return;
  2646. }
  2647. /**
  2648. * Add a line to the csv file
  2649. *
  2650. * @param array Possible answers
  2651. * @param array User's answers
  2652. * @param mixed User ID or user details as string - Used as a string in the result string
  2653. * @param boolean Whether to display user fields or not
  2654. * @return string One line of the csv file
  2655. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2656. * @version February 2007
  2657. */
  2658. static function export_complete_report_row(
  2659. $survey_data,
  2660. $possible_options,
  2661. $answers_of_user,
  2662. $user,
  2663. $display_extra_user_fields = false
  2664. ) {
  2665. $return = '';
  2666. if ($survey_data['anonymous'] == 0) {
  2667. if (intval($user) !== 0) {
  2668. $userInfo = api_get_user_info($user);
  2669. if (!empty($userInfo)) {
  2670. $user_displayed = $userInfo['complete_name'];
  2671. } else {
  2672. $user_displayed = '-';
  2673. }
  2674. $return .= $user_displayed.';';
  2675. } else {
  2676. $return .= $user.';';
  2677. }
  2678. } else {
  2679. $return .= '-;'; // The user column
  2680. }
  2681. if ($display_extra_user_fields) {
  2682. // Show user fields data, if any, for this user
  2683. $user_fields_values = UserManager::get_extra_user_data($user,false,false, false, true);
  2684. foreach ($user_fields_values as & $value) {
  2685. $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
  2686. }
  2687. }
  2688. if (is_array($possible_options)) {
  2689. foreach ($possible_options as $question_id => $possible_option) {
  2690. if (is_array($possible_option) && count($possible_option) > 0) {
  2691. foreach ($possible_option as $option_id => & $value) {
  2692. $my_answer_of_user = ($answers_of_user[$question_id] == null) ? array() : $answers_of_user[$question_id];
  2693. $key = array_keys($my_answer_of_user);
  2694. if (substr($key[0], 0, 4) == 'open') {
  2695. $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)).'"';
  2696. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  2697. //$return .= 'v';
  2698. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  2699. $return .= $answers_of_user[$question_id][$option_id]['value'];
  2700. } else {
  2701. $return .= 'v';
  2702. }
  2703. }
  2704. $return .= ';';
  2705. }
  2706. }
  2707. }
  2708. }
  2709. $return .= "\n";
  2710. return $return;
  2711. }
  2712. /**
  2713. * Quite similar to display_complete_report(), returns an HTML string
  2714. * that can be used in a csv file
  2715. * @todo consider merging this function with display_complete_report
  2716. * @return string The contents of a csv file
  2717. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2718. * @version February 2007
  2719. */
  2720. static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
  2721. {
  2722. $spreadsheet = new PHPExcel();
  2723. $spreadsheet->setActiveSheetIndex(0);
  2724. $worksheet = $spreadsheet->getActiveSheet();
  2725. $line = 0;
  2726. $column = 1; // Skip the first column (row titles)
  2727. // Show extra fields blank space (enough for extra fields on next line)
  2728. //if (!empty($_REQUEST['fields_filter'])) {
  2729. // Show user fields section with a big th colspan that spans over all fields
  2730. $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
  2731. $num = count($extra_user_fields);
  2732. for ($i = 0; $i < $num; $i++) {
  2733. $worksheet->SetCellValueByColumnAndRow($line, $column, '');
  2734. $column++;
  2735. }
  2736. $display_extra_user_fields = true;
  2737. //}
  2738. // Database table definitions
  2739. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  2740. $table_survey_question_option = Database :: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  2741. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  2742. $course_id = api_get_course_int_id();
  2743. // First line (questions)
  2744. $sql = "SELECT
  2745. questions.question_id,
  2746. questions.type,
  2747. questions.survey_question,
  2748. count(options.question_option_id) as number_of_options
  2749. FROM $table_survey_question questions
  2750. LEFT JOIN $table_survey_question_option options
  2751. ON questions.question_id = options.question_id AND options.c_id = $course_id
  2752. WHERE
  2753. questions.survey_id = '".intval($_GET['survey_id'])."' AND
  2754. questions.c_id = $course_id
  2755. GROUP BY questions.question_id
  2756. ORDER BY questions.sort ASC";
  2757. $result = Database::query($sql);
  2758. while ($row = Database::fetch_array($result)) {
  2759. // We show the questions if
  2760. // 1. there is no question filter and the export button has not been clicked
  2761. // 2. there is a quesiton filter but the question is selected for display
  2762. if (!($_POST['submit_question_filter']) || (is_array($_POST['questions_filter']) &&
  2763. in_array($row['question_id'], $_POST['questions_filter']))
  2764. ) {
  2765. // We do not show comment and pagebreak question types
  2766. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  2767. if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
  2768. $worksheet->SetCellValueByColumnAndRow(
  2769. $line,
  2770. $column,
  2771. api_html_entity_decode(
  2772. strip_tags($row['survey_question']),
  2773. ENT_QUOTES
  2774. )
  2775. );
  2776. $column ++;
  2777. } else {
  2778. for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
  2779. $worksheet->SetCellValueByColumnAndRow(
  2780. $line,
  2781. $column,
  2782. api_html_entity_decode(
  2783. strip_tags($row['survey_question']),
  2784. ENT_QUOTES
  2785. )
  2786. );
  2787. $column ++;
  2788. }
  2789. }
  2790. }
  2791. }
  2792. }
  2793. $line++;
  2794. $column = 1;
  2795. // Show extra field values
  2796. if ($display_extra_user_fields) {
  2797. // Show the fields names for user fields
  2798. foreach ($extra_user_fields as & $field) {
  2799. $worksheet->SetCellValueByColumnAndRow(
  2800. $line,
  2801. $column,
  2802. api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
  2803. );
  2804. $column++;
  2805. }
  2806. }
  2807. // Getting all the questions and options (second line)
  2808. $sql = "SELECT
  2809. survey_question.question_id, survey_question.survey_id, survey_question.survey_question, survey_question.display, survey_question.sort, survey_question.type,
  2810. survey_question_option.question_option_id, survey_question_option.option_text, survey_question_option.sort as option_sort
  2811. FROM $table_survey_question survey_question
  2812. LEFT JOIN $table_survey_question_option survey_question_option
  2813. ON survey_question.question_id = survey_question_option.question_id AND survey_question_option.c_id = $course_id
  2814. WHERE survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
  2815. survey_question.c_id = $course_id
  2816. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  2817. $result = Database::query($sql);
  2818. $possible_answers = array();
  2819. $possible_answers_type = array();
  2820. while ($row = Database::fetch_array($result)) {
  2821. // We show the options if
  2822. // 1. there is no question filter and the export button has not been clicked
  2823. // 2. there is a quesiton filter but the question is selected for display
  2824. if (!($_POST['submit_question_filter']) ||
  2825. (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
  2826. ) {
  2827. // We do not show comment and pagebreak question types
  2828. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  2829. $worksheet->SetCellValueByColumnAndRow(
  2830. $line,
  2831. $column,
  2832. api_html_entity_decode(
  2833. strip_tags($row['option_text']),
  2834. ENT_QUOTES
  2835. )
  2836. );
  2837. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  2838. $possible_answers_type[$row['question_id']] = $row['type'];
  2839. $column++;
  2840. }
  2841. }
  2842. }
  2843. // Getting all the answers of the users
  2844. $line ++;
  2845. $column = 0;
  2846. $old_user = '';
  2847. $answers_of_user = array();
  2848. $sql = "SELECT * FROM $table_survey_answer
  2849. WHERE c_id = $course_id AND survey_id='".intval($_GET['survey_id'])."' ";
  2850. if ($user_id != 0) {
  2851. $sql .= "AND user='".intval($user_id)."' ";
  2852. }
  2853. $sql .= "ORDER BY user ASC";
  2854. $open_question_iterator = 1;
  2855. $result = Database::query($sql);
  2856. while ($row = Database::fetch_array($result)) {
  2857. if ($old_user != $row['user'] && $old_user != '') {
  2858. $return = SurveyUtil::export_complete_report_row_xls(
  2859. $survey_data,
  2860. $possible_answers,
  2861. $answers_of_user,
  2862. $old_user,
  2863. true
  2864. );
  2865. foreach ($return as $elem) {
  2866. $worksheet->SetCellValueByColumnAndRow($line, $column, $elem);
  2867. $column++;
  2868. }
  2869. $answers_of_user = array();
  2870. $line++;
  2871. $column = 0;
  2872. }
  2873. if ($possible_answers_type[$row['question_id']] == 'open') {
  2874. $temp_id = 'open'.$open_question_iterator;
  2875. $answers_of_user[$row['question_id']][$temp_id] = $row;
  2876. $open_question_iterator++;
  2877. } else {
  2878. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  2879. }
  2880. $old_user = $row['user'];
  2881. }
  2882. $return = SurveyUtil::export_complete_report_row_xls(
  2883. $survey_data,
  2884. $possible_answers,
  2885. $answers_of_user,
  2886. $old_user,
  2887. true
  2888. );
  2889. // this is to display the last user
  2890. foreach ($return as $elem) {
  2891. $worksheet->SetCellValueByColumnAndRow($line, $column, $elem);
  2892. $column++;
  2893. }
  2894. $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
  2895. $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
  2896. $writer->save($file);
  2897. DocumentManager::file_send_for_download($file, true, $filename);
  2898. return null;
  2899. }
  2900. /**
  2901. * Add a line to the csv file
  2902. *
  2903. * @param array Possible answers
  2904. * @param array User's answers
  2905. * @param mixed User ID or user details as string - Used as a string in the result string
  2906. * @param boolean Whether to display user fields or not
  2907. * @return string One line of the csv file
  2908. */
  2909. public static function export_complete_report_row_xls(
  2910. $survey_data,
  2911. $possible_options,
  2912. $answers_of_user,
  2913. $user,
  2914. $display_extra_user_fields = false
  2915. ) {
  2916. $return = array();
  2917. if ($survey_data['anonymous'] == 0) {
  2918. if (intval($user) !== 0) {
  2919. $sql = 'SELECT firstname, lastname
  2920. FROM '.Database::get_main_table(TABLE_MAIN_USER).'
  2921. WHERE user_id='.intval($user);
  2922. $rs = Database::query($sql);
  2923. if($row = Database::fetch_array($rs)) {
  2924. $user_displayed = api_get_person_name($row['firstname'], $row['lastname']);
  2925. } else {
  2926. $user_displayed = '-';
  2927. }
  2928. $return[] = $user_displayed;
  2929. } else {
  2930. $return[] = $user;
  2931. }
  2932. } else {
  2933. $return[] = '-'; // The user column
  2934. }
  2935. if ($display_extra_user_fields) {
  2936. //show user fields data, if any, for this user
  2937. $user_fields_values = UserManager::get_extra_user_data(intval($user),false,false, false, true);
  2938. foreach($user_fields_values as $value) {
  2939. $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
  2940. }
  2941. }
  2942. if (is_array($possible_options)) {
  2943. foreach ($possible_options as $question_id => & $possible_option) {
  2944. if (is_array($possible_option) && count($possible_option) > 0) {
  2945. foreach ($possible_option as $option_id => & $value) {
  2946. $my_answers_of_user = ($answers_of_user[$question_id]==null) ? array() : $answers_of_user[$question_id];
  2947. $key = array_keys($my_answers_of_user);
  2948. if (substr($key[0], 0, 4) == 'open') {
  2949. $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
  2950. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  2951. //$return .= 'v';
  2952. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  2953. $return[] = $answers_of_user[$question_id][$option_id]['value'];
  2954. } else {
  2955. $return[] = 'v';
  2956. }
  2957. } else {
  2958. $return[] = '';
  2959. }
  2960. }
  2961. }
  2962. }
  2963. }
  2964. return $return;
  2965. }
  2966. /**
  2967. * This function displays the comparative report which allows you to compare two questions
  2968. * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
  2969. * In the intersection is the number of people who have answerd positive on both options.
  2970. *
  2971. * @return string HTML code
  2972. *
  2973. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2974. * @version February 2007
  2975. */
  2976. public static function display_comparative_report()
  2977. {
  2978. // Allowed question types for comparative report
  2979. $allowed_question_types = array(
  2980. 'yesno',
  2981. 'multiplechoice',
  2982. 'multipleresponse',
  2983. 'dropdown',
  2984. 'percentage',
  2985. 'score',
  2986. );
  2987. // Getting all the questions
  2988. $questions = SurveyManager::get_questions($_GET['survey_id']);
  2989. // Actions bar
  2990. echo '<div class="actions">';
  2991. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.intval($_GET['survey_id']).'&'.api_get_cidreq().'">'.
  2992. Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  2993. echo '</div>';
  2994. // Displaying an information message that only the questions with predefined answers can be used in a comparative report
  2995. Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
  2996. // The form for selecting the axis of the table
  2997. echo '<form id="form1" name="form1" method="get" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.intval($_GET['survey_id']).'&xaxis='.Security::remove_XSS($_GET['xaxis']).'&y='.Security::remove_XSS($_GET['yaxis']).'">';
  2998. // Survey_id
  2999. echo '<input type="hidden" name="action" value="'.Security::remove_XSS($_GET['action']).'"/>';
  3000. echo '<input type="hidden" name="survey_id" value="'.intval($_GET['survey_id']).'"/>';
  3001. // X axis
  3002. echo get_lang('SelectXAxis').': ';
  3003. echo '<select name="xaxis">';
  3004. echo '<option value="">---</option>';
  3005. foreach ($questions as $key => & $question) {
  3006. if (is_array($allowed_question_types)) {
  3007. if (in_array($question['type'], $allowed_question_types)) {
  3008. echo '<option value="'.$question['question_id'].'"';
  3009. if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
  3010. echo ' selected="selected"';
  3011. }
  3012. echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
  3013. }
  3014. }
  3015. }
  3016. echo '</select><br /><br />';
  3017. // Y axis
  3018. echo get_lang('SelectYAxis').': ';
  3019. echo '<select name="yaxis">';
  3020. echo '<option value="">---</option>';
  3021. foreach ($questions as $key => &$question) {
  3022. if (in_array($question['type'], $allowed_question_types)) {
  3023. echo '<option value="'.$question['question_id'].'"';
  3024. if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
  3025. echo ' selected="selected"';
  3026. }
  3027. echo '">'.api_substr(strip_tags($question['question']), 0, 50).'</option>';
  3028. }
  3029. }
  3030. echo '</select><br /><br />';
  3031. echo '<button class="save" type="submit" name="Submit" value="Submit">'.get_lang('CompareQuestions').'</button>';
  3032. echo '</form>';
  3033. // Getting all the information of the x axis
  3034. if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis'])) {
  3035. $question_x = SurveyManager::get_question($_GET['xaxis']);
  3036. }
  3037. // Getting all the information of the y axis
  3038. if (isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
  3039. $question_y = SurveyManager::get_question($_GET['yaxis']);
  3040. }
  3041. if (isset($_GET['xaxis']) && is_numeric($_GET['xaxis']) && isset($_GET['yaxis']) && is_numeric($_GET['yaxis'])) {
  3042. // Getting the answers of the two questions
  3043. $answers_x = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['xaxis']);
  3044. $answers_y = SurveyUtil::get_answers_of_question_by_user($_GET['survey_id'], $_GET['yaxis']);
  3045. // Displaying the table
  3046. $tableHtml = '<table border="1" class="data_table">';
  3047. $xOptions = array();
  3048. // The header
  3049. $tableHtml .= ' <tr>';
  3050. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  3051. if ($ii == 0) {
  3052. $tableHtml .= ' <th>&nbsp;</th>';
  3053. } else {
  3054. if ($question_x['type'] == 'score') {
  3055. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  3056. $tableHtml .= ' <th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
  3057. }
  3058. $x = '';
  3059. } else {
  3060. $tableHtml .= ' <th>'.$question_x['answers'][($ii-1)].'</th>';
  3061. }
  3062. $optionText = strip_tags($question_x['answers'][$ii-1]);
  3063. $optionText = html_entity_decode($optionText);
  3064. array_push($xOptions, trim($optionText));
  3065. }
  3066. }
  3067. $tableHtml .= ' </tr>';
  3068. $chartData = array();
  3069. // The main part
  3070. for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
  3071. $currentYQuestion = strip_tags($question_y['answers'][$ij]);
  3072. $currentYQuestion = html_entity_decode($currentYQuestion);
  3073. // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
  3074. if ($question_y['type'] == 'score') {
  3075. for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
  3076. $tableHtml .= ' <tr>';
  3077. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  3078. if ($question_x['type'] == 'score') {
  3079. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  3080. if ($ii == 0) {
  3081. $tableHtml .= ' <th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
  3082. break;
  3083. } else {
  3084. $tableHtml .= ' <td align="center">';
  3085. $votes = SurveyUtil::comparative_check(
  3086. $answers_x,
  3087. $answers_y,
  3088. $question_x['answersid'][($ii - 1)],
  3089. $question_y['answersid'][($ij)],
  3090. $x,
  3091. $y
  3092. );
  3093. $tableHtml .= $votes;
  3094. array_push(
  3095. $chartData,
  3096. array(
  3097. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  3098. 'option' => $x,
  3099. 'votes' => $votes
  3100. )
  3101. );
  3102. $tableHtml .= '</td>';
  3103. }
  3104. }
  3105. } else {
  3106. if ($ii == 0) {
  3107. $tableHtml .= '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
  3108. } else {
  3109. $tableHtml .= '<td align="center">';
  3110. $votes = SurveyUtil::comparative_check(
  3111. $answers_x,
  3112. $answers_y,
  3113. $question_x['answersid'][($ii - 1)],
  3114. $question_y['answersid'][($ij)],
  3115. 0,
  3116. $y
  3117. );
  3118. $tableHtml .= $votes;
  3119. array_push(
  3120. $chartData,
  3121. array(
  3122. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  3123. 'option' => $y,
  3124. 'votes' => $votes
  3125. )
  3126. );
  3127. $tableHtml .= '</td>';
  3128. }
  3129. }
  3130. }
  3131. $tableHtml .= ' </tr>';
  3132. }
  3133. }
  3134. // The Y axis is NOT a score question type so the number of rows = the number of options
  3135. else {
  3136. $tableHtml .= ' <tr>';
  3137. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  3138. if ($question_x['type'] == 'score') {
  3139. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  3140. if ($ii == 0) {
  3141. $tableHtml .= ' <th>'.$question_y['answers'][$ij].'</th>';
  3142. break;
  3143. } else {
  3144. $tableHtml .= ' <td align="center">';
  3145. $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)], $x, 0);
  3146. $tableHtml .= $votes;
  3147. array_push(
  3148. $chartData,
  3149. array(
  3150. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  3151. 'option' => $x,
  3152. 'votes' => $votes
  3153. )
  3154. );
  3155. $tableHtml .= '</td>';
  3156. }
  3157. }
  3158. } else {
  3159. if ($ii == 0) {
  3160. $tableHtml .= ' <th>'.$question_y['answers'][($ij)].'</th>';
  3161. } else {
  3162. $tableHtml .= ' <td align="center">';
  3163. $votes = SurveyUtil::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
  3164. $tableHtml .= $votes;
  3165. array_push(
  3166. $chartData,
  3167. array(
  3168. 'serie' => $xOptions[$ii-1],
  3169. 'option' => $currentYQuestion,
  3170. 'votes' => $votes
  3171. )
  3172. );
  3173. $tableHtml .= '</td>';
  3174. }
  3175. }
  3176. }
  3177. $tableHtml .= ' </tr>';
  3178. }
  3179. }
  3180. $tableHtml .= '</table>';
  3181. echo '<div id="chartContainer" class="col-md-12">';
  3182. echo self::drawChart($chartData, true);
  3183. echo '</div>';
  3184. echo $tableHtml;
  3185. }
  3186. }
  3187. /**
  3188. * Get all the answers of a question grouped by user
  3189. *
  3190. * @param integer Survey ID
  3191. * @param integer Question ID
  3192. * @return Array Array containing all answers of all users, grouped by user
  3193. *
  3194. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3195. * @version February 2007 - Updated March 2008
  3196. */
  3197. public static function get_answers_of_question_by_user($survey_id, $question_id)
  3198. {
  3199. $course_id = api_get_course_int_id();
  3200. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  3201. $sql = "SELECT * FROM $table_survey_answer
  3202. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
  3203. AND question_id='".intval($question_id)."'
  3204. ORDER BY USER ASC";
  3205. $result = Database::query($sql);
  3206. while ($row = Database::fetch_array($result)) {
  3207. if ($row['value'] == 0) {
  3208. $return[$row['user']][] = $row['option_id'];
  3209. } else {
  3210. $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
  3211. }
  3212. }
  3213. return $return;
  3214. }
  3215. /**
  3216. * Count the number of users who answer positively on both options
  3217. *
  3218. * @param array All answers of the x axis
  3219. * @param array All answers of the y axis
  3220. * @param integer x axis value (= the option_id of the first question)
  3221. * @param integer y axis value (= the option_id of the second question)
  3222. * @return integer Number of users who have answered positively to both options
  3223. *
  3224. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3225. * @version February 2007
  3226. */
  3227. public static function comparative_check($answers_x, $answers_y, $option_x, $option_y, $value_x = 0, $value_y = 0)
  3228. {
  3229. if ($value_x == 0) {
  3230. $check_x = $option_x;
  3231. } else {
  3232. $check_x = $option_x.'*'.$value_x;
  3233. }
  3234. if ($value_y == 0) {
  3235. $check_y = $option_y;
  3236. } else {
  3237. $check_y = $option_y.'*'.$value_y;
  3238. }
  3239. $counter = 0;
  3240. if (is_array($answers_x)) {
  3241. foreach ($answers_x as $user => & $answers) {
  3242. // Check if the user has given $option_x as answer
  3243. if (in_array($check_x, $answers)) {
  3244. // Check if the user has given $option_y as an answer
  3245. if (!is_null($answers_y[$user]) && in_array($check_y, $answers_y[$user])) {
  3246. $counter++;
  3247. }
  3248. }
  3249. }
  3250. }
  3251. return $counter;
  3252. }
  3253. /**
  3254. * Get all the information about the invitations of a certain survey
  3255. *
  3256. * @return array Lines of invitation [user, code, date, empty element]
  3257. *
  3258. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3259. * @version January 2007
  3260. *
  3261. * @todo use survey_id parameter instead of $_GET
  3262. */
  3263. public static function get_survey_invitations_data()
  3264. {
  3265. $course_id = api_get_course_int_id();
  3266. // Database table definition
  3267. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  3268. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  3269. $sql = "SELECT
  3270. survey_invitation.user as col1,
  3271. survey_invitation.invitation_code as col2,
  3272. survey_invitation.invitation_date as col3,
  3273. '' as col4
  3274. FROM $table_survey_invitation survey_invitation
  3275. LEFT JOIN $table_user user
  3276. ON survey_invitation.user = user.user_id
  3277. WHERE
  3278. survey_invitation.c_id = $course_id AND
  3279. survey_invitation.survey_id = '".intval($_GET['survey_id'])."' AND
  3280. session_id='".api_get_session_id()."' ";
  3281. $res = Database::query($sql);
  3282. $data = [];
  3283. while ($row = Database::fetch_array($res)) {
  3284. $data[] = $row;
  3285. }
  3286. return $data;
  3287. }
  3288. /**
  3289. * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
  3290. *
  3291. * @return integer Total number of survey invitations
  3292. *
  3293. * @todo use survey_id parameter instead of $_GET
  3294. *
  3295. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3296. * @version January 2007
  3297. */
  3298. public static function get_number_of_survey_invitations()
  3299. {
  3300. $course_id = api_get_course_int_id();
  3301. // Database table definition
  3302. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  3303. $sql = "SELECT count(user) AS total
  3304. FROM $table_survey_invitation
  3305. WHERE
  3306. c_id = $course_id AND
  3307. survey_id='".intval($_GET['survey_id'])."' AND
  3308. session_id='".api_get_session_id()."' ";
  3309. $res = Database::query($sql);
  3310. $row = Database::fetch_array($res,'ASSOC');
  3311. return $row['total'];
  3312. }
  3313. /**
  3314. * Save the invitation mail
  3315. *
  3316. * @param string Text of the e-mail
  3317. * @param integer Whether the mail contents are for invite mail (0, default) or reminder mail (1)
  3318. *
  3319. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3320. * @version January 2007
  3321. */
  3322. public static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
  3323. {
  3324. $course_id = api_get_course_int_id();
  3325. // Database table definition
  3326. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  3327. // Reminder or not
  3328. if ($reminder == 0) {
  3329. $mail_field = 'invite_mail';
  3330. } else {
  3331. $mail_field = 'reminder_mail';
  3332. }
  3333. $sql = "UPDATE $table_survey SET
  3334. mail_subject='".Database::escape_string($mail_subject)."',
  3335. $mail_field = '".Database::escape_string($mailtext)."'
  3336. WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
  3337. Database::query($sql);
  3338. }
  3339. /**
  3340. * This function saves all the invitations of course users and additional users in the database
  3341. * and sends the invitations by email
  3342. *
  3343. * @param array Users array can be both a list of course uids AND a list of additional emailaddresses
  3344. * @param string Title of the invitation, used as the title of the mail
  3345. * @param string Text of the invitation, used as the text of the mail.
  3346. * The text has to contain a **link** string or this will automatically be added to the end
  3347. *
  3348. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3349. * @author Julio Montoya - Adding auto-generated link support
  3350. * @version January 2007
  3351. *
  3352. */
  3353. public static function saveInvitations(
  3354. $users_array,
  3355. $invitation_title,
  3356. $invitation_text,
  3357. $reminder = 0,
  3358. $sendmail = 0,
  3359. $remindUnAnswered = 0
  3360. ) {
  3361. if (!is_array($users_array)) {
  3362. // Should not happen
  3363. return 0;
  3364. }
  3365. // Getting the survey information
  3366. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  3367. $survey_invitations = SurveyUtil::get_invitations($survey_data['survey_code']);
  3368. $already_invited = SurveyUtil::get_invited_users($survey_data['code']);
  3369. // Remind unanswered is a special version of remind all reminder
  3370. $exclude_users = array();
  3371. if ($remindUnAnswered == 1) { // Remind only unanswered users
  3372. $reminder = 1;
  3373. $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
  3374. }
  3375. $counter = 0; // Nr of invitations "sent" (if sendmail option)
  3376. $course_id = api_get_course_int_id();
  3377. $session_id = api_get_session_id();
  3378. $result = CourseManager::separateUsersGroups($users_array);
  3379. $groupList = $result['groups'];
  3380. $users_array = $result['users'];
  3381. foreach ($groupList as $groupId) {
  3382. $userGroupList = GroupManager::getStudents($groupId);
  3383. $userGroupIdList = array_column($userGroupList, 'user_id');
  3384. $users_array = array_merge($users_array, $userGroupIdList);
  3385. $params = array(
  3386. 'c_id' => $course_id,
  3387. 'session_id' => $session_id,
  3388. 'group_id' => $groupId,
  3389. 'survey_code' => $survey_data['code']
  3390. );
  3391. $invitationExists = self::invitationExists(
  3392. $course_id,
  3393. $session_id,
  3394. $groupId,
  3395. $survey_data['code']
  3396. );
  3397. if (empty($invitationExists)) {
  3398. self::save_invitation($params);
  3399. }
  3400. }
  3401. $users_array = array_unique($users_array);
  3402. foreach ($users_array as $key => $value) {
  3403. if (!isset($value) || $value == '') {
  3404. continue;
  3405. }
  3406. // Skip user if reminding only unanswered people
  3407. if (in_array($value, $exclude_users)) {
  3408. continue;
  3409. }
  3410. // Get the unique invitation code if we already have it
  3411. if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
  3412. $invitation_code = $survey_invitations[$value]['invitation_code'];
  3413. } else {
  3414. $invitation_code = md5($value.microtime());
  3415. }
  3416. $new_user = false; // User not already invited
  3417. // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
  3418. $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
  3419. $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
  3420. if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
  3421. (!is_numeric($value) && !in_array($value, $addit_users_array))
  3422. ) {
  3423. $new_user = true;
  3424. if (!array_key_exists($value, $survey_invitations)) {
  3425. $params = array(
  3426. 'c_id' => $course_id,
  3427. 'session_id' => $session_id,
  3428. 'user' => $value,
  3429. 'survey_code' => $survey_data['code'],
  3430. 'invitation_code' => $invitation_code,
  3431. 'invitation_date' => api_get_utc_datetime()
  3432. );
  3433. self::save_invitation($params);
  3434. }
  3435. }
  3436. // Send the email if checkboxed
  3437. if (($new_user || $reminder == 1) && $sendmail != 0) {
  3438. // Make a change for absolute url
  3439. if (isset($invitation_text)) {
  3440. $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
  3441. $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
  3442. $invitation_text = trim(stripslashes($invitation_text));
  3443. }
  3444. SurveyUtil::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
  3445. $counter++;
  3446. }
  3447. }
  3448. return $counter; // Number of invitations sent
  3449. }
  3450. /**
  3451. * @param $params
  3452. * @return bool|int
  3453. */
  3454. public static function save_invitation($params)
  3455. {
  3456. // Database table to store the invitations data
  3457. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  3458. if (!empty($params['c_id']) &&
  3459. (!empty($params['user']) || !empty($params['group_id'])) &&
  3460. !empty($params['survey_code'])
  3461. ) {
  3462. $insertId = Database::insert($table, $params);
  3463. if ($insertId) {
  3464. $sql = "UPDATE $table SET survey_invitation_id = $insertId
  3465. WHERE iid = $insertId";
  3466. Database::query($sql);
  3467. }
  3468. return $insertId;
  3469. }
  3470. return false;
  3471. }
  3472. /**
  3473. * @param int $courseId
  3474. * @param int $sessionId
  3475. * @param int $groupId
  3476. * @param string $surveyCode
  3477. * @return int
  3478. */
  3479. public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
  3480. {
  3481. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  3482. $courseId = intval($courseId);
  3483. $sessionId = intval($sessionId);
  3484. $groupId = intval($groupId);
  3485. $surveyCode = Database::escape_string($surveyCode);
  3486. $sql = "SELECT survey_invitation_id FROM $table
  3487. WHERE
  3488. c_id = $courseId AND
  3489. session_id = $sessionId AND
  3490. group_id = $groupId AND
  3491. survey_code = '$surveyCode'
  3492. ";
  3493. $result = Database::query($sql);
  3494. return Database::num_rows($result);
  3495. }
  3496. /**
  3497. * Send the invitation by mail.
  3498. *
  3499. * @param int invitedUser - the userId (course user) or emailaddress of additional user
  3500. * $param string $invitation_code - the unique invitation code for the URL
  3501. * @return void
  3502. */
  3503. public static function send_invitation_mail($invitedUser, $invitation_code, $invitation_title, $invitation_text)
  3504. {
  3505. $_user = api_get_user_info();
  3506. $_course = api_get_course_info();
  3507. // Replacing the **link** part with a valid link for the user
  3508. $survey_link = api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['code'].'&invitationcode='.$invitation_code;
  3509. $text_link = '<a href="'.$survey_link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n".get_lang('OrCopyPasteTheFollowingUrl')." <br />\r\n ".$survey_link;
  3510. $replace_count = 0;
  3511. $full_invitation_text = api_str_ireplace('**link**', $text_link ,$invitation_text, $replace_count);
  3512. if ($replace_count < 1) {
  3513. $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
  3514. }
  3515. // Sending the mail
  3516. $sender_name = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
  3517. $sender_email = $_user['mail'];
  3518. $sender_user_id = api_get_user_id();
  3519. $replyto = array();
  3520. if (api_get_setting('survey.survey_email_sender_noreply') == 'noreply') {
  3521. $noreply = api_get_setting('mail.noreply_email_address');
  3522. if (!empty($noreply)) {
  3523. $replyto['Reply-to'] = $noreply;
  3524. $sender_name = $noreply;
  3525. $sender_email = $noreply;
  3526. $sender_user_id = null;
  3527. }
  3528. }
  3529. // Optionally: finding the e-mail of the course user
  3530. if (is_numeric($invitedUser)) {
  3531. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  3532. $sql = "SELECT firstname, lastname, email FROM $table_user
  3533. WHERE user_id='".Database::escape_string($invitedUser)."'";
  3534. $result = Database::query($sql);
  3535. $row = Database::fetch_array($result);
  3536. $recipient_email = $row['email'];
  3537. $recipient_name = api_get_person_name($row['firstname'], $row['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  3538. MessageManager::send_message(
  3539. $invitedUser,
  3540. $invitation_title,
  3541. $full_invitation_text,
  3542. [],
  3543. [],
  3544. null,
  3545. null,
  3546. null,
  3547. null,
  3548. $sender_user_id
  3549. );
  3550. } else {
  3551. /** @todo check if the address is a valid email */
  3552. $recipient_email = $invitedUser;
  3553. @api_mail_html(
  3554. $recipient_name,
  3555. $recipient_email,
  3556. $invitation_title,
  3557. $full_invitation_text,
  3558. $sender_name,
  3559. $sender_email,
  3560. $replyto
  3561. );
  3562. }
  3563. }
  3564. /**
  3565. * This function recalculates the number of users who have been invited and updates the survey table with this value.
  3566. *
  3567. * @param string Survey code
  3568. * @return void
  3569. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3570. * @version January 2007
  3571. */
  3572. public static function update_count_invited($survey_code)
  3573. {
  3574. $course_id = api_get_course_int_id();
  3575. // Database table definition
  3576. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  3577. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  3578. // Counting the number of people that are invited
  3579. $sql = "SELECT count(user) as total
  3580. FROM $table_survey_invitation
  3581. WHERE
  3582. c_id = $course_id AND
  3583. survey_code = '".Database::escape_string($survey_code)."' AND
  3584. user <> ''
  3585. ";
  3586. $result = Database::query($sql);
  3587. $row = Database::fetch_array($result);
  3588. $total_invited = $row['total'];
  3589. // Updating the field in the survey table
  3590. $sql = "UPDATE $table_survey
  3591. SET invited = '".Database::escape_string($total_invited)."'
  3592. WHERE
  3593. c_id = $course_id AND
  3594. code = '".Database::escape_string($survey_code)."'
  3595. ";
  3596. Database::query($sql);
  3597. }
  3598. /**
  3599. * This function gets all the invited users for a given survey code.
  3600. *
  3601. * @param string Survey code
  3602. * @param string optional - course database
  3603. * @return array Array containing the course users and additional users (non course users)
  3604. *
  3605. * @todo consider making $defaults['additional_users'] also an array
  3606. *
  3607. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3608. * @author Julio Montoya, adding c_id fixes - Dec 2012
  3609. * @version January 2007
  3610. */
  3611. public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
  3612. {
  3613. if (!empty($course_code)) {
  3614. $course_info = api_get_course_info($course_code);
  3615. $course_id = $course_info['real_id'];
  3616. } else {
  3617. $course_id = api_get_course_int_id();
  3618. }
  3619. if (empty($session_id)) {
  3620. $session_id = api_get_session_id();
  3621. }
  3622. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  3623. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  3624. // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
  3625. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
  3626. $sql = "SELECT user, group_id
  3627. FROM $table_survey_invitation as table_invitation
  3628. WHERE
  3629. table_invitation.c_id = $course_id AND
  3630. survey_code='".Database::escape_string($survey_code)."' AND
  3631. session_id = $session_id
  3632. ";
  3633. $defaults = array();
  3634. $defaults['course_users'] = array();
  3635. $defaults['additional_users'] = array(); // Textarea
  3636. $defaults['users'] = array(); // user and groups
  3637. $result = Database::query($sql);
  3638. while ($row = Database::fetch_array($result)) {
  3639. if (is_numeric($row['user'])) {
  3640. $defaults['course_users'][] = $row['user'];
  3641. $defaults['users'][] = 'USER:'.$row['user'];
  3642. } else {
  3643. if (!empty($row['user'])) {
  3644. $defaults['additional_users'][] = $row['user'];
  3645. }
  3646. }
  3647. if (isset($row['group_id']) && !empty($row['group_id'])) {
  3648. $defaults['users'][] = 'GROUP:'.$row['group_id'];
  3649. }
  3650. }
  3651. if (!empty($defaults['course_users'])) {
  3652. $user_ids = implode("','", $defaults['course_users']);
  3653. $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
  3654. $result = Database::query($sql);
  3655. $fixed_users = array();
  3656. while ($row = Database::fetch_array($result)) {
  3657. $fixed_users[] = $row['user_id'];
  3658. }
  3659. $defaults['course_users'] = $fixed_users;
  3660. }
  3661. if (!empty($defaults['additional_users'])) {
  3662. $defaults['additional_users'] = implode(';', $defaults['additional_users']);
  3663. }
  3664. return $defaults;
  3665. }
  3666. /**
  3667. * Get all the invitations
  3668. *
  3669. * @param string Survey code
  3670. * @return array Database rows matching the survey code
  3671. *
  3672. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3673. * @version September 2007
  3674. */
  3675. public static function get_invitations($survey_code)
  3676. {
  3677. $course_id = api_get_course_int_id();
  3678. // Database table definition
  3679. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  3680. $sql = "SELECT * FROM $table_survey_invitation
  3681. WHERE
  3682. c_id = $course_id AND
  3683. survey_code = '".Database::escape_string($survey_code)."'";
  3684. $result = Database::query($sql);
  3685. $return = array();
  3686. while ($row = Database::fetch_array($result)) {
  3687. $return[$row['user']] = $row;
  3688. }
  3689. return $return;
  3690. }
  3691. /**
  3692. * This function displays the form for searching a survey
  3693. *
  3694. * @return void (direct output)
  3695. *
  3696. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3697. * @version January 2007
  3698. *
  3699. * @todo use quickforms
  3700. * @todo consider moving this to surveymanager.inc.lib.php
  3701. */
  3702. public static function display_survey_search_form()
  3703. {
  3704. $url = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced&'.api_get_cidreq();
  3705. $form = new FormValidator('search', 'get', $url);
  3706. $form->addHeader(get_lang('SearchASurvey'));
  3707. $form->addText('keyword_title', get_lang('Title'));
  3708. $form->addText('keyword_code', get_lang('Code'));
  3709. $form->addSelectLanguage('keyword_language', get_lang('Language'));
  3710. $form->addHidden('cidReq', api_get_course_id());
  3711. $form->addButtonSearch(get_lang('Search'), 'do_search');
  3712. $form->display();
  3713. }
  3714. /**
  3715. * Show table only visible by DRH users
  3716. */
  3717. public static function displaySurveyListForDrh()
  3718. {
  3719. $parameters = array();
  3720. $parameters['cidReq'] = api_get_course_id();
  3721. // Create a sortable table with survey-data
  3722. $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data_drh', 2);
  3723. $table->set_additional_parameters($parameters);
  3724. $table->set_header(0, '', false);
  3725. $table->set_header(1, get_lang('SurveyName'));
  3726. $table->set_header(2, get_lang('SurveyCode'));
  3727. $table->set_header(3, get_lang('NumberOfQuestions'));
  3728. $table->set_header(4, get_lang('Author'));
  3729. $table->set_header(5, get_lang('AvailableFrom'));
  3730. $table->set_header(6, get_lang('AvailableUntil'));
  3731. $table->set_header(7, get_lang('Invite'));
  3732. $table->set_header(8, get_lang('Anonymous'));
  3733. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  3734. $table->set_column_filter(8, 'anonymous_filter');
  3735. $table->set_column_filter(9, 'modify_filter_drh');
  3736. $table->display();
  3737. }
  3738. /**
  3739. * This function displays the sortable table with all the surveys
  3740. *
  3741. * @return void (direct output)
  3742. *
  3743. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3744. * @version January 2007
  3745. */
  3746. public static function display_survey_list()
  3747. {
  3748. $parameters = array();
  3749. $parameters['cidReq'] = api_get_course_id();
  3750. if (isset($_GET['do_search']) && $_GET['do_search']) {
  3751. $message = get_lang('DisplaySearchResults').'<br />';
  3752. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  3753. Display::display_normal_message($message, false);
  3754. }
  3755. // Create a sortable table with survey-data
  3756. $table = new SortableTable('surveys', 'get_number_of_surveys', 'get_survey_data', 2);
  3757. $table->set_additional_parameters($parameters);
  3758. $table->set_header(0, '', false);
  3759. $table->set_header(1, get_lang('SurveyName'));
  3760. $table->set_header(2, get_lang('SurveyCode'));
  3761. $table->set_header(3, get_lang('NumberOfQuestions'));
  3762. $table->set_header(4, get_lang('Author'));
  3763. //$table->set_header(5, get_lang('Language'));
  3764. //$table->set_header(6, get_lang('Shared'));
  3765. $table->set_header(5, get_lang('AvailableFrom'));
  3766. $table->set_header(6, get_lang('AvailableUntil'));
  3767. $table->set_header(7, get_lang('Invite'));
  3768. $table->set_header(8, get_lang('Anonymous'));
  3769. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  3770. $table->set_column_filter(8, 'anonymous_filter');
  3771. $table->set_column_filter(9, 'modify_filter');
  3772. $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
  3773. $table->display();
  3774. }
  3775. /**
  3776. * Survey list for coach
  3777. */
  3778. public static function display_survey_list_for_coach()
  3779. {
  3780. $parameters = array();
  3781. $parameters['cidReq']=api_get_course_id();
  3782. if (isset($_GET['do_search'])) {
  3783. $message = get_lang('DisplaySearchResults').'<br />';
  3784. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  3785. Display::display_normal_message($message, false);
  3786. }
  3787. // Create a sortable table with survey-data
  3788. $table = new SortableTable('surveys_coach', 'get_number_of_surveys_for_coach', 'get_survey_data_for_coach', 2);
  3789. $table->set_additional_parameters($parameters);
  3790. $table->set_header(0, '', false);
  3791. $table->set_header(1, get_lang('SurveyName'));
  3792. $table->set_header(2, get_lang('SurveyCode'));
  3793. $table->set_header(3, get_lang('NumberOfQuestions'));
  3794. $table->set_header(4, get_lang('Author'));
  3795. //$table->set_header(5, get_lang('Language'));
  3796. //$table->set_header(6, get_lang('Shared'));
  3797. $table->set_header(5, get_lang('AvailableFrom'));
  3798. $table->set_header(6, get_lang('AvailableUntil'));
  3799. $table->set_header(7, get_lang('Invite'));
  3800. $table->set_header(8, get_lang('Anonymous'));
  3801. $table->set_header(9, get_lang('Modify'), false, 'width="130"');
  3802. $table->set_column_filter(8, 'anonymous_filter');
  3803. $table->set_column_filter(9, 'modify_filter_for_coach');
  3804. $table->display();
  3805. }
  3806. /**
  3807. * This function changes the modify column of the sortable table
  3808. *
  3809. * @param integer $survey_id the id of the survey
  3810. * @param bool $drh
  3811. * @return string html code that are the actions that can be performed on any survey
  3812. *
  3813. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3814. * @version January 2007
  3815. */
  3816. public static function modify_filter($survey_id, $drh = false)
  3817. {
  3818. $survey_id = Security::remove_XSS($survey_id);
  3819. $return = '';
  3820. if ($drh) {
  3821. return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  3822. Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
  3823. }
  3824. // Coach can see that only if the survey is in his session
  3825. if (api_is_allowed_to_edit() ||
  3826. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  3827. ) {
  3828. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
  3829. if (SurveyManager::survey_generation_hash_available()) {
  3830. $return .= Display::url(
  3831. Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
  3832. api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
  3833. );
  3834. }
  3835. $return .= Display::url(
  3836. Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
  3837. 'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
  3838. );
  3839. $return .= ' <a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?')).'\')) return false;">'.
  3840. Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3841. }
  3842. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  3843. Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3844. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  3845. Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3846. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  3847. Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
  3848. if (api_is_allowed_to_edit() ||
  3849. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  3850. ) {
  3851. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.
  3852. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3853. }
  3854. return $return;
  3855. }
  3856. public static function modify_filter_for_coach($survey_id)
  3857. {
  3858. $survey_id = Security::remove_XSS($survey_id);
  3859. //$return = '<a href="create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
  3860. //$return .= '<a href="survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
  3861. //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
  3862. //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
  3863. $return = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3864. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3865. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  3866. return $return;
  3867. }
  3868. /**
  3869. * Returns "yes" when given parameter is one, "no" for any other value
  3870. * @param integer Whether anonymous or not
  3871. * @return string "Yes" or "No" in the current language
  3872. */
  3873. public static function anonymous_filter($anonymous)
  3874. {
  3875. if ($anonymous == 1) {
  3876. return get_lang('Yes');
  3877. } else {
  3878. return get_lang('No');
  3879. }
  3880. }
  3881. /**
  3882. * This function handles the search restriction for the SQL statements
  3883. *
  3884. * @return string Part of a SQL statement or false on error
  3885. *
  3886. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3887. * @version January 2007
  3888. */
  3889. public static function survey_search_restriction()
  3890. {
  3891. if (isset($_GET['do_search'])) {
  3892. if ($_GET['keyword_title'] != '') {
  3893. $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
  3894. }
  3895. if ($_GET['keyword_code'] != '') {
  3896. $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
  3897. }
  3898. if ($_GET['keyword_language'] != '%') {
  3899. $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
  3900. }
  3901. $my_search_term = ($search_term == null) ? array() : $search_term;
  3902. $search_restriction = implode(' AND ', $my_search_term);
  3903. return $search_restriction;
  3904. } else {
  3905. return false;
  3906. }
  3907. }
  3908. /**
  3909. * This function calculates the total number of surveys
  3910. *
  3911. * @return integer Total number of surveys
  3912. *
  3913. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3914. * @version January 2007
  3915. */
  3916. public static function get_number_of_surveys()
  3917. {
  3918. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  3919. $course_id = api_get_course_int_id();
  3920. $search_restriction = SurveyUtil::survey_search_restriction();
  3921. if ($search_restriction) {
  3922. $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
  3923. } else {
  3924. $search_restriction = "WHERE c_id = $course_id";
  3925. }
  3926. $sql = "SELECT count(survey_id) AS total_number_of_items
  3927. FROM ".$table_survey.' '.$search_restriction;
  3928. $res = Database::query($sql);
  3929. $obj = Database::fetch_object($res);
  3930. return $obj->total_number_of_items;
  3931. }
  3932. public static function get_number_of_surveys_for_coach()
  3933. {
  3934. $survey_tree = new SurveyTree();
  3935. return count($survey_tree->get_last_children_from_branch($survey_tree->surveylist));
  3936. }
  3937. /**
  3938. * This function gets all the survey data that is to be displayed in the sortable table
  3939. *
  3940. * @param int $from
  3941. * @param int $number_of_items
  3942. * @param int $column
  3943. * @param string $direction
  3944. * @param bool $isDrh
  3945. * @return unknown
  3946. *
  3947. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  3948. * @author Julio Montoya <gugli100@gmail.com>, Beeznest - Adding intvals
  3949. * @version January 2007
  3950. */
  3951. public static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
  3952. {
  3953. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  3954. $table_user = Database :: get_main_table(TABLE_MAIN_USER);
  3955. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  3956. $_user = api_get_user_info();
  3957. // Searching
  3958. $search_restriction = SurveyUtil::survey_search_restriction();
  3959. if ($search_restriction) {
  3960. $search_restriction = ' AND '.$search_restriction;
  3961. }
  3962. $from = intval($from);
  3963. $number_of_items = intval($number_of_items);
  3964. $column = intval($column);
  3965. if (!in_array(strtolower($direction), array('asc', 'desc'))) {
  3966. $direction = 'asc';
  3967. }
  3968. // Condition for the session
  3969. $session_id = api_get_session_id();
  3970. $condition_session = api_get_session_condition($session_id);
  3971. $course_id = api_get_course_int_id();
  3972. $sql = "SELECT
  3973. survey.survey_id AS col0,
  3974. survey.title AS col1,
  3975. survey.code AS col2,
  3976. count(survey_question.question_id) AS col3,
  3977. ".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")." AS col4,
  3978. survey.avail_from AS col5,
  3979. survey.avail_till AS col6,
  3980. survey.invited AS col7,
  3981. survey.anonymous AS col8,
  3982. survey.survey_id AS col9,
  3983. survey.session_id AS session_id,
  3984. survey.answered,
  3985. survey.invited
  3986. FROM $table_survey survey
  3987. LEFT JOIN $table_survey_question survey_question
  3988. ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
  3989. LEFT JOIN $table_user user
  3990. ON (survey.author = user.user_id)
  3991. WHERE survey.c_id = $course_id
  3992. $search_restriction
  3993. $condition_session ";
  3994. $sql .= " GROUP BY survey.survey_id";
  3995. $sql .= " ORDER BY col$column $direction ";
  3996. $sql .= " LIMIT $from,$number_of_items";
  3997. $res = Database::query($sql);
  3998. $surveys = array();
  3999. $array = array();
  4000. while ($survey = Database::fetch_array($res)) {
  4001. $array[0] = $survey[0];
  4002. $array[1] = Display::url(
  4003. $survey[1],
  4004. api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
  4005. );
  4006. // Validation when belonging to a session
  4007. $session_img = api_get_session_image($survey['session_id'], $_user['status']);
  4008. $array[2] = $survey[2] . $session_img;
  4009. $array[3] = $survey[3];
  4010. $array[4] = $survey[4];
  4011. $array[5] = $survey[5];
  4012. $array[6] = $survey[6];
  4013. $array[7] =
  4014. Display::url(
  4015. $survey['answered'],
  4016. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
  4017. ).' / '.
  4018. Display::url(
  4019. $survey['invited'],
  4020. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
  4021. );
  4022. $array[8] = $survey[8];
  4023. $array[9] = $survey[9];
  4024. if ($isDrh) {
  4025. $array[1] = $survey[1];
  4026. $array[7] = strip_tags($array[7]);
  4027. }
  4028. $surveys[] = $array;
  4029. }
  4030. return $surveys;
  4031. }
  4032. public static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
  4033. {
  4034. $survey_tree = new SurveyTree();
  4035. $last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
  4036. $list = array();
  4037. foreach ($last_version_surveys as & $survey) {
  4038. $list[]=$survey['id'];
  4039. }
  4040. if (count($list) > 0) {
  4041. $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
  4042. } else {
  4043. $list_condition = '';
  4044. }
  4045. $from = intval($from);
  4046. $number_of_items = intval($number_of_items);
  4047. $column = intval($column);
  4048. if (!in_array(strtolower($direction), array('asc', 'desc'))) {
  4049. $direction = 'asc';
  4050. }
  4051. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  4052. $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
  4053. $table_user = Database:: get_main_table(TABLE_MAIN_USER);
  4054. $course_id = api_get_course_int_id();
  4055. $sql = "SELECT ".
  4056. "survey.survey_id AS col0, ".
  4057. "survey.title AS col1, ".
  4058. "survey.code AS col2, ".
  4059. "count(survey_question.question_id) AS col3, ".
  4060. (api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")." AS col4, ".
  4061. "survey.avail_from AS col5, ".
  4062. "survey.avail_till AS col6, ".
  4063. "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, ".
  4064. "survey.anonymous AS col8, ".
  4065. "survey.survey_id AS col9 ".
  4066. "FROM $table_survey survey ".
  4067. "LEFT JOIN $table_survey_question survey_question
  4068. ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id) ".
  4069. ", $table_user user
  4070. WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
  4071. $sql .= " GROUP BY survey.survey_id";
  4072. $sql .= " ORDER BY col$column $direction ";
  4073. $sql .= " LIMIT $from,$number_of_items";
  4074. $res = Database::query($sql);
  4075. $surveys = array();
  4076. while ($survey = Database::fetch_array($res)) {
  4077. $surveys[] = $survey;
  4078. }
  4079. return $surveys;
  4080. }
  4081. /**
  4082. * Display all the active surveys for the given course user
  4083. *
  4084. * @param int $user_id
  4085. *
  4086. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  4087. * @version April 2007
  4088. */
  4089. public static function getSurveyList($user_id)
  4090. {
  4091. $_course = api_get_course_info();
  4092. $course_id = $_course['real_id'];
  4093. $user_id = intval($user_id);
  4094. $sessionId = api_get_session_id();
  4095. // Database table definitions
  4096. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  4097. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  4098. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  4099. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  4100. $sql = 'SELECT question_id
  4101. FROM '.$table_survey_question."
  4102. WHERE c_id = $course_id";
  4103. $result = Database::query($sql);
  4104. $all_question_id = array();
  4105. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4106. $all_question_id[] = $row;
  4107. }
  4108. $count = 0;
  4109. for ($i = 0; $i < count($all_question_id); $i++) {
  4110. $sql = 'SELECT COUNT(*) as count
  4111. FROM '.$table_survey_answer.'
  4112. WHERE
  4113. c_id = '.$course_id.' AND
  4114. question_id='.intval($all_question_id[$i]['question_id']).' AND
  4115. user = '.$user_id;
  4116. $result = Database::query($sql);
  4117. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4118. if ($row['count'] == 0) {
  4119. $count++;
  4120. break;
  4121. }
  4122. }
  4123. if ($count > 0) {
  4124. $link_add = true;
  4125. break;
  4126. }
  4127. }
  4128. echo '<table id="list-survey" class="table ">';
  4129. echo '<tr>';
  4130. echo ' <th>'.get_lang('SurveyName').'</th>';
  4131. echo ' <th>'.get_lang('Anonymous').'</th>';
  4132. echo '</tr>';
  4133. $sql = "SELECT *
  4134. FROM $table_survey survey,
  4135. $table_survey_invitation survey_invitation
  4136. WHERE
  4137. survey_invitation.user = $user_id AND
  4138. survey.code = survey_invitation.survey_code AND
  4139. survey.avail_from <= '".date('Y-m-d H:i:s')."' AND
  4140. survey.avail_till >= '".date('Y-m-d H:i:s')."' AND
  4141. survey.c_id = $course_id AND
  4142. survey.session_id = $sessionId AND
  4143. survey_invitation.c_id = $course_id
  4144. ";
  4145. $result = Database::query($sql);
  4146. $counter = 0;
  4147. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4148. // Get the user into survey answer table (user or anonymus)
  4149. $sql = "SELECT user FROM $table_survey_answer
  4150. WHERE c_id = $course_id AND survey_id = (
  4151. SELECT survey_id from $table_survey
  4152. WHERE code ='".Database::escape_string($row['code'])." AND c_id = $course_id'
  4153. )
  4154. ";
  4155. $result_answer = Database::query($sql);
  4156. $row_answer = Database::fetch_array($result_answer,'ASSOC');
  4157. echo '<tr>';
  4158. if ($row['answered'] == 0) {
  4159. echo '<td>';
  4160. echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
  4161. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.$row['title'].'</a></td>';
  4162. } else {
  4163. //echo '<td>'.$row['title'].'</td>';
  4164. echo '<td>';
  4165. echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'),array('style'=>'inline-block'),ICON_SIZE_TINY);
  4166. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=questionreport&cidReq='.$_course['sysCode'].'&id_session='.$row['session_id'].'&gidReq='.'0'.'&origin='.''.'&survey_id='.$row['survey_id'].'">'.$row['title'].'</a></td>';
  4167. }
  4168. echo '<td class="center">';
  4169. echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
  4170. echo '</td>';
  4171. echo '</tr>';
  4172. if ($row['anonymous'] == 1) {
  4173. $current_user_id = $_SESSION['surveyuser'];
  4174. } else {
  4175. $current_user_id = api_get_user_id();
  4176. }
  4177. $link_available = self::show_link_available(api_get_user_id(),$row['code'],$current_user_id);
  4178. //todo check this link
  4179. if ($link_add === true && $link_available === true) {
  4180. //echo '<tr><td><a href="fillsurvey.php?user_id='.api_get_user_id().'&course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.get_lang('CompleteTheSurveysQuestions').'</a></td><td></td></tr>';
  4181. }
  4182. }
  4183. echo '</table>';
  4184. }
  4185. /**
  4186. * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
  4187. * The username is always NOT able to change it.
  4188. * @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification
  4189. * @return array[value_name][name]
  4190. * array[value_name][visibilty]
  4191. */
  4192. public static function make_field_list()
  4193. {
  4194. // LAST NAME and FIRST NAME
  4195. $field_list_array = array();
  4196. $field_list_array['lastname']['name'] = get_lang('LastName');
  4197. $field_list_array['firstname']['name'] = get_lang('FirstName');
  4198. if (api_get_setting('profile', 'name') != 'true') {
  4199. $field_list_array['firstname']['visibility'] = 0;
  4200. $field_list_array['lastname']['visibility'] = 0;
  4201. } else {
  4202. $field_list_array['firstname']['visibility'] = 1;
  4203. $field_list_array['lastname']['visibility'] = 1;
  4204. }
  4205. $field_list_array['username']['name'] = get_lang('Username');
  4206. $field_list_array['username']['visibility'] = 0;
  4207. // OFFICIAL CODE
  4208. $field_list_array['official_code']['name'] = get_lang('OfficialCode');
  4209. if (api_get_setting('profile', 'officialcode') != 'true') {
  4210. $field_list_array['official_code']['visibility'] = 1;
  4211. } else {
  4212. $field_list_array['official_code']['visibility'] = 0;
  4213. }
  4214. // EMAIL
  4215. $field_list_array['email']['name'] = get_lang('Email');
  4216. if (api_get_setting('profile', 'email') != 'true') {
  4217. $field_list_array['email']['visibility'] = 1;
  4218. } else {
  4219. $field_list_array['email']['visibility'] = 0;
  4220. }
  4221. // PHONE
  4222. $field_list_array['phone']['name'] = get_lang('Phone');
  4223. if (api_get_setting('profile', 'phone') != 'true') {
  4224. $field_list_array['phone']['visibility'] = 0;
  4225. } else {
  4226. $field_list_array['phone']['visibility'] = 1;
  4227. }
  4228. // LANGUAGE
  4229. $field_list_array['language']['name'] = get_lang('Language');
  4230. if (api_get_setting('profile', 'language') != 'true') {
  4231. $field_list_array['language']['visibility'] = 0;
  4232. } else {
  4233. $field_list_array['language']['visibility'] = 1;
  4234. }
  4235. // EXTRA FIELDS
  4236. $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  4237. foreach ($extra as $id => $field_details) {
  4238. if ($field_details[6] == 0) {
  4239. continue;
  4240. }
  4241. switch ($field_details[2]) {
  4242. case UserManager::USER_FIELD_TYPE_TEXT:
  4243. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4244. if ($field_details[7] == 0) {
  4245. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4246. } else {
  4247. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4248. }
  4249. break;
  4250. case UserManager::USER_FIELD_TYPE_TEXTAREA:
  4251. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4252. if ($field_details[7] == 0) {
  4253. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4254. } else {
  4255. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4256. }
  4257. break;
  4258. case UserManager::USER_FIELD_TYPE_RADIO:
  4259. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4260. if ($field_details[7] == 0) {
  4261. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4262. } else {
  4263. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4264. }
  4265. break;
  4266. case UserManager::USER_FIELD_TYPE_SELECT:
  4267. $get_lang_variables = false;
  4268. if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
  4269. $get_lang_variables = true;
  4270. }
  4271. if ($get_lang_variables) {
  4272. $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
  4273. } else {
  4274. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4275. }
  4276. if ($field_details[7] == 0) {
  4277. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4278. } else {
  4279. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4280. }
  4281. break;
  4282. case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
  4283. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4284. if ($field_details[7] == 0) {
  4285. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4286. } else {
  4287. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4288. }
  4289. break;
  4290. case UserManager::USER_FIELD_TYPE_DATE:
  4291. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4292. if ($field_details[7] == 0) {
  4293. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4294. } else {
  4295. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4296. }
  4297. break;
  4298. case UserManager::USER_FIELD_TYPE_DATETIME:
  4299. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4300. if ($field_details[7] == 0) {
  4301. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4302. } else {
  4303. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  4304. }
  4305. break;
  4306. case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
  4307. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  4308. if ($field_details[7] == 0) {
  4309. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  4310. } else {
  4311. $field_list_array['extra_'.$field_details[1]]['visibility']=1;
  4312. }
  4313. break;
  4314. case UserManager::USER_FIELD_TYPE_DIVIDER:
  4315. //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
  4316. break;
  4317. }
  4318. }
  4319. return $field_list_array;
  4320. }
  4321. /**
  4322. * @author Isaac Flores Paz <florespaz@bidsoftperu.com>
  4323. * @param int $user_id - User ID
  4324. * @param int $user_id_answer - User in survey answer table (user id or anonymus)
  4325. * @return boolean
  4326. */
  4327. public static function show_link_available($user_id, $survey_code, $user_answer)
  4328. {
  4329. $table_survey = Database :: get_course_table(TABLE_SURVEY);
  4330. $table_survey_invitation = Database :: get_course_table(TABLE_SURVEY_INVITATION);
  4331. $table_survey_answer = Database :: get_course_table(TABLE_SURVEY_ANSWER);
  4332. $table_survey_question = Database :: get_course_table(TABLE_SURVEY_QUESTION);
  4333. $survey_code = Database::escape_string($survey_code);
  4334. $user_id = intval($user_id);
  4335. $user_answer = Database::escape_string($user_answer);
  4336. $course_id = api_get_course_int_id();
  4337. $sql = 'SELECT COUNT(*) as count
  4338. FROM '.$table_survey_invitation.'
  4339. WHERE user='.$user_id.' AND survey_code="'.$survey_code.'" AND answered="1" AND c_id = '.$course_id.' ';
  4340. $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s INNER JOIN '.$table_survey_question.' q ON s.survey_id=q.survey_id
  4341. WHERE s.code="'.$survey_code.'" AND q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
  4342. $sql3 = 'SELECT COUNT(DISTINCT question_id) as count FROM '.$table_survey_answer.'
  4343. WHERE survey_id=(SELECT survey_id FROM '.$table_survey.'
  4344. WHERE code="'.$survey_code.'" AND c_id = '.$course_id.' ) AND user="'.$user_answer.'" AND c_id = '.$course_id.' ';
  4345. $result = Database::query($sql);
  4346. $result2 = Database::query($sql2);
  4347. $result3 = Database::query($sql3);
  4348. $row = Database::fetch_array($result, 'ASSOC');
  4349. $row2 = Database::fetch_array($result2, 'ASSOC');
  4350. $row3 = Database::fetch_array($result3, 'ASSOC');
  4351. if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
  4352. return true;
  4353. } else {
  4354. return false;
  4355. }
  4356. }
  4357. /**
  4358. * Display survey question chart
  4359. * @param array Chart data
  4360. * @param boolean Tells if the chart has a serie. False by default
  4361. * @return void (direct output)
  4362. */
  4363. public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
  4364. {
  4365. $htmlChart = '';
  4366. if (api_browser_support("svg")) {
  4367. $htmlChart .= api_get_js("js/d3/d3.v3.5.4.min.js");
  4368. $htmlChart .= api_get_js("js/dimple.v2.1.2.min.js").'
  4369. <script type="text/javascript">
  4370. var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
  4371. var data = [';
  4372. $serie = array();
  4373. $order = array();
  4374. foreach ($chartData as $chartDataElement) {
  4375. $htmlChart .= '{"';
  4376. if (!$hasSerie) {
  4377. $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
  4378. array_push($order, $chartDataElement['option']);
  4379. } else {
  4380. if (!is_array($chartDataElement['serie'])) {
  4381. $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
  4382. get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
  4383. array_push($serie, $chartDataElement['serie']);
  4384. } else {
  4385. $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
  4386. get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
  4387. get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
  4388. }
  4389. }
  4390. $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
  4391. '"},';
  4392. }
  4393. rtrim($htmlChart, ",");
  4394. $htmlChart .= '];
  4395. var myChart = new dimple.chart(svg, data);
  4396. myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
  4397. if (!$hasSerie) {
  4398. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
  4399. xAxisCategory.addOrderRule(' . json_encode($order) . ');
  4400. myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
  4401. } else {
  4402. if (!is_array($chartDataElement['serie'])) {
  4403. $serie = array_values(array_unique($serie));
  4404. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
  4405. xAxisCategory.addOrderRule(' . json_encode($serie) . ');
  4406. xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
  4407. myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
  4408. } else {
  4409. $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
  4410. myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
  4411. }
  4412. }
  4413. $htmlChart .= 'myChart.draw();
  4414. </script>';
  4415. }
  4416. return $htmlChart;
  4417. }
  4418. /**
  4419. * Set a flag to the current survey as answered by the current user
  4420. * @param string $surveyCode The survey code
  4421. * @param int $courseId The course ID
  4422. */
  4423. public static function flagSurveyAsAnswered($surveyCode, $courseId)
  4424. {
  4425. $currenUserId = api_get_user_id();
  4426. $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
  4427. if (!isset($_SESSION['filled_surveys'])) {
  4428. $_SESSION['filled_surveys'] = array();
  4429. }
  4430. $_SESSION['filled_surveys'][] = $flag;
  4431. }
  4432. /**
  4433. * Check whether a survey was answered by the current user
  4434. * @param string $surveyCode The survey code
  4435. * @param int $courseId The course ID
  4436. * @return boolean
  4437. */
  4438. public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
  4439. {
  4440. $currenUserId = api_get_user_id();
  4441. $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currenUserId);
  4442. if (!isset($_SESSION['filled_surveys'])) {
  4443. return false;
  4444. }
  4445. if (!is_array($_SESSION['filled_surveys'])) {
  4446. return false;
  4447. }
  4448. foreach ($_SESSION['filled_surveys'] as $flag) {
  4449. if ($flagToCheck != $flag) {
  4450. continue;
  4451. }
  4452. return true;
  4453. }
  4454. return false;
  4455. }
  4456. }