exercise.class.php 262 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise class: This class allows to instantiate an object of type Exercise
  5. * @package chamilo.exercise
  6. * @author Olivier Brouckaert
  7. * @author Julio Montoya Cleaning exercises
  8. * Modified by Hubert Borderiou #294
  9. */
  10. /**
  11. * Code
  12. */
  13. use \ChamiloSession as Session;
  14. // Page options
  15. define('ALL_ON_ONE_PAGE', 1);
  16. define('ONE_PER_PAGE', 2);
  17. define('EXERCISE_MODEL_TYPE_NORMAL', 1);
  18. define('EXERCISE_MODEL_TYPE_COMMITTEE', 2);
  19. define('EXERCISE_FEEDBACK_TYPE_END', 0); //Feedback - show score and expected answers
  20. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1); //DirectFeedback - Do not show score nor answers
  21. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2); //NoFeedback - Show score only
  22. define('RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS', 0); //show score and expected answers
  23. define('RESULT_DISABLE_NO_SCORE_AND_EXPECTED_ANSWERS', 1); //Do not show score nor answers
  24. define('RESULT_DISABLE_SHOW_SCORE_ONLY', 2); //Show score only
  25. define('RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES', 3); //Show final score only with categories
  26. define('EXERCISE_MAX_NAME_SIZE', 80);
  27. define('EXERCISE_CATEGORY_RANDOM_SHUFFLED', 1);
  28. define('EXERCISE_CATEGORY_RANDOM_ORDERED', 2);
  29. define('EXERCISE_CATEGORY_RANDOM_DISABLED', 0);
  30. $debug = false; //All exercise scripts should depend in this debug variable
  31. class Exercise
  32. {
  33. public $id;
  34. public $name;
  35. public $title;
  36. public $exercise;
  37. public $description;
  38. public $sound;
  39. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  40. public $random;
  41. public $random_answers;
  42. public $active;
  43. public $timeLimit;
  44. public $attempts;
  45. public $feedback_type;
  46. public $end_time;
  47. public $start_time;
  48. /* show media id */
  49. public $questionList; // medias as id
  50. /* including question list of the media */
  51. public $questionListUncompressed;
  52. public $results_disabled;
  53. public $expired_time;
  54. public $course;
  55. public $course_id;
  56. public $propagate_neg;
  57. public $review_answers;
  58. public $randomByCat;
  59. public $text_when_finished;
  60. public $display_category_name;
  61. public $pass_percentage;
  62. public $edit_exercise_in_lp = false;
  63. public $is_gradebook_locked = false;
  64. public $exercise_was_added_in_lp = false;
  65. public $force_edit_exercise_in_lp = false;
  66. public $categories;
  67. public $categories_grouping = true;
  68. public $endButton = 0;
  69. public $categoryWithQuestionList;
  70. public $mediaList;
  71. public $loadQuestionAJAX = false;
  72. public $emailNotificationTemplate = null;
  73. public $countQuestions = 0;
  74. public $fastEdition = false;
  75. public $modelType = 1;
  76. /**
  77. * Constructor of the class
  78. *
  79. * @author - Olivier Brouckaert
  80. * @param int $course_id
  81. */
  82. public function Exercise($course_id = null)
  83. {
  84. $this->id = 0;
  85. $this->exercise = '';
  86. $this->description = '';
  87. $this->sound = '';
  88. $this->type = ALL_ON_ONE_PAGE;
  89. $this->random = 0;
  90. $this->random_answers = 0;
  91. $this->active = 1;
  92. $this->questionList = array();
  93. $this->timeLimit = 0;
  94. $this->end_time = '0000-00-00 00:00:00';
  95. $this->start_time = '0000-00-00 00:00:00';
  96. $this->results_disabled = 1;
  97. $this->expired_time = '0000-00-00 00:00:00';
  98. $this->propagate_neg = 0;
  99. $this->review_answers = false;
  100. $this->randomByCat = 0;
  101. $this->text_when_finished = "";
  102. $this->display_category_name = 0;
  103. $this->pass_percentage = null;
  104. $this->modelType = 1;
  105. $this->endButton = 0;
  106. if (!empty($course_id)) {
  107. $course_info = api_get_course_info_by_id($course_id);
  108. } else {
  109. $course_info = api_get_course_info();
  110. }
  111. $this->course_id = $course_info['real_id'];
  112. $this->course = $course_info;
  113. $this->fastEdition = api_get_course_setting('allow_fast_exercise_edition') == 1 ? true : false;
  114. $this->emailAlert = api_get_course_setting('email_alert_manager_on_new_quiz') == 1 ? true : false;
  115. }
  116. /**
  117. * Reads exercise information from the database
  118. *
  119. * @author Olivier Brouckaert
  120. * @param int $id - exercise ID
  121. * @param bool parse exercise question list
  122. * @return boolean - true if exercise exists, otherwise false
  123. */
  124. public function read($id, $parseQuestionList = true)
  125. {
  126. if (empty($this->course_id)) {
  127. return false;
  128. }
  129. global $_configuration;
  130. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  131. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  132. $id = intval($id);
  133. $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = ".$this->course_id." AND iid = ".$id;
  134. $result = Database::query($sql);
  135. // if the exercise has been found
  136. if ($object = Database::fetch_object($result)) {
  137. $this->id = $id;
  138. $this->exercise = $object->title;
  139. $this->name = $object->title;
  140. $this->title = $object->title;
  141. $this->description = $object->description;
  142. $this->sound = $object->sound;
  143. $this->type = $object->type;
  144. if (empty($this->type)) {
  145. $this->type = ONE_PER_PAGE;
  146. }
  147. $this->random = $object->random;
  148. $this->random_answers = $object->random_answers;
  149. $this->active = $object->active;
  150. $this->results_disabled = $object->results_disabled;
  151. $this->attempts = $object->max_attempt;
  152. $this->feedback_type = $object->feedback_type;
  153. $this->propagate_neg = $object->propagate_neg;
  154. $this->randomByCat = $object->random_by_category;
  155. $this->text_when_finished = $object->text_when_finished;
  156. $this->display_category_name = $object->display_category_name;
  157. $this->pass_percentage = $object->pass_percentage;
  158. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  159. $this->endButton = $object->end_button;
  160. $this->emailNotificationTemplate = $object->email_notification_template;
  161. $this->modelType = $object->model_type;
  162. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  163. $sql = "SELECT max_score FROM $table_lp_item
  164. WHERE c_id = {$this->course_id} AND
  165. item_type = '".TOOL_QUIZ."' AND
  166. path = '".$id."'";
  167. $result = Database::query($sql);
  168. if (Database::num_rows($result) > 0) {
  169. $this->exercise_was_added_in_lp = true;
  170. }
  171. $this->force_edit_exercise_in_lp = isset($_configuration['force_edit_exercise_in_lp']) ? $_configuration['force_edit_exercise_in_lp'] : false;
  172. if ($this->exercise_was_added_in_lp) {
  173. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  174. } else {
  175. $this->edit_exercise_in_lp = true;
  176. }
  177. if ($object->end_time != '0000-00-00 00:00:00') {
  178. $this->end_time = $object->end_time;
  179. }
  180. if ($object->start_time != '0000-00-00 00:00:00') {
  181. $this->start_time = $object->start_time;
  182. }
  183. // Control time
  184. $this->expired_time = $object->expired_time;
  185. if ($parseQuestionList) {
  186. $this->setQuestionList();
  187. }
  188. //overload questions list with recorded questions list
  189. //load questions only for exercises of type 'one question per page'
  190. //this is needed only is there is no questions
  191. /*
  192. // @todo not sure were in the code this is used somebody mess with the exercise tool
  193. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  194. global $_configuration, $questionList;
  195. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  196. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
  197. $this->questionList = $questionList;
  198. } */
  199. return true;
  200. }
  201. // exercise not found
  202. return false;
  203. }
  204. /**
  205. * @return string
  206. */
  207. public function getCutTitle()
  208. {
  209. return Text::cut($this->exercise, EXERCISE_MAX_NAME_SIZE);
  210. }
  211. /**
  212. * Returns the exercise ID
  213. *
  214. * @author - Olivier Brouckaert
  215. *
  216. * @return int - exercise ID
  217. */
  218. public function selectId()
  219. {
  220. return $this->id;
  221. }
  222. /**
  223. * returns the exercise title
  224. *
  225. * @author - Olivier Brouckaert
  226. *
  227. * @return string - exercise title
  228. */
  229. function selectTitle()
  230. {
  231. return $this->exercise;
  232. }
  233. /**
  234. * returns the number of attempts setted
  235. *
  236. * @return numeric - exercise attempts
  237. */
  238. function selectAttempts()
  239. {
  240. return $this->attempts;
  241. }
  242. /** returns the number of FeedbackType *
  243. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  244. *
  245. * @return int exercise attempts
  246. */
  247. function selectFeedbackType()
  248. {
  249. return $this->feedback_type;
  250. }
  251. /**
  252. * returns the time limit
  253. */
  254. function selectTimeLimit()
  255. {
  256. return $this->timeLimit;
  257. }
  258. /**
  259. * returns the exercise description
  260. *
  261. * @author - Olivier Brouckaert
  262. *
  263. * @return string - exercise description
  264. */
  265. function selectDescription()
  266. {
  267. return $this->description;
  268. }
  269. /**
  270. * Returns the exercise sound file
  271. *
  272. * @author Olivier Brouckaert
  273. * @return string - exercise description
  274. */
  275. function selectSound()
  276. {
  277. return $this->sound;
  278. }
  279. /**
  280. * Returns the exercise type
  281. *
  282. * @author - Olivier Brouckaert
  283. * @return integer - exercise type
  284. */
  285. public function selectType()
  286. {
  287. return $this->type;
  288. }
  289. /**
  290. * @author - hubert borderiou 30-11-11
  291. * @return integer : do we display the question category name for students
  292. */
  293. public function selectDisplayCategoryName()
  294. {
  295. return $this->display_category_name;
  296. }
  297. /**
  298. * @return string
  299. */
  300. public function selectPassPercentage()
  301. {
  302. return $this->pass_percentage;
  303. }
  304. /**
  305. * @return string
  306. */
  307. public function selectEmailNotificationTemplate()
  308. {
  309. return $this->emailNotificationTemplate;
  310. }
  311. public function getModelType()
  312. {
  313. return $this->modelType;
  314. }
  315. /**
  316. * @return int
  317. */
  318. public function selectEndButton()
  319. {
  320. return $this->endButton;
  321. }
  322. /**
  323. * @author Hubert borderiou 30-11-11
  324. * @return void modify object to update the switch display_category_name
  325. * $in_txt is an integer 0 or 1
  326. */
  327. public function updateDisplayCategoryName($text)
  328. {
  329. $this->display_category_name = $text;
  330. }
  331. /**
  332. * @author - hubert borderiou 28-11-11
  333. * @return string html text : the text to display ay the end of the test.
  334. */
  335. public function selectTextWhenFinished()
  336. {
  337. return $this->text_when_finished;
  338. }
  339. /**
  340. * @author Hubert borderiou 28-11-11
  341. * @return string html text : update the text to display ay the end of the test.
  342. */
  343. public function updateTextWhenFinished($text)
  344. {
  345. $this->text_when_finished = $text;
  346. }
  347. /**
  348. * return 1 or 2 if randomByCat
  349. * @author - hubert borderiou
  350. * @return integer - quiz random by category
  351. */
  352. public function selectRandomByCat()
  353. {
  354. return $this->randomByCat;
  355. }
  356. /**
  357. * return 0 if no random by cat
  358. * return 1 if random by cat, categories shuffled
  359. * return 2 if random by cat, categories sorted by alphabetic order
  360. * @author Hubert borderiou
  361. *
  362. * @return integer - quiz random by category
  363. */
  364. public function isRandomByCat()
  365. {
  366. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  367. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  368. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  369. } else if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  370. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  371. }
  372. return $res;
  373. }
  374. /**
  375. * Sets the random by category value
  376. * @author Julio Montoya
  377. * @param int random by category
  378. */
  379. public function updateRandomByCat($random)
  380. {
  381. if (in_array($random, array(
  382. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  383. EXERCISE_CATEGORY_RANDOM_ORDERED,
  384. EXERCISE_CATEGORY_RANDOM_DISABLED
  385. )
  386. )) {
  387. $this->randomByCat = $random;
  388. } else {
  389. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  390. }
  391. }
  392. /**
  393. * Tells if questions are selected randomly, and if so returns the draws
  394. *
  395. * @author - Carlos Vargas
  396. *
  397. * @return int results disabled exercise
  398. */
  399. public function selectResultsDisabled()
  400. {
  401. return $this->results_disabled;
  402. }
  403. /**
  404. * tells if questions are selected randomly, and if so returns the draws
  405. *
  406. * @author - Olivier Brouckaert
  407. *
  408. * @return bool - 0 if not random, otherwise the draws
  409. */
  410. public function isRandom()
  411. {
  412. if ($this->random > 0 || $this->random == -1) {
  413. return true;
  414. } else {
  415. return false;
  416. }
  417. }
  418. /**
  419. * returns random answers status.
  420. *
  421. * @author - Juan Carlos Ra�a
  422. */
  423. public function selectRandomAnswers()
  424. {
  425. return $this->random_answers;
  426. }
  427. /**
  428. * Same as isRandom() but has a name applied to values different than 0 or 1
  429. */
  430. public function getShuffle()
  431. {
  432. return $this->random;
  433. }
  434. /**
  435. * Returns the exercise status (1 = enabled ; 0 = disabled)
  436. *
  437. * @author - Olivier Brouckaert
  438. * @return - boolean - true if enabled, otherwise false
  439. */
  440. public function selectStatus()
  441. {
  442. return $this->active;
  443. }
  444. /**
  445. * If false the question list will be managed as always if true the question will be filtered
  446. * depending of the exercise settings (table c_quiz_rel_category)
  447. * @param bool active or inactive grouping
  448. **/
  449. public function setCategoriesGrouping($status)
  450. {
  451. $this->categories_grouping = (bool) $status;
  452. }
  453. /**
  454. *
  455. * @param int $start
  456. * @param int $limit
  457. * @param int $sidx
  458. * @param string $sord
  459. * @param array $where_condition
  460. */
  461. public function getQuestionListPagination($start, $limit, $sidx, $sord, $where_condition = array())
  462. {
  463. if (!empty($this->id)) {
  464. $category_list = Testcategory::getListOfCategoriesNameForTest($this->id, false);
  465. //$category_list = Testcategory::getListOfCategoriesIDForTestObject($this);
  466. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  467. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  468. $sql = "SELECT q.iid
  469. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  470. ON (e.question_id = q.iid AND e.c_id = ".$this->course_id." )
  471. WHERE e.exercice_id = '".Database::escape_string($this->id)."'
  472. ";
  473. $orderCondition = "ORDER BY question_order";
  474. if (!empty($sidx) && !empty($sord)) {
  475. if ($sidx == 'question') {
  476. if (in_array(strtolower($sord), array('desc', 'asc'))) {
  477. $orderCondition = " ORDER BY q.$sidx $sord";
  478. }
  479. }
  480. }
  481. $sql .= $orderCondition;
  482. $limitCondition = null;
  483. if (isset($start) && isset($limit)) {
  484. $start = intval($start);
  485. $limit = intval($limit);
  486. $limitCondition = " LIMIT $start, $limit";
  487. }
  488. $sql .= $limitCondition;
  489. $result = Database::query($sql);
  490. $questions = array();
  491. if (Database::num_rows($result)) {
  492. while ($question = Database::fetch_array($result, 'ASSOC')) {
  493. $objQuestionTmp = Question::read($question['iid']);
  494. $category_labels = Testcategory::return_category_labels($objQuestionTmp->category_list, $category_list);
  495. if (empty($category_labels)) {
  496. $category_labels = "-";
  497. }
  498. // Question type
  499. list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
  500. $question_media = null;
  501. if (!empty($objQuestionTmp->parent_id)) {
  502. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  503. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  504. }
  505. $questionType = Display::tag('div', Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media);
  506. $question = array(
  507. 'id' => $question['iid'],
  508. 'question' => $objQuestionTmp->selectTitle(),
  509. 'type' => $questionType,
  510. 'category' => Display::tag('div', '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'),
  511. 'score' => $objQuestionTmp->selectWeighting(),
  512. 'level' => $objQuestionTmp->level
  513. );
  514. $questions[] = $question;
  515. }
  516. }
  517. return $questions;
  518. }
  519. }
  520. /**
  521. * Get question count per exercise from DB (any special treatment)
  522. * @return int
  523. */
  524. public function getQuestionCount()
  525. {
  526. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  527. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  528. $sql = "SELECT count(e.iid) as count
  529. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  530. ON (e.question_id = q.iid)
  531. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  532. $result = Database::query($sql);
  533. $count = 0;
  534. if (Database::num_rows($result)) {
  535. $row = Database::fetch_array($result);
  536. $count = $row['count'];
  537. }
  538. return $count;
  539. }
  540. /**
  541. * Gets the question list ordered by the question_order setting (drag and drop)
  542. * @return array
  543. */
  544. private function getQuestionOrderedList()
  545. {
  546. $questionList = array();
  547. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  548. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  549. // Getting question_order to verify that the question list is correct and all question_order's were set
  550. $sql = "SELECT DISTINCT e.question_order
  551. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  552. ON (e.question_id = q.iid)
  553. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  554. $result = Database::query($sql);
  555. $count_question_orders = Database::num_rows($result);
  556. // Getting question list from the order (question list drag n drop interface ).
  557. $sql = "SELECT e.question_id, e.question_order
  558. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  559. ON (e.question_id= q.iid)
  560. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  561. ORDER BY question_order";
  562. $result = Database::query($sql);
  563. // Fills the array with the question ID for this exercise
  564. // the key of the array is the question position
  565. $temp_question_list = array();
  566. $counter = 1;
  567. while ($new_object = Database::fetch_object($result)) {
  568. // Correct order.
  569. $questionList[$new_object->question_order] = $new_object->question_id;
  570. // Just in case we save the order in other array
  571. $temp_question_list[$counter] = $new_object->question_id;
  572. $counter++;
  573. }
  574. if (!empty($temp_question_list)) {
  575. /* If both array don't match it means that question_order was not correctly set
  576. for all questions using the default mysql order */
  577. if (count($temp_question_list) != $count_question_orders) {
  578. $questionList = $temp_question_list;
  579. }
  580. }
  581. return $questionList;
  582. }
  583. /**
  584. * Select N values from the questions per category array
  585. * @param array $question_list
  586. * @param array $questions_by_category per category
  587. * @param array
  588. * @param bool flat result
  589. * @return array
  590. */
  591. private function pickQuestionsPerCategory($question_list, $questions_by_category, $categoryCountArray = array(), $flatResult = true)
  592. {
  593. if (!empty($questions_by_category)) {
  594. // Sets random per category
  595. $numberOfQuestions = $this->random;
  596. $randomize = true;
  597. // If random is not set then take the max value, this value could be set to 1000 or 9999
  598. if ($this->random == -1 || empty($this->random)) {
  599. $numberOfQuestions = count($question_list);
  600. $randomize = false;
  601. }
  602. $temp_question_list = array();
  603. while (list($category_id, $categoryQuestionList) = each($questions_by_category)) {
  604. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  605. if (isset($categoryCountArray[$category_id])) {
  606. $numberOfQuestions = $categoryCountArray[$category_id];
  607. } else {
  608. $numberOfQuestions = 0;
  609. }
  610. }
  611. $elements = Testcategory::getNElementsFromArray($categoryQuestionList, $numberOfQuestions, $randomize);
  612. if (!empty($elements)) {
  613. $temp_question_list[$category_id] = $elements;
  614. }
  615. }
  616. if (!empty($temp_question_list)) {
  617. if ($flatResult) {
  618. $temp_question_list = ArrayClass::array_flatten($temp_question_list);
  619. }
  620. $question_list = $temp_question_list;
  621. }
  622. }
  623. return $question_list;
  624. }
  625. /**
  626. * Selecting question list depending in the exercise-category
  627. * relationship (category table in exercise settings)
  628. *
  629. * @param array $question_list
  630. * @return array
  631. */
  632. public function getQuestionListWithCategoryListFilteredByCategorySettings($question_list)
  633. {
  634. $result = array();
  635. $result['question_list'] = array();
  636. $result['category_with_questions_list'] = array();
  637. $randomByCategory = $this->isRandomByCat();
  638. $categoriesAddedInExercise = array();
  639. // Order/random categories
  640. $cat = new Testcategory();
  641. switch ($randomByCategory) {
  642. case EXERCISE_CATEGORY_RANDOM_DISABLED: // 0
  643. break;
  644. case EXERCISE_CATEGORY_RANDOM_SHUFFLED: // 1
  645. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id']);
  646. if (!empty($categoriesAddedInExercise)) {
  647. shuffle($categoriesAddedInExercise);
  648. }
  649. break;
  650. case EXERCISE_CATEGORY_RANDOM_ORDERED: // 2
  651. $categoriesAddedInExercise = $cat->getCategoryExerciseTree($this->id, $this->course['real_id'], 'title DESC');
  652. break;
  653. }
  654. // Checking if the "category rel exercise" was set
  655. $totalCategoriesRelExercise = 0;
  656. if (!empty($categoriesAddedInExercise)) {
  657. foreach ($categoriesAddedInExercise as $category_info) {
  658. $totalCategoriesRelExercise += intval($category_info['count_questions']);
  659. }
  660. }
  661. // "Category rel exercise" is empty we search now for the "category rel question" relationships
  662. if (empty($totalCategoriesRelExercise)) {
  663. switch ($randomByCategory) {
  664. case EXERCISE_CATEGORY_RANDOM_SHUFFLED: // 1
  665. // Getting questions by category in an exercise with shuffling mode ON
  666. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, null, true);
  667. $question_list = $this->pickQuestionsPerCategory($question_list, $questions_by_category);
  668. break;
  669. case EXERCISE_CATEGORY_RANDOM_DISABLED: // 0
  670. // No category order to apply check the random
  671. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list);
  672. break;
  673. case EXERCISE_CATEGORY_RANDOM_ORDERED: // 2
  674. // Getting questions by category in an exercise ordered by category title
  675. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list);
  676. $question_list = $this->pickQuestionsPerCategory($question_list, $questions_by_category);
  677. break;
  678. }
  679. } else {
  680. // Reorder questions depending of the category settings
  681. switch ($randomByCategory) {
  682. case EXERCISE_CATEGORY_RANDOM_DISABLED: // 0
  683. // No category order to apply check the random
  684. break;
  685. case EXERCISE_CATEGORY_RANDOM_SHUFFLED: // 1
  686. // Getting questions by category in an exercise with shuffling mode ON
  687. $questions_by_category = Testcategory::getQuestionsByCat($this->id, $question_list, null, true);
  688. break;
  689. case EXERCISE_CATEGORY_RANDOM_ORDERED: // 2
  690. // Getting questions by category in an exercise ordered by category title
  691. $questions_by_category = Testcategory::getQuestionsByCat($this->id);
  692. break;
  693. }
  694. // Checking if the category rel exercise settings was set (category table in the exercise settings)
  695. // Parsing question according the category rel exercise settings
  696. $categoryCountArray = array();
  697. foreach ($categoriesAddedInExercise as $category_info) {
  698. $category_id = $category_info['category_id'];
  699. if (isset($questions_by_category[$category_id])) {
  700. // How many question will be picked from this category.
  701. $count = $category_info['count_questions'];
  702. if (!empty($count)) {
  703. $categoryCountArray[$category_id] = $count;
  704. }
  705. }
  706. }
  707. $questions_by_category = $this->pickQuestionsPerCategory($question_list, $questions_by_category, $categoryCountArray, false);
  708. $question_list = ArrayClass::array_flatten($questions_by_category);
  709. }
  710. $result['question_list'] = isset($question_list) ? $question_list : array();
  711. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : array();
  712. if (!empty($result['category_with_questions_list'])) {
  713. global $app;
  714. $em = $app['orm.em'];
  715. $repo = $em->getRepository('Entity\CQuizCategory');
  716. $newCategoryList = array();
  717. foreach ($result['category_with_questions_list'] as $categoryId => $questionList) {
  718. $cat = new Testcategory($categoryId);
  719. $cat = (array)$cat;
  720. $cat['iid'] = $cat['id'];
  721. $cat['name'] = $cat['title'];
  722. $categoryParentInfo = null;
  723. if (!empty($cat['parent_id'])) {
  724. if (!isset($parentsLoaded[$cat['parent_id']])) {
  725. $categoryEntity = $em->find('Entity\CQuizCategory', $cat['parent_id']);
  726. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  727. } else {
  728. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  729. }
  730. $path = $repo->getPath($categoryEntity);
  731. if (isset($path) && isset($path[0])) {
  732. $categoryParentId = $path[0]->getIid();
  733. $categoryParentInfo['id'] = $categoryParentId;
  734. $categoryParentInfo['iid'] = $categoryParentId;
  735. $categoryParentInfo['parent_path'] = null;
  736. $categoryParentInfo['title'] = $path[0]->getTitle();
  737. $categoryParentInfo['name'] = $path[0]->getTitle();
  738. $categoryParentInfo['parent_id'] = null;
  739. }
  740. }
  741. $cat['parent_info'] = $categoryParentInfo;
  742. $newCategoryList[$categoryId] = array(
  743. 'category' => $cat,
  744. 'question_list' => $questionList
  745. );
  746. }
  747. $result['category_with_questions_list'] = $newCategoryList;
  748. }
  749. return $result;
  750. }
  751. /**
  752. * Returns the array with the question ID list ordered by question order (including question list in medias)
  753. *
  754. * @author Olivier Brouckaert
  755. * @param bool $from_db
  756. * @return array question ID list
  757. */
  758. private function selectQuestionList($from_db = false)
  759. {
  760. if ($from_db && !empty($this->id)) {
  761. $nbQuestions = $this->getQuestionCount();
  762. // Not a random exercise, or if there are not at least 2 questions
  763. if ($this->random == 0 || $nbQuestions < 2) {
  764. $questionList = $this->getQuestionOrderedList();
  765. } else {
  766. $questionList = $this->selectRandomList();
  767. }
  768. if ($this->categories_grouping) {
  769. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings($questionList);
  770. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  771. $questionList = $result['question_list'];
  772. }
  773. return $questionList;
  774. }
  775. return $this->questionList;
  776. }
  777. /**
  778. * returns the number of questions in this exercise
  779. *
  780. * @author - Olivier Brouckaert
  781. * @return integer - number of questions
  782. */
  783. public function selectNbrQuestions()
  784. {
  785. return sizeof($this->questionList);
  786. }
  787. public function selectPropagateNeg()
  788. {
  789. return $this->propagate_neg;
  790. }
  791. /**
  792. * Selects questions randomly in the question list
  793. * If the exercise is not set to take questions randomly, returns the question list
  794. * without randomizing, otherwise, returns the list with questions selected randomly
  795. *
  796. * @author Olivier Brouckaert, Modified by Hubert Borderiou 15 nov 2011
  797. * @param array question list
  798. * @return array question list modified or unmodified
  799. *
  800. */
  801. public function selectRandomList()
  802. {
  803. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  804. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  805. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  806. $randomLimit = "LIMIT $random";
  807. // Random all questions so no limit
  808. if ($random == -1) {
  809. $randomLimit = null;
  810. }
  811. // @todo improve this query
  812. $sql = "SELECT e.question_id
  813. FROM $TBL_EXERCISE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  814. ON (e.question_id= q.iid)
  815. WHERE e.c_id = {$this->course_id} AND e.exercice_id = '".Database::escape_string($this->id)."'
  816. ORDER BY RAND()
  817. $randomLimit ";
  818. $result = Database::query($sql);
  819. $questionList = array();
  820. while ($row = Database::fetch_object($result)) {
  821. $questionList[] = $row->question_id;
  822. }
  823. return $questionList;
  824. }
  825. /**
  826. * returns 'true' if the question ID is in the question list
  827. *
  828. * @author - Olivier Brouckaert
  829. * @param - integer $questionId - question ID
  830. *
  831. * @return boolean - true if in the list, otherwise false
  832. */
  833. public function isInList($questionId)
  834. {
  835. if (is_array($this->questionList)) {
  836. return in_array($questionId, $this->questionList);
  837. } else {
  838. return false;
  839. }
  840. }
  841. /**
  842. * changes the exercise title
  843. *
  844. * @author - Olivier Brouckaert
  845. * @param - string $title - exercise title
  846. */
  847. public function updateTitle($title)
  848. {
  849. $this->exercise = $title;
  850. }
  851. /**
  852. * changes the exercise max attempts
  853. *
  854. * @param - numeric $attempts - exercise max attempts
  855. */
  856. public function updateAttempts($attempts)
  857. {
  858. $this->attempts = $attempts;
  859. }
  860. public function updateActive($active)
  861. {
  862. $this->active = $active;
  863. }
  864. /**
  865. * changes the exercise feedback type
  866. *
  867. * @param - numeric $attempts - exercise max attempts
  868. */
  869. public function updateFeedbackType($feedback_type)
  870. {
  871. $this->feedback_type = $feedback_type;
  872. }
  873. /**
  874. * changes the exercise description
  875. *
  876. * @author - Olivier Brouckaert
  877. * @param - string $description - exercise description
  878. */
  879. public function updateDescription($description)
  880. {
  881. $this->description = $description;
  882. }
  883. /**
  884. * changes the exercise expired_time
  885. *
  886. * @author - Isaac flores
  887. * @param - int The expired time of the quiz
  888. */
  889. public function updateExpiredTime($expired_time)
  890. {
  891. $this->expired_time = $expired_time;
  892. }
  893. public function updatePropagateNegative($value)
  894. {
  895. $this->propagate_neg = $value;
  896. }
  897. /**
  898. * @param $value
  899. */
  900. public function updateReviewAnswers($value)
  901. {
  902. $this->review_answers = (isset($value) && $value) ? true : false;
  903. }
  904. /**
  905. * @param $value
  906. */
  907. public function updatePassPercentage($value)
  908. {
  909. $this->pass_percentage = $value;
  910. }
  911. /**
  912. * @param $text
  913. */
  914. public function updateEmailNotificationTemplate($text)
  915. {
  916. $this->emailNotificationTemplate = $text;
  917. }
  918. public function updateEndButton($value)
  919. {
  920. $this->endButton = intval($value);
  921. }
  922. public function setModelType($value)
  923. {
  924. $this->modelType = intval($value);
  925. }
  926. /**
  927. * @param array $categories
  928. */
  929. public function updateCategories($categories)
  930. {
  931. if (!empty($categories)) {
  932. $categories = array_map('intval', $categories);
  933. $this->categories = $categories;
  934. }
  935. }
  936. /**
  937. * changes the exercise sound file
  938. *
  939. * @author - Olivier Brouckaert
  940. * @param - string $sound - exercise sound file
  941. * @param - string $delete - ask to delete the file
  942. */
  943. public function updateSound($sound, $delete)
  944. {
  945. global $audioPath, $documentPath;
  946. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  947. if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
  948. $this->sound = $sound['name'];
  949. if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
  950. $query = "SELECT 1 FROM $TBL_DOCUMENT WHERE c_id = ".$this->course_id." AND path='".str_replace(
  951. $documentPath,
  952. '',
  953. $audioPath
  954. ).'/'.$this->sound."'";
  955. $result = Database::query($query);
  956. if (!Database::num_rows($result)) {
  957. $id = FileManager::add_document(
  958. $this->course,
  959. str_replace($documentPath, '', $audioPath).'/'.$this->sound,
  960. 'file',
  961. $sound['size'],
  962. $sound['name']
  963. );
  964. api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded', api_get_user_id());
  965. FileManager::item_property_update_on_folder(
  966. $this->course,
  967. str_replace($documentPath, '', $audioPath),
  968. api_get_user_id()
  969. );
  970. }
  971. }
  972. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  973. $this->sound = '';
  974. }
  975. }
  976. /**
  977. * changes the exercise type
  978. *
  979. * @author - Olivier Brouckaert
  980. * @param - integer $type - exercise type
  981. */
  982. public function updateType($type)
  983. {
  984. $this->type = $type;
  985. }
  986. /**
  987. * sets to 0 if questions are not selected randomly
  988. * if questions are selected randomly, sets the draws
  989. *
  990. * @author - Olivier Brouckaert
  991. * @param - integer $random - 0 if not random, otherwise the draws
  992. */
  993. public function setRandom($random)
  994. {
  995. $this->random = $random;
  996. }
  997. /**
  998. * sets to 0 if answers are not selected randomly
  999. * if answers are selected randomly
  1000. * @author - Juan Carlos Ra�a
  1001. * @param - integer $random_answers - random answers
  1002. */
  1003. public function updateRandomAnswers($random_answers)
  1004. {
  1005. $this->random_answers = $random_answers;
  1006. }
  1007. /**
  1008. * enables the exercise
  1009. *
  1010. * @author - Olivier Brouckaert
  1011. */
  1012. public function enable()
  1013. {
  1014. $this->active = 1;
  1015. }
  1016. /**
  1017. * disables the exercise
  1018. *
  1019. * @author - Olivier Brouckaert
  1020. */
  1021. public function disable()
  1022. {
  1023. $this->active = 0;
  1024. }
  1025. public function disable_results()
  1026. {
  1027. $this->results_disabled = true;
  1028. }
  1029. public function enable_results()
  1030. {
  1031. $this->results_disabled = false;
  1032. }
  1033. public function updateResultsDisabled($results_disabled)
  1034. {
  1035. $this->results_disabled = intval($results_disabled);
  1036. }
  1037. /**
  1038. * updates the exercise in the data base
  1039. *
  1040. * @author - Olivier Brouckaert
  1041. */
  1042. public function save($type_e = '')
  1043. {
  1044. $_course = $this->course;
  1045. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1046. $id = $this->id;
  1047. $exercise = $this->exercise;
  1048. $description = $this->description;
  1049. $sound = $this->sound;
  1050. $type = $this->type;
  1051. $attempts = $this->attempts;
  1052. $feedback_type = $this->feedback_type;
  1053. $random = $this->random;
  1054. $random_answers = $this->random_answers;
  1055. $active = $this->active;
  1056. $propagate_neg = $this->propagate_neg;
  1057. $review_answers = (isset($this->review_answers) && $this->review_answers) ? 1 : 0;
  1058. $randomByCat = $this->randomByCat;
  1059. $text_when_finished = $this->text_when_finished;
  1060. $display_category_name = intval($this->display_category_name);
  1061. $pass_percentage = intval($this->pass_percentage);
  1062. $session_id = api_get_session_id();
  1063. // If direct we do not show results
  1064. if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1065. $results_disabled = 0;
  1066. } else {
  1067. $results_disabled = intval($this->results_disabled);
  1068. }
  1069. $expired_time = intval($this->expired_time);
  1070. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  1071. $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
  1072. } else {
  1073. $start_time = '0000-00-00 00:00:00';
  1074. }
  1075. if (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00') {
  1076. $end_time = Database::escape_string(api_get_utc_datetime($this->end_time));
  1077. } else {
  1078. $end_time = '0000-00-00 00:00:00';
  1079. }
  1080. // Exercise already exists
  1081. if ($id) {
  1082. $sql = "UPDATE $TBL_EXERCICES SET
  1083. title='".Database::escape_string($exercise)."',
  1084. description='".Database::escape_string($description)."'";
  1085. if ($type_e != 'simple') {
  1086. $sql .= ",sound='".Database::escape_string($sound)."',
  1087. type ='".Database::escape_string($type)."',
  1088. random ='".Database::escape_string($random)."',
  1089. random_answers ='".Database::escape_string($random_answers)."',
  1090. active ='".Database::escape_string($active)."',
  1091. feedback_type ='".Database::escape_string($feedback_type)."',
  1092. start_time = '$start_time',
  1093. end_time = '$end_time',
  1094. max_attempt ='".Database::escape_string($attempts)."',
  1095. expired_time ='".Database::escape_string($expired_time)."',
  1096. propagate_neg ='".Database::escape_string($propagate_neg)."',
  1097. review_answers ='".Database::escape_string($review_answers)."',
  1098. random_by_category='".Database::escape_string($randomByCat)."',
  1099. text_when_finished = '".Database::escape_string($text_when_finished)."',
  1100. display_category_name = '".Database::escape_string($display_category_name)."',
  1101. pass_percentage = '".Database::escape_string($pass_percentage)."',
  1102. end_button = '".$this->selectEndButton()."',
  1103. email_notification_template = '".Database::escape_string($this->selectEmailNotificationTemplate())."',
  1104. model_type = '".$this->getModelType()."',
  1105. results_disabled='".Database::escape_string($results_disabled)."'";
  1106. }
  1107. $sql .= " WHERE iid = ".Database::escape_string($id)." AND c_id = {$this->course_id}";
  1108. Database::query($sql);
  1109. // update into the item_property table
  1110. api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizUpdated', api_get_user_id());
  1111. if (api_get_setting('search_enabled') == 'true') {
  1112. $this->search_engine_edit();
  1113. }
  1114. } else {
  1115. // Creates a new exercise
  1116. $sql = "INSERT INTO $TBL_EXERCICES (
  1117. c_id, start_time, end_time, title, description, sound, type, random, random_answers, active,
  1118. max_attempt, feedback_type, expired_time, session_id, review_answers, random_by_category,
  1119. text_when_finished, display_category_name, pass_percentage, end_button, email_notification_template, results_disabled, model_type)
  1120. VALUES(
  1121. ".$this->course_id.",
  1122. '$start_time',
  1123. '$end_time',
  1124. '".Database::escape_string($exercise)."',
  1125. '".Database::escape_string($description)."',
  1126. '".Database::escape_string($sound)."',
  1127. '".Database::escape_string($type)."',
  1128. '".Database::escape_string($random)."',
  1129. '".Database::escape_string($random_answers)."',
  1130. '".Database::escape_string($active)."',
  1131. '".Database::escape_string($attempts)."',
  1132. '".Database::escape_string($feedback_type)."',
  1133. '".Database::escape_string($expired_time)."',
  1134. '".Database::escape_string($session_id)."',
  1135. '".Database::escape_string($review_answers)."',
  1136. '".Database::escape_string($randomByCat)."',
  1137. '".Database::escape_string($text_when_finished)."',
  1138. '".Database::escape_string($display_category_name)."',
  1139. '".Database::escape_string($pass_percentage)."',
  1140. '".Database::escape_string($this->selectEndButton())."',
  1141. '".Database::escape_string($this->selectEmailNotificationTemplate())."',
  1142. '".Database::escape_string($results_disabled)."',
  1143. '".Database::escape_string($this->getModelType())."'
  1144. )";
  1145. Database::query($sql);
  1146. $this->id = Database::insert_id();
  1147. $this->addExerciseToOrderTable();
  1148. // insert into the item_property table
  1149. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizAdded', api_get_user_id());
  1150. api_set_default_visibility($this->course, $this->id, TOOL_QUIZ);
  1151. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1152. $this->search_engine_save();
  1153. }
  1154. }
  1155. $this->save_categories_in_exercise($this->categories);
  1156. // Updates the question position.
  1157. $this->update_question_positions();
  1158. }
  1159. /**
  1160. * Updates question position
  1161. */
  1162. public function update_question_positions()
  1163. {
  1164. $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1165. //Fixes #3483 when updating order
  1166. $question_list = $this->selectQuestionList(true);
  1167. if (!empty($question_list) && !empty($this->course_id) && !empty($this->id)) {
  1168. foreach ($question_list as $position => $questionId) {
  1169. $sql = "UPDATE $quiz_question_table SET question_order ='".intval($position)."'".
  1170. "WHERE c_id = ".$this->course_id." AND question_id = ".intval($questionId)." AND exercice_id = ".$this->id;
  1171. Database::query($sql);
  1172. }
  1173. }
  1174. }
  1175. /**
  1176. * Adds a question into the question list
  1177. *
  1178. * @author Olivier Brouckaert
  1179. * @param integer $questionId - question ID
  1180. * @return boolean - true if the question has been added, otherwise false
  1181. */
  1182. public function addToList($questionId)
  1183. {
  1184. // checks if the question ID is not in the list
  1185. if (!$this->isInList($questionId)) {
  1186. // selects the max position
  1187. if (!$this->selectNbrQuestions()) {
  1188. $pos = 1;
  1189. } else {
  1190. if (is_array($this->questionList)) {
  1191. $pos = max(array_keys($this->questionList)) + 1;
  1192. }
  1193. }
  1194. $this->questionList[$pos] = $questionId;
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. /**
  1200. * removes a question from the question list
  1201. *
  1202. * @author - Olivier Brouckaert
  1203. * @param integer $questionId - question ID
  1204. * @return boolean - true if the question has been removed, otherwise false
  1205. */
  1206. public function removeFromList($questionId)
  1207. {
  1208. // searches the position of the question ID in the list
  1209. $pos = array_search($questionId, $this->questionList);
  1210. // question not found
  1211. if ($pos === false) {
  1212. return false;
  1213. } else {
  1214. // dont reduce the number of random question if we use random by category option, or if
  1215. // random all questions
  1216. if ($this->isRandom() && $this->isRandomByCat() == EXERCISE_CATEGORY_RANDOM_DISABLED) {
  1217. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1218. $this->random -= 1;
  1219. $this->save();
  1220. }
  1221. }
  1222. // deletes the position from the array containing the wanted question ID
  1223. unset($this->questionList[$pos]);
  1224. return true;
  1225. }
  1226. }
  1227. /**
  1228. * deletes the exercise from the database
  1229. * Notice : leaves the question in the data base
  1230. *
  1231. * @author - Olivier Brouckaert
  1232. */
  1233. public function delete()
  1234. {
  1235. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1236. $sql = "UPDATE $TBL_EXERCICES
  1237. SET active='-1' WHERE c_id = ".$this->course_id." AND iid='".Database::escape_string($this->id)."'";
  1238. Database::query($sql);
  1239. api_item_property_update($this->course, TOOL_QUIZ, $this->id, 'QuizDeleted', api_get_user_id());
  1240. $this->delete_exercise_order();
  1241. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1242. $this->search_engine_delete();
  1243. }
  1244. }
  1245. /**
  1246. * Creates the form to create / edit an exercise
  1247. * @param FormValidator $form the formvalidator instance (by reference)
  1248. * @param string
  1249. */
  1250. public function createForm($form, $type = 'full')
  1251. {
  1252. if (empty($type)) {
  1253. $type = 'full';
  1254. }
  1255. // form title
  1256. if (!empty($_GET['exerciseId'])) {
  1257. $form_title = get_lang('ModifyExercise');
  1258. } else {
  1259. $form_title = get_lang('NewEx');
  1260. }
  1261. $form->addElement('header', $form_title);
  1262. // title
  1263. $form->addElement(
  1264. 'text',
  1265. 'exerciseTitle',
  1266. get_lang('ExerciseName'),
  1267. array('class' => 'span6', 'id' => 'exercise_title')
  1268. );
  1269. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1270. if (is_array($type)) {
  1271. $editor_config = array_merge($editor_config, $type);
  1272. }
  1273. $form->add_html_editor('exerciseDescription', get_lang('ExerciseDescription'), false, false, $editor_config);
  1274. $form->addElement(
  1275. 'advanced_settings',
  1276. '<a href="javascript://" onclick=" return advanced_parameters()">
  1277. <span id="img_plus_and_minus">
  1278. <div style="vertical-align:top;" >
  1279. '.Display::return_icon('div_show.gif').' '.addslashes(get_lang('AdvancedParameters')).'</div>
  1280. </span>
  1281. </a>'
  1282. );
  1283. // Random questions
  1284. // style="" and not "display:none" to avoid #4029 Random and number of attempt menu empty
  1285. $form->addElement('html', '<div id="options" style="">');
  1286. $radio = array(
  1287. $form->createElement('radio', 'model_type', null, get_lang('Normal'), EXERCISE_MODEL_TYPE_NORMAL),
  1288. $form->createElement('radio', 'model_type', null, get_lang('Committee'), EXERCISE_MODEL_TYPE_COMMITTEE)
  1289. );
  1290. $form->addGroup($radio, null, get_lang('ModelType'), '');
  1291. if ($type == 'full') {
  1292. //Can't modify a DirectFeedback question
  1293. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1294. // feedback type
  1295. $radios_feedback = array();
  1296. $radios_feedback[] = $form->createElement(
  1297. 'radio',
  1298. 'exerciseFeedbackType',
  1299. null,
  1300. get_lang('ExerciseAtTheEndOfTheTest'),
  1301. '0',
  1302. array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')
  1303. );
  1304. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1305. //Can't convert a question from one feedback to another if there is more than 1 question already added
  1306. if ($this->selectNbrQuestions() == 0) {
  1307. $radios_feedback[] = $form->createElement(
  1308. 'radio',
  1309. 'exerciseFeedbackType',
  1310. null,
  1311. get_lang('DirectFeedback'),
  1312. '1',
  1313. array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')
  1314. );
  1315. }
  1316. }
  1317. $radios_feedback[] = $form->createElement(
  1318. 'radio',
  1319. 'exerciseFeedbackType',
  1320. null,
  1321. get_lang('NoFeedback'),
  1322. '2',
  1323. array('id' => 'exerciseType_2')
  1324. );
  1325. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'), '');
  1326. // question
  1327. $radios = array(
  1328. $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), ALL_ON_ONE_PAGE, array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')),
  1329. $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), ONE_PER_PAGE, array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')),
  1330. );
  1331. $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  1332. $radios_results_disabled = array();
  1333. $radios_results_disabled[] = $form->createElement(
  1334. 'radio',
  1335. 'results_disabled',
  1336. null,
  1337. get_lang('ShowScoreAndRightAnswer'),
  1338. '0',
  1339. array('id' => 'result_disabled_0')
  1340. );
  1341. $radios_results_disabled[] = $form->createElement(
  1342. 'radio',
  1343. 'results_disabled',
  1344. null,
  1345. get_lang('DoNotShowScoreNorRightAnswer'),
  1346. '1',
  1347. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1348. );
  1349. $radios_results_disabled[] = $form->createElement(
  1350. 'radio',
  1351. 'results_disabled',
  1352. null,
  1353. get_lang('OnlyShowScore'),
  1354. '2',
  1355. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1356. );
  1357. //$radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ExamModeWithFinalScoreShowOnlyFinalScoreWithCategoriesIfAvailable'), '3', array('id'=>'result_disabled_3','onclick' => 'check_results_disabled()'));
  1358. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  1359. } else {
  1360. // if is Directfeedback but has not questions we can allow to modify the question type
  1361. if ($this->selectNbrQuestions() == 0) {
  1362. // feedback type
  1363. $radios_feedback = array();
  1364. $radios_feedback[] = $form->createElement(
  1365. 'radio',
  1366. 'exerciseFeedbackType',
  1367. null,
  1368. get_lang('ExerciseAtTheEndOfTheTest'),
  1369. '0',
  1370. array('id' => 'exerciseType_0', 'onclick' => 'check_feedback()')
  1371. );
  1372. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1373. $radios_feedback[] = $form->createElement(
  1374. 'radio',
  1375. 'exerciseFeedbackType',
  1376. null,
  1377. get_lang('DirectFeedback'),
  1378. '1',
  1379. array('id' => 'exerciseType_1', 'onclick' => 'check_direct_feedback()')
  1380. );
  1381. }
  1382. $radios_feedback[] = $form->createElement(
  1383. 'radio',
  1384. 'exerciseFeedbackType',
  1385. null,
  1386. get_lang('NoFeedback'),
  1387. '2',
  1388. array('id' => 'exerciseType_2')
  1389. );
  1390. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
  1391. // Exercise type
  1392. $radios = array(
  1393. $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1'),
  1394. $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2'),
  1395. $form->createElement('radio', 'exerciseType', null, get_lang('Committee'), '3')
  1396. );
  1397. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1398. $radios_results_disabled = array();
  1399. $radios_results_disabled[] = $form->createElement(
  1400. 'radio',
  1401. 'results_disabled',
  1402. null,
  1403. get_lang('ShowScoreAndRightAnswer'),
  1404. '0',
  1405. array('id' => 'result_disabled_0')
  1406. );
  1407. $radios_results_disabled[] = $form->createElement(
  1408. 'radio',
  1409. 'results_disabled',
  1410. null,
  1411. get_lang('DoNotShowScoreNorRightAnswer'),
  1412. '1',
  1413. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1414. );
  1415. $radios_results_disabled[] = $form->createElement(
  1416. 'radio',
  1417. 'results_disabled',
  1418. null,
  1419. get_lang('OnlyShowScore'),
  1420. '2',
  1421. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1422. );
  1423. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  1424. } else {
  1425. //Show options freeze
  1426. $radios_results_disabled[] = $form->createElement(
  1427. 'radio',
  1428. 'results_disabled',
  1429. null,
  1430. get_lang('ShowScoreAndRightAnswer'),
  1431. '0',
  1432. array('id' => 'result_disabled_0')
  1433. );
  1434. $radios_results_disabled[] = $form->createElement(
  1435. 'radio',
  1436. 'results_disabled',
  1437. null,
  1438. get_lang('DoNotShowScoreNorRightAnswer'),
  1439. '1',
  1440. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1441. );
  1442. $radios_results_disabled[] = $form->createElement(
  1443. 'radio',
  1444. 'results_disabled',
  1445. null,
  1446. get_lang('OnlyShowScore'),
  1447. '2',
  1448. array('id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()')
  1449. );
  1450. $result_disable_group = $form->addGroup(
  1451. $radios_results_disabled,
  1452. null,
  1453. get_lang('ShowResultsToStudents'),
  1454. ''
  1455. );
  1456. $result_disable_group->freeze();
  1457. $radios[] = $form->createElement(
  1458. 'radio',
  1459. 'exerciseType',
  1460. null,
  1461. get_lang('SimpleExercise'),
  1462. '1',
  1463. array('onclick' => 'check_per_page_all()', 'id' => 'option_page_all')
  1464. );
  1465. $radios[] = $form->createElement(
  1466. 'radio',
  1467. 'exerciseType',
  1468. null,
  1469. get_lang('SequentialExercise'),
  1470. '2',
  1471. array('onclick' => 'check_per_page_one()', 'id' => 'option_page_one')
  1472. );
  1473. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'), '');
  1474. $type_group->freeze();
  1475. //we force the options to the DirectFeedback exercisetype
  1476. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  1477. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1478. }
  1479. }
  1480. // Number of random question.
  1481. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10;
  1482. $option = range(0, $max);
  1483. $option[0] = get_lang('No');
  1484. $option[-1] = get_lang('AllQuestionsShort');
  1485. $form->addElement(
  1486. 'select',
  1487. 'randomQuestions',
  1488. array(get_lang('RandomQuestions'), get_lang('RandomQuestionsHelp')),
  1489. $option,
  1490. array('id' => 'randomQuestions', 'class' => 'chzn-select')
  1491. );
  1492. // Random answers.
  1493. $radios_random_answers = array(
  1494. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  1495. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0')
  1496. );
  1497. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'), '');
  1498. // Random by category.
  1499. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1500. $radiocat = array(
  1501. $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesShuffled'), '1'),
  1502. $form->createElement('radio', 'randomByCat', null, get_lang('YesWithCategoriesSorted'), '2'),
  1503. $form->createElement('radio', 'randomByCat', null, get_lang('No'), '0')
  1504. );
  1505. $form->addGroup($radiocat, null, get_lang('RandomQuestionByCategory'), '');
  1506. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1507. // Category name.
  1508. $radio_display_cat_name = array(
  1509. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1' ),
  1510. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0' )
  1511. );
  1512. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'), '');
  1513. // Attempts.
  1514. $attempt_option = range(0, 10);
  1515. $attempt_option[0] = get_lang('Infinite');
  1516. $form->addElement(
  1517. 'select',
  1518. 'exerciseAttempts',
  1519. get_lang('ExerciseAttempts'),
  1520. $attempt_option,
  1521. array('id' => 'exerciseAttempts', 'class' => 'chzn-select')
  1522. );
  1523. // Exercise time limit.
  1524. $form->addElement(
  1525. 'checkbox',
  1526. 'activate_start_date_check',
  1527. null,
  1528. get_lang('EnableStartTime'),
  1529. array('onclick' => 'activate_start_date()')
  1530. );
  1531. // Start time.
  1532. if (($this->start_time != '0000-00-00 00:00:00')) {
  1533. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  1534. } else {
  1535. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  1536. }
  1537. $form->addElement('datepicker', 'start_time', '', array('form_name' => 'exercise_admin'), 5);
  1538. $form->addElement('html', '</div>');
  1539. // End time.
  1540. $form->addElement(
  1541. 'checkbox',
  1542. 'activate_end_date_check',
  1543. null,
  1544. get_lang('EnableEndTime'),
  1545. array('onclick' => 'activate_end_date()')
  1546. );
  1547. if (($this->end_time != '0000-00-00 00:00:00')) {
  1548. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  1549. } else {
  1550. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  1551. }
  1552. $form->addElement('datepicker', 'end_time', '', array('form_name' => 'exercise_admin'), 5);
  1553. $form->addElement('html', '</div>');
  1554. // Propagate negative values.
  1555. $display = 'block';
  1556. $form->addElement('checkbox', 'propagate_neg', null, get_lang('PropagateNegativeResults'));
  1557. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1558. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  1559. $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
  1560. // Exercise timer.
  1561. $form->addElement(
  1562. 'checkbox',
  1563. 'enabletimercontrol',
  1564. null,
  1565. get_lang('EnableTimerControl'),
  1566. array(
  1567. 'onclick' => 'option_time_expired()',
  1568. 'id' => 'enabletimercontrol',
  1569. 'onload' => 'check_load_time()'
  1570. )
  1571. );
  1572. $expired_date = (int)$this->selectExpiredTime();
  1573. if (($expired_date != '0')) {
  1574. $form->addElement('html', '<div id="timercontrol" style="display:block;">');
  1575. } else {
  1576. $form->addElement('html', '<div id="timercontrol" style="display:none;">');
  1577. }
  1578. $form->addElement(
  1579. 'text',
  1580. 'enabletimercontroltotalminutes',
  1581. get_lang('ExerciseTotalDurationInMinutes'),
  1582. array('style' => 'width : 35px', 'id' => 'enabletimercontroltotalminutes')
  1583. );
  1584. $form->addElement('html', '</div>');
  1585. // Pass percentage.
  1586. $form->addElement(
  1587. 'text',
  1588. 'pass_percentage',
  1589. array(get_lang('PassPercentage'), null, '%'),
  1590. array('id' => 'pass_percentage')
  1591. );
  1592. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  1593. // Text when ending an exam
  1594. $form->add_html_editor('text_when_finished', get_lang('TextWhenFinished'), false, false, $editor_config);
  1595. // Exam end button.
  1596. $group = array(
  1597. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonCourseHome'), '0'),
  1598. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonExerciseHome'), '1'),
  1599. $form->createElement('radio', 'end_button', null, get_lang('ExerciseEndButtonDisconnect'), '2')
  1600. );
  1601. $form->addGroup($group, null, get_lang('ExerciseEndButton'));
  1602. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  1603. $defaults = array();
  1604. if (api_get_setting('search_enabled') === 'true') {
  1605. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1606. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  1607. $form->addElement('select_language', 'language', get_lang('SearchFeatureDocumentLanguage'));
  1608. $specific_fields = get_specific_field_list();
  1609. foreach ($specific_fields as $specific_field) {
  1610. $form->addElement('text', $specific_field['code'], $specific_field['name']);
  1611. $filter = array(
  1612. 'c_id' => "'".api_get_course_int_id()."'",
  1613. 'field_id' => $specific_field['id'],
  1614. 'ref_id' => $this->id,
  1615. 'tool_id' => '\''.TOOL_QUIZ.'\''
  1616. );
  1617. $values = get_specific_field_values_list($filter, array('value'));
  1618. if (!empty($values)) {
  1619. $arr_str_values = array();
  1620. foreach ($values as $value) {
  1621. $arr_str_values[] = $value['value'];
  1622. }
  1623. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  1624. }
  1625. }
  1626. }
  1627. if ($this->emailAlert) {
  1628. // Text when ending an exam
  1629. $form->add_html_editor(
  1630. 'email_notification_template',
  1631. array(get_lang('EmailNotificationTemplate'), get_lang('EmailNotificationTemplateDescription')),
  1632. null,
  1633. false,
  1634. $editor_config
  1635. );
  1636. }
  1637. // End advanced setting.
  1638. $form->addElement('html', '</div>');
  1639. $form->addElement('html', '</div>');
  1640. }
  1641. // Category selection.
  1642. $cat = new Testcategory();
  1643. $cat_form = $cat->return_category_form($this);
  1644. $form->addElement('html', $cat_form);
  1645. // submit
  1646. $text = isset($_GET['exerciseId']) ? get_lang('ModifyExercise') : get_lang('ProcedToQuestions');
  1647. $form->addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  1648. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  1649. if ($type == 'full') {
  1650. // rules
  1651. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  1652. $form->addRule('start_time', get_lang('InvalidDate'), 'date');
  1653. $form->addRule('end_time', get_lang('InvalidDate'), 'date');
  1654. }
  1655. // defaults
  1656. if ($type == 'full') {
  1657. if ($this->id > 0) {
  1658. if ($this->random > $this->selectNbrQuestions()) {
  1659. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  1660. } else {
  1661. $defaults['randomQuestions'] = $this->random;
  1662. }
  1663. $defaults['randomAnswers'] = $this->selectRandomAnswers();
  1664. $defaults['exerciseType'] = $this->selectType();
  1665. $defaults['exerciseTitle'] = $this->selectTitle();
  1666. $defaults['exerciseDescription'] = $this->selectDescription();
  1667. $defaults['exerciseAttempts'] = $this->selectAttempts();
  1668. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  1669. $defaults['results_disabled'] = $this->selectResultsDisabled();
  1670. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  1671. $defaults['review_answers'] = $this->review_answers;
  1672. $defaults['randomByCat'] = $this->selectRandomByCat();
  1673. $defaults['text_when_finished'] = $this->selectTextWhenFinished();
  1674. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  1675. $defaults['pass_percentage'] = $this->selectPassPercentage();
  1676. $defaults['end_button'] = $this->selectEndButton();
  1677. $defaults['email_notification_template'] = $this->selectEmailNotificationTemplate();
  1678. $defaults['model_type'] = $this->getModelType();
  1679. if (($this->start_time != '0000-00-00 00:00:00')) {
  1680. $defaults['activate_start_date_check'] = 1;
  1681. }
  1682. if ($this->end_time != '0000-00-00 00:00:00') {
  1683. $defaults['activate_end_date_check'] = 1;
  1684. }
  1685. $defaults['start_time'] = ($this->start_time != '0000-00-00 00:00:00') ? api_get_local_time(
  1686. $this->start_time
  1687. ) : date('Y-m-d 12:00:00');
  1688. $defaults['end_time'] = ($this->end_time != '0000-00-00 00:00:00') ? api_get_local_time(
  1689. $this->end_time
  1690. ) : date('Y-m-d 12:00:00', time() + 84600);
  1691. //Get expired time
  1692. if ($this->expired_time != '0') {
  1693. $defaults['enabletimercontrol'] = 1;
  1694. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  1695. } else {
  1696. $defaults['enabletimercontroltotalminutes'] = 0;
  1697. }
  1698. } else {
  1699. $defaults['model_type'] = 1;
  1700. $defaults['exerciseType'] = 2;
  1701. $defaults['exerciseAttempts'] = 0;
  1702. $defaults['randomQuestions'] = 0;
  1703. $defaults['randomAnswers'] = 0;
  1704. $defaults['exerciseDescription'] = '';
  1705. $defaults['exerciseFeedbackType'] = 0;
  1706. $defaults['results_disabled'] = 0;
  1707. $defaults['randomByCat'] = 0; //
  1708. $defaults['text_when_finished'] = ""; //
  1709. $defaults['start_time'] = date('Y-m-d 12:00:00');
  1710. $defaults['display_category_name'] = 1; //
  1711. $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
  1712. $defaults['pass_percentage'] = '';
  1713. $defaults['end_button'] = $this->selectEndButton();
  1714. }
  1715. } else {
  1716. $defaults['exerciseTitle'] = $this->selectTitle();
  1717. $defaults['exerciseDescription'] = $this->selectDescription();
  1718. }
  1719. if (api_get_setting('search_enabled') === 'true') {
  1720. $defaults['index_document'] = 'checked="checked"';
  1721. }
  1722. $form->setDefaults($defaults);
  1723. }
  1724. /**
  1725. * function which process the creation of exercises
  1726. * @param FormValidator $form the formvalidator instance
  1727. */
  1728. function processCreation($form, $type = '')
  1729. {
  1730. $this->updateTitle($form->getSubmitValue('exerciseTitle'));
  1731. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  1732. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  1733. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  1734. $this->updateType($form->getSubmitValue('exerciseType'));
  1735. $this->setRandom($form->getSubmitValue('randomQuestions'));
  1736. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  1737. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  1738. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  1739. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  1740. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  1741. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  1742. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  1743. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  1744. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  1745. $this->updateCategories($form->getSubmitValue('category'));
  1746. $this->updateEndButton($form->getSubmitValue('end_button'));
  1747. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  1748. $this->setModelType($form->getSubmitValue('model_type'));
  1749. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  1750. $start_time = $form->getSubmitValue('start_time');
  1751. $start_time['F'] = sprintf('%02d', $start_time['F']);
  1752. $start_time['i'] = sprintf('%02d', $start_time['i']);
  1753. $start_time['d'] = sprintf('%02d', $start_time['d']);
  1754. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1755. } else {
  1756. $this->start_time = '0000-00-00 00:00:00';
  1757. }
  1758. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  1759. $end_time = $form->getSubmitValue('end_time');
  1760. $end_time['F'] = sprintf('%02d', $end_time['F']);
  1761. $end_time['i'] = sprintf('%02d', $end_time['i']);
  1762. $end_time['d'] = sprintf('%02d', $end_time['d']);
  1763. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1764. } else {
  1765. $this->end_time = '0000-00-00 00:00:00';
  1766. }
  1767. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  1768. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  1769. if ($this->expired_time == 0) {
  1770. $this->expired_time = $expired_total_time;
  1771. }
  1772. } else {
  1773. $this->expired_time = 0;
  1774. }
  1775. if ($form->getSubmitValue('randomAnswers') == 1) {
  1776. $this->random_answers = 1;
  1777. } else {
  1778. $this->random_answers = 0;
  1779. }
  1780. $this->save($type);
  1781. }
  1782. public function search_engine_save()
  1783. {
  1784. if ($_POST['index_document'] != 1) {
  1785. return;
  1786. }
  1787. $course_id = api_get_course_id();
  1788. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  1789. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  1790. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1791. $specific_fields = get_specific_field_list();
  1792. $ic_slide = new IndexableChunk();
  1793. $all_specific_terms = '';
  1794. foreach ($specific_fields as $specific_field) {
  1795. if (isset($_REQUEST[$specific_field['code']])) {
  1796. $sterms = trim($_REQUEST[$specific_field['code']]);
  1797. if (!empty($sterms)) {
  1798. $all_specific_terms .= ' '.$sterms;
  1799. $sterms = explode(',', $sterms);
  1800. foreach ($sterms as $sterm) {
  1801. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1802. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1803. }
  1804. }
  1805. }
  1806. }
  1807. // build the chunk to index
  1808. $ic_slide->addValue("title", $this->exercise);
  1809. $ic_slide->addCourseId($course_id);
  1810. $ic_slide->addToolId(TOOL_QUIZ);
  1811. $xapian_data = array(
  1812. SE_COURSE_ID => $course_id,
  1813. SE_TOOL_ID => TOOL_QUIZ,
  1814. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1815. SE_USER => (int)api_get_user_id(),
  1816. );
  1817. $ic_slide->xapian_data = serialize($xapian_data);
  1818. $exercise_description = $all_specific_terms.' '.$this->description;
  1819. $ic_slide->addValue("content", $exercise_description);
  1820. $di = new ChamiloIndexer();
  1821. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  1822. $di->connectDb(null, null, $lang);
  1823. $di->addChunk($ic_slide);
  1824. //index and return search engine document id
  1825. $did = $di->index();
  1826. if ($did) {
  1827. // save it to db
  1828. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1829. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1830. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1831. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1832. Database::query($sql);
  1833. }
  1834. }
  1835. function search_engine_edit()
  1836. {
  1837. // update search enchine and its values table if enabled
  1838. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1839. $course_id = api_get_course_id();
  1840. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1841. // get search_did
  1842. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1843. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1844. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1845. $res = Database::query($sql);
  1846. if (Database::num_rows($res) > 0) {
  1847. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  1848. require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
  1849. require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
  1850. $se_ref = Database::fetch_array($res);
  1851. $specific_fields = get_specific_field_list();
  1852. $ic_slide = new IndexableChunk();
  1853. $all_specific_terms = '';
  1854. foreach ($specific_fields as $specific_field) {
  1855. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  1856. if (isset($_REQUEST[$specific_field['code']])) {
  1857. $sterms = trim($_REQUEST[$specific_field['code']]);
  1858. $all_specific_terms .= ' '.$sterms;
  1859. $sterms = explode(',', $sterms);
  1860. foreach ($sterms as $sterm) {
  1861. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1862. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1863. }
  1864. }
  1865. }
  1866. // build the chunk to index
  1867. $ic_slide->addValue("title", $this->exercise);
  1868. $ic_slide->addCourseId($course_id);
  1869. $ic_slide->addToolId(TOOL_QUIZ);
  1870. $xapian_data = array(
  1871. SE_COURSE_ID => $course_id,
  1872. SE_TOOL_ID => TOOL_QUIZ,
  1873. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1874. SE_USER => (int)api_get_user_id(),
  1875. );
  1876. $ic_slide->xapian_data = serialize($xapian_data);
  1877. $exercise_description = $all_specific_terms.' '.$this->description;
  1878. $ic_slide->addValue("content", $exercise_description);
  1879. $di = new ChamiloIndexer();
  1880. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  1881. $di->connectDb(null, null, $lang);
  1882. $di->remove_document((int)$se_ref['search_did']);
  1883. $di->addChunk($ic_slide);
  1884. //index and return search engine document id
  1885. $did = $di->index();
  1886. if ($did) {
  1887. // save it to db
  1888. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  1889. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1890. Database::query($sql);
  1891. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1892. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1893. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1894. Database::query($sql);
  1895. }
  1896. } else {
  1897. $this->search_engine_save();
  1898. }
  1899. }
  1900. }
  1901. public function search_engine_delete()
  1902. {
  1903. // remove from search engine if enabled
  1904. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1905. $course_id = api_get_course_id();
  1906. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1907. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1908. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1909. $res = Database::query($sql);
  1910. if (Database::num_rows($res) > 0) {
  1911. $row = Database::fetch_array($res);
  1912. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  1913. $di = new ChamiloIndexer();
  1914. $di->remove_document((int)$row['search_did']);
  1915. unset($di);
  1916. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1917. foreach ($this->questionList as $question_i) {
  1918. $sql = 'SELECT type FROM %s WHERE id=%s';
  1919. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1920. $qres = Database::query($sql);
  1921. if (Database::num_rows($qres) > 0) {
  1922. $qrow = Database::fetch_array($qres);
  1923. $objQuestion = Question::getInstance($qrow['type']);
  1924. $objQuestion = Question::read((int)$question_i);
  1925. $objQuestion->search_engine_edit($this->id, false, true);
  1926. unset($objQuestion);
  1927. }
  1928. }
  1929. }
  1930. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1931. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1932. Database::query($sql);
  1933. // remove terms from db
  1934. require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
  1935. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1936. }
  1937. }
  1938. public function selectExpiredTime()
  1939. {
  1940. return $this->expired_time;
  1941. }
  1942. /**
  1943. * Cleans the student's results only for the Exercise tool (Not from the LP)
  1944. * The LP results are NOT deleted
  1945. * Works with exercises in sessions
  1946. * @return int quantity of user's exercises deleted
  1947. */
  1948. public function clean_results()
  1949. {
  1950. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1951. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1952. $sql = "SELECT exe_id FROM $table_track_e_exercises
  1953. WHERE c_id = '".api_get_course_int_id()."' AND
  1954. exe_exo_id = ".$this->id." AND
  1955. orig_lp_id = 0 AND
  1956. orig_lp_item_id = 0 AND
  1957. session_id = ".api_get_session_id()."";
  1958. $result = Database::query($sql);
  1959. $exe_list = Database::store_result($result);
  1960. //deleting TRACK_E_ATTEMPT table
  1961. $i = 0;
  1962. if (is_array($exe_list) && count($exe_list) > 0) {
  1963. foreach ($exe_list as $item) {
  1964. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  1965. Database::query($sql);
  1966. $i++;
  1967. }
  1968. }
  1969. //delete TRACK_E_EXERCICES table
  1970. $sql = "DELETE FROM $table_track_e_exercises
  1971. WHERE c_id = '".api_get_course_int_id()."' AND
  1972. exe_exo_id = ".$this->id." AND
  1973. orig_lp_id = 0 AND
  1974. orig_lp_item_id = 0 AND
  1975. session_id = ".api_get_session_id();
  1976. Database::query($sql);
  1977. return $i;
  1978. }
  1979. /**
  1980. * Gets the latest exercise order
  1981. * @return int
  1982. */
  1983. public function getLastExerciseOrder()
  1984. {
  1985. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  1986. $course_id = intval($this->course_id);
  1987. $sql = "SELECT exercise_order FROM $table WHERE c_id = $course_id ORDER BY exercise_order DESC LIMIT 1";
  1988. $result = Database::query($sql);
  1989. if (Database::num_rows($result)) {
  1990. $row = Database::fetch_array($result);
  1991. return $row['exercise_order'];
  1992. }
  1993. return 0;
  1994. }
  1995. /**
  1996. * Get exercise order
  1997. * @return mixed
  1998. */
  1999. public function getExerciseOrder()
  2000. {
  2001. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2002. $courseId = $this->course_id;
  2003. $sessionId = api_get_session_id();
  2004. $sql = "SELECT exercise_order FROM $table
  2005. WHERE exercise_id = {$this->id} AND c_id = $courseId AND session_id = $sessionId ";
  2006. $result = Database::query($sql);
  2007. if (Database::num_rows($result)) {
  2008. $row = Database::fetch_array($result);
  2009. return $row['exercise_order'];
  2010. }
  2011. return false;
  2012. }
  2013. /**
  2014. * Add the exercise to the exercise order table
  2015. */
  2016. public function addExerciseToOrderTable()
  2017. {
  2018. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2019. $last_order = $this->getLastExerciseOrder();
  2020. $course_id = $this->course_id;
  2021. if ($last_order == 0) {
  2022. Database::insert(
  2023. $table,
  2024. array(
  2025. 'exercise_id' => $this->id,
  2026. 'exercise_order' => 1,
  2027. 'c_id' => $course_id,
  2028. 'session_id' => api_get_session_id(),
  2029. )
  2030. );
  2031. } else {
  2032. $current_exercise_order = $this->getExerciseOrder();
  2033. if ($current_exercise_order == false) {
  2034. Database::insert(
  2035. $table,
  2036. array(
  2037. 'exercise_id' => $this->id,
  2038. 'exercise_order' => $last_order + 1,
  2039. 'c_id' => $course_id,
  2040. 'session_id' => api_get_session_id(),
  2041. )
  2042. );
  2043. }
  2044. }
  2045. }
  2046. public function update_exercise_list_order($new_exercise_list, $course_id, $session_id)
  2047. {
  2048. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2049. $counter = 1;
  2050. // Drop all
  2051. $session_id = intval($session_id);
  2052. $course_id = intval($course_id);
  2053. Database::query("DELETE FROM $table WHERE session_id = $session_id AND c_id = $course_id");
  2054. //Insert all
  2055. foreach ($new_exercise_list as $new_order_id) {
  2056. Database::insert(
  2057. $table,
  2058. array(
  2059. 'exercise_order' => $counter,
  2060. 'session_id' => $session_id,
  2061. 'exercise_id' => intval($new_order_id),
  2062. 'c_id' => $course_id
  2063. )
  2064. );
  2065. $counter++;
  2066. }
  2067. }
  2068. function delete_exercise_order()
  2069. {
  2070. $table = Database::get_course_table(TABLE_QUIZ_ORDER);
  2071. $session_id = api_get_session_id();
  2072. $course_id = $this->course_id;
  2073. Database::query(
  2074. "DELETE FROM $table WHERE exercise_id = {$this->id} AND session_id = $session_id AND c_id = $course_id"
  2075. );
  2076. }
  2077. function save_exercise_list_order($course_id, $session_id)
  2078. {
  2079. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  2080. $ordered_list = $this->get_exercise_list_ordered();
  2081. $ordered_count = count($ordered_list);
  2082. $session_id = intval($session_id);
  2083. $course_id = intval($course_id);
  2084. //Check if order exists and matchs the current status
  2085. $sql = "SELECT iid FROM $TBL_EXERCICES WHERE c_id = $course_id AND active = '1' AND session_id = $session_id ORDER BY title";
  2086. $result = Database::query($sql);
  2087. $unordered_count = Database::num_rows($result);
  2088. if ($unordered_count != $ordered_count) {
  2089. $exercise_list = array();
  2090. while ($row = Database::fetch_array($result)) {
  2091. $exercise_list[] = $row['iid'];
  2092. }
  2093. $this->update_exercise_list_order($exercise_list, $course_id, $session_id);
  2094. }
  2095. }
  2096. /**
  2097. * Copies an exercise (duplicate all questions and answers)
  2098. */
  2099. public function copy_exercise()
  2100. {
  2101. $original_exercise = $this;
  2102. $exercise_obj = new Exercise();
  2103. $exercise_obj->setCategoriesGrouping(false);
  2104. $exercise_obj->read($this->id);
  2105. // force the creation of a new exercise
  2106. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  2107. //Hides the new exercise
  2108. $exercise_obj->updateStatus(false);
  2109. $exercise_obj->updateId(0);
  2110. $exercise_obj->save();
  2111. $exercise_obj->save_exercise_list_order($this->course['real_id'], api_get_session_id());
  2112. $new_exercise_id = $exercise_obj->selectId();
  2113. if ($new_exercise_id) {
  2114. $original_exercise->copy_exercise_categories($exercise_obj);
  2115. $question_list = $exercise_obj->selectQuestionList();
  2116. if (!empty($question_list)) {
  2117. //Question creation
  2118. foreach ($question_list as $old_question_id) {
  2119. $old_question_obj = Question::read($old_question_id);
  2120. $new_id = $old_question_obj->duplicate();
  2121. if ($new_id) {
  2122. $new_question_obj = Question::read($new_id);
  2123. if (isset($new_question_obj) && $new_question_obj) {
  2124. $new_question_obj->addToList($new_exercise_id);
  2125. // This should be moved to the duplicate function
  2126. $new_answer_obj = new Answer($old_question_id);
  2127. //$new_answer_obj->read();
  2128. $new_answer_obj->duplicate($new_id);
  2129. }
  2130. }
  2131. }
  2132. }
  2133. }
  2134. }
  2135. /**
  2136. *
  2137. */
  2138. public function set_autolaunch()
  2139. {
  2140. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  2141. $session_id = api_get_session_id();
  2142. $course_id = $this->course_id;
  2143. $sql = "UPDATE $table SET autolaunch = 0 WHERE c_id = $course_id AND session_id = $session_id ";
  2144. Database::query($sql);
  2145. $sql = "UPDATE $table SET autolaunch = 1 WHERE iid = {$this->id} ";
  2146. Database::query($sql);
  2147. }
  2148. /**
  2149. * Copy exercise categories to a new exercise
  2150. * @params obj exercise object
  2151. */
  2152. function copy_exercise_categories($new_exercise_obj)
  2153. {
  2154. $categories = $this->get_categories_in_exercise();
  2155. if ($categories) {
  2156. $cat_list = array();
  2157. foreach($categories as $cat) {
  2158. $cat_list[$cat['category_id']] = $cat['count_questions'];
  2159. }
  2160. $new_exercise_obj->save_categories_in_exercise($cat_list);
  2161. }
  2162. }
  2163. /**
  2164. * Changes the exercise id
  2165. *
  2166. * @param - in $id - exercise id
  2167. */
  2168. private function updateId($id)
  2169. {
  2170. $this->id = $id;
  2171. }
  2172. /**
  2173. * Changes the exercise status
  2174. *
  2175. * @param string $status - exercise status
  2176. */
  2177. function updateStatus($status)
  2178. {
  2179. $this->active = $status;
  2180. }
  2181. /**
  2182. * @param int $lp_id
  2183. * @param int $lp_item_id
  2184. * @param int $lp_item_view_id
  2185. * @param string $status
  2186. * @return array
  2187. */
  2188. public function getStatTrackExerciseInfo(
  2189. $lp_id = 0,
  2190. $lp_item_id = 0,
  2191. $lp_item_view_id = 0,
  2192. $status = 'incomplete'
  2193. ) {
  2194. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2195. if (empty($lp_id)) {
  2196. $lp_id = 0;
  2197. }
  2198. if (empty($lp_item_id)) {
  2199. $lp_item_id = 0;
  2200. }
  2201. if (empty($lp_item_view_id)) {
  2202. $lp_item_view_id = 0;
  2203. }
  2204. $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
  2205. exe_user_id = '."'".api_get_user_id()."'".' AND
  2206. c_id = '."'".api_get_course_int_id()."'".' AND
  2207. status = '."'".Database::escape_string($status)."'".' AND
  2208. orig_lp_id = '."'".$lp_id."'".' AND
  2209. orig_lp_item_id = '."'".$lp_item_id."'".' AND
  2210. orig_lp_item_view_id = '."'".$lp_item_view_id."'".' AND
  2211. session_id = '."'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
  2212. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2213. $result = Database::query($sql_track);
  2214. $new_array = array();
  2215. if (Database::num_rows($result) > 0) {
  2216. $new_array = Database::fetch_array($result, 'ASSOC');
  2217. }
  2218. return $new_array;
  2219. }
  2220. /**
  2221. * Saves a test attempt
  2222. *
  2223. * @param int clock_expired_time
  2224. * @param int lp id
  2225. * @param int lp item id
  2226. * @param int lp item_view id
  2227. * @param array question list
  2228. */
  2229. public function save_stat_track_exercise_info(
  2230. $clock_expired_time = 0,
  2231. $safe_lp_id = 0,
  2232. $safe_lp_item_id = 0,
  2233. $safe_lp_item_view_id = 0,
  2234. $questionList = array(),
  2235. $weight = 0
  2236. ) {
  2237. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2238. $safe_lp_id = intval($safe_lp_id);
  2239. $safe_lp_item_id = intval($safe_lp_item_id);
  2240. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  2241. if (empty($safe_lp_id)) {
  2242. $safe_lp_id = 0;
  2243. }
  2244. if (empty($safe_lp_item_id)) {
  2245. $safe_lp_item_id = 0;
  2246. }
  2247. if (empty($clock_expired_time)) {
  2248. $clock_expired_time = 0;
  2249. }
  2250. if ($this->expired_time != 0) {
  2251. $sql_fields = "expired_time_control, ";
  2252. $sql_fields_values = "'"."$clock_expired_time"."',";
  2253. } else {
  2254. $sql_fields = "";
  2255. $sql_fields_values = "";
  2256. }
  2257. $questionList = array_map('intval', $questionList);
  2258. $weight = Database::escape_string($weight);
  2259. $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, c_id, status, session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, exe_weighting)
  2260. VALUES($sql_fields_values '".$this->id."','".api_get_user_id()."','".api_get_course_int_id()."', 'incomplete','".api_get_session_id()."','".implode(',', $questionList)."', '".api_get_utc_datetime(
  2261. )."', '$safe_lp_id', '$safe_lp_item_id', '$weight')";
  2262. Database::query($sql);
  2263. $id = Database::insert_id();
  2264. return $id;
  2265. }
  2266. /**
  2267. * @param int $question_id
  2268. * @param int $questionNum
  2269. * @param array $questions_in_media
  2270. * @param array $remindList
  2271. * @return string
  2272. */
  2273. public function show_button($question_id, $questionNum, $questions_in_media = array(), $remindList = array())
  2274. {
  2275. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2276. $nbrQuestions = $this->getCountCompressedQuestionList();
  2277. $all_button = $html = $label = '';
  2278. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
  2279. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  2280. $html .= '<a href="exercise_submit_modal.php?learnpath_id='.$safe_lp_id.'&learnpath_item_id='.$safe_lp_item_id.'&learnpath_item_view_id='.$safe_lp_item_view_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&num='.$questionNum.'&exerciseType='.$this->type.'&exerciseId='.$this->id.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox btn">';
  2281. if ($questionNum == count($this->questionList)) {
  2282. $html .= get_lang('EndTest').'</a>';
  2283. } else {
  2284. $html .= get_lang('ContinueTest').'</a>';
  2285. }
  2286. $html .= '<br />';
  2287. } else {
  2288. // User
  2289. if (api_is_allowed_to_session_edit()) {
  2290. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  2291. if ($this->review_answers) {
  2292. $label = get_lang('ReviewQuestions');
  2293. $class = 'btn btn-success';
  2294. } else {
  2295. $label = get_lang('EndTest');
  2296. $class = 'btn btn-warning';
  2297. }
  2298. } else {
  2299. $label = get_lang('NextQuestion');
  2300. $class = 'btn btn-primary';
  2301. }
  2302. if ($this->type == ONE_PER_PAGE) {
  2303. if ($questionNum != 1) {
  2304. $prev_question = $questionNum - 2;
  2305. $all_button .= '<a href="javascript://" class="btn" onclick="previous_question_and_save('.$prev_question.', '.$question_id.' ); ">'.get_lang('PreviousQuestion').'</a>';
  2306. }
  2307. //Next question
  2308. if (isset($questions_in_media) && !empty($questions_in_media) && is_array($questions_in_media)) {
  2309. $questions_in_media = "['".implode("','", $questions_in_media)."']";
  2310. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_question_list('.$questions_in_media.'); ">'.$label.'</a>';
  2311. } else {
  2312. $all_button .= '&nbsp;<a href="javascript://" class="'.$class.'" onclick="save_now('.$question_id.'); ">'.$label.'</a>';
  2313. }
  2314. $all_button .= '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2315. $html .= $all_button;
  2316. } else {
  2317. if ($this->review_answers) {
  2318. $all_label = get_lang('ReviewQuestions');
  2319. $class = 'btn btn-success';
  2320. } else {
  2321. $all_label = get_lang('EndTest');
  2322. $class = 'btn btn-warning';
  2323. }
  2324. $all_button = '&nbsp;<a href="javascript://" class="'.$class.'" onclick="validate_all(); ">'.$all_label.'</a>';
  2325. $all_button .= '&nbsp;<span id="save_all_reponse"></span>';
  2326. $html .= $all_button;
  2327. }
  2328. }
  2329. }
  2330. return $html;
  2331. }
  2332. /**
  2333. * So the time control will work
  2334. */
  2335. public function show_time_control_js($time_left)
  2336. {
  2337. $time_left = intval($time_left);
  2338. return "<script>
  2339. function get_expired_date_string(expired_time) {
  2340. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  2341. var day, month, year, hours, minutes, seconds, date_string;
  2342. var obj_date = new Date(expired_time);
  2343. day = obj_date.getDate();
  2344. if (day < 10) day = '0' + day;
  2345. month = obj_date.getMonth();
  2346. year = obj_date.getFullYear();
  2347. hours = obj_date.getHours();
  2348. if (hours < 10) hours = '0' + hours;
  2349. minutes = obj_date.getMinutes();
  2350. if (minutes < 10) minutes = '0' + minutes;
  2351. seconds = obj_date.getSeconds();
  2352. if (seconds < 10) seconds = '0' + seconds;
  2353. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  2354. return date_string;
  2355. }
  2356. function open_clock_warning() {
  2357. $('#clock_warning').dialog({
  2358. modal:true,
  2359. height:250,
  2360. closeOnEscape: false,
  2361. resizable: false,
  2362. buttons: {
  2363. '".addslashes(get_lang("EndTest"))."': function() {
  2364. $('#clock_warning').dialog('close');
  2365. },
  2366. },
  2367. close: function() {
  2368. send_form();
  2369. }
  2370. });
  2371. $('#clock_warning').dialog('open');
  2372. $('#counter_to_redirect').epiclock({
  2373. mode: $.epiclock.modes.countdown,
  2374. offset: { seconds: 5 },
  2375. format: 's'
  2376. }).bind('timer', function () {
  2377. send_form();
  2378. });
  2379. }
  2380. function send_form() {
  2381. if ($('#exercise_form').length) {
  2382. $('#exercise_form').submit();
  2383. } else {
  2384. // In reminder
  2385. final_submit();
  2386. }
  2387. }
  2388. function onExpiredTimeExercise() {
  2389. $('#wrapper-clock').hide();
  2390. $('#exercise_form').hide();
  2391. $('#expired-message-id').show();
  2392. // Fixes bug #5263.
  2393. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  2394. open_clock_warning();
  2395. }
  2396. $(document).ready(function() {
  2397. var current_time = new Date().getTime();
  2398. // Time in seconds. When using minutes there are some seconds lost.
  2399. var time_left = parseInt(".$time_left.");
  2400. var expired_time = current_time + (time_left*1000);
  2401. var expired_date = get_expired_date_string(expired_time);
  2402. $('#exercise_clock_warning').epiclock({
  2403. mode: $.epiclock.modes.countdown,
  2404. offset: {seconds: time_left},
  2405. format: 'x:i:s',
  2406. renderer: 'minute'
  2407. }).bind('timer', function () {
  2408. onExpiredTimeExercise();
  2409. });
  2410. $('#submit_save').click(function () {});
  2411. });
  2412. </script>";
  2413. }
  2414. /**
  2415. * Lp javascript for hotspots
  2416. */
  2417. public function show_lp_javascript()
  2418. {
  2419. return "<script type=\"text/javascript\" src=\"../plugin/hotspot/JavaScriptFlashGateway.js\"></script>
  2420. <script src=\"../plugin/hotspot/hotspot.js\" type=\"text/javascript\"></script>
  2421. <script language=\"JavaScript\" type=\"text/javascript\">
  2422. <!--
  2423. // -----------------------------------------------------------------------------
  2424. // Globals
  2425. // Major version of Flash required
  2426. var requiredMajorVersion = 7;
  2427. // Minor version of Flash required
  2428. var requiredMinorVersion = 0;
  2429. // Minor version of Flash required
  2430. var requiredRevision = 0;
  2431. // the version of javascript supported
  2432. var jsVersion = 1.0;
  2433. // -----------------------------------------------------------------------------
  2434. // -->
  2435. </script>
  2436. <script language=\"VBScript\" type=\"text/vbscript\">
  2437. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  2438. Function VBGetSwfVer(i)
  2439. on error resume next
  2440. Dim swControl, swVersion
  2441. swVersion = 0
  2442. set swControl = CreateObject(\"ShockwaveFlash.ShockwaveFlash.\" + CStr(i))
  2443. if (IsObject(swControl)) then
  2444. swVersion = swControl.GetVariable(\"\$version\")
  2445. end if
  2446. VBGetSwfVer = swVersion
  2447. End Function
  2448. // -->
  2449. </script>
  2450. <script language=\"JavaScript1.1\" type=\"text/javascript\">
  2451. <!-- // Detect Client Browser type
  2452. var isIE = (navigator.appVersion.indexOf(\"MSIE\") != -1) ? true : false;
  2453. var isWin = (navigator.appVersion.toLowerCase().indexOf(\"win\") != -1) ? true : false;
  2454. var isOpera = (navigator.userAgent.indexOf(\"Opera\") != -1) ? true : false;
  2455. jsVersion = 1.1;
  2456. // JavaScript helper required to detect Flash Player PlugIn version information
  2457. function JSGetSwfVer(i){
  2458. // NS/Opera version >= 3 check for Flash plugin in plugin array
  2459. if (navigator.plugins != null && navigator.plugins.length > 0) {
  2460. if (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]) {
  2461. var swVer2 = navigator.plugins[\"Shockwave Flash 2.0\"] ? \" 2.0\" : \"\";
  2462. var flashDescription = navigator.plugins[\"Shockwave Flash\" + swVer2].description;
  2463. descArray = flashDescription.split(\" \");
  2464. tempArrayMajor = descArray[2].split(\".\");
  2465. versionMajor = tempArrayMajor[0];
  2466. versionMinor = tempArrayMajor[1];
  2467. if ( descArray[3] != \"\" ) {
  2468. tempArrayMinor = descArray[3].split(\"r\");
  2469. } else {
  2470. tempArrayMinor = descArray[4].split(\"r\");
  2471. }
  2472. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  2473. flashVer = versionMajor + \".\" + versionMinor + \".\" + versionRevision;
  2474. } else {
  2475. flashVer = -1;
  2476. }
  2477. }
  2478. // MSN/WebTV 2.6 supports Flash 4
  2479. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.6\") != -1) flashVer = 4;
  2480. // WebTV 2.5 supports Flash 3
  2481. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.5\") != -1) flashVer = 3;
  2482. // older WebTV supports Flash 2
  2483. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv\") != -1) flashVer = 2;
  2484. // Can't detect in all other cases
  2485. else {
  2486. flashVer = -1;
  2487. }
  2488. return flashVer;
  2489. }
  2490. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  2491. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
  2492. {
  2493. reqVer = parseFloat(reqMajorVer + \".\" + reqRevision);
  2494. // loop backwards through the versions until we find the newest version
  2495. for (i=25;i>0;i--) {
  2496. if (isIE && isWin && !isOpera) {
  2497. versionStr = VBGetSwfVer(i);
  2498. } else {
  2499. versionStr = JSGetSwfVer(i);
  2500. }
  2501. if (versionStr == -1 ) {
  2502. return false;
  2503. } else if (versionStr != 0) {
  2504. if(isIE && isWin && !isOpera) {
  2505. tempArray = versionStr.split(\" \");
  2506. tempString = tempArray[1];
  2507. versionArray = tempString .split(\",\");
  2508. } else {
  2509. versionArray = versionStr.split(\".\");
  2510. }
  2511. versionMajor = versionArray[0];
  2512. versionMinor = versionArray[1];
  2513. versionRevision = versionArray[2];
  2514. versionString = versionMajor + \".\" + versionRevision; // 7.0r24 == 7.24
  2515. versionNum = parseFloat(versionString);
  2516. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  2517. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  2518. return true;
  2519. } else {
  2520. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  2521. }
  2522. }
  2523. }
  2524. }
  2525. // -->
  2526. </script>";
  2527. }
  2528. /**
  2529. * This function was originally found in the exercise_show.php
  2530. * @param int exe id
  2531. * @param int question id
  2532. * @param int the choice the user selected
  2533. * @param array the hotspot coordinates $hotspot[$question_id] = coordinates
  2534. * @param string function is called from 'exercise_show' or 'exercise_result'
  2535. * @param bool save results in the DB or just show the reponse
  2536. * @param bool gets information from DB or from the current selection
  2537. * @param bool show results or not
  2538. * @todo reduce parameters of this function
  2539. * @return string html code
  2540. */
  2541. public function manageAnswers(
  2542. $exeId,
  2543. $questionId,
  2544. $choice,
  2545. $from = 'exercise_show',
  2546. $exerciseResultCoordinates = array(),
  2547. $saved_results = true,
  2548. $from_database = false,
  2549. $show_result = true,
  2550. $hotspot_delineation_result = array(),
  2551. $updateResults = false
  2552. ) {
  2553. global $feedback_type, $debug;
  2554. global $learnpath_id, $learnpath_item_id; //needed in order to use in the exercise_attempt() for the time
  2555. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  2556. $propagate_neg = $this->selectPropagateNeg();
  2557. if ($debug) {
  2558. error_log("<------ manage_answer ------> ");
  2559. error_log('exe_id: '.$exeId);
  2560. error_log('$from: '.$from);
  2561. error_log('$saved_results: '.intval($saved_results));
  2562. error_log('$from_database: '.intval($from_database));
  2563. error_log('$show_result: '.$show_result);
  2564. error_log('$propagate_neg: '.$propagate_neg);
  2565. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  2566. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  2567. error_log('$learnpath_id: '.$learnpath_id);
  2568. error_log('$learnpath_item_id: '.$learnpath_item_id);
  2569. error_log('$choice: '.print_r($choice, 1));
  2570. }
  2571. $extra_data = array();
  2572. $final_overlap = 0;
  2573. $final_missing = 0;
  2574. $final_excess = 0;
  2575. $overlap_color = 0;
  2576. $missing_color = 0;
  2577. $excess_color = 0;
  2578. $threadhold1 = 0;
  2579. $threadhold2 = 0;
  2580. $threadhold3 = 0;
  2581. $arrques = null;
  2582. $arrans = null;
  2583. $questionId = intval($questionId);
  2584. $exeId = intval($exeId);
  2585. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2586. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  2587. // Creates a temporary Question object
  2588. $course_id = api_get_course_int_id();
  2589. $objQuestionTmp = Question::read($questionId, $course_id);
  2590. if ($objQuestionTmp === false) {
  2591. return false;
  2592. }
  2593. $questionName = $objQuestionTmp->selectTitle();
  2594. $questionWeighting = $objQuestionTmp->selectWeighting();
  2595. $answerType = $objQuestionTmp->selectType();
  2596. $quesId = $objQuestionTmp->selectId();
  2597. $extra = $objQuestionTmp->extra;
  2598. $next = 1; //not for now
  2599. //Extra information of the question
  2600. if (!empty($extra)) {
  2601. $extra = explode(':', $extra);
  2602. if ($debug) {
  2603. error_log(print_r($extra, 1));
  2604. }
  2605. //Fixes problems with negatives values using intval
  2606. $true_score = intval($extra[0]);
  2607. $false_score = intval($extra[1]);
  2608. $doubt_score = intval($extra[2]);
  2609. }
  2610. $totalWeighting = 0;
  2611. $totalScore = 0;
  2612. // Destruction of the Question object
  2613. unset($objQuestionTmp);
  2614. // Construction of the Answer object
  2615. $objAnswerTmp = new Answer($questionId, null, $this);
  2616. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  2617. if ($debug) {
  2618. error_log('Count of answers: '.$nbrAnswers);
  2619. error_log('$answerType: '.$answerType);
  2620. }
  2621. if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
  2622. $nbrAnswers = 1;
  2623. }
  2624. $nano = null;
  2625. if ($answerType == ORAL_EXPRESSION) {
  2626. $exe_info = get_exercise_results_by_attempt($exeId);
  2627. $exe_info = $exe_info[$exeId];
  2628. $params = array();
  2629. $params['course_id'] = api_get_course_int_id();
  2630. $params['session_id'] = api_get_session_id();
  2631. $params['user_id'] = isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id();
  2632. $params['exercise_id'] = isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id;
  2633. $params['question_id'] = $questionId;
  2634. $params['exe_id'] = isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId;
  2635. $nano = new Nanogong($params);
  2636. //probably this attempt came in an exercise all question by page
  2637. if ($feedback_type == 0) {
  2638. $nano->replace_with_real_exe($exeId);
  2639. }
  2640. }
  2641. $user_answer = '';
  2642. // Get answer list for matching
  2643. $sql_answer = 'SELECT iid, answer FROM '.$table_ans.' WHERE question_id = "'.$questionId.'" ';
  2644. $res_answer = Database::query($sql_answer);
  2645. $answer_matching = array();
  2646. $answer_list = array();
  2647. while ($real_answer = Database::fetch_array($res_answer)) {
  2648. $answer_matching[$real_answer['iid']] = $real_answer['answer'];
  2649. $answer_list[] = $real_answer['iid'];
  2650. }
  2651. if ($answerType == FREE_ANSWER || $answerType == ORAL_EXPRESSION) {
  2652. $nbrAnswers = 1;
  2653. $answer_list[] = 1;
  2654. }
  2655. $real_answers = array();
  2656. $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
  2657. $organs_at_risk_hit = 0;
  2658. $questionScore = 0;
  2659. if ($debug) {
  2660. error_log('<<-- Start answer loop -->');
  2661. }
  2662. $answer_correct_array = array();
  2663. //for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  2664. $counter = 1;
  2665. foreach ($answer_list as $answerId) {
  2666. /** @var \Answer $objAnswerTmp */
  2667. $answer = $objAnswerTmp->selectAnswer($answerId);
  2668. $answerComment = $objAnswerTmp->selectComment($answerId);
  2669. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  2670. $answerWeighting = (float)$objAnswerTmp->selectWeighting($answerId);
  2671. //$numAnswer = $objAnswerTmp->selectAutoId($answerId);
  2672. $numAnswer = $answerId;
  2673. $answer_correct_array[$answerId] = (bool)$answerCorrect;
  2674. if ($debug) {
  2675. error_log("answer auto id: $numAnswer ");
  2676. error_log("answer correct: $answerCorrect ");
  2677. }
  2678. //Delineation
  2679. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  2680. $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
  2681. switch ($answerType) {
  2682. // for unique answer
  2683. case UNIQUE_ANSWER:
  2684. case UNIQUE_ANSWER_IMAGE:
  2685. case UNIQUE_ANSWER_NO_OPTION:
  2686. if ($from_database) {
  2687. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2688. $resultans = Database::query($queryans);
  2689. $choice = Database::result($resultans, 0, "answer");
  2690. $studentChoice = ($choice == $numAnswer) ? 1 : 0;
  2691. if ($studentChoice) {
  2692. $questionScore += $answerWeighting;
  2693. $totalScore += $answerWeighting;
  2694. }
  2695. } else {
  2696. $studentChoice = ($choice == $numAnswer) ? 1 : 0;
  2697. if ($studentChoice) {
  2698. $questionScore += $answerWeighting;
  2699. $totalScore += $answerWeighting;
  2700. }
  2701. }
  2702. break;
  2703. // for multiple answers
  2704. case MULTIPLE_ANSWER_TRUE_FALSE:
  2705. if ($from_database) {
  2706. $choice = array();
  2707. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = ".$exeId." AND question_id = ".$questionId;
  2708. $resultans = Database::query($queryans);
  2709. while ($row = Database::fetch_array($resultans)) {
  2710. $ind = $row['answer'];
  2711. $result = explode(':', $ind);
  2712. $my_answer_id = $result[0];
  2713. $option = $result[1];
  2714. $choice[$my_answer_id] = $option;
  2715. }
  2716. $studentChoice = $choice[$numAnswer];
  2717. } else {
  2718. $studentChoice = $choice[$numAnswer];
  2719. }
  2720. if (!empty($studentChoice)) {
  2721. if ($studentChoice == $answerCorrect) {
  2722. $questionScore += $true_score;
  2723. } else {
  2724. if ($quiz_question_options[$studentChoice]['name'] != "Don't know") {
  2725. $questionScore += $false_score;
  2726. } else {
  2727. $questionScore += $doubt_score;
  2728. }
  2729. }
  2730. } else {
  2731. //if no result then the user just hit don't know
  2732. $studentChoice = 3;
  2733. $questionScore += $doubt_score;
  2734. }
  2735. $totalScore = $questionScore;
  2736. break;
  2737. case MULTIPLE_ANSWER: //2
  2738. if ($from_database) {
  2739. $choice = array();
  2740. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2741. $resultans = Database::query($queryans);
  2742. while ($row = Database::fetch_array($resultans)) {
  2743. $ind = $row['answer'];
  2744. $choice[$ind] = 1;
  2745. }
  2746. $studentChoice = isset($choice[$numAnswer]) ? $choice[$numAnswer] : null;
  2747. $real_answers[$answerId] = (bool)$studentChoice;
  2748. if ($studentChoice) {
  2749. $questionScore += $answerWeighting;
  2750. }
  2751. } else {
  2752. $studentChoice = isset($choice[$numAnswer]) ? $choice[$numAnswer] : null;
  2753. $real_answers[$answerId] = (bool)$studentChoice;
  2754. if (isset($studentChoice)) {
  2755. $questionScore += $answerWeighting;
  2756. }
  2757. }
  2758. $totalScore += $answerWeighting;
  2759. if ($debug) {
  2760. error_log("studentChoice: $studentChoice");
  2761. }
  2762. break;
  2763. case GLOBAL_MULTIPLE_ANSWER :
  2764. if ($from_database) {
  2765. $choice = array();
  2766. $queryans = "SELECT answer FROM $TBL_TRACK_ATTEMPT WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2767. $resultans = Database::query($queryans);
  2768. while ($row = Database::fetch_array($resultans)) {
  2769. $ind = $row['answer'];
  2770. $choice[$ind] = 1;
  2771. }
  2772. $studentChoice = $choice[$numAnswer];
  2773. $real_answers[$answerId] = (bool)$studentChoice;
  2774. if ($studentChoice) {
  2775. $questionScore += $answerWeighting;
  2776. }
  2777. } else {
  2778. $studentChoice = $choice[$numAnswer];
  2779. if (isset($studentChoice)) {
  2780. $questionScore += $answerWeighting;
  2781. }
  2782. $real_answers[$answerId] = (bool)$studentChoice;
  2783. }
  2784. $totalScore += $answerWeighting;
  2785. if ($debug) {
  2786. error_log("studentChoice: $studentChoice");
  2787. }
  2788. break;
  2789. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  2790. if ($from_database) {
  2791. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = ".$exeId." AND question_id= ".$questionId;
  2792. $resultans = Database::query($queryans);
  2793. while ($row = Database::fetch_array($resultans)) {
  2794. $ind = $row['answer'];
  2795. $result = explode(':', $ind);
  2796. $my_answer_id = $result[0];
  2797. $option = $result[1];
  2798. $choice[$my_answer_id] = $option;
  2799. }
  2800. //$numAnswer = $objAnswerTmp->selectAutoId($answerId);
  2801. $numAnswer = $answerId;
  2802. $studentChoice = $choice[$numAnswer];
  2803. if ($answerCorrect == $studentChoice) {
  2804. //$answerCorrect = 1;
  2805. $real_answers[$answerId] = true;
  2806. } else {
  2807. //$answerCorrect = 0;
  2808. $real_answers[$answerId] = false;
  2809. }
  2810. } else {
  2811. $studentChoice = $choice[$numAnswer];
  2812. if ($answerCorrect == $studentChoice) {
  2813. //$answerCorrect = 1;
  2814. $real_answers[$answerId] = true;
  2815. } else {
  2816. //$answerCorrect = 0;
  2817. $real_answers[$answerId] = false;
  2818. }
  2819. }
  2820. break;
  2821. case MULTIPLE_ANSWER_COMBINATION:
  2822. if ($from_database) {
  2823. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  2824. $resultans = Database::query($queryans);
  2825. while ($row = Database::fetch_array($resultans)) {
  2826. $choice[$row['answer']] = 1;
  2827. }
  2828. $studentChoice = $choice[$answerId];
  2829. if ($answerCorrect == 1) {
  2830. if ($studentChoice) {
  2831. $real_answers[$answerId] = true;
  2832. } else {
  2833. $real_answers[$answerId] = false;
  2834. }
  2835. } else {
  2836. if ($studentChoice) {
  2837. $real_answers[$answerId] = false;
  2838. } else {
  2839. $real_answers[$answerId] = true;
  2840. }
  2841. }
  2842. } else {
  2843. $studentChoice = $choice[$numAnswer];
  2844. if ($answerCorrect == 1) {
  2845. if ($studentChoice) {
  2846. $real_answers[$answerId] = true;
  2847. } else {
  2848. $real_answers[$answerId] = false;
  2849. }
  2850. } else {
  2851. if ($studentChoice) {
  2852. $real_answers[$answerId] = false;
  2853. } else {
  2854. $real_answers[$answerId] = true;
  2855. }
  2856. }
  2857. }
  2858. break;
  2859. // for fill in the blanks
  2860. case FILL_IN_BLANKS :
  2861. // the question is encoded like this
  2862. // [A] B [C] D [E] F::10,10,10@1
  2863. // number 1 before the "@" means that is a switchable fill in blank question
  2864. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  2865. // means that is a normal fill blank question
  2866. // first we explode the "::"
  2867. $pre_array = explode('::', $answer);
  2868. // is switchable fill blank or not
  2869. $last = count($pre_array) - 1;
  2870. $is_set_switchable = explode('@', $pre_array[$last]);
  2871. $switchable_answer_set = false;
  2872. if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  2873. $switchable_answer_set = true;
  2874. }
  2875. $answer = '';
  2876. for ($k = 0; $k < $last; $k++) {
  2877. $answer .= $pre_array[$k];
  2878. }
  2879. // splits weightings that are joined with a comma
  2880. $answerWeighting = explode(',', $is_set_switchable[0]);
  2881. // we save the answer because it will be modified
  2882. //$temp = $answer;
  2883. $temp = $answer;
  2884. $answer = '';
  2885. $j = 0;
  2886. //initialise answer tags
  2887. $user_tags = $correct_tags = $real_text = array();
  2888. // the loop will stop at the end of the text
  2889. while (1) {
  2890. // quits the loop if there are no more blanks (detect '[')
  2891. if (($pos = api_strpos($temp, '[')) === false) {
  2892. // adds the end of the text
  2893. $answer = $temp;
  2894. /* // Deprecated code
  2895. // TeX parsing - replacement of texcode tags
  2896. $answer = str_replace("{texcode}", $texstring, $answer);
  2897. */
  2898. $real_text[] = $answer;
  2899. break; //no more "blanks", quit the loop
  2900. }
  2901. // adds the piece of text that is before the blank
  2902. //and ends with '[' into a general storage array
  2903. $real_text[] = api_substr($temp, 0, $pos + 1);
  2904. $answer .= api_substr($temp, 0, $pos + 1);
  2905. //take the string remaining (after the last "[" we found)
  2906. $temp = api_substr($temp, $pos + 1);
  2907. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  2908. if (($pos = api_strpos($temp, ']')) === false) {
  2909. // adds the end of the text
  2910. $answer .= $temp;
  2911. break;
  2912. }
  2913. if ($from_database) {
  2914. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = ".$exeId." AND question_id= ".Database::escape_string($questionId);
  2915. $resfill = Database::query($queryfill);
  2916. if (Database::num_rows($resfill)) {
  2917. $str = Database::result($resfill, 0, 'answer');
  2918. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  2919. $str = str_replace('\r\n', '', $str);
  2920. $choice = $arr[1];
  2921. $tmp = api_strrpos($choice[$j], ' / ');
  2922. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  2923. $choice[$j] = trim($choice[$j]);
  2924. //Needed to let characters ' and " to work as part of an answer
  2925. $choice[$j] = stripslashes($choice[$j]);
  2926. }
  2927. } else {
  2928. $choice[$j] = trim($choice[$j]);
  2929. }
  2930. //No idea why we api_strtolower user reponses
  2931. //$user_tags[] = api_strtolower($choice[$j]);
  2932. $user_tags[] = $choice[$j];
  2933. //put the contents of the [] answer tag into correct_tags[]
  2934. //$correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  2935. $correct_tags[] = api_substr($temp, 0, $pos);
  2936. $j++;
  2937. $temp = api_substr($temp, $pos + 1);
  2938. }
  2939. $answer = '';
  2940. $real_correct_tags = $correct_tags;
  2941. $chosen_list = array();
  2942. for ($i = 0; $i < count($real_correct_tags); $i++) {
  2943. if ($i == 0) {
  2944. $answer .= $real_text[0];
  2945. }
  2946. if (!$switchable_answer_set) {
  2947. //needed to parse ' and " characters
  2948. $user_tags[$i] = stripslashes($user_tags[$i]);
  2949. if ($correct_tags[$i] == $user_tags[$i]) {
  2950. // gives the related weighting to the student
  2951. $questionScore += $answerWeighting[$i];
  2952. // increments total score
  2953. $totalScore += $answerWeighting[$i];
  2954. // adds the word in green at the end of the string
  2955. $answer .= $correct_tags[$i];
  2956. } // else if the word entered by the student IS NOT the same as the one defined by the professor
  2957. elseif (!empty($user_tags[$i])) {
  2958. // adds the word in red at the end of the string, and strikes it
  2959. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  2960. } else {
  2961. // adds a tabulation if no word has been typed by the student
  2962. $answer .= '&nbsp;&nbsp;&nbsp;';
  2963. }
  2964. } else {
  2965. // switchable fill in the blanks
  2966. if (in_array($user_tags[$i], $correct_tags)) {
  2967. $chosen_list[] = $user_tags[$i];
  2968. $correct_tags = array_diff($correct_tags, $chosen_list);
  2969. // gives the related weighting to the student
  2970. $questionScore += $answerWeighting[$i];
  2971. // increments total score
  2972. $totalScore += $answerWeighting[$i];
  2973. // adds the word in green at the end of the string
  2974. $answer .= $user_tags[$i];
  2975. } elseif (!empty($user_tags[$i])) {
  2976. // else if the word entered by the student IS NOT the same as the one defined by the professor
  2977. // adds the word in red at the end of the string, and strikes it
  2978. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  2979. } else {
  2980. // adds a tabulation if no word has been typed by the student
  2981. $answer .= '&nbsp;&nbsp;&nbsp;';
  2982. }
  2983. }
  2984. // adds the correct word, followed by ] to close the blank
  2985. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  2986. if (isset($real_text[$i + 1])) {
  2987. $answer .= $real_text[$i + 1];
  2988. }
  2989. }
  2990. break;
  2991. // for free answer
  2992. case FREE_ANSWER:
  2993. if ($from_database) {
  2994. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  2995. $resq = Database::query($query);
  2996. $questionScore = 0;
  2997. $choice = null;
  2998. if ($resq) {
  2999. $row = Database::fetch_array($resq);
  3000. $choice = $row['answer'];
  3001. $questionScore = $row['marks'];
  3002. $choice = str_replace('\r\n', '', $choice);
  3003. $choice = stripslashes($choice);
  3004. }
  3005. if ($questionScore == -1) {
  3006. $totalScore += 0;
  3007. } else {
  3008. $totalScore += $questionScore;
  3009. }
  3010. if ($questionScore == '') {
  3011. $questionScore = 0;
  3012. }
  3013. $arrques = $questionName;
  3014. $arrans = $choice;
  3015. } else {
  3016. $studentChoice = $choice;
  3017. if ($studentChoice) {
  3018. //Fixing negative puntation see #2193
  3019. $questionScore = 0;
  3020. $totalScore += 0;
  3021. }
  3022. }
  3023. break;
  3024. case ORAL_EXPRESSION :
  3025. if ($from_database) {
  3026. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3027. $resq = Database::query($query);
  3028. $choice = Database::result($resq, 0, 'answer');
  3029. $choice = str_replace('\r\n', '', $choice);
  3030. $choice = stripslashes($choice);
  3031. $questionScore = Database::result($resq, 0, "marks");
  3032. if ($questionScore == -1) {
  3033. $totalScore += 0;
  3034. } else {
  3035. $totalScore += $questionScore;
  3036. }
  3037. $arrques = $questionName;
  3038. $arrans = $choice;
  3039. } else {
  3040. $studentChoice = $choice;
  3041. if ($studentChoice) {
  3042. //Fixing negative puntation see #2193
  3043. $questionScore = 0;
  3044. $totalScore += 0;
  3045. }
  3046. }
  3047. break;
  3048. // for matching
  3049. case DRAGGABLE:
  3050. case MATCHING :
  3051. if ($from_database) {
  3052. $sql_answer = 'SELECT iid, answer FROM '.$table_ans.' WHERE c_id = '.$course_id.' AND question_id="'.$questionId.'" AND correct=0';
  3053. $res_answer = Database::query($sql_answer);
  3054. // getting the real answer
  3055. $real_list = array();
  3056. while ($real_answer = Database::fetch_array($res_answer)) {
  3057. $real_list[$real_answer['iid']] = $real_answer['answer'];
  3058. }
  3059. $sql_select_answer = "SELECT iid, answer, correct FROM $table_ans
  3060. WHERE c_id = $course_id AND question_id = '$questionId' AND correct <> 0
  3061. ORDER BY iid";
  3062. $res_answers = Database::query($sql_select_answer);
  3063. $questionScore = 0;
  3064. while ($a_answers = Database::fetch_array($res_answers)) {
  3065. $i_answer_id = $a_answers['iid']; //3
  3066. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3067. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3068. $answerIdCorrect = $a_answers['correct'];
  3069. $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3070. WHERE exe_id = '$exeId' AND
  3071. question_id = '$questionId' AND
  3072. position = '$i_answer_id'";
  3073. $res_user_answer = Database::query($sql_user_answer);
  3074. if (Database::num_rows($res_user_answer)) {
  3075. // Rich - good looking
  3076. $result = Database::fetch_array($res_user_answer, 'ASSOC');
  3077. $s_user_answer = $result['answer'];
  3078. } else {
  3079. $s_user_answer = 0;
  3080. }
  3081. $i_answerWeighting = $objAnswerTmp->selectWeighting($i_answer_id);
  3082. if ($answerType == MATCHING) {
  3083. $i_answer_correct_answer = $objAnswerTmp->getAnswerIdFromList($i_answer_correct_answer);
  3084. }
  3085. $user_answer = '';
  3086. if (!empty($s_user_answer)) {
  3087. if ($s_user_answer == $i_answer_correct_answer) {
  3088. $questionScore += $i_answerWeighting;
  3089. $totalScore += $i_answerWeighting;
  3090. if ($answerType == DRAGGABLE) {
  3091. $user_answer = Display::label(get_lang('Correct'), 'success');
  3092. } else {
  3093. $user_answer = '<span>'.$real_list[$answerIdCorrect].'</span>';
  3094. }
  3095. } else {
  3096. if ($answerType == DRAGGABLE) {
  3097. $user_answer = Display::label(get_lang('NotCorrect'), 'important');
  3098. } else {
  3099. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
  3100. }
  3101. }
  3102. } else {
  3103. if ($answerType == DRAGGABLE) {
  3104. $user_answer = Display::label(get_lang('Incorrect'), 'important');
  3105. }
  3106. }
  3107. if ($show_result) {
  3108. echo '<tr>';
  3109. echo '<td>'.$s_answer_label.'</td>';
  3110. echo '<td>'.$user_answer.'';
  3111. if ($answerType == MATCHING) {
  3112. echo '<b><span style="color: #008000;"> '.$real_list[$answerIdCorrect].'</span></b>';
  3113. }
  3114. echo '</td>';
  3115. echo '</tr>';
  3116. }
  3117. }
  3118. break(2); //break the switch and the "for" condition
  3119. } else {
  3120. $numAnswer = $answerId;
  3121. if ($answerCorrect) {
  3122. $matchingKey = $choice[$numAnswer];
  3123. if ($answerType == DRAGGABLE) {
  3124. $matchingKey = $numAnswer;
  3125. }
  3126. if ($answerType == MATCHING) {
  3127. $answerCorrect = $objAnswerTmp->getAnswerIdFromList($answerCorrect);
  3128. $matchingKey = $numAnswer;
  3129. }
  3130. if ($answerCorrect == $choice[$numAnswer]) {
  3131. $questionScore += $answerWeighting;
  3132. $totalScore += $answerWeighting;
  3133. $user_answer = '<span>'.$answer_matching[$matchingKey].'</span>';
  3134. } else {
  3135. if ($choice[$numAnswer]) {
  3136. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$matchingKey].'</span>';
  3137. }
  3138. }
  3139. $matching[$numAnswer] = $choice[$numAnswer];
  3140. }
  3141. break;
  3142. }
  3143. // for hotspot with no order
  3144. case HOT_SPOT :
  3145. if ($from_database) {
  3146. if ($show_result) {
  3147. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3148. $query = "SELECT hotspot_correct
  3149. FROM ".$TBL_TRACK_HOTSPOT."
  3150. WHERE hotspot_exe_id = '".$exeId."' and
  3151. hotspot_question_id= '".$questionId."' AND
  3152. hotspot_answer_id='".Database::escape_string($answerId)."'";
  3153. $resq = Database::query($query);
  3154. $studentChoice = Database::result($resq, 0, "hotspot_correct");
  3155. if ($studentChoice == 1) {
  3156. $questionScore += $answerWeighting;
  3157. $totalScore += $answerWeighting;
  3158. }
  3159. }
  3160. } else {
  3161. if (isset($choice[$answerId])) {
  3162. $studentChoice = $choice[$answerId];
  3163. } else {
  3164. $studentChoice = false;
  3165. }
  3166. if ($studentChoice) {
  3167. $questionScore += $answerWeighting;
  3168. $totalScore += $answerWeighting;
  3169. }
  3170. }
  3171. break;
  3172. // @todo never added to chamilo
  3173. //for hotspot with fixed order
  3174. case HOT_SPOT_ORDER :
  3175. $studentChoice = $choice['order'][$answerId];
  3176. if ($studentChoice == $answerId) {
  3177. $questionScore += $answerWeighting;
  3178. $totalScore += $answerWeighting;
  3179. $studentChoice = true;
  3180. } else {
  3181. $studentChoice = false;
  3182. }
  3183. break;
  3184. // for hotspot with delineation
  3185. case HOT_SPOT_DELINEATION :
  3186. if ($from_database) {
  3187. // getting the user answer
  3188. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3189. $query = "SELECT hotspot_correct, hotspot_coordinate
  3190. FROM ".$TBL_TRACK_HOTSPOT."
  3191. WHERE hotspot_exe_id = '".$exeId."' AND
  3192. hotspot_question_id= '".$questionId."' AND
  3193. hotspot_answer_id='1'"; //by default we take 1 because it's a delineation
  3194. $resq = Database::query($query);
  3195. $row = Database::fetch_array($resq, 'ASSOC');
  3196. $choice = $row['hotspot_correct'];
  3197. $user_answer = $row['hotspot_coordinate'];
  3198. // THIS is very important otherwise the poly_compile will throw an error!!
  3199. // round-up the coordinates
  3200. $coords = explode('/', $user_answer);
  3201. $user_array = '';
  3202. foreach ($coords as $coord) {
  3203. list($x, $y) = explode(';', $coord);
  3204. $user_array .= round($x).';'.round($y).'/';
  3205. }
  3206. $user_array = substr($user_array, 0, -1);
  3207. } else {
  3208. if ($studentChoice) {
  3209. $newquestionList[] = $questionId;
  3210. }
  3211. if ($answerId === 1) {
  3212. $studentChoice = $choice[$answerId];
  3213. $questionScore += $answerWeighting;
  3214. if ($hotspot_delineation_result[1] == 1) {
  3215. $totalScore += $answerWeighting; //adding the total
  3216. }
  3217. }
  3218. }
  3219. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  3220. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  3221. break;
  3222. } // end switch Answertype
  3223. global $origin;
  3224. if ($show_result) {
  3225. if ($debug) {
  3226. error_log('show result '.$show_result);
  3227. }
  3228. if ($from == 'exercise_result') {
  3229. if ($debug) {
  3230. error_log('Showing questions $from '.$from);
  3231. }
  3232. //display answers (if not matching type, or if the answer is correct)
  3233. if (!in_array($answerType, array(DRAGGABLE, MATCHING))|| $answerCorrect) {
  3234. if (in_array(
  3235. $answerType,
  3236. array(
  3237. UNIQUE_ANSWER,
  3238. UNIQUE_ANSWER_IMAGE,
  3239. UNIQUE_ANSWER_NO_OPTION,
  3240. MULTIPLE_ANSWER,
  3241. MULTIPLE_ANSWER_COMBINATION,
  3242. GLOBAL_MULTIPLE_ANSWER
  3243. )
  3244. )
  3245. ) {
  3246. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3247. $answerType,
  3248. $studentChoice,
  3249. $answer,
  3250. $answerComment,
  3251. $answerCorrect,
  3252. 0,
  3253. 0,
  3254. 0
  3255. );
  3256. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  3257. ExerciseShowFunctions::display_multiple_answer_true_false(
  3258. $answerType,
  3259. $studentChoice,
  3260. $answer,
  3261. $answerComment,
  3262. $answerCorrect,
  3263. 0,
  3264. $questionId,
  3265. 0
  3266. );
  3267. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  3268. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3269. $answerType,
  3270. $studentChoice,
  3271. $answer,
  3272. $answerComment,
  3273. $answerCorrect,
  3274. 0,
  3275. 0,
  3276. 0
  3277. );
  3278. } elseif ($answerType == FILL_IN_BLANKS) {
  3279. ExerciseShowFunctions::display_fill_in_blanks_answer($answer, 0, 0);
  3280. } elseif ($answerType == FREE_ANSWER) {
  3281. ExerciseShowFunctions::display_free_answer(
  3282. $choice,
  3283. $exeId,
  3284. $questionId,
  3285. $questionScore
  3286. );
  3287. } elseif ($answerType == ORAL_EXPRESSION) {
  3288. // to store the details of open questions in an array to be used in mail
  3289. ExerciseShowFunctions::display_oral_expression_answer($choice, 0, 0, $nano);
  3290. } elseif ($answerType == HOT_SPOT) {
  3291. ExerciseShowFunctions::display_hotspot_answer($counter, $answer, $studentChoice, $answerComment);
  3292. } elseif ($answerType == HOT_SPOT_ORDER) {
  3293. ExerciseShowFunctions::display_hotspot_order_answer(
  3294. $answerId,
  3295. $answer,
  3296. $studentChoice,
  3297. $answerComment
  3298. );
  3299. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  3300. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  3301. // Round-up the coordinates
  3302. $coords = explode('/', $user_answer);
  3303. $user_array = '';
  3304. foreach ($coords as $coord) {
  3305. list($x, $y) = explode(';', $coord);
  3306. $user_array .= round($x).';'.round($y).'/';
  3307. }
  3308. $user_array = substr($user_array, 0, -1);
  3309. if ($next) {
  3310. $user_answer = $user_array;
  3311. // we compare only the delineation not the other points
  3312. $answer_question = $_SESSION['hotspot_coord'][1];
  3313. $answerDestination = $_SESSION['hotspot_dest'][1];
  3314. //calculating the area
  3315. $poly_user = convert_coordinates($user_answer, '/');
  3316. $poly_answer = convert_coordinates($answer_question, '|');
  3317. $max_coord = poly_get_max($poly_user, $poly_answer);
  3318. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  3319. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3320. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  3321. $overlap = $poly_results['both'];
  3322. $poly_answer_area = $poly_results['s1'];
  3323. $poly_user_area = $poly_results['s2'];
  3324. $missing = $poly_results['s1Only'];
  3325. $excess = $poly_results['s2Only'];
  3326. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  3327. if ($debug > 0) {
  3328. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  3329. }
  3330. if ($overlap < 1) {
  3331. //shortcut to avoid complicated calculations
  3332. $final_overlap = 0;
  3333. $final_missing = 100;
  3334. $final_excess = 100;
  3335. } else {
  3336. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  3337. $final_overlap = round(((float)$overlap / (float)$poly_answer_area) * 100);
  3338. if ($debug > 1) {
  3339. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  3340. }
  3341. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  3342. $final_missing = 100 - $final_overlap;
  3343. if ($debug > 1) {
  3344. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  3345. }
  3346. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  3347. $final_excess = round(
  3348. (((float)$poly_user_area - (float)$overlap) / (float)$poly_answer_area) * 100
  3349. );
  3350. if ($debug > 1) {
  3351. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  3352. }
  3353. }
  3354. //checking the destination parameters parsing the "@@"
  3355. $destination_items = explode('@@', $answerDestination);
  3356. $threadhold_total = $destination_items[0];
  3357. $threadhold_items = explode(';', $threadhold_total);
  3358. $threadhold1 = $threadhold_items[0]; // overlap
  3359. $threadhold2 = $threadhold_items[1]; // excess
  3360. $threadhold3 = $threadhold_items[2]; //missing
  3361. // if is delineation
  3362. if ($answerId === 1) {
  3363. //setting colors
  3364. if ($final_overlap >= $threadhold1) {
  3365. $overlap_color = true; //echo 'a';
  3366. }
  3367. //echo $excess.'-'.$threadhold2;
  3368. if ($final_excess <= $threadhold2) {
  3369. $excess_color = true; //echo 'b';
  3370. }
  3371. //echo '--------'.$missing.'-'.$threadhold3;
  3372. if ($final_missing <= $threadhold3) {
  3373. $missing_color = true; //echo 'c';
  3374. }
  3375. // if pass
  3376. if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) {
  3377. $next = 1; //go to the oars
  3378. $result_comment = get_lang('Acceptable');
  3379. $final_answer = 1; // do not update with update_exercise_attempt
  3380. } else {
  3381. $next = 0;
  3382. $result_comment = get_lang('Unacceptable');
  3383. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  3384. $answerDestination = $objAnswerTmp->selectDestination(1);
  3385. //checking the destination parameters parsing the "@@"
  3386. $destination_items = explode('@@', $answerDestination);
  3387. }
  3388. } elseif ($answerId > 1) {
  3389. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  3390. if ($debug > 0) {
  3391. error_log(__LINE__.' - answerId is of type noerror', 0);
  3392. }
  3393. //type no error shouldn't be treated
  3394. $next = 1;
  3395. continue;
  3396. }
  3397. if ($debug > 0) {
  3398. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  3399. }
  3400. //check the intersection between the oar and the user
  3401. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  3402. //echo 'official';print_r($x_list);print_r($y_list);
  3403. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  3404. $inter = $result['success'];
  3405. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  3406. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3407. $poly_answer = convert_coordinates($delineation_cord, '|');
  3408. $max_coord = poly_get_max($poly_user, $poly_answer);
  3409. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3410. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  3411. if ($overlap == false) {
  3412. //all good, no overlap
  3413. $next = 1;
  3414. continue;
  3415. } else {
  3416. if ($debug > 0) {
  3417. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  3418. }
  3419. $organs_at_risk_hit++;
  3420. //show the feedback
  3421. $next = 0;
  3422. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  3423. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3424. $destination_items = explode('@@', $answerDestination);
  3425. $try_hotspot = $destination_items[1];
  3426. $lp_hotspot = $destination_items[2];
  3427. $select_question_hotspot = $destination_items[3];
  3428. $url_hotspot = $destination_items[4];
  3429. }
  3430. }
  3431. } else { // the first delineation feedback
  3432. if ($debug > 0) {
  3433. error_log(__LINE__.' first', 0);
  3434. }
  3435. }
  3436. } elseif ($answerType == MATCHING) {
  3437. //if ($origin != 'learnpath') {
  3438. echo '<tr>';
  3439. echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.
  3440. $answer_matching[$answerCorrect]
  3441. .'</span></b></td>';
  3442. echo '</tr>';
  3443. //}
  3444. }
  3445. }
  3446. } else {
  3447. if ($debug) {
  3448. error_log('Showing questions $from '.$from);
  3449. }
  3450. switch ($answerType) {
  3451. case UNIQUE_ANSWER :
  3452. case UNIQUE_ANSWER_IMAGE :
  3453. case UNIQUE_ANSWER_NO_OPTION:
  3454. case MULTIPLE_ANSWER :
  3455. case GLOBAL_MULTIPLE_ANSWER :
  3456. case MULTIPLE_ANSWER_COMBINATION :
  3457. if ($answerId == 1) {
  3458. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3459. $answerType,
  3460. $studentChoice,
  3461. $answer,
  3462. $answerComment,
  3463. $answerCorrect,
  3464. $exeId,
  3465. $questionId,
  3466. $answerId
  3467. );
  3468. } else {
  3469. ExerciseShowFunctions::display_unique_or_multiple_answer(
  3470. $answerType,
  3471. $studentChoice,
  3472. $answer,
  3473. $answerComment,
  3474. $answerCorrect,
  3475. $exeId,
  3476. $questionId,
  3477. ""
  3478. );
  3479. }
  3480. break;
  3481. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3482. if ($answerId == 1) {
  3483. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3484. $answerType,
  3485. $studentChoice,
  3486. $answer,
  3487. $answerComment,
  3488. $answerCorrect,
  3489. $exeId,
  3490. $questionId,
  3491. $answerId
  3492. );
  3493. } else {
  3494. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  3495. $answerType,
  3496. $studentChoice,
  3497. $answer,
  3498. $answerComment,
  3499. $answerCorrect,
  3500. $exeId,
  3501. $questionId,
  3502. ""
  3503. );
  3504. }
  3505. break;
  3506. case MULTIPLE_ANSWER_TRUE_FALSE :
  3507. if ($answerId == 1) {
  3508. ExerciseShowFunctions::display_multiple_answer_true_false(
  3509. $answerType,
  3510. $studentChoice,
  3511. $answer,
  3512. $answerComment,
  3513. $answerCorrect,
  3514. $exeId,
  3515. $questionId,
  3516. $answerId
  3517. );
  3518. } else {
  3519. ExerciseShowFunctions::display_multiple_answer_true_false(
  3520. $answerType,
  3521. $studentChoice,
  3522. $answer,
  3523. $answerComment,
  3524. $answerCorrect,
  3525. $exeId,
  3526. $questionId,
  3527. ""
  3528. );
  3529. }
  3530. break;
  3531. case FILL_IN_BLANKS:
  3532. ExerciseShowFunctions::display_fill_in_blanks_answer($answer, $exeId, $questionId);
  3533. break;
  3534. case FREE_ANSWER:
  3535. echo ExerciseShowFunctions::display_free_answer(
  3536. $choice,
  3537. $exeId,
  3538. $questionId,
  3539. $questionScore
  3540. );
  3541. break;
  3542. case ORAL_EXPRESSION:
  3543. echo '<tr>
  3544. <td valign="top">'.ExerciseShowFunctions::display_oral_expression_answer(
  3545. $choice,
  3546. $exeId,
  3547. $questionId,
  3548. $nano
  3549. ).'</td>
  3550. </tr>
  3551. </table>';
  3552. break;
  3553. case HOT_SPOT:
  3554. ExerciseShowFunctions::display_hotspot_answer($counter, $answer, $studentChoice, $answerComment);
  3555. break;
  3556. case HOT_SPOT_DELINEATION:
  3557. $user_answer = $user_array;
  3558. if ($next) {
  3559. $user_answer = $user_array;
  3560. // we compare only the delineation not the other points
  3561. $answer_question = $_SESSION['hotspot_coord'][1];
  3562. $answerDestination = $_SESSION['hotspot_dest'][1];
  3563. //calculating the area
  3564. $poly_user = convert_coordinates($user_answer, '/');
  3565. $poly_answer = convert_coordinates($answer_question, '|');
  3566. $max_coord = poly_get_max($poly_user, $poly_answer);
  3567. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  3568. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3569. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  3570. $overlap = $poly_results['both'];
  3571. $poly_answer_area = $poly_results['s1'];
  3572. $poly_user_area = $poly_results['s2'];
  3573. $missing = $poly_results['s1Only'];
  3574. $excess = $poly_results['s2Only'];
  3575. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  3576. if ($debug > 0) {
  3577. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  3578. }
  3579. if ($overlap < 1) {
  3580. //shortcut to avoid complicated calculations
  3581. $final_overlap = 0;
  3582. $final_missing = 100;
  3583. $final_excess = 100;
  3584. } else {
  3585. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  3586. $final_overlap = round(((float)$overlap / (float)$poly_answer_area) * 100);
  3587. if ($debug > 1) {
  3588. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  3589. }
  3590. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  3591. $final_missing = 100 - $final_overlap;
  3592. if ($debug > 1) {
  3593. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  3594. }
  3595. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  3596. $final_excess = round(
  3597. (((float)$poly_user_area - (float)$overlap) / (float)$poly_answer_area) * 100
  3598. );
  3599. if ($debug > 1) {
  3600. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  3601. }
  3602. }
  3603. //checking the destination parameters parsing the "@@"
  3604. $destination_items = explode('@@', $answerDestination);
  3605. $threadhold_total = $destination_items[0];
  3606. $threadhold_items = explode(';', $threadhold_total);
  3607. $threadhold1 = $threadhold_items[0]; // overlap
  3608. $threadhold2 = $threadhold_items[1]; // excess
  3609. $threadhold3 = $threadhold_items[2]; //missing
  3610. // if is delineation
  3611. if ($answerId === 1) {
  3612. //setting colors
  3613. if ($final_overlap >= $threadhold1) {
  3614. $overlap_color = true; //echo 'a';
  3615. }
  3616. //echo $excess.'-'.$threadhold2;
  3617. if ($final_excess <= $threadhold2) {
  3618. $excess_color = true; //echo 'b';
  3619. }
  3620. //echo '--------'.$missing.'-'.$threadhold3;
  3621. if ($final_missing <= $threadhold3) {
  3622. $missing_color = true; //echo 'c';
  3623. }
  3624. // if pass
  3625. if ($final_overlap >= $threadhold1 && $final_missing <= $threadhold3 && $final_excess <= $threadhold2) {
  3626. $next = 1; //go to the oars
  3627. $result_comment = get_lang('Acceptable');
  3628. $final_answer = 1; // do not update with update_exercise_attempt
  3629. } else {
  3630. $next = 0;
  3631. $result_comment = get_lang('Unacceptable');
  3632. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  3633. $answerDestination = $objAnswerTmp->selectDestination(1);
  3634. //checking the destination parameters parsing the "@@"
  3635. $destination_items = explode('@@', $answerDestination);
  3636. }
  3637. } elseif ($answerId > 1) {
  3638. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  3639. if ($debug > 0) {
  3640. error_log(__LINE__.' - answerId is of type noerror', 0);
  3641. }
  3642. //type no error shouldn't be treated
  3643. $next = 1;
  3644. continue;
  3645. }
  3646. if ($debug > 0) {
  3647. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  3648. }
  3649. //check the intersection between the oar and the user
  3650. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  3651. //echo 'official';print_r($x_list);print_r($y_list);
  3652. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  3653. $inter = $result['success'];
  3654. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  3655. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3656. $poly_answer = convert_coordinates($delineation_cord, '|');
  3657. $max_coord = poly_get_max($poly_user, $poly_answer);
  3658. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  3659. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  3660. if ($overlap == false) {
  3661. //all good, no overlap
  3662. $next = 1;
  3663. continue;
  3664. } else {
  3665. if ($debug > 0) {
  3666. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  3667. }
  3668. $organs_at_risk_hit++;
  3669. //show the feedback
  3670. $next = 0;
  3671. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  3672. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  3673. $destination_items = explode('@@', $answerDestination);
  3674. $try_hotspot = $destination_items[1];
  3675. $lp_hotspot = $destination_items[2];
  3676. $select_question_hotspot = $destination_items[3];
  3677. $url_hotspot = $destination_items[4];
  3678. }
  3679. }
  3680. } else { // the first delineation feedback
  3681. if ($debug > 0) {
  3682. error_log(__LINE__.' first', 0);
  3683. }
  3684. }
  3685. break;
  3686. case HOT_SPOT_ORDER:
  3687. ExerciseShowFunctions::display_hotspot_order_answer(
  3688. $answerId,
  3689. $answer,
  3690. $studentChoice,
  3691. $answerComment
  3692. );
  3693. break;
  3694. case DRAGGABLE:
  3695. case MATCHING:
  3696. //if ($origin != 'learnpath') {
  3697. echo '<tr>';
  3698. echo '<td>'.$answer_matching[$answerId].'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.$answer_matching[$answerCorrect].'</span></b></td>';
  3699. echo '</tr>';
  3700. //}
  3701. break;
  3702. }
  3703. }
  3704. }
  3705. $counter++;
  3706. } // end for that loops over all answers of the current question
  3707. if ($debug) {
  3708. error_log('<-- end answer loop -->');
  3709. }
  3710. $final_answer = true;
  3711. foreach ($real_answers as $my_answer) {
  3712. if (!$my_answer) {
  3713. $final_answer = false;
  3714. }
  3715. }
  3716. //we add the total score after dealing with the answers
  3717. if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  3718. if ($final_answer) {
  3719. //getting only the first score where we save the weight of all the question
  3720. $answerWeighting = $objAnswerTmp->selectWeighting($objAnswerTmp->getRealAnswerIdFromList(1));
  3721. $questionScore += $answerWeighting;
  3722. $totalScore += $answerWeighting;
  3723. }
  3724. }
  3725. //Fixes multiple answer question in order to be exact
  3726. if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  3727. $diff = @array_diff($answer_correct_array, $real_answers);
  3728. /*
  3729. * All good answers or nothing works like exact
  3730. $counter = 1;
  3731. $correct_answer = true;
  3732. foreach ($real_answers as $my_answer) {
  3733. if ($debug) error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  3734. if ($my_answer != $answer_correct_array[$counter]) {
  3735. $correct_answer = false;
  3736. break;
  3737. }
  3738. $counter++;
  3739. } */
  3740. if ($debug) {
  3741. error_log("answer_correct_array: ".print_r($answer_correct_array, 1)."");
  3742. error_log("real_answers: ".print_r($real_answers, 1)."");
  3743. }
  3744. // This makes the result non exact
  3745. if (!empty($diff)) {
  3746. //$questionScore = 0;
  3747. }
  3748. }
  3749. $extra_data = array(
  3750. 'final_overlap' => $final_overlap,
  3751. 'final_missing' => $final_missing,
  3752. 'final_excess' => $final_excess,
  3753. 'overlap_color' => $overlap_color,
  3754. 'missing_color' => $missing_color,
  3755. 'excess_color' => $excess_color,
  3756. 'threadhold1' => $threadhold1,
  3757. 'threadhold2' => $threadhold2,
  3758. 'threadhold3' => $threadhold3,
  3759. );
  3760. if ($from == 'exercise_result') {
  3761. // if answer is hotspot. To the difference of exercise_show.php, we use the results from the session (from_db=0)
  3762. // TODO Change this, because it is wrong to show the user some results that haven't been stored in the database yet
  3763. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
  3764. if ($debug) {
  3765. error_log('$from AND this is a hotspot kind of question ');
  3766. }
  3767. $my_exe_id = 0;
  3768. $from_database = 0;
  3769. if ($answerType == HOT_SPOT_DELINEATION) {
  3770. if (0) {
  3771. if ($overlap_color) {
  3772. $overlap_color = 'green';
  3773. } else {
  3774. $overlap_color = 'red';
  3775. }
  3776. if ($missing_color) {
  3777. $missing_color = 'green';
  3778. } else {
  3779. $missing_color = 'red';
  3780. }
  3781. if ($excess_color) {
  3782. $excess_color = 'green';
  3783. } else {
  3784. $excess_color = 'red';
  3785. }
  3786. if (!is_numeric($final_overlap)) {
  3787. $final_overlap = 0;
  3788. }
  3789. if (!is_numeric($final_missing)) {
  3790. $final_missing = 0;
  3791. }
  3792. if (!is_numeric($final_excess)) {
  3793. $final_excess = 0;
  3794. }
  3795. if ($final_overlap > 100) {
  3796. $final_overlap = 100;
  3797. }
  3798. $table_resume = '<table class="data_table">
  3799. <tr class="row_odd" >
  3800. <td></td>
  3801. <td ><b>'.get_lang('Requirements').'</b></td>
  3802. <td><b>'.get_lang('YourAnswer').'</b></td>
  3803. </tr>
  3804. <tr class="row_even">
  3805. <td><b>'.get_lang('Overlap').'</b></td>
  3806. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  3807. <td><div style="color:'.$overlap_color.'">'.(($final_overlap < 0) ? 0 : intval(
  3808. $final_overlap
  3809. )).'</div></td>
  3810. </tr>
  3811. <tr>
  3812. <td><b>'.get_lang('Excess').'</b></td>
  3813. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  3814. <td><div style="color:'.$excess_color.'">'.(($final_excess < 0) ? 0 : intval(
  3815. $final_excess
  3816. )).'</div></td>
  3817. </tr>
  3818. <tr class="row_even">
  3819. <td><b>'.get_lang('Missing').'</b></td>
  3820. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  3821. <td><div style="color:'.$missing_color.'">'.(($final_missing < 0) ? 0 : intval(
  3822. $final_missing
  3823. )).'</div></td>
  3824. </tr>
  3825. </table>';
  3826. if ($next == 0) {
  3827. $try = $try_hotspot;
  3828. $lp = $lp_hotspot;
  3829. $destinationid = $select_question_hotspot;
  3830. $url = $url_hotspot;
  3831. } else {
  3832. //show if no error
  3833. //echo 'no error';
  3834. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  3835. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  3836. }
  3837. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  3838. <p style="text-align:center">';
  3839. $message = '<p>'.get_lang('YourDelineation').'</p>';
  3840. $message .= $table_resume;
  3841. $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  3842. if ($organs_at_risk_hit > 0) {
  3843. $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
  3844. }
  3845. $message .= '<p>'.$comment.'</p>';
  3846. echo $message;
  3847. } else {
  3848. echo $hotspot_delineation_result[0]; //prints message
  3849. $from_database = 1; // the hotspot_solution.swf needs this variable
  3850. }
  3851. //save the score attempts
  3852. if (1) {
  3853. $final_answer = $hotspot_delineation_result[1]; //getting the answer 1 or 0 comes from exercise_submit_modal.php
  3854. if ($final_answer == 0) {
  3855. $questionScore = 0;
  3856. }
  3857. saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0, null, $updateResults); // we always insert the answer_id 1 = delineation
  3858. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  3859. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList(1), $hotspot_delineation_result[1], $exerciseResultCoordinates[$quesId], null, $updateResults);
  3860. } else {
  3861. if ($final_answer == 0) {
  3862. $questionScore = 0;
  3863. $answer = 0;
  3864. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, null, $updateResults);
  3865. if (is_array($exerciseResultCoordinates[$quesId])) {
  3866. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  3867. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), 0, $val, $updateResults);
  3868. }
  3869. }
  3870. } else {
  3871. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, null, $updateResults);
  3872. if (is_array($exerciseResultCoordinates[$quesId])) {
  3873. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  3874. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), $choice[$idx], $val, $updateResults);
  3875. }
  3876. }
  3877. }
  3878. }
  3879. $my_exe_id = $exeId;
  3880. }
  3881. }
  3882. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  3883. // We made an extra table for the answers
  3884. if ($show_result) {
  3885. //if ($origin != 'learnpath') {
  3886. echo '</table></td></tr>';
  3887. echo '<tr>
  3888. <td colspan="2">';
  3889. echo '<i>'.get_lang('HotSpot').'</i><br /><br />';
  3890. echo '<object type="application/x-shockwave-flash" data="'.api_get_path(
  3891. WEB_CODE_PATH
  3892. ).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS(
  3893. $questionId
  3894. ).'&exe_id='.$exeId.'&from_db=1" width="552" height="352">
  3895. <param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS(
  3896. $questionId
  3897. ).'&exe_id='.$exeId.'&from_db=1" />
  3898. </object>';
  3899. echo '</td>
  3900. </tr>';
  3901. //}
  3902. }
  3903. }
  3904. if ($origin != 'learnpath') {
  3905. if ($show_result) {
  3906. echo '</table>';
  3907. }
  3908. }
  3909. }
  3910. $totalWeighting += $questionWeighting;
  3911. // Store results directly in the database
  3912. // For all in one page exercises, the results will be
  3913. // stored by exercise_results.php (using the session)
  3914. if ($saved_results) {
  3915. if ($debug) {
  3916. error_log("Save question results: $saved_results");
  3917. error_log(print_r($choice, 1));
  3918. }
  3919. if (empty($choice)) {
  3920. $choice = 0;
  3921. }
  3922. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  3923. if ($choice != 0) {
  3924. $reply = array_keys($choice);
  3925. for ($i = 0; $i < sizeof($reply); $i++) {
  3926. $ans = $reply[$i];
  3927. saveQuestionAttempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id, $updateResults);
  3928. if ($debug) {
  3929. error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
  3930. }
  3931. }
  3932. } else {
  3933. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  3934. }
  3935. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  3936. if ($choice != 0) {
  3937. $reply = array_keys($choice);
  3938. if ($debug) {
  3939. error_log("reply ".print_r($reply, 1)."");
  3940. }
  3941. for ($i = 0; $i < sizeof($reply); $i++) {
  3942. $ans = $reply[$i];
  3943. saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id, $updateResults);
  3944. }
  3945. } else {
  3946. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  3947. }
  3948. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  3949. if ($choice != 0) {
  3950. $reply = array_keys($choice);
  3951. for ($i = 0; $i < sizeof($reply); $i++) {
  3952. $ans = $reply[$i];
  3953. saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id, $updateResults);
  3954. }
  3955. } else {
  3956. saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id, $updateResults);
  3957. }
  3958. } elseif ($answerType == MATCHING || $answerType == DRAGGABLE) {
  3959. if (isset($matching)) {
  3960. foreach ($matching as $j => $val) {
  3961. saveQuestionAttempt($questionScore, $val, $quesId, $exeId, $j, $this->id, $updateResults);
  3962. }
  3963. }
  3964. } elseif ($answerType == FREE_ANSWER) {
  3965. $answer = $choice;
  3966. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  3967. } elseif ($answerType == ORAL_EXPRESSION) {
  3968. $answer = $choice;
  3969. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults, $nano);
  3970. } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_IMAGE || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  3971. $answer = $choice;
  3972. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  3973. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  3974. } elseif ($answerType == HOT_SPOT) {
  3975. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  3976. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  3977. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  3978. saveExerciseAttemptHotspot($exeId, $quesId, $objAnswerTmp->getRealAnswerIdFromList($idx), $choice[$idx], $val, $updateResults, $this->id);
  3979. }
  3980. }
  3981. } else {
  3982. saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id, $updateResults);
  3983. }
  3984. }
  3985. if ($propagate_neg == 0 && $questionScore < 0) {
  3986. $questionScore = 0;
  3987. }
  3988. if ($saved_results) {
  3989. $stat_table = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  3990. $sql_update = 'UPDATE '.$stat_table.' SET exe_result = exe_result + '.floatval($questionScore).' WHERE exe_id = '.$exeId;
  3991. if ($debug) {
  3992. error_log($sql_update);
  3993. }
  3994. Database::query($sql_update);
  3995. }
  3996. $return_array = array(
  3997. 'score' => $questionScore,
  3998. 'weight' => $questionWeighting,
  3999. 'extra' => $extra_data,
  4000. 'open_question' => $arrques,
  4001. 'open_answer' => $arrans,
  4002. 'answer_type' => $answerType,
  4003. 'user_choices' => $choice,
  4004. );
  4005. return $return_array;
  4006. }
  4007. public function returnNotificationTag()
  4008. {
  4009. return array(
  4010. '{{ student.username }}',
  4011. '{{ student.firstname }}',
  4012. '{{ student.lastname }}',
  4013. '{{ exercise.title }}',
  4014. '{{ exercise.start_time }}',
  4015. '{{ exercise.end_time }}',
  4016. '{{ exercise.question_and_answer_ids }}',
  4017. '{{ exercise.assert_count }}'
  4018. );
  4019. }
  4020. /**
  4021. * @param $exeId
  4022. * @return bool
  4023. */
  4024. public function sendCustomNotification($exeId, $exerciseResult = array())
  4025. {
  4026. if ($this->emailAlert) {
  4027. // Getting attempt info
  4028. $trackExerciseInfo = ExerciseLib::get_exercise_track_exercise_info($exeId);
  4029. if (empty($trackExerciseInfo)) {
  4030. return false;
  4031. }
  4032. if (0) {
  4033. //if (!empty($this->emailNotificationTemplate)) {
  4034. $twig = new \Twig_Environment(new \Twig_Loader_String());
  4035. $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
  4036. $template = $this->emailNotificationTemplate;
  4037. } else {
  4038. global $app;
  4039. $twig = $app['twig'];
  4040. $template = 'default/mail/exercise/end_exercise_notification.tpl';
  4041. }
  4042. $userInfo = UserManager::get_user_info_by_id($trackExerciseInfo['exe_user_id']);
  4043. $courseInfo = api_get_course_info_by_id($trackExerciseInfo['c_id']);
  4044. $twig->addGlobal('student', $userInfo);
  4045. $twig->addGlobal('exercise', $this);
  4046. $twig->addGlobal('exercise.start_time', $trackExerciseInfo['start_time']);
  4047. $twig->addGlobal('exercise.end_time', $trackExerciseInfo['end_time']);
  4048. $twig->addGlobal('course', $courseInfo);
  4049. $resultInfo = array();
  4050. $resultInfoToString = null;
  4051. $countCorrectToString = null;
  4052. if (!empty($exerciseResult)) {
  4053. $countCorrect = array();
  4054. $countCorrect['correct'] = 0;
  4055. $countCorrect['total'] = 0;
  4056. $counter = 1;
  4057. foreach ($exerciseResult as $questionId => $result) {
  4058. $resultInfo[$questionId] = isset($result['details']['user_choices']) ? $result['details']['user_choices'] : null;
  4059. $correct = $result['score']['pass'] ? 1 : 0;
  4060. $countCorrect['correct'] += $correct;
  4061. $countCorrect['total'] = $counter;
  4062. $counter++;
  4063. }
  4064. if (!empty($resultInfo)) {
  4065. $resultInfoToString = json_encode($resultInfo);
  4066. }
  4067. if (!empty($countCorrect)) {
  4068. $countCorrectToString = json_encode($countCorrect);
  4069. }
  4070. }
  4071. $twig->addGlobal('question_and_answer_ids', $resultInfoToString);
  4072. $twig->addGlobal('asserts', $countCorrectToString);
  4073. if (api_get_session_id()) {
  4074. $teachers = CourseManager::get_coach_list_from_course_code($courseInfo['real_id'], api_get_session_id());
  4075. } else {
  4076. $teachers = CourseManager::get_teacher_list_from_course_code($courseInfo['real_id']);
  4077. }
  4078. try {
  4079. $twig->parse($twig->tokenize($template));
  4080. $content = $twig->render($template);
  4081. } catch (Twig_Error_Syntax $e) {
  4082. // $template contains one or more syntax errors
  4083. echo $e->getMessage();
  4084. }
  4085. // Student who finish the exercise
  4086. $subject = get_lang('ExerciseResult');
  4087. if (!empty($teachers)) {
  4088. foreach ($teachers as $user_id => $teacher_data) {
  4089. MessageManager::send_message_simple($user_id, $subject, $content);
  4090. }
  4091. }
  4092. }
  4093. }
  4094. /**
  4095. * Sends a notification when a user ends an examn
  4096. * @param array $question_list_answers
  4097. * @param string $origin
  4098. * @param int $exe_id
  4099. * @return null
  4100. */
  4101. public function sendNotificationForOpenQuestions($question_list_answers, $origin, $exe_id)
  4102. {
  4103. if ($this->emailAlert == false) {
  4104. return null;
  4105. }
  4106. // Email configuration settings
  4107. $course_info = api_get_course_info(api_get_course_id());
  4108. $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq().'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
  4109. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  4110. $msg = '<p>'.get_lang('OpenQuestionsAttempted').' :</p>
  4111. <p>'.get_lang('AttemptDetails').' : </p>
  4112. <table class="data_table">
  4113. <tr>
  4114. <td><h3>'.get_lang('CourseName').'</h3></td>
  4115. <td><h3>#course#</h3></td>
  4116. </tr>
  4117. <tr>
  4118. <td>'.get_lang('TestAttempted').'</span></td>
  4119. <td>#exercise#</td>
  4120. </tr>
  4121. <tr>
  4122. <td>'.get_lang('StudentName').'</td>
  4123. <td>#firstName# #lastName#</td>
  4124. </tr>
  4125. <tr>
  4126. <td>'.get_lang('StudentEmail').'</td>
  4127. <td>#mail#</td>
  4128. </tr>
  4129. </table>';
  4130. $open_question_list = null;
  4131. foreach ($question_list_answers as $item) {
  4132. $question = $item['question'];
  4133. $answer = $item['answer'];
  4134. $answer_type = $item['answer_type'];
  4135. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  4136. $open_question_list .= '<tr>
  4137. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  4138. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  4139. </tr>
  4140. <tr>
  4141. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  4142. <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
  4143. </tr>';
  4144. }
  4145. }
  4146. if (!empty($open_question_list)) {
  4147. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>
  4148. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  4149. $msg .= $open_question_list;
  4150. $msg .= '</table><br />';
  4151. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4152. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4153. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  4154. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  4155. $msg = str_replace("#course#", $course_info['name'], $msg1);
  4156. if ($origin != 'learnpath') {
  4157. $msg .= get_lang('ClickToCommentAndGiveFeedback').', <br />
  4158. <a href="#url#">#url#</a>';
  4159. }
  4160. $msg1 = str_replace("#url#", $url_email, $msg);
  4161. $mail_content = $msg1;
  4162. $subject = get_lang('OpenQuestionsAttempted');
  4163. if (api_get_session_id()) {
  4164. $teachers = CourseManager::get_coach_list_from_course_code($course_info['real_id'], api_get_session_id());
  4165. } else {
  4166. $teachers = CourseManager::get_teacher_list_from_course_code($course_info['real_id']);
  4167. }
  4168. if (!empty($teachers)) {
  4169. foreach ($teachers as $user_id => $teacher_data) {
  4170. MessageManager::send_message_simple($user_id, $subject, $mail_content);
  4171. }
  4172. }
  4173. }
  4174. }
  4175. public function sendNotificationForOralQuestions($question_list_answers, $origin, $exe_id)
  4176. {
  4177. if ($this->emailAlert == false) {
  4178. return null;
  4179. }
  4180. // Email configuration settings
  4181. $coursecode = api_get_course_id();
  4182. $course_info = api_get_course_info(api_get_course_id());
  4183. $url_email = api_get_path(WEB_CODE_PATH).'exercice/exercise_show.php?'.api_get_cidreq(
  4184. ).'&id_session='.api_get_session_id().'&id='.$exe_id.'&action=qualify';
  4185. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  4186. $oral_question_list = null;
  4187. foreach ($question_list_answers as $item) {
  4188. $question = $item['question'];
  4189. $answer = $item['answer'];
  4190. $answer_type = $item['answer_type'];
  4191. if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
  4192. $oral_question_list .= '<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3"><tr>
  4193. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  4194. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  4195. </tr>
  4196. <tr>
  4197. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  4198. <td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>
  4199. </tr></table>';
  4200. }
  4201. }
  4202. if (!empty($oral_question_list)) {
  4203. $msg = '<p>'.get_lang('OralQuestionsAttempted').' :</p>
  4204. <p>'.get_lang('AttemptDetails').' : </p>
  4205. <table class="data_table">
  4206. <tr>
  4207. <td><h3>'.get_lang('CourseName').'</h3></td>
  4208. <td><h3>#course#</h3></td>
  4209. </tr>
  4210. <tr>
  4211. <td>'.get_lang('TestAttempted').'</span></td>
  4212. <td>#exercise#</td>
  4213. </tr>
  4214. <tr>
  4215. <td>'.get_lang('StudentName').'</td>
  4216. <td>#firstName# #lastName#</td>
  4217. </tr>
  4218. <tr>
  4219. <td>'.get_lang('StudentEmail').'</td>
  4220. <td>#mail#</td>
  4221. </tr>
  4222. </table>';
  4223. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
  4224. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  4225. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  4226. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  4227. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  4228. $msg = str_replace("#course#", $course_info['name'], $msg1);
  4229. if ($origin != 'learnpath') {
  4230. $msg .= get_lang('ClickToCommentAndGiveFeedback').', <br />
  4231. <a href="#url#">#url#</a>';
  4232. }
  4233. $msg1 = str_replace("#url#", $url_email, $msg);
  4234. $mail_content = $msg1;
  4235. $subject = get_lang('OralQuestionsAttempted');
  4236. if (api_get_session_id()) {
  4237. $teachers = CourseManager::get_coach_list_from_course_code($course_info['real_id'], api_get_session_id());
  4238. } else {
  4239. $teachers = CourseManager::get_teacher_list_from_course_code($course_info['real_id']);
  4240. }
  4241. if (!empty($teachers)) {
  4242. foreach ($teachers as $user_id => $teacher_data) {
  4243. MessageManager::send_message_simple($user_id, $subject, $mail_content);
  4244. }
  4245. }
  4246. }
  4247. }
  4248. /**
  4249. * @param array $user_data
  4250. * @param string $start_date
  4251. * @param int $duration
  4252. * @return string
  4253. */
  4254. function show_exercise_result_header($user_data, $start_date = null, $duration = null)
  4255. {
  4256. $array = array();
  4257. if (!empty($user_data)) {
  4258. $array[] = array('title' => get_lang("User"), 'content' => $user_data);
  4259. }
  4260. if (!empty($this->description)) {
  4261. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  4262. }
  4263. if (!empty($start_date)) {
  4264. $array[] = array('title' => get_lang("StartDate"), 'content' => $start_date);
  4265. }
  4266. if (!empty($duration)) {
  4267. $array[] = array('title' => get_lang("Duration"), 'content' => $duration);
  4268. }
  4269. $html = Display::page_subheader(
  4270. Display::return_icon('quiz_big.png', get_lang('Result')).' '.$this->exercise.' : '.get_lang('Result')
  4271. );
  4272. $html .= Display::description($array);
  4273. return $html;
  4274. }
  4275. /**
  4276. * Create a quiz from quiz data
  4277. * @param string Title
  4278. * @param int Time before it expires (in minutes)
  4279. * @param int Type of exercise
  4280. * @param int Whether it's randomly picked questions (1) or not (0)
  4281. * @param int Whether the exercise is visible to the user (1) or not (0)
  4282. * @param int Whether the results are show to the user (0) or not (1)
  4283. * @param int Maximum number of attempts (0 if no limit)
  4284. * @param int Feedback type
  4285. * @todo this was function was added due the import exercise via CSV
  4286. * @return int New exercise ID
  4287. */
  4288. function create_quiz($title, $expired_time = 0, $type = 2, $random = 0, $active = 1, $results_disabled = 0, $max_attempt = 0, $feedback = 3) {
  4289. $this->updateTitle($title);
  4290. $this->updateActive($active);
  4291. $this->updateAttempts($max_attempt);
  4292. $this->updateFeedbackType($feedback);
  4293. $this->updateType($type);
  4294. $this->setRandom($random);
  4295. //$this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  4296. $this->updateResultsDisabled($results_disabled);
  4297. $this->updateExpiredTime($expired_time);
  4298. /*$this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  4299. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  4300. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  4301. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  4302. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  4303. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  4304. $this->updateCategories($form->getSubmitValue('category'));*/
  4305. $this->save();
  4306. $quiz_id = $this->selectId();
  4307. return $quiz_id;
  4308. }
  4309. function process_geometry()
  4310. {
  4311. }
  4312. /**
  4313. * Returns the exercise result
  4314. * @param int attempt id
  4315. * @return float exercise result
  4316. */
  4317. public function get_exercise_result($exe_id)
  4318. {
  4319. $result = array();
  4320. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  4321. $totalScore = 0;
  4322. if (!empty($track_exercise_info)) {
  4323. $objExercise = new Exercise();
  4324. $objExercise->read($track_exercise_info['exe_exo_id']);
  4325. if (!empty($track_exercise_info['data_tracking'])) {
  4326. $question_list = explode(',', $track_exercise_info['data_tracking']);
  4327. }
  4328. foreach ($question_list as $questionId) {
  4329. $question_result = $objExercise->manageAnswers(
  4330. $exe_id,
  4331. $questionId,
  4332. '',
  4333. 'exercise_show',
  4334. array(),
  4335. false,
  4336. true,
  4337. false
  4338. );
  4339. // $questionScore = $question_result['score'];
  4340. $totalScore += $question_result['score'];
  4341. }
  4342. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  4343. $totalScore = 0;
  4344. }
  4345. $result = array(
  4346. 'score' => $totalScore,
  4347. 'weight' => $track_exercise_info['exe_weighting']
  4348. );
  4349. }
  4350. return $result;
  4351. }
  4352. /**
  4353. * Checks if the exercise is visible due a lot of conditions - visibility, time limits, student attempts
  4354. *
  4355. * @param int $lp_id
  4356. * @param int $lp_item_id
  4357. * @param int $lp_item_view_id
  4358. * @param bool $filter_by_admin
  4359. * @return array
  4360. */
  4361. public function is_visible($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $filter_by_admin = true)
  4362. {
  4363. //1. By default the exercise is visible
  4364. $is_visible = true;
  4365. $message = null;
  4366. //1.1 Admins and teachers can access to the exercise
  4367. if ($filter_by_admin) {
  4368. if (api_is_platform_admin() || api_is_course_admin()) {
  4369. return array('value' => true, 'message' => '');
  4370. }
  4371. }
  4372. //Checking visibility in the item_property table
  4373. $visibility = api_get_item_visibility(api_get_course_info(), TOOL_QUIZ, $this->id, api_get_session_id());
  4374. if ($visibility == 0) {
  4375. $this->active = 0;
  4376. }
  4377. //2. If the exercise is not active
  4378. if (empty($lp_id)) {
  4379. //2.1 LP is OFF
  4380. if ($this->active == 0) {
  4381. return array(
  4382. 'value' => false,
  4383. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false)
  4384. );
  4385. }
  4386. } else {
  4387. //2.1 LP is loaded
  4388. if ($this->active == 0 AND !learnpath::is_lp_visible_for_student($lp_id, api_get_user_id())) {
  4389. return array(
  4390. 'value' => false,
  4391. 'message' => Display::return_message(get_lang('ExerciseNotFound'), 'warning', false)
  4392. );
  4393. }
  4394. }
  4395. //3. We check if the time limits are on
  4396. $limit_time_exists = ((!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') || (!empty($this->end_time) && $this->end_time != '0000-00-00 00:00:00')) ? true : false;
  4397. if ($limit_time_exists) {
  4398. $time_now = time();
  4399. if (!empty($this->start_time) && $this->start_time != '0000-00-00 00:00:00') {
  4400. $is_visible = (($time_now - api_strtotime($this->start_time, 'UTC')) > 0) ? true : false;
  4401. }
  4402. if ($is_visible == false) {
  4403. $message = sprintf(get_lang('ExerciseAvailableFromX'), api_convert_and_format_date($this->start_time));
  4404. }
  4405. if ($is_visible == true) {
  4406. if ($this->end_time != '0000-00-00 00:00:00') {
  4407. $is_visible = ((api_strtotime($this->end_time, 'UTC') > $time_now) > 0) ? true : false;
  4408. if ($is_visible == false) {
  4409. $message = sprintf(
  4410. get_lang('ExerciseAvailableUntilX'),
  4411. api_convert_and_format_date($this->end_time)
  4412. );
  4413. }
  4414. }
  4415. }
  4416. if ($is_visible == false && $this->start_time != '0000-00-00 00:00:00' && $this->end_time != '0000-00-00 00:00:00') {
  4417. $message = sprintf(
  4418. get_lang('ExerciseWillBeActivatedFromXToY'),
  4419. api_convert_and_format_date($this->start_time),
  4420. api_convert_and_format_date($this->end_time)
  4421. );
  4422. }
  4423. }
  4424. // 4. We check if the student have attempts
  4425. if ($is_visible) {
  4426. if ($this->selectAttempts() > 0) {
  4427. $attempt_count = get_attempt_count_not_finished(
  4428. api_get_user_id(),
  4429. $this->id,
  4430. $lp_id,
  4431. $lp_item_id,
  4432. $lp_item_view_id
  4433. );
  4434. if ($attempt_count >= $this->selectAttempts()) {
  4435. $message = sprintf(get_lang('ReachedMaxAttempts'), $this->name, $this->selectAttempts());
  4436. $is_visible = false;
  4437. }
  4438. }
  4439. }
  4440. if (!empty($message)) {
  4441. $message = Display :: return_message($message, 'warning', false);
  4442. }
  4443. return array('value' => $is_visible, 'message' => $message);
  4444. }
  4445. /**
  4446. * @return bool
  4447. */
  4448. function added_in_lp()
  4449. {
  4450. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  4451. $sql = "SELECT max_score FROM $TBL_LP_ITEM WHERE c_id = ".$this->course_id." AND item_type = '".TOOL_QUIZ."' AND path = '".$this->id."'";
  4452. $result = Database::query($sql);
  4453. if (Database::num_rows($result) > 0) {
  4454. return true;
  4455. }
  4456. return false;
  4457. }
  4458. /**
  4459. * Returns an array with the media list
  4460. * @param array question list
  4461. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  4462. * <code>
  4463. * array (size=2)
  4464. * 999 =>
  4465. * array (size=3)
  4466. * 0 => int 7
  4467. * 1 => int 6
  4468. * 2 => int 3254
  4469. * 100 =>
  4470. * array (size=1)
  4471. * 0 => int 5
  4472. * </code>
  4473. * @return array
  4474. */
  4475. private function setMediaList($questionList)
  4476. {
  4477. $mediaList= array();
  4478. if (!empty($questionList)) {
  4479. foreach ($questionList as $questionId) {
  4480. $objQuestionTmp = Question::read($questionId);
  4481. // If a media question exists
  4482. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  4483. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  4484. } else {
  4485. // Always the last item
  4486. $mediaList[999][] = $objQuestionTmp->id;
  4487. }
  4488. }
  4489. }
  4490. $this->mediaList = $mediaList;
  4491. }
  4492. /**
  4493. * Returns an array with this form
  4494. * @example
  4495. * <code>
  4496. * array (size=3)
  4497. 999 =>
  4498. array (size=3)
  4499. 0 => int 3422
  4500. 1 => int 3423
  4501. 2 => int 3424
  4502. 100 =>
  4503. array (size=2)
  4504. 0 => int 3469
  4505. 1 => int 3470
  4506. 101 =>
  4507. array (size=1)
  4508. 0 => int 3482
  4509. * </code>
  4510. * The array inside the key 999 means the question list that belongs to the media id = 999,
  4511. * this case is special because 999 means "no media".
  4512. * @return array
  4513. */
  4514. public function getMediaList()
  4515. {
  4516. return $this->mediaList;
  4517. }
  4518. /**
  4519. * Is media question activated?
  4520. * @return bool
  4521. */
  4522. public function mediaIsActivated()
  4523. {
  4524. $mediaQuestions = $this->getMediaList();
  4525. $active = false;
  4526. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  4527. $media_count = count($mediaQuestions);
  4528. if ($media_count > 1) {
  4529. return true;
  4530. } elseif ($media_count == 1) {
  4531. if (isset($mediaQuestions[999])) {
  4532. return false;
  4533. } else {
  4534. return true;
  4535. }
  4536. }
  4537. }
  4538. return $active;
  4539. }
  4540. /**
  4541. * Gets question list from the exercise
  4542. *
  4543. * @return array
  4544. */
  4545. public function getQuestionList()
  4546. {
  4547. return $this->questionList;
  4548. }
  4549. /**
  4550. * Question list with medias compressed like this
  4551. * @example
  4552. * <code>
  4553. * array(
  4554. * question_id_1,
  4555. * question_id_2,
  4556. * media_id, <- this media id contains question ids
  4557. * question_id_3,
  4558. * )
  4559. * </code>
  4560. * @return array
  4561. */
  4562. public function getQuestionListWithMediasCompressed()
  4563. {
  4564. return $this->questionList;
  4565. }
  4566. /**
  4567. * Question list with medias uncompressed like this
  4568. * @example
  4569. * <code>
  4570. * array(
  4571. * question_id,
  4572. * question_id,
  4573. * question_id, <- belongs to a media id
  4574. * question_id, <- belongs to a media id
  4575. * question_id,
  4576. * )
  4577. * </code>
  4578. * @return array
  4579. */
  4580. public function getQuestionListWithMediasUncompressed()
  4581. {
  4582. return $this->questionListUncompressed;
  4583. }
  4584. /**
  4585. * Sets the question list when the exercise->read() is executed
  4586. */
  4587. public function setQuestionList()
  4588. {
  4589. // Getting question list.
  4590. $questionList = $this->selectQuestionList(true);
  4591. $this->setMediaList($questionList);
  4592. $this->questionList = $this->transformQuestionListWithMedias($questionList, false);
  4593. $this->questionListUncompressed = $this->transformQuestionListWithMedias($questionList, true);
  4594. }
  4595. /**
  4596. *
  4597. * @params array question list
  4598. * @params bool expand or not question list (true show all questions, false show media question id instead of the question ids)
  4599. *
  4600. **/
  4601. public function transformQuestionListWithMedias($question_list, $expand_media_questions = false)
  4602. {
  4603. $new_question_list = array();
  4604. if (!empty($question_list)) {
  4605. $media_questions = $this->getMediaList();
  4606. $media_active = $this->mediaIsActivated($media_questions);
  4607. if ($media_active) {
  4608. $counter = 1;
  4609. foreach ($question_list as $question_id) {
  4610. $add_question = true;
  4611. foreach ($media_questions as $media_id => $question_list_in_media) {
  4612. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  4613. $add_question = false;
  4614. if (!in_array($media_id, $new_question_list)) {
  4615. $new_question_list[$counter] = $media_id;
  4616. $counter++;
  4617. }
  4618. break;
  4619. }
  4620. }
  4621. if ($add_question) {
  4622. $new_question_list[$counter] = $question_id;
  4623. $counter++;
  4624. }
  4625. }
  4626. if ($expand_media_questions) {
  4627. $media_key_list = array_keys($media_questions);
  4628. foreach ($new_question_list as &$question_id) {
  4629. if (in_array($question_id, $media_key_list)) {
  4630. $question_id = $media_questions[$question_id];
  4631. }
  4632. }
  4633. $new_question_list = ArrayClass::array_flatten($new_question_list);
  4634. }
  4635. } else {
  4636. $new_question_list = $question_list;
  4637. }
  4638. }
  4639. return $new_question_list;
  4640. }
  4641. /**
  4642. * @param int $exe_id
  4643. * @return array
  4644. */
  4645. public function getStatTrackExerciseInfoByExeId($exe_id)
  4646. {
  4647. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  4648. $exe_id = intval($exe_id);
  4649. $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
  4650. $result = Database::query($sql_track);
  4651. $new_array = array();
  4652. if (Database::num_rows($result) > 0) {
  4653. $new_array = Database::fetch_array($result, 'ASSOC');
  4654. $new_array['duration'] = null;
  4655. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  4656. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  4657. if (!empty($start_date) && !empty($end_date)) {
  4658. $start_date = api_strtotime($start_date, 'UTC');
  4659. $end_date = api_strtotime($end_date, 'UTC');
  4660. if ($start_date && $end_date) {
  4661. $mytime = $end_date - $start_date;
  4662. $new_learnpath_item = new learnpathItem(null);
  4663. $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
  4664. $h = get_lang('h');
  4665. $time_attemp = str_replace('NaN', '00'.$h.'00\'00"', $time_attemp);
  4666. $new_array['duration'] = $time_attemp;
  4667. }
  4668. }
  4669. }
  4670. return $new_array;
  4671. }
  4672. /**
  4673. * @param int $exe_id
  4674. * @param int $question_id
  4675. * @param string $action
  4676. */
  4677. public function edit_question_to_remind($exe_id, $question_id, $action = 'add')
  4678. {
  4679. $exercise_info = self::getStatTrackExerciseInfoByExeId($exe_id);
  4680. $question_id = intval($question_id);
  4681. $exe_id = intval($exe_id);
  4682. $track_exercises = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  4683. if ($exercise_info) {
  4684. if (empty($exercise_info['questions_to_check'])) {
  4685. if ($action == 'add') {
  4686. $sql = "UPDATE $track_exercises SET questions_to_check = '$question_id' WHERE exe_id = $exe_id ";
  4687. Database::query($sql);
  4688. }
  4689. } else {
  4690. $remind_list = explode(',', $exercise_info['questions_to_check']);
  4691. $remind_list_string = '';
  4692. if ($action == 'add') {
  4693. if (!in_array($question_id, $remind_list)) {
  4694. $remind_list[] = $question_id;
  4695. if (!empty($remind_list)) {
  4696. sort($remind_list);
  4697. array_filter($remind_list);
  4698. }
  4699. $remind_list_string = implode(',', $remind_list);
  4700. }
  4701. } elseif ($action == 'delete') {
  4702. if (!empty($remind_list)) {
  4703. if (in_array($question_id, $remind_list)) {
  4704. $remind_list = array_flip($remind_list);
  4705. unset($remind_list[$question_id]);
  4706. $remind_list = array_flip($remind_list);
  4707. if (!empty($remind_list)) {
  4708. sort($remind_list);
  4709. array_filter($remind_list);
  4710. $remind_list_string = implode(',', $remind_list);
  4711. }
  4712. }
  4713. }
  4714. }
  4715. $remind_list_string = Database::escape_string($remind_list_string);
  4716. $sql = "UPDATE $track_exercises SET questions_to_check = '$remind_list_string' WHERE exe_id = $exe_id ";
  4717. Database::query($sql);
  4718. }
  4719. }
  4720. }
  4721. /**
  4722. * @param string $answer
  4723. * @return mixed
  4724. */
  4725. public function fill_in_blank_answer_to_array($answer)
  4726. {
  4727. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  4728. $teacher_answer_list = $teacher_answer_list[0];
  4729. return $teacher_answer_list;
  4730. }
  4731. /**
  4732. * @param $answer
  4733. * @return string
  4734. */
  4735. public function fill_in_blank_answer_to_string($answer)
  4736. {
  4737. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  4738. $result = '';
  4739. if (!empty($teacher_answer_list)) {
  4740. foreach ($teacher_answer_list as $teacher_item) {
  4741. $value = null;
  4742. //Cleaning student answer list
  4743. $value = strip_tags($teacher_item);
  4744. $value = api_substr($value, 1, api_strlen($value) - 2);
  4745. $value = explode('/', $value);
  4746. if (!empty($value[0])) {
  4747. $value = trim($value[0]);
  4748. $value = str_replace('&nbsp;', '', $value);
  4749. $result .= $value;
  4750. }
  4751. }
  4752. }
  4753. return $result;
  4754. }
  4755. /**
  4756. * Returns a time limit message
  4757. * @return string
  4758. */
  4759. public function returnTimeLeftDiv()
  4760. {
  4761. $message = Display::return_message(
  4762. get_lang('ReachedTimeLimit'), 'warning' ).' '.sprintf(get_lang('YouWillBeRedirectedInXSeconds'),
  4763. '<span id="counter_to_redirect" class="red_alert"></span>'
  4764. );
  4765. $html = '<div id="clock_warning" style="display:none">'.$message.'</div>';
  4766. $html .= '<div class="row"><div class="pull-right"><div id="exercise_clock_warning" class="well count_down"></div></div></div>';
  4767. return $html;
  4768. }
  4769. /**
  4770. * Get question list (including question ids of the media)
  4771. * @return int
  4772. */
  4773. public function getCountUncompressedQuestionList()
  4774. {
  4775. $question_count = 0;
  4776. $questionList = $this->questionList;
  4777. if (!empty($questionList)) {
  4778. $question_count = count($questionList);
  4779. }
  4780. return $question_count;
  4781. }
  4782. /**
  4783. * Get question list (excluding question ids of the media)
  4784. * @return int
  4785. */
  4786. public function getCountCompressedQuestionList()
  4787. {
  4788. $mediaQuestions = $this->getMediaList();
  4789. $questionCount = 0;
  4790. foreach ($mediaQuestions as $mediaKey => $questionList) {
  4791. if ($mediaKey == 999) {
  4792. $questionCount += count($questionList);
  4793. } else {
  4794. $questionCount++;
  4795. }
  4796. }
  4797. return $questionCount;
  4798. }
  4799. /**
  4800. * Gets the position of a questionId in the question list
  4801. * @param $questionId
  4802. * @return int
  4803. */
  4804. public function getPositionInCompressedQuestionList($questionId)
  4805. {
  4806. $questionList = $this->getQuestionListWithMediasCompressed();
  4807. $mediaQuestions = $this->getMediaList();
  4808. $position = 1;
  4809. foreach ($questionList as $id) {
  4810. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  4811. $mediaQuestionList = $mediaQuestions[$id];
  4812. if (in_array($questionId, $mediaQuestionList)) {
  4813. return $position;
  4814. } else {
  4815. $position++;
  4816. }
  4817. } else {
  4818. if ($id == $questionId) {
  4819. return $position;
  4820. } else {
  4821. $position++;
  4822. }
  4823. }
  4824. }
  4825. return 1;
  4826. }
  4827. /**
  4828. * Get question list (excluding question ids of the media)
  4829. * @return int
  4830. */
  4831. public function getPositionOfQuestionInCompresedQuestionList()
  4832. {
  4833. $mediaQuestions = $this->getMediaList();
  4834. $questionCount = 0;
  4835. foreach ($mediaQuestions as $mediaKey => $questionList) {
  4836. if ($mediaKey == 999) {
  4837. $questionCount += count($questionList);
  4838. } else {
  4839. $questionCount++;
  4840. }
  4841. }
  4842. return $questionCount;
  4843. }
  4844. /**
  4845. * @return array
  4846. */
  4847. function get_exercise_list_ordered()
  4848. {
  4849. $table_exercise_order = Database::get_course_table(TABLE_QUIZ_ORDER);
  4850. $course_id = api_get_course_int_id();
  4851. $session_id = api_get_session_id();
  4852. $sql = "SELECT exercise_id, exercise_order FROM $table_exercise_order
  4853. WHERE c_id = $course_id AND session_id = $session_id ORDER BY exercise_order";
  4854. $result = Database::query($sql);
  4855. $list = array();
  4856. if (Database::num_rows($result)) {
  4857. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4858. $list[$row['exercise_order']] = $row['exercise_id'];
  4859. }
  4860. }
  4861. return $list;
  4862. }
  4863. /**
  4864. * @return bool
  4865. */
  4866. public function get_categories_in_exercise()
  4867. {
  4868. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  4869. if (!empty($this->id)) {
  4870. $sql = "SELECT * FROM $table WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  4871. $result = Database::query($sql);
  4872. $list = array();
  4873. if (Database::num_rows($result)) {
  4874. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4875. $list[$row['category_id']] = $row;
  4876. }
  4877. return $list;
  4878. }
  4879. }
  4880. return false;
  4881. }
  4882. /**
  4883. * @param null $order
  4884. * @return bool
  4885. */
  4886. public function get_categories_with_name_in_exercise($order = null)
  4887. {
  4888. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  4889. $table_category = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  4890. $sql = "SELECT * FROM $table qc INNER JOIN $table_category c ON (category_id = c.iid)
  4891. WHERE exercise_id = {$this->id} AND qc.c_id = {$this->course_id} ";
  4892. if (!empty($order)) {
  4893. $sql .= "ORDER BY $order ";
  4894. }
  4895. $result = Database::query($sql);
  4896. if (Database::num_rows($result)) {
  4897. while ($row = Database::fetch_array($result, 'ASSOC')) {
  4898. $list[$row['category_id']] = $row;
  4899. }
  4900. return $list;
  4901. }
  4902. return false;
  4903. }
  4904. /**
  4905. * Get total number of question that will be parsed when using the category/exercise
  4906. */
  4907. public function getNumberQuestionExerciseCategory()
  4908. {
  4909. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  4910. if (!empty($this->id)) {
  4911. $sql = "SELECT SUM(count_questions) count_questions FROM $table
  4912. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  4913. $result = Database::query($sql);
  4914. if (Database::num_rows($result)) {
  4915. $row = Database::fetch_array($result);
  4916. return $row['count_questions'];
  4917. }
  4918. }
  4919. return 0;
  4920. }
  4921. /**
  4922. * Save categories in the TABLE_QUIZ_REL_CATEGORY table
  4923. * @param array $categories
  4924. */
  4925. public function save_categories_in_exercise($categories)
  4926. {
  4927. if (!empty($categories) && !empty($this->id)) {
  4928. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  4929. $sql = "DELETE FROM $table WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  4930. Database::query($sql);
  4931. if (!empty($categories)) {
  4932. foreach ($categories as $category_id => $count_questions) {
  4933. $params = array(
  4934. 'c_id' => $this->course_id,
  4935. 'exercise_id' => $this->id,
  4936. 'category_id' => $category_id,
  4937. 'count_questions' => $count_questions
  4938. );
  4939. Database::insert($table, $params);
  4940. }
  4941. }
  4942. }
  4943. }
  4944. /**
  4945. * Returns a HTML link when the exercise ends (exercise result page)
  4946. * @return string
  4947. */
  4948. public function returnEndButtonHTML()
  4949. {
  4950. $endButtonSetting = $this->selectEndButton();
  4951. $html = '';
  4952. switch ($endButtonSetting) {
  4953. case '0':
  4954. $html = Display::url(get_lang('ReturnToCourseHomepage'), api_get_course_url(), array('class' => 'btn btn-large'));
  4955. break;
  4956. case '1':
  4957. $html = Display::url(get_lang('ReturnToExerciseList'), api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq(), array('class' => 'btn btn-large'));
  4958. break;
  4959. case '2':
  4960. global $app;
  4961. $url = $app['url_generator']->generate('admin_logout');
  4962. $html = Display::url(get_lang('Logout'), $url, array('class' => 'btn btn-large'));
  4963. break;
  4964. }
  4965. return $html;
  4966. }
  4967. /**
  4968. * Gets a list of numbers with links to the questions, like a pagination. If there are categories associated,
  4969. * the list is organized by categories.
  4970. *
  4971. * @param int $exe_id
  4972. * @param array $questionList
  4973. * @param array $questionListFlatten
  4974. * @param array $remindList
  4975. * @param int $reminder
  4976. * @param array $remindQuestionId
  4977. * @param string $url
  4978. * @param int $current_question
  4979. * @return string
  4980. */
  4981. public function getProgressPagination($exe_id, $questionList, $questionListFlatten, $remindList, $reminder, $remindQuestionId, $url, $current_question)
  4982. {
  4983. $exercise_result = getAnsweredQuestionsFromAttempt($exe_id, $this);
  4984. $fixedRemindList = array();
  4985. if (!empty($remindList)) {
  4986. foreach ($questionListFlatten as $questionId) {
  4987. if (in_array($questionId, $remindList)) {
  4988. $fixedRemindList[] = $questionId;
  4989. }
  4990. }
  4991. }
  4992. if (isset($reminder) && $reminder == 2) {
  4993. $values = array_flip($questionListFlatten);
  4994. if (!empty($current_question)) {
  4995. $current_question = isset($values[$remindQuestionId]) ? $values[$remindQuestionId] + 1 : $values[$fixedRemindList[0]] +1;
  4996. }
  4997. }
  4998. $categoryList = Session::read('categoryList');
  4999. $categoryList = null;
  5000. if (empty($categoryList)) {
  5001. $categoryList = $this->getListOfCategoriesWithQuestionForTest();
  5002. Session::write('categoryList', $categoryList);
  5003. }
  5004. //var_dump($categoryList);
  5005. $html = '<div class="row">';
  5006. $html .= '<div class="span2">';
  5007. $reviewAnswerLabel = null;
  5008. if ($this->review_answers) {
  5009. $reviewAnswerLabel = Display::label(get_lang('ToReview'), 'warning').'<br />';
  5010. }
  5011. $currentAnswerLabel = null;
  5012. if (!empty($current_question)) {
  5013. $currentAnswerLabel = Display::label(get_lang('CurrentQuestion'), 'info');
  5014. }
  5015. $html .= Display::label(get_lang('Answered'), 'success').'<br />'.Display::label(get_lang('Unanswered')).'<br />'.
  5016. $reviewAnswerLabel.$currentAnswerLabel;
  5017. $html .= '</div>';
  5018. $conditions = array();
  5019. $conditions[] = array("class" => 'answered', 'items' => $exercise_result);
  5020. $conditions[] = array("class" => 'remind', 'mode' => 'overwrite', 'items' => $remindList);
  5021. $link = $url.'&num=';
  5022. $html .= '<div class="span10">';
  5023. if (!empty($categoryList)) {
  5024. $html .= $this->progressExercisePaginationBarWithCategories($categoryList, $current_question, $conditions, $link);
  5025. } else {
  5026. $html .= $this->progressExercisePaginationBar($questionList, $current_question, $conditions, $link);
  5027. }
  5028. $html .= '</div>';
  5029. $html .= '</div>';
  5030. return $html;
  5031. }
  5032. /**
  5033. * @param array media question array
  5034. * @return array question list (flatten not grouped by Medias)
  5035. */
  5036. public function getListOfCategoriesWithQuestionForTest()
  5037. {
  5038. $newMediaList = array();
  5039. $mediaQuestions = $this->getMediaList();
  5040. foreach ($mediaQuestions as $mediaId => $questionMediaList) {
  5041. foreach ($questionMediaList as $questionId) {
  5042. $newMediaList[$questionId] = $mediaId;
  5043. }
  5044. }
  5045. $categoryList = $this->categoryWithQuestionList;
  5046. $categoriesWithQuestion = array();
  5047. foreach ($categoryList as $categoryId => $category) {
  5048. $categoriesWithQuestion[$categoryId] = $category['category'];
  5049. $categoriesWithQuestion[$categoryId]['question_list'] = $category['question_list'];
  5050. if (!empty($newMediaList)) {
  5051. foreach ($category['question_list'] as $questionId) {
  5052. if (isset($newMediaList[$questionId])) {
  5053. $categoriesWithQuestion[$categoryId]['media_question'] = $newMediaList[$questionId];
  5054. } else {
  5055. $categoriesWithQuestion[$categoryId]['media_question'] = 999;
  5056. }
  5057. }
  5058. }
  5059. }
  5060. return $categoriesWithQuestion;
  5061. }
  5062. public function progressExercisePaginationBar($questionList, $currentQuestion, $conditions, $link)
  5063. {
  5064. $mediaQuestions = $this->getMediaList();
  5065. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  5066. $counter = 0;
  5067. $nextValue = 0;
  5068. $wasMedia = false;
  5069. $before = 0;
  5070. $counterNoMedias = 0;
  5071. foreach ($questionList as $questionId) {
  5072. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  5073. if (!empty($nextValue)) {
  5074. if ($wasMedia) {
  5075. $nextValue = $nextValue - $before + 1;
  5076. }
  5077. }
  5078. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  5079. $fixedValue = $counterNoMedias;
  5080. $html .= Display::progressPaginationBar(
  5081. $nextValue,
  5082. $mediaQuestions[$questionId],
  5083. $currentQuestion,
  5084. $fixedValue,
  5085. $conditions,
  5086. $link,
  5087. true,
  5088. true
  5089. );
  5090. $counter += count($mediaQuestions[$questionId]) - 1 ;
  5091. $before = count($questionList);
  5092. $wasMedia = true;
  5093. $nextValue += count($questionList);
  5094. } else {
  5095. $html .= Display::parsePaginationItem($questionId, $isCurrent, $conditions, $link, $counter);
  5096. $counter++;
  5097. $nextValue++;
  5098. $wasMedia = false;
  5099. }
  5100. $counterNoMedias++;
  5101. }
  5102. $html .= '</ul></div>';
  5103. return $html;
  5104. }
  5105. function getFirstParent($catId)
  5106. {
  5107. global $app;
  5108. $em = $app['orm.em'];
  5109. /** @var Gedmo\Tree\Entity\Repository\NestedTreeRepository $repo */
  5110. $repo = $em->getRepository('Entity\CQuizCategory');
  5111. /** @var \Entity\CQuizCategory $category */
  5112. $category = $em->find('Entity\CQuizCategory', $catId);
  5113. $path = $repo->getPath($category);
  5114. return $path;
  5115. }
  5116. /**
  5117. * Shows a list of numbers that represents the question to answer in a exercise
  5118. *
  5119. * @param array $categories
  5120. * @param int $current
  5121. * @param array $conditions
  5122. * @param string $link
  5123. * @return string
  5124. */
  5125. public function progressExercisePaginationBarWithCategories($categories, $current, $conditions = array(), $link = null)
  5126. {
  5127. $html = null;
  5128. $counterNoMedias = 0;
  5129. $nextValue = 0;
  5130. $wasMedia = false;
  5131. $before = 0;
  5132. if (!empty($categories)) {
  5133. $newCategoryList = array();
  5134. /*var_dump($categories);
  5135. foreach ($categories as $category) {
  5136. var_dump($this->getFirstParent($category['id']));
  5137. $newCategoryList = $category;
  5138. foreach ($categories as $category) {
  5139. foreach ($categories as $category) {
  5140. }
  5141. }
  5142. }*/
  5143. foreach ($categories as $category) {
  5144. $questionList = $category['question_list'];
  5145. // Check if in this category there questions added in a media
  5146. $mediaQuestionId = $category['media_question'];
  5147. $isMedia = false;
  5148. $fixedValue = null;
  5149. // Media exists!
  5150. if ($mediaQuestionId != 999) {
  5151. $isMedia = true;
  5152. $fixedValue = $counterNoMedias;
  5153. }
  5154. $categoryName = $category['name'];
  5155. if (isset($category['parent_info'])) {
  5156. $categoryName = $category['parent_info']['title'];
  5157. }
  5158. $html .= '<div class="row">';
  5159. $html .= '<div class="span2">'.$categoryName.'</div>';
  5160. $html .= '<div class="span8">';
  5161. if (!empty($nextValue)) {
  5162. if ($wasMedia) {
  5163. $nextValue = $nextValue - $before + 1;
  5164. }
  5165. }
  5166. $html .= Display::progressPaginationBar(
  5167. $nextValue,
  5168. $questionList,
  5169. $current,
  5170. $fixedValue,
  5171. $conditions,
  5172. $link,
  5173. $isMedia,
  5174. true
  5175. );
  5176. $html .= '</div>';
  5177. $html .= '</div>';
  5178. if ($mediaQuestionId == 999) {
  5179. $counterNoMedias += count($questionList);
  5180. } else {
  5181. $counterNoMedias++;
  5182. }
  5183. $nextValue += count($questionList);
  5184. $before = count($questionList);
  5185. if ($mediaQuestionId != 999) {
  5186. $wasMedia = true;
  5187. } else {
  5188. $wasMedia = false;
  5189. }
  5190. }
  5191. }
  5192. return $html;
  5193. }
  5194. /**
  5195. * Renders a question list
  5196. *
  5197. * @param array $questionList (with media questions compressed)
  5198. * @param int $currentQuestion
  5199. * @param array $exerciseResult
  5200. * @param array $attemptList
  5201. * @param array $remindList
  5202. */
  5203. public function renderQuestionList($questionList, $currentQuestion, $exerciseResult, $attemptList, $remindList)
  5204. {
  5205. $mediaQuestions = $this->getMediaList();
  5206. $i = 0;
  5207. // Normal question list render (medias compressed)
  5208. foreach ($questionList as $questionId) {
  5209. $i++;
  5210. // For sequential exercises
  5211. if ($this->type == ONE_PER_PAGE) {
  5212. // If it is not the right question, goes to the next loop iteration
  5213. if ($currentQuestion != $i) {
  5214. continue;
  5215. } else {
  5216. if ($this->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  5217. // if the user has already answered this question
  5218. if (isset($exerciseResult[$questionId])) {
  5219. Display::display_normal_message(get_lang('AlreadyAnswered'));
  5220. break;
  5221. }
  5222. }
  5223. }
  5224. }
  5225. // The $questionList contains the media id we check if this questionId is a media question type
  5226. if (isset($mediaQuestions[$questionId]) && $mediaQuestions[$questionId] != 999) {
  5227. // The question belongs to a media
  5228. $mediaQuestionList = $mediaQuestions[$questionId];
  5229. $objQuestionTmp = Question::read($questionId);
  5230. $counter = 1;
  5231. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  5232. echo $objQuestionTmp->show_media_content();
  5233. $countQuestionsInsideMedia = count($mediaQuestionList);
  5234. // Show questions that belongs to a media
  5235. if (!empty($mediaQuestionList)) {
  5236. // In order to parse media questions we use letters a, b, c, etc.
  5237. $letterCounter = 97;
  5238. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  5239. $isLastQuestionInMedia = false;
  5240. if ($counter == $countQuestionsInsideMedia) {
  5241. $isLastQuestionInMedia = true;
  5242. }
  5243. $this->renderQuestion(
  5244. $questionIdInsideMedia,
  5245. $attemptList,
  5246. $remindList,
  5247. chr($letterCounter),
  5248. $currentQuestion,
  5249. $mediaQuestionList,
  5250. $isLastQuestionInMedia,
  5251. $questionList
  5252. );
  5253. $letterCounter++;
  5254. $counter++;
  5255. }
  5256. }
  5257. } else {
  5258. $this->renderQuestion(
  5259. $questionId,
  5260. $attemptList,
  5261. $remindList,
  5262. $i,
  5263. $currentQuestion,
  5264. null,
  5265. null,
  5266. $questionList
  5267. );
  5268. $i++;
  5269. }
  5270. } else {
  5271. // Normal question render.
  5272. $this->renderQuestion($questionId, $attemptList, $remindList, $i, $currentQuestion, null, null, $questionList);
  5273. }
  5274. // For sequential exercises.
  5275. if ($this->type == ONE_PER_PAGE) {
  5276. // quits the loop
  5277. break;
  5278. }
  5279. }
  5280. // end foreach()
  5281. if ($this->type == ALL_ON_ONE_PAGE) {
  5282. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  5283. echo Display::div($exercise_actions, array('class'=>'exercise_actions'));
  5284. }
  5285. }
  5286. /**
  5287. * @param int $questionId
  5288. * @param array $attemptList
  5289. * @param array $remindList
  5290. * @param int $i
  5291. * @param int $current_question
  5292. * @param array $questions_in_media
  5293. * @param bool $last_question_in_media
  5294. * @param array $realQuestionList
  5295. * @param bool $generateJS
  5296. * @return null
  5297. */
  5298. public function renderQuestion(
  5299. $questionId,
  5300. $attemptList,
  5301. $remindList,
  5302. $i,
  5303. $current_question,
  5304. $questions_in_media = array(),
  5305. $last_question_in_media = false,
  5306. $realQuestionList,
  5307. $generateJS = true
  5308. ) {
  5309. // With this option on the question is loaded via AJAX
  5310. //$generateJS = true;
  5311. //$this->loadQuestionAJAX = true;
  5312. if ($generateJS && $this->loadQuestionAJAX) {
  5313. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId;
  5314. $params = array(
  5315. 'questionId' => $questionId,
  5316. 'attemptList'=> $attemptList,
  5317. 'remindList' => $remindList,
  5318. 'i' => $i,
  5319. 'current_question' => $current_question,
  5320. 'questions_in_media' => $questions_in_media,
  5321. 'last_question_in_media' => $last_question_in_media
  5322. );
  5323. $params = json_encode($params);
  5324. $script = '<script>
  5325. $(function(){
  5326. var params = '.$params.';
  5327. $.ajax({
  5328. type: "GET",
  5329. async: false,
  5330. data: params,
  5331. url: "'.$url.'",
  5332. success: function(return_value) {
  5333. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  5334. }
  5335. });
  5336. });
  5337. </script>
  5338. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  5339. echo $script;
  5340. } else {
  5341. global $origin;
  5342. $question_obj = Question::read($questionId);
  5343. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  5344. $remind_highlight = null;
  5345. //Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  5346. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  5347. $remind_highlight = 'no_remind_highlight';
  5348. if (in_array($question_obj->type, Question::question_type_no_review())) {
  5349. return null;
  5350. }
  5351. }
  5352. $attributes = array('id' =>'remind_list['.$questionId.']');
  5353. if (is_array($remindList) && in_array($questionId, $remindList)) {
  5354. $attributes['checked'] = 1;
  5355. $remind_highlight = ' remind_highlight ';
  5356. }
  5357. // Showing the question
  5358. $exercise_actions = null;
  5359. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  5360. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  5361. // Shows the question + possible answers
  5362. echo ExerciseLib::showQuestion($question_obj, false, $origin, $i, true, false, $user_choice, false);
  5363. // Button save and continue
  5364. switch ($this->type) {
  5365. case ONE_PER_PAGE:
  5366. $exercise_actions .= $this->show_button($questionId, $current_question, null, $remindList);
  5367. break;
  5368. case ALL_ON_ONE_PAGE:
  5369. $button = '<a href="javascript://" class="btn" onclick="save_now(\''.$questionId.'\'); ">'.get_lang('SaveForNow').'</a>';
  5370. $button .= '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;';
  5371. $exercise_actions .= Display::div($button, array('class'=>'exercise_save_now_button'));
  5372. break;
  5373. }
  5374. if (!empty($questions_in_media)) {
  5375. $count_of_questions_inside_media = count($questions_in_media);
  5376. if ($count_of_questions_inside_media > 1) {
  5377. $button = '<a href="javascript://" class="btn" onclick="save_now(\''.$questionId.'\', false, false); ">'.get_lang('SaveForNow').'</a>';
  5378. $button .= '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;';
  5379. $exercise_actions = Display::div($button, array('class'=>'exercise_save_now_button'));
  5380. }
  5381. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  5382. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  5383. }
  5384. }
  5385. // Checkbox review answers
  5386. if ($this->review_answers && !in_array($question_obj->type, Question::question_type_no_review())) {
  5387. $remind_question_div = Display::tag('label', Display::input('checkbox', 'remind_list['.$questionId.']', '', $attributes).get_lang('ReviewQuestionLater'), array('class' => 'checkbox', 'for' =>'remind_list['.$questionId.']'));
  5388. $exercise_actions .= Display::div($remind_question_div, array('class'=>'exercise_save_now_button'));
  5389. }
  5390. echo Display::div(' ', array('class'=>'clear'));
  5391. $paginationCounter = null;
  5392. if ($this->type == ONE_PER_PAGE) {
  5393. if (empty($questions_in_media)) {
  5394. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  5395. } else {
  5396. if ($last_question_in_media) {
  5397. $paginationCounter = Display::paginationIndicator($current_question, count($realQuestionList));
  5398. }
  5399. }
  5400. }
  5401. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  5402. echo Display::div($exercise_actions, array('class'=>'form-actions'));
  5403. echo '</div>';
  5404. }
  5405. }
  5406. /**
  5407. * @param int $exeId
  5408. * @return array
  5409. */
  5410. public function returnQuestionListByAttempt($exeId)
  5411. {
  5412. return $this->displayQuestionListByAttempt($exeId, false, true);
  5413. }
  5414. /**
  5415. * Display the exercise results
  5416. * @param int attempt id (exe_id)
  5417. * @param bool save users results (true) or just show the results (false)
  5418. * @param bool return array with exercise result info
  5419. * @param mixed
  5420. */
  5421. public function displayQuestionListByAttempt($exe_id, $saveUserResult = false, $returnExerciseResult = false)
  5422. {
  5423. global $origin, $debug;
  5424. //Getting attempt info
  5425. $exercise_stat_info = $this->getStatTrackExerciseInfoByExeId($exe_id);
  5426. //Getting question list
  5427. $question_list = array();
  5428. if (!empty($exercise_stat_info['data_tracking'])) {
  5429. $question_list = explode(',', $exercise_stat_info['data_tracking']);
  5430. } else {
  5431. //Try getting the question list only if save result is off
  5432. if ($saveUserResult == false) {
  5433. $question_list = $this->selectQuestionList();
  5434. }
  5435. error_log("Data tracking is empty! exe_id: $exe_id");
  5436. }
  5437. $counter = 1;
  5438. $total_score = 0;
  5439. $total_weight = 0;
  5440. $exercise_content = null;
  5441. //Hide results
  5442. $show_results = false;
  5443. $show_only_score = false;
  5444. if ($this->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
  5445. $show_results = true;
  5446. }
  5447. if (in_array($this->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) {
  5448. $show_only_score = true;
  5449. }
  5450. if ($show_results || $show_only_score) {
  5451. $user_info = api_get_user_info($exercise_stat_info['exe_user_id']);
  5452. // Shows exercise header.
  5453. echo $this->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), $exercise_stat_info['duration']);
  5454. }
  5455. // Display text when test is finished #4074 and for LP #4227
  5456. $end_of_message = $this->selectTextWhenFinished();
  5457. if (!empty($end_of_message)) {
  5458. Display::display_normal_message($end_of_message, false);
  5459. echo "<div class='clear'>&nbsp;</div>";
  5460. }
  5461. $question_list_answers = array();
  5462. $media_list = array();
  5463. $category_list = array();
  5464. $tempParentId = null;
  5465. $mediaCounter = 0;
  5466. $exerciseResultInfo = array();
  5467. // Loop over all question to show results for each of them, one by one
  5468. if (!empty($question_list)) {
  5469. if ($debug) {
  5470. error_log('Looping question_list '.print_r($question_list, 1));
  5471. }
  5472. foreach ($question_list as $questionId) {
  5473. // Creates a temporary Question object
  5474. $objQuestionTmp = Question::read($questionId);
  5475. // This variable commes from exercise_submit_modal.php
  5476. ob_start();
  5477. $hotspot_delineation_result = null;
  5478. // We're inside *one* question. Go through each possible answer for this question
  5479. $result = $this->manageAnswers(
  5480. $exercise_stat_info['exe_id'],
  5481. $questionId,
  5482. null,
  5483. 'exercise_result',
  5484. array(),
  5485. $saveUserResult,
  5486. true,
  5487. $show_results,
  5488. $hotspot_delineation_result
  5489. );
  5490. if (empty($result)) {
  5491. continue;
  5492. }
  5493. $total_score += $result['score'];
  5494. $total_weight += $result['weight'];
  5495. $question_list_answers[] = array(
  5496. 'question' => $result['open_question'],
  5497. 'answer' => $result['open_answer'],
  5498. 'answer_type' => $result['answer_type']
  5499. );
  5500. $my_total_score = $result['score'];
  5501. $my_total_weight = $result['weight'];
  5502. // Category report
  5503. $category_was_added_for_this_test = false;
  5504. $categoryExerciseList = $this->getListOfCategoriesWithQuestionForTest();
  5505. $category_list = array();
  5506. if (isset($categoryExerciseList) && !empty($categoryExerciseList)) {
  5507. foreach ($categoryExerciseList as $category_id => $categoryInfo) {
  5508. if (!isset($category_list[$category_id])) {
  5509. $category_list[$category_id] = array();
  5510. $category_list[$category_id]['score'] = 0;
  5511. $category_list[$category_id]['total'] = 0;
  5512. }
  5513. $category_list[$category_id]['score'] += $my_total_score;
  5514. $category_list[$category_id]['total'] += $my_total_weight;
  5515. $category_was_added_for_this_test = true;
  5516. }
  5517. }
  5518. // No category for this question!
  5519. if ($category_was_added_for_this_test == false) {
  5520. if (!isset($category_list['none'])) {
  5521. $category_list['none'] = array();
  5522. $category_list['none']['score'] = 0;
  5523. $category_list['none']['total'] = 0;
  5524. }
  5525. $category_list['none']['score'] += $my_total_score;
  5526. $category_list['none']['total'] += $my_total_weight;
  5527. }
  5528. if ($this->selectPropagateNeg() == 0 && $my_total_score < 0) {
  5529. $my_total_score = 0;
  5530. }
  5531. $comnt = null;
  5532. if ($show_results) {
  5533. $comnt = get_comments($exe_id, $questionId);
  5534. if (!empty($comnt)) {
  5535. echo '<b>'.get_lang('Feedback').'</b>';
  5536. echo '<div id="question_feedback">'.$comnt.'</div>';
  5537. }
  5538. }
  5539. $score = array();
  5540. $score['result'] = get_lang('Score')." : ".ExerciseLib::show_score($my_total_score, $my_total_weight, false, true);
  5541. $score['pass'] = $my_total_score >= $my_total_weight ? true : false;
  5542. $score['score'] = $my_total_score;
  5543. $score['weight'] = $my_total_weight;
  5544. $score['comments'] = $comnt;
  5545. $exerciseResultInfo[$questionId]['score'] = $score;
  5546. $exerciseResultInfo[$questionId]['details'] = $result;
  5547. // If no results we hide the results
  5548. if ($show_results == false) {
  5549. $score = array();
  5550. }
  5551. $contents = ob_get_clean();
  5552. $question_content = '<div class="question_row">';
  5553. if ($show_results) {
  5554. $show_media = false;
  5555. $counterToShow = $counter;
  5556. if ($objQuestionTmp->parent_id != 0) {
  5557. if (!in_array($objQuestionTmp->parent_id, $media_list)) {
  5558. $media_list[] = $objQuestionTmp->parent_id;
  5559. $show_media = true;
  5560. }
  5561. if ($tempParentId == $objQuestionTmp->parent_id) {
  5562. $mediaCounter++;
  5563. } else {
  5564. $mediaCounter = 0;
  5565. }
  5566. $counterToShow = chr(97 + $mediaCounter);
  5567. $tempParentId = $objQuestionTmp->parent_id;
  5568. }
  5569. //Shows question title an description
  5570. $question_content .= $objQuestionTmp->return_header(null, $counterToShow, $score, $show_media);
  5571. // display question category, if any
  5572. $question_content .= Testcategory::getCategoryNamesForQuestion($questionId);
  5573. }
  5574. $counter++;
  5575. $question_content .= $contents;
  5576. $question_content .= '</div>';
  5577. $exercise_content .= $question_content;
  5578. } // end foreach() block that loops over all questions
  5579. }
  5580. $total_score_text = null;
  5581. if ($returnExerciseResult) {
  5582. return $exerciseResultInfo;
  5583. }
  5584. if ($origin != 'learnpath') {
  5585. if ($show_results || $show_only_score) {
  5586. $total_score_text .= '<div class="question_row">';
  5587. $total_score_text .= $this->get_question_ribbon($total_score, $total_weight, true);
  5588. $total_score_text .= '</div>';
  5589. }
  5590. }
  5591. if (!empty($category_list) && ($show_results || $show_only_score)) {
  5592. //Adding total
  5593. $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
  5594. echo Testcategory::get_stats_table_by_attempt($this->id, $category_list);
  5595. }
  5596. echo $total_score_text;
  5597. echo $exercise_content;
  5598. if (!$show_only_score) {
  5599. echo $total_score_text;
  5600. }
  5601. if ($saveUserResult) {
  5602. // Tracking of results
  5603. $learnpath_id = $exercise_stat_info['orig_lp_id'];
  5604. $learnpath_item_id = $exercise_stat_info['orig_lp_item_id'];
  5605. $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
  5606. if (api_is_allowed_to_session_edit()) {
  5607. update_event_exercise(
  5608. $exercise_stat_info['exe_id'],
  5609. $this->selectId(),
  5610. $total_score,
  5611. $total_weight,
  5612. api_get_session_id(),
  5613. $learnpath_id,
  5614. $learnpath_item_id,
  5615. $learnpath_item_view_id,
  5616. $exercise_stat_info['exe_duration'],
  5617. '',
  5618. array()
  5619. );
  5620. }
  5621. // Send notification.
  5622. if (!api_is_allowed_to_edit(null, true)) {
  5623. $this->sendCustomNotification($exe_id, $exerciseResultInfo);
  5624. $this->sendNotificationForOpenQuestions($question_list_answers, $origin, $exe_id);
  5625. $this->sendNotificationForOralQuestions($question_list_answers, $origin, $exe_id);
  5626. }
  5627. }
  5628. }
  5629. /**
  5630. * @param $score
  5631. * @param $weight
  5632. * @param bool $check_pass_percentage
  5633. * @return string
  5634. */
  5635. public function get_question_ribbon($score, $weight, $check_pass_percentage = false)
  5636. {
  5637. $ribbon = '<div class="ribbon">';
  5638. if ($check_pass_percentage) {
  5639. $is_success = ExerciseLib::is_success_exercise_result($score, $weight, $this->selectPassPercentage());
  5640. // Color the final test score if pass_percentage activated
  5641. $ribbon_total_success_or_error = "";
  5642. if (ExerciseLib::is_pass_pourcentage_enabled($this->selectPassPercentage())) {
  5643. if ($is_success) {
  5644. $ribbon_total_success_or_error = ' ribbon-total-success';
  5645. } else {
  5646. $ribbon_total_success_or_error = ' ribbon-total-error';
  5647. }
  5648. }
  5649. $ribbon .= '<div class="rib rib-total '.$ribbon_total_success_or_error.'">';
  5650. } else {
  5651. $ribbon .= '<div class="rib rib-total">';
  5652. }
  5653. $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
  5654. $ribbon .= ExerciseLib::show_score($score, $weight, false, true);
  5655. $ribbon .= '</h3>';
  5656. $ribbon .= '</div>';
  5657. if ($check_pass_percentage) {
  5658. $ribbon .= ExerciseLib::show_success_message($score, $weight, $this->selectPassPercentage());
  5659. }
  5660. $ribbon .= '</div>';
  5661. return $ribbon;
  5662. }
  5663. public function getQuestionWithCategories()
  5664. {
  5665. $categoryTable = Database::get_course_table(TABLE_QUIZ_CATEGORY);
  5666. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  5667. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  5668. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  5669. $sql = "SELECT DISTINCT cat.*
  5670. FROM $TBL_EXERCICE_QUESTION e INNER JOIN $TBL_QUESTIONS q
  5671. ON (e.question_id = q.iid and e.c_id = {$this->course_id})
  5672. INNER JOIN $categoryRelTable catRel
  5673. ON (catRel.question_id = e.question_id)
  5674. INNER JOIN $categoryTable cat
  5675. ON (cat.iid = catRel.category_id)
  5676. WHERE e.c_id = {$this->course_id} AND e.exercice_id = ".Database::escape_string($this->id);
  5677. $result = Database::query($sql);
  5678. $categoriesInExercise = array();
  5679. if (Database::num_rows($result)) {
  5680. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  5681. }
  5682. return $categoriesInExercise;
  5683. }
  5684. }