survey.lib.php 213 KB

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