survey.lib.php 207 KB

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