survey.lib.php 211 KB

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