exercise.class.php 310 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CoreBundle\Entity\TrackEHotspot;
  5. use Chamilo\CourseBundle\Entity\CQuizCategory;
  6. /**
  7. * Class Exercise
  8. *
  9. * Allows to instantiate an object of type Exercise
  10. * @package chamilo.exercise
  11. * @todo use doctrine object, use getters and setters correctly
  12. * @author Olivier Brouckaert
  13. * @author Julio Montoya Cleaning exercises
  14. * Modified by Hubert Borderiou #294
  15. */
  16. class Exercise
  17. {
  18. public $id;
  19. public $name;
  20. public $title;
  21. public $exercise;
  22. public $description;
  23. public $sound;
  24. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  25. public $random;
  26. public $random_answers;
  27. public $active;
  28. public $timeLimit;
  29. public $attempts;
  30. public $feedback_type;
  31. public $end_time;
  32. public $start_time;
  33. public $questionList; // array with the list of this exercise's questions
  34. /* including question list of the media */
  35. public $questionListUncompressed;
  36. public $results_disabled;
  37. public $expired_time;
  38. public $course;
  39. public $course_id;
  40. public $propagate_neg;
  41. public $saveCorrectAnswers;
  42. public $review_answers;
  43. public $randomByCat;
  44. public $text_when_finished;
  45. public $display_category_name;
  46. public $pass_percentage;
  47. public $edit_exercise_in_lp = false;
  48. public $is_gradebook_locked = false;
  49. public $exercise_was_added_in_lp = false;
  50. public $lpList = array();
  51. public $force_edit_exercise_in_lp = false;
  52. public $categories;
  53. public $categories_grouping = true;
  54. public $endButton = 0;
  55. public $categoryWithQuestionList;
  56. public $mediaList;
  57. public $loadQuestionAJAX = false;
  58. // Notification send to the teacher.
  59. public $emailNotificationTemplate = null;
  60. // Notification send to the student.
  61. public $emailNotificationTemplateToUser = null;
  62. public $countQuestions = 0;
  63. public $fastEdition = false;
  64. public $modelType = 1;
  65. public $questionSelectionType = EX_Q_SELECTION_ORDERED;
  66. public $hideQuestionTitle = 0;
  67. public $scoreTypeModel = 0;
  68. public $categoryMinusOne = true; // Shows the category -1: See BT#6540
  69. public $globalCategoryId = null;
  70. public $onSuccessMessage = null;
  71. public $onFailedMessage = null;
  72. public $emailAlert;
  73. public $notifyUserByEmail = '';
  74. public $sessionId = 0;
  75. public $questionFeedbackEnabled = false;
  76. public $questionTypeWithFeedback;
  77. public $showPreviousButton;
  78. public $notifications;
  79. /**
  80. * Constructor of the class
  81. * @param int $courseId
  82. * @author Olivier Brouckaert
  83. */
  84. public function __construct($courseId = 0)
  85. {
  86. $this->id = 0;
  87. $this->exercise = '';
  88. $this->description = '';
  89. $this->sound = '';
  90. $this->type = ALL_ON_ONE_PAGE;
  91. $this->random = 0;
  92. $this->random_answers = 0;
  93. $this->active = 1;
  94. $this->questionList = array();
  95. $this->timeLimit = 0;
  96. $this->end_time = '';
  97. $this->start_time = '';
  98. $this->results_disabled = 1;
  99. $this->expired_time = 0;
  100. $this->propagate_neg = 0;
  101. $this->saveCorrectAnswers = 0;
  102. $this->review_answers = false;
  103. $this->randomByCat = 0;
  104. $this->text_when_finished = '';
  105. $this->display_category_name = 0;
  106. $this->pass_percentage = '';
  107. $this->modelType = 1;
  108. $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
  109. $this->endButton = 0;
  110. $this->scoreTypeModel = 0;
  111. $this->globalCategoryId = null;
  112. if (!empty($courseId)) {
  113. $course_info = api_get_course_info_by_id($courseId);
  114. } else {
  115. $course_info = api_get_course_info();
  116. }
  117. $this->course_id = $course_info['real_id'];
  118. $this->course = $course_info;
  119. // ALTER TABLE c_quiz_question ADD COLUMN feedback text;
  120. $this->questionFeedbackEnabled = api_get_configuration_value('allow_quiz_question_feedback');
  121. $this->showPreviousButton = true;
  122. }
  123. /**
  124. * Reads exercise information from the data base
  125. *
  126. * @author Olivier Brouckaert
  127. * @param integer $id - exercise Id
  128. * @param bool $parseQuestionList
  129. *
  130. * @return boolean - true if exercise exists, otherwise false
  131. */
  132. public function read($id, $parseQuestionList = true)
  133. {
  134. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  135. $tableLpItem = Database::get_course_table(TABLE_LP_ITEM);
  136. $id = (int) $id;
  137. if (empty($this->course_id)) {
  138. return false;
  139. }
  140. $sql = "SELECT * FROM $table
  141. WHERE c_id = ".$this->course_id." AND id = ".$id;
  142. $result = Database::query($sql);
  143. // if the exercise has been found
  144. if ($object = Database::fetch_object($result)) {
  145. $this->id = $id;
  146. $this->exercise = $object->title;
  147. $this->name = $object->title;
  148. $this->title = $object->title;
  149. $this->description = $object->description;
  150. $this->sound = $object->sound;
  151. $this->type = $object->type;
  152. if (empty($this->type)) {
  153. $this->type = ONE_PER_PAGE;
  154. }
  155. $this->random = $object->random;
  156. $this->random_answers = $object->random_answers;
  157. $this->active = $object->active;
  158. $this->results_disabled = $object->results_disabled;
  159. $this->attempts = $object->max_attempt;
  160. $this->feedback_type = $object->feedback_type;
  161. $this->propagate_neg = $object->propagate_neg;
  162. $this->saveCorrectAnswers = $object->save_correct_answers;
  163. $this->randomByCat = $object->random_by_category;
  164. $this->text_when_finished = $object->text_when_finished;
  165. $this->display_category_name = $object->display_category_name;
  166. $this->pass_percentage = $object->pass_percentage;
  167. $this->sessionId = $object->session_id;
  168. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  169. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  170. $this->globalCategoryId = isset($object->global_category_id) ? $object->global_category_id : null;
  171. $this->questionSelectionType = isset($object->question_selection_type) ? $object->question_selection_type : null;
  172. $this->hideQuestionTitle = isset($object->hide_question_title) ? (int) $object->hide_question_title : 0;
  173. $this->notifications = [];
  174. if (!empty($object->notifications)) {
  175. $this->notifications = explode(',', $object->notifications);
  176. }
  177. if (isset($object->show_previous_button)) {
  178. $this->showPreviousButton = $object->show_previous_button == 1 ? true : false;
  179. }
  180. $sql = "SELECT lp_id, max_score
  181. FROM $tableLpItem
  182. WHERE
  183. c_id = {$this->course_id} AND
  184. item_type = '".TOOL_QUIZ."' AND
  185. path = '".$id."'";
  186. $result = Database::query($sql);
  187. if (Database::num_rows($result) > 0) {
  188. $this->exercise_was_added_in_lp = true;
  189. $this->lpList = Database::store_result($result, 'ASSOC');
  190. }
  191. $this->force_edit_exercise_in_lp = api_get_configuration_value('force_edit_exercise_in_lp');
  192. if ($this->exercise_was_added_in_lp) {
  193. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  194. } else {
  195. $this->edit_exercise_in_lp = true;
  196. }
  197. if (!empty($object->end_time)) {
  198. $this->end_time = $object->end_time;
  199. }
  200. if (!empty($object->start_time)) {
  201. $this->start_time = $object->start_time;
  202. }
  203. // Control time
  204. $this->expired_time = $object->expired_time;
  205. // Checking if question_order is correctly set
  206. if ($parseQuestionList) {
  207. $this->setQuestionList(true);
  208. }
  209. //overload questions list with recorded questions list
  210. //load questions only for exercises of type 'one question per page'
  211. //this is needed only is there is no questions
  212. /*
  213. // @todo not sure were in the code this is used somebody mess with the exercise tool
  214. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  215. global $_configuration, $questionList;
  216. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  217. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']) {
  218. $this->questionList = $questionList;
  219. }*/
  220. return true;
  221. }
  222. return false;
  223. }
  224. /**
  225. * @return string
  226. */
  227. public function getCutTitle()
  228. {
  229. $title = $this->getUnformattedTitle();
  230. return cut($title, EXERCISE_MAX_NAME_SIZE);
  231. }
  232. /**
  233. * returns the exercise ID
  234. *
  235. * @author Olivier Brouckaert
  236. * @return int - exercise ID
  237. */
  238. public function selectId()
  239. {
  240. return $this->id;
  241. }
  242. /**
  243. * returns the exercise title
  244. * @author Olivier Brouckaert
  245. * @param bool $unformattedText Optional. Get the title without HTML tags
  246. * @return string - exercise title
  247. */
  248. public function selectTitle($unformattedText = false)
  249. {
  250. if ($unformattedText) {
  251. return $this->getUnformattedTitle();
  252. }
  253. return $this->exercise;
  254. }
  255. /**
  256. * returns the number of attempts setted
  257. *
  258. * @return int - exercise attempts
  259. */
  260. public function selectAttempts()
  261. {
  262. return $this->attempts;
  263. }
  264. /** returns the number of FeedbackType *
  265. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  266. * @return int - exercise attempts
  267. */
  268. public function selectFeedbackType()
  269. {
  270. return $this->feedback_type;
  271. }
  272. /**
  273. * returns the time limit
  274. * @return int
  275. */
  276. public function selectTimeLimit()
  277. {
  278. return $this->timeLimit;
  279. }
  280. /**
  281. * returns the exercise description
  282. *
  283. * @author Olivier Brouckaert
  284. * @return string - exercise description
  285. */
  286. public function selectDescription()
  287. {
  288. return $this->description;
  289. }
  290. /**
  291. * returns the exercise sound file
  292. *
  293. * @author Olivier Brouckaert
  294. * @return string - exercise description
  295. */
  296. public function selectSound()
  297. {
  298. return $this->sound;
  299. }
  300. /**
  301. * returns the exercise type
  302. *
  303. * @author Olivier Brouckaert
  304. * @return int - exercise type
  305. */
  306. public function selectType()
  307. {
  308. return $this->type;
  309. }
  310. /**
  311. * @return int
  312. */
  313. public function getModelType()
  314. {
  315. return $this->modelType;
  316. }
  317. /**
  318. * @return int
  319. */
  320. public function selectEndButton()
  321. {
  322. return $this->endButton;
  323. }
  324. /**
  325. * @return string
  326. */
  327. public function getOnSuccessMessage()
  328. {
  329. return $this->onSuccessMessage;
  330. }
  331. /**
  332. * @return string
  333. */
  334. public function getOnFailedMessage()
  335. {
  336. return $this->onFailedMessage;
  337. }
  338. /**
  339. * @author hubert borderiou 30-11-11
  340. * @return integer : do we display the question category name for students
  341. */
  342. public function selectDisplayCategoryName()
  343. {
  344. return $this->display_category_name;
  345. }
  346. /**
  347. * @return int
  348. */
  349. public function selectPassPercentage()
  350. {
  351. return $this->pass_percentage;
  352. }
  353. /**
  354. *
  355. * Modify object to update the switch display_category_name
  356. * @author hubert borderiou 30-11-11
  357. * @param int $in_txt is an integer 0 or 1
  358. */
  359. public function updateDisplayCategoryName($in_txt)
  360. {
  361. $this->display_category_name = $in_txt;
  362. }
  363. /**
  364. * @author hubert borderiou 28-11-11
  365. * @return string html text : the text to display ay the end of the test.
  366. */
  367. public function selectTextWhenFinished()
  368. {
  369. return $this->text_when_finished;
  370. }
  371. /**
  372. * @author hubert borderiou 28-11-11
  373. * @return string html text : update the text to display ay the end of the test.
  374. */
  375. public function updateTextWhenFinished($in_txt)
  376. {
  377. $this->text_when_finished = $in_txt;
  378. }
  379. /**
  380. * return 1 or 2 if randomByCat
  381. * @author hubert borderiou
  382. * @return integer - quiz random by category
  383. */
  384. public function selectRandomByCat()
  385. {
  386. return $this->randomByCat;
  387. }
  388. /**
  389. * return 0 if no random by cat
  390. * return 1 if random by cat, categories shuffled
  391. * return 2 if random by cat, categories sorted by alphabetic order
  392. * @author hubert borderiou
  393. * @return integer - quiz random by category
  394. */
  395. public function isRandomByCat()
  396. {
  397. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  398. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  399. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  400. } elseif ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  401. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  402. }
  403. return $res;
  404. }
  405. /**
  406. * return nothing
  407. * update randomByCat value for object
  408. * @param int $random
  409. *
  410. * @author hubert borderiou
  411. */
  412. public function updateRandomByCat($random)
  413. {
  414. if (in_array(
  415. $random,
  416. array(
  417. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  418. EXERCISE_CATEGORY_RANDOM_ORDERED,
  419. EXERCISE_CATEGORY_RANDOM_DISABLED,
  420. )
  421. )) {
  422. $this->randomByCat = $random;
  423. } else {
  424. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  425. }
  426. }
  427. /**
  428. * Tells if questions are selected randomly, and if so returns the draws
  429. *
  430. * @author Carlos Vargas
  431. * @return integer - results disabled exercise
  432. */
  433. public function selectResultsDisabled()
  434. {
  435. return $this->results_disabled;
  436. }
  437. /**
  438. * tells if questions are selected randomly, and if so returns the draws
  439. *
  440. * @author Olivier Brouckaert
  441. * @return integer - 0 if not random, otherwise the draws
  442. */
  443. public function isRandom()
  444. {
  445. if ($this->random > 0 || $this->random == -1) {
  446. return true;
  447. } else {
  448. return false;
  449. }
  450. }
  451. /**
  452. * returns random answers status.
  453. *
  454. * @author Juan Carlos Rana
  455. */
  456. public function selectRandomAnswers()
  457. {
  458. return $this->random_answers;
  459. }
  460. /**
  461. * Same as isRandom() but has a name applied to values different than 0 or 1
  462. * @return int
  463. */
  464. public function getShuffle()
  465. {
  466. return $this->random;
  467. }
  468. /**
  469. * returns the exercise status (1 = enabled ; 0 = disabled)
  470. *
  471. * @author Olivier Brouckaert
  472. * @return boolean - true if enabled, otherwise false
  473. */
  474. public function selectStatus()
  475. {
  476. return $this->active;
  477. }
  478. /**
  479. * If false the question list will be managed as always if true
  480. * the question will be filtered
  481. * depending of the exercise settings (table c_quiz_rel_category)
  482. * @param bool $status active or inactive grouping
  483. **/
  484. public function setCategoriesGrouping($status)
  485. {
  486. $this->categories_grouping = (bool) $status;
  487. }
  488. /**
  489. * @return int
  490. */
  491. public function getHideQuestionTitle()
  492. {
  493. return $this->hideQuestionTitle;
  494. }
  495. /**
  496. * @param $value
  497. */
  498. public function setHideQuestionTitle($value)
  499. {
  500. $this->hideQuestionTitle = (int) $value;
  501. }
  502. /**
  503. * @return int
  504. */
  505. public function getScoreTypeModel()
  506. {
  507. return $this->scoreTypeModel;
  508. }
  509. /**
  510. * @param int $value
  511. */
  512. public function setScoreTypeModel($value)
  513. {
  514. $this->scoreTypeModel = (int) $value;
  515. }
  516. /**
  517. * @return int
  518. */
  519. public function getGlobalCategoryId()
  520. {
  521. return $this->globalCategoryId;
  522. }
  523. /**
  524. * @param int $value
  525. */
  526. public function setGlobalCategoryId($value)
  527. {
  528. if (is_array($value) && isset($value[0])) {
  529. $value = $value[0];
  530. }
  531. $this->globalCategoryId = (int) $value;
  532. }
  533. /**
  534. *
  535. * @param int $start
  536. * @param int $limit
  537. * @param int $sidx
  538. * @param string $sord
  539. * @param array $where_condition
  540. * @param array $extraFields
  541. *
  542. * @return array
  543. */
  544. public function getQuestionListPagination(
  545. $start,
  546. $limit,
  547. $sidx,
  548. $sord,
  549. $where_condition = array(),
  550. $extraFields = array()
  551. ) {
  552. if (!empty($this->id)) {
  553. $category_list = TestCategory::getListOfCategoriesNameForTest(
  554. $this->id,
  555. false
  556. );
  557. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  558. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  559. $sql = "SELECT q.iid
  560. FROM $TBL_EXERCICE_QUESTION e
  561. INNER JOIN $TBL_QUESTIONS q
  562. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." )
  563. WHERE e.exercice_id = '".Database::escape_string($this->id)."'
  564. ";
  565. $orderCondition = "ORDER BY question_order";
  566. if (!empty($sidx) && !empty($sord)) {
  567. if ($sidx == 'question') {
  568. if (in_array(strtolower($sord), array('desc', 'asc'))) {
  569. $orderCondition = " ORDER BY q.$sidx $sord";
  570. }
  571. }
  572. }
  573. $sql .= $orderCondition;
  574. $limitCondition = null;
  575. if (isset($start) && isset($limit)) {
  576. $start = intval($start);
  577. $limit = intval($limit);
  578. $limitCondition = " LIMIT $start, $limit";
  579. }
  580. $sql .= $limitCondition;
  581. $result = Database::query($sql);
  582. $questions = array();
  583. if (Database::num_rows($result)) {
  584. if (!empty($extraFields)) {
  585. $extraFieldValue = new ExtraFieldValue('question');
  586. }
  587. while ($question = Database::fetch_array($result, 'ASSOC')) {
  588. /** @var Question $objQuestionTmp */
  589. $objQuestionTmp = Question::read($question['iid']);
  590. $category_labels = TestCategory::return_category_labels(
  591. $objQuestionTmp->category_list,
  592. $category_list
  593. );
  594. if (empty($category_labels)) {
  595. $category_labels = "-";
  596. }
  597. // Question type
  598. list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
  599. $question_media = null;
  600. if (!empty($objQuestionTmp->parent_id)) {
  601. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  602. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  603. }
  604. $questionType = Display::tag(
  605. 'div',
  606. Display::return_icon($typeImg, $typeExpl, array(), ICON_SIZE_MEDIUM).$question_media
  607. );
  608. $question = array(
  609. 'id' => $question['iid'],
  610. 'question' => $objQuestionTmp->selectTitle(),
  611. 'type' => $questionType,
  612. 'category' => Display::tag('div', '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'),
  613. 'score' => $objQuestionTmp->selectWeighting(),
  614. 'level' => $objQuestionTmp->level
  615. );
  616. if (!empty($extraFields)) {
  617. foreach ($extraFields as $extraField) {
  618. $value = $extraFieldValue->get_values_by_handler_and_field_id(
  619. $question['id'],
  620. $extraField['id']
  621. );
  622. $stringValue = null;
  623. if ($value) {
  624. $stringValue = $value['field_value'];
  625. }
  626. $question[$extraField['field_variable']] = $stringValue;
  627. }
  628. }
  629. $questions[] = $question;
  630. }
  631. }
  632. return $questions;
  633. }
  634. }
  635. /**
  636. * Get question count per exercise from DB (any special treatment)
  637. * @return int
  638. */
  639. public function getQuestionCount()
  640. {
  641. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  642. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  643. $sql = "SELECT count(q.id) as count
  644. FROM $TBL_EXERCICE_QUESTION e
  645. INNER JOIN $TBL_QUESTIONS q
  646. ON (e.question_id = q.id AND e.c_id = q.c_id)
  647. WHERE
  648. e.c_id = {$this->course_id} AND
  649. e.exercice_id = ".Database::escape_string($this->id);
  650. $result = Database::query($sql);
  651. $count = 0;
  652. if (Database::num_rows($result)) {
  653. $row = Database::fetch_array($result);
  654. $count = $row['count'];
  655. }
  656. return $count;
  657. }
  658. /**
  659. * @return array
  660. */
  661. public function getQuestionOrderedListByName()
  662. {
  663. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  664. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  665. // Getting question list from the order (question list drag n drop interface ).
  666. $sql = "SELECT e.question_id
  667. FROM $TBL_EXERCICE_QUESTION e
  668. INNER JOIN $TBL_QUESTIONS q
  669. ON (e.question_id= q.id AND e.c_id = q.c_id)
  670. WHERE
  671. e.c_id = {$this->course_id} AND
  672. e.exercice_id = '".Database::escape_string($this->id)."'
  673. ORDER BY q.question";
  674. $result = Database::query($sql);
  675. $list = array();
  676. if (Database::num_rows($result)) {
  677. $list = Database::store_result($result, 'ASSOC');
  678. }
  679. return $list;
  680. }
  681. /**
  682. * Gets the question list ordered by the question_order setting (drag and drop)
  683. * @return array
  684. */
  685. private function getQuestionOrderedList()
  686. {
  687. $questionList = array();
  688. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  689. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  690. // Getting question_order to verify that the question
  691. // list is correct and all question_order's were set
  692. $sql = "SELECT DISTINCT e.question_order
  693. FROM $TBL_EXERCICE_QUESTION e
  694. INNER JOIN $TBL_QUESTIONS q
  695. ON (e.question_id = q.id AND e.c_id = q.c_id)
  696. WHERE
  697. e.c_id = {$this->course_id} AND
  698. e.exercice_id = ".Database::escape_string($this->id);
  699. $result = Database::query($sql);
  700. $count_question_orders = Database::num_rows($result);
  701. // Getting question list from the order (question list drag n drop interface).
  702. $sql = "SELECT DISTINCT e.question_id, e.question_order
  703. FROM $TBL_EXERCICE_QUESTION e
  704. INNER JOIN $TBL_QUESTIONS q
  705. ON (e.question_id = q.id AND e.c_id = q.c_id)
  706. WHERE
  707. e.c_id = {$this->course_id} AND
  708. e.exercice_id = '".Database::escape_string($this->id)."'
  709. ORDER BY question_order";
  710. $result = Database::query($sql);
  711. // Fills the array with the question ID for this exercise
  712. // the key of the array is the question position
  713. $temp_question_list = array();
  714. $counter = 1;
  715. while ($new_object = Database::fetch_object($result)) {
  716. // Correct order.
  717. $questionList[$new_object->question_order] = $new_object->question_id;
  718. // Just in case we save the order in other array
  719. $temp_question_list[$counter] = $new_object->question_id;
  720. $counter++;
  721. }
  722. if (!empty($temp_question_list)) {
  723. /* If both array don't match it means that question_order was not correctly set
  724. for all questions using the default mysql order */
  725. if (count($temp_question_list) != $count_question_orders) {
  726. $questionList = $temp_question_list;
  727. }
  728. }
  729. return $questionList;
  730. }
  731. /**
  732. * Select N values from the questions per category array
  733. *
  734. * @param array $categoriesAddedInExercise
  735. * @param array $question_list
  736. * @param array $questions_by_category per category
  737. * @param bool $flatResult
  738. * @param bool $randomizeQuestions
  739. *
  740. * @return array
  741. */
  742. private function pickQuestionsPerCategory(
  743. $categoriesAddedInExercise,
  744. $question_list,
  745. & $questions_by_category,
  746. $flatResult = true,
  747. $randomizeQuestions = false
  748. ) {
  749. $addAll = true;
  750. $categoryCountArray = array();
  751. // Getting how many questions will be selected per category.
  752. if (!empty($categoriesAddedInExercise)) {
  753. $addAll = false;
  754. // Parsing question according the category rel exercise settings
  755. foreach ($categoriesAddedInExercise as $category_info) {
  756. $category_id = $category_info['category_id'];
  757. if (isset($questions_by_category[$category_id])) {
  758. // How many question will be picked from this category.
  759. $count = $category_info['count_questions'];
  760. // -1 means all questions
  761. if ($count == -1) {
  762. $categoryCountArray[$category_id] = 999;
  763. } else {
  764. $categoryCountArray[$category_id] = $count;
  765. }
  766. }
  767. }
  768. }
  769. if (!empty($questions_by_category)) {
  770. $temp_question_list = array();
  771. foreach ($questions_by_category as $category_id => & $categoryQuestionList) {
  772. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  773. if (isset($categoryCountArray[$category_id])) {
  774. $numberOfQuestions = $categoryCountArray[$category_id];
  775. } else {
  776. $numberOfQuestions = 0;
  777. }
  778. }
  779. if ($addAll) {
  780. $numberOfQuestions = 999;
  781. }
  782. if (!empty($numberOfQuestions)) {
  783. $elements = TestCategory::getNElementsFromArray(
  784. $categoryQuestionList,
  785. $numberOfQuestions,
  786. $randomizeQuestions
  787. );
  788. if (!empty($elements)) {
  789. $temp_question_list[$category_id] = $elements;
  790. $categoryQuestionList = $elements;
  791. }
  792. }
  793. }
  794. if (!empty($temp_question_list)) {
  795. if ($flatResult) {
  796. $temp_question_list = array_flatten($temp_question_list);
  797. }
  798. $question_list = $temp_question_list;
  799. }
  800. }
  801. return $question_list;
  802. }
  803. /**
  804. * Selecting question list depending in the exercise-category
  805. * relationship (category table in exercise settings)
  806. *
  807. * @param array $question_list
  808. * @param int $questionSelectionType
  809. * @return array
  810. */
  811. public function getQuestionListWithCategoryListFilteredByCategorySettings(
  812. $question_list,
  813. $questionSelectionType
  814. ) {
  815. $result = array(
  816. 'question_list' => array(),
  817. 'category_with_questions_list' => array()
  818. );
  819. // Order/random categories
  820. $cat = new TestCategory();
  821. // Setting category order.
  822. switch ($questionSelectionType) {
  823. case EX_Q_SELECTION_ORDERED: // 1
  824. case EX_Q_SELECTION_RANDOM: // 2
  825. // This options are not allowed here.
  826. break;
  827. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
  828. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  829. $this,
  830. $this->course['real_id'],
  831. 'title ASC',
  832. false,
  833. true
  834. );
  835. $questions_by_category = TestCategory::getQuestionsByCat(
  836. $this->id,
  837. $question_list,
  838. $categoriesAddedInExercise
  839. );
  840. $question_list = $this->pickQuestionsPerCategory(
  841. $categoriesAddedInExercise,
  842. $question_list,
  843. $questions_by_category,
  844. true,
  845. false
  846. );
  847. break;
  848. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
  849. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  850. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  851. $this,
  852. $this->course['real_id'],
  853. null,
  854. true,
  855. true
  856. );
  857. $questions_by_category = TestCategory::getQuestionsByCat(
  858. $this->id,
  859. $question_list,
  860. $categoriesAddedInExercise
  861. );
  862. $question_list = $this->pickQuestionsPerCategory(
  863. $categoriesAddedInExercise,
  864. $question_list,
  865. $questions_by_category,
  866. true,
  867. false
  868. );
  869. break;
  870. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
  871. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  872. $this,
  873. $this->course['real_id'],
  874. 'title DESC',
  875. false,
  876. true
  877. );
  878. $questions_by_category = TestCategory::getQuestionsByCat(
  879. $this->id,
  880. $question_list,
  881. $categoriesAddedInExercise
  882. );
  883. $question_list = $this->pickQuestionsPerCategory(
  884. $categoriesAddedInExercise,
  885. $question_list,
  886. $questions_by_category,
  887. true,
  888. true
  889. );
  890. break;
  891. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
  892. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
  893. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  894. $this,
  895. $this->course['real_id'],
  896. null,
  897. true,
  898. true
  899. );
  900. $questions_by_category = TestCategory::getQuestionsByCat(
  901. $this->id,
  902. $question_list,
  903. $categoriesAddedInExercise
  904. );
  905. $question_list = $this->pickQuestionsPerCategory(
  906. $categoriesAddedInExercise,
  907. $question_list,
  908. $questions_by_category,
  909. true,
  910. true
  911. );
  912. break;
  913. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  914. break;
  915. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
  916. break;
  917. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
  918. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  919. $this,
  920. $this->course['real_id'],
  921. 'root ASC, lft ASC',
  922. false,
  923. true
  924. );
  925. $questions_by_category = TestCategory::getQuestionsByCat(
  926. $this->id,
  927. $question_list,
  928. $categoriesAddedInExercise
  929. );
  930. $question_list = $this->pickQuestionsPerCategory(
  931. $categoriesAddedInExercise,
  932. $question_list,
  933. $questions_by_category,
  934. true,
  935. false
  936. );
  937. break;
  938. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
  939. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  940. $this,
  941. $this->course['real_id'],
  942. 'root, lft ASC',
  943. false,
  944. true
  945. );
  946. $questions_by_category = TestCategory::getQuestionsByCat(
  947. $this->id,
  948. $question_list,
  949. $categoriesAddedInExercise
  950. );
  951. $question_list = $this->pickQuestionsPerCategory(
  952. $categoriesAddedInExercise,
  953. $question_list,
  954. $questions_by_category,
  955. true,
  956. true
  957. );
  958. break;
  959. }
  960. $result['question_list'] = isset($question_list) ? $question_list : array();
  961. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : array();
  962. // Adding category info in the category list with question list:
  963. if (!empty($questions_by_category)) {
  964. $newCategoryList = array();
  965. foreach ($questions_by_category as $categoryId => $questionList) {
  966. $cat = new TestCategory();
  967. $cat = $cat->getCategory($categoryId);
  968. $cat = (array) $cat;
  969. $cat['iid'] = $cat['id'];
  970. $categoryParentInfo = null;
  971. // Parent is not set no loop here
  972. if (!empty($cat['parent_id'])) {
  973. if (!isset($parentsLoaded[$cat['parent_id']])) {
  974. $categoryEntity = $em->find('ChamiloCoreBundle:CQuizCategory', $cat['parent_id']);
  975. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  976. } else {
  977. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  978. }
  979. $path = $repo->getPath($categoryEntity);
  980. $index = 0;
  981. if ($this->categoryMinusOne) {
  982. //$index = 1;
  983. }
  984. /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryParent*/
  985. foreach ($path as $categoryParent) {
  986. $visibility = $categoryParent->getVisibility();
  987. if ($visibility == 0) {
  988. $categoryParentId = $categoryId;
  989. $categoryTitle = $cat['title'];
  990. if (count($path) > 1) {
  991. continue;
  992. }
  993. } else {
  994. $categoryParentId = $categoryParent->getIid();
  995. $categoryTitle = $categoryParent->getTitle();
  996. }
  997. $categoryParentInfo['id'] = $categoryParentId;
  998. $categoryParentInfo['iid'] = $categoryParentId;
  999. $categoryParentInfo['parent_path'] = null;
  1000. $categoryParentInfo['title'] = $categoryTitle;
  1001. $categoryParentInfo['name'] = $categoryTitle;
  1002. $categoryParentInfo['parent_id'] = null;
  1003. break;
  1004. }
  1005. }
  1006. $cat['parent_info'] = $categoryParentInfo;
  1007. $newCategoryList[$categoryId] = array(
  1008. 'category' => $cat,
  1009. 'question_list' => $questionList
  1010. );
  1011. }
  1012. $result['category_with_questions_list'] = $newCategoryList;
  1013. }
  1014. return $result;
  1015. }
  1016. /**
  1017. * returns the array with the question ID list
  1018. * @param bool $from_db Whether the results should be fetched in the database or just from memory
  1019. * @param bool $adminView Whether we should return all questions (admin view) or
  1020. * just a list limited by the max number of random questions
  1021. * @author Olivier Brouckaert
  1022. * @return array - question ID list
  1023. */
  1024. public function selectQuestionList($from_db = false, $adminView = false)
  1025. {
  1026. if ($from_db && !empty($this->id)) {
  1027. $nbQuestions = $this->getQuestionCount();
  1028. $questionSelectionType = $this->getQuestionSelectionType();
  1029. switch ($questionSelectionType) {
  1030. case EX_Q_SELECTION_ORDERED:
  1031. $questionList = $this->getQuestionOrderedList();
  1032. break;
  1033. case EX_Q_SELECTION_RANDOM:
  1034. // Not a random exercise, or if there are not at least 2 questions
  1035. if ($this->random == 0 || $nbQuestions < 2) {
  1036. $questionList = $this->getQuestionOrderedList();
  1037. } else {
  1038. $questionList = $this->selectRandomList($adminView);
  1039. }
  1040. break;
  1041. default:
  1042. $questionList = $this->getQuestionOrderedList();
  1043. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings(
  1044. $questionList,
  1045. $questionSelectionType
  1046. );
  1047. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  1048. $questionList = $result['question_list'];
  1049. break;
  1050. }
  1051. return $questionList;
  1052. }
  1053. return $this->questionList;
  1054. }
  1055. /**
  1056. * returns the number of questions in this exercise
  1057. *
  1058. * @author Olivier Brouckaert
  1059. * @return integer - number of questions
  1060. */
  1061. public function selectNbrQuestions()
  1062. {
  1063. return sizeof($this->questionList);
  1064. }
  1065. /**
  1066. * @return int
  1067. */
  1068. public function selectPropagateNeg()
  1069. {
  1070. return $this->propagate_neg;
  1071. }
  1072. /**
  1073. * @return int
  1074. */
  1075. public function selectSaveCorrectAnswers()
  1076. {
  1077. return $this->saveCorrectAnswers;
  1078. }
  1079. /**
  1080. * Selects questions randomly in the question list
  1081. *
  1082. * @author Olivier Brouckaert
  1083. * @author Hubert Borderiou 15 nov 2011
  1084. * @param bool $adminView Whether we should return all
  1085. * questions (admin view) or just a list limited by the max number of random questions
  1086. * @return array - if the exercise is not set to take questions randomly, returns the question list
  1087. * without randomizing, otherwise, returns the list with questions selected randomly
  1088. */
  1089. public function selectRandomList($adminView = false)
  1090. {
  1091. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1092. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1093. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  1094. $randomLimit = "ORDER BY RAND() LIMIT $random";
  1095. // Random all questions so no limit
  1096. if ($random == -1 or $adminView === true) {
  1097. // If viewing it as admin for edition, don't show it randomly, use title + id
  1098. $randomLimit = 'ORDER BY e.question_order';
  1099. }
  1100. $sql = "SELECT e.question_id
  1101. FROM $TBL_EXERCISE_QUESTION e
  1102. INNER JOIN $TBL_QUESTIONS q
  1103. ON (e.question_id= q.id AND e.c_id = q.c_id)
  1104. WHERE
  1105. e.c_id = {$this->course_id} AND
  1106. e.exercice_id = '".Database::escape_string($this->id)."'
  1107. $randomLimit ";
  1108. $result = Database::query($sql);
  1109. $questionList = array();
  1110. while ($row = Database::fetch_object($result)) {
  1111. $questionList[] = $row->question_id;
  1112. }
  1113. return $questionList;
  1114. }
  1115. /**
  1116. * returns 'true' if the question ID is in the question list
  1117. *
  1118. * @author Olivier Brouckaert
  1119. * @param integer $questionId - question ID
  1120. * @return boolean - true if in the list, otherwise false
  1121. */
  1122. public function isInList($questionId)
  1123. {
  1124. if (is_array($this->questionList)) {
  1125. return in_array($questionId, $this->questionList);
  1126. } else {
  1127. return false;
  1128. }
  1129. }
  1130. /**
  1131. * changes the exercise title
  1132. *
  1133. * @author Olivier Brouckaert
  1134. * @param string $title - exercise title
  1135. */
  1136. public function updateTitle($title)
  1137. {
  1138. $this->title = $this->exercise = $title;
  1139. }
  1140. /**
  1141. * changes the exercise max attempts
  1142. *
  1143. * @param int $attempts - exercise max attempts
  1144. */
  1145. public function updateAttempts($attempts)
  1146. {
  1147. $this->attempts = $attempts;
  1148. }
  1149. /**
  1150. * changes the exercise feedback type
  1151. *
  1152. * @param int $feedback_type
  1153. */
  1154. public function updateFeedbackType($feedback_type)
  1155. {
  1156. $this->feedback_type = $feedback_type;
  1157. }
  1158. /**
  1159. * changes the exercise description
  1160. *
  1161. * @author Olivier Brouckaert
  1162. * @param string $description - exercise description
  1163. */
  1164. public function updateDescription($description)
  1165. {
  1166. $this->description = $description;
  1167. }
  1168. /**
  1169. * changes the exercise expired_time
  1170. *
  1171. * @author Isaac flores
  1172. * @param int $expired_time The expired time of the quiz
  1173. */
  1174. public function updateExpiredTime($expired_time)
  1175. {
  1176. $this->expired_time = $expired_time;
  1177. }
  1178. /**
  1179. * @param $value
  1180. */
  1181. public function updatePropagateNegative($value)
  1182. {
  1183. $this->propagate_neg = $value;
  1184. }
  1185. /**
  1186. * @param $value int
  1187. */
  1188. public function updateSaveCorrectAnswers($value)
  1189. {
  1190. $this->saveCorrectAnswers = $value;
  1191. }
  1192. /**
  1193. * @param $value
  1194. */
  1195. public function updateReviewAnswers($value)
  1196. {
  1197. $this->review_answers = isset($value) && $value ? true : false;
  1198. }
  1199. /**
  1200. * @param $value
  1201. */
  1202. public function updatePassPercentage($value)
  1203. {
  1204. $this->pass_percentage = $value;
  1205. }
  1206. /**
  1207. * @param string $text
  1208. */
  1209. public function updateEmailNotificationTemplate($text)
  1210. {
  1211. $this->emailNotificationTemplate = $text;
  1212. }
  1213. /**
  1214. * @param string $text
  1215. */
  1216. public function updateEmailNotificationTemplateToUser($text)
  1217. {
  1218. $this->emailNotificationTemplateToUser = $text;
  1219. }
  1220. /**
  1221. * @param string $value
  1222. */
  1223. public function setNotifyUserByEmail($value)
  1224. {
  1225. $this->notifyUserByEmail = $value;
  1226. }
  1227. /**
  1228. * @param int $value
  1229. */
  1230. public function updateEndButton($value)
  1231. {
  1232. $this->endButton = (int) $value;
  1233. }
  1234. /**
  1235. * @param string $value
  1236. */
  1237. public function setOnSuccessMessage($value)
  1238. {
  1239. $this->onSuccessMessage = $value;
  1240. }
  1241. /**
  1242. * @param string $value
  1243. */
  1244. public function setOnFailedMessage($value)
  1245. {
  1246. $this->onFailedMessage = $value;
  1247. }
  1248. /**
  1249. * @param $value
  1250. */
  1251. public function setModelType($value)
  1252. {
  1253. $this->modelType = (int) $value;
  1254. }
  1255. /**
  1256. * @param int $value
  1257. */
  1258. public function setQuestionSelectionType($value)
  1259. {
  1260. $this->questionSelectionType = (int) $value;
  1261. }
  1262. /**
  1263. * @return int
  1264. */
  1265. public function getQuestionSelectionType()
  1266. {
  1267. return $this->questionSelectionType;
  1268. }
  1269. /**
  1270. * @param array $categories
  1271. */
  1272. public function updateCategories($categories)
  1273. {
  1274. if (!empty($categories)) {
  1275. $categories = array_map('intval', $categories);
  1276. $this->categories = $categories;
  1277. }
  1278. }
  1279. /**
  1280. * changes the exercise sound file
  1281. *
  1282. * @author Olivier Brouckaert
  1283. * @param string $sound - exercise sound file
  1284. * @param string $delete - ask to delete the file
  1285. */
  1286. public function updateSound($sound, $delete)
  1287. {
  1288. global $audioPath, $documentPath;
  1289. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1290. if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
  1291. $this->sound = $sound['name'];
  1292. if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
  1293. $sql = "SELECT 1 FROM $TBL_DOCUMENT
  1294. WHERE
  1295. c_id = ".$this->course_id." AND
  1296. path = '".str_replace($documentPath, '', $audioPath).'/'.$this->sound."'";
  1297. $result = Database::query($sql);
  1298. if (!Database::num_rows($result)) {
  1299. $id = add_document(
  1300. $this->course,
  1301. str_replace($documentPath, '', $audioPath).'/'.$this->sound,
  1302. 'file',
  1303. $sound['size'],
  1304. $sound['name']
  1305. );
  1306. api_item_property_update(
  1307. $this->course,
  1308. TOOL_DOCUMENT,
  1309. $id,
  1310. 'DocumentAdded',
  1311. api_get_user_id()
  1312. );
  1313. item_property_update_on_folder(
  1314. $this->course,
  1315. str_replace($documentPath, '', $audioPath),
  1316. api_get_user_id()
  1317. );
  1318. }
  1319. }
  1320. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  1321. $this->sound = '';
  1322. }
  1323. }
  1324. /**
  1325. * changes the exercise type
  1326. *
  1327. * @author Olivier Brouckaert
  1328. * @param integer $type - exercise type
  1329. */
  1330. public function updateType($type)
  1331. {
  1332. $this->type = $type;
  1333. }
  1334. /**
  1335. * sets to 0 if questions are not selected randomly
  1336. * if questions are selected randomly, sets the draws
  1337. *
  1338. * @author Olivier Brouckaert
  1339. * @param integer $random - 0 if not random, otherwise the draws
  1340. */
  1341. public function setRandom($random)
  1342. {
  1343. /*if ($random == 'all') {
  1344. $random = $this->selectNbrQuestions();
  1345. }*/
  1346. $this->random = $random;
  1347. }
  1348. /**
  1349. * sets to 0 if answers are not selected randomly
  1350. * if answers are selected randomly
  1351. * @author Juan Carlos Rana
  1352. * @param integer $random_answers - random answers
  1353. */
  1354. public function updateRandomAnswers($random_answers)
  1355. {
  1356. $this->random_answers = $random_answers;
  1357. }
  1358. /**
  1359. * enables the exercise
  1360. *
  1361. * @author Olivier Brouckaert
  1362. */
  1363. public function enable()
  1364. {
  1365. $this->active = 1;
  1366. }
  1367. /**
  1368. * disables the exercise
  1369. *
  1370. * @author Olivier Brouckaert
  1371. */
  1372. public function disable()
  1373. {
  1374. $this->active = 0;
  1375. }
  1376. /**
  1377. * Set disable results
  1378. */
  1379. public function disable_results()
  1380. {
  1381. $this->results_disabled = true;
  1382. }
  1383. /**
  1384. * Enable results
  1385. */
  1386. public function enable_results()
  1387. {
  1388. $this->results_disabled = false;
  1389. }
  1390. /**
  1391. * @param int $results_disabled
  1392. */
  1393. public function updateResultsDisabled($results_disabled)
  1394. {
  1395. $this->results_disabled = (int) $results_disabled;
  1396. }
  1397. /**
  1398. * updates the exercise in the data base
  1399. * @param string $type_e
  1400. * @author Olivier Brouckaert
  1401. */
  1402. public function save($type_e = '')
  1403. {
  1404. $_course = $this->course;
  1405. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1406. $id = $this->id;
  1407. $exercise = $this->exercise;
  1408. $description = $this->description;
  1409. $sound = $this->sound;
  1410. $type = $this->type;
  1411. $attempts = isset($this->attempts) ? $this->attempts : 0;
  1412. $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
  1413. $random = $this->random;
  1414. $random_answers = $this->random_answers;
  1415. $active = $this->active;
  1416. $propagate_neg = (int) $this->propagate_neg;
  1417. $saveCorrectAnswers = isset($this->saveCorrectAnswers) && $this->saveCorrectAnswers ? 1 : 0;
  1418. $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
  1419. $randomByCat = intval($this->randomByCat);
  1420. $text_when_finished = $this->text_when_finished;
  1421. $display_category_name = intval($this->display_category_name);
  1422. $pass_percentage = intval($this->pass_percentage);
  1423. $session_id = $this->sessionId;
  1424. //If direct we do not show results
  1425. if ($feedback_type == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1426. $results_disabled = 0;
  1427. } else {
  1428. $results_disabled = intval($this->results_disabled);
  1429. }
  1430. $expired_time = intval($this->expired_time);
  1431. // Exercise already exists
  1432. if ($id) {
  1433. // we prepare date in the database using the api_get_utc_datetime() function
  1434. if (!empty($this->start_time)) {
  1435. $start_time = $this->start_time;
  1436. } else {
  1437. $start_time = null;
  1438. }
  1439. if (!empty($this->end_time)) {
  1440. $end_time = $this->end_time;
  1441. } else {
  1442. $end_time = null;
  1443. }
  1444. $params = [
  1445. 'title' => $exercise,
  1446. 'description' => $description,
  1447. ];
  1448. $paramsExtra = [];
  1449. if ($type_e != 'simple') {
  1450. $paramsExtra = [
  1451. 'sound' => $sound,
  1452. 'type' => $type,
  1453. 'random' => $random,
  1454. 'random_answers' => $random_answers,
  1455. 'active' => $active,
  1456. 'feedback_type' => $feedback_type,
  1457. 'start_time' => $start_time,
  1458. 'end_time' => $end_time,
  1459. 'max_attempt' => $attempts,
  1460. 'expired_time' => $expired_time,
  1461. 'propagate_neg' => $propagate_neg,
  1462. 'save_correct_answers' => $saveCorrectAnswers,
  1463. 'review_answers' => $review_answers,
  1464. 'random_by_category' => $randomByCat,
  1465. 'text_when_finished' => $text_when_finished,
  1466. 'display_category_name' => $display_category_name,
  1467. 'pass_percentage' => $pass_percentage,
  1468. 'results_disabled' => $results_disabled,
  1469. 'question_selection_type' => $this->getQuestionSelectionType(),
  1470. 'hide_question_title' => $this->getHideQuestionTitle()
  1471. ];
  1472. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1473. if ($allow === true) {
  1474. $paramsExtra['show_previous_button'] = $this->showPreviousButton();
  1475. }
  1476. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1477. if ($allow === true) {
  1478. $notifications = $this->getNotifications();
  1479. $notifications = implode(',', $notifications);
  1480. $paramsExtra['notifications'] = $notifications;
  1481. }
  1482. }
  1483. $params = array_merge($params, $paramsExtra);
  1484. Database::update(
  1485. $TBL_EXERCISES,
  1486. $params,
  1487. ['c_id = ? AND id = ?' => [$this->course_id, $id]]
  1488. );
  1489. // update into the item_property table
  1490. api_item_property_update(
  1491. $_course,
  1492. TOOL_QUIZ,
  1493. $id,
  1494. 'QuizUpdated',
  1495. api_get_user_id()
  1496. );
  1497. if (api_get_setting('search_enabled') == 'true') {
  1498. $this->search_engine_edit();
  1499. }
  1500. } else {
  1501. // Creates a new exercise
  1502. // In this case of new exercise, we don't do the api_get_utc_datetime()
  1503. // for date because, bellow, we call function api_set_default_visibility()
  1504. // In this function, api_set_default_visibility,
  1505. // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
  1506. // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
  1507. if (!empty($this->start_time)) {
  1508. $start_time = $this->start_time;
  1509. } else {
  1510. $start_time = null;
  1511. }
  1512. if (!empty($this->end_time)) {
  1513. $end_time = $this->end_time;
  1514. } else {
  1515. $end_time = null;
  1516. }
  1517. $params = [
  1518. 'c_id' => $this->course_id,
  1519. 'start_time' => $start_time,
  1520. 'end_time' => $end_time,
  1521. 'title' => $exercise,
  1522. 'description' => $description,
  1523. 'sound' => $sound,
  1524. 'type' => $type,
  1525. 'random' => $random,
  1526. 'random_answers' => $random_answers,
  1527. 'active' => $active,
  1528. 'results_disabled' => $results_disabled,
  1529. 'max_attempt' => $attempts,
  1530. 'feedback_type' => $feedback_type,
  1531. 'expired_time' => $expired_time,
  1532. 'session_id' => $session_id,
  1533. 'review_answers' => $review_answers,
  1534. 'random_by_category' => $randomByCat,
  1535. 'text_when_finished' => $text_when_finished,
  1536. 'display_category_name' => $display_category_name,
  1537. 'pass_percentage' => $pass_percentage,
  1538. 'save_correct_answers' => (int) $saveCorrectAnswers,
  1539. 'propagate_neg' => $propagate_neg,
  1540. 'hide_question_title' => $this->getHideQuestionTitle()
  1541. ];
  1542. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1543. if ($allow === true) {
  1544. $params['show_previous_button'] = $this->showPreviousButton();
  1545. }
  1546. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1547. if ($allow === true) {
  1548. $notifications = $this->getNotifications();
  1549. $notifications = implode(',', $notifications);
  1550. $params['notifications'] = $notifications;
  1551. }
  1552. $this->id = Database::insert($TBL_EXERCISES, $params);
  1553. if ($this->id) {
  1554. $sql = "UPDATE $TBL_EXERCISES SET id = iid WHERE iid = {$this->id} ";
  1555. Database::query($sql);
  1556. $sql = "UPDATE $TBL_EXERCISES
  1557. SET question_selection_type= ".intval($this->getQuestionSelectionType())."
  1558. WHERE id = ".$this->id." AND c_id = ".$this->course_id;
  1559. Database::query($sql);
  1560. // insert into the item_property table
  1561. api_item_property_update(
  1562. $this->course,
  1563. TOOL_QUIZ,
  1564. $this->id,
  1565. 'QuizAdded',
  1566. api_get_user_id()
  1567. );
  1568. // This function save the quiz again, carefull about start_time
  1569. // and end_time if you remove this line (see above)
  1570. api_set_default_visibility(
  1571. $this->id,
  1572. TOOL_QUIZ,
  1573. null,
  1574. $this->course
  1575. );
  1576. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1577. $this->search_engine_save();
  1578. }
  1579. }
  1580. }
  1581. $this->save_categories_in_exercise($this->categories);
  1582. // Updates the question position
  1583. $this->update_question_positions();
  1584. }
  1585. /**
  1586. * Updates question position
  1587. */
  1588. public function update_question_positions()
  1589. {
  1590. $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1591. //Fixes #3483 when updating order
  1592. $question_list = $this->selectQuestionList(true);
  1593. if (!empty($question_list)) {
  1594. foreach ($question_list as $position => $questionId) {
  1595. $sql = "UPDATE $table SET
  1596. question_order ='".intval($position)."'
  1597. WHERE
  1598. c_id = ".$this->course_id." AND
  1599. question_id = ".intval($questionId)." AND
  1600. exercice_id=".intval($this->id);
  1601. Database::query($sql);
  1602. }
  1603. }
  1604. }
  1605. /**
  1606. * Adds a question into the question list
  1607. *
  1608. * @author Olivier Brouckaert
  1609. * @param integer $questionId - question ID
  1610. * @return boolean - true if the question has been added, otherwise false
  1611. */
  1612. public function addToList($questionId)
  1613. {
  1614. // checks if the question ID is not in the list
  1615. if (!$this->isInList($questionId)) {
  1616. // selects the max position
  1617. if (!$this->selectNbrQuestions()) {
  1618. $pos = 1;
  1619. } else {
  1620. if (is_array($this->questionList)) {
  1621. $pos = max(array_keys($this->questionList)) + 1;
  1622. }
  1623. }
  1624. $this->questionList[$pos] = $questionId;
  1625. return true;
  1626. }
  1627. return false;
  1628. }
  1629. /**
  1630. * removes a question from the question list
  1631. *
  1632. * @author Olivier Brouckaert
  1633. * @param integer $questionId - question ID
  1634. * @return boolean - true if the question has been removed, otherwise false
  1635. */
  1636. public function removeFromList($questionId)
  1637. {
  1638. // searches the position of the question ID in the list
  1639. $pos = array_search($questionId, $this->questionList);
  1640. // question not found
  1641. if ($pos === false) {
  1642. return false;
  1643. } else {
  1644. // dont reduce the number of random question if we use random by category option, or if
  1645. // random all questions
  1646. if ($this->isRandom() && $this->isRandomByCat() == 0) {
  1647. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1648. $this->random -= 1;
  1649. $this->save();
  1650. }
  1651. }
  1652. // deletes the position from the array containing the wanted question ID
  1653. unset($this->questionList[$pos]);
  1654. return true;
  1655. }
  1656. }
  1657. /**
  1658. * deletes the exercise from the database
  1659. * Notice : leaves the question in the data base
  1660. *
  1661. * @author Olivier Brouckaert
  1662. */
  1663. public function delete()
  1664. {
  1665. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1666. $sql = "UPDATE $TBL_EXERCISES SET active='-1'
  1667. WHERE c_id = ".$this->course_id." AND id = ".intval($this->id);
  1668. Database::query($sql);
  1669. api_item_property_update(
  1670. $this->course,
  1671. TOOL_QUIZ,
  1672. $this->id,
  1673. 'QuizDeleted',
  1674. api_get_user_id()
  1675. );
  1676. api_item_property_update(
  1677. $this->course,
  1678. TOOL_QUIZ,
  1679. $this->id,
  1680. 'delete',
  1681. api_get_user_id()
  1682. );
  1683. if (api_get_setting('search_enabled') == 'true' &&
  1684. extension_loaded('xapian')
  1685. ) {
  1686. $this->search_engine_delete();
  1687. }
  1688. }
  1689. /**
  1690. * Creates the form to create / edit an exercise
  1691. * @param FormValidator $form
  1692. */
  1693. public function createForm($form, $type = 'full')
  1694. {
  1695. if (empty($type)) {
  1696. $type = 'full';
  1697. }
  1698. // form title
  1699. if (!empty($_GET['exerciseId'])) {
  1700. $form_title = get_lang('ModifyExercise');
  1701. } else {
  1702. $form_title = get_lang('NewEx');
  1703. }
  1704. $form->addElement('header', $form_title);
  1705. // Title.
  1706. if (api_get_configuration_value('save_titles_as_html')) {
  1707. $form->addHtmlEditor(
  1708. 'exerciseTitle',
  1709. get_lang('ExerciseName'),
  1710. false,
  1711. false,
  1712. ['ToolbarSet' => 'Minimal']
  1713. );
  1714. } else {
  1715. $form->addElement(
  1716. 'text',
  1717. 'exerciseTitle',
  1718. get_lang('ExerciseName'),
  1719. array('id' => 'exercise_title')
  1720. );
  1721. }
  1722. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  1723. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1724. $editor_config = array(
  1725. 'ToolbarSet' => 'TestQuestionDescription',
  1726. 'Width' => '100%',
  1727. 'Height' => '150',
  1728. );
  1729. if (is_array($type)) {
  1730. $editor_config = array_merge($editor_config, $type);
  1731. }
  1732. $form->addHtmlEditor(
  1733. 'exerciseDescription',
  1734. get_lang('ExerciseDescription'),
  1735. false,
  1736. false,
  1737. $editor_config
  1738. );
  1739. if ($type == 'full') {
  1740. //Can't modify a DirectFeedback question
  1741. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  1742. // feedback type
  1743. $radios_feedback = array();
  1744. $radios_feedback[] = $form->createElement(
  1745. 'radio',
  1746. 'exerciseFeedbackType',
  1747. null,
  1748. get_lang('ExerciseAtTheEndOfTheTest'),
  1749. '0',
  1750. array(
  1751. 'id' => 'exerciseType_0',
  1752. 'onclick' => 'check_feedback()',
  1753. )
  1754. );
  1755. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1756. //Can't convert a question from one feedback to another if there is more than 1 question already added
  1757. if ($this->selectNbrQuestions() == 0) {
  1758. $radios_feedback[] = $form->createElement(
  1759. 'radio',
  1760. 'exerciseFeedbackType',
  1761. null,
  1762. get_lang('DirectFeedback'),
  1763. '1',
  1764. array(
  1765. 'id' => 'exerciseType_1',
  1766. 'onclick' => 'check_direct_feedback()',
  1767. )
  1768. );
  1769. }
  1770. }
  1771. $radios_feedback[] = $form->createElement(
  1772. 'radio',
  1773. 'exerciseFeedbackType',
  1774. null,
  1775. get_lang('NoFeedback'),
  1776. '2',
  1777. array('id' => 'exerciseType_2')
  1778. );
  1779. $form->addGroup(
  1780. $radios_feedback,
  1781. null,
  1782. array(
  1783. get_lang('FeedbackType'),
  1784. get_lang('FeedbackDisplayOptions'),
  1785. )
  1786. );
  1787. // Type of results display on the final page
  1788. $radios_results_disabled = array();
  1789. $radios_results_disabled[] = $form->createElement(
  1790. 'radio',
  1791. 'results_disabled',
  1792. null,
  1793. get_lang('ShowScoreAndRightAnswer'),
  1794. '0',
  1795. array('id' => 'result_disabled_0')
  1796. );
  1797. $radios_results_disabled[] = $form->createElement(
  1798. 'radio',
  1799. 'results_disabled',
  1800. null,
  1801. get_lang('DoNotShowScoreNorRightAnswer'),
  1802. '1',
  1803. array('id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()')
  1804. );
  1805. $radios_results_disabled[] = $form->createElement(
  1806. 'radio',
  1807. 'results_disabled',
  1808. null,
  1809. get_lang('OnlyShowScore'),
  1810. '2',
  1811. array('id' => 'result_disabled_2')
  1812. );
  1813. $radios_results_disabled[] = $form->createElement(
  1814. 'radio',
  1815. 'results_disabled',
  1816. null,
  1817. get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
  1818. '4',
  1819. array('id' => 'result_disabled_4')
  1820. );
  1821. $form->addGroup(
  1822. $radios_results_disabled,
  1823. null,
  1824. get_lang('ShowResultsToStudents')
  1825. );
  1826. // Type of questions disposition on page
  1827. $radios = array();
  1828. $radios[] = $form->createElement(
  1829. 'radio',
  1830. 'exerciseType',
  1831. null,
  1832. get_lang('SimpleExercise'),
  1833. '1',
  1834. array(
  1835. 'onclick' => 'check_per_page_all()',
  1836. 'id' => 'option_page_all'
  1837. )
  1838. );
  1839. $radios[] = $form->createElement(
  1840. 'radio',
  1841. 'exerciseType',
  1842. null,
  1843. get_lang('SequentialExercise'),
  1844. '2',
  1845. array(
  1846. 'onclick' => 'check_per_page_one()',
  1847. 'id' => 'option_page_one'
  1848. )
  1849. );
  1850. $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1851. } else {
  1852. // if is Direct feedback but has not questions we can allow to modify the question type
  1853. if ($this->selectNbrQuestions() == 0) {
  1854. // feedback type
  1855. $radios_feedback = array();
  1856. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'), '0', array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  1857. if (api_get_setting('enable_quiz_scenario') == 'true') {
  1858. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1', 'onclick' => 'check_direct_feedback()'));
  1859. }
  1860. $radios_feedback[] = $form->createElement('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'), '2', array('id' =>'exerciseType_2'));
  1861. $form->addGroup($radios_feedback, null, array(get_lang('FeedbackType'), get_lang('FeedbackDisplayOptions')));
  1862. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  1863. $radios_results_disabled = array();
  1864. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  1865. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id'=>'result_disabled_1', 'onclick' => 'check_results_disabled()'));
  1866. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id'=>'result_disabled_2', 'onclick' => 'check_results_disabled()'));
  1867. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'), '');
  1868. // Type of questions disposition on page
  1869. $radios = array();
  1870. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  1871. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SequentialExercise'), '2');
  1872. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1873. } else {
  1874. //Show options freeze
  1875. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  1876. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1', array('id'=>'result_disabled_1', 'onclick' => 'check_results_disabled()'));
  1877. $radios_results_disabled[] = $form->createElement('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2', array('id'=>'result_disabled_2', 'onclick' => 'check_results_disabled()'));
  1878. $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'));
  1879. $result_disable_group->freeze();
  1880. //we force the options to the DirectFeedback exercisetype
  1881. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  1882. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1883. // Type of questions disposition on page
  1884. $radios[] = $form->createElement(
  1885. 'radio',
  1886. 'exerciseType',
  1887. null,
  1888. get_lang('SimpleExercise'),
  1889. '1',
  1890. array(
  1891. 'onclick' => 'check_per_page_all()',
  1892. 'id' => 'option_page_all',
  1893. )
  1894. );
  1895. $radios[] = $form->createElement(
  1896. 'radio',
  1897. 'exerciseType',
  1898. null,
  1899. get_lang('SequentialExercise'),
  1900. '2',
  1901. array(
  1902. 'onclick' => 'check_per_page_one()',
  1903. 'id' => 'option_page_one',
  1904. )
  1905. );
  1906. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1907. $type_group->freeze();
  1908. }
  1909. }
  1910. $option = array(
  1911. EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'),
  1912. // Defined by user
  1913. EX_Q_SELECTION_RANDOM => get_lang('Random'),
  1914. // 1-10, All
  1915. 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
  1916. // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
  1917. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'),
  1918. // A 123 B 456 C 78 (0, 1, all)
  1919. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'),
  1920. // C 78 B 456 A 123
  1921. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'),
  1922. // A 321 B 654 C 87
  1923. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'),
  1924. // C 87 B 654 A 321
  1925. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
  1926. /* B 456 C 78 A 123
  1927. 456 78 123
  1928. 123 456 78
  1929. */
  1930. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
  1931. /*
  1932. A 123 B 456 C 78
  1933. B 456 C 78 A 123
  1934. B 654 C 87 A 321
  1935. 654 87 321
  1936. 165 842 73
  1937. */
  1938. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
  1939. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
  1940. );
  1941. $form->addElement(
  1942. 'select',
  1943. 'question_selection_type',
  1944. array(get_lang('QuestionSelection')),
  1945. $option,
  1946. array(
  1947. 'id' => 'questionSelection',
  1948. 'onchange' => 'checkQuestionSelection()'
  1949. )
  1950. );
  1951. $displayMatrix = 'none';
  1952. $displayRandom = 'none';
  1953. $selectionType = $this->getQuestionSelectionType();
  1954. switch ($selectionType) {
  1955. case EX_Q_SELECTION_RANDOM:
  1956. $displayRandom = 'block';
  1957. break;
  1958. case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
  1959. $displayMatrix = 'block';
  1960. break;
  1961. }
  1962. $form->addElement(
  1963. 'html',
  1964. '<div id="hidden_random" style="display:'.$displayRandom.'">'
  1965. );
  1966. // Number of random question.
  1967. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10;
  1968. $option = range(0, $max);
  1969. $option[0] = get_lang('No');
  1970. $option[-1] = get_lang('AllQuestionsShort');
  1971. $form->addElement(
  1972. 'select',
  1973. 'randomQuestions',
  1974. array(
  1975. get_lang('RandomQuestions'),
  1976. get_lang('RandomQuestionsHelp')
  1977. ),
  1978. $option,
  1979. array('id' => 'randomQuestions')
  1980. );
  1981. $form->addElement('html', '</div>');
  1982. $form->addElement(
  1983. 'html',
  1984. '<div id="hidden_matrix" style="display:'.$displayMatrix.'">'
  1985. );
  1986. // Category selection.
  1987. $cat = new TestCategory();
  1988. $cat_form = $cat->returnCategoryForm($this);
  1989. if (empty($cat_form)) {
  1990. $cat_form = '<span class="label label-warning">'.get_lang('NoCategoriesDefined').'</span>';
  1991. }
  1992. $form->addElement('label', null, $cat_form);
  1993. $form->addElement('html', '</div>');
  1994. // Category name.
  1995. $radio_display_cat_name = array(
  1996. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
  1997. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0')
  1998. );
  1999. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'));
  2000. // Random answers.
  2001. $radios_random_answers = array(
  2002. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  2003. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0')
  2004. );
  2005. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  2006. // Hide question title.
  2007. $group = array(
  2008. $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
  2009. $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0')
  2010. );
  2011. $form->addGroup($group, null, get_lang('HideQuestionTitle'));
  2012. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  2013. if ($allow === true) {
  2014. // Hide question title.
  2015. $group = array(
  2016. $form->createElement(
  2017. 'radio',
  2018. 'show_previous_button',
  2019. null,
  2020. get_lang('Yes'),
  2021. '1'
  2022. ),
  2023. $form->createElement(
  2024. 'radio',
  2025. 'show_previous_button',
  2026. null,
  2027. get_lang('No'),
  2028. '0'
  2029. )
  2030. );
  2031. $form->addGroup($group, null, get_lang('ShowPreviousButton'));
  2032. }
  2033. // Attempts
  2034. $attempt_option = range(0, 10);
  2035. $attempt_option[0] = get_lang('Infinite');
  2036. $form->addElement(
  2037. 'select',
  2038. 'exerciseAttempts',
  2039. get_lang('ExerciseAttempts'),
  2040. $attempt_option,
  2041. ['id' => 'exerciseAttempts']
  2042. );
  2043. // Exercise time limit
  2044. $form->addElement(
  2045. 'checkbox',
  2046. 'activate_start_date_check',
  2047. null,
  2048. get_lang('EnableStartTime'),
  2049. array('onclick' => 'activate_start_date()')
  2050. );
  2051. $var = self::selectTimeLimit();
  2052. if (!empty($this->start_time)) {
  2053. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  2054. } else {
  2055. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  2056. }
  2057. $form->addElement('date_time_picker', 'start_time');
  2058. $form->addElement('html', '</div>');
  2059. $form->addElement(
  2060. 'checkbox',
  2061. 'activate_end_date_check',
  2062. null,
  2063. get_lang('EnableEndTime'),
  2064. array('onclick' => 'activate_end_date()')
  2065. );
  2066. if (!empty($this->end_time)) {
  2067. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  2068. } else {
  2069. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  2070. }
  2071. $form->addElement('date_time_picker', 'end_time');
  2072. $form->addElement('html', '</div>');
  2073. $display = 'block';
  2074. $form->addElement(
  2075. 'checkbox',
  2076. 'propagate_neg',
  2077. null,
  2078. get_lang('PropagateNegativeResults')
  2079. );
  2080. $form->addCheckBox(
  2081. 'save_correct_answers',
  2082. null,
  2083. get_lang('SaveTheCorrectAnswersForTheNextAttempt')
  2084. );
  2085. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  2086. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  2087. $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
  2088. // Timer control
  2089. //$time_hours_option = range(0,12);
  2090. //$time_minutes_option = range(0,59);
  2091. $form->addElement(
  2092. 'checkbox',
  2093. 'enabletimercontrol',
  2094. null,
  2095. get_lang('EnableTimerControl'),
  2096. array(
  2097. 'onclick' => 'option_time_expired()',
  2098. 'id' => 'enabletimercontrol',
  2099. 'onload' => 'check_load_time()',
  2100. )
  2101. );
  2102. $expired_date = (int) $this->selectExpiredTime();
  2103. if (($expired_date != '0')) {
  2104. $form->addElement('html', '<div id="timercontrol" style="display:block;">');
  2105. } else {
  2106. $form->addElement('html', '<div id="timercontrol" style="display:none;">');
  2107. }
  2108. $form->addText(
  2109. 'enabletimercontroltotalminutes',
  2110. get_lang('ExerciseTotalDurationInMinutes'),
  2111. false,
  2112. [
  2113. 'id' => 'enabletimercontroltotalminutes',
  2114. 'cols-size' => [2, 2, 8]
  2115. ]
  2116. );
  2117. $form->addElement('html', '</div>');
  2118. $form->addElement(
  2119. 'text',
  2120. 'pass_percentage',
  2121. array(get_lang('PassPercentage'), null, '%'),
  2122. array('id' => 'pass_percentage')
  2123. );
  2124. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  2125. $form->addRule('pass_percentage', get_lang('ValueTooSmall'), 'min_numeric_length', 0);
  2126. $form->addRule('pass_percentage', get_lang('ValueTooBig'), 'max_numeric_length', 100);
  2127. // add the text_when_finished textbox
  2128. $form->addHtmlEditor(
  2129. 'text_when_finished',
  2130. get_lang('TextWhenFinished'),
  2131. false,
  2132. false,
  2133. $editor_config
  2134. );
  2135. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  2136. if ($allow === true) {
  2137. $settings = ExerciseLib::getNotificationSettings();
  2138. $group = [];
  2139. foreach ($settings as $itemId => $label) {
  2140. $group[] = $form->createElement(
  2141. 'checkbox',
  2142. 'notifications[]',
  2143. null,
  2144. $label,
  2145. ['value' => $itemId]
  2146. );
  2147. }
  2148. $form->addGroup($group, '', [get_lang('EmailNotifications')]);
  2149. }
  2150. $form->addCheckBox(
  2151. 'update_title_in_lps',
  2152. null,
  2153. get_lang('UpdateTitleInLps')
  2154. );
  2155. $defaults = array();
  2156. if (api_get_setting('search_enabled') === 'true') {
  2157. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2158. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  2159. $form->addSelectLanguage('language', get_lang('SearchFeatureDocumentLanguage'));
  2160. $specific_fields = get_specific_field_list();
  2161. foreach ($specific_fields as $specific_field) {
  2162. $form->addElement('text', $specific_field['code'], $specific_field['name']);
  2163. $filter = array(
  2164. 'c_id' => api_get_course_int_id(),
  2165. 'field_id' => $specific_field['id'],
  2166. 'ref_id' => $this->id,
  2167. 'tool_id' => "'".TOOL_QUIZ."'"
  2168. );
  2169. $values = get_specific_field_values_list($filter, array('value'));
  2170. if (!empty($values)) {
  2171. $arr_str_values = array();
  2172. foreach ($values as $value) {
  2173. $arr_str_values[] = $value['value'];
  2174. }
  2175. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  2176. }
  2177. }
  2178. }
  2179. $form->addElement('html', '</div>'); //End advanced setting
  2180. $form->addElement('html', '</div>');
  2181. }
  2182. // submit
  2183. if (isset($_GET['exerciseId'])) {
  2184. $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise');
  2185. } else {
  2186. $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise');
  2187. }
  2188. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  2189. if ($type == 'full') {
  2190. // rules
  2191. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  2192. $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
  2193. $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
  2194. }
  2195. // defaults
  2196. if ($type == 'full') {
  2197. if ($this->id > 0) {
  2198. if ($this->random > $this->selectNbrQuestions()) {
  2199. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  2200. } else {
  2201. $defaults['randomQuestions'] = $this->random;
  2202. }
  2203. $defaults['randomAnswers'] = $this->selectRandomAnswers();
  2204. $defaults['exerciseType'] = $this->selectType();
  2205. $defaults['exerciseTitle'] = $this->get_formated_title();
  2206. $defaults['exerciseDescription'] = $this->selectDescription();
  2207. $defaults['exerciseAttempts'] = $this->selectAttempts();
  2208. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  2209. $defaults['results_disabled'] = $this->selectResultsDisabled();
  2210. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  2211. $defaults['save_correct_answers'] = $this->selectSaveCorrectAnswers();
  2212. $defaults['review_answers'] = $this->review_answers;
  2213. $defaults['randomByCat'] = $this->selectRandomByCat();
  2214. $defaults['text_when_finished'] = $this->selectTextWhenFinished();
  2215. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  2216. $defaults['pass_percentage'] = $this->selectPassPercentage();
  2217. $defaults['question_selection_type'] = $this->getQuestionSelectionType();
  2218. $defaults['hide_question_title'] = $this->getHideQuestionTitle();
  2219. $defaults['show_previous_button'] = $this->showPreviousButton();
  2220. if (!empty($this->start_time)) {
  2221. $defaults['activate_start_date_check'] = 1;
  2222. }
  2223. if (!empty($this->end_time)) {
  2224. $defaults['activate_end_date_check'] = 1;
  2225. }
  2226. $defaults['start_time'] = !empty($this->start_time) ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
  2227. $defaults['end_time'] = !empty($this->end_time) ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time() + 84600);
  2228. // Get expired time
  2229. if ($this->expired_time != '0') {
  2230. $defaults['enabletimercontrol'] = 1;
  2231. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  2232. } else {
  2233. $defaults['enabletimercontroltotalminutes'] = 0;
  2234. }
  2235. $defaults['notifications'] = $this->getNotifications();
  2236. } else {
  2237. $defaults['exerciseType'] = 2;
  2238. $defaults['exerciseAttempts'] = 0;
  2239. $defaults['randomQuestions'] = 0;
  2240. $defaults['randomAnswers'] = 0;
  2241. $defaults['exerciseDescription'] = '';
  2242. $defaults['exerciseFeedbackType'] = 0;
  2243. $defaults['results_disabled'] = 0;
  2244. $defaults['randomByCat'] = 0;
  2245. $defaults['text_when_finished'] = '';
  2246. $defaults['start_time'] = date('Y-m-d 12:00:00');
  2247. $defaults['display_category_name'] = 1;
  2248. $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
  2249. $defaults['pass_percentage'] = '';
  2250. $defaults['end_button'] = $this->selectEndButton();
  2251. $defaults['question_selection_type'] = 1;
  2252. $defaults['hide_question_title'] = 0;
  2253. $defaults['show_previous_button'] = 1;
  2254. $defaults['on_success_message'] = null;
  2255. $defaults['on_failed_message'] = null;
  2256. }
  2257. } else {
  2258. $defaults['exerciseTitle'] = $this->selectTitle();
  2259. $defaults['exerciseDescription'] = $this->selectDescription();
  2260. }
  2261. if (api_get_setting('search_enabled') === 'true') {
  2262. $defaults['index_document'] = 'checked="checked"';
  2263. }
  2264. $form->setDefaults($defaults);
  2265. // Freeze some elements.
  2266. if ($this->id != 0 && $this->edit_exercise_in_lp == false) {
  2267. $elementsToFreeze = array(
  2268. 'randomQuestions',
  2269. //'randomByCat',
  2270. 'exerciseAttempts',
  2271. 'propagate_neg',
  2272. 'enabletimercontrol',
  2273. 'review_answers'
  2274. );
  2275. foreach ($elementsToFreeze as $elementName) {
  2276. /** @var HTML_QuickForm_element $element */
  2277. $element = $form->getElement($elementName);
  2278. $element->freeze();
  2279. }
  2280. }
  2281. }
  2282. /**
  2283. * function which process the creation of exercises
  2284. * @param FormValidator $form
  2285. * @param string
  2286. */
  2287. public function processCreation($form, $type = '')
  2288. {
  2289. $this->updateTitle(self::format_title_variable($form->getSubmitValue('exerciseTitle')));
  2290. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  2291. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  2292. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  2293. $this->updateType($form->getSubmitValue('exerciseType'));
  2294. $this->setRandom($form->getSubmitValue('randomQuestions'));
  2295. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  2296. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  2297. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  2298. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  2299. $this->updateSaveCorrectAnswers($form->getSubmitValue('save_correct_answers'));
  2300. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  2301. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  2302. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  2303. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  2304. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  2305. $this->updateCategories($form->getSubmitValue('category'));
  2306. $this->updateEndButton($form->getSubmitValue('end_button'));
  2307. $this->setOnSuccessMessage($form->getSubmitValue('on_success_message'));
  2308. $this->setOnFailedMessage($form->getSubmitValue('on_failed_message'));
  2309. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  2310. $this->updateEmailNotificationTemplateToUser($form->getSubmitValue('email_notification_template_to_user'));
  2311. $this->setNotifyUserByEmail($form->getSubmitValue('notify_user_by_email'));
  2312. $this->setModelType($form->getSubmitValue('model_type'));
  2313. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2314. $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
  2315. $this->sessionId = api_get_session_id();
  2316. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2317. $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
  2318. $this->setGlobalCategoryId($form->getSubmitValue('global_category_id'));
  2319. $this->setShowPreviousButton($form->getSubmitValue('show_previous_button'));
  2320. $this->setNotifications($form->getSubmitValue('notifications'));
  2321. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  2322. $start_time = $form->getSubmitValue('start_time');
  2323. $this->start_time = api_get_utc_datetime($start_time);
  2324. } else {
  2325. $this->start_time = null;
  2326. }
  2327. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  2328. $end_time = $form->getSubmitValue('end_time');
  2329. $this->end_time = api_get_utc_datetime($end_time);
  2330. } else {
  2331. $this->end_time = null;
  2332. }
  2333. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  2334. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  2335. if ($this->expired_time == 0) {
  2336. $this->expired_time = $expired_total_time;
  2337. }
  2338. } else {
  2339. $this->expired_time = 0;
  2340. }
  2341. if ($form->getSubmitValue('randomAnswers') == 1) {
  2342. $this->random_answers = 1;
  2343. } else {
  2344. $this->random_answers = 0;
  2345. }
  2346. // Update title in all LPs that have this quiz added
  2347. if ($form->getSubmitValue('update_title_in_lps') == 1) {
  2348. $courseId = api_get_course_int_id();
  2349. $table = Database::get_course_table(TABLE_LP_ITEM);
  2350. $sql = "SELECT * FROM $table
  2351. WHERE
  2352. c_id = $courseId AND
  2353. item_type = 'quiz' AND
  2354. path = '".$this->id."'
  2355. ";
  2356. $result = Database::query($sql);
  2357. $items = Database::store_result($result);
  2358. if (!empty($items)) {
  2359. foreach ($items as $item) {
  2360. $itemId = $item['iid'];
  2361. $sql = "UPDATE $table SET title = '".$this->title."'
  2362. WHERE iid = $itemId AND c_id = $courseId ";
  2363. Database::query($sql);
  2364. }
  2365. }
  2366. }
  2367. $this->save($type);
  2368. }
  2369. function search_engine_save()
  2370. {
  2371. if ($_POST['index_document'] != 1) {
  2372. return;
  2373. }
  2374. $course_id = api_get_course_id();
  2375. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  2376. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  2377. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2378. $specific_fields = get_specific_field_list();
  2379. $ic_slide = new IndexableChunk();
  2380. $all_specific_terms = '';
  2381. foreach ($specific_fields as $specific_field) {
  2382. if (isset($_REQUEST[$specific_field['code']])) {
  2383. $sterms = trim($_REQUEST[$specific_field['code']]);
  2384. if (!empty($sterms)) {
  2385. $all_specific_terms .= ' '.$sterms;
  2386. $sterms = explode(',', $sterms);
  2387. foreach ($sterms as $sterm) {
  2388. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2389. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2390. }
  2391. }
  2392. }
  2393. }
  2394. // build the chunk to index
  2395. $ic_slide->addValue("title", $this->exercise);
  2396. $ic_slide->addCourseId($course_id);
  2397. $ic_slide->addToolId(TOOL_QUIZ);
  2398. $xapian_data = array(
  2399. SE_COURSE_ID => $course_id,
  2400. SE_TOOL_ID => TOOL_QUIZ,
  2401. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id),
  2402. SE_USER => (int) api_get_user_id(),
  2403. );
  2404. $ic_slide->xapian_data = serialize($xapian_data);
  2405. $exercise_description = $all_specific_terms.' '.$this->description;
  2406. $ic_slide->addValue("content", $exercise_description);
  2407. $di = new ChamiloIndexer();
  2408. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2409. $di->connectDb(NULL, NULL, $lang);
  2410. $di->addChunk($ic_slide);
  2411. //index and return search engine document id
  2412. $did = $di->index();
  2413. if ($did) {
  2414. // save it to db
  2415. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2416. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2417. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2418. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2419. Database::query($sql);
  2420. }
  2421. }
  2422. function search_engine_edit()
  2423. {
  2424. // update search enchine and its values table if enabled
  2425. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2426. $course_id = api_get_course_id();
  2427. // actually, it consists on delete terms from db,
  2428. // insert new ones, create a new search engine document, and remove the old one
  2429. // get search_did
  2430. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2431. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2432. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2433. $res = Database::query($sql);
  2434. if (Database::num_rows($res) > 0) {
  2435. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  2436. require_once(api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php');
  2437. require_once(api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php');
  2438. $se_ref = Database::fetch_array($res);
  2439. $specific_fields = get_specific_field_list();
  2440. $ic_slide = new IndexableChunk();
  2441. $all_specific_terms = '';
  2442. foreach ($specific_fields as $specific_field) {
  2443. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  2444. if (isset($_REQUEST[$specific_field['code']])) {
  2445. $sterms = trim($_REQUEST[$specific_field['code']]);
  2446. $all_specific_terms .= ' '.$sterms;
  2447. $sterms = explode(',', $sterms);
  2448. foreach ($sterms as $sterm) {
  2449. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2450. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2451. }
  2452. }
  2453. }
  2454. // build the chunk to index
  2455. $ic_slide->addValue("title", $this->exercise);
  2456. $ic_slide->addCourseId($course_id);
  2457. $ic_slide->addToolId(TOOL_QUIZ);
  2458. $xapian_data = array(
  2459. SE_COURSE_ID => $course_id,
  2460. SE_TOOL_ID => TOOL_QUIZ,
  2461. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id),
  2462. SE_USER => (int) api_get_user_id(),
  2463. );
  2464. $ic_slide->xapian_data = serialize($xapian_data);
  2465. $exercise_description = $all_specific_terms.' '.$this->description;
  2466. $ic_slide->addValue("content", $exercise_description);
  2467. $di = new ChamiloIndexer();
  2468. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2469. $di->connectDb(null, null, $lang);
  2470. $di->remove_document((int) $se_ref['search_did']);
  2471. $di->addChunk($ic_slide);
  2472. //index and return search engine document id
  2473. $did = $di->index();
  2474. if ($did) {
  2475. // save it to db
  2476. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  2477. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2478. Database::query($sql);
  2479. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2480. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2481. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2482. Database::query($sql);
  2483. }
  2484. } else {
  2485. $this->search_engine_save();
  2486. }
  2487. }
  2488. }
  2489. function search_engine_delete()
  2490. {
  2491. // remove from search engine if enabled
  2492. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2493. $course_id = api_get_course_id();
  2494. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2495. $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';
  2496. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2497. $res = Database::query($sql);
  2498. if (Database::num_rows($res) > 0) {
  2499. $row = Database::fetch_array($res);
  2500. require_once(api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php');
  2501. $di = new ChamiloIndexer();
  2502. $di->remove_document((int) $row['search_did']);
  2503. unset($di);
  2504. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2505. foreach ($this->questionList as $question_i) {
  2506. $sql = 'SELECT type FROM %s WHERE id=%s';
  2507. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  2508. $qres = Database::query($sql);
  2509. if (Database::num_rows($qres) > 0) {
  2510. $qrow = Database::fetch_array($qres);
  2511. $objQuestion = Question::getInstance($qrow['type']);
  2512. $objQuestion = Question::read((int) $question_i);
  2513. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  2514. unset($objQuestion);
  2515. }
  2516. }
  2517. }
  2518. $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';
  2519. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2520. Database::query($sql);
  2521. // remove terms from db
  2522. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2523. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  2524. }
  2525. }
  2526. public function selectExpiredTime()
  2527. {
  2528. return $this->expired_time;
  2529. }
  2530. /**
  2531. * Cleans the student's results only for the Exercise tool (Not from the LP)
  2532. * The LP results are NOT deleted by default, otherwise put $cleanLpTests = true
  2533. * Works with exercises in sessions
  2534. * @param bool $cleanLpTests
  2535. * @param string $cleanResultBeforeDate
  2536. *
  2537. * @return int quantity of user's exercises deleted
  2538. */
  2539. public function clean_results($cleanLpTests = false, $cleanResultBeforeDate = null)
  2540. {
  2541. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2542. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2543. $sql_where = ' AND
  2544. orig_lp_id = 0 AND
  2545. orig_lp_item_id = 0';
  2546. // if we want to delete results from LP too
  2547. if ($cleanLpTests) {
  2548. $sql_where = "";
  2549. }
  2550. // if we want to delete attempts before date $cleanResultBeforeDate
  2551. // $cleanResultBeforeDate must be a valid UTC-0 date yyyy-mm-dd
  2552. if (!empty($cleanResultBeforeDate)) {
  2553. $cleanResultBeforeDate = Database::escape_string($cleanResultBeforeDate);
  2554. if (api_is_valid_date($cleanResultBeforeDate)) {
  2555. $sql_where .= " AND exe_date <= '$cleanResultBeforeDate' ";
  2556. } else {
  2557. return 0;
  2558. }
  2559. }
  2560. $sql = "SELECT exe_id
  2561. FROM $table_track_e_exercises
  2562. WHERE
  2563. c_id = ".api_get_course_int_id()." AND
  2564. exe_exo_id = ".$this->id." AND
  2565. session_id = ".api_get_session_id()." ".
  2566. $sql_where;
  2567. $result = Database::query($sql);
  2568. $exe_list = Database::store_result($result);
  2569. // deleting TRACK_E_ATTEMPT table
  2570. // check if exe in learning path or not
  2571. $i = 0;
  2572. if (is_array($exe_list) && count($exe_list) > 0) {
  2573. foreach ($exe_list as $item) {
  2574. $sql = "DELETE FROM $table_track_e_attempt
  2575. WHERE exe_id = '".$item['exe_id']."'";
  2576. Database::query($sql);
  2577. $i++;
  2578. }
  2579. }
  2580. $session_id = api_get_session_id();
  2581. // delete TRACK_E_EXERCISES table
  2582. $sql = "DELETE FROM $table_track_e_exercises
  2583. WHERE c_id = ".api_get_course_int_id()."
  2584. AND exe_exo_id = ".$this->id."
  2585. $sql_where
  2586. AND session_id = ".$session_id."";
  2587. Database::query($sql);
  2588. Event::addEvent(
  2589. LOG_EXERCISE_RESULT_DELETE,
  2590. LOG_EXERCISE_ID,
  2591. $this->id,
  2592. null,
  2593. null,
  2594. api_get_course_int_id(),
  2595. $session_id
  2596. );
  2597. return $i;
  2598. }
  2599. /**
  2600. * Copies an exercise (duplicate all questions and answers)
  2601. */
  2602. public function copy_exercise()
  2603. {
  2604. $exercise_obj = $this;
  2605. // force the creation of a new exercise
  2606. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  2607. //Hides the new exercise
  2608. $exercise_obj->updateStatus(false);
  2609. $exercise_obj->updateId(0);
  2610. $exercise_obj->save();
  2611. $new_exercise_id = $exercise_obj->selectId();
  2612. $question_list = $exercise_obj->selectQuestionList();
  2613. if (!empty($question_list)) {
  2614. //Question creation
  2615. foreach ($question_list as $old_question_id) {
  2616. $old_question_obj = Question::read($old_question_id);
  2617. $new_id = $old_question_obj->duplicate();
  2618. if ($new_id) {
  2619. $new_question_obj = Question::read($new_id);
  2620. if (isset($new_question_obj) && $new_question_obj) {
  2621. $new_question_obj->addToList($new_exercise_id);
  2622. // This should be moved to the duplicate function
  2623. $new_answer_obj = new Answer($old_question_id);
  2624. $new_answer_obj->read();
  2625. $new_answer_obj->duplicate($new_question_obj);
  2626. }
  2627. }
  2628. }
  2629. }
  2630. }
  2631. /**
  2632. * Changes the exercise id
  2633. *
  2634. * @param int $id - exercise id
  2635. */
  2636. private function updateId($id)
  2637. {
  2638. $this->id = $id;
  2639. }
  2640. /**
  2641. * Changes the exercise status
  2642. *
  2643. * @param string $status - exercise status
  2644. */
  2645. function updateStatus($status)
  2646. {
  2647. $this->active = $status;
  2648. }
  2649. /**
  2650. * @param int $lp_id
  2651. * @param int $lp_item_id
  2652. * @param int $lp_item_view_id
  2653. * @param string $status
  2654. * @return array
  2655. */
  2656. public function get_stat_track_exercise_info(
  2657. $lp_id = 0,
  2658. $lp_item_id = 0,
  2659. $lp_item_view_id = 0,
  2660. $status = 'incomplete'
  2661. ) {
  2662. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2663. if (empty($lp_id)) {
  2664. $lp_id = 0;
  2665. }
  2666. if (empty($lp_item_id)) {
  2667. $lp_item_id = 0;
  2668. }
  2669. if (empty($lp_item_view_id)) {
  2670. $lp_item_view_id = 0;
  2671. }
  2672. $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
  2673. exe_user_id = ' . "'".api_get_user_id()."'".' AND
  2674. c_id = ' . api_get_course_int_id().' AND
  2675. status = ' . "'".Database::escape_string($status)."'".' AND
  2676. orig_lp_id = ' . "'".$lp_id."'".' AND
  2677. orig_lp_item_id = ' . "'".$lp_item_id."'".' AND
  2678. orig_lp_item_view_id = ' . "'".$lp_item_view_id."'".' AND
  2679. session_id = ' . "'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
  2680. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2681. $result = Database::query($sql_track);
  2682. $new_array = array();
  2683. if (Database::num_rows($result) > 0) {
  2684. $new_array = Database::fetch_array($result, 'ASSOC');
  2685. $new_array['num_exe'] = Database::num_rows($result);
  2686. }
  2687. return $new_array;
  2688. }
  2689. /**
  2690. * Saves a test attempt
  2691. *
  2692. * @param int $clock_expired_time clock_expired_time
  2693. * @param int int lp id
  2694. * @param int int lp item id
  2695. * @param int int lp item_view id
  2696. * @param array $questionList
  2697. * @param float $weight
  2698. *
  2699. * @return int
  2700. */
  2701. public function save_stat_track_exercise_info(
  2702. $clock_expired_time = 0,
  2703. $safe_lp_id = 0,
  2704. $safe_lp_item_id = 0,
  2705. $safe_lp_item_view_id = 0,
  2706. $questionList = array(),
  2707. $weight = 0
  2708. ) {
  2709. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2710. $safe_lp_id = intval($safe_lp_id);
  2711. $safe_lp_item_id = intval($safe_lp_item_id);
  2712. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  2713. if (empty($safe_lp_id)) {
  2714. $safe_lp_id = 0;
  2715. }
  2716. if (empty($safe_lp_item_id)) {
  2717. $safe_lp_item_id = 0;
  2718. }
  2719. if (empty($clock_expired_time)) {
  2720. $clock_expired_time = null;
  2721. }
  2722. $questionList = array_map('intval', $questionList);
  2723. $params = array(
  2724. 'exe_exo_id' => $this->id,
  2725. 'exe_user_id' => api_get_user_id(),
  2726. 'c_id' => api_get_course_int_id(),
  2727. 'status' => 'incomplete',
  2728. 'session_id' => api_get_session_id(),
  2729. 'data_tracking' => implode(',', $questionList),
  2730. 'start_date' => api_get_utc_datetime(),
  2731. 'orig_lp_id' => $safe_lp_id,
  2732. 'orig_lp_item_id' => $safe_lp_item_id,
  2733. 'orig_lp_item_view_id' => $safe_lp_item_view_id,
  2734. 'exe_weighting'=> $weight,
  2735. 'user_ip' => api_get_real_ip(),
  2736. 'exe_date' => api_get_utc_datetime(),
  2737. 'exe_result' => 0,
  2738. 'steps_counter' => 0,
  2739. 'exe_duration' => 0,
  2740. 'expired_time_control' => $clock_expired_time,
  2741. 'questions_to_check' => ''
  2742. );
  2743. $id = Database::insert($track_exercises, $params);
  2744. return $id;
  2745. }
  2746. /**
  2747. * @param int $question_id
  2748. * @param int $questionNum
  2749. * @param array $questions_in_media
  2750. * @param string $currentAnswer
  2751. * @return string
  2752. */
  2753. public function show_button(
  2754. $question_id,
  2755. $questionNum,
  2756. $questions_in_media = array(),
  2757. $currentAnswer = ''
  2758. ) {
  2759. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2760. $nbrQuestions = $this->get_count_question_list();
  2761. $all_button = [];
  2762. $html = $label = '';
  2763. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
  2764. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  2765. $urlTitle = get_lang('ContinueTest');
  2766. if ($questionNum == count($this->questionList)) {
  2767. $urlTitle = get_lang('EndTest');
  2768. }
  2769. $html .= Display::url(
  2770. $urlTitle,
  2771. 'exercise_submit_modal.php?'.http_build_query([
  2772. 'learnpath_id' => $safe_lp_id,
  2773. 'learnpath_item_id' => $safe_lp_item_id,
  2774. 'learnpath_item_view_id' => $safe_lp_item_view_id,
  2775. 'origin' => $origin,
  2776. 'hotspot' => $hotspot_get,
  2777. 'nbrQuestions' => $nbrQuestions,
  2778. 'num' => $questionNum,
  2779. 'exerciseType' => $this->type,
  2780. 'exerciseId' => $this->id
  2781. ]),
  2782. [
  2783. 'class' => 'ajax btn btn-default',
  2784. 'data-title' => $urlTitle,
  2785. 'data-size' => 'md'
  2786. ]
  2787. );
  2788. $html .= '<br />';
  2789. } else {
  2790. // User
  2791. if (api_is_allowed_to_session_edit()) {
  2792. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  2793. if ($this->review_answers) {
  2794. $label = get_lang('ReviewQuestions');
  2795. $class = 'btn btn-success';
  2796. } else {
  2797. $label = get_lang('EndTest');
  2798. $class = 'btn btn-warning';
  2799. }
  2800. } else {
  2801. $label = get_lang('NextQuestion');
  2802. $class = 'btn btn-primary';
  2803. }
  2804. // used to select it with jquery
  2805. $class .= ' question-validate-btn';
  2806. if ($this->type == ONE_PER_PAGE) {
  2807. if ($questionNum != 1) {
  2808. if ($this->showPreviousButton()) {
  2809. $prev_question = $questionNum - 2;
  2810. $all_button[] = Display::button(
  2811. 'previous_question_and_save',
  2812. get_lang('PreviousQuestion'),
  2813. [
  2814. 'type' => 'button',
  2815. 'class' => 'btn btn-default',
  2816. 'data-prev' => $prev_question,
  2817. 'data-question' => $question_id
  2818. ]
  2819. );
  2820. }
  2821. }
  2822. // Next question
  2823. if (!empty($questions_in_media)) {
  2824. $all_button[] = Display::button(
  2825. 'save_question_list',
  2826. $label,
  2827. [
  2828. 'type' => 'button',
  2829. 'class' => $class,
  2830. 'data-list' => implode(",", $questions_in_media)
  2831. ]
  2832. );
  2833. } else {
  2834. $all_button[] = Display::button(
  2835. 'save_now',
  2836. $label,
  2837. ['type' => 'button', 'class' => $class, 'data-question' => $question_id]
  2838. );
  2839. }
  2840. $all_button[] = '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2841. $html .= implode(PHP_EOL, $all_button);
  2842. } else {
  2843. if ($this->review_answers) {
  2844. $all_label = get_lang('ReviewQuestions');
  2845. $class = 'btn btn-success';
  2846. } else {
  2847. $all_label = get_lang('EndTest');
  2848. $class = 'btn btn-warning';
  2849. }
  2850. // used to select it with jquery
  2851. $class .= ' question-validate-btn';
  2852. $all_button[] = Display::button(
  2853. 'validate_all',
  2854. $all_label,
  2855. ['type' => 'button', 'class' => $class]
  2856. );
  2857. $all_button[] = '&nbsp;'.Display::span(null, ['id' => 'save_all_reponse']);
  2858. $html .= implode(PHP_EOL, $all_button);
  2859. }
  2860. }
  2861. }
  2862. return $html;
  2863. }
  2864. /**
  2865. * So the time control will work
  2866. *
  2867. * @param string $time_left
  2868. * @return string
  2869. */
  2870. public function showTimeControlJS($time_left)
  2871. {
  2872. $time_left = intval($time_left);
  2873. return "<script>
  2874. function get_expired_date_string(expired_time) {
  2875. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  2876. var day, month, year, hours, minutes, seconds, date_string;
  2877. var obj_date = new Date(expired_time);
  2878. day = obj_date.getDate();
  2879. if (day < 10) day = '0' + day;
  2880. month = obj_date.getMonth();
  2881. year = obj_date.getFullYear();
  2882. hours = obj_date.getHours();
  2883. if (hours < 10) hours = '0' + hours;
  2884. minutes = obj_date.getMinutes();
  2885. if (minutes < 10) minutes = '0' + minutes;
  2886. seconds = obj_date.getSeconds();
  2887. if (seconds < 10) seconds = '0' + seconds;
  2888. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  2889. return date_string;
  2890. }
  2891. function open_clock_warning() {
  2892. $('#clock_warning').dialog({
  2893. modal:true,
  2894. height:250,
  2895. closeOnEscape: false,
  2896. resizable: false,
  2897. buttons: {
  2898. '".addslashes(get_lang("EndTest"))."': function() {
  2899. $('#clock_warning').dialog('close');
  2900. }
  2901. },
  2902. close: function() {
  2903. send_form();
  2904. }
  2905. });
  2906. $('#clock_warning').dialog('open');
  2907. $('#counter_to_redirect').epiclock({
  2908. mode: $.epiclock.modes.countdown,
  2909. offset: {seconds: 5},
  2910. format: 's'
  2911. }).bind('timer', function () {
  2912. send_form();
  2913. });
  2914. }
  2915. function send_form() {
  2916. if ($('#exercise_form').length) {
  2917. $('#exercise_form').submit();
  2918. } else {
  2919. // In exercise_reminder.php
  2920. final_submit();
  2921. }
  2922. }
  2923. function onExpiredTimeExercise() {
  2924. $('#wrapper-clock').hide();
  2925. //$('#exercise_form').hide();
  2926. $('#expired-message-id').show();
  2927. //Fixes bug #5263
  2928. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  2929. open_clock_warning();
  2930. }
  2931. $(document).ready(function() {
  2932. var current_time = new Date().getTime();
  2933. var time_left = parseInt(".$time_left."); // time in seconds when using minutes there are some seconds lost
  2934. var expired_time = current_time + (time_left*1000);
  2935. var expired_date = get_expired_date_string(expired_time);
  2936. $('#exercise_clock_warning').epiclock({
  2937. mode: $.epiclock.modes.countdown,
  2938. offset: {seconds: time_left},
  2939. format: 'x:i:s',
  2940. renderer: 'minute'
  2941. }).bind('timer', function () {
  2942. onExpiredTimeExercise();
  2943. });
  2944. $('#submit_save').click(function () {});
  2945. });
  2946. </script>";
  2947. }
  2948. /**
  2949. * Lp javascript for hotspots
  2950. */
  2951. public function show_lp_javascript()
  2952. {
  2953. return '';
  2954. }
  2955. /**
  2956. * This function was originally found in the exercise_show.php
  2957. * @param int $exeId
  2958. * @param int $questionId
  2959. * @param int $choice the user selected
  2960. * @param string $from function is called from 'exercise_show' or 'exercise_result'
  2961. * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] = coordinates
  2962. * @param bool $saved_results save results in the DB or just show the reponse
  2963. * @param bool $from_database gets information from DB or from the current selection
  2964. * @param bool $show_result show results or not
  2965. * @param int $propagate_neg
  2966. * @param array $hotspot_delineation_result
  2967. * @param bool $showTotalScoreAndUserChoicesInLastAttempt
  2968. * @todo reduce parameters of this function
  2969. * @return string html code
  2970. */
  2971. public function manage_answer(
  2972. $exeId,
  2973. $questionId,
  2974. $choice,
  2975. $from = 'exercise_show',
  2976. $exerciseResultCoordinates = [],
  2977. $saved_results = true,
  2978. $from_database = false,
  2979. $show_result = true,
  2980. $propagate_neg = 0,
  2981. $hotspot_delineation_result = [],
  2982. $showTotalScoreAndUserChoicesInLastAttempt = true
  2983. ) {
  2984. global $debug;
  2985. //needed in order to use in the exercise_attempt() for the time
  2986. global $learnpath_id, $learnpath_item_id;
  2987. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  2988. $em = Database::getManager();
  2989. $feedback_type = $this->selectFeedbackType();
  2990. $results_disabled = $this->selectResultsDisabled();
  2991. if ($debug) {
  2992. error_log("<------ manage_answer ------> ");
  2993. error_log('exe_id: '.$exeId);
  2994. error_log('$from: '.$from);
  2995. error_log('$saved_results: '.intval($saved_results));
  2996. error_log('$from_database: '.intval($from_database));
  2997. error_log('$show_result: '.$show_result);
  2998. error_log('$propagate_neg: '.$propagate_neg);
  2999. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  3000. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  3001. error_log('$learnpath_id: '.$learnpath_id);
  3002. error_log('$learnpath_item_id: '.$learnpath_item_id);
  3003. error_log('$choice: '.print_r($choice, 1));
  3004. }
  3005. $final_overlap = 0;
  3006. $final_missing = 0;
  3007. $final_excess = 0;
  3008. $overlap_color = 0;
  3009. $missing_color = 0;
  3010. $excess_color = 0;
  3011. $threadhold1 = 0;
  3012. $threadhold2 = 0;
  3013. $threadhold3 = 0;
  3014. $arrques = null;
  3015. $arrans = null;
  3016. $questionId = intval($questionId);
  3017. $exeId = intval($exeId);
  3018. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3019. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  3020. // Creates a temporary Question object
  3021. $course_id = $this->course_id;
  3022. $objQuestionTmp = Question::read($questionId, $course_id);
  3023. if ($objQuestionTmp === false) {
  3024. return false;
  3025. }
  3026. $questionName = $objQuestionTmp->selectTitle();
  3027. $questionWeighting = $objQuestionTmp->selectWeighting();
  3028. $answerType = $objQuestionTmp->selectType();
  3029. $quesId = $objQuestionTmp->selectId();
  3030. $extra = $objQuestionTmp->extra;
  3031. $next = 1; //not for now
  3032. $totalWeighting = 0;
  3033. $totalScore = 0;
  3034. // Extra information of the question
  3035. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE && !empty($extra)) {
  3036. $extra = explode(':', $extra);
  3037. if ($debug) {
  3038. error_log(print_r($extra, 1));
  3039. }
  3040. // Fixes problems with negatives values using intval
  3041. $true_score = floatval(trim($extra[0]));
  3042. $false_score = floatval(trim($extra[1]));
  3043. $doubt_score = floatval(trim($extra[2]));
  3044. }
  3045. // Construction of the Answer object
  3046. $objAnswerTmp = new Answer($questionId);
  3047. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  3048. if ($debug) {
  3049. error_log('Count of answers: '.$nbrAnswers);
  3050. error_log('$answerType: '.$answerType);
  3051. }
  3052. if ($answerType == FREE_ANSWER ||
  3053. $answerType == ORAL_EXPRESSION ||
  3054. $answerType == CALCULATED_ANSWER ||
  3055. $answerType == ANNOTATION
  3056. ) {
  3057. $nbrAnswers = 1;
  3058. }
  3059. if ($answerType == ORAL_EXPRESSION) {
  3060. $exe_info = Event::get_exercise_results_by_attempt($exeId);
  3061. $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null;
  3062. $objQuestionTmp->initFile(
  3063. api_get_session_id(),
  3064. isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(),
  3065. isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id,
  3066. isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
  3067. );
  3068. //probably this attempt came in an exercise all question by page
  3069. if ($feedback_type == 0) {
  3070. $objQuestionTmp->replaceWithRealExe($exeId);
  3071. }
  3072. }
  3073. $user_answer = '';
  3074. // Get answer list for matching
  3075. $sql = "SELECT id_auto, id, answer
  3076. FROM $table_ans
  3077. WHERE c_id = $course_id AND question_id = $questionId";
  3078. $res_answer = Database::query($sql);
  3079. $answerMatching = array();
  3080. while ($real_answer = Database::fetch_array($res_answer)) {
  3081. $answerMatching[$real_answer['id_auto']] = $real_answer['answer'];
  3082. }
  3083. $real_answers = array();
  3084. $quiz_question_options = Question::readQuestionOption(
  3085. $questionId,
  3086. $course_id
  3087. );
  3088. $organs_at_risk_hit = 0;
  3089. $questionScore = 0;
  3090. $answer_correct_array = array();
  3091. $orderedHotspots = [];
  3092. if ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  3093. $orderedHotspots = $em
  3094. ->getRepository('ChamiloCoreBundle:TrackEHotspot')
  3095. ->findBy([
  3096. 'hotspotQuestionId' => $questionId,
  3097. 'cId' => $course_id,
  3098. 'hotspotExeId' => $exeId
  3099. ],
  3100. ['hotspotAnswerId' => 'ASC']
  3101. );
  3102. }
  3103. if ($debug) error_log('Start answer loop ');
  3104. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  3105. $answer = $objAnswerTmp->selectAnswer($answerId);
  3106. $answerComment = $objAnswerTmp->selectComment($answerId);
  3107. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  3108. $answerWeighting = (float) $objAnswerTmp->selectWeighting($answerId);
  3109. $answerAutoId = $objAnswerTmp->selectAutoId($answerId);
  3110. $answerIid = isset($objAnswerTmp->iid[$answerId]) ? $objAnswerTmp->iid[$answerId] : '';
  3111. $answer_correct_array[$answerId] = (bool) $answerCorrect;
  3112. if ($debug) {
  3113. error_log("answer auto id: $answerAutoId ");
  3114. error_log("answer correct: $answerCorrect ");
  3115. }
  3116. // Delineation
  3117. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  3118. $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
  3119. switch ($answerType) {
  3120. // for unique answer
  3121. case UNIQUE_ANSWER:
  3122. case UNIQUE_ANSWER_IMAGE:
  3123. case UNIQUE_ANSWER_NO_OPTION:
  3124. case READING_COMPREHENSION:
  3125. if ($from_database) {
  3126. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3127. WHERE
  3128. exe_id = '".$exeId."' AND
  3129. question_id= '".$questionId."'";
  3130. $result = Database::query($sql);
  3131. $choice = Database::result($result, 0, "answer");
  3132. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3133. if ($studentChoice) {
  3134. $questionScore += $answerWeighting;
  3135. $totalScore += $answerWeighting;
  3136. }
  3137. } else {
  3138. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3139. if ($studentChoice) {
  3140. $questionScore += $answerWeighting;
  3141. $totalScore += $answerWeighting;
  3142. }
  3143. }
  3144. break;
  3145. // for multiple answers
  3146. case MULTIPLE_ANSWER_TRUE_FALSE:
  3147. if ($from_database) {
  3148. $choice = array();
  3149. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3150. WHERE
  3151. exe_id = $exeId AND
  3152. question_id = ".$questionId;
  3153. $result = Database::query($sql);
  3154. while ($row = Database::fetch_array($result)) {
  3155. $ind = $row['answer'];
  3156. $values = explode(':', $ind);
  3157. $my_answer_id = isset($values[0]) ? $values[0] : '';
  3158. $option = isset($values[1]) ? $values[1] : '';
  3159. $choice[$my_answer_id] = $option;
  3160. }
  3161. }
  3162. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3163. if (!empty($studentChoice)) {
  3164. if ($studentChoice == $answerCorrect) {
  3165. $questionScore += $true_score;
  3166. } else {
  3167. if ($quiz_question_options[$studentChoice]['name'] == "Don't know" ||
  3168. $quiz_question_options[$studentChoice]['name'] == "DoubtScore"
  3169. ) {
  3170. $questionScore += $doubt_score;
  3171. } else {
  3172. $questionScore += $false_score;
  3173. }
  3174. }
  3175. } else {
  3176. // If no result then the user just hit don't know
  3177. $studentChoice = 3;
  3178. $questionScore += $doubt_score;
  3179. }
  3180. $totalScore = $questionScore;
  3181. break;
  3182. case MULTIPLE_ANSWER: //2
  3183. if ($from_database) {
  3184. $choice = array();
  3185. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3186. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3187. $resultans = Database::query($sql);
  3188. while ($row = Database::fetch_array($resultans)) {
  3189. $ind = $row['answer'];
  3190. $choice[$ind] = 1;
  3191. }
  3192. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3193. $real_answers[$answerId] = (bool) $studentChoice;
  3194. if ($studentChoice) {
  3195. $questionScore += $answerWeighting;
  3196. }
  3197. } else {
  3198. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3199. $real_answers[$answerId] = (bool) $studentChoice;
  3200. if (isset($studentChoice)) {
  3201. $questionScore += $answerWeighting;
  3202. }
  3203. }
  3204. $totalScore += $answerWeighting;
  3205. if ($debug) error_log("studentChoice: $studentChoice");
  3206. break;
  3207. case GLOBAL_MULTIPLE_ANSWER:
  3208. if ($from_database) {
  3209. $choice = array();
  3210. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3211. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3212. $resultans = Database::query($sql);
  3213. while ($row = Database::fetch_array($resultans)) {
  3214. $ind = $row['answer'];
  3215. $choice[$ind] = 1;
  3216. }
  3217. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3218. $real_answers[$answerId] = (bool) $studentChoice;
  3219. if ($studentChoice) {
  3220. $questionScore += $answerWeighting;
  3221. }
  3222. } else {
  3223. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3224. if (isset($studentChoice)) {
  3225. $questionScore += $answerWeighting;
  3226. }
  3227. $real_answers[$answerId] = (bool) $studentChoice;
  3228. }
  3229. $totalScore += $answerWeighting;
  3230. if ($debug) error_log("studentChoice: $studentChoice");
  3231. break;
  3232. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3233. if ($from_database) {
  3234. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3235. WHERE exe_id = $exeId AND question_id= ".$questionId;
  3236. $resultans = Database::query($sql);
  3237. while ($row = Database::fetch_array($resultans)) {
  3238. $ind = $row['answer'];
  3239. $result = explode(':', $ind);
  3240. if (isset($result[0])) {
  3241. $my_answer_id = isset($result[0]) ? $result[0] : '';
  3242. $option = isset($result[1]) ? $result[1] : '';
  3243. $choice[$my_answer_id] = $option;
  3244. }
  3245. }
  3246. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3247. if ($answerCorrect == $studentChoice) {
  3248. //$answerCorrect = 1;
  3249. $real_answers[$answerId] = true;
  3250. } else {
  3251. //$answerCorrect = 0;
  3252. $real_answers[$answerId] = false;
  3253. }
  3254. } else {
  3255. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3256. if ($answerCorrect == $studentChoice) {
  3257. //$answerCorrect = 1;
  3258. $real_answers[$answerId] = true;
  3259. } else {
  3260. //$answerCorrect = 0;
  3261. $real_answers[$answerId] = false;
  3262. }
  3263. }
  3264. break;
  3265. case MULTIPLE_ANSWER_COMBINATION:
  3266. if ($from_database) {
  3267. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3268. WHERE exe_id = $exeId AND question_id= $questionId";
  3269. $resultans = Database::query($sql);
  3270. while ($row = Database::fetch_array($resultans)) {
  3271. $ind = $row['answer'];
  3272. $choice[$ind] = 1;
  3273. }
  3274. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3275. if ($answerCorrect == 1) {
  3276. if ($studentChoice) {
  3277. $real_answers[$answerId] = true;
  3278. } else {
  3279. $real_answers[$answerId] = false;
  3280. }
  3281. } else {
  3282. if ($studentChoice) {
  3283. $real_answers[$answerId] = false;
  3284. } else {
  3285. $real_answers[$answerId] = true;
  3286. }
  3287. }
  3288. } else {
  3289. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3290. if ($answerCorrect == 1) {
  3291. if ($studentChoice) {
  3292. $real_answers[$answerId] = true;
  3293. } else {
  3294. $real_answers[$answerId] = false;
  3295. }
  3296. } else {
  3297. if ($studentChoice) {
  3298. $real_answers[$answerId] = false;
  3299. } else {
  3300. $real_answers[$answerId] = true;
  3301. }
  3302. }
  3303. }
  3304. break;
  3305. case FILL_IN_BLANKS:
  3306. $str = '';
  3307. $answerFromDatabase = '';
  3308. if ($from_database) {
  3309. $sql = "SELECT answer
  3310. FROM $TBL_TRACK_ATTEMPT
  3311. WHERE
  3312. exe_id = $exeId AND
  3313. question_id= ".intval($questionId);
  3314. $result = Database::query($sql);
  3315. $str = $answerFromDatabase = Database::result($result, 0, 'answer');
  3316. }
  3317. if ($saved_results == false && strpos($str, 'font color') !== false) {
  3318. // the question is encoded like this
  3319. // [A] B [C] D [E] F::10,10,10@1
  3320. // number 1 before the "@" means that is a switchable fill in blank question
  3321. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3322. // means that is a normal fill blank question
  3323. // first we explode the "::"
  3324. $pre_array = explode('::', $answer);
  3325. // is switchable fill blank or not
  3326. $last = count($pre_array) - 1;
  3327. $is_set_switchable = explode('@', $pre_array[$last]);
  3328. $switchable_answer_set = false;
  3329. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3330. $switchable_answer_set = true;
  3331. }
  3332. $answer = '';
  3333. for ($k = 0; $k < $last; $k++) {
  3334. $answer .= $pre_array[$k];
  3335. }
  3336. // splits weightings that are joined with a comma
  3337. $answerWeighting = explode(',', $is_set_switchable[0]);
  3338. // we save the answer because it will be modified
  3339. $temp = $answer;
  3340. $answer = '';
  3341. $j = 0;
  3342. //initialise answer tags
  3343. $user_tags = $correct_tags = $real_text = array();
  3344. // the loop will stop at the end of the text
  3345. while (1) {
  3346. // quits the loop if there are no more blanks (detect '[')
  3347. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3348. // adds the end of the text
  3349. $answer = $temp;
  3350. $real_text[] = $answer;
  3351. break; //no more "blanks", quit the loop
  3352. }
  3353. // adds the piece of text that is before the blank
  3354. //and ends with '[' into a general storage array
  3355. $real_text[] = api_substr($temp, 0, $pos + 1);
  3356. $answer .= api_substr($temp, 0, $pos + 1);
  3357. //take the string remaining (after the last "[" we found)
  3358. $temp = api_substr($temp, $pos + 1);
  3359. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3360. if (($pos = api_strpos($temp, ']')) === false) {
  3361. // adds the end of the text
  3362. $answer .= $temp;
  3363. break;
  3364. }
  3365. if ($from_database) {
  3366. $str = $answerFromDatabase;
  3367. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3368. $str = str_replace('\r\n', '', $str);
  3369. $choice = $arr[1];
  3370. if (isset($choice[$j])) {
  3371. $tmp = api_strrpos($choice[$j], ' / ');
  3372. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3373. $choice[$j] = trim($choice[$j]);
  3374. // Needed to let characters ' and " to work as part of an answer
  3375. $choice[$j] = stripslashes($choice[$j]);
  3376. } else {
  3377. $choice[$j] = null;
  3378. }
  3379. } else {
  3380. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3381. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3382. }
  3383. $user_tags[] = $choice[$j];
  3384. //put the contents of the [] answer tag into correct_tags[]
  3385. $correct_tags[] = api_substr($temp, 0, $pos);
  3386. $j++;
  3387. $temp = api_substr($temp, $pos + 1);
  3388. }
  3389. $answer = '';
  3390. $real_correct_tags = $correct_tags;
  3391. $chosen_list = array();
  3392. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3393. if ($i == 0) {
  3394. $answer .= $real_text[0];
  3395. }
  3396. if (!$switchable_answer_set) {
  3397. // Needed to parse ' and " characters
  3398. $user_tags[$i] = stripslashes($user_tags[$i]);
  3399. if ($correct_tags[$i] == $user_tags[$i]) {
  3400. // gives the related weighting to the student
  3401. $questionScore += $answerWeighting[$i];
  3402. // increments total score
  3403. $totalScore += $answerWeighting[$i];
  3404. // adds the word in green at the end of the string
  3405. $answer .= $correct_tags[$i];
  3406. } elseif (!empty($user_tags[$i])) {
  3407. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3408. // adds the word in red at the end of the string, and strikes it
  3409. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3410. } else {
  3411. // adds a tabulation if no word has been typed by the student
  3412. $answer .= ''; // remove &nbsp; that causes issue
  3413. }
  3414. } else {
  3415. // switchable fill in the blanks
  3416. if (in_array($user_tags[$i], $correct_tags)) {
  3417. $chosen_list[] = $user_tags[$i];
  3418. $correct_tags = array_diff($correct_tags, $chosen_list);
  3419. // gives the related weighting to the student
  3420. $questionScore += $answerWeighting[$i];
  3421. // increments total score
  3422. $totalScore += $answerWeighting[$i];
  3423. // adds the word in green at the end of the string
  3424. $answer .= $user_tags[$i];
  3425. } elseif (!empty ($user_tags[$i])) {
  3426. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3427. // adds the word in red at the end of the string, and strikes it
  3428. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3429. } else {
  3430. // adds a tabulation if no word has been typed by the student
  3431. $answer .= ''; // remove &nbsp; that causes issue
  3432. }
  3433. }
  3434. // adds the correct word, followed by ] to close the blank
  3435. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  3436. if (isset($real_text[$i + 1])) {
  3437. $answer .= $real_text[$i + 1];
  3438. }
  3439. }
  3440. } else {
  3441. // insert the student result in the track_e_attempt table, field answer
  3442. // $answer is the answer like in the c_quiz_answer table for the question
  3443. // student data are choice[]
  3444. $listCorrectAnswers = FillBlanks::getAnswerInfo(
  3445. $answer
  3446. );
  3447. $switchableAnswerSet = $listCorrectAnswers['switchable'];
  3448. $answerWeighting = $listCorrectAnswers['tabweighting'];
  3449. // user choices is an array $choice
  3450. // get existing user data in n the BDD
  3451. if ($from_database) {
  3452. $listStudentResults = FillBlanks::getAnswerInfo(
  3453. $answerFromDatabase,
  3454. true
  3455. );
  3456. $choice = $listStudentResults['studentanswer'];
  3457. }
  3458. // loop other all blanks words
  3459. if (!$switchableAnswerSet) {
  3460. // not switchable answer, must be in the same place than teacher order
  3461. for ($i = 0; $i < count($listCorrectAnswers['tabwords']); $i++) {
  3462. $studentAnswer = isset($choice[$i]) ? $choice[$i] : '';
  3463. $correctAnswer = $listCorrectAnswers['tabwords'][$i];
  3464. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3465. // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
  3466. // ENT_QUOTES is used in order to transform ' to &#039;
  3467. if (!$from_database) {
  3468. $studentAnswer = FillBlanks::clearStudentAnswer($studentAnswer);
  3469. }
  3470. $isAnswerCorrect = 0;
  3471. if (FillBlanks::isGoodStudentAnswer($studentAnswer, $correctAnswer)) {
  3472. // gives the related weighting to the student
  3473. $questionScore += $answerWeighting[$i];
  3474. // increments total score
  3475. $totalScore += $answerWeighting[$i];
  3476. $isAnswerCorrect = 1;
  3477. }
  3478. $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
  3479. $listCorrectAnswers['studentscore'][$i] = $isAnswerCorrect;
  3480. }
  3481. } else {
  3482. // switchable answer
  3483. $listStudentAnswerTemp = $choice;
  3484. $listTeacherAnswerTemp = $listCorrectAnswers['tabwords'];
  3485. // for every teacher answer, check if there is a student answer
  3486. for ($i = 0; $i < count($listStudentAnswerTemp); $i++) {
  3487. $studentAnswer = trim($listStudentAnswerTemp[$i]);
  3488. $found = false;
  3489. for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) {
  3490. $correctAnswer = $listTeacherAnswerTemp[$j];
  3491. if (!$found) {
  3492. if (FillBlanks::isGoodStudentAnswer(
  3493. $studentAnswer,
  3494. $correctAnswer
  3495. )
  3496. ) {
  3497. $questionScore += $answerWeighting[$i];
  3498. $totalScore += $answerWeighting[$i];
  3499. $listTeacherAnswerTemp[$j] = '';
  3500. $found = true;
  3501. }
  3502. }
  3503. }
  3504. $listCorrectAnswers['studentanswer'][$i] = $studentAnswer;
  3505. if (!$found) {
  3506. $listCorrectAnswers['studentscore'][$i] = 0;
  3507. } else {
  3508. $listCorrectAnswers['studentscore'][$i] = 1;
  3509. }
  3510. }
  3511. }
  3512. $answer = FillBlanks::getAnswerInStudentAttempt(
  3513. $listCorrectAnswers
  3514. );
  3515. }
  3516. break;
  3517. case CALCULATED_ANSWER:
  3518. $answer = $objAnswerTmp->selectAnswer($_SESSION['calculatedAnswerId'][$questionId]);
  3519. $preArray = explode('@@', $answer);
  3520. $last = count($preArray) - 1;
  3521. $answer = '';
  3522. for ($k = 0; $k < $last; $k++) {
  3523. $answer .= $preArray[$k];
  3524. }
  3525. $answerWeighting = array($answerWeighting);
  3526. // we save the answer because it will be modified
  3527. $temp = $answer;
  3528. $answer = '';
  3529. $j = 0;
  3530. //initialise answer tags
  3531. $userTags = $correctTags = $realText = array();
  3532. // the loop will stop at the end of the text
  3533. while (1) {
  3534. // quits the loop if there are no more blanks (detect '[')
  3535. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3536. // adds the end of the text
  3537. $answer = $temp;
  3538. $realText[] = $answer;
  3539. break; //no more "blanks", quit the loop
  3540. }
  3541. // adds the piece of text that is before the blank
  3542. //and ends with '[' into a general storage array
  3543. $realText[] = api_substr($temp, 0, $pos + 1);
  3544. $answer .= api_substr($temp, 0, $pos + 1);
  3545. //take the string remaining (after the last "[" we found)
  3546. $temp = api_substr($temp, $pos + 1);
  3547. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3548. if (($pos = api_strpos($temp, ']')) === false) {
  3549. // adds the end of the text
  3550. $answer .= $temp;
  3551. break;
  3552. }
  3553. if ($from_database) {
  3554. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3555. WHERE
  3556. exe_id = '".$exeId."' AND
  3557. question_id= ".intval($questionId);
  3558. $resfill = Database::query($queryfill);
  3559. $str = Database::result($resfill, 0, 'answer');
  3560. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3561. $str = str_replace('\r\n', '', $str);
  3562. $choice = $arr[1];
  3563. if (isset($choice[$j])) {
  3564. $tmp = api_strrpos($choice[$j], ' / ');
  3565. if ($tmp) {
  3566. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3567. } else {
  3568. $tmp = ltrim($tmp, '[');
  3569. $tmp = rtrim($tmp, ']');
  3570. }
  3571. $choice[$j] = trim($choice[$j]);
  3572. // Needed to let characters ' and " to work as part of an answer
  3573. $choice[$j] = stripslashes($choice[$j]);
  3574. } else {
  3575. $choice[$j] = null;
  3576. }
  3577. } else {
  3578. // This value is the user input, not escaped while correct answer is escaped by fckeditor
  3579. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3580. }
  3581. $userTags[] = $choice[$j];
  3582. //put the contents of the [] answer tag into correct_tags[]
  3583. $correctTags[] = api_substr($temp, 0, $pos);
  3584. $j++;
  3585. $temp = api_substr($temp, $pos + 1);
  3586. }
  3587. $answer = '';
  3588. $realCorrectTags = $correctTags;
  3589. for ($i = 0; $i < count($realCorrectTags); $i++) {
  3590. if ($i == 0) {
  3591. $answer .= $realText[0];
  3592. }
  3593. // Needed to parse ' and " characters
  3594. $userTags[$i] = stripslashes($userTags[$i]);
  3595. if ($correctTags[$i] == $userTags[$i]) {
  3596. // gives the related weighting to the student
  3597. $questionScore += $answerWeighting[$i];
  3598. // increments total score
  3599. $totalScore += $answerWeighting[$i];
  3600. // adds the word in green at the end of the string
  3601. $answer .= $correctTags[$i];
  3602. } elseif (!empty($userTags[$i])) {
  3603. // else if the word entered by the student IS NOT the same as the one defined by the professor
  3604. // adds the word in red at the end of the string, and strikes it
  3605. $answer .= '<font color="red"><s>'.$userTags[$i].'</s></font>';
  3606. } else {
  3607. // adds a tabulation if no word has been typed by the student
  3608. $answer .= ''; // remove &nbsp; that causes issue
  3609. }
  3610. // adds the correct word, followed by ] to close the blank
  3611. if (
  3612. $this->results_disabled != EXERCISE_FEEDBACK_TYPE_EXAM
  3613. ) {
  3614. $answer .= ' / <font color="green"><b>'.$realCorrectTags[$i].'</b></font>';
  3615. }
  3616. $answer .= ']';
  3617. if (isset($realText[$i + 1])) {
  3618. $answer .= $realText[$i + 1];
  3619. }
  3620. }
  3621. break;
  3622. case FREE_ANSWER:
  3623. if ($from_database) {
  3624. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3625. WHERE
  3626. exe_id = $exeId AND
  3627. question_id= ".$questionId;
  3628. $resq = Database::query($sql);
  3629. $data = Database::fetch_array($resq);
  3630. $choice = $data['answer'];
  3631. $choice = str_replace('\r\n', '', $choice);
  3632. $choice = stripslashes($choice);
  3633. $questionScore = $data['marks'];
  3634. if ($questionScore == -1) {
  3635. $totalScore += 0;
  3636. } else {
  3637. $totalScore += $questionScore;
  3638. }
  3639. if ($questionScore == '') {
  3640. $questionScore = 0;
  3641. }
  3642. $arrques = $questionName;
  3643. $arrans = $choice;
  3644. } else {
  3645. $studentChoice = $choice;
  3646. if ($studentChoice) {
  3647. //Fixing negative puntation see #2193
  3648. $questionScore = 0;
  3649. $totalScore += 0;
  3650. }
  3651. }
  3652. break;
  3653. case ORAL_EXPRESSION:
  3654. if ($from_database) {
  3655. $query = "SELECT answer, marks
  3656. FROM $TBL_TRACK_ATTEMPT
  3657. WHERE
  3658. exe_id = $exeId AND
  3659. question_id = $questionId
  3660. ";
  3661. $resq = Database::query($query);
  3662. $row = Database::fetch_assoc($resq);
  3663. $choice = $row['answer'];
  3664. $choice = str_replace('\r\n', '', $choice);
  3665. $choice = stripslashes($choice);
  3666. $questionScore = $row['marks'];
  3667. if ($questionScore == -1) {
  3668. $totalScore += 0;
  3669. } else {
  3670. $totalScore += $questionScore;
  3671. }
  3672. $arrques = $questionName;
  3673. $arrans = $choice;
  3674. } else {
  3675. $studentChoice = $choice;
  3676. if ($studentChoice) {
  3677. //Fixing negative puntation see #2193
  3678. $questionScore = 0;
  3679. $totalScore += 0;
  3680. }
  3681. }
  3682. break;
  3683. case DRAGGABLE:
  3684. //no break
  3685. case MATCHING_DRAGGABLE:
  3686. //no break
  3687. case MATCHING:
  3688. if ($from_database) {
  3689. $sql = "SELECT id, answer, id_auto
  3690. FROM $table_ans
  3691. WHERE
  3692. c_id = $course_id AND
  3693. question_id = $questionId AND
  3694. correct = 0
  3695. ";
  3696. $res_answer = Database::query($sql);
  3697. // Getting the real answer
  3698. $real_list = array();
  3699. while ($real_answer = Database::fetch_array($res_answer)) {
  3700. $real_list[$real_answer['id_auto']] = $real_answer['answer'];
  3701. }
  3702. $sql = "SELECT id, answer, correct, id_auto, ponderation
  3703. FROM $table_ans
  3704. WHERE
  3705. c_id = $course_id AND
  3706. question_id = $questionId AND
  3707. correct <> 0
  3708. ORDER BY id_auto";
  3709. $res_answers = Database::query($sql);
  3710. $questionScore = 0;
  3711. while ($a_answers = Database::fetch_array($res_answers)) {
  3712. $i_answer_id = $a_answers['id']; //3
  3713. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3714. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3715. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  3716. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3717. WHERE
  3718. exe_id = '$exeId' AND
  3719. question_id = '$questionId' AND
  3720. position = '$i_answer_id_auto'";
  3721. $res_user_answer = Database::query($sql);
  3722. if (Database::num_rows($res_user_answer) > 0) {
  3723. // rich - good looking
  3724. $s_user_answer = Database::result($res_user_answer, 0, 0);
  3725. } else {
  3726. $s_user_answer = 0;
  3727. }
  3728. $i_answerWeighting = $a_answers['ponderation'];
  3729. $user_answer = '';
  3730. if (!empty($s_user_answer)) {
  3731. if ($answerType == DRAGGABLE) {
  3732. if ($s_user_answer == $i_answer_correct_answer) {
  3733. $questionScore += $i_answerWeighting;
  3734. $totalScore += $i_answerWeighting;
  3735. $user_answer = Display::label(get_lang('Correct'), 'success');
  3736. } else {
  3737. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  3738. }
  3739. } else {
  3740. if ($s_user_answer == $i_answer_correct_answer) {
  3741. $questionScore += $i_answerWeighting;
  3742. $totalScore += $i_answerWeighting;
  3743. // Try with id
  3744. if (isset($real_list[$i_answer_id])) {
  3745. $user_answer = Display::span($real_list[$i_answer_id]);
  3746. }
  3747. // Try with $i_answer_id_auto
  3748. if (empty($user_answer)) {
  3749. if (isset($real_list[$i_answer_id_auto])) {
  3750. $user_answer = Display::span(
  3751. $real_list[$i_answer_id_auto]
  3752. );
  3753. }
  3754. }
  3755. } else {
  3756. $user_answer = Display::span(
  3757. $real_list[$s_user_answer],
  3758. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3759. );
  3760. }
  3761. }
  3762. } elseif ($answerType == DRAGGABLE) {
  3763. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  3764. } else {
  3765. $user_answer = Display::span(
  3766. get_lang('Incorrect').' &nbsp;',
  3767. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3768. );
  3769. }
  3770. if ($show_result) {
  3771. if ($showTotalScoreAndUserChoicesInLastAttempt === false) {
  3772. $user_answer = '';
  3773. }
  3774. echo '<tr>';
  3775. echo '<td>'.$s_answer_label.'</td>';
  3776. echo '<td>'.$user_answer;
  3777. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  3778. if (isset($real_list[$i_answer_correct_answer]) &&
  3779. $showTotalScoreAndUserChoicesInLastAttempt === true
  3780. ) {
  3781. echo Display::span(
  3782. $real_list[$i_answer_correct_answer],
  3783. ['style' => 'color: #008000; font-weight: bold;']
  3784. );
  3785. }
  3786. }
  3787. echo '</td>';
  3788. echo '</tr>';
  3789. }
  3790. }
  3791. break(2); // break the switch and the "for" condition
  3792. } else {
  3793. if ($answerCorrect) {
  3794. if (isset($choice[$answerAutoId]) &&
  3795. $answerCorrect == $choice[$answerAutoId]
  3796. ) {
  3797. $questionScore += $answerWeighting;
  3798. $totalScore += $answerWeighting;
  3799. $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]);
  3800. } else {
  3801. if (isset($answerMatching[$choice[$answerAutoId]])) {
  3802. $user_answer = Display::span(
  3803. $answerMatching[$choice[$answerAutoId]],
  3804. ['style' => 'color: #FF0000; text-decoration: line-through;']
  3805. );
  3806. }
  3807. }
  3808. $matching[$answerAutoId] = $choice[$answerAutoId];
  3809. }
  3810. }
  3811. break;
  3812. case HOT_SPOT:
  3813. if ($from_database) {
  3814. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3815. // Check auto id
  3816. $sql = "SELECT hotspot_correct
  3817. FROM $TBL_TRACK_HOTSPOT
  3818. WHERE
  3819. hotspot_exe_id = $exeId AND
  3820. hotspot_question_id= $questionId AND
  3821. hotspot_answer_id = ".intval($answerAutoId)."
  3822. ORDER BY hotspot_id ASC";
  3823. $result = Database::query($sql);
  3824. if (Database::num_rows($result)) {
  3825. $studentChoice = Database::result(
  3826. $result,
  3827. 0,
  3828. 'hotspot_correct'
  3829. );
  3830. if ($studentChoice) {
  3831. $questionScore += $answerWeighting;
  3832. $totalScore += $answerWeighting;
  3833. }
  3834. } else {
  3835. // If answer.id is different:
  3836. $sql = "SELECT hotspot_correct
  3837. FROM $TBL_TRACK_HOTSPOT
  3838. WHERE
  3839. hotspot_exe_id = $exeId AND
  3840. hotspot_question_id= $questionId AND
  3841. hotspot_answer_id = ".intval($answerId)."
  3842. ORDER BY hotspot_id ASC";
  3843. $result = Database::query($sql);
  3844. if (Database::num_rows($result)) {
  3845. $studentChoice = Database::result(
  3846. $result,
  3847. 0,
  3848. 'hotspot_correct'
  3849. );
  3850. if ($studentChoice) {
  3851. $questionScore += $answerWeighting;
  3852. $totalScore += $answerWeighting;
  3853. }
  3854. } else {
  3855. // check answer.iid
  3856. if (!empty($answerIid)) {
  3857. $sql = "SELECT hotspot_correct
  3858. FROM $TBL_TRACK_HOTSPOT
  3859. WHERE
  3860. hotspot_exe_id = $exeId AND
  3861. hotspot_question_id= $questionId AND
  3862. hotspot_answer_id = ".intval($answerIid)."
  3863. ORDER BY hotspot_id ASC";
  3864. $result = Database::query($sql);
  3865. $studentChoice = Database::result(
  3866. $result,
  3867. 0,
  3868. 'hotspot_correct'
  3869. );
  3870. if ($studentChoice) {
  3871. $questionScore += $answerWeighting;
  3872. $totalScore += $answerWeighting;
  3873. }
  3874. }
  3875. }
  3876. }
  3877. } else {
  3878. if (!isset($choice[$answerAutoId]) && !isset($choice[$answerIid])) {
  3879. $choice[$answerAutoId] = 0;
  3880. $choice[$answerIid] = 0;
  3881. } else {
  3882. $studentChoice = $choice[$answerAutoId];
  3883. if (empty($studentChoice)) {
  3884. $studentChoice = $choice[$answerIid];
  3885. }
  3886. $choiceIsValid = false;
  3887. if (!empty($studentChoice)) {
  3888. $hotspotType = $objAnswerTmp->selectHotspotType($answerId);
  3889. $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId);
  3890. $choicePoint = Geometry::decodePoint($studentChoice);
  3891. switch ($hotspotType) {
  3892. case 'square':
  3893. $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates);
  3894. $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint);
  3895. break;
  3896. case 'circle':
  3897. $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates);
  3898. $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint);
  3899. break;
  3900. case 'poly':
  3901. $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates);
  3902. $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint);
  3903. break;
  3904. }
  3905. }
  3906. $choice[$answerAutoId] = 0;
  3907. if ($choiceIsValid) {
  3908. $questionScore += $answerWeighting;
  3909. $totalScore += $answerWeighting;
  3910. $choice[$answerAutoId] = 1;
  3911. $choice[$answerIid] = 1;
  3912. }
  3913. }
  3914. }
  3915. break;
  3916. // @todo never added to chamilo
  3917. //for hotspot with fixed order
  3918. case HOT_SPOT_ORDER:
  3919. $studentChoice = $choice['order'][$answerId];
  3920. if ($studentChoice == $answerId) {
  3921. $questionScore += $answerWeighting;
  3922. $totalScore += $answerWeighting;
  3923. $studentChoice = true;
  3924. } else {
  3925. $studentChoice = false;
  3926. }
  3927. break;
  3928. // for hotspot with delineation
  3929. case HOT_SPOT_DELINEATION:
  3930. if ($from_database) {
  3931. // getting the user answer
  3932. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  3933. $query = "SELECT hotspot_correct, hotspot_coordinate
  3934. FROM $TBL_TRACK_HOTSPOT
  3935. WHERE
  3936. hotspot_exe_id = '".$exeId."' AND
  3937. hotspot_question_id= '".$questionId."' AND
  3938. hotspot_answer_id='1'";
  3939. //by default we take 1 because it's a delineation
  3940. $resq = Database::query($query);
  3941. $row = Database::fetch_array($resq, 'ASSOC');
  3942. $choice = $row['hotspot_correct'];
  3943. $user_answer = $row['hotspot_coordinate'];
  3944. // THIS is very important otherwise the poly_compile will throw an error!!
  3945. // round-up the coordinates
  3946. $coords = explode('/', $user_answer);
  3947. $user_array = '';
  3948. foreach ($coords as $coord) {
  3949. list($x, $y) = explode(';', $coord);
  3950. $user_array .= round($x).';'.round($y).'/';
  3951. }
  3952. $user_array = substr($user_array, 0, -1);
  3953. } else {
  3954. if (!empty($studentChoice)) {
  3955. $newquestionList[] = $questionId;
  3956. }
  3957. if ($answerId === 1) {
  3958. $studentChoice = $choice[$answerId];
  3959. $questionScore += $answerWeighting;
  3960. if ($hotspot_delineation_result[1] == 1) {
  3961. $totalScore += $answerWeighting; //adding the total
  3962. }
  3963. }
  3964. }
  3965. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  3966. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  3967. break;
  3968. case ANNOTATION:
  3969. if ($from_database) {
  3970. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3971. WHERE
  3972. exe_id = $exeId AND
  3973. question_id= ".$questionId;
  3974. $resq = Database::query($sql);
  3975. $data = Database::fetch_array($resq);
  3976. $questionScore = empty($data['marks']) ? 0 : $data['marks'];
  3977. $totalScore += $questionScore == -1 ? 0 : $questionScore;
  3978. $arrques = $questionName;
  3979. break;
  3980. }
  3981. $studentChoice = $choice;
  3982. if ($studentChoice) {
  3983. $questionScore = 0;
  3984. $totalScore += 0;
  3985. }
  3986. break;
  3987. } // end switch Answertype
  3988. if ($show_result) {
  3989. if ($debug) error_log('Showing questions $from '.$from);
  3990. if ($from == 'exercise_result') {
  3991. //display answers (if not matching type, or if the answer is correct)
  3992. if (
  3993. !in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) ||
  3994. $answerCorrect
  3995. ) {
  3996. if (
  3997. in_array(
  3998. $answerType,
  3999. array(
  4000. UNIQUE_ANSWER,
  4001. UNIQUE_ANSWER_IMAGE,
  4002. UNIQUE_ANSWER_NO_OPTION,
  4003. MULTIPLE_ANSWER,
  4004. MULTIPLE_ANSWER_COMBINATION,
  4005. GLOBAL_MULTIPLE_ANSWER,
  4006. READING_COMPREHENSION,
  4007. )
  4008. )
  4009. ) {
  4010. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4011. $feedback_type,
  4012. $answerType,
  4013. $studentChoice,
  4014. $answer,
  4015. $answerComment,
  4016. $answerCorrect,
  4017. 0,
  4018. 0,
  4019. 0,
  4020. $results_disabled,
  4021. $showTotalScoreAndUserChoicesInLastAttempt
  4022. );
  4023. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  4024. ExerciseShowFunctions::display_multiple_answer_true_false(
  4025. $feedback_type,
  4026. $answerType,
  4027. $studentChoice,
  4028. $answer,
  4029. $answerComment,
  4030. $answerCorrect,
  4031. 0,
  4032. $questionId,
  4033. 0,
  4034. $results_disabled,
  4035. $showTotalScoreAndUserChoicesInLastAttempt
  4036. );
  4037. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4038. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4039. $feedback_type,
  4040. $answerType,
  4041. $studentChoice,
  4042. $answer,
  4043. $answerComment,
  4044. $answerCorrect,
  4045. 0,
  4046. 0,
  4047. 0,
  4048. $results_disabled,
  4049. $showTotalScoreAndUserChoicesInLastAttempt
  4050. );
  4051. } elseif ($answerType == FILL_IN_BLANKS) {
  4052. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4053. $feedback_type,
  4054. $answer,
  4055. 0,
  4056. 0,
  4057. $results_disabled,
  4058. '',
  4059. $showTotalScoreAndUserChoicesInLastAttempt
  4060. );
  4061. } elseif ($answerType == CALCULATED_ANSWER) {
  4062. ExerciseShowFunctions::display_calculated_answer(
  4063. $feedback_type,
  4064. $answer,
  4065. 0,
  4066. 0,
  4067. $results_disabled,
  4068. $showTotalScoreAndUserChoicesInLastAttempt
  4069. );
  4070. } elseif ($answerType == FREE_ANSWER) {
  4071. ExerciseShowFunctions::display_free_answer(
  4072. $feedback_type,
  4073. $choice,
  4074. $exeId,
  4075. $questionId,
  4076. $questionScore,
  4077. $results_disabled
  4078. );
  4079. } elseif ($answerType == ORAL_EXPRESSION) {
  4080. // to store the details of open questions in an array to be used in mail
  4081. /** @var OralExpression $objQuestionTmp */
  4082. ExerciseShowFunctions::display_oral_expression_answer(
  4083. $feedback_type,
  4084. $choice,
  4085. 0,
  4086. 0,
  4087. $objQuestionTmp->getFileUrl(true),
  4088. $results_disabled,
  4089. $questionScore
  4090. );
  4091. } elseif ($answerType == HOT_SPOT) {
  4092. /**
  4093. * @var int $correctAnswerId
  4094. * @var TrackEHotspot $hotspot
  4095. */
  4096. foreach ($orderedHotspots as $correctAnswerId => $hotspot) {
  4097. if ($hotspot->getHotspotAnswerId() == $answerAutoId) {
  4098. break;
  4099. }
  4100. }
  4101. ExerciseShowFunctions::display_hotspot_answer(
  4102. $feedback_type,
  4103. ++$correctAnswerId,
  4104. $answer,
  4105. $studentChoice,
  4106. $answerComment,
  4107. $results_disabled,
  4108. $correctAnswerId,
  4109. $showTotalScoreAndUserChoicesInLastAttempt
  4110. );
  4111. } elseif ($answerType == HOT_SPOT_ORDER) {
  4112. ExerciseShowFunctions::display_hotspot_order_answer(
  4113. $feedback_type,
  4114. $answerId,
  4115. $answer,
  4116. $studentChoice,
  4117. $answerComment
  4118. );
  4119. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  4120. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  4121. //round-up the coordinates
  4122. $coords = explode('/', $user_answer);
  4123. $user_array = '';
  4124. foreach ($coords as $coord) {
  4125. list($x, $y) = explode(';', $coord);
  4126. $user_array .= round($x).';'.round($y).'/';
  4127. }
  4128. $user_array = substr($user_array, 0, -1);
  4129. if ($next) {
  4130. $user_answer = $user_array;
  4131. // we compare only the delineation not the other points
  4132. $answer_question = $_SESSION['hotspot_coord'][1];
  4133. $answerDestination = $_SESSION['hotspot_dest'][1];
  4134. //calculating the area
  4135. $poly_user = convert_coordinates($user_answer, '/');
  4136. $poly_answer = convert_coordinates($answer_question, '|');
  4137. $max_coord = poly_get_max($poly_user, $poly_answer);
  4138. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4139. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4140. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4141. $overlap = $poly_results['both'];
  4142. $poly_answer_area = $poly_results['s1'];
  4143. $poly_user_area = $poly_results['s2'];
  4144. $missing = $poly_results['s1Only'];
  4145. $excess = $poly_results['s2Only'];
  4146. //$overlap = round(polygons_overlap($poly_answer,$poly_user));
  4147. // //this is an area in pixels
  4148. if ($debug > 0) {
  4149. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4150. }
  4151. if ($overlap < 1) {
  4152. //shortcut to avoid complicated calculations
  4153. $final_overlap = 0;
  4154. $final_missing = 100;
  4155. $final_excess = 100;
  4156. } else {
  4157. // the final overlap is the percentage of the initial polygon
  4158. // that is overlapped by the user's polygon
  4159. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4160. if ($debug > 1) {
  4161. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  4162. }
  4163. // the final missing area is the percentage of the initial polygon
  4164. // that is not overlapped by the user's polygon
  4165. $final_missing = 100 - $final_overlap;
  4166. if ($debug > 1) {
  4167. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  4168. }
  4169. // the final excess area is the percentage of the initial polygon's size
  4170. // that is covered by the user's polygon outside of the initial polygon
  4171. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4172. if ($debug > 1) {
  4173. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  4174. }
  4175. }
  4176. //checking the destination parameters parsing the "@@"
  4177. $destination_items = explode(
  4178. '@@',
  4179. $answerDestination
  4180. );
  4181. $threadhold_total = $destination_items[0];
  4182. $threadhold_items = explode(
  4183. ';',
  4184. $threadhold_total
  4185. );
  4186. $threadhold1 = $threadhold_items[0]; // overlap
  4187. $threadhold2 = $threadhold_items[1]; // excess
  4188. $threadhold3 = $threadhold_items[2]; //missing
  4189. // if is delineation
  4190. if ($answerId === 1) {
  4191. //setting colors
  4192. if ($final_overlap >= $threadhold1) {
  4193. $overlap_color = true; //echo 'a';
  4194. }
  4195. //echo $excess.'-'.$threadhold2;
  4196. if ($final_excess <= $threadhold2) {
  4197. $excess_color = true; //echo 'b';
  4198. }
  4199. //echo '--------'.$missing.'-'.$threadhold3;
  4200. if ($final_missing <= $threadhold3) {
  4201. $missing_color = true; //echo 'c';
  4202. }
  4203. // if pass
  4204. if (
  4205. $final_overlap >= $threadhold1 &&
  4206. $final_missing <= $threadhold3 &&
  4207. $final_excess <= $threadhold2
  4208. ) {
  4209. $next = 1; //go to the oars
  4210. $result_comment = get_lang('Acceptable');
  4211. $final_answer = 1; // do not update with update_exercise_attempt
  4212. } else {
  4213. $next = 0;
  4214. $result_comment = get_lang('Unacceptable');
  4215. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4216. $answerDestination = $objAnswerTmp->selectDestination(1);
  4217. //checking the destination parameters parsing the "@@"
  4218. $destination_items = explode('@@', $answerDestination);
  4219. }
  4220. } elseif ($answerId > 1) {
  4221. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4222. if ($debug > 0) {
  4223. error_log(__LINE__.' - answerId is of type noerror', 0);
  4224. }
  4225. //type no error shouldn't be treated
  4226. $next = 1;
  4227. continue;
  4228. }
  4229. if ($debug > 0) {
  4230. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4231. }
  4232. //check the intersection between the oar and the user
  4233. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  4234. //echo 'official';print_r($x_list);print_r($y_list);
  4235. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  4236. $inter = $result['success'];
  4237. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4238. $poly_answer = convert_coordinates($delineation_cord, '|');
  4239. $max_coord = poly_get_max($poly_user, $poly_answer);
  4240. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4241. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4242. if ($overlap == false) {
  4243. //all good, no overlap
  4244. $next = 1;
  4245. continue;
  4246. } else {
  4247. if ($debug > 0) {
  4248. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4249. }
  4250. $organs_at_risk_hit++;
  4251. //show the feedback
  4252. $next = 0;
  4253. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4254. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4255. $destination_items = explode('@@', $answerDestination);
  4256. $try_hotspot = $destination_items[1];
  4257. $lp_hotspot = $destination_items[2];
  4258. $select_question_hotspot = $destination_items[3];
  4259. $url_hotspot = $destination_items[4];
  4260. }
  4261. }
  4262. } else { // the first delineation feedback
  4263. if ($debug > 0) {
  4264. error_log(__LINE__.' first', 0);
  4265. }
  4266. }
  4267. } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4268. echo '<tr>';
  4269. echo Display::tag('td', $answerMatching[$answerId]);
  4270. echo Display::tag(
  4271. 'td',
  4272. "$user_answer / ".Display::tag(
  4273. 'strong',
  4274. $answerMatching[$answerCorrect],
  4275. ['style' => 'color: #008000; font-weight: bold;']
  4276. )
  4277. );
  4278. echo '</tr>';
  4279. } elseif ($answerType == ANNOTATION) {
  4280. ExerciseShowFunctions::displayAnnotationAnswer(
  4281. $feedback_type,
  4282. $exeId,
  4283. $questionId,
  4284. $questionScore,
  4285. $results_disabled
  4286. );
  4287. }
  4288. }
  4289. } else {
  4290. if ($debug) error_log('Showing questions $from '.$from);
  4291. switch ($answerType) {
  4292. case UNIQUE_ANSWER:
  4293. //no break
  4294. case UNIQUE_ANSWER_IMAGE:
  4295. //no break
  4296. case UNIQUE_ANSWER_NO_OPTION:
  4297. //no break
  4298. case MULTIPLE_ANSWER:
  4299. //no break
  4300. case GLOBAL_MULTIPLE_ANSWER :
  4301. //no break
  4302. case MULTIPLE_ANSWER_COMBINATION:
  4303. //no break
  4304. case READING_COMPREHENSION:
  4305. if ($answerId == 1) {
  4306. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4307. $feedback_type,
  4308. $answerType,
  4309. $studentChoice,
  4310. $answer,
  4311. $answerComment,
  4312. $answerCorrect,
  4313. $exeId,
  4314. $questionId,
  4315. $answerId,
  4316. $results_disabled,
  4317. $showTotalScoreAndUserChoicesInLastAttempt
  4318. );
  4319. } else {
  4320. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4321. $feedback_type,
  4322. $answerType,
  4323. $studentChoice,
  4324. $answer,
  4325. $answerComment,
  4326. $answerCorrect,
  4327. $exeId,
  4328. $questionId,
  4329. '',
  4330. $results_disabled,
  4331. $showTotalScoreAndUserChoicesInLastAttempt
  4332. );
  4333. }
  4334. break;
  4335. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  4336. if ($answerId == 1) {
  4337. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4338. $feedback_type,
  4339. $answerType,
  4340. $studentChoice,
  4341. $answer,
  4342. $answerComment,
  4343. $answerCorrect,
  4344. $exeId,
  4345. $questionId,
  4346. $answerId,
  4347. $results_disabled,
  4348. $showTotalScoreAndUserChoicesInLastAttempt
  4349. );
  4350. } else {
  4351. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4352. $feedback_type,
  4353. $answerType,
  4354. $studentChoice,
  4355. $answer,
  4356. $answerComment,
  4357. $answerCorrect,
  4358. $exeId,
  4359. $questionId,
  4360. '',
  4361. $results_disabled,
  4362. $showTotalScoreAndUserChoicesInLastAttempt
  4363. );
  4364. }
  4365. break;
  4366. case MULTIPLE_ANSWER_TRUE_FALSE:
  4367. if ($answerId == 1) {
  4368. ExerciseShowFunctions::display_multiple_answer_true_false(
  4369. $feedback_type,
  4370. $answerType,
  4371. $studentChoice,
  4372. $answer,
  4373. $answerComment,
  4374. $answerCorrect,
  4375. $exeId,
  4376. $questionId,
  4377. $answerId,
  4378. $results_disabled,
  4379. $showTotalScoreAndUserChoicesInLastAttempt
  4380. );
  4381. } else {
  4382. ExerciseShowFunctions::display_multiple_answer_true_false(
  4383. $feedback_type,
  4384. $answerType,
  4385. $studentChoice,
  4386. $answer,
  4387. $answerComment,
  4388. $answerCorrect,
  4389. $exeId,
  4390. $questionId,
  4391. '',
  4392. $results_disabled,
  4393. $showTotalScoreAndUserChoicesInLastAttempt
  4394. );
  4395. }
  4396. break;
  4397. case FILL_IN_BLANKS:
  4398. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4399. $feedback_type,
  4400. $answer,
  4401. $exeId,
  4402. $questionId,
  4403. $results_disabled,
  4404. $str,
  4405. $showTotalScoreAndUserChoicesInLastAttempt
  4406. );
  4407. break;
  4408. case CALCULATED_ANSWER:
  4409. ExerciseShowFunctions::display_calculated_answer(
  4410. $feedback_type,
  4411. $answer,
  4412. $exeId,
  4413. $questionId,
  4414. $results_disabled,
  4415. '',
  4416. $showTotalScoreAndUserChoicesInLastAttempt
  4417. );
  4418. break;
  4419. case FREE_ANSWER:
  4420. echo ExerciseShowFunctions::display_free_answer(
  4421. $feedback_type,
  4422. $choice,
  4423. $exeId,
  4424. $questionId,
  4425. $questionScore,
  4426. $results_disabled
  4427. );
  4428. break;
  4429. case ORAL_EXPRESSION:
  4430. echo '<tr>
  4431. <td valign="top">' . ExerciseShowFunctions::display_oral_expression_answer(
  4432. $feedback_type,
  4433. $choice,
  4434. $exeId,
  4435. $questionId,
  4436. $objQuestionTmp->getFileUrl(),
  4437. $results_disabled,
  4438. $questionScore
  4439. ).'</td>
  4440. </tr>
  4441. </table>';
  4442. break;
  4443. case HOT_SPOT:
  4444. ExerciseShowFunctions::display_hotspot_answer(
  4445. $feedback_type,
  4446. $answerId,
  4447. $answer,
  4448. $studentChoice,
  4449. $answerComment,
  4450. $results_disabled,
  4451. $answerId,
  4452. $showTotalScoreAndUserChoicesInLastAttempt
  4453. );
  4454. break;
  4455. case HOT_SPOT_DELINEATION:
  4456. $user_answer = $user_array;
  4457. if ($next) {
  4458. //$tbl_track_e_hotspot = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4459. // Save into db
  4460. /* $sql = "INSERT INTO $tbl_track_e_hotspot (
  4461. * hotspot_user_id,
  4462. * hotspot_course_code,
  4463. * hotspot_exe_id,
  4464. * hotspot_question_id,
  4465. * hotspot_answer_id,
  4466. * hotspot_correct,
  4467. * hotspot_coordinate
  4468. * )
  4469. VALUES (
  4470. * '".Database::escape_string($_user['user_id'])."',
  4471. * '".Database::escape_string($_course['id'])."',
  4472. * '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."',
  4473. * '".Database::escape_string($answerId)."',
  4474. * '".Database::escape_string($studentChoice)."',
  4475. * '".Database::escape_string($user_array)."')";
  4476. $result = Database::query($sql,__FILE__,__LINE__);
  4477. */
  4478. $user_answer = $user_array;
  4479. // we compare only the delineation not the other points
  4480. $answer_question = $_SESSION['hotspot_coord'][1];
  4481. $answerDestination = $_SESSION['hotspot_dest'][1];
  4482. // calculating the area
  4483. $poly_user = convert_coordinates($user_answer, '/');
  4484. $poly_answer = convert_coordinates($answer_question, '|');
  4485. $max_coord = poly_get_max($poly_user, $poly_answer);
  4486. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4487. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4488. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4489. $overlap = $poly_results['both'];
  4490. $poly_answer_area = $poly_results['s1'];
  4491. $poly_user_area = $poly_results['s2'];
  4492. $missing = $poly_results['s1Only'];
  4493. $excess = $poly_results['s2Only'];
  4494. if ($debug > 0) {
  4495. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4496. }
  4497. if ($overlap < 1) {
  4498. //shortcut to avoid complicated calculations
  4499. $final_overlap = 0;
  4500. $final_missing = 100;
  4501. $final_excess = 100;
  4502. } else {
  4503. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  4504. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4505. if ($debug > 1) {
  4506. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  4507. }
  4508. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  4509. $final_missing = 100 - $final_overlap;
  4510. if ($debug > 1) {
  4511. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  4512. }
  4513. // 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
  4514. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4515. if ($debug > 1) {
  4516. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  4517. }
  4518. }
  4519. // Checking the destination parameters parsing the "@@"
  4520. $destination_items = explode('@@', $answerDestination);
  4521. $threadhold_total = $destination_items[0];
  4522. $threadhold_items = explode(';', $threadhold_total);
  4523. $threadhold1 = $threadhold_items[0]; // overlap
  4524. $threadhold2 = $threadhold_items[1]; // excess
  4525. $threadhold3 = $threadhold_items[2]; //missing
  4526. // if is delineation
  4527. if ($answerId === 1) {
  4528. //setting colors
  4529. if ($final_overlap >= $threadhold1) {
  4530. $overlap_color = true; //echo 'a';
  4531. }
  4532. //echo $excess.'-'.$threadhold2;
  4533. if ($final_excess <= $threadhold2) {
  4534. $excess_color = true; //echo 'b';
  4535. }
  4536. //echo '--------'.$missing.'-'.$threadhold3;
  4537. if ($final_missing <= $threadhold3) {
  4538. $missing_color = true; //echo 'c';
  4539. }
  4540. // if pass
  4541. if ($final_overlap >= $threadhold1 &&
  4542. $final_missing <= $threadhold3 &&
  4543. $final_excess <= $threadhold2
  4544. ) {
  4545. $next = 1; //go to the oars
  4546. $result_comment = get_lang('Acceptable');
  4547. $final_answer = 1; // do not update with update_exercise_attempt
  4548. } else {
  4549. $next = 0;
  4550. $result_comment = get_lang('Unacceptable');
  4551. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4552. $answerDestination = $objAnswerTmp->selectDestination(1);
  4553. //checking the destination parameters parsing the "@@"
  4554. $destination_items = explode('@@', $answerDestination);
  4555. }
  4556. } elseif ($answerId > 1) {
  4557. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4558. if ($debug > 0) {
  4559. error_log(__LINE__.' - answerId is of type noerror', 0);
  4560. }
  4561. //type no error shouldn't be treated
  4562. $next = 1;
  4563. continue;
  4564. }
  4565. if ($debug > 0) {
  4566. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4567. }
  4568. //check the intersection between the oar and the user
  4569. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  4570. //echo 'official';print_r($x_list);print_r($y_list);
  4571. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  4572. $inter = $result['success'];
  4573. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  4574. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4575. $poly_answer = convert_coordinates($delineation_cord, '|');
  4576. $max_coord = poly_get_max($poly_user, $poly_answer);
  4577. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4578. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4579. if ($overlap == false) {
  4580. //all good, no overlap
  4581. $next = 1;
  4582. continue;
  4583. } else {
  4584. if ($debug > 0) {
  4585. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4586. }
  4587. $organs_at_risk_hit++;
  4588. //show the feedback
  4589. $next = 0;
  4590. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4591. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4592. $destination_items = explode('@@', $answerDestination);
  4593. $try_hotspot = $destination_items[1];
  4594. $lp_hotspot = $destination_items[2];
  4595. $select_question_hotspot = $destination_items[3];
  4596. $url_hotspot = $destination_items[4];
  4597. }
  4598. }
  4599. } else { // the first delineation feedback
  4600. if ($debug > 0) {
  4601. error_log(__LINE__.' first', 0);
  4602. }
  4603. }
  4604. break;
  4605. case HOT_SPOT_ORDER:
  4606. ExerciseShowFunctions::display_hotspot_order_answer(
  4607. $feedback_type,
  4608. $answerId,
  4609. $answer,
  4610. $studentChoice,
  4611. $answerComment
  4612. );
  4613. break;
  4614. case DRAGGABLE:
  4615. //no break
  4616. case MATCHING_DRAGGABLE:
  4617. //no break
  4618. case MATCHING:
  4619. echo '<tr>';
  4620. echo Display::tag('td', $answerMatching[$answerId]);
  4621. echo Display::tag(
  4622. 'td',
  4623. "$user_answer / ".Display::tag(
  4624. 'strong',
  4625. $answerMatching[$answerCorrect],
  4626. ['style' => 'color: #008000; font-weight: bold;']
  4627. )
  4628. );
  4629. echo '</tr>';
  4630. break;
  4631. case ANNOTATION:
  4632. ExerciseShowFunctions::displayAnnotationAnswer(
  4633. $feedback_type,
  4634. $exeId,
  4635. $questionId,
  4636. $questionScore,
  4637. $results_disabled
  4638. );
  4639. break;
  4640. }
  4641. }
  4642. }
  4643. if ($debug) error_log(' ------ ');
  4644. } // end for that loops over all answers of the current question
  4645. if ($debug) error_log('-- end answer loop --');
  4646. $final_answer = true;
  4647. foreach ($real_answers as $my_answer) {
  4648. if (!$my_answer) {
  4649. $final_answer = false;
  4650. }
  4651. }
  4652. //we add the total score after dealing with the answers
  4653. if ($answerType == MULTIPLE_ANSWER_COMBINATION ||
  4654. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  4655. ) {
  4656. if ($final_answer) {
  4657. //getting only the first score where we save the weight of all the question
  4658. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  4659. $questionScore += $answerWeighting;
  4660. $totalScore += $answerWeighting;
  4661. }
  4662. }
  4663. //Fixes multiple answer question in order to be exact
  4664. //if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  4665. /* if ($answerType == GLOBAL_MULTIPLE_ANSWER) {
  4666. $diff = @array_diff($answer_correct_array, $real_answers);
  4667. // All good answers or nothing works like exact
  4668. $counter = 1;
  4669. $correct_answer = true;
  4670. foreach ($real_answers as $my_answer) {
  4671. if ($debug)
  4672. error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  4673. if ($my_answer != $answer_correct_array[$counter]) {
  4674. $correct_answer = false;
  4675. break;
  4676. }
  4677. $counter++;
  4678. }
  4679. if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
  4680. if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
  4681. if ($debug) error_log(" correct_answer: ".$correct_answer);
  4682. if ($correct_answer == false) {
  4683. $questionScore = 0;
  4684. }
  4685. // This makes the result non exact
  4686. if (!empty($diff)) {
  4687. $questionScore = 0;
  4688. }
  4689. }*/
  4690. $extra_data = array(
  4691. 'final_overlap' => $final_overlap,
  4692. 'final_missing' => $final_missing,
  4693. 'final_excess' => $final_excess,
  4694. 'overlap_color' => $overlap_color,
  4695. 'missing_color' => $missing_color,
  4696. 'excess_color' => $excess_color,
  4697. 'threadhold1' => $threadhold1,
  4698. 'threadhold2' => $threadhold2,
  4699. 'threadhold3' => $threadhold3,
  4700. );
  4701. if ($from == 'exercise_result') {
  4702. // if answer is hotspot. To the difference of exercise_show.php,
  4703. // we use the results from the session (from_db=0)
  4704. // TODO Change this, because it is wrong to show the user
  4705. // some results that haven't been stored in the database yet
  4706. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
  4707. if ($debug) error_log('$from AND this is a hotspot kind of question ');
  4708. $my_exe_id = 0;
  4709. $from_database = 0;
  4710. if ($answerType == HOT_SPOT_DELINEATION) {
  4711. if (0) {
  4712. if ($overlap_color) {
  4713. $overlap_color = 'green';
  4714. } else {
  4715. $overlap_color = 'red';
  4716. }
  4717. if ($missing_color) {
  4718. $missing_color = 'green';
  4719. } else {
  4720. $missing_color = 'red';
  4721. }
  4722. if ($excess_color) {
  4723. $excess_color = 'green';
  4724. } else {
  4725. $excess_color = 'red';
  4726. }
  4727. if (!is_numeric($final_overlap)) {
  4728. $final_overlap = 0;
  4729. }
  4730. if (!is_numeric($final_missing)) {
  4731. $final_missing = 0;
  4732. }
  4733. if (!is_numeric($final_excess)) {
  4734. $final_excess = 0;
  4735. }
  4736. if ($final_overlap > 100) {
  4737. $final_overlap = 100;
  4738. }
  4739. $table_resume = '<table class="data_table">
  4740. <tr class="row_odd" >
  4741. <td></td>
  4742. <td ><b>' . get_lang('Requirements').'</b></td>
  4743. <td><b>' . get_lang('YourAnswer').'</b></td>
  4744. </tr>
  4745. <tr class="row_even">
  4746. <td><b>' . get_lang('Overlap').'</b></td>
  4747. <td>' . get_lang('Min').' '.$threadhold1.'</td>
  4748. <td><div style="color:' . $overlap_color.'">'
  4749. . (($final_overlap < 0) ? 0 : intval($final_overlap)).'</div></td>
  4750. </tr>
  4751. <tr>
  4752. <td><b>' . get_lang('Excess').'</b></td>
  4753. <td>' . get_lang('Max').' '.$threadhold2.'</td>
  4754. <td><div style="color:' . $excess_color.'">'
  4755. . (($final_excess < 0) ? 0 : intval($final_excess)).'</div></td>
  4756. </tr>
  4757. <tr class="row_even">
  4758. <td><b>' . get_lang('Missing').'</b></td>
  4759. <td>' . get_lang('Max').' '.$threadhold3.'</td>
  4760. <td><div style="color:' . $missing_color.'">'
  4761. . (($final_missing < 0) ? 0 : intval($final_missing)).'</div></td>
  4762. </tr>
  4763. </table>';
  4764. if ($next == 0) {
  4765. $try = $try_hotspot;
  4766. $lp = $lp_hotspot;
  4767. $destinationid = $select_question_hotspot;
  4768. $url = $url_hotspot;
  4769. } else {
  4770. //show if no error
  4771. //echo 'no error';
  4772. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  4773. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  4774. }
  4775. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  4776. <p style="text-align:center">';
  4777. $message = '<p>'.get_lang('YourDelineation').'</p>';
  4778. $message .= $table_resume;
  4779. $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  4780. if ($organs_at_risk_hit > 0) {
  4781. $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
  4782. }
  4783. $message .= '<p>'.$comment.'</p>';
  4784. echo $message;
  4785. } else {
  4786. echo $hotspot_delineation_result[0]; //prints message
  4787. $from_database = 1; // the hotspot_solution.swf needs this variable
  4788. }
  4789. //save the score attempts
  4790. if (1) {
  4791. //getting the answer 1 or 0 comes from exercise_submit_modal.php
  4792. $final_answer = $hotspot_delineation_result[1];
  4793. if ($final_answer == 0) {
  4794. $questionScore = 0;
  4795. }
  4796. // we always insert the answer_id 1 = delineation
  4797. Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0);
  4798. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  4799. $hotspotValue = (int) $hotspot_delineation_result[1] === 1 ? 1 : 0;
  4800. Event::saveExerciseAttemptHotspot(
  4801. $exeId,
  4802. $quesId,
  4803. 1,
  4804. $hotspotValue,
  4805. $exerciseResultCoordinates[$quesId]
  4806. );
  4807. } else {
  4808. if ($final_answer == 0) {
  4809. $questionScore = 0;
  4810. $answer = 0;
  4811. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  4812. if (is_array($exerciseResultCoordinates[$quesId])) {
  4813. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4814. Event::saveExerciseAttemptHotspot(
  4815. $exeId,
  4816. $quesId,
  4817. $idx,
  4818. 0,
  4819. $val
  4820. );
  4821. }
  4822. }
  4823. } else {
  4824. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  4825. if (is_array($exerciseResultCoordinates[$quesId])) {
  4826. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  4827. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  4828. Event::saveExerciseAttemptHotspot(
  4829. $exeId,
  4830. $quesId,
  4831. $idx,
  4832. $hotspotValue,
  4833. $val
  4834. );
  4835. }
  4836. }
  4837. }
  4838. }
  4839. $my_exe_id = $exeId;
  4840. }
  4841. }
  4842. $relPath = api_get_path(WEB_CODE_PATH);
  4843. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  4844. // We made an extra table for the answers
  4845. if ($show_result) {
  4846. // if ($origin != 'learnpath') {
  4847. echo '</table></td></tr>';
  4848. echo "
  4849. <tr>
  4850. <td colspan=\"2\">
  4851. <p><em>" . get_lang('HotSpot')."</em></p>
  4852. <div id=\"hotspot-solution-$questionId\"></div>
  4853. <script>
  4854. $(document).on('ready', function () {
  4855. new HotspotQuestion({
  4856. questionId: $questionId,
  4857. exerciseId: $exeId,
  4858. selector: '#hotspot-solution-$questionId',
  4859. for: 'solution',
  4860. relPath: '$relPath'
  4861. });
  4862. });
  4863. </script>
  4864. </td>
  4865. </tr>
  4866. ";
  4867. // }
  4868. }
  4869. } elseif ($answerType == ANNOTATION) {
  4870. if ($show_result) {
  4871. echo '
  4872. <p><em>' . get_lang('Annotation').'</em></p>
  4873. <div id="annotation-canvas-'.$questionId.'"></div>
  4874. <script>
  4875. AnnotationQuestion({
  4876. questionId: parseInt('.$questionId.'),
  4877. exerciseId: parseInt('.$exeId.'),
  4878. relPath: \''.$relPath.'\'
  4879. });
  4880. </script>
  4881. ';
  4882. }
  4883. }
  4884. //if ($origin != 'learnpath') {
  4885. if ($show_result && $answerType != ANNOTATION) {
  4886. echo '</table>';
  4887. }
  4888. // }
  4889. }
  4890. unset($objAnswerTmp);
  4891. $totalWeighting += $questionWeighting;
  4892. // Store results directly in the database
  4893. // For all in one page exercises, the results will be
  4894. // stored by exercise_results.php (using the session)
  4895. if ($saved_results) {
  4896. if ($debug) error_log("Save question results $saved_results");
  4897. if ($debug) error_log(print_r($choice, 1));
  4898. if (empty($choice)) {
  4899. $choice = 0;
  4900. }
  4901. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4902. if ($choice != 0) {
  4903. $reply = array_keys($choice);
  4904. for ($i = 0; $i < sizeof($reply); $i++) {
  4905. $ans = $reply[$i];
  4906. Event::saveQuestionAttempt(
  4907. $questionScore,
  4908. $ans.':'.$choice[$ans],
  4909. $quesId,
  4910. $exeId,
  4911. $i,
  4912. $this->id
  4913. );
  4914. if ($debug) {
  4915. error_log('result =>'.$questionScore.' '.$ans.':'.$choice[$ans]);
  4916. }
  4917. }
  4918. } else {
  4919. Event::saveQuestionAttempt(
  4920. $questionScore,
  4921. 0,
  4922. $quesId,
  4923. $exeId,
  4924. 0,
  4925. $this->id
  4926. );
  4927. }
  4928. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  4929. if ($choice != 0) {
  4930. $reply = array_keys($choice);
  4931. if ($debug) {
  4932. error_log("reply ".print_r($reply, 1)."");
  4933. }
  4934. for ($i = 0; $i < sizeof($reply); $i++) {
  4935. $ans = $reply[$i];
  4936. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  4937. }
  4938. } else {
  4939. Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  4940. }
  4941. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  4942. if ($choice != 0) {
  4943. $reply = array_keys($choice);
  4944. for ($i = 0; $i < sizeof($reply); $i++) {
  4945. $ans = $reply[$i];
  4946. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  4947. }
  4948. } else {
  4949. Event::saveQuestionAttempt(
  4950. $questionScore,
  4951. 0,
  4952. $quesId,
  4953. $exeId,
  4954. 0,
  4955. $this->id
  4956. );
  4957. }
  4958. } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
  4959. if (isset($matching)) {
  4960. foreach ($matching as $j => $val) {
  4961. Event::saveQuestionAttempt(
  4962. $questionScore,
  4963. $val,
  4964. $quesId,
  4965. $exeId,
  4966. $j,
  4967. $this->id
  4968. );
  4969. }
  4970. }
  4971. } elseif ($answerType == FREE_ANSWER) {
  4972. $answer = $choice;
  4973. Event::saveQuestionAttempt(
  4974. $questionScore,
  4975. $answer,
  4976. $quesId,
  4977. $exeId,
  4978. 0,
  4979. $this->id
  4980. );
  4981. } elseif ($answerType == ORAL_EXPRESSION) {
  4982. $answer = $choice;
  4983. Event::saveQuestionAttempt(
  4984. $questionScore,
  4985. $answer,
  4986. $quesId,
  4987. $exeId,
  4988. 0,
  4989. $this->id,
  4990. false,
  4991. $objQuestionTmp->getAbsoluteFilePath()
  4992. );
  4993. } elseif (in_array($answerType, [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, READING_COMPREHENSION])) {
  4994. $answer = $choice;
  4995. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  4996. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  4997. } elseif ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  4998. $answer = [];
  4999. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  5000. Database::delete(
  5001. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  5002. [
  5003. 'hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [
  5004. $exeId,
  5005. $questionId,
  5006. api_get_course_int_id()
  5007. ]
  5008. ]
  5009. );
  5010. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  5011. $answer[] = $val;
  5012. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  5013. Event::saveExerciseAttemptHotspot(
  5014. $exeId,
  5015. $quesId,
  5016. $idx,
  5017. $hotspotValue,
  5018. $val,
  5019. false,
  5020. $this->id
  5021. );
  5022. }
  5023. }
  5024. Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id);
  5025. } else {
  5026. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  5027. }
  5028. }
  5029. if ($propagate_neg == 0 && $questionScore < 0) {
  5030. $questionScore = 0;
  5031. }
  5032. if ($saved_results) {
  5033. $stat_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5034. $sql = 'UPDATE '.$stat_table.' SET
  5035. exe_result = exe_result + ' . floatval($questionScore).'
  5036. WHERE exe_id = ' . $exeId;
  5037. Database::query($sql);
  5038. }
  5039. $return_array = array(
  5040. 'score' => $questionScore,
  5041. 'weight' => $questionWeighting,
  5042. 'extra' => $extra_data,
  5043. 'open_question' => $arrques,
  5044. 'open_answer' => $arrans,
  5045. 'answer_type' => $answerType,
  5046. );
  5047. return $return_array;
  5048. }
  5049. /**
  5050. * Sends a notification when a user ends an examn
  5051. *
  5052. * @param string $type 'start' or 'end' of an exercise
  5053. * @param array $question_list_answers
  5054. * @param string $origin
  5055. * @param int $exe_id
  5056. * @param float $score
  5057. * @param float $weight
  5058. * @return bool
  5059. */
  5060. public function send_mail_notification_for_exam(
  5061. $type = 'end',
  5062. $question_list_answers,
  5063. $origin,
  5064. $exe_id,
  5065. $score = null,
  5066. $weight = null
  5067. ) {
  5068. $setting = api_get_course_setting('email_alert_manager_on_new_quiz');
  5069. if (empty($setting) && empty($this->getNotifications())) {
  5070. return false;
  5071. }
  5072. $settingFromExercise = $this->getNotifications();
  5073. if (!empty($settingFromExercise)) {
  5074. $setting = $settingFromExercise;
  5075. }
  5076. // Email configuration settings
  5077. $courseCode = api_get_course_id();
  5078. $courseInfo = api_get_course_info($courseCode);
  5079. if (empty($courseInfo)) {
  5080. return false;
  5081. }
  5082. $sessionId = api_get_session_id();
  5083. $sendStart = false;
  5084. $sendEnd = false;
  5085. $sendEndOpenQuestion = false;
  5086. $sendEndOralQuestion = false;
  5087. foreach ($setting as $option) {
  5088. switch ($option) {
  5089. case 0:
  5090. return false;
  5091. break;
  5092. case 1: // End
  5093. if ($type == 'end') {
  5094. $sendEnd = true;
  5095. }
  5096. break;
  5097. case 2: // start
  5098. if ($type == 'start') {
  5099. $sendStart = true;
  5100. }
  5101. break;
  5102. case 3: // end + open
  5103. if ($type == 'end') {
  5104. $sendEndOpenQuestion = true;
  5105. }
  5106. break;
  5107. case 4: // end + oral
  5108. if ($type == 'end') {
  5109. $sendEndOralQuestion = true;
  5110. }
  5111. break;
  5112. }
  5113. }
  5114. $user_info = api_get_user_info(api_get_user_id());
  5115. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_show.php?'.api_get_cidreq().'&id_session='.$sessionId.'&id='.$exe_id.'&action=qualify';
  5116. if (!empty($sessionId)) {
  5117. $addGeneralCoach = true;
  5118. $setting = api_get_configuration_value('block_quiz_mail_notification_general_coach');
  5119. if ($setting === true) {
  5120. $addGeneralCoach = false;
  5121. }
  5122. $teachers = CourseManager::get_coach_list_from_course_code(
  5123. $courseCode,
  5124. $sessionId,
  5125. $addGeneralCoach
  5126. );
  5127. } else {
  5128. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  5129. }
  5130. if ($sendEndOpenQuestion) {
  5131. $this->send_notification_for_open_questions(
  5132. $question_list_answers,
  5133. $origin,
  5134. $exe_id,
  5135. $user_info,
  5136. $url,
  5137. $teachers
  5138. );
  5139. }
  5140. if ($sendEndOralQuestion) {
  5141. $this->send_notification_for_oral_questions(
  5142. $question_list_answers,
  5143. $origin,
  5144. $exe_id,
  5145. $user_info,
  5146. $url,
  5147. $teachers
  5148. );
  5149. }
  5150. if (!$sendEnd && !$sendStart) {
  5151. return false;
  5152. }
  5153. $scoreLabel = '';
  5154. if ($sendEnd && api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true) {
  5155. $scoreLabel = ExerciseLib::show_score($score, $weight, false, true);
  5156. $scoreLabel = "<tr>
  5157. <td>".get_lang('Score')."</td>
  5158. <td>&nbsp;$scoreLabel</td>
  5159. </tr>";
  5160. }
  5161. if ($sendEnd) {
  5162. $msg = get_lang('ExerciseAttempted').'<br /><br />';
  5163. } else {
  5164. $msg = get_lang('StudentStartExercise').'<br /><br />';
  5165. }
  5166. $msg .= get_lang('AttemptDetails').' : <br /><br />
  5167. <table>
  5168. <tr>
  5169. <td>'.get_lang('CourseName').'</td>
  5170. <td>#course#</td>
  5171. </tr>
  5172. <tr>
  5173. <td>'.get_lang('Exercise').'</td>
  5174. <td>&nbsp;#exercise#</td>
  5175. </tr>
  5176. <tr>
  5177. <td>'.get_lang('StudentName').'</td>
  5178. <td>&nbsp;#student_complete_name#</td>
  5179. </tr>
  5180. <tr>
  5181. <td>'.get_lang('StudentEmail').'</td>
  5182. <td>&nbsp;#email#</td>
  5183. </tr>
  5184. '.$scoreLabel.'
  5185. </table>';
  5186. $variables = [
  5187. '#email#' => $user_info['email'],
  5188. '#exercise#' => $this->exercise,
  5189. '#student_complete_name#' => $user_info['complete_name'],
  5190. '#course#' => $courseInfo['title']
  5191. ];
  5192. if ($origin != 'learnpath' && $sendEnd) {
  5193. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5194. $variables['#url#'] = $url;
  5195. }
  5196. $mail_content = str_replace(array_keys($variables), array_values($variables), $msg);
  5197. if ($sendEnd) {
  5198. $subject = get_lang('ExerciseAttempted');
  5199. } else {
  5200. $subject = get_lang('StudentStartExercise');
  5201. }
  5202. if (!empty($teachers)) {
  5203. foreach ($teachers as $user_id => $teacher_data) {
  5204. MessageManager::send_message_simple(
  5205. $user_id,
  5206. $subject,
  5207. $mail_content
  5208. );
  5209. }
  5210. }
  5211. }
  5212. /**
  5213. * Sends a notification when a user ends an examn
  5214. * @param array $question_list_answers
  5215. * @param string $origin
  5216. * @param int $exe_id
  5217. * @return null
  5218. */
  5219. private function send_notification_for_open_questions(
  5220. $question_list_answers,
  5221. $origin,
  5222. $exe_id,
  5223. $user_info,
  5224. $url_email,
  5225. $teachers
  5226. ) {
  5227. // Email configuration settings
  5228. $courseCode = api_get_course_id();
  5229. $course_info = api_get_course_info($courseCode);
  5230. $msg = get_lang('OpenQuestionsAttempted').'<br /><br />'
  5231. .get_lang('AttemptDetails').' : <br /><br />'
  5232. .'<table>'
  5233. .'<tr>'
  5234. .'<td><em>'.get_lang('CourseName').'</em></td>'
  5235. .'<td>&nbsp;<b>#course#</b></td>'
  5236. .'</tr>'
  5237. .'<tr>'
  5238. .'<td>'.get_lang('TestAttempted').'</td>'
  5239. .'<td>&nbsp;#exercise#</td>'
  5240. .'</tr>'
  5241. .'<tr>'
  5242. .'<td>'.get_lang('StudentName').'</td>'
  5243. .'<td>&nbsp;#firstName# #lastName#</td>'
  5244. .'</tr>'
  5245. .'<tr>'
  5246. .'<td>'.get_lang('StudentEmail').'</td>'
  5247. .'<td>&nbsp;#mail#</td>'
  5248. .'</tr>'
  5249. .'</table>';
  5250. $open_question_list = null;
  5251. foreach ($question_list_answers as $item) {
  5252. $question = $item['question'];
  5253. $answer = $item['answer'];
  5254. $answer_type = $item['answer_type'];
  5255. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  5256. $open_question_list .=
  5257. '<tr>'
  5258. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  5259. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  5260. .'</tr>'
  5261. .'<tr>'
  5262. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  5263. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  5264. .'</tr>';
  5265. }
  5266. }
  5267. if (!empty($open_question_list)) {
  5268. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>'.
  5269. '<table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  5270. $msg .= $open_question_list;
  5271. $msg .= '</table><br />';
  5272. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  5273. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  5274. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  5275. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  5276. $msg = str_replace("#course#", $course_info['name'], $msg1);
  5277. if ($origin != 'learnpath') {
  5278. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5279. }
  5280. $msg1 = str_replace("#url#", $url_email, $msg);
  5281. $mail_content = $msg1;
  5282. $subject = get_lang('OpenQuestionsAttempted');
  5283. if (!empty($teachers)) {
  5284. foreach ($teachers as $user_id => $teacher_data) {
  5285. MessageManager::send_message_simple(
  5286. $user_id,
  5287. $subject,
  5288. $mail_content
  5289. );
  5290. }
  5291. }
  5292. }
  5293. }
  5294. /**
  5295. * Send notification for oral questions
  5296. * @param array $question_list_answers
  5297. * @param string $origin
  5298. * @param int $exe_id
  5299. * @return null
  5300. */
  5301. private function send_notification_for_oral_questions(
  5302. $question_list_answers,
  5303. $origin,
  5304. $exe_id,
  5305. $user_info,
  5306. $url_email,
  5307. $teachers
  5308. ) {
  5309. // Email configuration settings
  5310. $courseCode = api_get_course_id();
  5311. $course_info = api_get_course_info($courseCode);
  5312. $oral_question_list = null;
  5313. foreach ($question_list_answers as $item) {
  5314. $question = $item['question'];
  5315. $answer = $item['answer'];
  5316. $answer_type = $item['answer_type'];
  5317. if (!empty($question) && !empty($answer) && $answer_type == ORAL_EXPRESSION) {
  5318. $oral_question_list .= '<br /><table width="730" height="136" border="0" cellpadding="3" cellspacing="3">'
  5319. .'<tr>'
  5320. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  5321. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  5322. .'</tr>'
  5323. .'<tr>'
  5324. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  5325. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  5326. .'</tr></table>';
  5327. }
  5328. }
  5329. if (!empty($oral_question_list)) {
  5330. $msg = get_lang('OralQuestionsAttempted').'<br /><br />
  5331. '.get_lang('AttemptDetails').' : <br /><br />'
  5332. .'<table>'
  5333. .'<tr>'
  5334. .'<td><em>'.get_lang('CourseName').'</em></td>'
  5335. .'<td>&nbsp;<b>#course#</b></td>'
  5336. .'</tr>'
  5337. .'<tr>'
  5338. .'<td>'.get_lang('TestAttempted').'</td>'
  5339. .'<td>&nbsp;#exercise#</td>'
  5340. .'</tr>'
  5341. .'<tr>'
  5342. .'<td>'.get_lang('StudentName').'</td>'
  5343. .'<td>&nbsp;#firstName# #lastName#</td>'
  5344. .'</tr>'
  5345. .'<tr>'
  5346. .'<td>'.get_lang('StudentEmail').'</td>'
  5347. .'<td>&nbsp;#mail#</td>'
  5348. .'</tr>'
  5349. .'</table>';
  5350. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
  5351. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  5352. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  5353. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  5354. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  5355. $msg = str_replace("#course#", $course_info['name'], $msg1);
  5356. if ($origin != 'learnpath') {
  5357. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5358. }
  5359. $msg1 = str_replace("#url#", $url_email, $msg);
  5360. $mail_content = $msg1;
  5361. $subject = get_lang('OralQuestionsAttempted');
  5362. if (!empty($teachers)) {
  5363. foreach ($teachers as $user_id => $teacher_data) {
  5364. MessageManager::send_message_simple(
  5365. $user_id,
  5366. $subject,
  5367. $mail_content
  5368. );
  5369. }
  5370. }
  5371. }
  5372. }
  5373. /**
  5374. * @param array $user_data result of api_get_user_info()
  5375. * @param string $start_date
  5376. * @param null $duration
  5377. * @param string $ip Optional. The user IP
  5378. * @return string
  5379. */
  5380. public function show_exercise_result_header(
  5381. $user_data,
  5382. $start_date = null,
  5383. $duration = null,
  5384. $ip = null
  5385. ) {
  5386. $array = [];
  5387. if (!empty($user_data)) {
  5388. $array[] = array(
  5389. 'title' => get_lang('Name'),
  5390. 'content' => $user_data['complete_name']
  5391. );
  5392. $array[] = array(
  5393. 'title' => get_lang('Username'),
  5394. 'content' => $user_data['username']
  5395. );
  5396. if (!empty($user_data['official_code'])) {
  5397. $array[] = array(
  5398. 'title' => get_lang('OfficialCode'),
  5399. 'content' => $user_data['official_code']
  5400. );
  5401. }
  5402. }
  5403. // Description can be very long and is generally meant to explain
  5404. // rules *before* the exam. Leaving here to make display easier if
  5405. // necessary
  5406. /*
  5407. if (!empty($this->description)) {
  5408. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  5409. }
  5410. */
  5411. if (!empty($start_date)) {
  5412. $array[] = array('title' => get_lang('StartDate'), 'content' => $start_date);
  5413. }
  5414. if (!empty($duration)) {
  5415. $array[] = array('title' => get_lang('Duration'), 'content' => $duration);
  5416. }
  5417. if (!empty($ip)) {
  5418. $array[] = array('title' => get_lang('IP'), 'content' => $ip);
  5419. }
  5420. $icon = Display::return_icon(
  5421. 'test-quiz.png',
  5422. get_lang('Result'),
  5423. null,
  5424. ICON_SIZE_MEDIUM
  5425. );
  5426. $html = '<div class="question-result">';
  5427. if (api_get_configuration_value('save_titles_as_html')) {
  5428. $html .= $this->get_formated_title();
  5429. $html .= Display::page_header(get_lang('Result'));
  5430. } else {
  5431. $html .= Display::page_header(
  5432. $icon.PHP_EOL.$this->exercise.' : '.get_lang('Result')
  5433. );
  5434. }
  5435. $hide = api_get_configuration_value('hide_user_info_in_quiz_result');
  5436. if ($hide === false) {
  5437. $html .= Display::description($array);
  5438. }
  5439. $html .= "</div>";
  5440. return $html;
  5441. }
  5442. /**
  5443. * Create a quiz from quiz data
  5444. * @param string Title
  5445. * @param int Time before it expires (in minutes)
  5446. * @param int Type of exercise
  5447. * @param int Whether it's randomly picked questions (1) or not (0)
  5448. * @param int Whether the exercise is visible to the user (1) or not (0)
  5449. * @param int Whether the results are show to the user (0) or not (1)
  5450. * @param int Maximum number of attempts (0 if no limit)
  5451. * @param int Feedback type
  5452. * @todo this was function was added due the import exercise via CSV
  5453. * @return int New exercise ID
  5454. */
  5455. public function createExercise(
  5456. $title,
  5457. $expired_time = 0,
  5458. $type = 2,
  5459. $random = 0,
  5460. $active = 1,
  5461. $results_disabled = 0,
  5462. $max_attempt = 0,
  5463. $feedback = 3,
  5464. $propagateNegative = 0
  5465. ) {
  5466. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  5467. $type = intval($type);
  5468. $random = intval($random);
  5469. $active = intval($active);
  5470. $results_disabled = intval($results_disabled);
  5471. $max_attempt = intval($max_attempt);
  5472. $feedback = intval($feedback);
  5473. $expired_time = intval($expired_time);
  5474. $title = Database::escape_string($title);
  5475. $propagateNegative = intval($propagateNegative);
  5476. $sessionId = api_get_session_id();
  5477. $course_id = api_get_course_int_id();
  5478. // Save a new quiz
  5479. $sql = "INSERT INTO $tbl_quiz (
  5480. c_id,
  5481. title,
  5482. type,
  5483. random,
  5484. active,
  5485. results_disabled,
  5486. max_attempt,
  5487. start_time,
  5488. end_time,
  5489. feedback_type,
  5490. expired_time,
  5491. session_id,
  5492. propagate_neg
  5493. )
  5494. VALUES (
  5495. '$course_id',
  5496. '$title',
  5497. $type,
  5498. $random,
  5499. $active,
  5500. $results_disabled,
  5501. $max_attempt,
  5502. '',
  5503. '',
  5504. $feedback,
  5505. $expired_time,
  5506. $sessionId,
  5507. $propagateNegative
  5508. )";
  5509. Database::query($sql);
  5510. $quiz_id = Database::insert_id();
  5511. if ($quiz_id) {
  5512. $sql = "UPDATE $tbl_quiz SET id = iid WHERE iid = {$quiz_id} ";
  5513. Database::query($sql);
  5514. }
  5515. return $quiz_id;
  5516. }
  5517. function process_geometry()
  5518. {
  5519. }
  5520. /**
  5521. * Returns the exercise result
  5522. * @param int attempt id
  5523. * @return float exercise result
  5524. */
  5525. public function get_exercise_result($exe_id)
  5526. {
  5527. $result = array();
  5528. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  5529. if (!empty($track_exercise_info)) {
  5530. $totalScore = 0;
  5531. $objExercise = new Exercise();
  5532. $objExercise->read($track_exercise_info['exe_exo_id']);
  5533. if (!empty($track_exercise_info['data_tracking'])) {
  5534. $question_list = explode(',', $track_exercise_info['data_tracking']);
  5535. }
  5536. foreach ($question_list as $questionId) {
  5537. $question_result = $objExercise->manage_answer(
  5538. $exe_id,
  5539. $questionId,
  5540. '',
  5541. 'exercise_show',
  5542. array(),
  5543. false,
  5544. true,
  5545. false,
  5546. $objExercise->selectPropagateNeg()
  5547. );
  5548. $totalScore += $question_result['score'];
  5549. }
  5550. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  5551. $totalScore = 0;
  5552. }
  5553. $result = array(
  5554. 'score' => $totalScore,
  5555. 'weight' => $track_exercise_info['exe_weighting']
  5556. );
  5557. }
  5558. return $result;
  5559. }
  5560. /**
  5561. * Checks if the exercise is visible due a lot of conditions
  5562. * visibility, time limits, student attempts
  5563. * Return associative array
  5564. * value : true if exercise visible
  5565. * message : HTML formatted message
  5566. * rawMessage : text message
  5567. * @param int $lpId
  5568. * @param int $lpItemId
  5569. * @param int $lpItemViewId
  5570. * @param bool $filterByAdmin
  5571. * @return array
  5572. */
  5573. public function is_visible(
  5574. $lpId = 0,
  5575. $lpItemId = 0,
  5576. $lpItemViewId = 0,
  5577. $filterByAdmin = true
  5578. ) {
  5579. // 1. By default the exercise is visible
  5580. $isVisible = true;
  5581. $message = null;
  5582. // 1.1 Admins and teachers can access to the exercise
  5583. if ($filterByAdmin) {
  5584. if (api_is_platform_admin() || api_is_course_admin()) {
  5585. return array('value' => true, 'message' => '');
  5586. }
  5587. }
  5588. // Deleted exercise.
  5589. if ($this->active == -1) {
  5590. return array(
  5591. 'value' => false,
  5592. 'message' => Display::return_message(
  5593. get_lang('ExerciseNotFound'),
  5594. 'warning',
  5595. false
  5596. ),
  5597. 'rawMessage' => get_lang('ExerciseNotFound')
  5598. );
  5599. }
  5600. // Checking visibility in the item_property table.
  5601. $visibility = api_get_item_visibility(
  5602. api_get_course_info(),
  5603. TOOL_QUIZ,
  5604. $this->id,
  5605. api_get_session_id()
  5606. );
  5607. if ($visibility == 0 || $visibility == 2) {
  5608. $this->active = 0;
  5609. }
  5610. // 2. If the exercise is not active.
  5611. if (empty($lpId)) {
  5612. // 2.1 LP is OFF
  5613. if ($this->active == 0) {
  5614. return array(
  5615. 'value' => false,
  5616. 'message' => Display::return_message(
  5617. get_lang('ExerciseNotFound'),
  5618. 'warning',
  5619. false
  5620. ),
  5621. 'rawMessage' => get_lang('ExerciseNotFound')
  5622. );
  5623. }
  5624. } else {
  5625. // 2.1 LP is loaded
  5626. if ($this->active == 0 &&
  5627. !learnpath::is_lp_visible_for_student($lpId, api_get_user_id())
  5628. ) {
  5629. return array(
  5630. 'value' => false,
  5631. 'message' => Display::return_message(
  5632. get_lang('ExerciseNotFound'),
  5633. 'warning',
  5634. false
  5635. ),
  5636. 'rawMessage' => get_lang('ExerciseNotFound')
  5637. );
  5638. }
  5639. }
  5640. //3. We check if the time limits are on
  5641. if (!empty($this->start_time) || !empty($this->end_time)) {
  5642. $limitTimeExists = true;
  5643. } else {
  5644. $limitTimeExists = false;
  5645. }
  5646. if ($limitTimeExists) {
  5647. $timeNow = time();
  5648. $existsStartDate = false;
  5649. $nowIsAfterStartDate = true;
  5650. $existsEndDate = false;
  5651. $nowIsBeforeEndDate = true;
  5652. if (!empty($this->start_time)) {
  5653. $existsStartDate = true;
  5654. }
  5655. if (!empty($this->end_time)) {
  5656. $existsEndDate = true;
  5657. }
  5658. // check if we are before-or-after end-or-start date
  5659. if ($existsStartDate && $timeNow < api_strtotime($this->start_time, 'UTC')) {
  5660. $nowIsAfterStartDate = false;
  5661. }
  5662. if ($existsEndDate & $timeNow >= api_strtotime($this->end_time, 'UTC')) {
  5663. $nowIsBeforeEndDate = false;
  5664. }
  5665. // lets check all cases
  5666. if ($existsStartDate && !$existsEndDate) {
  5667. // exists start date and dont exists end date
  5668. if ($nowIsAfterStartDate) {
  5669. // after start date, no end date
  5670. $isVisible = true;
  5671. $message = sprintf(
  5672. get_lang('ExerciseAvailableSinceX'),
  5673. api_convert_and_format_date($this->start_time)
  5674. );
  5675. } else {
  5676. // before start date, no end date
  5677. $isVisible = false;
  5678. $message = sprintf(
  5679. get_lang('ExerciseAvailableFromX'),
  5680. api_convert_and_format_date($this->start_time)
  5681. );
  5682. }
  5683. } elseif (!$existsStartDate && $existsEndDate) {
  5684. // doesnt exist start date, exists end date
  5685. if ($nowIsBeforeEndDate) {
  5686. // before end date, no start date
  5687. $isVisible = true;
  5688. $message = sprintf(
  5689. get_lang('ExerciseAvailableUntilX'),
  5690. api_convert_and_format_date($this->end_time)
  5691. );
  5692. } else {
  5693. // after end date, no start date
  5694. $isVisible = false;
  5695. $message = sprintf(
  5696. get_lang('ExerciseAvailableUntilX'),
  5697. api_convert_and_format_date($this->end_time)
  5698. );
  5699. }
  5700. } elseif ($existsStartDate && $existsEndDate) {
  5701. // exists start date and end date
  5702. if ($nowIsAfterStartDate) {
  5703. if ($nowIsBeforeEndDate) {
  5704. // after start date and before end date
  5705. $isVisible = true;
  5706. $message = sprintf(
  5707. get_lang('ExerciseIsActivatedFromXToY'),
  5708. api_convert_and_format_date($this->start_time),
  5709. api_convert_and_format_date($this->end_time)
  5710. );
  5711. } else {
  5712. // after start date and after end date
  5713. $isVisible = false;
  5714. $message = sprintf(
  5715. get_lang('ExerciseWasActivatedFromXToY'),
  5716. api_convert_and_format_date($this->start_time),
  5717. api_convert_and_format_date($this->end_time)
  5718. );
  5719. }
  5720. } else {
  5721. if ($nowIsBeforeEndDate) {
  5722. // before start date and before end date
  5723. $isVisible = false;
  5724. $message = sprintf(
  5725. get_lang('ExerciseWillBeActivatedFromXToY'),
  5726. api_convert_and_format_date($this->start_time),
  5727. api_convert_and_format_date($this->end_time)
  5728. );
  5729. }
  5730. // case before start date and after end date is impossible
  5731. }
  5732. } elseif (!$existsStartDate && !$existsEndDate) {
  5733. // doesnt exist start date nor end date
  5734. $isVisible = true;
  5735. $message = '';
  5736. }
  5737. }
  5738. // 4. We check if the student have attempts
  5739. $exerciseAttempts = $this->selectAttempts();
  5740. if ($isVisible) {
  5741. if ($exerciseAttempts > 0) {
  5742. $attemptCount = Event::get_attempt_count_not_finished(
  5743. api_get_user_id(),
  5744. $this->id,
  5745. $lpId,
  5746. $lpItemId,
  5747. $lpItemViewId
  5748. );
  5749. if ($attemptCount >= $exerciseAttempts) {
  5750. $message = sprintf(
  5751. get_lang('ReachedMaxAttempts'),
  5752. $this->name,
  5753. $exerciseAttempts
  5754. );
  5755. $isVisible = false;
  5756. }
  5757. }
  5758. }
  5759. $rawMessage = '';
  5760. if (!empty($message)) {
  5761. $rawMessage = $message;
  5762. $message = Display::return_message($message, 'warning', false);
  5763. }
  5764. return array(
  5765. 'value' => $isVisible,
  5766. 'message' => $message,
  5767. 'rawMessage' => $rawMessage
  5768. );
  5769. }
  5770. public function added_in_lp()
  5771. {
  5772. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  5773. $sql = "SELECT max_score FROM $TBL_LP_ITEM
  5774. WHERE
  5775. c_id = {$this->course_id} AND
  5776. item_type = '".TOOL_QUIZ."' AND
  5777. path = '{$this->id}'";
  5778. $result = Database::query($sql);
  5779. if (Database::num_rows($result) > 0) {
  5780. return true;
  5781. }
  5782. return false;
  5783. }
  5784. /**
  5785. * Returns an array with the media list
  5786. * @param array question list
  5787. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  5788. * <code>
  5789. * array (size=2)
  5790. * 999 =>
  5791. * array (size=3)
  5792. * 0 => int 7
  5793. * 1 => int 6
  5794. * 2 => int 3254
  5795. * 100 =>
  5796. * array (size=1)
  5797. * 0 => int 5
  5798. * </code>
  5799. * @return array
  5800. */
  5801. private function setMediaList($questionList)
  5802. {
  5803. $mediaList = array();
  5804. if (!empty($questionList)) {
  5805. foreach ($questionList as $questionId) {
  5806. $objQuestionTmp = Question::read($questionId, $this->course_id);
  5807. // If a media question exists
  5808. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  5809. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  5810. } else {
  5811. //Always the last item
  5812. $mediaList[999][] = $objQuestionTmp->id;
  5813. }
  5814. }
  5815. }
  5816. $this->mediaList = $mediaList;
  5817. }
  5818. /**
  5819. * Returns an array with this form
  5820. * @example
  5821. * <code>
  5822. * array (size=3)
  5823. 999 =>
  5824. array (size=3)
  5825. 0 => int 3422
  5826. 1 => int 3423
  5827. 2 => int 3424
  5828. 100 =>
  5829. array (size=2)
  5830. 0 => int 3469
  5831. 1 => int 3470
  5832. 101 =>
  5833. array (size=1)
  5834. 0 => int 3482
  5835. * </code>
  5836. * The array inside the key 999 means the question list that belongs to the media id = 999,
  5837. * this case is special because 999 means "no media".
  5838. * @return array
  5839. */
  5840. public function getMediaList()
  5841. {
  5842. return $this->mediaList;
  5843. }
  5844. /**
  5845. * Is media question activated?
  5846. * @return bool
  5847. */
  5848. public function mediaIsActivated()
  5849. {
  5850. $mediaQuestions = $this->getMediaList();
  5851. $active = false;
  5852. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  5853. $media_count = count($mediaQuestions);
  5854. if ($media_count > 1) {
  5855. return true;
  5856. } elseif ($media_count == 1) {
  5857. if (isset($mediaQuestions[999])) {
  5858. return false;
  5859. } else {
  5860. return true;
  5861. }
  5862. }
  5863. }
  5864. return $active;
  5865. }
  5866. /**
  5867. * Gets question list from the exercise
  5868. *
  5869. * @return array
  5870. */
  5871. public function getQuestionList()
  5872. {
  5873. return $this->questionList;
  5874. }
  5875. /**
  5876. * Question list with medias compressed like this
  5877. * @example
  5878. * <code>
  5879. * array(
  5880. * question_id_1,
  5881. * question_id_2,
  5882. * media_id, <- this media id contains question ids
  5883. * question_id_3,
  5884. * )
  5885. * </code>
  5886. * @return array
  5887. */
  5888. public function getQuestionListWithMediasCompressed()
  5889. {
  5890. return $this->questionList;
  5891. }
  5892. /**
  5893. * Question list with medias uncompressed like this
  5894. * @example
  5895. * <code>
  5896. * array(
  5897. * question_id,
  5898. * question_id,
  5899. * question_id, <- belongs to a media id
  5900. * question_id, <- belongs to a media id
  5901. * question_id,
  5902. * )
  5903. * </code>
  5904. * @return array
  5905. */
  5906. public function getQuestionListWithMediasUncompressed()
  5907. {
  5908. return $this->questionListUncompressed;
  5909. }
  5910. /**
  5911. * Sets the question list when the exercise->read() is executed
  5912. * @param bool $adminView Whether to view the set the list of *all* questions or just the normal student view
  5913. */
  5914. public function setQuestionList($adminView = false)
  5915. {
  5916. // Getting question list.
  5917. $questionList = $this->selectQuestionList(true, $adminView);
  5918. $this->setMediaList($questionList);
  5919. $this->questionList = $this->transformQuestionListWithMedias(
  5920. $questionList,
  5921. false
  5922. );
  5923. $this->questionListUncompressed = $this->transformQuestionListWithMedias(
  5924. $questionList,
  5925. true
  5926. );
  5927. }
  5928. /**
  5929. * @params array question list
  5930. * @params bool expand or not question list (true show all questions,
  5931. * false show media question id instead of the question ids)
  5932. **/
  5933. public function transformQuestionListWithMedias(
  5934. $question_list,
  5935. $expand_media_questions = false
  5936. ) {
  5937. $new_question_list = array();
  5938. if (!empty($question_list)) {
  5939. $media_questions = $this->getMediaList();
  5940. $media_active = $this->mediaIsActivated($media_questions);
  5941. if ($media_active) {
  5942. $counter = 1;
  5943. foreach ($question_list as $question_id) {
  5944. $add_question = true;
  5945. foreach ($media_questions as $media_id => $question_list_in_media) {
  5946. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  5947. $add_question = false;
  5948. if (!in_array($media_id, $new_question_list)) {
  5949. $new_question_list[$counter] = $media_id;
  5950. $counter++;
  5951. }
  5952. break;
  5953. }
  5954. }
  5955. if ($add_question) {
  5956. $new_question_list[$counter] = $question_id;
  5957. $counter++;
  5958. }
  5959. }
  5960. if ($expand_media_questions) {
  5961. $media_key_list = array_keys($media_questions);
  5962. foreach ($new_question_list as &$question_id) {
  5963. if (in_array($question_id, $media_key_list)) {
  5964. $question_id = $media_questions[$question_id];
  5965. }
  5966. }
  5967. $new_question_list = array_flatten($new_question_list);
  5968. }
  5969. } else {
  5970. $new_question_list = $question_list;
  5971. }
  5972. }
  5973. return $new_question_list;
  5974. }
  5975. /**
  5976. * Get question list depend on the random settings.
  5977. *
  5978. * @return array
  5979. */
  5980. public function get_validated_question_list()
  5981. {
  5982. $tabres = array();
  5983. $isRandomByCategory = $this->isRandomByCat();
  5984. if ($isRandomByCategory == 0) {
  5985. if ($this->isRandom()) {
  5986. $tabres = $this->selectRandomList();
  5987. } else {
  5988. $tabres = $this->selectQuestionList();
  5989. }
  5990. } else {
  5991. if ($this->isRandom()) {
  5992. // USE question categories
  5993. // get questions by category for this exercise
  5994. // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
  5995. // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
  5996. // value is the array of question id of this category
  5997. $questionList = array();
  5998. $tabCategoryQuestions = TestCategory::getQuestionsByCat($this->id);
  5999. $isRandomByCategory = $this->selectRandomByCat();
  6000. // We sort categories based on the term between [] in the head
  6001. // of the category's description
  6002. /* examples of categories :
  6003. * [biologie] Maitriser les mecanismes de base de la genetique
  6004. * [biologie] Relier les moyens de depenses et les agents infectieux
  6005. * [biologie] Savoir ou est produite l'enrgie dans les cellules et sous quelle forme
  6006. * [chimie] Classer les molles suivant leur pouvoir oxydant ou reacteur
  6007. * [chimie] Connaître la denition de la theoie acide/base selon Brönsted
  6008. * [chimie] Connaître les charges des particules
  6009. * We want that in the order of the groups defined by the term
  6010. * between brackets at the beginning of the category title
  6011. */
  6012. // If test option is Grouped By Categories
  6013. if ($isRandomByCategory == 2) {
  6014. $tabCategoryQuestions = TestCategory::sortTabByBracketLabel($tabCategoryQuestions);
  6015. }
  6016. while (list($cat_id, $tabquestion) = each($tabCategoryQuestions)) {
  6017. $number_of_random_question = $this->random;
  6018. if ($this->random == -1) {
  6019. $number_of_random_question = count($this->questionList);
  6020. }
  6021. $questionList = array_merge(
  6022. $questionList,
  6023. TestCategory::getNElementsFromArray(
  6024. $tabquestion,
  6025. $number_of_random_question
  6026. )
  6027. );
  6028. }
  6029. // shuffle the question list if test is not grouped by categories
  6030. if ($isRandomByCategory == 1) {
  6031. shuffle($questionList); // or not
  6032. }
  6033. $tabres = $questionList;
  6034. } else {
  6035. // Problem, random by category has been selected and
  6036. // we have no $this->isRandom number of question selected
  6037. // Should not happened
  6038. }
  6039. }
  6040. return $tabres;
  6041. }
  6042. function get_question_list($expand_media_questions = false)
  6043. {
  6044. $question_list = $this->get_validated_question_list();
  6045. $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
  6046. return $question_list;
  6047. }
  6048. function transform_question_list_with_medias($question_list, $expand_media_questions = false)
  6049. {
  6050. $new_question_list = array();
  6051. if (!empty($question_list)) {
  6052. $media_questions = $this->getMediaList();
  6053. $media_active = $this->mediaIsActivated($media_questions);
  6054. if ($media_active) {
  6055. $counter = 1;
  6056. foreach ($question_list as $question_id) {
  6057. $add_question = true;
  6058. foreach ($media_questions as $media_id => $question_list_in_media) {
  6059. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  6060. $add_question = false;
  6061. if (!in_array($media_id, $new_question_list)) {
  6062. $new_question_list[$counter] = $media_id;
  6063. $counter++;
  6064. }
  6065. break;
  6066. }
  6067. }
  6068. if ($add_question) {
  6069. $new_question_list[$counter] = $question_id;
  6070. $counter++;
  6071. }
  6072. }
  6073. if ($expand_media_questions) {
  6074. $media_key_list = array_keys($media_questions);
  6075. foreach ($new_question_list as &$question_id) {
  6076. if (in_array($question_id, $media_key_list)) {
  6077. $question_id = $media_questions[$question_id];
  6078. }
  6079. }
  6080. $new_question_list = array_flatten($new_question_list);
  6081. }
  6082. } else {
  6083. $new_question_list = $question_list;
  6084. }
  6085. }
  6086. return $new_question_list;
  6087. }
  6088. /**
  6089. * @param int $exe_id
  6090. * @return array|mixed
  6091. */
  6092. public function get_stat_track_exercise_info_by_exe_id($exe_id)
  6093. {
  6094. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6095. $exe_id = intval($exe_id);
  6096. $sql_track = "SELECT * FROM $track_exercises WHERE exe_id = $exe_id ";
  6097. $result = Database::query($sql_track);
  6098. $new_array = array();
  6099. if (Database::num_rows($result) > 0) {
  6100. $new_array = Database::fetch_array($result, 'ASSOC');
  6101. $new_array['duration'] = null;
  6102. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  6103. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  6104. if (!empty($start_date) && !empty($end_date)) {
  6105. $start_date = api_strtotime($start_date, 'UTC');
  6106. $end_date = api_strtotime($end_date, 'UTC');
  6107. if ($start_date && $end_date) {
  6108. $mytime = $end_date - $start_date;
  6109. $new_learnpath_item = new learnpathItem(null);
  6110. $time_attemp = $new_learnpath_item->get_scorm_time('js', $mytime);
  6111. $h = get_lang('h');
  6112. $time_attemp = str_replace('NaN', '00'.$h.'00\'00"', $time_attemp);
  6113. $new_array['duration'] = $time_attemp;
  6114. }
  6115. }
  6116. }
  6117. return $new_array;
  6118. }
  6119. /**
  6120. * @param int $exe_id
  6121. * @param int $question_id
  6122. * @param string $action
  6123. */
  6124. public function editQuestionToRemind($exe_id, $question_id, $action = 'add')
  6125. {
  6126. $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
  6127. $question_id = intval($question_id);
  6128. $exe_id = intval($exe_id);
  6129. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6130. if ($exercise_info) {
  6131. if (empty($exercise_info['questions_to_check'])) {
  6132. if ($action == 'add') {
  6133. $sql = "UPDATE $track_exercises
  6134. SET questions_to_check = '$question_id'
  6135. WHERE exe_id = $exe_id ";
  6136. Database::query($sql);
  6137. }
  6138. } else {
  6139. $remind_list = explode(',', $exercise_info['questions_to_check']);
  6140. $remind_list_string = '';
  6141. if ($action == 'add') {
  6142. if (!in_array($question_id, $remind_list)) {
  6143. $remind_list[] = $question_id;
  6144. if (!empty($remind_list)) {
  6145. sort($remind_list);
  6146. array_filter($remind_list);
  6147. }
  6148. $remind_list_string = implode(',', $remind_list);
  6149. }
  6150. } elseif ($action == 'delete') {
  6151. if (!empty($remind_list)) {
  6152. if (in_array($question_id, $remind_list)) {
  6153. $remind_list = array_flip($remind_list);
  6154. unset($remind_list[$question_id]);
  6155. $remind_list = array_flip($remind_list);
  6156. if (!empty($remind_list)) {
  6157. sort($remind_list);
  6158. array_filter($remind_list);
  6159. $remind_list_string = implode(',', $remind_list);
  6160. }
  6161. }
  6162. }
  6163. }
  6164. $remind_list_string = Database::escape_string($remind_list_string);
  6165. $sql = "UPDATE $track_exercises
  6166. SET questions_to_check = '$remind_list_string'
  6167. WHERE exe_id = $exe_id ";
  6168. Database::query($sql);
  6169. }
  6170. }
  6171. }
  6172. /**
  6173. * @param string $answer
  6174. * @return mixed
  6175. */
  6176. public function fill_in_blank_answer_to_array($answer)
  6177. {
  6178. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  6179. $teacher_answer_list = $teacher_answer_list[0];
  6180. return $teacher_answer_list;
  6181. }
  6182. public function fill_in_blank_answer_to_string($answer)
  6183. {
  6184. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  6185. $result = '';
  6186. if (!empty($teacher_answer_list)) {
  6187. $i = 0;
  6188. foreach ($teacher_answer_list as $teacher_item) {
  6189. $value = null;
  6190. //Cleaning student answer list
  6191. $value = strip_tags($teacher_item);
  6192. $value = api_substr($value, 1, api_strlen($value) - 2);
  6193. $value = explode('/', $value);
  6194. if (!empty($value[0])) {
  6195. $value = trim($value[0]);
  6196. $value = str_replace('&nbsp;', '', $value);
  6197. $result .= $value;
  6198. }
  6199. }
  6200. }
  6201. return $result;
  6202. }
  6203. /**
  6204. * @return string
  6205. */
  6206. public function return_time_left_div()
  6207. {
  6208. $html = '<div id="clock_warning" style="display:none">';
  6209. $html .= Display::return_message(
  6210. get_lang('ReachedTimeLimit'),
  6211. 'warning'
  6212. );
  6213. $html .= ' ';
  6214. $html .= sprintf(
  6215. get_lang('YouWillBeRedirectedInXSeconds'),
  6216. '<span id="counter_to_redirect" class="red_alert"></span>'
  6217. );
  6218. $html .= '</div>';
  6219. $html .= '<div id="exercise_clock_warning" class="count_down"></div>';
  6220. return $html;
  6221. }
  6222. public function get_count_question_list()
  6223. {
  6224. //Real question count
  6225. $question_count = 0;
  6226. $question_list = $this->get_question_list();
  6227. if (!empty($question_list)) {
  6228. $question_count = count($question_list);
  6229. }
  6230. return $question_count;
  6231. }
  6232. /**
  6233. * Get categories added in the exercise--category matrix
  6234. * @return array
  6235. */
  6236. public function get_categories_in_exercise()
  6237. {
  6238. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6239. if (!empty($this->id)) {
  6240. $sql = "SELECT * FROM $table
  6241. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  6242. $result = Database::query($sql);
  6243. $list = array();
  6244. if (Database::num_rows($result)) {
  6245. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6246. $list[$row['category_id']] = $row;
  6247. }
  6248. return $list;
  6249. }
  6250. }
  6251. return [];
  6252. }
  6253. /**
  6254. * Get total number of question that will be parsed when using the category/exercise
  6255. * @return int
  6256. */
  6257. public function getNumberQuestionExerciseCategory()
  6258. {
  6259. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6260. if (!empty($this->id)) {
  6261. $sql = "SELECT SUM(count_questions) count_questions
  6262. FROM $table
  6263. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6264. $result = Database::query($sql);
  6265. if (Database::num_rows($result)) {
  6266. $row = Database::fetch_array($result);
  6267. return $row['count_questions'];
  6268. }
  6269. }
  6270. return 0;
  6271. }
  6272. /**
  6273. * Save categories in the TABLE_QUIZ_REL_CATEGORY table
  6274. * @param array $categories
  6275. */
  6276. public function save_categories_in_exercise($categories)
  6277. {
  6278. if (!empty($categories) && !empty($this->id)) {
  6279. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6280. $sql = "DELETE FROM $table
  6281. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6282. Database::query($sql);
  6283. if (!empty($categories)) {
  6284. foreach ($categories as $category_id => $count_questions) {
  6285. $params = array(
  6286. 'c_id' => $this->course_id,
  6287. 'exercise_id' => $this->id,
  6288. 'category_id' => $category_id,
  6289. 'count_questions' => $count_questions
  6290. );
  6291. Database::insert($table, $params);
  6292. }
  6293. }
  6294. }
  6295. }
  6296. /**
  6297. * @param array $questionList
  6298. * @param int $currentQuestion
  6299. * @param array $conditions
  6300. * @param string $link
  6301. * @return string
  6302. */
  6303. public function progressExercisePaginationBar(
  6304. $questionList,
  6305. $currentQuestion,
  6306. $conditions,
  6307. $link
  6308. ) {
  6309. $mediaQuestions = $this->getMediaList();
  6310. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  6311. $counter = 0;
  6312. $nextValue = 0;
  6313. $wasMedia = false;
  6314. $before = 0;
  6315. $counterNoMedias = 0;
  6316. foreach ($questionList as $questionId) {
  6317. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  6318. if (!empty($nextValue)) {
  6319. if ($wasMedia) {
  6320. $nextValue = $nextValue - $before + 1;
  6321. }
  6322. }
  6323. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  6324. $fixedValue = $counterNoMedias;
  6325. $html .= Display::progressPaginationBar(
  6326. $nextValue,
  6327. $mediaQuestions[$questionId],
  6328. $currentQuestion,
  6329. $fixedValue,
  6330. $conditions,
  6331. $link,
  6332. true,
  6333. true
  6334. );
  6335. $counter += count($mediaQuestions[$questionId]) - 1;
  6336. $before = count($questionList);
  6337. $wasMedia = true;
  6338. $nextValue += count($questionList);
  6339. } else {
  6340. $html .= Display::parsePaginationItem(
  6341. $questionId,
  6342. $isCurrent,
  6343. $conditions,
  6344. $link,
  6345. $counter
  6346. );
  6347. $counter++;
  6348. $nextValue++;
  6349. $wasMedia = false;
  6350. }
  6351. $counterNoMedias++;
  6352. }
  6353. $html .= '</ul></div>';
  6354. return $html;
  6355. }
  6356. /**
  6357. * Shows a list of numbers that represents the question to answer in a exercise
  6358. *
  6359. * @param array $categories
  6360. * @param int $current
  6361. * @param array $conditions
  6362. * @param string $link
  6363. * @return string
  6364. */
  6365. public function progressExercisePaginationBarWithCategories(
  6366. $categories,
  6367. $current,
  6368. $conditions = array(),
  6369. $link = null
  6370. ) {
  6371. $html = null;
  6372. $counterNoMedias = 0;
  6373. $nextValue = 0;
  6374. $wasMedia = false;
  6375. $before = 0;
  6376. if (!empty($categories)) {
  6377. $selectionType = $this->getQuestionSelectionType();
  6378. $useRootAsCategoryTitle = false;
  6379. // Grouping questions per parent category see BT#6540
  6380. if (in_array(
  6381. $selectionType,
  6382. array(
  6383. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
  6384. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM
  6385. )
  6386. )) {
  6387. $useRootAsCategoryTitle = true;
  6388. }
  6389. // If the exercise is set to only show the titles of the categories
  6390. // at the root of the tree, then pre-order the categories tree by
  6391. // removing children and summing their questions into the parent
  6392. // categories
  6393. if ($useRootAsCategoryTitle) {
  6394. // The new categories list starts empty
  6395. $newCategoryList = array();
  6396. foreach ($categories as $category) {
  6397. $rootElement = $category['root'];
  6398. if (isset($category['parent_info'])) {
  6399. $rootElement = $category['parent_info']['id'];
  6400. }
  6401. //$rootElement = $category['id'];
  6402. // If the current category's ancestor was never seen
  6403. // before, then declare it and assign the current
  6404. // category to it.
  6405. if (!isset($newCategoryList[$rootElement])) {
  6406. $newCategoryList[$rootElement] = $category;
  6407. } else {
  6408. // If it was already seen, then merge the previous with
  6409. // the current category
  6410. $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
  6411. $category['question_list'] = array_merge($oldQuestionList, $category['question_list']);
  6412. $newCategoryList[$rootElement] = $category;
  6413. }
  6414. }
  6415. // Now use the newly built categories list, with only parents
  6416. $categories = $newCategoryList;
  6417. }
  6418. foreach ($categories as $category) {
  6419. $questionList = $category['question_list'];
  6420. // Check if in this category there questions added in a media
  6421. $mediaQuestionId = $category['media_question'];
  6422. $isMedia = false;
  6423. $fixedValue = null;
  6424. // Media exists!
  6425. if ($mediaQuestionId != 999) {
  6426. $isMedia = true;
  6427. $fixedValue = $counterNoMedias;
  6428. }
  6429. //$categoryName = $category['path']; << show the path
  6430. $categoryName = $category['name'];
  6431. if ($useRootAsCategoryTitle) {
  6432. if (isset($category['parent_info'])) {
  6433. $categoryName = $category['parent_info']['title'];
  6434. }
  6435. }
  6436. $html .= '<div class="row">';
  6437. $html .= '<div class="span2">'.$categoryName.'</div>';
  6438. $html .= '<div class="span8">';
  6439. if (!empty($nextValue)) {
  6440. if ($wasMedia) {
  6441. $nextValue = $nextValue - $before + 1;
  6442. }
  6443. }
  6444. $html .= Display::progressPaginationBar(
  6445. $nextValue,
  6446. $questionList,
  6447. $current,
  6448. $fixedValue,
  6449. $conditions,
  6450. $link,
  6451. $isMedia,
  6452. true
  6453. );
  6454. $html .= '</div>';
  6455. $html .= '</div>';
  6456. if ($mediaQuestionId == 999) {
  6457. $counterNoMedias += count($questionList);
  6458. } else {
  6459. $counterNoMedias++;
  6460. }
  6461. $nextValue += count($questionList);
  6462. $before = count($questionList);
  6463. if ($mediaQuestionId != 999) {
  6464. $wasMedia = true;
  6465. } else {
  6466. $wasMedia = false;
  6467. }
  6468. }
  6469. }
  6470. return $html;
  6471. }
  6472. /**
  6473. * Renders a question list
  6474. *
  6475. * @param array $questionList (with media questions compressed)
  6476. * @param int $currentQuestion
  6477. * @param array $exerciseResult
  6478. * @param array $attemptList
  6479. * @param array $remindList
  6480. */
  6481. public function renderQuestionList(
  6482. $questionList,
  6483. $currentQuestion,
  6484. $exerciseResult,
  6485. $attemptList,
  6486. $remindList
  6487. ) {
  6488. $mediaQuestions = $this->getMediaList();
  6489. $i = 0;
  6490. // Normal question list render (medias compressed)
  6491. foreach ($questionList as $questionId) {
  6492. $i++;
  6493. // For sequential exercises
  6494. if ($this->type == ONE_PER_PAGE) {
  6495. // If it is not the right question, goes to the next loop iteration
  6496. if ($currentQuestion != $i) {
  6497. continue;
  6498. } else {
  6499. if ($this->feedback_type != EXERCISE_FEEDBACK_TYPE_DIRECT) {
  6500. // if the user has already answered this question
  6501. if (isset($exerciseResult[$questionId])) {
  6502. echo Display::return_message(
  6503. get_lang('AlreadyAnswered'),
  6504. 'normal'
  6505. );
  6506. break;
  6507. }
  6508. }
  6509. }
  6510. }
  6511. // The $questionList contains the media id we check
  6512. // if this questionId is a media question type
  6513. if (isset($mediaQuestions[$questionId]) &&
  6514. $mediaQuestions[$questionId] != 999
  6515. ) {
  6516. // The question belongs to a media
  6517. $mediaQuestionList = $mediaQuestions[$questionId];
  6518. $objQuestionTmp = Question::read($questionId);
  6519. $counter = 1;
  6520. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  6521. echo $objQuestionTmp->show_media_content();
  6522. $countQuestionsInsideMedia = count($mediaQuestionList);
  6523. // Show questions that belongs to a media
  6524. if (!empty($mediaQuestionList)) {
  6525. // In order to parse media questions we use letters a, b, c, etc.
  6526. $letterCounter = 97;
  6527. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  6528. $isLastQuestionInMedia = false;
  6529. if ($counter == $countQuestionsInsideMedia) {
  6530. $isLastQuestionInMedia = true;
  6531. }
  6532. $this->renderQuestion(
  6533. $questionIdInsideMedia,
  6534. $attemptList,
  6535. $remindList,
  6536. chr($letterCounter),
  6537. $currentQuestion,
  6538. $mediaQuestionList,
  6539. $isLastQuestionInMedia,
  6540. $questionList
  6541. );
  6542. $letterCounter++;
  6543. $counter++;
  6544. }
  6545. }
  6546. } else {
  6547. $this->renderQuestion(
  6548. $questionId,
  6549. $attemptList,
  6550. $remindList,
  6551. $i,
  6552. $currentQuestion,
  6553. null,
  6554. null,
  6555. $questionList
  6556. );
  6557. $i++;
  6558. }
  6559. } else {
  6560. // Normal question render.
  6561. $this->renderQuestion(
  6562. $questionId,
  6563. $attemptList,
  6564. $remindList,
  6565. $i,
  6566. $currentQuestion,
  6567. null,
  6568. null,
  6569. $questionList
  6570. );
  6571. }
  6572. // For sequential exercises.
  6573. if ($this->type == ONE_PER_PAGE) {
  6574. // quits the loop
  6575. break;
  6576. }
  6577. }
  6578. // end foreach()
  6579. if ($this->type == ALL_ON_ONE_PAGE) {
  6580. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  6581. echo Display::div($exercise_actions, ['class' => 'exercise_actions']);
  6582. }
  6583. }
  6584. /**
  6585. * @param int $questionId
  6586. * @param array $attemptList
  6587. * @param array $remindList
  6588. * @param int $i
  6589. * @param int $current_question
  6590. * @param array $questions_in_media
  6591. * @param bool $last_question_in_media
  6592. * @param array $realQuestionList
  6593. * @param bool $generateJS
  6594. * @return null
  6595. */
  6596. public function renderQuestion(
  6597. $questionId,
  6598. $attemptList,
  6599. $remindList,
  6600. $i,
  6601. $current_question,
  6602. $questions_in_media = array(),
  6603. $last_question_in_media = false,
  6604. $realQuestionList,
  6605. $generateJS = true
  6606. ) {
  6607. // With this option on the question is loaded via AJAX
  6608. //$generateJS = true;
  6609. //$this->loadQuestionAJAX = true;
  6610. if ($generateJS && $this->loadQuestionAJAX) {
  6611. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId.'&'.api_get_cidreq();
  6612. $params = array(
  6613. 'questionId' => $questionId,
  6614. 'attemptList'=> $attemptList,
  6615. 'remindList' => $remindList,
  6616. 'i' => $i,
  6617. 'current_question' => $current_question,
  6618. 'questions_in_media' => $questions_in_media,
  6619. 'last_question_in_media' => $last_question_in_media
  6620. );
  6621. $params = json_encode($params);
  6622. $script = '<script>
  6623. $(function(){
  6624. var params = '.$params.';
  6625. $.ajax({
  6626. type: "GET",
  6627. async: false,
  6628. data: params,
  6629. url: "'.$url.'",
  6630. success: function(return_value) {
  6631. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  6632. }
  6633. });
  6634. });
  6635. </script>
  6636. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  6637. echo $script;
  6638. } else {
  6639. global $origin;
  6640. $question_obj = Question::read($questionId);
  6641. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  6642. $remind_highlight = null;
  6643. //Hides questions when reviewing a ALL_ON_ONE_PAGE exercise see #4542 no_remind_highlight class hide with jquery
  6644. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  6645. $remind_highlight = 'no_remind_highlight';
  6646. if (in_array($question_obj->type, Question::question_type_no_review())) {
  6647. return null;
  6648. }
  6649. }
  6650. $attributes = array('id' =>'remind_list['.$questionId.']');
  6651. if (is_array($remindList) && in_array($questionId, $remindList)) {
  6652. //$attributes['checked'] = 1;
  6653. //$remind_highlight = ' remind_highlight ';
  6654. }
  6655. // Showing the question
  6656. $exercise_actions = null;
  6657. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  6658. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  6659. // Shows the question + possible answers
  6660. $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
  6661. echo $this->showQuestion(
  6662. $question_obj,
  6663. false,
  6664. $origin,
  6665. $i,
  6666. $showTitle,
  6667. false,
  6668. $user_choice,
  6669. false,
  6670. null,
  6671. false,
  6672. $this->getModelType(),
  6673. $this->categoryMinusOne
  6674. );
  6675. // Button save and continue
  6676. switch ($this->type) {
  6677. case ONE_PER_PAGE:
  6678. $exercise_actions .= $this->show_button(
  6679. $questionId,
  6680. $current_question,
  6681. null,
  6682. $remindList
  6683. );
  6684. break;
  6685. case ALL_ON_ONE_PAGE:
  6686. $button = [
  6687. Display::button(
  6688. 'save_now',
  6689. get_lang('SaveForNow'),
  6690. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6691. ),
  6692. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>'
  6693. ];
  6694. $exercise_actions .= Display::div(
  6695. implode(PHP_EOL, $button),
  6696. array('class'=>'exercise_save_now_button')
  6697. );
  6698. break;
  6699. }
  6700. if (!empty($questions_in_media)) {
  6701. $count_of_questions_inside_media = count($questions_in_media);
  6702. if ($count_of_questions_inside_media > 1) {
  6703. $button = [
  6704. Display::button(
  6705. 'save_now',
  6706. get_lang('SaveForNow'),
  6707. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6708. ),
  6709. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;'
  6710. ];
  6711. $exercise_actions = Display::div(
  6712. implode(PHP_EOL, $button),
  6713. array('class'=>'exercise_save_now_button')
  6714. );
  6715. }
  6716. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  6717. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  6718. }
  6719. }
  6720. // Checkbox review answers
  6721. if ($this->review_answers &&
  6722. !in_array($question_obj->type, Question::question_type_no_review())
  6723. ) {
  6724. $remind_question_div = Display::tag(
  6725. 'label',
  6726. Display::input(
  6727. 'checkbox',
  6728. 'remind_list['.$questionId.']',
  6729. '',
  6730. $attributes
  6731. ).get_lang('ReviewQuestionLater'),
  6732. array(
  6733. 'class' => 'checkbox',
  6734. 'for' => 'remind_list['.$questionId.']'
  6735. )
  6736. );
  6737. $exercise_actions .= Display::div(
  6738. $remind_question_div,
  6739. array('class' => 'exercise_save_now_button')
  6740. );
  6741. }
  6742. echo Display::div(' ', array('class'=>'clear'));
  6743. $paginationCounter = null;
  6744. if ($this->type == ONE_PER_PAGE) {
  6745. if (empty($questions_in_media)) {
  6746. $paginationCounter = Display::paginationIndicator(
  6747. $current_question,
  6748. count($realQuestionList)
  6749. );
  6750. } else {
  6751. if ($last_question_in_media) {
  6752. $paginationCounter = Display::paginationIndicator(
  6753. $current_question,
  6754. count($realQuestionList)
  6755. );
  6756. }
  6757. }
  6758. }
  6759. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  6760. echo Display::div($exercise_actions, array('class'=>'form-actions'));
  6761. echo '</div>';
  6762. }
  6763. }
  6764. /**
  6765. * Returns an array of categories details for the questions of the current
  6766. * exercise.
  6767. * @return array
  6768. */
  6769. public function getQuestionWithCategories()
  6770. {
  6771. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  6772. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  6773. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  6774. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  6775. $sql = "SELECT DISTINCT cat.*
  6776. FROM $TBL_EXERCICE_QUESTION e
  6777. INNER JOIN $TBL_QUESTIONS q
  6778. ON (e.question_id = q.id AND e.c_id = q.c_id)
  6779. INNER JOIN $categoryRelTable catRel
  6780. ON (catRel.question_id = e.question_id)
  6781. INNER JOIN $categoryTable cat
  6782. ON (cat.id = catRel.category_id)
  6783. WHERE
  6784. e.c_id = {$this->course_id} AND
  6785. e.exercice_id = ".intval($this->id);
  6786. $result = Database::query($sql);
  6787. $categoriesInExercise = array();
  6788. if (Database::num_rows($result)) {
  6789. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  6790. }
  6791. return $categoriesInExercise;
  6792. }
  6793. /**
  6794. * Calculate the max_score of the quiz, depending of question inside, and quiz advanced option
  6795. */
  6796. public function get_max_score()
  6797. {
  6798. $out_max_score = 0;
  6799. // list of question's id !!! the array key start at 1 !!!
  6800. $questionList = $this->selectQuestionList(true);
  6801. // test is randomQuestions - see field random of test
  6802. if ($this->random > 0 && $this->randomByCat == 0) {
  6803. $numberRandomQuestions = $this->random;
  6804. $questionScoreList = array();
  6805. for ($i = 1; $i <= count($questionList); $i++) {
  6806. if (isset($questionList[$i])) {
  6807. $tmpobj_question = Question::read($questionList[$i]);
  6808. if (is_object($tmpobj_question)) {
  6809. $questionScoreList[] = $tmpobj_question->weighting;
  6810. }
  6811. }
  6812. }
  6813. rsort($questionScoreList);
  6814. // add the first $numberRandomQuestions value of score array to get max_score
  6815. for ($i = 0; $i < min($numberRandomQuestions, count($questionScoreList)); $i++) {
  6816. $out_max_score += $questionScoreList[$i];
  6817. }
  6818. } elseif ($this->random > 0 && $this->randomByCat > 0) {
  6819. // test is random by category
  6820. // get the $numberRandomQuestions best score question of each category
  6821. $numberRandomQuestions = $this->random;
  6822. $tab_categories_scores = array();
  6823. for ($i = 1; $i <= count($questionList); $i++) {
  6824. $question_category_id = TestCategory::getCategoryForQuestion($questionList[$i]);
  6825. if (!is_array($tab_categories_scores[$question_category_id])) {
  6826. $tab_categories_scores[$question_category_id] = array();
  6827. }
  6828. $tmpobj_question = Question::read($questionList[$i]);
  6829. $tab_categories_scores[$question_category_id][] = $tmpobj_question->weighting;
  6830. }
  6831. // here we've got an array with first key, the category_id, second key, score of question for this cat
  6832. while (list($key, $tab_scores) = each($tab_categories_scores)) {
  6833. rsort($tab_scores);
  6834. for ($i = 0; $i < min($numberRandomQuestions, count($tab_scores)); $i++) {
  6835. $out_max_score += $tab_scores[$i];
  6836. }
  6837. }
  6838. } else {
  6839. // standard test, just add each question score
  6840. foreach ($questionList as $questionId) {
  6841. $question = Question::read($questionId, $this->course_id);
  6842. $out_max_score += $question->weighting;
  6843. }
  6844. }
  6845. return $out_max_score;
  6846. }
  6847. /**
  6848. * @return string
  6849. */
  6850. public function get_formated_title()
  6851. {
  6852. if (api_get_configuration_value('save_titles_as_html')) {
  6853. }
  6854. return api_html_entity_decode($this->selectTitle());
  6855. }
  6856. /**
  6857. * @param $in_title
  6858. * @return string
  6859. */
  6860. public static function get_formated_title_variable($in_title)
  6861. {
  6862. return api_html_entity_decode($in_title);
  6863. }
  6864. /**
  6865. * @return string
  6866. */
  6867. public function format_title()
  6868. {
  6869. return api_htmlentities($this->title);
  6870. }
  6871. /**
  6872. * @param $in_title
  6873. * @return string
  6874. */
  6875. public static function format_title_variable($in_title)
  6876. {
  6877. return api_htmlentities($in_title);
  6878. }
  6879. /**
  6880. * @param int $courseId
  6881. * @param int $sessionId
  6882. * @return array exercises
  6883. */
  6884. public function getExercisesByCourseSession($courseId, $sessionId)
  6885. {
  6886. $courseId = intval($courseId);
  6887. $sessionId = intval($sessionId);
  6888. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6889. $sql = "SELECT * FROM $tbl_quiz cq
  6890. WHERE
  6891. cq.c_id = %s AND
  6892. (cq.session_id = %s OR cq.session_id = 0) AND
  6893. cq.active = 0
  6894. ORDER BY cq.id";
  6895. $sql = sprintf($sql, $courseId, $sessionId);
  6896. $result = Database::query($sql);
  6897. $rows = array();
  6898. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6899. $rows[] = $row;
  6900. }
  6901. return $rows;
  6902. }
  6903. /**
  6904. *
  6905. * @param int $courseId
  6906. * @param int $sessionId
  6907. * @param array $quizId
  6908. * @return array exercises
  6909. */
  6910. public function getExerciseAndResult($courseId, $sessionId, $quizId = array())
  6911. {
  6912. if (empty($quizId)) {
  6913. return array();
  6914. }
  6915. $sessionId = intval($sessionId);
  6916. $ids = is_array($quizId) ? $quizId : array($quizId);
  6917. $ids = array_map('intval', $ids);
  6918. $ids = implode(',', $ids);
  6919. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6920. if ($sessionId != 0) {
  6921. $sql = "SELECT * FROM $track_exercises te
  6922. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  6923. WHERE
  6924. te.id = %s AND
  6925. te.session_id = %s AND
  6926. cq.id IN (%s)
  6927. ORDER BY cq.id";
  6928. $sql = sprintf($sql, $courseId, $sessionId, $ids);
  6929. } else {
  6930. $sql = "SELECT * FROM $track_exercises te
  6931. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  6932. WHERE
  6933. te.id = %s AND
  6934. cq.id IN (%s)
  6935. ORDER BY cq.id";
  6936. $sql = sprintf($sql, $courseId, $ids);
  6937. }
  6938. $result = Database::query($sql);
  6939. $rows = array();
  6940. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6941. $rows[] = $row;
  6942. }
  6943. return $rows;
  6944. }
  6945. /**
  6946. * @param $exeId
  6947. * @param $exercise_stat_info
  6948. * @param $remindList
  6949. * @param $currentQuestion
  6950. * @return int|null
  6951. */
  6952. public static function getNextQuestionId(
  6953. $exeId,
  6954. $exercise_stat_info,
  6955. $remindList,
  6956. $currentQuestion
  6957. ) {
  6958. $result = Event::get_exercise_results_by_attempt($exeId, 'incomplete');
  6959. if (isset($result[$exeId])) {
  6960. $result = $result[$exeId];
  6961. } else {
  6962. return null;
  6963. }
  6964. $data_tracking = $exercise_stat_info['data_tracking'];
  6965. $data_tracking = explode(',', $data_tracking);
  6966. // if this is the final question do nothing.
  6967. if ($currentQuestion == count($data_tracking)) {
  6968. return null;
  6969. }
  6970. $currentQuestion = $currentQuestion - 1;
  6971. if (!empty($result['question_list'])) {
  6972. $answeredQuestions = array();
  6973. foreach ($result['question_list'] as $question) {
  6974. if (!empty($question['answer'])) {
  6975. $answeredQuestions[] = $question['question_id'];
  6976. }
  6977. }
  6978. // Checking answered questions
  6979. $counterAnsweredQuestions = 0;
  6980. foreach ($data_tracking as $questionId) {
  6981. if (!in_array($questionId, $answeredQuestions)) {
  6982. if ($currentQuestion != $counterAnsweredQuestions) {
  6983. break;
  6984. }
  6985. }
  6986. $counterAnsweredQuestions++;
  6987. }
  6988. $counterRemindListQuestions = 0;
  6989. // Checking questions saved in the reminder list
  6990. if (!empty($remindList)) {
  6991. foreach ($data_tracking as $questionId) {
  6992. if (in_array($questionId, $remindList)) {
  6993. // Skip the current question
  6994. if ($currentQuestion != $counterRemindListQuestions) {
  6995. break;
  6996. }
  6997. }
  6998. $counterRemindListQuestions++;
  6999. }
  7000. if ($counterRemindListQuestions < $currentQuestion) {
  7001. return null;
  7002. }
  7003. if (!empty($counterRemindListQuestions)) {
  7004. if ($counterRemindListQuestions > $counterAnsweredQuestions) {
  7005. return $counterAnsweredQuestions;
  7006. } else {
  7007. return $counterRemindListQuestions;
  7008. }
  7009. }
  7010. }
  7011. return $counterAnsweredQuestions;
  7012. }
  7013. }
  7014. /**
  7015. * Gets the position of a questionId in the question list
  7016. * @param $questionId
  7017. * @return int
  7018. */
  7019. public function getPositionInCompressedQuestionList($questionId)
  7020. {
  7021. $questionList = $this->getQuestionListWithMediasCompressed();
  7022. $mediaQuestions = $this->getMediaList();
  7023. $position = 1;
  7024. foreach ($questionList as $id) {
  7025. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  7026. $mediaQuestionList = $mediaQuestions[$id];
  7027. if (in_array($questionId, $mediaQuestionList)) {
  7028. return $position;
  7029. } else {
  7030. $position++;
  7031. }
  7032. } else {
  7033. if ($id == $questionId) {
  7034. return $position;
  7035. } else {
  7036. $position++;
  7037. }
  7038. }
  7039. }
  7040. return 1;
  7041. }
  7042. /**
  7043. * Get the correct answers in all attempts
  7044. * @param int $learnPathId
  7045. * @param int $learnPathItemId
  7046. * @return array
  7047. */
  7048. public function getCorrectAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0)
  7049. {
  7050. $attempts = Event::getExerciseResultsByUser(
  7051. api_get_user_id(),
  7052. $this->id,
  7053. api_get_course_int_id(),
  7054. api_get_session_id(),
  7055. $learnPathId,
  7056. $learnPathItemId,
  7057. 'asc'
  7058. );
  7059. $corrects = [];
  7060. foreach ($attempts as $attempt) {
  7061. foreach ($attempt['question_list'] as $answers) {
  7062. foreach ($answers as $answer) {
  7063. $objAnswer = new Answer($answer['question_id']);
  7064. switch ($objAnswer->getQuestionType()) {
  7065. case FILL_IN_BLANKS:
  7066. $isCorrect = FillBlanks::isCorrect($answer['answer']);
  7067. break;
  7068. case MATCHING:
  7069. //no break
  7070. case DRAGGABLE:
  7071. //no break
  7072. case MATCHING_DRAGGABLE:
  7073. $isCorrect = Matching::isCorrect(
  7074. $answer['position'],
  7075. $answer['answer'],
  7076. $answer['question_id']
  7077. );
  7078. break;
  7079. default:
  7080. $isCorrect = $objAnswer->isCorrectByAutoId($answer['answer']);
  7081. }
  7082. if ($isCorrect) {
  7083. $corrects[$answer['question_id']][] = $answer;
  7084. }
  7085. }
  7086. }
  7087. }
  7088. return $corrects;
  7089. }
  7090. /**
  7091. * Get the title without HTML tags
  7092. * @return string
  7093. */
  7094. private function getUnformattedTitle()
  7095. {
  7096. return strip_tags(api_html_entity_decode($this->title));
  7097. }
  7098. /**
  7099. * @return bool
  7100. */
  7101. public function showPreviousButton()
  7102. {
  7103. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  7104. if ($allow === false) {
  7105. return true;
  7106. }
  7107. return $this->showPreviousButton;
  7108. }
  7109. /**
  7110. * @param bool $showPreviousButton
  7111. * @return Exercise
  7112. */
  7113. public function setShowPreviousButton($showPreviousButton)
  7114. {
  7115. $this->showPreviousButton = $showPreviousButton;
  7116. return $this;
  7117. }
  7118. /**
  7119. * @param array $notifications
  7120. */
  7121. public function setNotifications($notifications)
  7122. {
  7123. $this->notifications = $notifications;
  7124. }
  7125. /**
  7126. * @return array
  7127. */
  7128. public function getNotifications()
  7129. {
  7130. return $this->notifications;
  7131. }
  7132. }