exercise.class.php 399 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\GradebookLink;
  4. use Chamilo\CoreBundle\Entity\TrackEHotspot;
  5. use ChamiloSession as Session;
  6. use Doctrine\DBAL\Types\Type;
  7. /**
  8. * Class Exercise.
  9. *
  10. * Allows to instantiate an object of type Exercise
  11. *
  12. * @package chamilo.exercise
  13. *
  14. * @todo use getters and setters correctly
  15. *
  16. * @author Olivier Brouckaert
  17. * @author Julio Montoya Cleaning exercises
  18. * Modified by Hubert Borderiou #294
  19. */
  20. class Exercise
  21. {
  22. public $iId;
  23. public $id;
  24. public $name;
  25. public $title;
  26. public $exercise;
  27. public $description;
  28. public $sound;
  29. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  30. public $random;
  31. public $random_answers;
  32. public $active;
  33. public $timeLimit;
  34. public $attempts;
  35. public $feedback_type;
  36. public $end_time;
  37. public $start_time;
  38. public $questionList; // array with the list of this exercise's questions
  39. /* including question list of the media */
  40. public $questionListUncompressed;
  41. public $results_disabled;
  42. public $expired_time;
  43. public $course;
  44. public $course_id;
  45. public $propagate_neg;
  46. public $saveCorrectAnswers;
  47. public $review_answers;
  48. public $randomByCat;
  49. public $text_when_finished;
  50. public $display_category_name;
  51. public $pass_percentage;
  52. public $edit_exercise_in_lp = false;
  53. public $is_gradebook_locked = false;
  54. public $exercise_was_added_in_lp = false;
  55. public $lpList = [];
  56. public $force_edit_exercise_in_lp = false;
  57. public $categories;
  58. public $categories_grouping = true;
  59. public $endButton = 0;
  60. public $categoryWithQuestionList;
  61. public $mediaList;
  62. public $loadQuestionAJAX = false;
  63. // Notification send to the teacher.
  64. public $emailNotificationTemplate = null;
  65. // Notification send to the student.
  66. public $emailNotificationTemplateToUser = null;
  67. public $countQuestions = 0;
  68. public $fastEdition = false;
  69. public $modelType = 1;
  70. public $questionSelectionType = EX_Q_SELECTION_ORDERED;
  71. public $hideQuestionTitle = 0;
  72. public $scoreTypeModel = 0;
  73. public $categoryMinusOne = true; // Shows the category -1: See BT#6540
  74. public $globalCategoryId = null;
  75. public $onSuccessMessage = null;
  76. public $onFailedMessage = null;
  77. public $emailAlert;
  78. public $notifyUserByEmail = '';
  79. public $sessionId = 0;
  80. public $questionFeedbackEnabled = false;
  81. public $questionTypeWithFeedback;
  82. public $showPreviousButton;
  83. public $notifications;
  84. public $export = false;
  85. public $autolaunch;
  86. public $exerciseCategoryId;
  87. public $pageResultConfiguration;
  88. /**
  89. * Constructor of the class.
  90. *
  91. * @param int $courseId
  92. *
  93. * @author Olivier Brouckaert
  94. */
  95. public function __construct($courseId = 0)
  96. {
  97. $this->iId = 0;
  98. $this->id = 0;
  99. $this->exercise = '';
  100. $this->description = '';
  101. $this->sound = '';
  102. $this->type = ALL_ON_ONE_PAGE;
  103. $this->random = 0;
  104. $this->random_answers = 0;
  105. $this->active = 1;
  106. $this->questionList = [];
  107. $this->timeLimit = 0;
  108. $this->end_time = '';
  109. $this->start_time = '';
  110. $this->results_disabled = 1;
  111. $this->expired_time = 0;
  112. $this->propagate_neg = 0;
  113. $this->saveCorrectAnswers = 0;
  114. $this->review_answers = false;
  115. $this->randomByCat = 0;
  116. $this->text_when_finished = '';
  117. $this->display_category_name = 0;
  118. $this->pass_percentage = 0;
  119. $this->modelType = 1;
  120. $this->questionSelectionType = EX_Q_SELECTION_ORDERED;
  121. $this->endButton = 0;
  122. $this->scoreTypeModel = 0;
  123. $this->globalCategoryId = null;
  124. $this->notifications = [];
  125. $this->exerciseCategoryId = 0;
  126. $this->pageResultConfiguration;
  127. if (!empty($courseId)) {
  128. $courseInfo = api_get_course_info_by_id($courseId);
  129. } else {
  130. $courseInfo = api_get_course_info();
  131. }
  132. $this->course_id = $courseInfo['real_id'];
  133. $this->course = $courseInfo;
  134. $this->sessionId = api_get_session_id();
  135. // ALTER TABLE c_quiz_question ADD COLUMN feedback text;
  136. $this->questionFeedbackEnabled = api_get_configuration_value('allow_quiz_question_feedback');
  137. $this->showPreviousButton = true;
  138. }
  139. /**
  140. * Reads exercise information from the data base.
  141. *
  142. * @author Olivier Brouckaert
  143. *
  144. * @param int $id - exercise Id
  145. * @param bool $parseQuestionList
  146. *
  147. * @return bool - true if exercise exists, otherwise false
  148. */
  149. public function read($id, $parseQuestionList = true)
  150. {
  151. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  152. $tableLpItem = Database::get_course_table(TABLE_LP_ITEM);
  153. $id = (int) $id;
  154. if (empty($this->course_id)) {
  155. return false;
  156. }
  157. $sql = "SELECT * FROM $table
  158. WHERE c_id = ".$this->course_id." AND id = ".$id;
  159. $result = Database::query($sql);
  160. // if the exercise has been found
  161. if ($object = Database::fetch_object($result)) {
  162. $this->iId = $object->iid;
  163. $this->id = $id;
  164. $this->exercise = $object->title;
  165. $this->name = $object->title;
  166. $this->title = $object->title;
  167. $this->description = $object->description;
  168. $this->sound = $object->sound;
  169. $this->type = $object->type;
  170. if (empty($this->type)) {
  171. $this->type = ONE_PER_PAGE;
  172. }
  173. $this->random = $object->random;
  174. $this->random_answers = $object->random_answers;
  175. $this->active = $object->active;
  176. $this->results_disabled = $object->results_disabled;
  177. $this->attempts = $object->max_attempt;
  178. $this->feedback_type = $object->feedback_type;
  179. $this->sessionId = $object->session_id;
  180. $this->propagate_neg = $object->propagate_neg;
  181. $this->saveCorrectAnswers = $object->save_correct_answers;
  182. $this->randomByCat = $object->random_by_category;
  183. $this->text_when_finished = $object->text_when_finished;
  184. $this->display_category_name = $object->display_category_name;
  185. $this->pass_percentage = $object->pass_percentage;
  186. $this->is_gradebook_locked = api_resource_is_locked_by_gradebook($id, LINK_EXERCISE);
  187. $this->review_answers = (isset($object->review_answers) && $object->review_answers == 1) ? true : false;
  188. $this->globalCategoryId = isset($object->global_category_id) ? $object->global_category_id : null;
  189. $this->questionSelectionType = isset($object->question_selection_type) ? $object->question_selection_type : null;
  190. $this->hideQuestionTitle = isset($object->hide_question_title) ? (int) $object->hide_question_title : 0;
  191. $this->autolaunch = isset($object->autolaunch) ? (int) $object->autolaunch : 0;
  192. $this->exerciseCategoryId = isset($object->exercise_category_id) ? (int) $object->exercise_category_id : 0;
  193. $this->notifications = [];
  194. if (!empty($object->notifications)) {
  195. $this->notifications = explode(',', $object->notifications);
  196. }
  197. if (!empty($object->page_result_configuration)) {
  198. $this->pageResultConfiguration = $object->page_result_configuration;
  199. }
  200. if (isset($object->show_previous_button)) {
  201. $this->showPreviousButton = $object->show_previous_button == 1 ? true : false;
  202. }
  203. $sql = "SELECT lp_id, max_score
  204. FROM $tableLpItem
  205. WHERE
  206. c_id = {$this->course_id} AND
  207. item_type = '".TOOL_QUIZ."' AND
  208. path = '".$id."'";
  209. $result = Database::query($sql);
  210. if (Database::num_rows($result) > 0) {
  211. $this->exercise_was_added_in_lp = true;
  212. $this->lpList = Database::store_result($result, 'ASSOC');
  213. }
  214. $this->force_edit_exercise_in_lp = api_get_configuration_value('force_edit_exercise_in_lp');
  215. $this->edit_exercise_in_lp = true;
  216. if ($this->exercise_was_added_in_lp) {
  217. $this->edit_exercise_in_lp = $this->force_edit_exercise_in_lp == true;
  218. }
  219. if (!empty($object->end_time)) {
  220. $this->end_time = $object->end_time;
  221. }
  222. if (!empty($object->start_time)) {
  223. $this->start_time = $object->start_time;
  224. }
  225. // Control time
  226. $this->expired_time = $object->expired_time;
  227. // Checking if question_order is correctly set
  228. if ($parseQuestionList) {
  229. $this->setQuestionList(true);
  230. }
  231. //overload questions list with recorded questions list
  232. //load questions only for exercises of type 'one question per page'
  233. //this is needed only is there is no questions
  234. // @todo not sure were in the code this is used somebody mess with the exercise tool
  235. // @todo don't know who add that config and why $_configuration['live_exercise_tracking']
  236. /*global $_configuration, $questionList;
  237. if ($this->type == ONE_PER_PAGE && $_SERVER['REQUEST_METHOD'] != 'POST'
  238. && defined('QUESTION_LIST_ALREADY_LOGGED') &&
  239. isset($_configuration['live_exercise_tracking']) && $_configuration['live_exercise_tracking']
  240. ) {
  241. $this->questionList = $questionList;
  242. }*/
  243. return true;
  244. }
  245. return false;
  246. }
  247. /**
  248. * @return string
  249. */
  250. public function getCutTitle()
  251. {
  252. $title = $this->getUnformattedTitle();
  253. return cut($title, EXERCISE_MAX_NAME_SIZE);
  254. }
  255. /**
  256. * returns the exercise ID.
  257. *
  258. * @author Olivier Brouckaert
  259. *
  260. * @return int - exercise ID
  261. */
  262. public function selectId()
  263. {
  264. return $this->id;
  265. }
  266. /**
  267. * returns the exercise title.
  268. *
  269. * @author Olivier Brouckaert
  270. *
  271. * @param bool $unformattedText Optional. Get the title without HTML tags
  272. *
  273. * @return string - exercise title
  274. */
  275. public function selectTitle($unformattedText = false)
  276. {
  277. if ($unformattedText) {
  278. return $this->getUnformattedTitle();
  279. }
  280. return $this->exercise;
  281. }
  282. /**
  283. * returns the number of attempts setted.
  284. *
  285. * @return int - exercise attempts
  286. */
  287. public function selectAttempts()
  288. {
  289. return $this->attempts;
  290. }
  291. /**
  292. * Returns the number of FeedbackType
  293. * 0: Feedback , 1: DirectFeedback, 2: NoFeedback.
  294. *
  295. * @return int - exercise attempts
  296. */
  297. public function getFeedbackType()
  298. {
  299. return (int) $this->feedback_type;
  300. }
  301. /**
  302. * returns the time limit.
  303. *
  304. * @return int
  305. */
  306. public function selectTimeLimit()
  307. {
  308. return $this->timeLimit;
  309. }
  310. /**
  311. * returns the exercise description.
  312. *
  313. * @author Olivier Brouckaert
  314. *
  315. * @return string - exercise description
  316. */
  317. public function selectDescription()
  318. {
  319. return $this->description;
  320. }
  321. /**
  322. * returns the exercise sound file.
  323. *
  324. * @author Olivier Brouckaert
  325. *
  326. * @return string - exercise description
  327. */
  328. public function selectSound()
  329. {
  330. return $this->sound;
  331. }
  332. /**
  333. * returns the exercise type.
  334. *
  335. * @author Olivier Brouckaert
  336. *
  337. * @return int - exercise type
  338. */
  339. public function selectType()
  340. {
  341. return $this->type;
  342. }
  343. /**
  344. * @return int
  345. */
  346. public function getModelType()
  347. {
  348. return $this->modelType;
  349. }
  350. /**
  351. * @return int
  352. */
  353. public function selectEndButton()
  354. {
  355. return $this->endButton;
  356. }
  357. /**
  358. * @author hubert borderiou 30-11-11
  359. *
  360. * @return int : do we display the question category name for students
  361. */
  362. public function selectDisplayCategoryName()
  363. {
  364. return $this->display_category_name;
  365. }
  366. /**
  367. * @return int
  368. */
  369. public function selectPassPercentage()
  370. {
  371. return $this->pass_percentage;
  372. }
  373. /**
  374. * Modify object to update the switch display_category_name.
  375. *
  376. * @author hubert borderiou 30-11-11
  377. *
  378. * @param int $value is an integer 0 or 1
  379. */
  380. public function updateDisplayCategoryName($value)
  381. {
  382. $this->display_category_name = $value;
  383. }
  384. /**
  385. * @author hubert borderiou 28-11-11
  386. *
  387. * @return string html text : the text to display ay the end of the test
  388. */
  389. public function getTextWhenFinished()
  390. {
  391. return $this->text_when_finished;
  392. }
  393. /**
  394. * @param string $text
  395. *
  396. * @author hubert borderiou 28-11-11
  397. */
  398. public function updateTextWhenFinished($text)
  399. {
  400. $this->text_when_finished = $text;
  401. }
  402. /**
  403. * return 1 or 2 if randomByCat.
  404. *
  405. * @author hubert borderiou
  406. *
  407. * @return int - quiz random by category
  408. */
  409. public function getRandomByCategory()
  410. {
  411. return $this->randomByCat;
  412. }
  413. /**
  414. * return 0 if no random by cat
  415. * return 1 if random by cat, categories shuffled
  416. * return 2 if random by cat, categories sorted by alphabetic order.
  417. *
  418. * @author hubert borderiou
  419. *
  420. * @return int - quiz random by category
  421. */
  422. public function isRandomByCat()
  423. {
  424. $res = EXERCISE_CATEGORY_RANDOM_DISABLED;
  425. if ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_SHUFFLED) {
  426. $res = EXERCISE_CATEGORY_RANDOM_SHUFFLED;
  427. } elseif ($this->randomByCat == EXERCISE_CATEGORY_RANDOM_ORDERED) {
  428. $res = EXERCISE_CATEGORY_RANDOM_ORDERED;
  429. }
  430. return $res;
  431. }
  432. /**
  433. * return nothing
  434. * update randomByCat value for object.
  435. *
  436. * @param int $random
  437. *
  438. * @author hubert borderiou
  439. */
  440. public function updateRandomByCat($random)
  441. {
  442. $this->randomByCat = EXERCISE_CATEGORY_RANDOM_DISABLED;
  443. if (in_array(
  444. $random,
  445. [
  446. EXERCISE_CATEGORY_RANDOM_SHUFFLED,
  447. EXERCISE_CATEGORY_RANDOM_ORDERED,
  448. EXERCISE_CATEGORY_RANDOM_DISABLED,
  449. ]
  450. )) {
  451. $this->randomByCat = $random;
  452. }
  453. }
  454. /**
  455. * Tells if questions are selected randomly, and if so returns the draws.
  456. *
  457. * @author Carlos Vargas
  458. *
  459. * @return int - results disabled exercise
  460. */
  461. public function selectResultsDisabled()
  462. {
  463. return $this->results_disabled;
  464. }
  465. /**
  466. * tells if questions are selected randomly, and if so returns the draws.
  467. *
  468. * @author Olivier Brouckaert
  469. *
  470. * @return bool
  471. */
  472. public function isRandom()
  473. {
  474. $isRandom = false;
  475. // "-1" means all questions will be random
  476. if ($this->random > 0 || $this->random == -1) {
  477. $isRandom = true;
  478. }
  479. return $isRandom;
  480. }
  481. /**
  482. * returns random answers status.
  483. *
  484. * @author Juan Carlos Rana
  485. */
  486. public function getRandomAnswers()
  487. {
  488. return $this->random_answers;
  489. }
  490. /**
  491. * Same as isRandom() but has a name applied to values different than 0 or 1.
  492. *
  493. * @return int
  494. */
  495. public function getShuffle()
  496. {
  497. return $this->random;
  498. }
  499. /**
  500. * returns the exercise status (1 = enabled ; 0 = disabled).
  501. *
  502. * @author Olivier Brouckaert
  503. *
  504. * @return int - 1 if enabled, otherwise 0
  505. */
  506. public function selectStatus()
  507. {
  508. return $this->active;
  509. }
  510. /**
  511. * If false the question list will be managed as always if true
  512. * the question will be filtered
  513. * depending of the exercise settings (table c_quiz_rel_category).
  514. *
  515. * @param bool $status active or inactive grouping
  516. */
  517. public function setCategoriesGrouping($status)
  518. {
  519. $this->categories_grouping = (bool) $status;
  520. }
  521. /**
  522. * @return int
  523. */
  524. public function getHideQuestionTitle()
  525. {
  526. return $this->hideQuestionTitle;
  527. }
  528. /**
  529. * @param $value
  530. */
  531. public function setHideQuestionTitle($value)
  532. {
  533. $this->hideQuestionTitle = (int) $value;
  534. }
  535. /**
  536. * @return int
  537. */
  538. public function getScoreTypeModel()
  539. {
  540. return $this->scoreTypeModel;
  541. }
  542. /**
  543. * @param int $value
  544. */
  545. public function setScoreTypeModel($value)
  546. {
  547. $this->scoreTypeModel = (int) $value;
  548. }
  549. /**
  550. * @return int
  551. */
  552. public function getGlobalCategoryId()
  553. {
  554. return $this->globalCategoryId;
  555. }
  556. /**
  557. * @param int $value
  558. */
  559. public function setGlobalCategoryId($value)
  560. {
  561. if (is_array($value) && isset($value[0])) {
  562. $value = $value[0];
  563. }
  564. $this->globalCategoryId = (int) $value;
  565. }
  566. /**
  567. * @param int $start
  568. * @param int $limit
  569. * @param int $sidx
  570. * @param string $sord
  571. * @param array $whereCondition
  572. * @param array $extraFields
  573. *
  574. * @return array
  575. */
  576. public function getQuestionListPagination(
  577. $start,
  578. $limit,
  579. $sidx,
  580. $sord,
  581. $whereCondition = [],
  582. $extraFields = []
  583. ) {
  584. if (!empty($this->id)) {
  585. $category_list = TestCategory::getListOfCategoriesNameForTest(
  586. $this->id,
  587. false
  588. );
  589. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  590. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  591. $sql = "SELECT q.iid
  592. FROM $TBL_EXERCICE_QUESTION e
  593. INNER JOIN $TBL_QUESTIONS q
  594. ON (e.question_id = q.id AND e.c_id = ".$this->course_id." )
  595. WHERE e.exercice_id = '".$this->id."' ";
  596. $orderCondition = ' ORDER BY question_order ';
  597. if (!empty($sidx) && !empty($sord)) {
  598. if ($sidx === 'question') {
  599. if (in_array(strtolower($sord), ['desc', 'asc'])) {
  600. $orderCondition = " ORDER BY q.$sidx $sord";
  601. }
  602. }
  603. }
  604. $sql .= $orderCondition;
  605. $limitCondition = null;
  606. if (isset($start) && isset($limit)) {
  607. $start = (int) $start;
  608. $limit = (int) $limit;
  609. $limitCondition = " LIMIT $start, $limit";
  610. }
  611. $sql .= $limitCondition;
  612. $result = Database::query($sql);
  613. $questions = [];
  614. if (Database::num_rows($result)) {
  615. if (!empty($extraFields)) {
  616. $extraFieldValue = new ExtraFieldValue('question');
  617. }
  618. while ($question = Database::fetch_array($result, 'ASSOC')) {
  619. /** @var Question $objQuestionTmp */
  620. $objQuestionTmp = Question::read($question['iid']);
  621. $category_labels = TestCategory::return_category_labels(
  622. $objQuestionTmp->category_list,
  623. $category_list
  624. );
  625. if (empty($category_labels)) {
  626. $category_labels = '-';
  627. }
  628. // Question type
  629. list($typeImg, $typeExpl) = $objQuestionTmp->get_type_icon_html();
  630. $question_media = null;
  631. if (!empty($objQuestionTmp->parent_id)) {
  632. $objQuestionMedia = Question::read($objQuestionTmp->parent_id);
  633. $question_media = Question::getMediaLabel($objQuestionMedia->question);
  634. }
  635. $questionType = Display::tag(
  636. 'div',
  637. Display::return_icon($typeImg, $typeExpl, [], ICON_SIZE_MEDIUM).$question_media
  638. );
  639. $question = [
  640. 'id' => $question['iid'],
  641. 'question' => $objQuestionTmp->selectTitle(),
  642. 'type' => $questionType,
  643. 'category' => Display::tag(
  644. 'div',
  645. '<a href="#" style="padding:0px; margin:0px;">'.$category_labels.'</a>'
  646. ),
  647. 'score' => $objQuestionTmp->selectWeighting(),
  648. 'level' => $objQuestionTmp->level,
  649. ];
  650. if (!empty($extraFields)) {
  651. foreach ($extraFields as $extraField) {
  652. $value = $extraFieldValue->get_values_by_handler_and_field_id(
  653. $question['id'],
  654. $extraField['id']
  655. );
  656. $stringValue = null;
  657. if ($value) {
  658. $stringValue = $value['field_value'];
  659. }
  660. $question[$extraField['field_variable']] = $stringValue;
  661. }
  662. }
  663. $questions[] = $question;
  664. }
  665. }
  666. return $questions;
  667. }
  668. }
  669. /**
  670. * Get question count per exercise from DB (any special treatment).
  671. *
  672. * @return int
  673. */
  674. public function getQuestionCount()
  675. {
  676. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  677. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  678. $sql = "SELECT count(q.id) as count
  679. FROM $TBL_EXERCICE_QUESTION e
  680. INNER JOIN $TBL_QUESTIONS q
  681. ON (e.question_id = q.id AND e.c_id = q.c_id)
  682. WHERE
  683. e.c_id = {$this->course_id} AND
  684. e.exercice_id = ".$this->id;
  685. $result = Database::query($sql);
  686. $count = 0;
  687. if (Database::num_rows($result)) {
  688. $row = Database::fetch_array($result);
  689. $count = (int) $row['count'];
  690. }
  691. return $count;
  692. }
  693. /**
  694. * @return array
  695. */
  696. public function getQuestionOrderedListByName()
  697. {
  698. if (empty($this->course_id) || empty($this->id)) {
  699. return [];
  700. }
  701. $exerciseQuestionTable = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  702. $questionTable = Database::get_course_table(TABLE_QUIZ_QUESTION);
  703. // Getting question list from the order (question list drag n drop interface ).
  704. $sql = "SELECT e.question_id
  705. FROM $exerciseQuestionTable e
  706. INNER JOIN $questionTable q
  707. ON (e.question_id= q.id AND e.c_id = q.c_id)
  708. WHERE
  709. e.c_id = {$this->course_id} AND
  710. e.exercice_id = '".$this->id."'
  711. ORDER BY q.question";
  712. $result = Database::query($sql);
  713. $list = [];
  714. if (Database::num_rows($result)) {
  715. $list = Database::store_result($result, 'ASSOC');
  716. }
  717. return $list;
  718. }
  719. /**
  720. * Selecting question list depending in the exercise-category
  721. * relationship (category table in exercise settings).
  722. *
  723. * @param array $question_list
  724. * @param int $questionSelectionType
  725. *
  726. * @return array
  727. */
  728. public function getQuestionListWithCategoryListFilteredByCategorySettings(
  729. $question_list,
  730. $questionSelectionType
  731. ) {
  732. $result = [
  733. 'question_list' => [],
  734. 'category_with_questions_list' => [],
  735. ];
  736. // Order/random categories
  737. $cat = new TestCategory();
  738. // Setting category order.
  739. switch ($questionSelectionType) {
  740. case EX_Q_SELECTION_ORDERED: // 1
  741. case EX_Q_SELECTION_RANDOM: // 2
  742. // This options are not allowed here.
  743. break;
  744. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED: // 3
  745. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  746. $this,
  747. $this->course['real_id'],
  748. 'title ASC',
  749. false,
  750. true
  751. );
  752. $questions_by_category = TestCategory::getQuestionsByCat(
  753. $this->id,
  754. $question_list,
  755. $categoriesAddedInExercise
  756. );
  757. $question_list = $this->pickQuestionsPerCategory(
  758. $categoriesAddedInExercise,
  759. $question_list,
  760. $questions_by_category,
  761. true,
  762. false
  763. );
  764. break;
  765. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED: // 4
  766. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  767. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  768. $this,
  769. $this->course['real_id'],
  770. null,
  771. true,
  772. true
  773. );
  774. $questions_by_category = TestCategory::getQuestionsByCat(
  775. $this->id,
  776. $question_list,
  777. $categoriesAddedInExercise
  778. );
  779. $question_list = $this->pickQuestionsPerCategory(
  780. $categoriesAddedInExercise,
  781. $question_list,
  782. $questions_by_category,
  783. true,
  784. false
  785. );
  786. break;
  787. case EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM: // 5
  788. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  789. $this,
  790. $this->course['real_id'],
  791. 'title ASC',
  792. false,
  793. true
  794. );
  795. $questions_by_category = TestCategory::getQuestionsByCat(
  796. $this->id,
  797. $question_list,
  798. $categoriesAddedInExercise
  799. );
  800. $question_list = $this->pickQuestionsPerCategory(
  801. $categoriesAddedInExercise,
  802. $question_list,
  803. $questions_by_category,
  804. true,
  805. true
  806. );
  807. break;
  808. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM: // 6
  809. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED:
  810. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  811. $this,
  812. $this->course['real_id'],
  813. null,
  814. true,
  815. true
  816. );
  817. $questions_by_category = TestCategory::getQuestionsByCat(
  818. $this->id,
  819. $question_list,
  820. $categoriesAddedInExercise
  821. );
  822. $question_list = $this->pickQuestionsPerCategory(
  823. $categoriesAddedInExercise,
  824. $question_list,
  825. $questions_by_category,
  826. true,
  827. true
  828. );
  829. break;
  830. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED: // 7
  831. break;
  832. case EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED: // 8
  833. break;
  834. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED: // 9
  835. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  836. $this,
  837. $this->course['real_id'],
  838. 'root ASC, lft ASC',
  839. false,
  840. true
  841. );
  842. $questions_by_category = TestCategory::getQuestionsByCat(
  843. $this->id,
  844. $question_list,
  845. $categoriesAddedInExercise
  846. );
  847. $question_list = $this->pickQuestionsPerCategory(
  848. $categoriesAddedInExercise,
  849. $question_list,
  850. $questions_by_category,
  851. true,
  852. false
  853. );
  854. break;
  855. case EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM: // 10
  856. $categoriesAddedInExercise = $cat->getCategoryExerciseTree(
  857. $this,
  858. $this->course['real_id'],
  859. 'root, lft ASC',
  860. false,
  861. true
  862. );
  863. $questions_by_category = TestCategory::getQuestionsByCat(
  864. $this->id,
  865. $question_list,
  866. $categoriesAddedInExercise
  867. );
  868. $question_list = $this->pickQuestionsPerCategory(
  869. $categoriesAddedInExercise,
  870. $question_list,
  871. $questions_by_category,
  872. true,
  873. true
  874. );
  875. break;
  876. }
  877. $result['question_list'] = isset($question_list) ? $question_list : [];
  878. $result['category_with_questions_list'] = isset($questions_by_category) ? $questions_by_category : [];
  879. $parentsLoaded = [];
  880. // Adding category info in the category list with question list:
  881. if (!empty($questions_by_category)) {
  882. $newCategoryList = [];
  883. $em = Database::getManager();
  884. foreach ($questions_by_category as $categoryId => $questionList) {
  885. $cat = new TestCategory();
  886. $cat = $cat->getCategory($categoryId);
  887. if ($cat) {
  888. $cat = (array) $cat;
  889. $cat['iid'] = $cat['id'];
  890. }
  891. $categoryParentInfo = null;
  892. // Parent is not set no loop here
  893. if (isset($cat['parent_id']) && !empty($cat['parent_id'])) {
  894. /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryEntity */
  895. if (!isset($parentsLoaded[$cat['parent_id']])) {
  896. $categoryEntity = $em->find('ChamiloCoreBundle:CQuizCategory', $cat['parent_id']);
  897. $parentsLoaded[$cat['parent_id']] = $categoryEntity;
  898. } else {
  899. $categoryEntity = $parentsLoaded[$cat['parent_id']];
  900. }
  901. $repo = $em->getRepository('ChamiloCoreBundle:CQuizCategory');
  902. $path = $repo->getPath($categoryEntity);
  903. $index = 0;
  904. if ($this->categoryMinusOne) {
  905. //$index = 1;
  906. }
  907. /** @var \Chamilo\CourseBundle\Entity\CQuizCategory $categoryParent */
  908. foreach ($path as $categoryParent) {
  909. $visibility = $categoryParent->getVisibility();
  910. if ($visibility == 0) {
  911. $categoryParentId = $categoryId;
  912. $categoryTitle = $cat['title'];
  913. if (count($path) > 1) {
  914. continue;
  915. }
  916. } else {
  917. $categoryParentId = $categoryParent->getIid();
  918. $categoryTitle = $categoryParent->getTitle();
  919. }
  920. $categoryParentInfo['id'] = $categoryParentId;
  921. $categoryParentInfo['iid'] = $categoryParentId;
  922. $categoryParentInfo['parent_path'] = null;
  923. $categoryParentInfo['title'] = $categoryTitle;
  924. $categoryParentInfo['name'] = $categoryTitle;
  925. $categoryParentInfo['parent_id'] = null;
  926. break;
  927. }
  928. }
  929. $cat['parent_info'] = $categoryParentInfo;
  930. $newCategoryList[$categoryId] = [
  931. 'category' => $cat,
  932. 'question_list' => $questionList,
  933. ];
  934. }
  935. $result['category_with_questions_list'] = $newCategoryList;
  936. }
  937. return $result;
  938. }
  939. /**
  940. * returns the array with the question ID list.
  941. *
  942. * @param bool $fromDatabase Whether the results should be fetched in the database or just from memory
  943. * @param bool $adminView Whether we should return all questions (admin view) or
  944. * just a list limited by the max number of random questions
  945. *
  946. * @author Olivier Brouckaert
  947. *
  948. * @return array - question ID list
  949. */
  950. public function selectQuestionList($fromDatabase = false, $adminView = false)
  951. {
  952. if ($fromDatabase && !empty($this->id)) {
  953. $nbQuestions = $this->getQuestionCount();
  954. $questionSelectionType = $this->getQuestionSelectionType();
  955. switch ($questionSelectionType) {
  956. case EX_Q_SELECTION_ORDERED:
  957. $questionList = $this->getQuestionOrderedList();
  958. break;
  959. case EX_Q_SELECTION_RANDOM:
  960. // Not a random exercise, or if there are not at least 2 questions
  961. if ($this->random == 0 || $nbQuestions < 2) {
  962. $questionList = $this->getQuestionOrderedList();
  963. } else {
  964. $questionList = $this->getRandomList($adminView);
  965. }
  966. break;
  967. default:
  968. $questionList = $this->getQuestionOrderedList();
  969. $result = $this->getQuestionListWithCategoryListFilteredByCategorySettings(
  970. $questionList,
  971. $questionSelectionType
  972. );
  973. $this->categoryWithQuestionList = $result['category_with_questions_list'];
  974. $questionList = $result['question_list'];
  975. break;
  976. }
  977. return $questionList;
  978. }
  979. return $this->questionList;
  980. }
  981. /**
  982. * returns the number of questions in this exercise.
  983. *
  984. * @author Olivier Brouckaert
  985. *
  986. * @return int - number of questions
  987. */
  988. public function selectNbrQuestions()
  989. {
  990. return count($this->questionList);
  991. }
  992. /**
  993. * @return int
  994. */
  995. public function selectPropagateNeg()
  996. {
  997. return $this->propagate_neg;
  998. }
  999. /**
  1000. * @return int
  1001. */
  1002. public function getSaveCorrectAnswers()
  1003. {
  1004. return $this->saveCorrectAnswers;
  1005. }
  1006. /**
  1007. * Selects questions randomly in the question list.
  1008. *
  1009. * @author Olivier Brouckaert
  1010. * @author Hubert Borderiou 15 nov 2011
  1011. *
  1012. * @param bool $adminView Whether we should return all
  1013. * questions (admin view) or just a list limited by the max number of random questions
  1014. *
  1015. * @return array - if the exercise is not set to take questions randomly, returns the question list
  1016. * without randomizing, otherwise, returns the list with questions selected randomly
  1017. */
  1018. public function getRandomList($adminView = false)
  1019. {
  1020. $quizRelQuestion = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1021. $question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1022. $random = isset($this->random) && !empty($this->random) ? $this->random : 0;
  1023. // Random with limit
  1024. $randomLimit = " ORDER BY RAND() LIMIT $random";
  1025. // Random with no limit
  1026. if ($random == -1) {
  1027. $randomLimit = ' ORDER BY RAND() ';
  1028. }
  1029. // Admin see the list in default order
  1030. if ($adminView === true) {
  1031. // If viewing it as admin for edition, don't show it randomly, use title + id
  1032. $randomLimit = 'ORDER BY e.question_order';
  1033. }
  1034. $sql = "SELECT e.question_id
  1035. FROM $quizRelQuestion e
  1036. INNER JOIN $question q
  1037. ON (e.question_id= q.id AND e.c_id = q.c_id)
  1038. WHERE
  1039. e.c_id = {$this->course_id} AND
  1040. e.exercice_id = '".Database::escape_string($this->id)."'
  1041. $randomLimit ";
  1042. $result = Database::query($sql);
  1043. $questionList = [];
  1044. while ($row = Database::fetch_object($result)) {
  1045. $questionList[] = $row->question_id;
  1046. }
  1047. return $questionList;
  1048. }
  1049. /**
  1050. * returns 'true' if the question ID is in the question list.
  1051. *
  1052. * @author Olivier Brouckaert
  1053. *
  1054. * @param int $questionId - question ID
  1055. *
  1056. * @return bool - true if in the list, otherwise false
  1057. */
  1058. public function isInList($questionId)
  1059. {
  1060. $inList = false;
  1061. if (is_array($this->questionList)) {
  1062. $inList = in_array($questionId, $this->questionList);
  1063. }
  1064. return $inList;
  1065. }
  1066. /**
  1067. * If current exercise has a question.
  1068. *
  1069. * @param int $questionId
  1070. *
  1071. * @return int
  1072. */
  1073. public function hasQuestion($questionId)
  1074. {
  1075. $questionId = (int) $questionId;
  1076. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1077. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1078. $sql = "SELECT q.id
  1079. FROM $TBL_EXERCICE_QUESTION e
  1080. INNER JOIN $TBL_QUESTIONS q
  1081. ON (e.question_id = q.id AND e.c_id = q.c_id)
  1082. WHERE
  1083. q.id = $questionId AND
  1084. e.c_id = {$this->course_id} AND
  1085. e.exercice_id = ".$this->id;
  1086. $result = Database::query($sql);
  1087. return Database::num_rows($result) > 0;
  1088. }
  1089. /**
  1090. * changes the exercise title.
  1091. *
  1092. * @author Olivier Brouckaert
  1093. *
  1094. * @param string $title - exercise title
  1095. */
  1096. public function updateTitle($title)
  1097. {
  1098. $this->title = $this->exercise = $title;
  1099. }
  1100. /**
  1101. * changes the exercise max attempts.
  1102. *
  1103. * @param int $attempts - exercise max attempts
  1104. */
  1105. public function updateAttempts($attempts)
  1106. {
  1107. $this->attempts = $attempts;
  1108. }
  1109. /**
  1110. * changes the exercise feedback type.
  1111. *
  1112. * @param int $feedback_type
  1113. */
  1114. public function updateFeedbackType($feedback_type)
  1115. {
  1116. $this->feedback_type = $feedback_type;
  1117. }
  1118. /**
  1119. * changes the exercise description.
  1120. *
  1121. * @author Olivier Brouckaert
  1122. *
  1123. * @param string $description - exercise description
  1124. */
  1125. public function updateDescription($description)
  1126. {
  1127. $this->description = $description;
  1128. }
  1129. /**
  1130. * changes the exercise expired_time.
  1131. *
  1132. * @author Isaac flores
  1133. *
  1134. * @param int $expired_time The expired time of the quiz
  1135. */
  1136. public function updateExpiredTime($expired_time)
  1137. {
  1138. $this->expired_time = $expired_time;
  1139. }
  1140. /**
  1141. * @param $value
  1142. */
  1143. public function updatePropagateNegative($value)
  1144. {
  1145. $this->propagate_neg = $value;
  1146. }
  1147. /**
  1148. * @param $value int
  1149. */
  1150. public function updateSaveCorrectAnswers($value)
  1151. {
  1152. $this->saveCorrectAnswers = (int) $value;
  1153. }
  1154. /**
  1155. * @param $value
  1156. */
  1157. public function updateReviewAnswers($value)
  1158. {
  1159. $this->review_answers = isset($value) && $value ? true : false;
  1160. }
  1161. /**
  1162. * @param $value
  1163. */
  1164. public function updatePassPercentage($value)
  1165. {
  1166. $this->pass_percentage = $value;
  1167. }
  1168. /**
  1169. * @param string $text
  1170. */
  1171. public function updateEmailNotificationTemplate($text)
  1172. {
  1173. $this->emailNotificationTemplate = $text;
  1174. }
  1175. /**
  1176. * @param string $text
  1177. */
  1178. public function setEmailNotificationTemplateToUser($text)
  1179. {
  1180. $this->emailNotificationTemplateToUser = $text;
  1181. }
  1182. /**
  1183. * @param string $value
  1184. */
  1185. public function setNotifyUserByEmail($value)
  1186. {
  1187. $this->notifyUserByEmail = $value;
  1188. }
  1189. /**
  1190. * @param int $value
  1191. */
  1192. public function updateEndButton($value)
  1193. {
  1194. $this->endButton = (int) $value;
  1195. }
  1196. /**
  1197. * @param string $value
  1198. */
  1199. public function setOnSuccessMessage($value)
  1200. {
  1201. $this->onSuccessMessage = $value;
  1202. }
  1203. /**
  1204. * @param string $value
  1205. */
  1206. public function setOnFailedMessage($value)
  1207. {
  1208. $this->onFailedMessage = $value;
  1209. }
  1210. /**
  1211. * @param $value
  1212. */
  1213. public function setModelType($value)
  1214. {
  1215. $this->modelType = (int) $value;
  1216. }
  1217. /**
  1218. * @param int $value
  1219. */
  1220. public function setQuestionSelectionType($value)
  1221. {
  1222. $this->questionSelectionType = (int) $value;
  1223. }
  1224. /**
  1225. * @return int
  1226. */
  1227. public function getQuestionSelectionType()
  1228. {
  1229. return (int) $this->questionSelectionType;
  1230. }
  1231. /**
  1232. * @param array $categories
  1233. */
  1234. public function updateCategories($categories)
  1235. {
  1236. if (!empty($categories)) {
  1237. $categories = array_map('intval', $categories);
  1238. $this->categories = $categories;
  1239. }
  1240. }
  1241. /**
  1242. * changes the exercise sound file.
  1243. *
  1244. * @author Olivier Brouckaert
  1245. *
  1246. * @param string $sound - exercise sound file
  1247. * @param string $delete - ask to delete the file
  1248. */
  1249. public function updateSound($sound, $delete)
  1250. {
  1251. global $audioPath, $documentPath;
  1252. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  1253. if ($sound['size'] && (strstr($sound['type'], 'audio') || strstr($sound['type'], 'video'))) {
  1254. $this->sound = $sound['name'];
  1255. if (@move_uploaded_file($sound['tmp_name'], $audioPath.'/'.$this->sound)) {
  1256. $sql = "SELECT 1 FROM $TBL_DOCUMENT
  1257. WHERE
  1258. c_id = ".$this->course_id." AND
  1259. path = '".str_replace($documentPath, '', $audioPath).'/'.$this->sound."'";
  1260. $result = Database::query($sql);
  1261. if (!Database::num_rows($result)) {
  1262. $id = add_document(
  1263. $this->course,
  1264. str_replace($documentPath, '', $audioPath).'/'.$this->sound,
  1265. 'file',
  1266. $sound['size'],
  1267. $sound['name']
  1268. );
  1269. api_item_property_update(
  1270. $this->course,
  1271. TOOL_DOCUMENT,
  1272. $id,
  1273. 'DocumentAdded',
  1274. api_get_user_id()
  1275. );
  1276. item_property_update_on_folder(
  1277. $this->course,
  1278. str_replace($documentPath, '', $audioPath),
  1279. api_get_user_id()
  1280. );
  1281. }
  1282. }
  1283. } elseif ($delete && is_file($audioPath.'/'.$this->sound)) {
  1284. $this->sound = '';
  1285. }
  1286. }
  1287. /**
  1288. * changes the exercise type.
  1289. *
  1290. * @author Olivier Brouckaert
  1291. *
  1292. * @param int $type - exercise type
  1293. */
  1294. public function updateType($type)
  1295. {
  1296. $this->type = $type;
  1297. }
  1298. /**
  1299. * sets to 0 if questions are not selected randomly
  1300. * if questions are selected randomly, sets the draws.
  1301. *
  1302. * @author Olivier Brouckaert
  1303. *
  1304. * @param int $random - 0 if not random, otherwise the draws
  1305. */
  1306. public function setRandom($random)
  1307. {
  1308. $this->random = $random;
  1309. }
  1310. /**
  1311. * sets to 0 if answers are not selected randomly
  1312. * if answers are selected randomly.
  1313. *
  1314. * @author Juan Carlos Rana
  1315. *
  1316. * @param int $random_answers - random answers
  1317. */
  1318. public function updateRandomAnswers($random_answers)
  1319. {
  1320. $this->random_answers = $random_answers;
  1321. }
  1322. /**
  1323. * enables the exercise.
  1324. *
  1325. * @author Olivier Brouckaert
  1326. */
  1327. public function enable()
  1328. {
  1329. $this->active = 1;
  1330. }
  1331. /**
  1332. * disables the exercise.
  1333. *
  1334. * @author Olivier Brouckaert
  1335. */
  1336. public function disable()
  1337. {
  1338. $this->active = 0;
  1339. }
  1340. /**
  1341. * Set disable results.
  1342. */
  1343. public function disable_results()
  1344. {
  1345. $this->results_disabled = true;
  1346. }
  1347. /**
  1348. * Enable results.
  1349. */
  1350. public function enable_results()
  1351. {
  1352. $this->results_disabled = false;
  1353. }
  1354. /**
  1355. * @param int $results_disabled
  1356. */
  1357. public function updateResultsDisabled($results_disabled)
  1358. {
  1359. $this->results_disabled = (int) $results_disabled;
  1360. }
  1361. /**
  1362. * updates the exercise in the data base.
  1363. *
  1364. * @param string $type_e
  1365. *
  1366. * @author Olivier Brouckaert
  1367. */
  1368. public function save($type_e = '')
  1369. {
  1370. $_course = $this->course;
  1371. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  1372. $id = $this->id;
  1373. $exercise = $this->exercise;
  1374. $description = $this->description;
  1375. $sound = $this->sound;
  1376. $type = $this->type;
  1377. $attempts = isset($this->attempts) ? $this->attempts : 0;
  1378. $feedback_type = isset($this->feedback_type) ? $this->feedback_type : 0;
  1379. $random = $this->random;
  1380. $random_answers = $this->random_answers;
  1381. $active = $this->active;
  1382. $propagate_neg = (int) $this->propagate_neg;
  1383. $saveCorrectAnswers = isset($this->saveCorrectAnswers) ? (int) $this->saveCorrectAnswers : 0;
  1384. $review_answers = isset($this->review_answers) && $this->review_answers ? 1 : 0;
  1385. $randomByCat = (int) $this->randomByCat;
  1386. $text_when_finished = $this->text_when_finished;
  1387. $display_category_name = (int) $this->display_category_name;
  1388. $pass_percentage = (int) $this->pass_percentage;
  1389. $session_id = $this->sessionId;
  1390. // If direct we do not show results
  1391. $results_disabled = (int) $this->results_disabled;
  1392. if (in_array($feedback_type, [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1393. $results_disabled = 0;
  1394. }
  1395. $expired_time = (int) $this->expired_time;
  1396. // Exercise already exists
  1397. if ($id) {
  1398. // we prepare date in the database using the api_get_utc_datetime() function
  1399. $start_time = null;
  1400. if (!empty($this->start_time)) {
  1401. $start_time = $this->start_time;
  1402. }
  1403. $end_time = null;
  1404. if (!empty($this->end_time)) {
  1405. $end_time = $this->end_time;
  1406. }
  1407. $params = [
  1408. 'title' => $exercise,
  1409. 'description' => $description,
  1410. ];
  1411. $paramsExtra = [];
  1412. if ($type_e != 'simple') {
  1413. $paramsExtra = [
  1414. 'sound' => $sound,
  1415. 'type' => $type,
  1416. 'random' => $random,
  1417. 'random_answers' => $random_answers,
  1418. 'active' => $active,
  1419. 'feedback_type' => $feedback_type,
  1420. 'start_time' => $start_time,
  1421. 'end_time' => $end_time,
  1422. 'max_attempt' => $attempts,
  1423. 'expired_time' => $expired_time,
  1424. 'propagate_neg' => $propagate_neg,
  1425. 'save_correct_answers' => $saveCorrectAnswers,
  1426. 'review_answers' => $review_answers,
  1427. 'random_by_category' => $randomByCat,
  1428. 'text_when_finished' => $text_when_finished,
  1429. 'display_category_name' => $display_category_name,
  1430. 'pass_percentage' => $pass_percentage,
  1431. 'results_disabled' => $results_disabled,
  1432. 'question_selection_type' => $this->getQuestionSelectionType(),
  1433. 'hide_question_title' => $this->getHideQuestionTitle(),
  1434. ];
  1435. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1436. if ($allow === true) {
  1437. $paramsExtra['show_previous_button'] = $this->showPreviousButton();
  1438. }
  1439. $allow = api_get_configuration_value('allow_exercise_categories');
  1440. if ($allow === true) {
  1441. $paramsExtra['exercise_category_id'] = $this->getExerciseCategoryId();
  1442. }
  1443. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1444. if ($allow === true) {
  1445. $notifications = $this->getNotifications();
  1446. $notifications = implode(',', $notifications);
  1447. $paramsExtra['notifications'] = $notifications;
  1448. }
  1449. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1450. if ($pageConfig && !empty($this->pageResultConfiguration)) {
  1451. $paramsExtra['page_result_configuration'] = $this->pageResultConfiguration;
  1452. }
  1453. }
  1454. $params = array_merge($params, $paramsExtra);
  1455. Database::update(
  1456. $TBL_EXERCISES,
  1457. $params,
  1458. ['c_id = ? AND id = ?' => [$this->course_id, $id]]
  1459. );
  1460. // update into the item_property table
  1461. api_item_property_update(
  1462. $_course,
  1463. TOOL_QUIZ,
  1464. $id,
  1465. 'QuizUpdated',
  1466. api_get_user_id()
  1467. );
  1468. if (api_get_setting('search_enabled') == 'true') {
  1469. $this->search_engine_edit();
  1470. }
  1471. } else {
  1472. // Creates a new exercise
  1473. // In this case of new exercise, we don't do the api_get_utc_datetime()
  1474. // for date because, bellow, we call function api_set_default_visibility()
  1475. // In this function, api_set_default_visibility,
  1476. // the Quiz is saved too, with an $id and api_get_utc_datetime() is done.
  1477. // If we do it now, it will be done twice (cf. https://support.chamilo.org/issues/6586)
  1478. $start_time = null;
  1479. if (!empty($this->start_time)) {
  1480. $start_time = $this->start_time;
  1481. }
  1482. $end_time = null;
  1483. if (!empty($this->end_time)) {
  1484. $end_time = $this->end_time;
  1485. }
  1486. $params = [
  1487. 'c_id' => $this->course_id,
  1488. 'start_time' => $start_time,
  1489. 'end_time' => $end_time,
  1490. 'title' => $exercise,
  1491. 'description' => $description,
  1492. 'sound' => $sound,
  1493. 'type' => $type,
  1494. 'random' => $random,
  1495. 'random_answers' => $random_answers,
  1496. 'active' => $active,
  1497. 'results_disabled' => $results_disabled,
  1498. 'max_attempt' => $attempts,
  1499. 'feedback_type' => $feedback_type,
  1500. 'expired_time' => $expired_time,
  1501. 'session_id' => $session_id,
  1502. 'review_answers' => $review_answers,
  1503. 'random_by_category' => $randomByCat,
  1504. 'text_when_finished' => $text_when_finished,
  1505. 'display_category_name' => $display_category_name,
  1506. 'pass_percentage' => $pass_percentage,
  1507. 'save_correct_answers' => $saveCorrectAnswers,
  1508. 'propagate_neg' => $propagate_neg,
  1509. 'hide_question_title' => $this->getHideQuestionTitle(),
  1510. ];
  1511. $allow = api_get_configuration_value('allow_exercise_categories');
  1512. if ($allow === true) {
  1513. $params['exercise_category_id'] = $this->getExerciseCategoryId();
  1514. }
  1515. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1516. if ($allow === true) {
  1517. $params['show_previous_button'] = $this->showPreviousButton();
  1518. }
  1519. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  1520. if ($allow === true) {
  1521. $notifications = $this->getNotifications();
  1522. $params['notifications'] = '';
  1523. if (!empty($notifications)) {
  1524. $notifications = implode(',', $notifications);
  1525. $params['notifications'] = $notifications;
  1526. }
  1527. }
  1528. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1529. if ($pageConfig && !empty($this->pageResultConfiguration)) {
  1530. $params['page_result_configuration'] = $this->pageResultConfiguration;
  1531. }
  1532. $this->id = $this->iId = Database::insert($TBL_EXERCISES, $params);
  1533. if ($this->id) {
  1534. $sql = "UPDATE $TBL_EXERCISES SET id = iid WHERE iid = {$this->id} ";
  1535. Database::query($sql);
  1536. $sql = "UPDATE $TBL_EXERCISES
  1537. SET question_selection_type= ".$this->getQuestionSelectionType()."
  1538. WHERE id = ".$this->id." AND c_id = ".$this->course_id;
  1539. Database::query($sql);
  1540. // insert into the item_property table
  1541. api_item_property_update(
  1542. $this->course,
  1543. TOOL_QUIZ,
  1544. $this->id,
  1545. 'QuizAdded',
  1546. api_get_user_id()
  1547. );
  1548. // This function save the quiz again, carefull about start_time
  1549. // and end_time if you remove this line (see above)
  1550. api_set_default_visibility(
  1551. $this->id,
  1552. TOOL_QUIZ,
  1553. null,
  1554. $this->course
  1555. );
  1556. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  1557. $this->search_engine_save();
  1558. }
  1559. }
  1560. }
  1561. $this->save_categories_in_exercise($this->categories);
  1562. // Updates the question position
  1563. $this->update_question_positions();
  1564. return $this->iId;
  1565. }
  1566. /**
  1567. * Updates question position.
  1568. *
  1569. * @return bool
  1570. */
  1571. public function update_question_positions()
  1572. {
  1573. $table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1574. // Fixes #3483 when updating order
  1575. $questionList = $this->selectQuestionList(true);
  1576. $this->id = (int) $this->id;
  1577. if (empty($this->id)) {
  1578. return false;
  1579. }
  1580. if (!empty($questionList)) {
  1581. foreach ($questionList as $position => $questionId) {
  1582. $position = (int) $position;
  1583. $questionId = (int) $questionId;
  1584. $sql = "UPDATE $table SET
  1585. question_order ='".$position."'
  1586. WHERE
  1587. c_id = ".$this->course_id." AND
  1588. question_id = ".$questionId." AND
  1589. exercice_id=".$this->id;
  1590. Database::query($sql);
  1591. }
  1592. }
  1593. return true;
  1594. }
  1595. /**
  1596. * Adds a question into the question list.
  1597. *
  1598. * @author Olivier Brouckaert
  1599. *
  1600. * @param int $questionId - question ID
  1601. *
  1602. * @return bool - true if the question has been added, otherwise false
  1603. */
  1604. public function addToList($questionId)
  1605. {
  1606. // checks if the question ID is not in the list
  1607. if (!$this->isInList($questionId)) {
  1608. // selects the max position
  1609. if (!$this->selectNbrQuestions()) {
  1610. $pos = 1;
  1611. } else {
  1612. if (is_array($this->questionList)) {
  1613. $pos = max(array_keys($this->questionList)) + 1;
  1614. }
  1615. }
  1616. $this->questionList[$pos] = $questionId;
  1617. return true;
  1618. }
  1619. return false;
  1620. }
  1621. /**
  1622. * removes a question from the question list.
  1623. *
  1624. * @author Olivier Brouckaert
  1625. *
  1626. * @param int $questionId - question ID
  1627. *
  1628. * @return bool - true if the question has been removed, otherwise false
  1629. */
  1630. public function removeFromList($questionId)
  1631. {
  1632. // searches the position of the question ID in the list
  1633. $pos = array_search($questionId, $this->questionList);
  1634. // question not found
  1635. if ($pos === false) {
  1636. return false;
  1637. } else {
  1638. // dont reduce the number of random question if we use random by category option, or if
  1639. // random all questions
  1640. if ($this->isRandom() && $this->isRandomByCat() == 0) {
  1641. if (count($this->questionList) >= $this->random && $this->random > 0) {
  1642. $this->random--;
  1643. $this->save();
  1644. }
  1645. }
  1646. // deletes the position from the array containing the wanted question ID
  1647. unset($this->questionList[$pos]);
  1648. return true;
  1649. }
  1650. }
  1651. /**
  1652. * deletes the exercise from the database
  1653. * Notice : leaves the question in the data base.
  1654. *
  1655. * @author Olivier Brouckaert
  1656. */
  1657. public function delete()
  1658. {
  1659. $limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
  1660. if ($limitTeacherAccess && !api_is_platform_admin()) {
  1661. return false;
  1662. }
  1663. $locked = api_resource_is_locked_by_gradebook(
  1664. $this->id,
  1665. LINK_EXERCISE
  1666. );
  1667. if ($locked) {
  1668. return false;
  1669. }
  1670. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  1671. $sql = "UPDATE $table SET active='-1'
  1672. WHERE c_id = ".$this->course_id." AND id = ".intval($this->id);
  1673. Database::query($sql);
  1674. api_item_property_update(
  1675. $this->course,
  1676. TOOL_QUIZ,
  1677. $this->id,
  1678. 'QuizDeleted',
  1679. api_get_user_id()
  1680. );
  1681. api_item_property_update(
  1682. $this->course,
  1683. TOOL_QUIZ,
  1684. $this->id,
  1685. 'delete',
  1686. api_get_user_id()
  1687. );
  1688. Skill::deleteSkillsFromItem($this->iId, ITEM_TYPE_EXERCISE);
  1689. if (api_get_setting('search_enabled') === 'true' &&
  1690. extension_loaded('xapian')
  1691. ) {
  1692. $this->search_engine_delete();
  1693. }
  1694. $linkInfo = GradebookUtils::isResourceInCourseGradebook(
  1695. $this->course['code'],
  1696. LINK_EXERCISE,
  1697. $this->id,
  1698. $this->sessionId
  1699. );
  1700. if ($linkInfo !== false) {
  1701. GradebookUtils::remove_resource_from_course_gradebook($linkInfo['id']);
  1702. }
  1703. return true;
  1704. }
  1705. /**
  1706. * Creates the form to create / edit an exercise.
  1707. *
  1708. * @param FormValidator $form
  1709. * @param string $type
  1710. */
  1711. public function createForm($form, $type = 'full')
  1712. {
  1713. if (empty($type)) {
  1714. $type = 'full';
  1715. }
  1716. // Form title
  1717. $form_title = get_lang('NewEx');
  1718. if (!empty($_GET['exerciseId'])) {
  1719. $form_title = get_lang('ModifyExercise');
  1720. }
  1721. $form->addHeader($form_title);
  1722. // Title.
  1723. if (api_get_configuration_value('save_titles_as_html')) {
  1724. $form->addHtmlEditor(
  1725. 'exerciseTitle',
  1726. get_lang('ExerciseName'),
  1727. false,
  1728. false,
  1729. ['ToolbarSet' => 'Minimal']
  1730. );
  1731. } else {
  1732. $form->addElement(
  1733. 'text',
  1734. 'exerciseTitle',
  1735. get_lang('ExerciseName'),
  1736. ['id' => 'exercise_title']
  1737. );
  1738. }
  1739. $form->addElement('advanced_settings', 'advanced_params', get_lang('AdvancedParameters'));
  1740. $form->addElement('html', '<div id="advanced_params_options" style="display:none">');
  1741. if (api_get_configuration_value('allow_exercise_categories')) {
  1742. $categoryManager = new ExerciseCategoryManager();
  1743. $categories = $categoryManager->getCategories(api_get_course_int_id());
  1744. $options = [];
  1745. if (!empty($categories)) {
  1746. /** @var \Chamilo\CourseBundle\Entity\CExerciseCategory $category */
  1747. foreach ($categories as $category) {
  1748. $options[$category->getId()] = $category->getName();
  1749. }
  1750. }
  1751. $form->addSelect(
  1752. 'exercise_category_id',
  1753. get_lang('Category'),
  1754. $options,
  1755. ['placeholder' => get_lang('SelectAnOption')]
  1756. );
  1757. }
  1758. $editor_config = [
  1759. 'ToolbarSet' => 'TestQuestionDescription',
  1760. 'Width' => '100%',
  1761. 'Height' => '150',
  1762. ];
  1763. if (is_array($type)) {
  1764. $editor_config = array_merge($editor_config, $type);
  1765. }
  1766. $form->addHtmlEditor(
  1767. 'exerciseDescription',
  1768. get_lang('ExerciseDescription'),
  1769. false,
  1770. false,
  1771. $editor_config
  1772. );
  1773. $skillList = [];
  1774. if ($type === 'full') {
  1775. // Can't modify a DirectFeedback question.
  1776. if (!in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  1777. $this->setResultFeedbackGroup($form);
  1778. // Type of results display on the final page
  1779. $this->setResultDisabledGroup($form);
  1780. // Type of questions disposition on page
  1781. $radios = [];
  1782. $radios[] = $form->createElement(
  1783. 'radio',
  1784. 'exerciseType',
  1785. null,
  1786. get_lang('SimpleExercise'),
  1787. '1',
  1788. [
  1789. 'onclick' => 'check_per_page_all()',
  1790. 'id' => 'option_page_all',
  1791. ]
  1792. );
  1793. $radios[] = $form->createElement(
  1794. 'radio',
  1795. 'exerciseType',
  1796. null,
  1797. get_lang('SequentialExercise'),
  1798. '2',
  1799. [
  1800. 'onclick' => 'check_per_page_one()',
  1801. 'id' => 'option_page_one',
  1802. ]
  1803. );
  1804. $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1805. } else {
  1806. // if is Direct feedback but has not questions we can allow to modify the question type
  1807. if ($this->getQuestionCount() === 0) {
  1808. $this->setResultFeedbackGroup($form);
  1809. $this->setResultDisabledGroup($form);
  1810. // Type of questions disposition on page
  1811. $radios = [];
  1812. $radios[] = $form->createElement('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  1813. $radios[] = $form->createElement(
  1814. 'radio',
  1815. 'exerciseType',
  1816. null,
  1817. get_lang('SequentialExercise'),
  1818. '2'
  1819. );
  1820. $form->addGroup($radios, null, get_lang('ExerciseType'));
  1821. } else {
  1822. $group = $this->setResultDisabledGroup($form);
  1823. $group->freeze();
  1824. // we force the options to the DirectFeedback exercisetype
  1825. $form->addElement('hidden', 'exerciseFeedbackType', $this->getFeedbackType());
  1826. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  1827. // Type of questions disposition on page
  1828. $radios[] = $form->createElement(
  1829. 'radio',
  1830. 'exerciseType',
  1831. null,
  1832. get_lang('SimpleExercise'),
  1833. '1',
  1834. [
  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. [
  1846. 'onclick' => 'check_per_page_one()',
  1847. 'id' => 'option_page_one',
  1848. ]
  1849. );
  1850. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  1851. $type_group->freeze();
  1852. }
  1853. }
  1854. $option = [
  1855. EX_Q_SELECTION_ORDERED => get_lang('OrderedByUser'),
  1856. // Defined by user
  1857. EX_Q_SELECTION_RANDOM => get_lang('Random'),
  1858. // 1-10, All
  1859. 'per_categories' => '--------'.get_lang('UsingCategories').'----------',
  1860. // Base (A 123 {3} B 456 {3} C 789{2} D 0{0}) --> Matrix {3, 3, 2, 0}
  1861. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED => get_lang('OrderedCategoriesAlphabeticallyWithQuestionsOrdered'),
  1862. // A 123 B 456 C 78 (0, 1, all)
  1863. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED => get_lang('RandomCategoriesWithQuestionsOrdered'),
  1864. // C 78 B 456 A 123
  1865. EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_RANDOM => get_lang('OrderedCategoriesAlphabeticallyWithRandomQuestions'),
  1866. // A 321 B 654 C 87
  1867. EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM => get_lang('RandomCategoriesWithRandomQuestions'),
  1868. // C 87 B 654 A 321
  1869. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_ORDERED_NO_GROUPED => get_lang('RandomCategoriesWithQuestionsOrderedNoQuestionGrouped'),
  1870. /* B 456 C 78 A 123
  1871. 456 78 123
  1872. 123 456 78
  1873. */
  1874. //EX_Q_SELECTION_CATEGORIES_RANDOM_QUESTIONS_RANDOM_NO_GROUPED => get_lang('RandomCategoriesWithRandomQuestionsNoQuestionGrouped'),
  1875. /*
  1876. A 123 B 456 C 78
  1877. B 456 C 78 A 123
  1878. B 654 C 87 A 321
  1879. 654 87 321
  1880. 165 842 73
  1881. */
  1882. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED => get_lang('OrderedCategoriesByParentWithQuestionsOrdered'),
  1883. //EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM => get_lang('OrderedCategoriesByParentWithQuestionsRandom'),
  1884. ];
  1885. $form->addElement(
  1886. 'select',
  1887. 'question_selection_type',
  1888. [get_lang('QuestionSelection')],
  1889. $option,
  1890. [
  1891. 'id' => 'questionSelection',
  1892. 'onchange' => 'checkQuestionSelection()',
  1893. ]
  1894. );
  1895. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  1896. if ($pageConfig) {
  1897. $group = [
  1898. $form->createElement(
  1899. 'checkbox',
  1900. 'hide_expected_answer',
  1901. null,
  1902. get_lang('HideExpectedAnswer')
  1903. ),
  1904. $form->createElement(
  1905. 'checkbox',
  1906. 'hide_total_score',
  1907. null,
  1908. get_lang('HideTotalScore')
  1909. ),
  1910. $form->createElement(
  1911. 'checkbox',
  1912. 'hide_question_score',
  1913. null,
  1914. get_lang('HideQuestionScore')
  1915. ),
  1916. ];
  1917. $form->addGroup($group, null, get_lang('ResultsConfigurationPage'));
  1918. }
  1919. $displayMatrix = 'none';
  1920. $displayRandom = 'none';
  1921. $selectionType = $this->getQuestionSelectionType();
  1922. switch ($selectionType) {
  1923. case EX_Q_SELECTION_RANDOM:
  1924. $displayRandom = 'block';
  1925. break;
  1926. case $selectionType >= EX_Q_SELECTION_CATEGORIES_ORDERED_QUESTIONS_ORDERED:
  1927. $displayMatrix = 'block';
  1928. break;
  1929. }
  1930. $form->addElement(
  1931. 'html',
  1932. '<div id="hidden_random" style="display:'.$displayRandom.'">'
  1933. );
  1934. // Number of random question.
  1935. $max = ($this->id > 0) ? $this->getQuestionCount() : 10;
  1936. $option = range(0, $max);
  1937. $option[0] = get_lang('No');
  1938. $option[-1] = get_lang('AllQuestionsShort');
  1939. $form->addElement(
  1940. 'select',
  1941. 'randomQuestions',
  1942. [
  1943. get_lang('RandomQuestions'),
  1944. get_lang('RandomQuestionsHelp'),
  1945. ],
  1946. $option,
  1947. ['id' => 'randomQuestions']
  1948. );
  1949. $form->addElement('html', '</div>');
  1950. $form->addElement(
  1951. 'html',
  1952. '<div id="hidden_matrix" style="display:'.$displayMatrix.'">'
  1953. );
  1954. // Category selection.
  1955. $cat = new TestCategory();
  1956. $cat_form = $cat->returnCategoryForm($this);
  1957. if (empty($cat_form)) {
  1958. $cat_form = '<span class="label label-warning">'.get_lang('NoCategoriesDefined').'</span>';
  1959. }
  1960. $form->addElement('label', null, $cat_form);
  1961. $form->addElement('html', '</div>');
  1962. // Random answers.
  1963. $radios_random_answers = [
  1964. $form->createElement('radio', 'randomAnswers', null, get_lang('Yes'), '1'),
  1965. $form->createElement('radio', 'randomAnswers', null, get_lang('No'), '0'),
  1966. ];
  1967. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  1968. // Category name.
  1969. $radio_display_cat_name = [
  1970. $form->createElement('radio', 'display_category_name', null, get_lang('Yes'), '1'),
  1971. $form->createElement('radio', 'display_category_name', null, get_lang('No'), '0'),
  1972. ];
  1973. $form->addGroup($radio_display_cat_name, null, get_lang('QuestionDisplayCategoryName'));
  1974. // Hide question title.
  1975. $group = [
  1976. $form->createElement('radio', 'hide_question_title', null, get_lang('Yes'), '1'),
  1977. $form->createElement('radio', 'hide_question_title', null, get_lang('No'), '0'),
  1978. ];
  1979. $form->addGroup($group, null, get_lang('HideQuestionTitle'));
  1980. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  1981. if ($allow === true) {
  1982. // Hide question title.
  1983. $group = [
  1984. $form->createElement(
  1985. 'radio',
  1986. 'show_previous_button',
  1987. null,
  1988. get_lang('Yes'),
  1989. '1'
  1990. ),
  1991. $form->createElement(
  1992. 'radio',
  1993. 'show_previous_button',
  1994. null,
  1995. get_lang('No'),
  1996. '0'
  1997. ),
  1998. ];
  1999. $form->addGroup($group, null, get_lang('ShowPreviousButton'));
  2000. }
  2001. // Attempts
  2002. $attempt_option = range(0, 10);
  2003. $attempt_option[0] = get_lang('Infinite');
  2004. $form->addElement(
  2005. 'select',
  2006. 'exerciseAttempts',
  2007. get_lang('ExerciseAttempts'),
  2008. $attempt_option,
  2009. ['id' => 'exerciseAttempts']
  2010. );
  2011. // Exercise time limit
  2012. $form->addElement(
  2013. 'checkbox',
  2014. 'activate_start_date_check',
  2015. null,
  2016. get_lang('EnableStartTime'),
  2017. ['onclick' => 'activate_start_date()']
  2018. );
  2019. if (!empty($this->start_time)) {
  2020. $form->addElement('html', '<div id="start_date_div" style="display:block;">');
  2021. } else {
  2022. $form->addElement('html', '<div id="start_date_div" style="display:none;">');
  2023. }
  2024. $form->addElement('date_time_picker', 'start_time');
  2025. $form->addElement('html', '</div>');
  2026. $form->addElement(
  2027. 'checkbox',
  2028. 'activate_end_date_check',
  2029. null,
  2030. get_lang('EnableEndTime'),
  2031. ['onclick' => 'activate_end_date()']
  2032. );
  2033. if (!empty($this->end_time)) {
  2034. $form->addElement('html', '<div id="end_date_div" style="display:block;">');
  2035. } else {
  2036. $form->addElement('html', '<div id="end_date_div" style="display:none;">');
  2037. }
  2038. $form->addElement('date_time_picker', 'end_time');
  2039. $form->addElement('html', '</div>');
  2040. $display = 'block';
  2041. $form->addElement(
  2042. 'checkbox',
  2043. 'propagate_neg',
  2044. null,
  2045. get_lang('PropagateNegativeResults')
  2046. );
  2047. if (api_get_configuration_value('allow_quiz_save_correct_options')) {
  2048. $options = [
  2049. '' => get_lang('SelectAnOption'),
  2050. 1 => get_lang('SaveTheCorrectAnswersForTheNextAttempt'),
  2051. 2 => get_lang('SaveAllAnswers'),
  2052. ];
  2053. $form->addSelect(
  2054. 'save_correct_answers',
  2055. get_lang('SaveAnswers'),
  2056. $options
  2057. );
  2058. } else {
  2059. $form->addCheckBox(
  2060. 'save_correct_answers',
  2061. null,
  2062. get_lang('SaveTheCorrectAnswersForTheNextAttempt')
  2063. );
  2064. }
  2065. $form->addElement('html', '<div class="clear">&nbsp;</div>');
  2066. $form->addElement('checkbox', 'review_answers', null, get_lang('ReviewAnswers'));
  2067. $form->addElement('html', '<div id="divtimecontrol" style="display:'.$display.';">');
  2068. // Timer control
  2069. $form->addElement(
  2070. 'checkbox',
  2071. 'enabletimercontrol',
  2072. null,
  2073. get_lang('EnableTimerControl'),
  2074. [
  2075. 'onclick' => 'option_time_expired()',
  2076. 'id' => 'enabletimercontrol',
  2077. 'onload' => 'check_load_time()',
  2078. ]
  2079. );
  2080. $expired_date = (int) $this->selectExpiredTime();
  2081. if (($expired_date != '0')) {
  2082. $form->addElement('html', '<div id="timercontrol" style="display:block;">');
  2083. } else {
  2084. $form->addElement('html', '<div id="timercontrol" style="display:none;">');
  2085. }
  2086. $form->addText(
  2087. 'enabletimercontroltotalminutes',
  2088. get_lang('ExerciseTotalDurationInMinutes'),
  2089. false,
  2090. [
  2091. 'id' => 'enabletimercontroltotalminutes',
  2092. 'cols-size' => [2, 2, 8],
  2093. ]
  2094. );
  2095. $form->addElement('html', '</div>');
  2096. $form->addElement(
  2097. 'text',
  2098. 'pass_percentage',
  2099. [get_lang('PassPercentage'), null, '%'],
  2100. ['id' => 'pass_percentage']
  2101. );
  2102. $form->addRule('pass_percentage', get_lang('Numeric'), 'numeric');
  2103. $form->addRule('pass_percentage', get_lang('ValueTooSmall'), 'min_numeric_length', 0);
  2104. $form->addRule('pass_percentage', get_lang('ValueTooBig'), 'max_numeric_length', 100);
  2105. // add the text_when_finished textbox
  2106. $form->addHtmlEditor(
  2107. 'text_when_finished',
  2108. get_lang('TextWhenFinished'),
  2109. false,
  2110. false,
  2111. $editor_config
  2112. );
  2113. $allow = api_get_configuration_value('allow_notification_setting_per_exercise');
  2114. if ($allow === true) {
  2115. $settings = ExerciseLib::getNotificationSettings();
  2116. $group = [];
  2117. foreach ($settings as $itemId => $label) {
  2118. $group[] = $form->createElement(
  2119. 'checkbox',
  2120. 'notifications[]',
  2121. null,
  2122. $label,
  2123. ['value' => $itemId]
  2124. );
  2125. }
  2126. $form->addGroup($group, '', [get_lang('EmailNotifications')]);
  2127. }
  2128. $form->addCheckBox(
  2129. 'update_title_in_lps',
  2130. null,
  2131. get_lang('UpdateTitleInLps')
  2132. );
  2133. $defaults = [];
  2134. if (api_get_setting('search_enabled') === 'true') {
  2135. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2136. $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument'));
  2137. $form->addSelectLanguage('language', get_lang('SearchFeatureDocumentLanguage'));
  2138. $specific_fields = get_specific_field_list();
  2139. foreach ($specific_fields as $specific_field) {
  2140. $form->addElement('text', $specific_field['code'], $specific_field['name']);
  2141. $filter = [
  2142. 'c_id' => api_get_course_int_id(),
  2143. 'field_id' => $specific_field['id'],
  2144. 'ref_id' => $this->id,
  2145. 'tool_id' => "'".TOOL_QUIZ."'",
  2146. ];
  2147. $values = get_specific_field_values_list($filter, ['value']);
  2148. if (!empty($values)) {
  2149. $arr_str_values = [];
  2150. foreach ($values as $value) {
  2151. $arr_str_values[] = $value['value'];
  2152. }
  2153. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  2154. }
  2155. }
  2156. }
  2157. $skillList = Skill::addSkillsToForm($form, ITEM_TYPE_EXERCISE, $this->iId);
  2158. $extraField = new ExtraField('exercise');
  2159. $extraField->addElements(
  2160. $form,
  2161. $this->iId,
  2162. [], //exclude
  2163. false, // filter
  2164. false, // tag as select
  2165. [], //show only fields
  2166. [], // order fields
  2167. [] // extra data
  2168. );
  2169. $form->addElement('html', '</div>'); //End advanced setting
  2170. $form->addElement('html', '</div>');
  2171. }
  2172. // submit
  2173. if (isset($_GET['exerciseId'])) {
  2174. $form->addButtonSave(get_lang('ModifyExercise'), 'submitExercise');
  2175. } else {
  2176. $form->addButtonUpdate(get_lang('ProcedToQuestions'), 'submitExercise');
  2177. }
  2178. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  2179. // defaults
  2180. if ($type == 'full') {
  2181. // rules
  2182. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  2183. $form->addRule('start_time', get_lang('InvalidDate'), 'datetime');
  2184. $form->addRule('end_time', get_lang('InvalidDate'), 'datetime');
  2185. if ($this->id > 0) {
  2186. $defaults['randomQuestions'] = $this->random;
  2187. $defaults['randomAnswers'] = $this->getRandomAnswers();
  2188. $defaults['exerciseType'] = $this->selectType();
  2189. $defaults['exerciseTitle'] = $this->get_formated_title();
  2190. $defaults['exerciseDescription'] = $this->selectDescription();
  2191. $defaults['exerciseAttempts'] = $this->selectAttempts();
  2192. $defaults['exerciseFeedbackType'] = $this->getFeedbackType();
  2193. $defaults['results_disabled'] = $this->selectResultsDisabled();
  2194. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  2195. $defaults['save_correct_answers'] = $this->getSaveCorrectAnswers();
  2196. $defaults['review_answers'] = $this->review_answers;
  2197. $defaults['randomByCat'] = $this->getRandomByCategory();
  2198. $defaults['text_when_finished'] = $this->getTextWhenFinished();
  2199. $defaults['display_category_name'] = $this->selectDisplayCategoryName();
  2200. $defaults['pass_percentage'] = $this->selectPassPercentage();
  2201. $defaults['question_selection_type'] = $this->getQuestionSelectionType();
  2202. $defaults['hide_question_title'] = $this->getHideQuestionTitle();
  2203. $defaults['show_previous_button'] = $this->showPreviousButton();
  2204. $defaults['exercise_category_id'] = $this->getExerciseCategoryId();
  2205. if (!empty($this->start_time)) {
  2206. $defaults['activate_start_date_check'] = 1;
  2207. }
  2208. if (!empty($this->end_time)) {
  2209. $defaults['activate_end_date_check'] = 1;
  2210. }
  2211. $defaults['start_time'] = !empty($this->start_time) ? api_get_local_time($this->start_time) : date('Y-m-d 12:00:00');
  2212. $defaults['end_time'] = !empty($this->end_time) ? api_get_local_time($this->end_time) : date('Y-m-d 12:00:00', time() + 84600);
  2213. // Get expired time
  2214. if ($this->expired_time != '0') {
  2215. $defaults['enabletimercontrol'] = 1;
  2216. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  2217. } else {
  2218. $defaults['enabletimercontroltotalminutes'] = 0;
  2219. }
  2220. $defaults['skills'] = array_keys($skillList);
  2221. $defaults['notifications'] = $this->getNotifications();
  2222. } else {
  2223. $defaults['exerciseType'] = 2;
  2224. $defaults['exerciseAttempts'] = 0;
  2225. $defaults['randomQuestions'] = 0;
  2226. $defaults['randomAnswers'] = 0;
  2227. $defaults['exerciseDescription'] = '';
  2228. $defaults['exerciseFeedbackType'] = 0;
  2229. $defaults['results_disabled'] = 0;
  2230. $defaults['randomByCat'] = 0;
  2231. $defaults['text_when_finished'] = '';
  2232. $defaults['start_time'] = date('Y-m-d 12:00:00');
  2233. $defaults['display_category_name'] = 1;
  2234. $defaults['end_time'] = date('Y-m-d 12:00:00', time() + 84600);
  2235. $defaults['pass_percentage'] = '';
  2236. $defaults['end_button'] = $this->selectEndButton();
  2237. $defaults['question_selection_type'] = 1;
  2238. $defaults['hide_question_title'] = 0;
  2239. $defaults['show_previous_button'] = 1;
  2240. $defaults['on_success_message'] = null;
  2241. $defaults['on_failed_message'] = null;
  2242. }
  2243. } else {
  2244. $defaults['exerciseTitle'] = $this->selectTitle();
  2245. $defaults['exerciseDescription'] = $this->selectDescription();
  2246. }
  2247. if (api_get_setting('search_enabled') === 'true') {
  2248. $defaults['index_document'] = 'checked="checked"';
  2249. }
  2250. $this->setPageResultConfigurationDefaults($defaults);
  2251. $form->setDefaults($defaults);
  2252. // Freeze some elements.
  2253. if ($this->id != 0 && $this->edit_exercise_in_lp == false) {
  2254. $elementsToFreeze = [
  2255. 'randomQuestions',
  2256. //'randomByCat',
  2257. 'exerciseAttempts',
  2258. 'propagate_neg',
  2259. 'enabletimercontrol',
  2260. 'review_answers',
  2261. ];
  2262. foreach ($elementsToFreeze as $elementName) {
  2263. /** @var HTML_QuickForm_element $element */
  2264. $element = $form->getElement($elementName);
  2265. $element->freeze();
  2266. }
  2267. }
  2268. }
  2269. /**
  2270. * @param $form
  2271. */
  2272. public function setResultFeedbackGroup(FormValidator $form)
  2273. {
  2274. // Feedback type.
  2275. $feedback = [];
  2276. $feedback[] = $form->createElement(
  2277. 'radio',
  2278. 'exerciseFeedbackType',
  2279. null,
  2280. get_lang('ExerciseAtTheEndOfTheTest'),
  2281. EXERCISE_FEEDBACK_TYPE_END,
  2282. [
  2283. 'id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_END,
  2284. 'onclick' => 'check_feedback()',
  2285. ]
  2286. );
  2287. if (api_get_setting('enable_quiz_scenario') === 'true') {
  2288. // Can't convert a question from one feedback to another
  2289. // if there is more than 1 question already added
  2290. if ($this->selectNbrQuestions() == 0) {
  2291. $feedback[] = $form->createElement(
  2292. 'radio',
  2293. 'exerciseFeedbackType',
  2294. null,
  2295. get_lang('DirectFeedback'),
  2296. EXERCISE_FEEDBACK_TYPE_DIRECT,
  2297. [
  2298. 'id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_DIRECT,
  2299. 'onclick' => 'check_direct_feedback()',
  2300. ]
  2301. );
  2302. }
  2303. }
  2304. $feedback[] = $form->createElement(
  2305. 'radio',
  2306. 'exerciseFeedbackType',
  2307. null,
  2308. get_lang('ExerciseDirectPopUp'),
  2309. EXERCISE_FEEDBACK_TYPE_POPUP,
  2310. ['id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_POPUP, 'onclick' => 'check_direct_feedback()']
  2311. );
  2312. $feedback[] = $form->createElement(
  2313. 'radio',
  2314. 'exerciseFeedbackType',
  2315. null,
  2316. get_lang('NoFeedback'),
  2317. EXERCISE_FEEDBACK_TYPE_EXAM,
  2318. ['id' => 'exerciseType_'.EXERCISE_FEEDBACK_TYPE_EXAM]
  2319. );
  2320. $form->addGroup(
  2321. $feedback,
  2322. null,
  2323. [
  2324. get_lang('FeedbackType'),
  2325. get_lang('FeedbackDisplayOptions'),
  2326. ]
  2327. );
  2328. }
  2329. /**
  2330. * function which process the creation of exercises.
  2331. *
  2332. * @param FormValidator $form
  2333. * @param string
  2334. *
  2335. * @return int c_quiz.iid
  2336. */
  2337. public function processCreation($form, $type = '')
  2338. {
  2339. $this->updateTitle(self::format_title_variable($form->getSubmitValue('exerciseTitle')));
  2340. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  2341. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  2342. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  2343. $this->updateType($form->getSubmitValue('exerciseType'));
  2344. $this->setRandom($form->getSubmitValue('randomQuestions'));
  2345. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  2346. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  2347. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  2348. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  2349. $this->updateSaveCorrectAnswers($form->getSubmitValue('save_correct_answers'));
  2350. $this->updateRandomByCat($form->getSubmitValue('randomByCat'));
  2351. $this->updateTextWhenFinished($form->getSubmitValue('text_when_finished'));
  2352. $this->updateDisplayCategoryName($form->getSubmitValue('display_category_name'));
  2353. $this->updateReviewAnswers($form->getSubmitValue('review_answers'));
  2354. $this->updatePassPercentage($form->getSubmitValue('pass_percentage'));
  2355. $this->updateCategories($form->getSubmitValue('category'));
  2356. $this->updateEndButton($form->getSubmitValue('end_button'));
  2357. $this->setOnSuccessMessage($form->getSubmitValue('on_success_message'));
  2358. $this->setOnFailedMessage($form->getSubmitValue('on_failed_message'));
  2359. $this->updateEmailNotificationTemplate($form->getSubmitValue('email_notification_template'));
  2360. $this->setEmailNotificationTemplateToUser($form->getSubmitValue('email_notification_template_to_user'));
  2361. $this->setNotifyUserByEmail($form->getSubmitValue('notify_user_by_email'));
  2362. $this->setModelType($form->getSubmitValue('model_type'));
  2363. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2364. $this->setHideQuestionTitle($form->getSubmitValue('hide_question_title'));
  2365. $this->sessionId = api_get_session_id();
  2366. $this->setQuestionSelectionType($form->getSubmitValue('question_selection_type'));
  2367. $this->setScoreTypeModel($form->getSubmitValue('score_type_model'));
  2368. $this->setGlobalCategoryId($form->getSubmitValue('global_category_id'));
  2369. $this->setShowPreviousButton($form->getSubmitValue('show_previous_button'));
  2370. $this->setNotifications($form->getSubmitValue('notifications'));
  2371. $this->setExerciseCategoryId($form->getSubmitValue('exercise_category_id'));
  2372. $this->setPageResultConfiguration($form->getSubmitValues());
  2373. $this->start_time = null;
  2374. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  2375. $start_time = $form->getSubmitValue('start_time');
  2376. $this->start_time = api_get_utc_datetime($start_time);
  2377. }
  2378. $this->end_time = null;
  2379. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  2380. $end_time = $form->getSubmitValue('end_time');
  2381. $this->end_time = api_get_utc_datetime($end_time);
  2382. }
  2383. $this->expired_time = 0;
  2384. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  2385. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  2386. if ($this->expired_time == 0) {
  2387. $this->expired_time = $expired_total_time;
  2388. }
  2389. }
  2390. $this->random_answers = 0;
  2391. if ($form->getSubmitValue('randomAnswers') == 1) {
  2392. $this->random_answers = 1;
  2393. }
  2394. // Update title in all LPs that have this quiz added
  2395. if ($form->getSubmitValue('update_title_in_lps') == 1) {
  2396. $courseId = api_get_course_int_id();
  2397. $table = Database::get_course_table(TABLE_LP_ITEM);
  2398. $sql = "SELECT * FROM $table
  2399. WHERE
  2400. c_id = $courseId AND
  2401. item_type = 'quiz' AND
  2402. path = '".$this->id."'
  2403. ";
  2404. $result = Database::query($sql);
  2405. $items = Database::store_result($result);
  2406. if (!empty($items)) {
  2407. foreach ($items as $item) {
  2408. $itemId = $item['iid'];
  2409. $sql = "UPDATE $table SET title = '".$this->title."'
  2410. WHERE iid = $itemId AND c_id = $courseId ";
  2411. Database::query($sql);
  2412. }
  2413. }
  2414. }
  2415. $iId = $this->save($type);
  2416. if (!empty($iId)) {
  2417. $values = $form->getSubmitValues();
  2418. $values['item_id'] = $iId;
  2419. $extraFieldValue = new ExtraFieldValue('exercise');
  2420. $extraFieldValue->saveFieldValues($values);
  2421. Skill::saveSkills($form, ITEM_TYPE_EXERCISE, $iId);
  2422. }
  2423. }
  2424. public function search_engine_save()
  2425. {
  2426. if ($_POST['index_document'] != 1) {
  2427. return;
  2428. }
  2429. $course_id = api_get_course_id();
  2430. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2431. $specific_fields = get_specific_field_list();
  2432. $ic_slide = new IndexableChunk();
  2433. $all_specific_terms = '';
  2434. foreach ($specific_fields as $specific_field) {
  2435. if (isset($_REQUEST[$specific_field['code']])) {
  2436. $sterms = trim($_REQUEST[$specific_field['code']]);
  2437. if (!empty($sterms)) {
  2438. $all_specific_terms .= ' '.$sterms;
  2439. $sterms = explode(',', $sterms);
  2440. foreach ($sterms as $sterm) {
  2441. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2442. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2443. }
  2444. }
  2445. }
  2446. }
  2447. // build the chunk to index
  2448. $ic_slide->addValue("title", $this->exercise);
  2449. $ic_slide->addCourseId($course_id);
  2450. $ic_slide->addToolId(TOOL_QUIZ);
  2451. $xapian_data = [
  2452. SE_COURSE_ID => $course_id,
  2453. SE_TOOL_ID => TOOL_QUIZ,
  2454. SE_DATA => ['type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id],
  2455. SE_USER => (int) api_get_user_id(),
  2456. ];
  2457. $ic_slide->xapian_data = serialize($xapian_data);
  2458. $exercise_description = $all_specific_terms.' '.$this->description;
  2459. $ic_slide->addValue("content", $exercise_description);
  2460. $di = new ChamiloIndexer();
  2461. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2462. $di->connectDb(null, null, $lang);
  2463. $di->addChunk($ic_slide);
  2464. //index and return search engine document id
  2465. $did = $di->index();
  2466. if ($did) {
  2467. // save it to db
  2468. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2469. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2470. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2471. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2472. Database::query($sql);
  2473. }
  2474. }
  2475. public function search_engine_edit()
  2476. {
  2477. // update search enchine and its values table if enabled
  2478. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2479. $course_id = api_get_course_id();
  2480. // actually, it consists on delete terms from db,
  2481. // insert new ones, create a new search engine document, and remove the old one
  2482. // get search_did
  2483. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2484. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  2485. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2486. $res = Database::query($sql);
  2487. if (Database::num_rows($res) > 0) {
  2488. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2489. $se_ref = Database::fetch_array($res);
  2490. $specific_fields = get_specific_field_list();
  2491. $ic_slide = new IndexableChunk();
  2492. $all_specific_terms = '';
  2493. foreach ($specific_fields as $specific_field) {
  2494. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  2495. if (isset($_REQUEST[$specific_field['code']])) {
  2496. $sterms = trim($_REQUEST[$specific_field['code']]);
  2497. $all_specific_terms .= ' '.$sterms;
  2498. $sterms = explode(',', $sterms);
  2499. foreach ($sterms as $sterm) {
  2500. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  2501. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  2502. }
  2503. }
  2504. }
  2505. // build the chunk to index
  2506. $ic_slide->addValue('title', $this->exercise);
  2507. $ic_slide->addCourseId($course_id);
  2508. $ic_slide->addToolId(TOOL_QUIZ);
  2509. $xapian_data = [
  2510. SE_COURSE_ID => $course_id,
  2511. SE_TOOL_ID => TOOL_QUIZ,
  2512. SE_DATA => ['type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int) $this->id],
  2513. SE_USER => (int) api_get_user_id(),
  2514. ];
  2515. $ic_slide->xapian_data = serialize($xapian_data);
  2516. $exercise_description = $all_specific_terms.' '.$this->description;
  2517. $ic_slide->addValue("content", $exercise_description);
  2518. $di = new ChamiloIndexer();
  2519. isset($_POST['language']) ? $lang = Database::escape_string($_POST['language']) : $lang = 'english';
  2520. $di->connectDb(null, null, $lang);
  2521. $di->remove_document($se_ref['search_did']);
  2522. $di->addChunk($ic_slide);
  2523. //index and return search engine document id
  2524. $did = $di->index();
  2525. if ($did) {
  2526. // save it to db
  2527. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  2528. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2529. Database::query($sql);
  2530. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  2531. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  2532. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  2533. Database::query($sql);
  2534. }
  2535. } else {
  2536. $this->search_engine_save();
  2537. }
  2538. }
  2539. }
  2540. public function search_engine_delete()
  2541. {
  2542. // remove from search engine if enabled
  2543. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian')) {
  2544. $course_id = api_get_course_id();
  2545. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  2546. $sql = 'SELECT * FROM %s
  2547. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL
  2548. LIMIT 1';
  2549. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2550. $res = Database::query($sql);
  2551. if (Database::num_rows($res) > 0) {
  2552. $row = Database::fetch_array($res);
  2553. $di = new ChamiloIndexer();
  2554. $di->remove_document($row['search_did']);
  2555. unset($di);
  2556. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  2557. foreach ($this->questionList as $question_i) {
  2558. $sql = 'SELECT type FROM %s WHERE id=%s';
  2559. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  2560. $qres = Database::query($sql);
  2561. if (Database::num_rows($qres) > 0) {
  2562. $qrow = Database::fetch_array($qres);
  2563. $objQuestion = Question::getInstance($qrow['type']);
  2564. $objQuestion = Question::read((int) $question_i);
  2565. $objQuestion->search_engine_edit($this->id, false, true);
  2566. unset($objQuestion);
  2567. }
  2568. }
  2569. }
  2570. $sql = 'DELETE FROM %s
  2571. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL
  2572. LIMIT 1';
  2573. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  2574. Database::query($sql);
  2575. // remove terms from db
  2576. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  2577. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  2578. }
  2579. }
  2580. public function selectExpiredTime()
  2581. {
  2582. return $this->expired_time;
  2583. }
  2584. /**
  2585. * Cleans the student's results only for the Exercise tool (Not from the LP)
  2586. * The LP results are NOT deleted by default, otherwise put $cleanLpTests = true
  2587. * Works with exercises in sessions.
  2588. *
  2589. * @param bool $cleanLpTests
  2590. * @param string $cleanResultBeforeDate
  2591. *
  2592. * @return int quantity of user's exercises deleted
  2593. */
  2594. public function cleanResults($cleanLpTests = false, $cleanResultBeforeDate = null)
  2595. {
  2596. $sessionId = api_get_session_id();
  2597. $table_track_e_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2598. $table_track_e_attempt = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  2599. $sql_where = ' AND
  2600. orig_lp_id = 0 AND
  2601. orig_lp_item_id = 0';
  2602. // if we want to delete results from LP too
  2603. if ($cleanLpTests) {
  2604. $sql_where = '';
  2605. }
  2606. // if we want to delete attempts before date $cleanResultBeforeDate
  2607. // $cleanResultBeforeDate must be a valid UTC-0 date yyyy-mm-dd
  2608. if (!empty($cleanResultBeforeDate)) {
  2609. $cleanResultBeforeDate = Database::escape_string($cleanResultBeforeDate);
  2610. if (api_is_valid_date($cleanResultBeforeDate)) {
  2611. $sql_where .= " AND exe_date <= '$cleanResultBeforeDate' ";
  2612. } else {
  2613. return 0;
  2614. }
  2615. }
  2616. $sql = "SELECT exe_id
  2617. FROM $table_track_e_exercises
  2618. WHERE
  2619. c_id = ".api_get_course_int_id()." AND
  2620. exe_exo_id = ".$this->id." AND
  2621. session_id = ".$sessionId." ".
  2622. $sql_where;
  2623. $result = Database::query($sql);
  2624. $exe_list = Database::store_result($result);
  2625. // deleting TRACK_E_ATTEMPT table
  2626. // check if exe in learning path or not
  2627. $i = 0;
  2628. if (is_array($exe_list) && count($exe_list) > 0) {
  2629. foreach ($exe_list as $item) {
  2630. $sql = "DELETE FROM $table_track_e_attempt
  2631. WHERE exe_id = '".$item['exe_id']."'";
  2632. Database::query($sql);
  2633. $i++;
  2634. }
  2635. }
  2636. // delete TRACK_E_EXERCISES table
  2637. $sql = "DELETE FROM $table_track_e_exercises
  2638. WHERE
  2639. c_id = ".api_get_course_int_id()." AND
  2640. exe_exo_id = ".$this->id." $sql_where AND
  2641. session_id = ".$sessionId;
  2642. Database::query($sql);
  2643. $this->generateStats($this->id, api_get_course_info(), $sessionId);
  2644. Event::addEvent(
  2645. LOG_EXERCISE_RESULT_DELETE,
  2646. LOG_EXERCISE_ID,
  2647. $this->id,
  2648. null,
  2649. null,
  2650. api_get_course_int_id(),
  2651. $sessionId
  2652. );
  2653. return $i;
  2654. }
  2655. /**
  2656. * Copies an exercise (duplicate all questions and answers).
  2657. */
  2658. public function copyExercise()
  2659. {
  2660. $exerciseObject = $this;
  2661. $categories = $exerciseObject->getCategoriesInExercise();
  2662. // Get all questions no matter the order/category settings
  2663. $questionList = $exerciseObject->getQuestionOrderedList();
  2664. // Force the creation of a new exercise
  2665. $exerciseObject->updateTitle($exerciseObject->selectTitle().' - '.get_lang('Copy'));
  2666. // Hides the new exercise
  2667. $exerciseObject->updateStatus(false);
  2668. $exerciseObject->updateId(0);
  2669. $exerciseObject->save();
  2670. $newId = $exerciseObject->selectId();
  2671. if ($newId && !empty($questionList)) {
  2672. // Question creation
  2673. foreach ($questionList as $oldQuestionId) {
  2674. $oldQuestionObj = Question::read($oldQuestionId);
  2675. $newQuestionId = $oldQuestionObj->duplicate();
  2676. if ($newQuestionId) {
  2677. $newQuestionObj = Question::read($newQuestionId);
  2678. if (isset($newQuestionObj) && $newQuestionObj) {
  2679. $newQuestionObj->addToList($newId);
  2680. if (!empty($oldQuestionObj->category)) {
  2681. $newQuestionObj->saveCategory($oldQuestionObj->category);
  2682. }
  2683. // This should be moved to the duplicate function
  2684. $newAnswerObj = new Answer($oldQuestionId);
  2685. $newAnswerObj->read();
  2686. $newAnswerObj->duplicate($newQuestionObj);
  2687. }
  2688. }
  2689. }
  2690. if (!empty($categories)) {
  2691. $newCategoryList = [];
  2692. foreach ($categories as $category) {
  2693. $newCategoryList[$category['category_id']] = $category['count_questions'];
  2694. }
  2695. $exerciseObject->save_categories_in_exercise($newCategoryList);
  2696. }
  2697. }
  2698. }
  2699. /**
  2700. * Changes the exercise status.
  2701. *
  2702. * @param string $status - exercise status
  2703. */
  2704. public function updateStatus($status)
  2705. {
  2706. $this->active = $status;
  2707. }
  2708. /**
  2709. * @param int $lp_id
  2710. * @param int $lp_item_id
  2711. * @param int $lp_item_view_id
  2712. * @param string $status
  2713. *
  2714. * @return array
  2715. */
  2716. public function get_stat_track_exercise_info(
  2717. $lp_id = 0,
  2718. $lp_item_id = 0,
  2719. $lp_item_view_id = 0,
  2720. $status = 'incomplete'
  2721. ) {
  2722. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2723. if (empty($lp_id)) {
  2724. $lp_id = 0;
  2725. }
  2726. if (empty($lp_item_id)) {
  2727. $lp_item_id = 0;
  2728. }
  2729. if (empty($lp_item_view_id)) {
  2730. $lp_item_view_id = 0;
  2731. }
  2732. $condition = ' WHERE exe_exo_id = '."'".$this->id."'".' AND
  2733. exe_user_id = '."'".api_get_user_id()."'".' AND
  2734. c_id = '.api_get_course_int_id().' AND
  2735. status = '."'".Database::escape_string($status)."'".' AND
  2736. orig_lp_id = '."'".$lp_id."'".' AND
  2737. orig_lp_item_id = '."'".$lp_item_id."'".' AND
  2738. orig_lp_item_view_id = '."'".$lp_item_view_id."'".' AND
  2739. session_id = '."'".api_get_session_id()."' LIMIT 1"; //Adding limit 1 just in case
  2740. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  2741. $result = Database::query($sql_track);
  2742. $new_array = [];
  2743. if (Database::num_rows($result) > 0) {
  2744. $new_array = Database::fetch_array($result, 'ASSOC');
  2745. $new_array['num_exe'] = Database::num_rows($result);
  2746. }
  2747. return $new_array;
  2748. }
  2749. /**
  2750. * Saves a test attempt.
  2751. *
  2752. * @param int $clock_expired_time clock_expired_time
  2753. * @param int int lp id
  2754. * @param int int lp item id
  2755. * @param int int lp item_view id
  2756. * @param array $questionList
  2757. * @param float $weight
  2758. *
  2759. * @return int
  2760. */
  2761. public function save_stat_track_exercise_info(
  2762. $clock_expired_time = 0,
  2763. $safe_lp_id = 0,
  2764. $safe_lp_item_id = 0,
  2765. $safe_lp_item_view_id = 0,
  2766. $questionList = [],
  2767. $weight = 0
  2768. ) {
  2769. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  2770. $safe_lp_id = intval($safe_lp_id);
  2771. $safe_lp_item_id = intval($safe_lp_item_id);
  2772. $safe_lp_item_view_id = intval($safe_lp_item_view_id);
  2773. if (empty($safe_lp_id)) {
  2774. $safe_lp_id = 0;
  2775. }
  2776. if (empty($safe_lp_item_id)) {
  2777. $safe_lp_item_id = 0;
  2778. }
  2779. if (empty($clock_expired_time)) {
  2780. $clock_expired_time = null;
  2781. }
  2782. $questionList = array_map('intval', $questionList);
  2783. $params = [
  2784. 'exe_exo_id' => $this->id,
  2785. 'exe_user_id' => api_get_user_id(),
  2786. 'c_id' => api_get_course_int_id(),
  2787. 'status' => 'incomplete',
  2788. 'session_id' => api_get_session_id(),
  2789. 'data_tracking' => implode(',', $questionList),
  2790. 'start_date' => api_get_utc_datetime(),
  2791. 'orig_lp_id' => $safe_lp_id,
  2792. 'orig_lp_item_id' => $safe_lp_item_id,
  2793. 'orig_lp_item_view_id' => $safe_lp_item_view_id,
  2794. 'exe_weighting' => $weight,
  2795. 'user_ip' => Database::escape_string(api_get_real_ip()),
  2796. 'exe_date' => api_get_utc_datetime(),
  2797. 'exe_result' => 0,
  2798. 'steps_counter' => 0,
  2799. 'exe_duration' => 0,
  2800. 'expired_time_control' => $clock_expired_time,
  2801. 'questions_to_check' => '',
  2802. ];
  2803. $id = Database::insert($track_exercises, $params);
  2804. return $id;
  2805. }
  2806. /**
  2807. * @param int $question_id
  2808. * @param int $questionNum
  2809. * @param array $questions_in_media
  2810. * @param string $currentAnswer
  2811. * @param array $myRemindList
  2812. *
  2813. * @return string
  2814. */
  2815. public function show_button(
  2816. $question_id,
  2817. $questionNum,
  2818. $questions_in_media = [],
  2819. $currentAnswer = '',
  2820. $myRemindList = []
  2821. ) {
  2822. global $origin, $safe_lp_id, $safe_lp_item_id, $safe_lp_item_view_id;
  2823. $nbrQuestions = $this->getQuestionCount();
  2824. $buttonList = [];
  2825. $html = $label = '';
  2826. $hotspot_get = isset($_POST['hotspot']) ? Security::remove_XSS($_POST['hotspot']) : null;
  2827. if (in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP]) &&
  2828. $this->type == ONE_PER_PAGE
  2829. ) {
  2830. $urlTitle = get_lang('ContinueTest');
  2831. if ($questionNum == count($this->questionList)) {
  2832. $urlTitle = get_lang('EndTest');
  2833. }
  2834. $html .= Display::url(
  2835. $urlTitle,
  2836. api_get_path(WEB_CODE_PATH).'exercise/exercise_submit_modal.php?'.http_build_query([
  2837. 'learnpath_id' => $safe_lp_id,
  2838. 'learnpath_item_id' => $safe_lp_item_id,
  2839. 'learnpath_item_view_id' => $safe_lp_item_view_id,
  2840. 'origin' => $origin,
  2841. 'hotspot' => $hotspot_get,
  2842. 'nbrQuestions' => $nbrQuestions,
  2843. 'num' => $questionNum,
  2844. 'exerciseType' => $this->type,
  2845. 'exerciseId' => $this->id,
  2846. 'reminder' => empty($myRemindList) ? null : 2,
  2847. ]),
  2848. [
  2849. 'class' => 'ajax btn btn-default',
  2850. 'data-title' => Security::remove_XSS(get_lang('Comment')),
  2851. 'data-size' => 'md',
  2852. ]
  2853. );
  2854. $html .= '<br />';
  2855. } else {
  2856. // User
  2857. if (api_is_allowed_to_session_edit()) {
  2858. $endReminderValue = false;
  2859. if (!empty($myRemindList)) {
  2860. $endValue = end($myRemindList);
  2861. if ($endValue == $question_id) {
  2862. $endReminderValue = true;
  2863. }
  2864. }
  2865. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum || $endReminderValue) {
  2866. if ($this->review_answers) {
  2867. $label = get_lang('ReviewQuestions');
  2868. $class = 'btn btn-success';
  2869. } else {
  2870. $label = get_lang('EndTest');
  2871. $class = 'btn btn-warning';
  2872. }
  2873. } else {
  2874. $label = get_lang('NextQuestion');
  2875. $class = 'btn btn-primary';
  2876. }
  2877. // used to select it with jquery
  2878. $class .= ' question-validate-btn';
  2879. if ($this->type == ONE_PER_PAGE) {
  2880. if ($questionNum != 1) {
  2881. if ($this->showPreviousButton()) {
  2882. $prev_question = $questionNum - 2;
  2883. $showPreview = true;
  2884. if (!empty($myRemindList)) {
  2885. $beforeId = null;
  2886. for ($i = 0; $i < count($myRemindList); $i++) {
  2887. if (isset($myRemindList[$i]) && $myRemindList[$i] == $question_id) {
  2888. $beforeId = isset($myRemindList[$i - 1]) ? $myRemindList[$i - 1] : null;
  2889. break;
  2890. }
  2891. }
  2892. if (empty($beforeId)) {
  2893. $showPreview = false;
  2894. } else {
  2895. $num = 0;
  2896. foreach ($this->questionList as $originalQuestionId) {
  2897. if ($originalQuestionId == $beforeId) {
  2898. break;
  2899. }
  2900. $num++;
  2901. }
  2902. $prev_question = $num;
  2903. }
  2904. }
  2905. if ($showPreview) {
  2906. $buttonList[] = Display::button(
  2907. 'previous_question_and_save',
  2908. get_lang('PreviousQuestion'),
  2909. [
  2910. 'type' => 'button',
  2911. 'class' => 'btn btn-default',
  2912. 'data-prev' => $prev_question,
  2913. 'data-question' => $question_id,
  2914. ]
  2915. );
  2916. }
  2917. }
  2918. }
  2919. // Next question
  2920. if (!empty($questions_in_media)) {
  2921. $buttonList[] = Display::button(
  2922. 'save_question_list',
  2923. $label,
  2924. [
  2925. 'type' => 'button',
  2926. 'class' => $class,
  2927. 'data-list' => implode(",", $questions_in_media),
  2928. ]
  2929. );
  2930. } else {
  2931. $buttonList[] = Display::button(
  2932. 'save_now',
  2933. $label,
  2934. ['type' => 'button', 'class' => $class, 'data-question' => $question_id]
  2935. );
  2936. }
  2937. $buttonList[] = '<span id="save_for_now_'.$question_id.'" class="exercise_save_mini_message"></span>&nbsp;';
  2938. $html .= implode(PHP_EOL, $buttonList);
  2939. } else {
  2940. if ($this->review_answers) {
  2941. $all_label = get_lang('ReviewQuestions');
  2942. $class = 'btn btn-success';
  2943. } else {
  2944. $all_label = get_lang('EndTest');
  2945. $class = 'btn btn-warning';
  2946. }
  2947. // used to select it with jquery
  2948. $class .= ' question-validate-btn';
  2949. $buttonList[] = Display::button(
  2950. 'validate_all',
  2951. $all_label,
  2952. ['type' => 'button', 'class' => $class]
  2953. );
  2954. $buttonList[] = '&nbsp;'.Display::span(null, ['id' => 'save_all_response']);
  2955. $html .= implode(PHP_EOL, $buttonList);
  2956. }
  2957. }
  2958. }
  2959. return $html;
  2960. }
  2961. /**
  2962. * @param int $timeLeft in seconds
  2963. * @param string $url
  2964. *
  2965. * @return string
  2966. */
  2967. public function showSimpleTimeControl($timeLeft, $url = '')
  2968. {
  2969. $timeLeft = (int) $timeLeft;
  2970. return "<script>
  2971. function openClockWarning() {
  2972. $('#clock_warning').dialog({
  2973. modal:true,
  2974. height:320,
  2975. width:550,
  2976. closeOnEscape: false,
  2977. resizable: false,
  2978. buttons: {
  2979. '".addslashes(get_lang('Close'))."': function() {
  2980. $('#clock_warning').dialog('close');
  2981. }
  2982. },
  2983. close: function() {
  2984. window.location.href = '$url';
  2985. }
  2986. });
  2987. $('#clock_warning').dialog('open');
  2988. $('#counter_to_redirect').epiclock({
  2989. mode: $.epiclock.modes.countdown,
  2990. offset: {seconds: 5},
  2991. format: 's'
  2992. }).bind('timer', function () {
  2993. window.location.href = '$url';
  2994. });
  2995. }
  2996. function onExpiredTimeExercise() {
  2997. $('#wrapper-clock').hide();
  2998. $('#expired-message-id').show();
  2999. // Fixes bug #5263
  3000. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  3001. openClockWarning();
  3002. }
  3003. $(function() {
  3004. // time in seconds when using minutes there are some seconds lost
  3005. var time_left = parseInt(".$timeLeft.");
  3006. $('#exercise_clock_warning').epiclock({
  3007. mode: $.epiclock.modes.countdown,
  3008. offset: {seconds: time_left},
  3009. format: 'x:i:s',
  3010. renderer: 'minute'
  3011. }).bind('timer', function () {
  3012. onExpiredTimeExercise();
  3013. });
  3014. $('#submit_save').click(function () {});
  3015. });
  3016. </script>";
  3017. }
  3018. /**
  3019. * So the time control will work.
  3020. *
  3021. * @param int $timeLeft
  3022. *
  3023. * @return string
  3024. */
  3025. public function showTimeControlJS($timeLeft)
  3026. {
  3027. $timeLeft = (int) $timeLeft;
  3028. $script = 'redirectExerciseToResult();';
  3029. if ($this->type == ALL_ON_ONE_PAGE) {
  3030. $script = "save_now_all('validate');";
  3031. }
  3032. return "<script>
  3033. function openClockWarning() {
  3034. $('#clock_warning').dialog({
  3035. modal:true,
  3036. height:320,
  3037. width:550,
  3038. closeOnEscape: false,
  3039. resizable: false,
  3040. buttons: {
  3041. '".addslashes(get_lang('EndTest'))."': function() {
  3042. $('#clock_warning').dialog('close');
  3043. }
  3044. },
  3045. close: function() {
  3046. send_form();
  3047. }
  3048. });
  3049. $('#clock_warning').dialog('open');
  3050. $('#counter_to_redirect').epiclock({
  3051. mode: $.epiclock.modes.countdown,
  3052. offset: {seconds: 5},
  3053. format: 's'
  3054. }).bind('timer', function () {
  3055. send_form();
  3056. });
  3057. }
  3058. function send_form() {
  3059. if ($('#exercise_form').length) {
  3060. $script
  3061. } else {
  3062. // In exercise_reminder.php
  3063. final_submit();
  3064. }
  3065. }
  3066. function onExpiredTimeExercise() {
  3067. $('#wrapper-clock').hide();
  3068. $('#expired-message-id').show();
  3069. // Fixes bug #5263
  3070. $('#num_current_id').attr('value', '".$this->selectNbrQuestions()."');
  3071. openClockWarning();
  3072. }
  3073. $(function() {
  3074. // time in seconds when using minutes there are some seconds lost
  3075. var time_left = parseInt(".$timeLeft.");
  3076. $('#exercise_clock_warning').epiclock({
  3077. mode: $.epiclock.modes.countdown,
  3078. offset: {seconds: time_left},
  3079. format: 'x:i:s',
  3080. renderer: 'minute'
  3081. }).bind('timer', function () {
  3082. onExpiredTimeExercise();
  3083. });
  3084. $('#submit_save').click(function () {});
  3085. });
  3086. </script>";
  3087. }
  3088. /**
  3089. * This function was originally found in the exercise_show.php.
  3090. *
  3091. * @param int $exeId
  3092. * @param int $questionId
  3093. * @param mixed $choice the user-selected option
  3094. * @param string $from function is called from 'exercise_show' or
  3095. * 'exercise_result'
  3096. * @param array $exerciseResultCoordinates the hotspot coordinates $hotspot[$question_id] =
  3097. * coordinates
  3098. * @param bool $saved_results save results in the DB or just show the reponse
  3099. * @param bool $from_database gets information from DB or from the current selection
  3100. * @param bool $show_result show results or not
  3101. * @param int $propagate_neg
  3102. * @param array $hotspot_delineation_result
  3103. * @param bool $showTotalScoreAndUserChoicesInLastAttempt
  3104. * @param bool $updateResults
  3105. *
  3106. * @todo reduce parameters of this function
  3107. *
  3108. * @return string html code
  3109. */
  3110. public function manage_answer(
  3111. $exeId,
  3112. $questionId,
  3113. $choice,
  3114. $from = 'exercise_show',
  3115. $exerciseResultCoordinates = [],
  3116. $saved_results = true,
  3117. $from_database = false,
  3118. $show_result = true,
  3119. $propagate_neg = 0,
  3120. $hotspot_delineation_result = [],
  3121. $showTotalScoreAndUserChoicesInLastAttempt = true,
  3122. $updateResults = false
  3123. ) {
  3124. $debug = false;
  3125. //needed in order to use in the exercise_attempt() for the time
  3126. global $learnpath_id, $learnpath_item_id;
  3127. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  3128. $em = Database::getManager();
  3129. $feedback_type = $this->getFeedbackType();
  3130. $results_disabled = $this->selectResultsDisabled();
  3131. if ($debug) {
  3132. error_log("<------ manage_answer ------> ");
  3133. error_log('exe_id: '.$exeId);
  3134. error_log('$from: '.$from);
  3135. error_log('$saved_results: '.intval($saved_results));
  3136. error_log('$from_database: '.intval($from_database));
  3137. error_log('$show_result: '.intval($show_result));
  3138. error_log('$propagate_neg: '.$propagate_neg);
  3139. error_log('$exerciseResultCoordinates: '.print_r($exerciseResultCoordinates, 1));
  3140. error_log('$hotspot_delineation_result: '.print_r($hotspot_delineation_result, 1));
  3141. error_log('$learnpath_id: '.$learnpath_id);
  3142. error_log('$learnpath_item_id: '.$learnpath_item_id);
  3143. error_log('$choice: '.print_r($choice, 1));
  3144. }
  3145. $final_overlap = 0;
  3146. $final_missing = 0;
  3147. $final_excess = 0;
  3148. $overlap_color = 0;
  3149. $missing_color = 0;
  3150. $excess_color = 0;
  3151. $threadhold1 = 0;
  3152. $threadhold2 = 0;
  3153. $threadhold3 = 0;
  3154. $arrques = null;
  3155. $arrans = null;
  3156. $studentChoice = null;
  3157. $expectedAnswer = '';
  3158. $calculatedChoice = '';
  3159. $calculatedStatus = '';
  3160. $questionId = (int) $questionId;
  3161. $exeId = (int) $exeId;
  3162. $TBL_TRACK_ATTEMPT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  3163. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  3164. // Creates a temporary Question object
  3165. $course_id = $this->course_id;
  3166. $objQuestionTmp = Question::read($questionId, $this->course);
  3167. if ($objQuestionTmp === false) {
  3168. return false;
  3169. }
  3170. $questionName = $objQuestionTmp->selectTitle();
  3171. $questionWeighting = $objQuestionTmp->selectWeighting();
  3172. $answerType = $objQuestionTmp->selectType();
  3173. $quesId = $objQuestionTmp->selectId();
  3174. $extra = $objQuestionTmp->extra;
  3175. $next = 1; //not for now
  3176. $totalWeighting = 0;
  3177. $totalScore = 0;
  3178. // Extra information of the question
  3179. if ((
  3180. $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  3181. $answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY
  3182. )
  3183. && !empty($extra)
  3184. ) {
  3185. $extra = explode(':', $extra);
  3186. if ($debug) {
  3187. error_log(print_r($extra, 1));
  3188. }
  3189. // Fixes problems with negatives values using intval
  3190. $true_score = floatval(trim($extra[0]));
  3191. $false_score = floatval(trim($extra[1]));
  3192. $doubt_score = floatval(trim($extra[2]));
  3193. }
  3194. // Construction of the Answer object
  3195. $objAnswerTmp = new Answer($questionId, $course_id);
  3196. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  3197. if ($debug) {
  3198. error_log('Count of answers: '.$nbrAnswers);
  3199. error_log('$answerType: '.$answerType);
  3200. }
  3201. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  3202. $choiceTmp = $choice;
  3203. $choice = isset($choiceTmp['choice']) ? $choiceTmp['choice'] : '';
  3204. $choiceDegreeCertainty = isset($choiceTmp['choiceDegreeCertainty']) ? $choiceTmp['choiceDegreeCertainty'] : '';
  3205. }
  3206. if ($answerType == FREE_ANSWER ||
  3207. $answerType == ORAL_EXPRESSION ||
  3208. $answerType == CALCULATED_ANSWER ||
  3209. $answerType == ANNOTATION
  3210. ) {
  3211. $nbrAnswers = 1;
  3212. }
  3213. $generatedFile = '';
  3214. if ($answerType == ORAL_EXPRESSION) {
  3215. $exe_info = Event::get_exercise_results_by_attempt($exeId);
  3216. $exe_info = isset($exe_info[$exeId]) ? $exe_info[$exeId] : null;
  3217. $objQuestionTmp->initFile(
  3218. api_get_session_id(),
  3219. isset($exe_info['exe_user_id']) ? $exe_info['exe_user_id'] : api_get_user_id(),
  3220. isset($exe_info['exe_exo_id']) ? $exe_info['exe_exo_id'] : $this->id,
  3221. isset($exe_info['exe_id']) ? $exe_info['exe_id'] : $exeId
  3222. );
  3223. // Probably this attempt came in an exercise all question by page
  3224. if ($feedback_type == 0) {
  3225. $objQuestionTmp->replaceWithRealExe($exeId);
  3226. }
  3227. $generatedFile = $objQuestionTmp->getFileUrl();
  3228. }
  3229. $user_answer = '';
  3230. // Get answer list for matching
  3231. $sql = "SELECT id_auto, id, answer
  3232. FROM $table_ans
  3233. WHERE c_id = $course_id AND question_id = $questionId";
  3234. $res_answer = Database::query($sql);
  3235. $answerMatching = [];
  3236. while ($real_answer = Database::fetch_array($res_answer)) {
  3237. $answerMatching[$real_answer['id_auto']] = $real_answer['answer'];
  3238. }
  3239. $real_answers = [];
  3240. $quiz_question_options = Question::readQuestionOption(
  3241. $questionId,
  3242. $course_id
  3243. );
  3244. $organs_at_risk_hit = 0;
  3245. $questionScore = 0;
  3246. $answer_correct_array = [];
  3247. $orderedHotspots = [];
  3248. if ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  3249. $orderedHotspots = $em->getRepository('ChamiloCoreBundle:TrackEHotspot')->findBy(
  3250. [
  3251. 'hotspotQuestionId' => $questionId,
  3252. 'cId' => $course_id,
  3253. 'hotspotExeId' => $exeId,
  3254. ],
  3255. ['hotspotAnswerId' => 'ASC']
  3256. );
  3257. }
  3258. if ($debug) {
  3259. error_log('Start answer loop ');
  3260. }
  3261. $userAnsweredQuestion = false;
  3262. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  3263. $answer = $objAnswerTmp->selectAnswer($answerId);
  3264. $answerComment = $objAnswerTmp->selectComment($answerId);
  3265. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  3266. $answerWeighting = (float) $objAnswerTmp->selectWeighting($answerId);
  3267. $answerAutoId = $objAnswerTmp->selectAutoId($answerId);
  3268. $answerIid = isset($objAnswerTmp->iid[$answerId]) ? $objAnswerTmp->iid[$answerId] : '';
  3269. $answer_correct_array[$answerId] = (bool) $answerCorrect;
  3270. if ($debug) {
  3271. error_log("answer auto id: $answerAutoId ");
  3272. error_log("answer correct: $answerCorrect ");
  3273. }
  3274. // Delineation
  3275. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  3276. $answer_delineation_destination = $objAnswerTmp->selectDestination(1);
  3277. switch ($answerType) {
  3278. case UNIQUE_ANSWER:
  3279. case UNIQUE_ANSWER_IMAGE:
  3280. case UNIQUE_ANSWER_NO_OPTION:
  3281. case READING_COMPREHENSION:
  3282. if ($from_database) {
  3283. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3284. WHERE
  3285. exe_id = $exeId AND
  3286. question_id = $questionId";
  3287. $result = Database::query($sql);
  3288. $choice = Database::result($result, 0, 'answer');
  3289. if ($userAnsweredQuestion === false) {
  3290. $userAnsweredQuestion = !empty($choice);
  3291. }
  3292. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3293. if ($studentChoice) {
  3294. $questionScore += $answerWeighting;
  3295. $totalScore += $answerWeighting;
  3296. }
  3297. } else {
  3298. $studentChoice = $choice == $answerAutoId ? 1 : 0;
  3299. if ($studentChoice) {
  3300. $questionScore += $answerWeighting;
  3301. $totalScore += $answerWeighting;
  3302. }
  3303. }
  3304. break;
  3305. case MULTIPLE_ANSWER_TRUE_FALSE:
  3306. if ($from_database) {
  3307. $choice = [];
  3308. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3309. WHERE
  3310. exe_id = $exeId AND
  3311. question_id = ".$questionId;
  3312. $result = Database::query($sql);
  3313. while ($row = Database::fetch_array($result)) {
  3314. $values = explode(':', $row['answer']);
  3315. $my_answer_id = isset($values[0]) ? $values[0] : '';
  3316. $option = isset($values[1]) ? $values[1] : '';
  3317. $choice[$my_answer_id] = $option;
  3318. }
  3319. }
  3320. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3321. if (!empty($studentChoice)) {
  3322. if ($studentChoice == $answerCorrect) {
  3323. $questionScore += $true_score;
  3324. } else {
  3325. if ($quiz_question_options[$studentChoice]['name'] == "Don't know" ||
  3326. $quiz_question_options[$studentChoice]['name'] == "DoubtScore"
  3327. ) {
  3328. $questionScore += $doubt_score;
  3329. } else {
  3330. $questionScore += $false_score;
  3331. }
  3332. }
  3333. } else {
  3334. // If no result then the user just hit don't know
  3335. $studentChoice = 3;
  3336. $questionScore += $doubt_score;
  3337. }
  3338. $totalScore = $questionScore;
  3339. break;
  3340. case MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY:
  3341. if ($from_database) {
  3342. $choice = [];
  3343. $choiceDegreeCertainty = [];
  3344. $sql = "SELECT answer
  3345. FROM $TBL_TRACK_ATTEMPT
  3346. WHERE
  3347. exe_id = $exeId AND question_id = $questionId";
  3348. $result = Database::query($sql);
  3349. while ($row = Database::fetch_array($result)) {
  3350. $ind = $row['answer'];
  3351. $values = explode(':', $ind);
  3352. $myAnswerId = $values[0];
  3353. $option = $values[1];
  3354. $percent = $values[2];
  3355. $choice[$myAnswerId] = $option;
  3356. $choiceDegreeCertainty[$myAnswerId] = $percent;
  3357. }
  3358. }
  3359. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3360. $studentChoiceDegree = isset($choiceDegreeCertainty[$answerAutoId]) ?
  3361. $choiceDegreeCertainty[$answerAutoId] : null;
  3362. // student score update
  3363. if (!empty($studentChoice)) {
  3364. if ($studentChoice == $answerCorrect) {
  3365. // correct answer and student is Unsure or PrettySur
  3366. if (isset($quiz_question_options[$studentChoiceDegree]) &&
  3367. $quiz_question_options[$studentChoiceDegree]['position'] >= 3 &&
  3368. $quiz_question_options[$studentChoiceDegree]['position'] < 9
  3369. ) {
  3370. $questionScore += $true_score;
  3371. } else {
  3372. // student ignore correct answer
  3373. $questionScore += $doubt_score;
  3374. }
  3375. } else {
  3376. // false answer and student is Unsure or PrettySur
  3377. if ($quiz_question_options[$studentChoiceDegree]['position'] >= 3
  3378. && $quiz_question_options[$studentChoiceDegree]['position'] < 9) {
  3379. $questionScore += $false_score;
  3380. } else {
  3381. // student ignore correct answer
  3382. $questionScore += $doubt_score;
  3383. }
  3384. }
  3385. }
  3386. $totalScore = $questionScore;
  3387. break;
  3388. case MULTIPLE_ANSWER: //2
  3389. if ($from_database) {
  3390. $choice = [];
  3391. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3392. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3393. $resultans = Database::query($sql);
  3394. while ($row = Database::fetch_array($resultans)) {
  3395. $choice[$row['answer']] = 1;
  3396. }
  3397. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3398. $real_answers[$answerId] = (bool) $studentChoice;
  3399. if ($studentChoice) {
  3400. $questionScore += $answerWeighting;
  3401. }
  3402. } else {
  3403. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3404. $real_answers[$answerId] = (bool) $studentChoice;
  3405. if (isset($studentChoice)) {
  3406. $questionScore += $answerWeighting;
  3407. }
  3408. }
  3409. $totalScore += $answerWeighting;
  3410. if ($debug) {
  3411. error_log("studentChoice: $studentChoice");
  3412. }
  3413. break;
  3414. case GLOBAL_MULTIPLE_ANSWER:
  3415. if ($from_database) {
  3416. $choice = [];
  3417. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3418. WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  3419. $resultans = Database::query($sql);
  3420. while ($row = Database::fetch_array($resultans)) {
  3421. $choice[$row['answer']] = 1;
  3422. }
  3423. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3424. $real_answers[$answerId] = (bool) $studentChoice;
  3425. if ($studentChoice) {
  3426. $questionScore += $answerWeighting;
  3427. }
  3428. } else {
  3429. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3430. if (isset($studentChoice)) {
  3431. $questionScore += $answerWeighting;
  3432. }
  3433. $real_answers[$answerId] = (bool) $studentChoice;
  3434. }
  3435. $totalScore += $answerWeighting;
  3436. if ($debug) {
  3437. error_log("studentChoice: $studentChoice");
  3438. }
  3439. break;
  3440. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  3441. if ($from_database) {
  3442. $choice = [];
  3443. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3444. WHERE exe_id = $exeId AND question_id= ".$questionId;
  3445. $resultans = Database::query($sql);
  3446. while ($row = Database::fetch_array($resultans)) {
  3447. $result = explode(':', $row['answer']);
  3448. if (isset($result[0])) {
  3449. $my_answer_id = isset($result[0]) ? $result[0] : '';
  3450. $option = isset($result[1]) ? $result[1] : '';
  3451. $choice[$my_answer_id] = $option;
  3452. }
  3453. }
  3454. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3455. $real_answers[$answerId] = false;
  3456. if ($answerCorrect == $studentChoice) {
  3457. $real_answers[$answerId] = true;
  3458. }
  3459. } else {
  3460. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : '';
  3461. $real_answers[$answerId] = false;
  3462. if ($answerCorrect == $studentChoice) {
  3463. $real_answers[$answerId] = true;
  3464. }
  3465. }
  3466. break;
  3467. case MULTIPLE_ANSWER_COMBINATION:
  3468. if ($from_database) {
  3469. $choice = [];
  3470. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3471. WHERE exe_id = $exeId AND question_id = $questionId";
  3472. $resultans = Database::query($sql);
  3473. while ($row = Database::fetch_array($resultans)) {
  3474. $choice[$row['answer']] = 1;
  3475. }
  3476. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3477. if ($answerCorrect == 1) {
  3478. $real_answers[$answerId] = false;
  3479. if ($studentChoice) {
  3480. $real_answers[$answerId] = true;
  3481. }
  3482. } else {
  3483. $real_answers[$answerId] = true;
  3484. if ($studentChoice) {
  3485. $real_answers[$answerId] = false;
  3486. }
  3487. }
  3488. } else {
  3489. $studentChoice = isset($choice[$answerAutoId]) ? $choice[$answerAutoId] : null;
  3490. if ($answerCorrect == 1) {
  3491. $real_answers[$answerId] = false;
  3492. if ($studentChoice) {
  3493. $real_answers[$answerId] = true;
  3494. }
  3495. } else {
  3496. $real_answers[$answerId] = true;
  3497. if ($studentChoice) {
  3498. $real_answers[$answerId] = false;
  3499. }
  3500. }
  3501. }
  3502. break;
  3503. case FILL_IN_BLANKS:
  3504. $str = '';
  3505. $answerFromDatabase = '';
  3506. if ($from_database) {
  3507. $sql = "SELECT answer
  3508. FROM $TBL_TRACK_ATTEMPT
  3509. WHERE
  3510. exe_id = $exeId AND
  3511. question_id= ".intval($questionId);
  3512. $result = Database::query($sql);
  3513. if ($debug) {
  3514. error_log($sql);
  3515. }
  3516. $str = $answerFromDatabase = Database::result($result, 0, 'answer');
  3517. }
  3518. //ofaj
  3519. if ($saved_results == false && strpos($answerFromDatabase, 'font color') !== false) {
  3520. // the question is encoded like this
  3521. // [A] B [C] D [E] F::10,10,10@1
  3522. // number 1 before the "@" means that is a switchable fill in blank question
  3523. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  3524. // means that is a normal fill blank question
  3525. // first we explode the "::"
  3526. $pre_array = explode('::', $answer);
  3527. // is switchable fill blank or not
  3528. $last = count($pre_array) - 1;
  3529. $is_set_switchable = explode('@', $pre_array[$last]);
  3530. $switchable_answer_set = false;
  3531. if (isset($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  3532. $switchable_answer_set = true;
  3533. }
  3534. $answer = '';
  3535. for ($k = 0; $k < $last; $k++) {
  3536. $answer .= $pre_array[$k];
  3537. }
  3538. // splits weightings that are joined with a comma
  3539. $answerWeighting = explode(',', $is_set_switchable[0]);
  3540. // we save the answer because it will be modified
  3541. $temp = $answer;
  3542. $answer = '';
  3543. $j = 0;
  3544. //initialise answer tags
  3545. $user_tags = $correct_tags = $real_text = [];
  3546. // the loop will stop at the end of the text
  3547. while (1) {
  3548. // quits the loop if there are no more blanks (detect '[')
  3549. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3550. // adds the end of the text
  3551. $answer = $temp;
  3552. $real_text[] = $answer;
  3553. break; //no more "blanks", quit the loop
  3554. }
  3555. // adds the piece of text that is before the blank
  3556. //and ends with '[' into a general storage array
  3557. $real_text[] = api_substr($temp, 0, $pos + 1);
  3558. $answer .= api_substr($temp, 0, $pos + 1);
  3559. //take the string remaining (after the last "[" we found)
  3560. $temp = api_substr($temp, $pos + 1);
  3561. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3562. if (($pos = api_strpos($temp, ']')) === false) {
  3563. // adds the end of the text
  3564. $answer .= $temp;
  3565. break;
  3566. }
  3567. if ($from_database) {
  3568. $str = $answerFromDatabase;
  3569. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3570. $str = str_replace('\r\n', '', $str);
  3571. $choice = $arr[1];
  3572. if (isset($choice[$j])) {
  3573. $tmp = api_strrpos($choice[$j], ' / ');
  3574. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3575. $choice[$j] = trim($choice[$j]);
  3576. // Needed to let characters ' and " to work as part of an answer
  3577. $choice[$j] = stripslashes($choice[$j]);
  3578. } else {
  3579. $choice[$j] = null;
  3580. }
  3581. } else {
  3582. // This value is the user input, not escaped while correct answer is escaped by ckeditor
  3583. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3584. }
  3585. $user_tags[] = $choice[$j];
  3586. // Put the contents of the [] answer tag into correct_tags[]
  3587. $correct_tags[] = api_substr($temp, 0, $pos);
  3588. $j++;
  3589. $temp = api_substr($temp, $pos + 1);
  3590. }
  3591. $answer = '';
  3592. $real_correct_tags = $correct_tags;
  3593. $chosen_list = [];
  3594. for ($i = 0; $i < count($real_correct_tags); $i++) {
  3595. if ($i == 0) {
  3596. $answer .= $real_text[0];
  3597. }
  3598. if (!$switchable_answer_set) {
  3599. // Needed to parse ' and " characters
  3600. $user_tags[$i] = stripslashes($user_tags[$i]);
  3601. if ($correct_tags[$i] == $user_tags[$i]) {
  3602. // gives the related weighting to the student
  3603. $questionScore += $answerWeighting[$i];
  3604. // increments total score
  3605. $totalScore += $answerWeighting[$i];
  3606. // adds the word in green at the end of the string
  3607. $answer .= $correct_tags[$i];
  3608. } elseif (!empty($user_tags[$i])) {
  3609. // else if the word entered by the student IS NOT the same as
  3610. // the one defined by the professor
  3611. // adds the word in red at the end of the string, and strikes it
  3612. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3613. } else {
  3614. // adds a tabulation if no word has been typed by the student
  3615. $answer .= ''; // remove &nbsp; that causes issue
  3616. }
  3617. } else {
  3618. // switchable fill in the blanks
  3619. if (in_array($user_tags[$i], $correct_tags)) {
  3620. $chosen_list[] = $user_tags[$i];
  3621. $correct_tags = array_diff($correct_tags, $chosen_list);
  3622. // gives the related weighting to the student
  3623. $questionScore += $answerWeighting[$i];
  3624. // increments total score
  3625. $totalScore += $answerWeighting[$i];
  3626. // adds the word in green at the end of the string
  3627. $answer .= $user_tags[$i];
  3628. } elseif (!empty($user_tags[$i])) {
  3629. // else if the word entered by the student IS NOT the same
  3630. // as the one defined by the professor
  3631. // adds the word in red at the end of the string, and strikes it
  3632. $answer .= '<font color="red"><s>'.$user_tags[$i].'</s></font>';
  3633. } else {
  3634. // adds a tabulation if no word has been typed by the student
  3635. $answer .= ''; // remove &nbsp; that causes issue
  3636. }
  3637. }
  3638. // adds the correct word, followed by ] to close the blank
  3639. $answer .= ' / <font color="green"><b>'.$real_correct_tags[$i].'</b></font>]';
  3640. if (isset($real_text[$i + 1])) {
  3641. $answer .= $real_text[$i + 1];
  3642. }
  3643. }
  3644. } else {
  3645. // insert the student result in the track_e_attempt table, field answer
  3646. // $answer is the answer like in the c_quiz_answer table for the question
  3647. // student data are choice[]
  3648. $listCorrectAnswers = FillBlanks::getAnswerInfo($answer);
  3649. $switchableAnswerSet = $listCorrectAnswers['switchable'];
  3650. $answerWeighting = $listCorrectAnswers['weighting'];
  3651. // user choices is an array $choice
  3652. // get existing user data in n the BDD
  3653. if ($from_database) {
  3654. $listStudentResults = FillBlanks::getAnswerInfo(
  3655. $answerFromDatabase,
  3656. true
  3657. );
  3658. $choice = $listStudentResults['student_answer'];
  3659. }
  3660. // loop other all blanks words
  3661. if (!$switchableAnswerSet) {
  3662. // not switchable answer, must be in the same place than teacher order
  3663. for ($i = 0; $i < count($listCorrectAnswers['words']); $i++) {
  3664. $studentAnswer = isset($choice[$i]) ? $choice[$i] : '';
  3665. $correctAnswer = $listCorrectAnswers['words'][$i];
  3666. if ($debug) {
  3667. error_log("Student answer: $i");
  3668. error_log($studentAnswer);
  3669. }
  3670. // This value is the user input, not escaped while correct answer is escaped by ckeditor
  3671. // Works with cyrillic alphabet and when using ">" chars see #7718 #7610 #7618
  3672. // ENT_QUOTES is used in order to transform ' to &#039;
  3673. if (!$from_database) {
  3674. $studentAnswer = FillBlanks::clearStudentAnswer($studentAnswer);
  3675. if ($debug) {
  3676. error_log("Student answer cleaned:");
  3677. error_log($studentAnswer);
  3678. }
  3679. }
  3680. $isAnswerCorrect = 0;
  3681. if (FillBlanks::isStudentAnswerGood($studentAnswer, $correctAnswer, $from_database)) {
  3682. // gives the related weighting to the student
  3683. $questionScore += $answerWeighting[$i];
  3684. // increments total score
  3685. $totalScore += $answerWeighting[$i];
  3686. $isAnswerCorrect = 1;
  3687. }
  3688. if ($debug) {
  3689. error_log("isAnswerCorrect $i: $isAnswerCorrect");
  3690. }
  3691. $studentAnswerToShow = $studentAnswer;
  3692. $type = FillBlanks::getFillTheBlankAnswerType($correctAnswer);
  3693. if ($debug) {
  3694. error_log("Fill in blank type: $type");
  3695. }
  3696. if ($type == FillBlanks::FILL_THE_BLANK_MENU) {
  3697. $listMenu = FillBlanks::getFillTheBlankMenuAnswers($correctAnswer, false);
  3698. if ($studentAnswer != '') {
  3699. foreach ($listMenu as $item) {
  3700. if (sha1($item) == $studentAnswer) {
  3701. $studentAnswerToShow = $item;
  3702. }
  3703. }
  3704. }
  3705. }
  3706. $listCorrectAnswers['student_answer'][$i] = $studentAnswerToShow;
  3707. $listCorrectAnswers['student_score'][$i] = $isAnswerCorrect;
  3708. }
  3709. } else {
  3710. // switchable answer
  3711. $listStudentAnswerTemp = $choice;
  3712. $listTeacherAnswerTemp = $listCorrectAnswers['words'];
  3713. // for every teacher answer, check if there is a student answer
  3714. for ($i = 0; $i < count($listStudentAnswerTemp); $i++) {
  3715. $studentAnswer = trim($listStudentAnswerTemp[$i]);
  3716. $studentAnswerToShow = $studentAnswer;
  3717. if ($debug) {
  3718. error_log("Student answer: $i");
  3719. error_log($studentAnswer);
  3720. }
  3721. $found = false;
  3722. for ($j = 0; $j < count($listTeacherAnswerTemp); $j++) {
  3723. $correctAnswer = $listTeacherAnswerTemp[$j];
  3724. $type = FillBlanks::getFillTheBlankAnswerType($correctAnswer);
  3725. if ($type == FillBlanks::FILL_THE_BLANK_MENU) {
  3726. $listMenu = FillBlanks::getFillTheBlankMenuAnswers($correctAnswer, false);
  3727. if (!empty($studentAnswer)) {
  3728. foreach ($listMenu as $key => $item) {
  3729. if ($key == $correctAnswer) {
  3730. $studentAnswerToShow = $item;
  3731. break;
  3732. }
  3733. }
  3734. }
  3735. }
  3736. if (!$found) {
  3737. if (FillBlanks::isStudentAnswerGood(
  3738. $studentAnswer,
  3739. $correctAnswer,
  3740. $from_database
  3741. )
  3742. ) {
  3743. $questionScore += $answerWeighting[$i];
  3744. $totalScore += $answerWeighting[$i];
  3745. $listTeacherAnswerTemp[$j] = '';
  3746. $found = true;
  3747. }
  3748. }
  3749. }
  3750. $listCorrectAnswers['student_answer'][$i] = $studentAnswerToShow;
  3751. if (!$found) {
  3752. $listCorrectAnswers['student_score'][$i] = 0;
  3753. } else {
  3754. $listCorrectAnswers['student_score'][$i] = 1;
  3755. }
  3756. }
  3757. }
  3758. $answer = FillBlanks::getAnswerInStudentAttempt($listCorrectAnswers);
  3759. }
  3760. break;
  3761. case CALCULATED_ANSWER:
  3762. $calculatedAnswerList = Session::read('calculatedAnswerId');
  3763. if (!empty($calculatedAnswerList)) {
  3764. $answer = $objAnswerTmp->selectAnswer($calculatedAnswerList[$questionId]);
  3765. $preArray = explode('@@', $answer);
  3766. $last = count($preArray) - 1;
  3767. $answer = '';
  3768. for ($k = 0; $k < $last; $k++) {
  3769. $answer .= $preArray[$k];
  3770. }
  3771. $answerWeighting = [$answerWeighting];
  3772. // we save the answer because it will be modified
  3773. $temp = $answer;
  3774. $answer = '';
  3775. $j = 0;
  3776. // initialise answer tags
  3777. $userTags = $correctTags = $realText = [];
  3778. // the loop will stop at the end of the text
  3779. while (1) {
  3780. // quits the loop if there are no more blanks (detect '[')
  3781. if ($temp == false || ($pos = api_strpos($temp, '[')) === false) {
  3782. // adds the end of the text
  3783. $answer = $temp;
  3784. $realText[] = $answer;
  3785. break; //no more "blanks", quit the loop
  3786. }
  3787. // adds the piece of text that is before the blank
  3788. // and ends with '[' into a general storage array
  3789. $realText[] = api_substr($temp, 0, $pos + 1);
  3790. $answer .= api_substr($temp, 0, $pos + 1);
  3791. // take the string remaining (after the last "[" we found)
  3792. $temp = api_substr($temp, $pos + 1);
  3793. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  3794. if (($pos = api_strpos($temp, ']')) === false) {
  3795. // adds the end of the text
  3796. $answer .= $temp;
  3797. break;
  3798. }
  3799. if ($from_database) {
  3800. $sql = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT."
  3801. WHERE
  3802. exe_id = '".$exeId."' AND
  3803. question_id = ".intval($questionId);
  3804. $result = Database::query($sql);
  3805. $str = Database::result($result, 0, 'answer');
  3806. api_preg_match_all('#\[([^[]*)\]#', $str, $arr);
  3807. $str = str_replace('\r\n', '', $str);
  3808. $choice = $arr[1];
  3809. if (isset($choice[$j])) {
  3810. $tmp = api_strrpos($choice[$j], ' / ');
  3811. if ($tmp) {
  3812. $choice[$j] = api_substr($choice[$j], 0, $tmp);
  3813. } else {
  3814. $tmp = ltrim($tmp, '[');
  3815. $tmp = rtrim($tmp, ']');
  3816. }
  3817. $choice[$j] = trim($choice[$j]);
  3818. // Needed to let characters ' and " to work as part of an answer
  3819. $choice[$j] = stripslashes($choice[$j]);
  3820. } else {
  3821. $choice[$j] = null;
  3822. }
  3823. } else {
  3824. // This value is the user input not escaped while correct answer is escaped by ckeditor
  3825. $choice[$j] = api_htmlentities(trim($choice[$j]));
  3826. }
  3827. $userTags[] = $choice[$j];
  3828. // put the contents of the [] answer tag into correct_tags[]
  3829. $correctTags[] = api_substr($temp, 0, $pos);
  3830. $j++;
  3831. $temp = api_substr($temp, $pos + 1);
  3832. }
  3833. $answer = '';
  3834. $realCorrectTags = $correctTags;
  3835. $calculatedStatus = Display::label(get_lang('Incorrect'), 'danger');
  3836. $expectedAnswer = '';
  3837. $calculatedChoice = '';
  3838. for ($i = 0; $i < count($realCorrectTags); $i++) {
  3839. if ($i == 0) {
  3840. $answer .= $realText[0];
  3841. }
  3842. // Needed to parse ' and " characters
  3843. $userTags[$i] = stripslashes($userTags[$i]);
  3844. if ($correctTags[$i] == $userTags[$i]) {
  3845. // gives the related weighting to the student
  3846. $questionScore += $answerWeighting[$i];
  3847. // increments total score
  3848. $totalScore += $answerWeighting[$i];
  3849. // adds the word in green at the end of the string
  3850. $answer .= $correctTags[$i];
  3851. $calculatedChoice = $correctTags[$i];
  3852. } elseif (!empty($userTags[$i])) {
  3853. // else if the word entered by the student IS NOT the same as
  3854. // the one defined by the professor
  3855. // adds the word in red at the end of the string, and strikes it
  3856. $answer .= '<font color="red"><s>'.$userTags[$i].'</s></font>';
  3857. $calculatedChoice = $userTags[$i];
  3858. } else {
  3859. // adds a tabulation if no word has been typed by the student
  3860. $answer .= ''; // remove &nbsp; that causes issue
  3861. }
  3862. // adds the correct word, followed by ] to close the blank
  3863. if ($this->results_disabled != EXERCISE_FEEDBACK_TYPE_EXAM) {
  3864. $answer .= ' / <font color="green"><b>'.$realCorrectTags[$i].'</b></font>';
  3865. $calculatedStatus = Display::label(get_lang('Correct'), 'success');
  3866. $expectedAnswer = $realCorrectTags[$i];
  3867. }
  3868. $answer .= ']';
  3869. if (isset($realText[$i + 1])) {
  3870. $answer .= $realText[$i + 1];
  3871. }
  3872. }
  3873. } else {
  3874. if ($from_database) {
  3875. $sql = "SELECT *
  3876. FROM $TBL_TRACK_ATTEMPT
  3877. WHERE
  3878. exe_id = $exeId AND
  3879. question_id = $questionId";
  3880. $result = Database::query($sql);
  3881. $resultData = Database::fetch_array($result, 'ASSOC');
  3882. $answer = $resultData['answer'];
  3883. $questionScore = $resultData['marks'];
  3884. }
  3885. }
  3886. break;
  3887. case FREE_ANSWER:
  3888. if ($from_database) {
  3889. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  3890. WHERE
  3891. exe_id = $exeId AND
  3892. question_id= ".$questionId;
  3893. $result = Database::query($sql);
  3894. $data = Database::fetch_array($result);
  3895. $choice = $data['answer'];
  3896. $choice = str_replace('\r\n', '', $choice);
  3897. $choice = stripslashes($choice);
  3898. $questionScore = $data['marks'];
  3899. if ($questionScore == -1) {
  3900. $totalScore += 0;
  3901. } else {
  3902. $totalScore += $questionScore;
  3903. }
  3904. if ($questionScore == '') {
  3905. $questionScore = 0;
  3906. }
  3907. $arrques = $questionName;
  3908. $arrans = $choice;
  3909. } else {
  3910. $studentChoice = $choice;
  3911. if ($studentChoice) {
  3912. //Fixing negative puntation see #2193
  3913. $questionScore = 0;
  3914. $totalScore += 0;
  3915. }
  3916. }
  3917. break;
  3918. case ORAL_EXPRESSION:
  3919. if ($from_database) {
  3920. $query = "SELECT answer, marks
  3921. FROM $TBL_TRACK_ATTEMPT
  3922. WHERE
  3923. exe_id = $exeId AND
  3924. question_id = $questionId
  3925. ";
  3926. $resq = Database::query($query);
  3927. $row = Database::fetch_assoc($resq);
  3928. $choice = $row['answer'];
  3929. $choice = str_replace('\r\n', '', $choice);
  3930. $choice = stripslashes($choice);
  3931. $questionScore = $row['marks'];
  3932. if ($questionScore == -1) {
  3933. $totalScore += 0;
  3934. } else {
  3935. $totalScore += $questionScore;
  3936. }
  3937. $arrques = $questionName;
  3938. $arrans = $choice;
  3939. } else {
  3940. $studentChoice = $choice;
  3941. if ($studentChoice) {
  3942. //Fixing negative puntation see #2193
  3943. $questionScore = 0;
  3944. $totalScore += 0;
  3945. }
  3946. }
  3947. break;
  3948. case DRAGGABLE:
  3949. case MATCHING_DRAGGABLE:
  3950. case MATCHING:
  3951. if ($from_database) {
  3952. $sql = "SELECT id, answer, id_auto
  3953. FROM $table_ans
  3954. WHERE
  3955. c_id = $course_id AND
  3956. question_id = $questionId AND
  3957. correct = 0
  3958. ";
  3959. $result = Database::query($sql);
  3960. // Getting the real answer
  3961. $real_list = [];
  3962. while ($realAnswer = Database::fetch_array($result)) {
  3963. $real_list[$realAnswer['id_auto']] = $realAnswer['answer'];
  3964. }
  3965. $sql = "SELECT id, answer, correct, id_auto, ponderation
  3966. FROM $table_ans
  3967. WHERE
  3968. c_id = $course_id AND
  3969. question_id = $questionId AND
  3970. correct <> 0
  3971. ORDER BY id_auto";
  3972. $result = Database::query($sql);
  3973. $options = [];
  3974. while ($row = Database::fetch_array($result, 'ASSOC')) {
  3975. $options[] = $row;
  3976. }
  3977. $questionScore = 0;
  3978. $counterAnswer = 1;
  3979. foreach ($options as $a_answers) {
  3980. $i_answer_id = $a_answers['id']; //3
  3981. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  3982. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  3983. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  3984. $sql = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  3985. WHERE
  3986. exe_id = '$exeId' AND
  3987. question_id = '$questionId' AND
  3988. position = '$i_answer_id_auto'";
  3989. $result = Database::query($sql);
  3990. $s_user_answer = 0;
  3991. if (Database::num_rows($result) > 0) {
  3992. // rich - good looking
  3993. $s_user_answer = Database::result($result, 0, 0);
  3994. }
  3995. $i_answerWeighting = $a_answers['ponderation'];
  3996. $user_answer = '';
  3997. $status = Display::label(get_lang('Incorrect'), 'danger');
  3998. if (!empty($s_user_answer)) {
  3999. if ($answerType == DRAGGABLE) {
  4000. if ($s_user_answer == $i_answer_correct_answer) {
  4001. $questionScore += $i_answerWeighting;
  4002. $totalScore += $i_answerWeighting;
  4003. $user_answer = Display::label(get_lang('Correct'), 'success');
  4004. if ($this->showExpectedChoice()) {
  4005. $user_answer = $answerMatching[$i_answer_id_auto];
  4006. }
  4007. $status = Display::label(get_lang('Correct'), 'success');
  4008. } else {
  4009. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  4010. if ($this->showExpectedChoice()) {
  4011. $data = $options[$real_list[$s_user_answer] - 1];
  4012. $user_answer = $data['answer'];
  4013. }
  4014. }
  4015. } else {
  4016. if ($s_user_answer == $i_answer_correct_answer) {
  4017. $questionScore += $i_answerWeighting;
  4018. $totalScore += $i_answerWeighting;
  4019. $status = Display::label(get_lang('Correct'), 'success');
  4020. // Try with id
  4021. if (isset($real_list[$i_answer_id])) {
  4022. $user_answer = Display::span(
  4023. $real_list[$i_answer_id],
  4024. ['style' => 'color: #008000; font-weight: bold;']
  4025. );
  4026. }
  4027. // Try with $i_answer_id_auto
  4028. if (empty($user_answer)) {
  4029. if (isset($real_list[$i_answer_id_auto])) {
  4030. $user_answer = Display::span(
  4031. $real_list[$i_answer_id_auto],
  4032. ['style' => 'color: #008000; font-weight: bold;']
  4033. );
  4034. }
  4035. }
  4036. if (isset($real_list[$i_answer_correct_answer])) {
  4037. $user_answer = Display::span(
  4038. $real_list[$i_answer_correct_answer],
  4039. ['style' => 'color: #008000; font-weight: bold;']
  4040. );
  4041. }
  4042. } else {
  4043. $user_answer = Display::span(
  4044. $real_list[$s_user_answer],
  4045. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4046. );
  4047. if ($this->showExpectedChoice()) {
  4048. if (isset($real_list[$s_user_answer])) {
  4049. $user_answer = Display::span($real_list[$s_user_answer]);
  4050. }
  4051. }
  4052. }
  4053. }
  4054. } elseif ($answerType == DRAGGABLE) {
  4055. $user_answer = Display::label(get_lang('Incorrect'), 'danger');
  4056. if ($this->showExpectedChoice()) {
  4057. $user_answer = '';
  4058. }
  4059. } else {
  4060. $user_answer = Display::span(
  4061. get_lang('Incorrect').' &nbsp;',
  4062. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4063. );
  4064. if ($this->showExpectedChoice()) {
  4065. $user_answer = '';
  4066. }
  4067. }
  4068. if ($show_result) {
  4069. if ($this->showExpectedChoice() === false &&
  4070. $showTotalScoreAndUserChoicesInLastAttempt === false
  4071. ) {
  4072. $user_answer = '';
  4073. }
  4074. switch ($answerType) {
  4075. case MATCHING:
  4076. case MATCHING_DRAGGABLE:
  4077. echo '<tr>';
  4078. if (!in_array(
  4079. $this->results_disabled,
  4080. [
  4081. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  4082. ]
  4083. )
  4084. ) {
  4085. echo '<td>'.$s_answer_label.'</td>';
  4086. echo '<td>'.$user_answer.'</td>';
  4087. } else {
  4088. echo '<td>'.$s_answer_label.'</td>';
  4089. $status = Display::label(get_lang('Correct'), 'success');
  4090. }
  4091. if ($this->showExpectedChoice()) {
  4092. if ($this->showExpectedChoiceColumn()) {
  4093. echo '<td>';
  4094. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4095. if (isset($real_list[$i_answer_correct_answer]) &&
  4096. $showTotalScoreAndUserChoicesInLastAttempt == true
  4097. ) {
  4098. echo Display::span(
  4099. $real_list[$i_answer_correct_answer]
  4100. );
  4101. }
  4102. }
  4103. echo '</td>';
  4104. }
  4105. echo '<td>'.$status.'</td>';
  4106. } else {
  4107. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4108. if (isset($real_list[$i_answer_correct_answer]) &&
  4109. $showTotalScoreAndUserChoicesInLastAttempt === true
  4110. ) {
  4111. if ($this->showExpectedChoiceColumn()) {
  4112. echo '<td>';
  4113. echo Display::span(
  4114. $real_list[$i_answer_correct_answer],
  4115. ['style' => 'color: #008000; font-weight: bold;']
  4116. );
  4117. echo '</td>';
  4118. }
  4119. }
  4120. }
  4121. }
  4122. echo '</tr>';
  4123. break;
  4124. case DRAGGABLE:
  4125. if ($showTotalScoreAndUserChoicesInLastAttempt == false) {
  4126. $s_answer_label = '';
  4127. }
  4128. echo '<tr>';
  4129. if ($this->showExpectedChoice()) {
  4130. if (!in_array($this->results_disabled, [
  4131. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  4132. //RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  4133. ])
  4134. ) {
  4135. echo '<td>'.$user_answer.'</td>';
  4136. } else {
  4137. $status = Display::label(get_lang('Correct'), 'success');
  4138. }
  4139. echo '<td>'.$s_answer_label.'</td>';
  4140. echo '<td>'.$status.'</td>';
  4141. } else {
  4142. echo '<td>'.$s_answer_label.'</td>';
  4143. echo '<td>'.$user_answer.'</td>';
  4144. echo '<td>';
  4145. if (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4146. if (isset($real_list[$i_answer_correct_answer]) &&
  4147. $showTotalScoreAndUserChoicesInLastAttempt === true
  4148. ) {
  4149. echo Display::span(
  4150. $real_list[$i_answer_correct_answer],
  4151. ['style' => 'color: #008000; font-weight: bold;']
  4152. );
  4153. }
  4154. }
  4155. echo '</td>';
  4156. }
  4157. echo '</tr>';
  4158. break;
  4159. }
  4160. }
  4161. $counterAnswer++;
  4162. }
  4163. break 2; // break the switch and the "for" condition
  4164. } else {
  4165. if ($answerCorrect) {
  4166. if (isset($choice[$answerAutoId]) &&
  4167. $answerCorrect == $choice[$answerAutoId]
  4168. ) {
  4169. $questionScore += $answerWeighting;
  4170. $totalScore += $answerWeighting;
  4171. $user_answer = Display::span($answerMatching[$choice[$answerAutoId]]);
  4172. } else {
  4173. if (isset($answerMatching[$choice[$answerAutoId]])) {
  4174. $user_answer = Display::span(
  4175. $answerMatching[$choice[$answerAutoId]],
  4176. ['style' => 'color: #FF0000; text-decoration: line-through;']
  4177. );
  4178. }
  4179. }
  4180. $matching[$answerAutoId] = $choice[$answerAutoId];
  4181. }
  4182. }
  4183. break;
  4184. case HOT_SPOT:
  4185. if ($from_database) {
  4186. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4187. // Check auto id
  4188. $sql = "SELECT hotspot_correct
  4189. FROM $TBL_TRACK_HOTSPOT
  4190. WHERE
  4191. hotspot_exe_id = $exeId AND
  4192. hotspot_question_id= $questionId AND
  4193. hotspot_answer_id = $answerAutoId
  4194. ORDER BY hotspot_id ASC";
  4195. $result = Database::query($sql);
  4196. if (Database::num_rows($result)) {
  4197. $studentChoice = Database::result(
  4198. $result,
  4199. 0,
  4200. 'hotspot_correct'
  4201. );
  4202. if ($studentChoice) {
  4203. $questionScore += $answerWeighting;
  4204. $totalScore += $answerWeighting;
  4205. }
  4206. } else {
  4207. // If answer.id is different:
  4208. $sql = "SELECT hotspot_correct
  4209. FROM $TBL_TRACK_HOTSPOT
  4210. WHERE
  4211. hotspot_exe_id = $exeId AND
  4212. hotspot_question_id= $questionId AND
  4213. hotspot_answer_id = ".intval($answerId)."
  4214. ORDER BY hotspot_id ASC";
  4215. $result = Database::query($sql);
  4216. if (Database::num_rows($result)) {
  4217. $studentChoice = Database::result(
  4218. $result,
  4219. 0,
  4220. 'hotspot_correct'
  4221. );
  4222. if ($studentChoice) {
  4223. $questionScore += $answerWeighting;
  4224. $totalScore += $answerWeighting;
  4225. }
  4226. } else {
  4227. // check answer.iid
  4228. if (!empty($answerIid)) {
  4229. $sql = "SELECT hotspot_correct
  4230. FROM $TBL_TRACK_HOTSPOT
  4231. WHERE
  4232. hotspot_exe_id = $exeId AND
  4233. hotspot_question_id= $questionId AND
  4234. hotspot_answer_id = ".intval($answerIid)."
  4235. ORDER BY hotspot_id ASC";
  4236. $result = Database::query($sql);
  4237. $studentChoice = Database::result(
  4238. $result,
  4239. 0,
  4240. 'hotspot_correct'
  4241. );
  4242. if ($studentChoice) {
  4243. $questionScore += $answerWeighting;
  4244. $totalScore += $answerWeighting;
  4245. }
  4246. }
  4247. }
  4248. }
  4249. } else {
  4250. if (!isset($choice[$answerAutoId]) && !isset($choice[$answerIid])) {
  4251. $choice[$answerAutoId] = 0;
  4252. $choice[$answerIid] = 0;
  4253. } else {
  4254. $studentChoice = $choice[$answerAutoId];
  4255. if (empty($studentChoice)) {
  4256. $studentChoice = $choice[$answerIid];
  4257. }
  4258. $choiceIsValid = false;
  4259. if (!empty($studentChoice)) {
  4260. $hotspotType = $objAnswerTmp->selectHotspotType($answerId);
  4261. $hotspotCoordinates = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4262. $choicePoint = Geometry::decodePoint($studentChoice);
  4263. switch ($hotspotType) {
  4264. case 'square':
  4265. $hotspotProperties = Geometry::decodeSquare($hotspotCoordinates);
  4266. $choiceIsValid = Geometry::pointIsInSquare($hotspotProperties, $choicePoint);
  4267. break;
  4268. case 'circle':
  4269. $hotspotProperties = Geometry::decodeEllipse($hotspotCoordinates);
  4270. $choiceIsValid = Geometry::pointIsInEllipse($hotspotProperties, $choicePoint);
  4271. break;
  4272. case 'poly':
  4273. $hotspotProperties = Geometry::decodePolygon($hotspotCoordinates);
  4274. $choiceIsValid = Geometry::pointIsInPolygon($hotspotProperties, $choicePoint);
  4275. break;
  4276. }
  4277. }
  4278. $choice[$answerAutoId] = 0;
  4279. if ($choiceIsValid) {
  4280. $questionScore += $answerWeighting;
  4281. $totalScore += $answerWeighting;
  4282. $choice[$answerAutoId] = 1;
  4283. $choice[$answerIid] = 1;
  4284. }
  4285. }
  4286. }
  4287. break;
  4288. case HOT_SPOT_ORDER:
  4289. // @todo never added to chamilo
  4290. // for hotspot with fixed order
  4291. $studentChoice = $choice['order'][$answerId];
  4292. if ($studentChoice == $answerId) {
  4293. $questionScore += $answerWeighting;
  4294. $totalScore += $answerWeighting;
  4295. $studentChoice = true;
  4296. } else {
  4297. $studentChoice = false;
  4298. }
  4299. break;
  4300. case HOT_SPOT_DELINEATION:
  4301. // for hotspot with delineation
  4302. if ($from_database) {
  4303. // getting the user answer
  4304. $TBL_TRACK_HOTSPOT = Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  4305. $query = "SELECT hotspot_correct, hotspot_coordinate
  4306. FROM $TBL_TRACK_HOTSPOT
  4307. WHERE
  4308. hotspot_exe_id = '".$exeId."' AND
  4309. hotspot_question_id= '".$questionId."' AND
  4310. hotspot_answer_id='1'";
  4311. //by default we take 1 because it's a delineation
  4312. $resq = Database::query($query);
  4313. $row = Database::fetch_array($resq, 'ASSOC');
  4314. $choice = $row['hotspot_correct'];
  4315. $user_answer = $row['hotspot_coordinate'];
  4316. // THIS is very important otherwise the poly_compile will throw an error!!
  4317. // round-up the coordinates
  4318. $coords = explode('/', $user_answer);
  4319. $user_array = '';
  4320. foreach ($coords as $coord) {
  4321. list($x, $y) = explode(';', $coord);
  4322. $user_array .= round($x).';'.round($y).'/';
  4323. }
  4324. $user_array = substr($user_array, 0, -1);
  4325. } else {
  4326. if (!empty($studentChoice)) {
  4327. $newquestionList[] = $questionId;
  4328. }
  4329. if ($answerId === 1) {
  4330. $studentChoice = $choice[$answerId];
  4331. $questionScore += $answerWeighting;
  4332. if ($hotspot_delineation_result[1] == 1) {
  4333. $totalScore += $answerWeighting; //adding the total
  4334. }
  4335. }
  4336. }
  4337. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  4338. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  4339. break;
  4340. case ANNOTATION:
  4341. if ($from_database) {
  4342. $sql = "SELECT answer, marks FROM $TBL_TRACK_ATTEMPT
  4343. WHERE
  4344. exe_id = $exeId AND
  4345. question_id= ".$questionId;
  4346. $resq = Database::query($sql);
  4347. $data = Database::fetch_array($resq);
  4348. $questionScore = empty($data['marks']) ? 0 : $data['marks'];
  4349. $totalScore += $questionScore == -1 ? 0 : $questionScore;
  4350. $arrques = $questionName;
  4351. break;
  4352. }
  4353. $studentChoice = $choice;
  4354. if ($studentChoice) {
  4355. $questionScore = 0;
  4356. $totalScore += 0;
  4357. }
  4358. break;
  4359. } // end switch Answertype
  4360. if ($show_result) {
  4361. if ($debug) {
  4362. error_log('Showing questions $from '.$from);
  4363. }
  4364. if ($from === 'exercise_result') {
  4365. //display answers (if not matching type, or if the answer is correct)
  4366. if (!in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE]) ||
  4367. $answerCorrect
  4368. ) {
  4369. if (in_array(
  4370. $answerType,
  4371. [
  4372. UNIQUE_ANSWER,
  4373. UNIQUE_ANSWER_IMAGE,
  4374. UNIQUE_ANSWER_NO_OPTION,
  4375. MULTIPLE_ANSWER,
  4376. MULTIPLE_ANSWER_COMBINATION,
  4377. GLOBAL_MULTIPLE_ANSWER,
  4378. READING_COMPREHENSION,
  4379. ]
  4380. )) {
  4381. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4382. $this,
  4383. $feedback_type,
  4384. $answerType,
  4385. $studentChoice,
  4386. $answer,
  4387. $answerComment,
  4388. $answerCorrect,
  4389. 0,
  4390. 0,
  4391. 0,
  4392. $results_disabled,
  4393. $showTotalScoreAndUserChoicesInLastAttempt,
  4394. $this->export
  4395. );
  4396. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  4397. ExerciseShowFunctions::display_multiple_answer_true_false(
  4398. $this,
  4399. $feedback_type,
  4400. $answerType,
  4401. $studentChoice,
  4402. $answer,
  4403. $answerComment,
  4404. $answerCorrect,
  4405. 0,
  4406. $questionId,
  4407. 0,
  4408. $results_disabled,
  4409. $showTotalScoreAndUserChoicesInLastAttempt
  4410. );
  4411. } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  4412. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4413. $this,
  4414. $feedback_type,
  4415. $studentChoice,
  4416. $studentChoiceDegree,
  4417. $answer,
  4418. $answerComment,
  4419. $answerCorrect,
  4420. $questionId,
  4421. $results_disabled
  4422. );
  4423. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
  4424. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4425. $this,
  4426. $feedback_type,
  4427. $answerType,
  4428. $studentChoice,
  4429. $answer,
  4430. $answerComment,
  4431. $answerCorrect,
  4432. 0,
  4433. 0,
  4434. 0,
  4435. $results_disabled,
  4436. $showTotalScoreAndUserChoicesInLastAttempt
  4437. );
  4438. } elseif ($answerType == FILL_IN_BLANKS) {
  4439. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4440. $this,
  4441. $feedback_type,
  4442. $answer,
  4443. 0,
  4444. 0,
  4445. $results_disabled,
  4446. '',
  4447. $showTotalScoreAndUserChoicesInLastAttempt
  4448. );
  4449. } elseif ($answerType == CALCULATED_ANSWER) {
  4450. ExerciseShowFunctions::display_calculated_answer(
  4451. $this,
  4452. $feedback_type,
  4453. $answer,
  4454. 0,
  4455. 0,
  4456. $results_disabled,
  4457. $showTotalScoreAndUserChoicesInLastAttempt,
  4458. $expectedAnswer,
  4459. $calculatedChoice,
  4460. $calculatedStatus
  4461. );
  4462. } elseif ($answerType == FREE_ANSWER) {
  4463. ExerciseShowFunctions::display_free_answer(
  4464. $feedback_type,
  4465. $choice,
  4466. $exeId,
  4467. $questionId,
  4468. $questionScore,
  4469. $results_disabled
  4470. );
  4471. } elseif ($answerType == ORAL_EXPRESSION) {
  4472. // to store the details of open questions in an array to be used in mail
  4473. /** @var OralExpression $objQuestionTmp */
  4474. ExerciseShowFunctions::display_oral_expression_answer(
  4475. $feedback_type,
  4476. $choice,
  4477. 0,
  4478. 0,
  4479. $objQuestionTmp->getFileUrl(true),
  4480. $results_disabled,
  4481. $questionScore
  4482. );
  4483. } elseif ($answerType == HOT_SPOT) {
  4484. $correctAnswerId = 0;
  4485. /**
  4486. * @var int
  4487. * @var TrackEHotspot $hotspot
  4488. */
  4489. foreach ($orderedHotspots as $correctAnswerId => $hotspot) {
  4490. if ($hotspot->getHotspotAnswerId() == $answerAutoId) {
  4491. break;
  4492. }
  4493. }
  4494. // force to show whether the choice is correct or not
  4495. $showTotalScoreAndUserChoicesInLastAttempt = true;
  4496. ExerciseShowFunctions::display_hotspot_answer(
  4497. $feedback_type,
  4498. ++$correctAnswerId,
  4499. $answer,
  4500. $studentChoice,
  4501. $answerComment,
  4502. $results_disabled,
  4503. $correctAnswerId,
  4504. $showTotalScoreAndUserChoicesInLastAttempt
  4505. );
  4506. } elseif ($answerType == HOT_SPOT_ORDER) {
  4507. ExerciseShowFunctions::display_hotspot_order_answer(
  4508. $feedback_type,
  4509. $answerId,
  4510. $answer,
  4511. $studentChoice,
  4512. $answerComment
  4513. );
  4514. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  4515. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  4516. //round-up the coordinates
  4517. $coords = explode('/', $user_answer);
  4518. $user_array = '';
  4519. foreach ($coords as $coord) {
  4520. if (!empty($coord)) {
  4521. $parts = explode(';', $coord);
  4522. if (!empty($parts)) {
  4523. $user_array .= round($parts[0]).';'.round($parts[1]).'/';
  4524. }
  4525. }
  4526. }
  4527. $user_array = substr($user_array, 0, -1);
  4528. if ($next) {
  4529. $user_answer = $user_array;
  4530. // we compare only the delineation not the other points
  4531. $answer_question = $_SESSION['hotspot_coord'][1];
  4532. $answerDestination = $_SESSION['hotspot_dest'][1];
  4533. //calculating the area
  4534. $poly_user = convert_coordinates($user_answer, '/');
  4535. $poly_answer = convert_coordinates($answer_question, '|');
  4536. $max_coord = poly_get_max($poly_user, $poly_answer);
  4537. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4538. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4539. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4540. $overlap = $poly_results['both'];
  4541. $poly_answer_area = $poly_results['s1'];
  4542. $poly_user_area = $poly_results['s2'];
  4543. $missing = $poly_results['s1Only'];
  4544. $excess = $poly_results['s2Only'];
  4545. //$overlap = round(polygons_overlap($poly_answer,$poly_user));
  4546. // //this is an area in pixels
  4547. if ($debug > 0) {
  4548. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4549. }
  4550. if ($overlap < 1) {
  4551. //shortcut to avoid complicated calculations
  4552. $final_overlap = 0;
  4553. $final_missing = 100;
  4554. $final_excess = 100;
  4555. } else {
  4556. // the final overlap is the percentage of the initial polygon
  4557. // that is overlapped by the user's polygon
  4558. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4559. if ($debug > 1) {
  4560. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  4561. }
  4562. // the final missing area is the percentage of the initial polygon
  4563. // that is not overlapped by the user's polygon
  4564. $final_missing = 100 - $final_overlap;
  4565. if ($debug > 1) {
  4566. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  4567. }
  4568. // the final excess area is the percentage of the initial polygon's size
  4569. // that is covered by the user's polygon outside of the initial polygon
  4570. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4571. if ($debug > 1) {
  4572. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  4573. }
  4574. }
  4575. //checking the destination parameters parsing the "@@"
  4576. $destination_items = explode(
  4577. '@@',
  4578. $answerDestination
  4579. );
  4580. $threadhold_total = $destination_items[0];
  4581. $threadhold_items = explode(
  4582. ';',
  4583. $threadhold_total
  4584. );
  4585. $threadhold1 = $threadhold_items[0]; // overlap
  4586. $threadhold2 = $threadhold_items[1]; // excess
  4587. $threadhold3 = $threadhold_items[2]; //missing
  4588. // if is delineation
  4589. if ($answerId === 1) {
  4590. //setting colors
  4591. if ($final_overlap >= $threadhold1) {
  4592. $overlap_color = true; //echo 'a';
  4593. }
  4594. //echo $excess.'-'.$threadhold2;
  4595. if ($final_excess <= $threadhold2) {
  4596. $excess_color = true; //echo 'b';
  4597. }
  4598. //echo '--------'.$missing.'-'.$threadhold3;
  4599. if ($final_missing <= $threadhold3) {
  4600. $missing_color = true; //echo 'c';
  4601. }
  4602. // if pass
  4603. if ($final_overlap >= $threadhold1 &&
  4604. $final_missing <= $threadhold3 &&
  4605. $final_excess <= $threadhold2
  4606. ) {
  4607. $next = 1; //go to the oars
  4608. $result_comment = get_lang('Acceptable');
  4609. $final_answer = 1; // do not update with update_exercise_attempt
  4610. } else {
  4611. $next = 0;
  4612. $result_comment = get_lang('Unacceptable');
  4613. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4614. $answerDestination = $objAnswerTmp->selectDestination(1);
  4615. // checking the destination parameters parsing the "@@"
  4616. $destination_items = explode('@@', $answerDestination);
  4617. }
  4618. } elseif ($answerId > 1) {
  4619. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4620. if ($debug > 0) {
  4621. error_log(__LINE__.' - answerId is of type noerror', 0);
  4622. }
  4623. //type no error shouldn't be treated
  4624. $next = 1;
  4625. continue;
  4626. }
  4627. if ($debug > 0) {
  4628. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4629. }
  4630. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4631. $poly_answer = convert_coordinates($delineation_cord, '|');
  4632. $max_coord = poly_get_max($poly_user, $poly_answer);
  4633. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4634. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4635. if ($overlap == false) {
  4636. //all good, no overlap
  4637. $next = 1;
  4638. continue;
  4639. } else {
  4640. if ($debug > 0) {
  4641. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4642. }
  4643. $organs_at_risk_hit++;
  4644. //show the feedback
  4645. $next = 0;
  4646. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4647. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4648. $destination_items = explode('@@', $answerDestination);
  4649. $try_hotspot = $destination_items[1];
  4650. $lp_hotspot = $destination_items[2];
  4651. $select_question_hotspot = $destination_items[3];
  4652. $url_hotspot = $destination_items[4];
  4653. }
  4654. }
  4655. } else {
  4656. // the first delineation feedback
  4657. if ($debug > 0) {
  4658. error_log(__LINE__.' first', 0);
  4659. }
  4660. }
  4661. } elseif (in_array($answerType, [MATCHING, MATCHING_DRAGGABLE])) {
  4662. echo '<tr>';
  4663. echo Display::tag('td', $answerMatching[$answerId]);
  4664. echo Display::tag(
  4665. 'td',
  4666. "$user_answer / ".Display::tag(
  4667. 'strong',
  4668. $answerMatching[$answerCorrect],
  4669. ['style' => 'color: #008000; font-weight: bold;']
  4670. )
  4671. );
  4672. echo '</tr>';
  4673. } elseif ($answerType == ANNOTATION) {
  4674. ExerciseShowFunctions::displayAnnotationAnswer(
  4675. $feedback_type,
  4676. $exeId,
  4677. $questionId,
  4678. $questionScore,
  4679. $results_disabled
  4680. );
  4681. }
  4682. }
  4683. } else {
  4684. if ($debug) {
  4685. error_log('Showing questions $from '.$from);
  4686. }
  4687. switch ($answerType) {
  4688. case UNIQUE_ANSWER:
  4689. case UNIQUE_ANSWER_IMAGE:
  4690. case UNIQUE_ANSWER_NO_OPTION:
  4691. case MULTIPLE_ANSWER:
  4692. case GLOBAL_MULTIPLE_ANSWER:
  4693. case MULTIPLE_ANSWER_COMBINATION:
  4694. case READING_COMPREHENSION:
  4695. if ($answerId == 1) {
  4696. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4697. $this,
  4698. $feedback_type,
  4699. $answerType,
  4700. $studentChoice,
  4701. $answer,
  4702. $answerComment,
  4703. $answerCorrect,
  4704. $exeId,
  4705. $questionId,
  4706. $answerId,
  4707. $results_disabled,
  4708. $showTotalScoreAndUserChoicesInLastAttempt,
  4709. $this->export
  4710. );
  4711. } else {
  4712. ExerciseShowFunctions::display_unique_or_multiple_answer(
  4713. $this,
  4714. $feedback_type,
  4715. $answerType,
  4716. $studentChoice,
  4717. $answer,
  4718. $answerComment,
  4719. $answerCorrect,
  4720. $exeId,
  4721. $questionId,
  4722. '',
  4723. $results_disabled,
  4724. $showTotalScoreAndUserChoicesInLastAttempt,
  4725. $this->export
  4726. );
  4727. }
  4728. break;
  4729. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  4730. if ($answerId == 1) {
  4731. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4732. $this,
  4733. $feedback_type,
  4734. $answerType,
  4735. $studentChoice,
  4736. $answer,
  4737. $answerComment,
  4738. $answerCorrect,
  4739. $exeId,
  4740. $questionId,
  4741. $answerId,
  4742. $results_disabled,
  4743. $showTotalScoreAndUserChoicesInLastAttempt
  4744. );
  4745. } else {
  4746. ExerciseShowFunctions::display_multiple_answer_combination_true_false(
  4747. $this,
  4748. $feedback_type,
  4749. $answerType,
  4750. $studentChoice,
  4751. $answer,
  4752. $answerComment,
  4753. $answerCorrect,
  4754. $exeId,
  4755. $questionId,
  4756. '',
  4757. $results_disabled,
  4758. $showTotalScoreAndUserChoicesInLastAttempt
  4759. );
  4760. }
  4761. break;
  4762. case MULTIPLE_ANSWER_TRUE_FALSE:
  4763. if ($answerId == 1) {
  4764. ExerciseShowFunctions::display_multiple_answer_true_false(
  4765. $this,
  4766. $feedback_type,
  4767. $answerType,
  4768. $studentChoice,
  4769. $answer,
  4770. $answerComment,
  4771. $answerCorrect,
  4772. $exeId,
  4773. $questionId,
  4774. $answerId,
  4775. $results_disabled,
  4776. $showTotalScoreAndUserChoicesInLastAttempt
  4777. );
  4778. } else {
  4779. ExerciseShowFunctions::display_multiple_answer_true_false(
  4780. $this,
  4781. $feedback_type,
  4782. $answerType,
  4783. $studentChoice,
  4784. $answer,
  4785. $answerComment,
  4786. $answerCorrect,
  4787. $exeId,
  4788. $questionId,
  4789. '',
  4790. $results_disabled,
  4791. $showTotalScoreAndUserChoicesInLastAttempt
  4792. );
  4793. }
  4794. break;
  4795. case MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY:
  4796. if ($answerId == 1) {
  4797. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4798. $this,
  4799. $feedback_type,
  4800. $studentChoice,
  4801. $studentChoiceDegree,
  4802. $answer,
  4803. $answerComment,
  4804. $answerCorrect,
  4805. $questionId,
  4806. $results_disabled
  4807. );
  4808. } else {
  4809. ExerciseShowFunctions::displayMultipleAnswerTrueFalseDegreeCertainty(
  4810. $this,
  4811. $feedback_type,
  4812. $studentChoice,
  4813. $studentChoiceDegree,
  4814. $answer,
  4815. $answerComment,
  4816. $answerCorrect,
  4817. $questionId,
  4818. $results_disabled
  4819. );
  4820. }
  4821. break;
  4822. case FILL_IN_BLANKS:
  4823. ExerciseShowFunctions::display_fill_in_blanks_answer(
  4824. $this,
  4825. $feedback_type,
  4826. $answer,
  4827. $exeId,
  4828. $questionId,
  4829. $results_disabled,
  4830. $str,
  4831. $showTotalScoreAndUserChoicesInLastAttempt
  4832. );
  4833. break;
  4834. case CALCULATED_ANSWER:
  4835. ExerciseShowFunctions::display_calculated_answer(
  4836. $this,
  4837. $feedback_type,
  4838. $answer,
  4839. $exeId,
  4840. $questionId,
  4841. $results_disabled,
  4842. '',
  4843. $showTotalScoreAndUserChoicesInLastAttempt
  4844. );
  4845. break;
  4846. case FREE_ANSWER:
  4847. echo ExerciseShowFunctions::display_free_answer(
  4848. $feedback_type,
  4849. $choice,
  4850. $exeId,
  4851. $questionId,
  4852. $questionScore,
  4853. $results_disabled
  4854. );
  4855. break;
  4856. case ORAL_EXPRESSION:
  4857. echo '<tr>
  4858. <td valign="top">'.
  4859. ExerciseShowFunctions::display_oral_expression_answer(
  4860. $feedback_type,
  4861. $choice,
  4862. $exeId,
  4863. $questionId,
  4864. $objQuestionTmp->getFileUrl(),
  4865. $results_disabled,
  4866. $questionScore
  4867. ).'</td>
  4868. </tr>
  4869. </table>';
  4870. break;
  4871. case HOT_SPOT:
  4872. ExerciseShowFunctions::display_hotspot_answer(
  4873. $feedback_type,
  4874. $answerId,
  4875. $answer,
  4876. $studentChoice,
  4877. $answerComment,
  4878. $results_disabled,
  4879. $answerId,
  4880. $showTotalScoreAndUserChoicesInLastAttempt
  4881. );
  4882. break;
  4883. case HOT_SPOT_DELINEATION:
  4884. $user_answer = $user_array;
  4885. if ($next) {
  4886. $user_answer = $user_array;
  4887. // we compare only the delineation not the other points
  4888. $answer_question = $_SESSION['hotspot_coord'][1];
  4889. $answerDestination = $_SESSION['hotspot_dest'][1];
  4890. // calculating the area
  4891. $poly_user = convert_coordinates($user_answer, '/');
  4892. $poly_answer = convert_coordinates($answer_question, '|');
  4893. $max_coord = poly_get_max($poly_user, $poly_answer);
  4894. $poly_user_compiled = poly_compile($poly_user, $max_coord);
  4895. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4896. $poly_results = poly_result($poly_answer_compiled, $poly_user_compiled, $max_coord);
  4897. $overlap = $poly_results['both'];
  4898. $poly_answer_area = $poly_results['s1'];
  4899. $poly_user_area = $poly_results['s2'];
  4900. $missing = $poly_results['s1Only'];
  4901. $excess = $poly_results['s2Only'];
  4902. if ($debug > 0) {
  4903. error_log(__LINE__.' - Polygons results are '.print_r($poly_results, 1), 0);
  4904. }
  4905. if ($overlap < 1) {
  4906. //shortcut to avoid complicated calculations
  4907. $final_overlap = 0;
  4908. $final_missing = 100;
  4909. $final_excess = 100;
  4910. } else {
  4911. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  4912. $final_overlap = round(((float) $overlap / (float) $poly_answer_area) * 100);
  4913. if ($debug > 1) {
  4914. error_log(__LINE__.' - Final overlap is '.$final_overlap, 0);
  4915. }
  4916. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  4917. $final_missing = 100 - $final_overlap;
  4918. if ($debug > 1) {
  4919. error_log(__LINE__.' - Final missing is '.$final_missing, 0);
  4920. }
  4921. // 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
  4922. $final_excess = round((((float) $poly_user_area - (float) $overlap) / (float) $poly_answer_area) * 100);
  4923. if ($debug > 1) {
  4924. error_log(__LINE__.' - Final excess is '.$final_excess, 0);
  4925. }
  4926. }
  4927. // Checking the destination parameters parsing the "@@"
  4928. $destination_items = explode('@@', $answerDestination);
  4929. $threadhold_total = $destination_items[0];
  4930. $threadhold_items = explode(';', $threadhold_total);
  4931. $threadhold1 = $threadhold_items[0]; // overlap
  4932. $threadhold2 = $threadhold_items[1]; // excess
  4933. $threadhold3 = $threadhold_items[2]; //missing
  4934. // if is delineation
  4935. if ($answerId === 1) {
  4936. //setting colors
  4937. if ($final_overlap >= $threadhold1) {
  4938. $overlap_color = true; //echo 'a';
  4939. }
  4940. if ($final_excess <= $threadhold2) {
  4941. $excess_color = true; //echo 'b';
  4942. }
  4943. if ($final_missing <= $threadhold3) {
  4944. $missing_color = true; //echo 'c';
  4945. }
  4946. // if pass
  4947. if ($final_overlap >= $threadhold1 &&
  4948. $final_missing <= $threadhold3 &&
  4949. $final_excess <= $threadhold2
  4950. ) {
  4951. $next = 1; //go to the oars
  4952. $result_comment = get_lang('Acceptable');
  4953. $final_answer = 1; // do not update with update_exercise_attempt
  4954. } else {
  4955. $next = 0;
  4956. $result_comment = get_lang('Unacceptable');
  4957. $comment = $answerDestination = $objAnswerTmp->selectComment(1);
  4958. $answerDestination = $objAnswerTmp->selectDestination(1);
  4959. //checking the destination parameters parsing the "@@"
  4960. $destination_items = explode('@@', $answerDestination);
  4961. }
  4962. } elseif ($answerId > 1) {
  4963. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  4964. if ($debug > 0) {
  4965. error_log(__LINE__.' - answerId is of type noerror', 0);
  4966. }
  4967. //type no error shouldn't be treated
  4968. $next = 1;
  4969. break;
  4970. }
  4971. if ($debug > 0) {
  4972. error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR', 0);
  4973. }
  4974. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates($answerId);
  4975. $poly_answer = convert_coordinates($delineation_cord, '|');
  4976. $max_coord = poly_get_max($poly_user, $poly_answer);
  4977. $poly_answer_compiled = poly_compile($poly_answer, $max_coord);
  4978. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled, $max_coord);
  4979. if ($overlap == false) {
  4980. //all good, no overlap
  4981. $next = 1;
  4982. break;
  4983. } else {
  4984. if ($debug > 0) {
  4985. error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit', 0);
  4986. }
  4987. $organs_at_risk_hit++;
  4988. //show the feedback
  4989. $next = 0;
  4990. $comment = $answerDestination = $objAnswerTmp->selectComment($answerId);
  4991. $answerDestination = $objAnswerTmp->selectDestination($answerId);
  4992. $destination_items = explode('@@', $answerDestination);
  4993. $try_hotspot = $destination_items[1];
  4994. $lp_hotspot = $destination_items[2];
  4995. $select_question_hotspot = $destination_items[3];
  4996. $url_hotspot = $destination_items[4];
  4997. }
  4998. }
  4999. } else {
  5000. // the first delineation feedback
  5001. if ($debug > 0) {
  5002. error_log(__LINE__.' first', 0);
  5003. }
  5004. }
  5005. break;
  5006. case HOT_SPOT_ORDER:
  5007. ExerciseShowFunctions::display_hotspot_order_answer(
  5008. $feedback_type,
  5009. $answerId,
  5010. $answer,
  5011. $studentChoice,
  5012. $answerComment
  5013. );
  5014. break;
  5015. case DRAGGABLE:
  5016. case MATCHING_DRAGGABLE:
  5017. case MATCHING:
  5018. echo '<tr>';
  5019. echo Display::tag('td', $answerMatching[$answerId]);
  5020. echo Display::tag(
  5021. 'td',
  5022. "$user_answer / ".Display::tag(
  5023. 'strong',
  5024. $answerMatching[$answerCorrect],
  5025. ['style' => 'color: #008000; font-weight: bold;']
  5026. )
  5027. );
  5028. echo '</tr>';
  5029. break;
  5030. case ANNOTATION:
  5031. ExerciseShowFunctions::displayAnnotationAnswer(
  5032. $feedback_type,
  5033. $exeId,
  5034. $questionId,
  5035. $questionScore,
  5036. $results_disabled
  5037. );
  5038. break;
  5039. }
  5040. }
  5041. }
  5042. if ($debug) {
  5043. error_log(' ------ ');
  5044. }
  5045. } // end for that loops over all answers of the current question
  5046. if ($debug) {
  5047. error_log('-- end answer loop --');
  5048. }
  5049. $final_answer = true;
  5050. foreach ($real_answers as $my_answer) {
  5051. if (!$my_answer) {
  5052. $final_answer = false;
  5053. }
  5054. }
  5055. //we add the total score after dealing with the answers
  5056. if ($answerType == MULTIPLE_ANSWER_COMBINATION ||
  5057. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE
  5058. ) {
  5059. if ($final_answer) {
  5060. //getting only the first score where we save the weight of all the question
  5061. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  5062. $questionScore += $answerWeighting;
  5063. $totalScore += $answerWeighting;
  5064. }
  5065. }
  5066. //Fixes multiple answer question in order to be exact
  5067. //if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  5068. /* if ($answerType == GLOBAL_MULTIPLE_ANSWER) {
  5069. $diff = @array_diff($answer_correct_array, $real_answers);
  5070. // All good answers or nothing works like exact
  5071. $counter = 1;
  5072. $correct_answer = true;
  5073. foreach ($real_answers as $my_answer) {
  5074. if ($debug)
  5075. error_log(" my_answer: $my_answer answer_correct_array[counter]: ".$answer_correct_array[$counter]);
  5076. if ($my_answer != $answer_correct_array[$counter]) {
  5077. $correct_answer = false;
  5078. break;
  5079. }
  5080. $counter++;
  5081. }
  5082. if ($debug) error_log(" answer_correct_array: ".print_r($answer_correct_array, 1)."");
  5083. if ($debug) error_log(" real_answers: ".print_r($real_answers, 1)."");
  5084. if ($debug) error_log(" correct_answer: ".$correct_answer);
  5085. if ($correct_answer == false) {
  5086. $questionScore = 0;
  5087. }
  5088. // This makes the result non exact
  5089. if (!empty($diff)) {
  5090. $questionScore = 0;
  5091. }
  5092. }*/
  5093. $extra_data = [
  5094. 'final_overlap' => $final_overlap,
  5095. 'final_missing' => $final_missing,
  5096. 'final_excess' => $final_excess,
  5097. 'overlap_color' => $overlap_color,
  5098. 'missing_color' => $missing_color,
  5099. 'excess_color' => $excess_color,
  5100. 'threadhold1' => $threadhold1,
  5101. 'threadhold2' => $threadhold2,
  5102. 'threadhold3' => $threadhold3,
  5103. ];
  5104. if ($from == 'exercise_result') {
  5105. // if answer is hotspot. To the difference of exercise_show.php,
  5106. // we use the results from the session (from_db=0)
  5107. // TODO Change this, because it is wrong to show the user
  5108. // some results that haven't been stored in the database yet
  5109. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION) {
  5110. if ($debug) {
  5111. error_log('$from AND this is a hotspot kind of question ');
  5112. }
  5113. $my_exe_id = 0;
  5114. $from_database = 0;
  5115. if ($answerType == HOT_SPOT_DELINEATION) {
  5116. if (0) {
  5117. if ($overlap_color) {
  5118. $overlap_color = 'green';
  5119. } else {
  5120. $overlap_color = 'red';
  5121. }
  5122. if ($missing_color) {
  5123. $missing_color = 'green';
  5124. } else {
  5125. $missing_color = 'red';
  5126. }
  5127. if ($excess_color) {
  5128. $excess_color = 'green';
  5129. } else {
  5130. $excess_color = 'red';
  5131. }
  5132. if (!is_numeric($final_overlap)) {
  5133. $final_overlap = 0;
  5134. }
  5135. if (!is_numeric($final_missing)) {
  5136. $final_missing = 0;
  5137. }
  5138. if (!is_numeric($final_excess)) {
  5139. $final_excess = 0;
  5140. }
  5141. if ($final_overlap > 100) {
  5142. $final_overlap = 100;
  5143. }
  5144. $table_resume = '<table class="data_table">
  5145. <tr class="row_odd" >
  5146. <td></td>
  5147. <td ><b>'.get_lang('Requirements').'</b></td>
  5148. <td><b>'.get_lang('YourAnswer').'</b></td>
  5149. </tr>
  5150. <tr class="row_even">
  5151. <td><b>'.get_lang('Overlap').'</b></td>
  5152. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  5153. <td><div style="color:'.$overlap_color.'">'
  5154. .(($final_overlap < 0) ? 0 : intval($final_overlap)).'</div></td>
  5155. </tr>
  5156. <tr>
  5157. <td><b>'.get_lang('Excess').'</b></td>
  5158. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  5159. <td><div style="color:'.$excess_color.'">'
  5160. .(($final_excess < 0) ? 0 : intval($final_excess)).'</div></td>
  5161. </tr>
  5162. <tr class="row_even">
  5163. <td><b>'.get_lang('Missing').'</b></td>
  5164. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  5165. <td><div style="color:'.$missing_color.'">'
  5166. .(($final_missing < 0) ? 0 : intval($final_missing)).'</div></td>
  5167. </tr>
  5168. </table>';
  5169. if ($next == 0) {
  5170. $try = $try_hotspot;
  5171. $lp = $lp_hotspot;
  5172. $destinationid = $select_question_hotspot;
  5173. $url = $url_hotspot;
  5174. } else {
  5175. //show if no error
  5176. //echo 'no error';
  5177. $comment = $answerComment = $objAnswerTmp->selectComment($nbrAnswers);
  5178. $answerDestination = $objAnswerTmp->selectDestination($nbrAnswers);
  5179. }
  5180. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  5181. <p style="text-align:center">';
  5182. $message = '<p>'.get_lang('YourDelineation').'</p>';
  5183. $message .= $table_resume;
  5184. $message .= '<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  5185. if ($organs_at_risk_hit > 0) {
  5186. $message .= '<p><b>'.get_lang('OARHit').'</b></p>';
  5187. }
  5188. $message .= '<p>'.$comment.'</p>';
  5189. echo $message;
  5190. } else {
  5191. echo $hotspot_delineation_result[0]; //prints message
  5192. $from_database = 1; // the hotspot_solution.swf needs this variable
  5193. }
  5194. //save the score attempts
  5195. if (1) {
  5196. //getting the answer 1 or 0 comes from exercise_submit_modal.php
  5197. $final_answer = $hotspot_delineation_result[1];
  5198. if ($final_answer == 0) {
  5199. $questionScore = 0;
  5200. }
  5201. // we always insert the answer_id 1 = delineation
  5202. Event::saveQuestionAttempt($questionScore, 1, $quesId, $exeId, 0);
  5203. //in delineation mode, get the answer from $hotspot_delineation_result[1]
  5204. $hotspotValue = (int) $hotspot_delineation_result[1] === 1 ? 1 : 0;
  5205. Event::saveExerciseAttemptHotspot(
  5206. $exeId,
  5207. $quesId,
  5208. 1,
  5209. $hotspotValue,
  5210. $exerciseResultCoordinates[$quesId]
  5211. );
  5212. } else {
  5213. if ($final_answer == 0) {
  5214. $questionScore = 0;
  5215. $answer = 0;
  5216. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  5217. if (is_array($exerciseResultCoordinates[$quesId])) {
  5218. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  5219. Event::saveExerciseAttemptHotspot(
  5220. $exeId,
  5221. $quesId,
  5222. $idx,
  5223. 0,
  5224. $val
  5225. );
  5226. }
  5227. }
  5228. } else {
  5229. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0);
  5230. if (is_array($exerciseResultCoordinates[$quesId])) {
  5231. foreach ($exerciseResultCoordinates[$quesId] as $idx => $val) {
  5232. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  5233. Event::saveExerciseAttemptHotspot(
  5234. $exeId,
  5235. $quesId,
  5236. $idx,
  5237. $hotspotValue,
  5238. $val
  5239. );
  5240. }
  5241. }
  5242. }
  5243. }
  5244. $my_exe_id = $exeId;
  5245. }
  5246. }
  5247. $relPath = api_get_path(WEB_CODE_PATH);
  5248. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  5249. // We made an extra table for the answers
  5250. if ($show_result) {
  5251. echo '</table></td></tr>';
  5252. echo "
  5253. <tr>
  5254. <td colspan=\"2\">
  5255. <p><em>".get_lang('HotSpot')."</em></p>
  5256. <div id=\"hotspot-solution-$questionId\"></div>
  5257. <script>
  5258. $(function() {
  5259. new HotspotQuestion({
  5260. questionId: $questionId,
  5261. exerciseId: {$this->id},
  5262. exeId: $exeId,
  5263. selector: '#hotspot-solution-$questionId',
  5264. for: 'solution',
  5265. relPath: '$relPath'
  5266. });
  5267. });
  5268. </script>
  5269. </td>
  5270. </tr>
  5271. ";
  5272. }
  5273. } elseif ($answerType == ANNOTATION) {
  5274. if ($show_result) {
  5275. echo '
  5276. <p><em>'.get_lang('Annotation').'</em></p>
  5277. <div id="annotation-canvas-'.$questionId.'"></div>
  5278. <script>
  5279. AnnotationQuestion({
  5280. questionId: parseInt('.$questionId.'),
  5281. exerciseId: parseInt('.$exeId.'),
  5282. relPath: \''.$relPath.'\',
  5283. courseId: parseInt('.$course_id.')
  5284. });
  5285. </script>
  5286. ';
  5287. }
  5288. }
  5289. //if ($origin != 'learnpath') {
  5290. if ($show_result && $answerType != ANNOTATION) {
  5291. echo '</table>';
  5292. }
  5293. // }
  5294. }
  5295. unset($objAnswerTmp);
  5296. $totalWeighting += $questionWeighting;
  5297. // Store results directly in the database
  5298. // For all in one page exercises, the results will be
  5299. // stored by exercise_results.php (using the session)
  5300. if ($saved_results) {
  5301. if ($debug) {
  5302. error_log("Save question results $saved_results");
  5303. error_log('choice: ');
  5304. error_log(print_r($choice, 1));
  5305. }
  5306. if (empty($choice)) {
  5307. $choice = 0;
  5308. }
  5309. // with certainty degree
  5310. if (empty($choiceDegreeCertainty)) {
  5311. $choiceDegreeCertainty = 0;
  5312. }
  5313. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
  5314. $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ||
  5315. $answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY
  5316. ) {
  5317. if ($choice != 0) {
  5318. $reply = array_keys($choice);
  5319. $countReply = count($reply);
  5320. for ($i = 0; $i < $countReply; $i++) {
  5321. $chosenAnswer = $reply[$i];
  5322. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE_DEGREE_CERTAINTY) {
  5323. if ($choiceDegreeCertainty != 0) {
  5324. $replyDegreeCertainty = array_keys($choiceDegreeCertainty);
  5325. $answerDegreeCertainty = isset($replyDegreeCertainty[$i]) ? $replyDegreeCertainty[$i] : '';
  5326. $answerValue = isset($choiceDegreeCertainty[$answerDegreeCertainty]) ? $choiceDegreeCertainty[$answerDegreeCertainty] : '';
  5327. Event::saveQuestionAttempt(
  5328. $questionScore,
  5329. $chosenAnswer.':'.$choice[$chosenAnswer].':'.$answerValue,
  5330. $quesId,
  5331. $exeId,
  5332. $i,
  5333. $this->id,
  5334. $updateResults
  5335. );
  5336. }
  5337. } else {
  5338. Event::saveQuestionAttempt(
  5339. $questionScore,
  5340. $chosenAnswer.':'.$choice[$chosenAnswer],
  5341. $quesId,
  5342. $exeId,
  5343. $i,
  5344. $this->id,
  5345. $updateResults
  5346. );
  5347. }
  5348. if ($debug) {
  5349. error_log('result =>'.$questionScore.' '.$chosenAnswer.':'.$choice[$chosenAnswer]);
  5350. }
  5351. }
  5352. } else {
  5353. Event::saveQuestionAttempt(
  5354. $questionScore,
  5355. 0,
  5356. $quesId,
  5357. $exeId,
  5358. 0,
  5359. $this->id
  5360. );
  5361. }
  5362. } elseif ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
  5363. if ($choice != 0) {
  5364. $reply = array_keys($choice);
  5365. if ($debug) {
  5366. error_log("reply ".print_r($reply, 1)."");
  5367. }
  5368. for ($i = 0; $i < sizeof($reply); $i++) {
  5369. $ans = $reply[$i];
  5370. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  5371. }
  5372. } else {
  5373. Event::saveQuestionAttempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  5374. }
  5375. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  5376. if ($choice != 0) {
  5377. $reply = array_keys($choice);
  5378. for ($i = 0; $i < sizeof($reply); $i++) {
  5379. $ans = $reply[$i];
  5380. Event::saveQuestionAttempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  5381. }
  5382. } else {
  5383. Event::saveQuestionAttempt(
  5384. $questionScore,
  5385. 0,
  5386. $quesId,
  5387. $exeId,
  5388. 0,
  5389. $this->id
  5390. );
  5391. }
  5392. } elseif (in_array($answerType, [MATCHING, DRAGGABLE, MATCHING_DRAGGABLE])) {
  5393. if (isset($matching)) {
  5394. foreach ($matching as $j => $val) {
  5395. Event::saveQuestionAttempt(
  5396. $questionScore,
  5397. $val,
  5398. $quesId,
  5399. $exeId,
  5400. $j,
  5401. $this->id
  5402. );
  5403. }
  5404. }
  5405. } elseif ($answerType == FREE_ANSWER) {
  5406. $answer = $choice;
  5407. Event::saveQuestionAttempt(
  5408. $questionScore,
  5409. $answer,
  5410. $quesId,
  5411. $exeId,
  5412. 0,
  5413. $this->id
  5414. );
  5415. } elseif ($answerType == ORAL_EXPRESSION) {
  5416. $answer = $choice;
  5417. Event::saveQuestionAttempt(
  5418. $questionScore,
  5419. $answer,
  5420. $quesId,
  5421. $exeId,
  5422. 0,
  5423. $this->id,
  5424. false,
  5425. $objQuestionTmp->getAbsoluteFilePath()
  5426. );
  5427. } elseif (
  5428. in_array(
  5429. $answerType,
  5430. [UNIQUE_ANSWER, UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION, READING_COMPREHENSION]
  5431. )
  5432. ) {
  5433. $answer = $choice;
  5434. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  5435. } elseif ($answerType == HOT_SPOT || $answerType == ANNOTATION) {
  5436. $answer = [];
  5437. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  5438. if ($debug) {
  5439. error_log('Checking result coordinates');
  5440. }
  5441. Database::delete(
  5442. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  5443. [
  5444. 'hotspot_exe_id = ? AND hotspot_question_id = ? AND c_id = ?' => [
  5445. $exeId,
  5446. $questionId,
  5447. api_get_course_int_id(),
  5448. ],
  5449. ]
  5450. );
  5451. foreach ($exerciseResultCoordinates[$questionId] as $idx => $val) {
  5452. $answer[] = $val;
  5453. $hotspotValue = (int) $choice[$idx] === 1 ? 1 : 0;
  5454. if ($debug) {
  5455. error_log('Hotspot value: '.$hotspotValue);
  5456. }
  5457. Event::saveExerciseAttemptHotspot(
  5458. $exeId,
  5459. $quesId,
  5460. $idx,
  5461. $hotspotValue,
  5462. $val,
  5463. false,
  5464. $this->id
  5465. );
  5466. }
  5467. } else {
  5468. if ($debug) {
  5469. error_log('Empty: exerciseResultCoordinates');
  5470. }
  5471. }
  5472. Event::saveQuestionAttempt($questionScore, implode('|', $answer), $quesId, $exeId, 0, $this->id);
  5473. } else {
  5474. Event::saveQuestionAttempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  5475. }
  5476. }
  5477. if ($propagate_neg == 0 && $questionScore < 0) {
  5478. $questionScore = 0;
  5479. }
  5480. if ($saved_results) {
  5481. $statsTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  5482. $sql = "UPDATE $statsTable SET
  5483. exe_result = exe_result + ".floatval($questionScore)."
  5484. WHERE exe_id = $exeId";
  5485. Database::query($sql);
  5486. if ($debug) {
  5487. error_log($sql);
  5488. }
  5489. }
  5490. $return = [
  5491. 'score' => $questionScore,
  5492. 'weight' => $questionWeighting,
  5493. 'extra' => $extra_data,
  5494. 'open_question' => $arrques,
  5495. 'open_answer' => $arrans,
  5496. 'answer_type' => $answerType,
  5497. 'generated_oral_file' => $generatedFile,
  5498. 'user_answered' => $userAnsweredQuestion,
  5499. ];
  5500. return $return;
  5501. }
  5502. /**
  5503. * Sends a notification when a user ends an examn.
  5504. *
  5505. * @param string $type 'start' or 'end' of an exercise
  5506. * @param array $question_list_answers
  5507. * @param string $origin
  5508. * @param int $exe_id
  5509. * @param float $score
  5510. * @param float $weight
  5511. *
  5512. * @return bool
  5513. */
  5514. public function send_mail_notification_for_exam(
  5515. $type = 'end',
  5516. $question_list_answers,
  5517. $origin,
  5518. $exe_id,
  5519. $score = null,
  5520. $weight = null
  5521. ) {
  5522. $setting = api_get_course_setting('email_alert_manager_on_new_quiz');
  5523. if (empty($setting) && empty($this->getNotifications())) {
  5524. return false;
  5525. }
  5526. $settingFromExercise = $this->getNotifications();
  5527. if (!empty($settingFromExercise)) {
  5528. $setting = $settingFromExercise;
  5529. }
  5530. // Email configuration settings
  5531. $courseCode = api_get_course_id();
  5532. $courseInfo = api_get_course_info($courseCode);
  5533. if (empty($courseInfo)) {
  5534. return false;
  5535. }
  5536. $sessionId = api_get_session_id();
  5537. $sessionData = '';
  5538. if (!empty($sessionId)) {
  5539. $sessionInfo = api_get_session_info($sessionId);
  5540. if (!empty($sessionInfo)) {
  5541. $sessionData = '<tr>'
  5542. .'<td>'.get_lang('SessionName').'</td>'
  5543. .'<td>'.$sessionInfo['name'].'</td>'
  5544. .'</tr>';
  5545. }
  5546. }
  5547. $sendStart = false;
  5548. $sendEnd = false;
  5549. $sendEndOpenQuestion = false;
  5550. $sendEndOralQuestion = false;
  5551. foreach ($setting as $option) {
  5552. switch ($option) {
  5553. case 0:
  5554. return false;
  5555. break;
  5556. case 1: // End
  5557. if ($type == 'end') {
  5558. $sendEnd = true;
  5559. }
  5560. break;
  5561. case 2: // start
  5562. if ($type == 'start') {
  5563. $sendStart = true;
  5564. }
  5565. break;
  5566. case 3: // end + open
  5567. if ($type == 'end') {
  5568. $sendEndOpenQuestion = true;
  5569. }
  5570. break;
  5571. case 4: // end + oral
  5572. if ($type == 'end') {
  5573. $sendEndOralQuestion = true;
  5574. }
  5575. break;
  5576. }
  5577. }
  5578. $user_info = api_get_user_info(api_get_user_id());
  5579. $url = api_get_path(WEB_CODE_PATH).'exercise/exercise_show.php?'.
  5580. api_get_cidreq(true, true, 'qualify').'&id='.$exe_id.'&action=qualify';
  5581. if (!empty($sessionId)) {
  5582. $addGeneralCoach = true;
  5583. $setting = api_get_configuration_value('block_quiz_mail_notification_general_coach');
  5584. if ($setting === true) {
  5585. $addGeneralCoach = false;
  5586. }
  5587. $teachers = CourseManager::get_coach_list_from_course_code(
  5588. $courseCode,
  5589. $sessionId,
  5590. $addGeneralCoach
  5591. );
  5592. } else {
  5593. $teachers = CourseManager::get_teacher_list_from_course_code($courseCode);
  5594. }
  5595. if ($sendEndOpenQuestion) {
  5596. $this->sendNotificationForOpenQuestions(
  5597. $question_list_answers,
  5598. $origin,
  5599. $user_info,
  5600. $url,
  5601. $teachers
  5602. );
  5603. }
  5604. if ($sendEndOralQuestion) {
  5605. $this->sendNotificationForOralQuestions(
  5606. $question_list_answers,
  5607. $origin,
  5608. $exe_id,
  5609. $user_info,
  5610. $url,
  5611. $teachers
  5612. );
  5613. }
  5614. if (!$sendEnd && !$sendStart) {
  5615. return false;
  5616. }
  5617. $scoreLabel = '';
  5618. if ($sendEnd &&
  5619. api_get_configuration_value('send_score_in_exam_notification_mail_to_manager') == true
  5620. ) {
  5621. $notificationPercentage = api_get_configuration_value('send_notification_score_in_percentage');
  5622. $scoreLabel = ExerciseLib::show_score($score, $weight, $notificationPercentage, true);
  5623. $scoreLabel = "<tr>
  5624. <td>".get_lang('Score')."</td>
  5625. <td>&nbsp;$scoreLabel</td>
  5626. </tr>";
  5627. }
  5628. if ($sendEnd) {
  5629. $msg = get_lang('ExerciseAttempted').'<br /><br />';
  5630. } else {
  5631. $msg = get_lang('StudentStartExercise').'<br /><br />';
  5632. }
  5633. $msg .= get_lang('AttemptDetails').' : <br /><br />
  5634. <table>
  5635. <tr>
  5636. <td>'.get_lang('CourseName').'</td>
  5637. <td>#course#</td>
  5638. </tr>
  5639. '.$sessionData.'
  5640. <tr>
  5641. <td>'.get_lang('Exercise').'</td>
  5642. <td>&nbsp;#exercise#</td>
  5643. </tr>
  5644. <tr>
  5645. <td>'.get_lang('StudentName').'</td>
  5646. <td>&nbsp;#student_complete_name#</td>
  5647. </tr>
  5648. <tr>
  5649. <td>'.get_lang('StudentEmail').'</td>
  5650. <td>&nbsp;#email#</td>
  5651. </tr>
  5652. '.$scoreLabel.'
  5653. </table>';
  5654. $variables = [
  5655. '#email#' => $user_info['email'],
  5656. '#exercise#' => $this->exercise,
  5657. '#student_complete_name#' => $user_info['complete_name'],
  5658. '#course#' => Display::url(
  5659. $courseInfo['title'],
  5660. $courseInfo['course_public_url'].'?id_session='.$sessionId
  5661. ),
  5662. ];
  5663. if ($sendEnd) {
  5664. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  5665. $variables['#url#'] = $url;
  5666. }
  5667. $content = str_replace(array_keys($variables), array_values($variables), $msg);
  5668. if ($sendEnd) {
  5669. $subject = get_lang('ExerciseAttempted');
  5670. } else {
  5671. $subject = get_lang('StudentStartExercise');
  5672. }
  5673. if (!empty($teachers)) {
  5674. foreach ($teachers as $user_id => $teacher_data) {
  5675. MessageManager::send_message_simple(
  5676. $user_id,
  5677. $subject,
  5678. $content
  5679. );
  5680. }
  5681. }
  5682. }
  5683. /**
  5684. * @param array $user_data result of api_get_user_info()
  5685. * @param array $trackExerciseInfo result of get_stat_track_exercise_info
  5686. *
  5687. * @return string
  5688. */
  5689. public function showExerciseResultHeader(
  5690. $user_data,
  5691. $trackExerciseInfo
  5692. ) {
  5693. if (api_get_configuration_value('hide_user_info_in_quiz_result')) {
  5694. return '';
  5695. }
  5696. $start_date = null;
  5697. if (isset($trackExerciseInfo['start_date'])) {
  5698. $start_date = api_convert_and_format_date($trackExerciseInfo['start_date']);
  5699. }
  5700. $duration = isset($trackExerciseInfo['duration_formatted']) ? $trackExerciseInfo['duration_formatted'] : null;
  5701. $ip = isset($trackExerciseInfo['user_ip']) ? $trackExerciseInfo['user_ip'] : null;
  5702. if (!empty($user_data)) {
  5703. $userFullName = $user_data['complete_name'];
  5704. if (api_is_teacher() || api_is_platform_admin(true, true)) {
  5705. $userFullName = '<a href="'.$user_data['profile_url'].'" title="'.get_lang('GoToStudentDetails').'">'.
  5706. $user_data['complete_name'].'</a>';
  5707. }
  5708. $data = [
  5709. 'name_url' => $userFullName,
  5710. 'complete_name' => $user_data['complete_name'],
  5711. 'username' => $user_data['username'],
  5712. 'avatar' => $user_data['avatar_medium'],
  5713. 'url' => $user_data['profile_url'],
  5714. ];
  5715. if (!empty($user_data['official_code'])) {
  5716. $data['code'] = $user_data['official_code'];
  5717. }
  5718. }
  5719. // Description can be very long and is generally meant to explain
  5720. // rules *before* the exam. Leaving here to make display easier if
  5721. // necessary
  5722. /*
  5723. if (!empty($this->description)) {
  5724. $array[] = array('title' => get_lang("Description"), 'content' => $this->description);
  5725. }
  5726. */
  5727. if (!empty($start_date)) {
  5728. $data['start_date'] = $start_date;
  5729. }
  5730. if (!empty($duration)) {
  5731. $data['duration'] = $duration;
  5732. }
  5733. if (!empty($ip)) {
  5734. $data['ip'] = $ip;
  5735. }
  5736. if (api_get_configuration_value('save_titles_as_html')) {
  5737. $data['title'] = $this->get_formated_title().get_lang('Result');
  5738. } else {
  5739. $data['title'] = PHP_EOL.$this->exercise.' : '.get_lang('Result');
  5740. }
  5741. $tpl = new Template(null, false, false, false, false, false, false);
  5742. $tpl->assign('data', $data);
  5743. $layoutTemplate = $tpl->get_template('exercise/partials/result_exercise.tpl');
  5744. $content = $tpl->fetch($layoutTemplate);
  5745. return $content;
  5746. }
  5747. /**
  5748. * Returns the exercise result.
  5749. *
  5750. * @param int attempt id
  5751. *
  5752. * @return array
  5753. */
  5754. public function get_exercise_result($exe_id)
  5755. {
  5756. $result = [];
  5757. $track_exercise_info = ExerciseLib::get_exercise_track_exercise_info($exe_id);
  5758. if (!empty($track_exercise_info)) {
  5759. $totalScore = 0;
  5760. $objExercise = new Exercise();
  5761. $objExercise->read($track_exercise_info['exe_exo_id']);
  5762. if (!empty($track_exercise_info['data_tracking'])) {
  5763. $question_list = explode(',', $track_exercise_info['data_tracking']);
  5764. }
  5765. foreach ($question_list as $questionId) {
  5766. $question_result = $objExercise->manage_answer(
  5767. $exe_id,
  5768. $questionId,
  5769. '',
  5770. 'exercise_show',
  5771. [],
  5772. false,
  5773. true,
  5774. false,
  5775. $objExercise->selectPropagateNeg()
  5776. );
  5777. $totalScore += $question_result['score'];
  5778. }
  5779. if ($objExercise->selectPropagateNeg() == 0 && $totalScore < 0) {
  5780. $totalScore = 0;
  5781. }
  5782. $result = [
  5783. 'score' => $totalScore,
  5784. 'weight' => $track_exercise_info['exe_weighting'],
  5785. ];
  5786. }
  5787. return $result;
  5788. }
  5789. /**
  5790. * Checks if the exercise is visible due a lot of conditions
  5791. * visibility, time limits, student attempts
  5792. * Return associative array
  5793. * value : true if exercise visible
  5794. * message : HTML formatted message
  5795. * rawMessage : text message.
  5796. *
  5797. * @param int $lpId
  5798. * @param int $lpItemId
  5799. * @param int $lpItemViewId
  5800. * @param bool $filterByAdmin
  5801. *
  5802. * @return array
  5803. */
  5804. public function is_visible(
  5805. $lpId = 0,
  5806. $lpItemId = 0,
  5807. $lpItemViewId = 0,
  5808. $filterByAdmin = true
  5809. ) {
  5810. // 1. By default the exercise is visible
  5811. $isVisible = true;
  5812. $message = null;
  5813. // 1.1 Admins and teachers can access to the exercise
  5814. if ($filterByAdmin) {
  5815. if (api_is_platform_admin() || api_is_course_admin()) {
  5816. return ['value' => true, 'message' => ''];
  5817. }
  5818. }
  5819. // Deleted exercise.
  5820. if ($this->active == -1) {
  5821. return [
  5822. 'value' => false,
  5823. 'message' => Display::return_message(
  5824. get_lang('ExerciseNotFound'),
  5825. 'warning',
  5826. false
  5827. ),
  5828. 'rawMessage' => get_lang('ExerciseNotFound'),
  5829. ];
  5830. }
  5831. // Checking visibility in the item_property table.
  5832. $visibility = api_get_item_visibility(
  5833. api_get_course_info(),
  5834. TOOL_QUIZ,
  5835. $this->id,
  5836. api_get_session_id()
  5837. );
  5838. if ($visibility == 0 || $visibility == 2) {
  5839. $this->active = 0;
  5840. }
  5841. // 2. If the exercise is not active.
  5842. if (empty($lpId)) {
  5843. // 2.1 LP is OFF
  5844. if ($this->active == 0) {
  5845. return [
  5846. 'value' => false,
  5847. 'message' => Display::return_message(
  5848. get_lang('ExerciseNotFound'),
  5849. 'warning',
  5850. false
  5851. ),
  5852. 'rawMessage' => get_lang('ExerciseNotFound'),
  5853. ];
  5854. }
  5855. } else {
  5856. // 2.1 LP is loaded
  5857. if ($this->active == 0 &&
  5858. !learnpath::is_lp_visible_for_student($lpId, api_get_user_id())
  5859. ) {
  5860. return [
  5861. 'value' => false,
  5862. 'message' => Display::return_message(
  5863. get_lang('ExerciseNotFound'),
  5864. 'warning',
  5865. false
  5866. ),
  5867. 'rawMessage' => get_lang('ExerciseNotFound'),
  5868. ];
  5869. }
  5870. }
  5871. // 3. We check if the time limits are on
  5872. $limitTimeExists = false;
  5873. if (!empty($this->start_time) || !empty($this->end_time)) {
  5874. $limitTimeExists = true;
  5875. }
  5876. if ($limitTimeExists) {
  5877. $timeNow = time();
  5878. $existsStartDate = false;
  5879. $nowIsAfterStartDate = true;
  5880. $existsEndDate = false;
  5881. $nowIsBeforeEndDate = true;
  5882. if (!empty($this->start_time)) {
  5883. $existsStartDate = true;
  5884. }
  5885. if (!empty($this->end_time)) {
  5886. $existsEndDate = true;
  5887. }
  5888. // check if we are before-or-after end-or-start date
  5889. if ($existsStartDate && $timeNow < api_strtotime($this->start_time, 'UTC')) {
  5890. $nowIsAfterStartDate = false;
  5891. }
  5892. if ($existsEndDate & $timeNow >= api_strtotime($this->end_time, 'UTC')) {
  5893. $nowIsBeforeEndDate = false;
  5894. }
  5895. // lets check all cases
  5896. if ($existsStartDate && !$existsEndDate) {
  5897. // exists start date and dont exists end date
  5898. if ($nowIsAfterStartDate) {
  5899. // after start date, no end date
  5900. $isVisible = true;
  5901. $message = sprintf(
  5902. get_lang('ExerciseAvailableSinceX'),
  5903. api_convert_and_format_date($this->start_time)
  5904. );
  5905. } else {
  5906. // before start date, no end date
  5907. $isVisible = false;
  5908. $message = sprintf(
  5909. get_lang('ExerciseAvailableFromX'),
  5910. api_convert_and_format_date($this->start_time)
  5911. );
  5912. }
  5913. } elseif (!$existsStartDate && $existsEndDate) {
  5914. // doesnt exist start date, exists end date
  5915. if ($nowIsBeforeEndDate) {
  5916. // before end date, no start date
  5917. $isVisible = true;
  5918. $message = sprintf(
  5919. get_lang('ExerciseAvailableUntilX'),
  5920. api_convert_and_format_date($this->end_time)
  5921. );
  5922. } else {
  5923. // after end date, no start date
  5924. $isVisible = false;
  5925. $message = sprintf(
  5926. get_lang('ExerciseAvailableUntilX'),
  5927. api_convert_and_format_date($this->end_time)
  5928. );
  5929. }
  5930. } elseif ($existsStartDate && $existsEndDate) {
  5931. // exists start date and end date
  5932. if ($nowIsAfterStartDate) {
  5933. if ($nowIsBeforeEndDate) {
  5934. // after start date and before end date
  5935. $isVisible = true;
  5936. $message = sprintf(
  5937. get_lang('ExerciseIsActivatedFromXToY'),
  5938. api_convert_and_format_date($this->start_time),
  5939. api_convert_and_format_date($this->end_time)
  5940. );
  5941. } else {
  5942. // after start date and after end date
  5943. $isVisible = false;
  5944. $message = sprintf(
  5945. get_lang('ExerciseWasActivatedFromXToY'),
  5946. api_convert_and_format_date($this->start_time),
  5947. api_convert_and_format_date($this->end_time)
  5948. );
  5949. }
  5950. } else {
  5951. if ($nowIsBeforeEndDate) {
  5952. // before start date and before end date
  5953. $isVisible = false;
  5954. $message = sprintf(
  5955. get_lang('ExerciseWillBeActivatedFromXToY'),
  5956. api_convert_and_format_date($this->start_time),
  5957. api_convert_and_format_date($this->end_time)
  5958. );
  5959. }
  5960. // case before start date and after end date is impossible
  5961. }
  5962. } elseif (!$existsStartDate && !$existsEndDate) {
  5963. // doesnt exist start date nor end date
  5964. $isVisible = true;
  5965. $message = '';
  5966. }
  5967. }
  5968. // 4. We check if the student have attempts
  5969. if ($isVisible) {
  5970. $exerciseAttempts = $this->selectAttempts();
  5971. if ($exerciseAttempts > 0) {
  5972. $attemptCount = Event::get_attempt_count_not_finished(
  5973. api_get_user_id(),
  5974. $this->id,
  5975. $lpId,
  5976. $lpItemId,
  5977. $lpItemViewId
  5978. );
  5979. if ($attemptCount >= $exerciseAttempts) {
  5980. $message = sprintf(
  5981. get_lang('ReachedMaxAttempts'),
  5982. $this->name,
  5983. $exerciseAttempts
  5984. );
  5985. $isVisible = false;
  5986. }
  5987. }
  5988. }
  5989. $rawMessage = '';
  5990. if (!empty($message)) {
  5991. $rawMessage = $message;
  5992. $message = Display::return_message($message, 'warning', false);
  5993. }
  5994. return [
  5995. 'value' => $isVisible,
  5996. 'message' => $message,
  5997. 'rawMessage' => $rawMessage,
  5998. ];
  5999. }
  6000. /**
  6001. * @return bool
  6002. */
  6003. public function added_in_lp()
  6004. {
  6005. $TBL_LP_ITEM = Database::get_course_table(TABLE_LP_ITEM);
  6006. $sql = "SELECT max_score FROM $TBL_LP_ITEM
  6007. WHERE
  6008. c_id = {$this->course_id} AND
  6009. item_type = '".TOOL_QUIZ."' AND
  6010. path = '{$this->id}'";
  6011. $result = Database::query($sql);
  6012. if (Database::num_rows($result) > 0) {
  6013. return true;
  6014. }
  6015. return false;
  6016. }
  6017. /**
  6018. * Returns an array with this form.
  6019. *
  6020. * @example
  6021. * <code>
  6022. * array (size=3)
  6023. * 999 =>
  6024. * array (size=3)
  6025. * 0 => int 3422
  6026. * 1 => int 3423
  6027. * 2 => int 3424
  6028. * 100 =>
  6029. * array (size=2)
  6030. * 0 => int 3469
  6031. * 1 => int 3470
  6032. * 101 =>
  6033. * array (size=1)
  6034. * 0 => int 3482
  6035. * </code>
  6036. * The array inside the key 999 means the question list that belongs to the media id = 999,
  6037. * this case is special because 999 means "no media".
  6038. *
  6039. * @return array
  6040. */
  6041. public function getMediaList()
  6042. {
  6043. return $this->mediaList;
  6044. }
  6045. /**
  6046. * Is media question activated?
  6047. *
  6048. * @return bool
  6049. */
  6050. public function mediaIsActivated()
  6051. {
  6052. $mediaQuestions = $this->getMediaList();
  6053. $active = false;
  6054. if (isset($mediaQuestions) && !empty($mediaQuestions)) {
  6055. $media_count = count($mediaQuestions);
  6056. if ($media_count > 1) {
  6057. return true;
  6058. } elseif ($media_count == 1) {
  6059. if (isset($mediaQuestions[999])) {
  6060. return false;
  6061. } else {
  6062. return true;
  6063. }
  6064. }
  6065. }
  6066. return $active;
  6067. }
  6068. /**
  6069. * Gets question list from the exercise.
  6070. *
  6071. * @return array
  6072. */
  6073. public function getQuestionList()
  6074. {
  6075. return $this->questionList;
  6076. }
  6077. /**
  6078. * Question list with medias compressed like this.
  6079. *
  6080. * @example
  6081. * <code>
  6082. * array(
  6083. * question_id_1,
  6084. * question_id_2,
  6085. * media_id, <- this media id contains question ids
  6086. * question_id_3,
  6087. * )
  6088. * </code>
  6089. *
  6090. * @return array
  6091. */
  6092. public function getQuestionListWithMediasCompressed()
  6093. {
  6094. return $this->questionList;
  6095. }
  6096. /**
  6097. * Question list with medias uncompressed like this.
  6098. *
  6099. * @example
  6100. * <code>
  6101. * array(
  6102. * question_id,
  6103. * question_id,
  6104. * question_id, <- belongs to a media id
  6105. * question_id, <- belongs to a media id
  6106. * question_id,
  6107. * )
  6108. * </code>
  6109. *
  6110. * @return array
  6111. */
  6112. public function getQuestionListWithMediasUncompressed()
  6113. {
  6114. return $this->questionListUncompressed;
  6115. }
  6116. /**
  6117. * Sets the question list when the exercise->read() is executed.
  6118. *
  6119. * @param bool $adminView Whether to view the set the list of *all* questions or just the normal student view
  6120. */
  6121. public function setQuestionList($adminView = false)
  6122. {
  6123. // Getting question list.
  6124. $questionList = $this->selectQuestionList(true, $adminView);
  6125. $this->setMediaList($questionList);
  6126. $this->questionList = $this->transformQuestionListWithMedias(
  6127. $questionList,
  6128. false
  6129. );
  6130. $this->questionListUncompressed = $this->transformQuestionListWithMedias(
  6131. $questionList,
  6132. true
  6133. );
  6134. }
  6135. /**
  6136. * @params array question list
  6137. * @params bool expand or not question list (true show all questions,
  6138. * false show media question id instead of the question ids)
  6139. */
  6140. public function transformQuestionListWithMedias(
  6141. $question_list,
  6142. $expand_media_questions = false
  6143. ) {
  6144. $new_question_list = [];
  6145. if (!empty($question_list)) {
  6146. $media_questions = $this->getMediaList();
  6147. $media_active = $this->mediaIsActivated($media_questions);
  6148. if ($media_active) {
  6149. $counter = 1;
  6150. foreach ($question_list as $question_id) {
  6151. $add_question = true;
  6152. foreach ($media_questions as $media_id => $question_list_in_media) {
  6153. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  6154. $add_question = false;
  6155. if (!in_array($media_id, $new_question_list)) {
  6156. $new_question_list[$counter] = $media_id;
  6157. $counter++;
  6158. }
  6159. break;
  6160. }
  6161. }
  6162. if ($add_question) {
  6163. $new_question_list[$counter] = $question_id;
  6164. $counter++;
  6165. }
  6166. }
  6167. if ($expand_media_questions) {
  6168. $media_key_list = array_keys($media_questions);
  6169. foreach ($new_question_list as &$question_id) {
  6170. if (in_array($question_id, $media_key_list)) {
  6171. $question_id = $media_questions[$question_id];
  6172. }
  6173. }
  6174. $new_question_list = array_flatten($new_question_list);
  6175. }
  6176. } else {
  6177. $new_question_list = $question_list;
  6178. }
  6179. }
  6180. return $new_question_list;
  6181. }
  6182. /**
  6183. * Get question list depend on the random settings.
  6184. *
  6185. * @return array
  6186. */
  6187. public function get_validated_question_list()
  6188. {
  6189. $isRandomByCategory = $this->isRandomByCat();
  6190. if ($isRandomByCategory == 0) {
  6191. if ($this->isRandom()) {
  6192. return $this->getRandomList();
  6193. }
  6194. return $this->selectQuestionList();
  6195. }
  6196. if ($this->isRandom()) {
  6197. // USE question categories
  6198. // get questions by category for this exercise
  6199. // we have to choice $objExercise->random question in each array values of $tabCategoryQuestions
  6200. // key of $tabCategoryQuestions are the categopy id (0 for not in a category)
  6201. // value is the array of question id of this category
  6202. $questionList = [];
  6203. $tabCategoryQuestions = TestCategory::getQuestionsByCat($this->id);
  6204. $isRandomByCategory = $this->getRandomByCategory();
  6205. // We sort categories based on the term between [] in the head
  6206. // of the category's description
  6207. /* examples of categories :
  6208. * [biologie] Maitriser les mecanismes de base de la genetique
  6209. * [biologie] Relier les moyens de depenses et les agents infectieux
  6210. * [biologie] Savoir ou est produite l'enrgie dans les cellules et sous quelle forme
  6211. * [chimie] Classer les molles suivant leur pouvoir oxydant ou reacteur
  6212. * [chimie] Connaître la denition de la theoie acide/base selon Brönsted
  6213. * [chimie] Connaître les charges des particules
  6214. * We want that in the order of the groups defined by the term
  6215. * between brackets at the beginning of the category title
  6216. */
  6217. // If test option is Grouped By Categories
  6218. if ($isRandomByCategory == 2) {
  6219. $tabCategoryQuestions = TestCategory::sortTabByBracketLabel($tabCategoryQuestions);
  6220. }
  6221. foreach ($tabCategoryQuestions as $tabquestion) {
  6222. $number_of_random_question = $this->random;
  6223. if ($this->random == -1) {
  6224. $number_of_random_question = count($this->questionList);
  6225. }
  6226. $questionList = array_merge(
  6227. $questionList,
  6228. TestCategory::getNElementsFromArray(
  6229. $tabquestion,
  6230. $number_of_random_question
  6231. )
  6232. );
  6233. }
  6234. // shuffle the question list if test is not grouped by categories
  6235. if ($isRandomByCategory == 1) {
  6236. shuffle($questionList); // or not
  6237. }
  6238. return $questionList;
  6239. }
  6240. // Problem, random by category has been selected and
  6241. // we have no $this->isRandom number of question selected
  6242. // Should not happened
  6243. return [];
  6244. }
  6245. public function get_question_list($expand_media_questions = false)
  6246. {
  6247. $question_list = $this->get_validated_question_list();
  6248. $question_list = $this->transform_question_list_with_medias($question_list, $expand_media_questions);
  6249. return $question_list;
  6250. }
  6251. public function transform_question_list_with_medias($question_list, $expand_media_questions = false)
  6252. {
  6253. $new_question_list = [];
  6254. if (!empty($question_list)) {
  6255. $media_questions = $this->getMediaList();
  6256. $media_active = $this->mediaIsActivated($media_questions);
  6257. if ($media_active) {
  6258. $counter = 1;
  6259. foreach ($question_list as $question_id) {
  6260. $add_question = true;
  6261. foreach ($media_questions as $media_id => $question_list_in_media) {
  6262. if ($media_id != 999 && in_array($question_id, $question_list_in_media)) {
  6263. $add_question = false;
  6264. if (!in_array($media_id, $new_question_list)) {
  6265. $new_question_list[$counter] = $media_id;
  6266. $counter++;
  6267. }
  6268. break;
  6269. }
  6270. }
  6271. if ($add_question) {
  6272. $new_question_list[$counter] = $question_id;
  6273. $counter++;
  6274. }
  6275. }
  6276. if ($expand_media_questions) {
  6277. $media_key_list = array_keys($media_questions);
  6278. foreach ($new_question_list as &$question_id) {
  6279. if (in_array($question_id, $media_key_list)) {
  6280. $question_id = $media_questions[$question_id];
  6281. }
  6282. }
  6283. $new_question_list = array_flatten($new_question_list);
  6284. }
  6285. } else {
  6286. $new_question_list = $question_list;
  6287. }
  6288. }
  6289. return $new_question_list;
  6290. }
  6291. /**
  6292. * @param int $exe_id
  6293. *
  6294. * @return array
  6295. */
  6296. public function get_stat_track_exercise_info_by_exe_id($exe_id)
  6297. {
  6298. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6299. $exe_id = (int) $exe_id;
  6300. $sql_track = "SELECT * FROM $table WHERE exe_id = $exe_id ";
  6301. $result = Database::query($sql_track);
  6302. $new_array = [];
  6303. if (Database::num_rows($result) > 0) {
  6304. $new_array = Database::fetch_array($result, 'ASSOC');
  6305. $start_date = api_get_utc_datetime($new_array['start_date'], true);
  6306. $end_date = api_get_utc_datetime($new_array['exe_date'], true);
  6307. $new_array['duration_formatted'] = '';
  6308. if (!empty($new_array['exe_duration']) && !empty($start_date) && !empty($end_date)) {
  6309. $time = api_format_time($new_array['exe_duration'], 'js');
  6310. $new_array['duration_formatted'] = $time;
  6311. }
  6312. }
  6313. return $new_array;
  6314. }
  6315. /**
  6316. * @param int $exeId
  6317. *
  6318. * @return bool
  6319. */
  6320. public function removeAllQuestionToRemind($exeId)
  6321. {
  6322. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6323. $exeId = (int) $exeId;
  6324. if (empty($exeId)) {
  6325. return false;
  6326. }
  6327. $sql = "UPDATE $table
  6328. SET questions_to_check = ''
  6329. WHERE exe_id = $exeId ";
  6330. Database::query($sql);
  6331. return true;
  6332. }
  6333. /**
  6334. * @param int $exeId
  6335. * @param array $questionList
  6336. *
  6337. * @return bool
  6338. */
  6339. public function addAllQuestionToRemind($exeId, $questionList = [])
  6340. {
  6341. $exeId = (int) $exeId;
  6342. if (empty($questionList)) {
  6343. return false;
  6344. }
  6345. $questionListToString = implode(',', $questionList);
  6346. $questionListToString = Database::escape_string($questionListToString);
  6347. $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6348. $sql = "UPDATE $table
  6349. SET questions_to_check = '$questionListToString'
  6350. WHERE exe_id = $exeId";
  6351. Database::query($sql);
  6352. return true;
  6353. }
  6354. /**
  6355. * @param int $exe_id
  6356. * @param int $question_id
  6357. * @param string $action
  6358. */
  6359. public function editQuestionToRemind($exe_id, $question_id, $action = 'add')
  6360. {
  6361. $exercise_info = self::get_stat_track_exercise_info_by_exe_id($exe_id);
  6362. $question_id = (int) $question_id;
  6363. $exe_id = (int) $exe_id;
  6364. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  6365. if ($exercise_info) {
  6366. if (empty($exercise_info['questions_to_check'])) {
  6367. if ($action == 'add') {
  6368. $sql = "UPDATE $track_exercises
  6369. SET questions_to_check = '$question_id'
  6370. WHERE exe_id = $exe_id ";
  6371. Database::query($sql);
  6372. }
  6373. } else {
  6374. $remind_list = explode(',', $exercise_info['questions_to_check']);
  6375. $remind_list_string = '';
  6376. if ($action == 'add') {
  6377. if (!in_array($question_id, $remind_list)) {
  6378. $newRemindList = [];
  6379. $remind_list[] = $question_id;
  6380. $questionListInSession = Session::read('questionList');
  6381. if (!empty($questionListInSession)) {
  6382. foreach ($questionListInSession as $originalQuestionId) {
  6383. if (in_array($originalQuestionId, $remind_list)) {
  6384. $newRemindList[] = $originalQuestionId;
  6385. }
  6386. }
  6387. }
  6388. $remind_list_string = implode(',', $newRemindList);
  6389. }
  6390. } elseif ($action == 'delete') {
  6391. if (!empty($remind_list)) {
  6392. if (in_array($question_id, $remind_list)) {
  6393. $remind_list = array_flip($remind_list);
  6394. unset($remind_list[$question_id]);
  6395. $remind_list = array_flip($remind_list);
  6396. if (!empty($remind_list)) {
  6397. sort($remind_list);
  6398. array_filter($remind_list);
  6399. $remind_list_string = implode(',', $remind_list);
  6400. }
  6401. }
  6402. }
  6403. }
  6404. $value = Database::escape_string($remind_list_string);
  6405. $sql = "UPDATE $track_exercises
  6406. SET questions_to_check = '$value'
  6407. WHERE exe_id = $exe_id ";
  6408. Database::query($sql);
  6409. }
  6410. }
  6411. }
  6412. /**
  6413. * @param string $answer
  6414. *
  6415. * @return mixed
  6416. */
  6417. public function fill_in_blank_answer_to_array($answer)
  6418. {
  6419. api_preg_match_all('/\[[^]]+\]/', $answer, $teacher_answer_list);
  6420. $teacher_answer_list = $teacher_answer_list[0];
  6421. return $teacher_answer_list;
  6422. }
  6423. /**
  6424. * @param string $answer
  6425. *
  6426. * @return string
  6427. */
  6428. public function fill_in_blank_answer_to_string($answer)
  6429. {
  6430. $teacher_answer_list = $this->fill_in_blank_answer_to_array($answer);
  6431. $result = '';
  6432. if (!empty($teacher_answer_list)) {
  6433. $i = 0;
  6434. foreach ($teacher_answer_list as $teacher_item) {
  6435. $value = null;
  6436. //Cleaning student answer list
  6437. $value = strip_tags($teacher_item);
  6438. $value = api_substr($value, 1, api_strlen($value) - 2);
  6439. $value = explode('/', $value);
  6440. if (!empty($value[0])) {
  6441. $value = trim($value[0]);
  6442. $value = str_replace('&nbsp;', '', $value);
  6443. $result .= $value;
  6444. }
  6445. }
  6446. }
  6447. return $result;
  6448. }
  6449. /**
  6450. * @return string
  6451. */
  6452. public function returnTimeLeftDiv()
  6453. {
  6454. $html = '<div id="clock_warning" style="display:none">';
  6455. $html .= Display::return_message(
  6456. get_lang('ReachedTimeLimit'),
  6457. 'warning'
  6458. );
  6459. $html .= ' ';
  6460. $html .= sprintf(
  6461. get_lang('YouWillBeRedirectedInXSeconds'),
  6462. '<span id="counter_to_redirect" class="red_alert"></span>'
  6463. );
  6464. $html .= '</div>';
  6465. $html .= '<div id="exercise_clock_warning" class="count_down"></div>';
  6466. return $html;
  6467. }
  6468. /**
  6469. * Get categories added in the exercise--category matrix.
  6470. *
  6471. * @return array
  6472. */
  6473. public function getCategoriesInExercise()
  6474. {
  6475. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6476. if (!empty($this->id)) {
  6477. $sql = "SELECT * FROM $table
  6478. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id} ";
  6479. $result = Database::query($sql);
  6480. $list = [];
  6481. if (Database::num_rows($result)) {
  6482. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6483. $list[$row['category_id']] = $row;
  6484. }
  6485. return $list;
  6486. }
  6487. }
  6488. return [];
  6489. }
  6490. /**
  6491. * Get total number of question that will be parsed when using the category/exercise.
  6492. *
  6493. * @return int
  6494. */
  6495. public function getNumberQuestionExerciseCategory()
  6496. {
  6497. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6498. if (!empty($this->id)) {
  6499. $sql = "SELECT SUM(count_questions) count_questions
  6500. FROM $table
  6501. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6502. $result = Database::query($sql);
  6503. if (Database::num_rows($result)) {
  6504. $row = Database::fetch_array($result);
  6505. return (int) $row['count_questions'];
  6506. }
  6507. }
  6508. return 0;
  6509. }
  6510. /**
  6511. * Save categories in the TABLE_QUIZ_REL_CATEGORY table.
  6512. *
  6513. * @param array $categories
  6514. */
  6515. public function save_categories_in_exercise($categories)
  6516. {
  6517. if (!empty($categories) && !empty($this->id)) {
  6518. $table = Database::get_course_table(TABLE_QUIZ_REL_CATEGORY);
  6519. $sql = "DELETE FROM $table
  6520. WHERE exercise_id = {$this->id} AND c_id = {$this->course_id}";
  6521. Database::query($sql);
  6522. if (!empty($categories)) {
  6523. foreach ($categories as $categoryId => $countQuestions) {
  6524. $params = [
  6525. 'c_id' => $this->course_id,
  6526. 'exercise_id' => $this->id,
  6527. 'category_id' => $categoryId,
  6528. 'count_questions' => $countQuestions,
  6529. ];
  6530. Database::insert($table, $params);
  6531. }
  6532. }
  6533. }
  6534. }
  6535. /**
  6536. * @param array $questionList
  6537. * @param int $currentQuestion
  6538. * @param array $conditions
  6539. * @param string $link
  6540. *
  6541. * @return string
  6542. */
  6543. public function progressExercisePaginationBar(
  6544. $questionList,
  6545. $currentQuestion,
  6546. $conditions,
  6547. $link
  6548. ) {
  6549. $mediaQuestions = $this->getMediaList();
  6550. $html = '<div class="exercise_pagination pagination pagination-mini"><ul>';
  6551. $counter = 0;
  6552. $nextValue = 0;
  6553. $wasMedia = false;
  6554. $before = 0;
  6555. $counterNoMedias = 0;
  6556. foreach ($questionList as $questionId) {
  6557. $isCurrent = $currentQuestion == ($counterNoMedias + 1) ? true : false;
  6558. if (!empty($nextValue)) {
  6559. if ($wasMedia) {
  6560. $nextValue = $nextValue - $before + 1;
  6561. }
  6562. }
  6563. if (isset($mediaQuestions) && isset($mediaQuestions[$questionId])) {
  6564. $fixedValue = $counterNoMedias;
  6565. $html .= Display::progressPaginationBar(
  6566. $nextValue,
  6567. $mediaQuestions[$questionId],
  6568. $currentQuestion,
  6569. $fixedValue,
  6570. $conditions,
  6571. $link,
  6572. true,
  6573. true
  6574. );
  6575. $counter += count($mediaQuestions[$questionId]) - 1;
  6576. $before = count($questionList);
  6577. $wasMedia = true;
  6578. $nextValue += count($questionList);
  6579. } else {
  6580. $html .= Display::parsePaginationItem(
  6581. $questionId,
  6582. $isCurrent,
  6583. $conditions,
  6584. $link,
  6585. $counter
  6586. );
  6587. $counter++;
  6588. $nextValue++;
  6589. $wasMedia = false;
  6590. }
  6591. $counterNoMedias++;
  6592. }
  6593. $html .= '</ul></div>';
  6594. return $html;
  6595. }
  6596. /**
  6597. * Shows a list of numbers that represents the question to answer in a exercise.
  6598. *
  6599. * @param array $categories
  6600. * @param int $current
  6601. * @param array $conditions
  6602. * @param string $link
  6603. *
  6604. * @return string
  6605. */
  6606. public function progressExercisePaginationBarWithCategories(
  6607. $categories,
  6608. $current,
  6609. $conditions = [],
  6610. $link = null
  6611. ) {
  6612. $html = null;
  6613. $counterNoMedias = 0;
  6614. $nextValue = 0;
  6615. $wasMedia = false;
  6616. $before = 0;
  6617. if (!empty($categories)) {
  6618. $selectionType = $this->getQuestionSelectionType();
  6619. $useRootAsCategoryTitle = false;
  6620. // Grouping questions per parent category see BT#6540
  6621. if (in_array(
  6622. $selectionType,
  6623. [
  6624. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_ORDERED,
  6625. EX_Q_SELECTION_CATEGORIES_ORDERED_BY_PARENT_QUESTIONS_RANDOM,
  6626. ]
  6627. )) {
  6628. $useRootAsCategoryTitle = true;
  6629. }
  6630. // If the exercise is set to only show the titles of the categories
  6631. // at the root of the tree, then pre-order the categories tree by
  6632. // removing children and summing their questions into the parent
  6633. // categories
  6634. if ($useRootAsCategoryTitle) {
  6635. // The new categories list starts empty
  6636. $newCategoryList = [];
  6637. foreach ($categories as $category) {
  6638. $rootElement = $category['root'];
  6639. if (isset($category['parent_info'])) {
  6640. $rootElement = $category['parent_info']['id'];
  6641. }
  6642. //$rootElement = $category['id'];
  6643. // If the current category's ancestor was never seen
  6644. // before, then declare it and assign the current
  6645. // category to it.
  6646. if (!isset($newCategoryList[$rootElement])) {
  6647. $newCategoryList[$rootElement] = $category;
  6648. } else {
  6649. // If it was already seen, then merge the previous with
  6650. // the current category
  6651. $oldQuestionList = $newCategoryList[$rootElement]['question_list'];
  6652. $category['question_list'] = array_merge($oldQuestionList, $category['question_list']);
  6653. $newCategoryList[$rootElement] = $category;
  6654. }
  6655. }
  6656. // Now use the newly built categories list, with only parents
  6657. $categories = $newCategoryList;
  6658. }
  6659. foreach ($categories as $category) {
  6660. $questionList = $category['question_list'];
  6661. // Check if in this category there questions added in a media
  6662. $mediaQuestionId = $category['media_question'];
  6663. $isMedia = false;
  6664. $fixedValue = null;
  6665. // Media exists!
  6666. if ($mediaQuestionId != 999) {
  6667. $isMedia = true;
  6668. $fixedValue = $counterNoMedias;
  6669. }
  6670. //$categoryName = $category['path']; << show the path
  6671. $categoryName = $category['name'];
  6672. if ($useRootAsCategoryTitle) {
  6673. if (isset($category['parent_info'])) {
  6674. $categoryName = $category['parent_info']['title'];
  6675. }
  6676. }
  6677. $html .= '<div class="row">';
  6678. $html .= '<div class="span2">'.$categoryName.'</div>';
  6679. $html .= '<div class="span8">';
  6680. if (!empty($nextValue)) {
  6681. if ($wasMedia) {
  6682. $nextValue = $nextValue - $before + 1;
  6683. }
  6684. }
  6685. $html .= Display::progressPaginationBar(
  6686. $nextValue,
  6687. $questionList,
  6688. $current,
  6689. $fixedValue,
  6690. $conditions,
  6691. $link,
  6692. $isMedia,
  6693. true
  6694. );
  6695. $html .= '</div>';
  6696. $html .= '</div>';
  6697. if ($mediaQuestionId == 999) {
  6698. $counterNoMedias += count($questionList);
  6699. } else {
  6700. $counterNoMedias++;
  6701. }
  6702. $nextValue += count($questionList);
  6703. $before = count($questionList);
  6704. if ($mediaQuestionId != 999) {
  6705. $wasMedia = true;
  6706. } else {
  6707. $wasMedia = false;
  6708. }
  6709. }
  6710. }
  6711. return $html;
  6712. }
  6713. /**
  6714. * Renders a question list.
  6715. *
  6716. * @param array $questionList (with media questions compressed)
  6717. * @param int $currentQuestion
  6718. * @param array $exerciseResult
  6719. * @param array $attemptList
  6720. * @param array $remindList
  6721. */
  6722. public function renderQuestionList(
  6723. $questionList,
  6724. $currentQuestion,
  6725. $exerciseResult,
  6726. $attemptList,
  6727. $remindList
  6728. ) {
  6729. $mediaQuestions = $this->getMediaList();
  6730. $i = 0;
  6731. // Normal question list render (medias compressed)
  6732. foreach ($questionList as $questionId) {
  6733. $i++;
  6734. // For sequential exercises
  6735. if ($this->type == ONE_PER_PAGE) {
  6736. // If it is not the right question, goes to the next loop iteration
  6737. if ($currentQuestion != $i) {
  6738. continue;
  6739. } else {
  6740. if (!in_array(
  6741. $this->getFeedbackType(),
  6742. [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP]
  6743. )) {
  6744. // if the user has already answered this question
  6745. if (isset($exerciseResult[$questionId])) {
  6746. echo Display::return_message(
  6747. get_lang('AlreadyAnswered'),
  6748. 'normal'
  6749. );
  6750. break;
  6751. }
  6752. }
  6753. }
  6754. }
  6755. // The $questionList contains the media id we check
  6756. // if this questionId is a media question type
  6757. if (isset($mediaQuestions[$questionId]) &&
  6758. $mediaQuestions[$questionId] != 999
  6759. ) {
  6760. // The question belongs to a media
  6761. $mediaQuestionList = $mediaQuestions[$questionId];
  6762. $objQuestionTmp = Question::read($questionId);
  6763. $counter = 1;
  6764. if ($objQuestionTmp->type == MEDIA_QUESTION) {
  6765. echo $objQuestionTmp->show_media_content();
  6766. $countQuestionsInsideMedia = count($mediaQuestionList);
  6767. // Show questions that belongs to a media
  6768. if (!empty($mediaQuestionList)) {
  6769. // In order to parse media questions we use letters a, b, c, etc.
  6770. $letterCounter = 97;
  6771. foreach ($mediaQuestionList as $questionIdInsideMedia) {
  6772. $isLastQuestionInMedia = false;
  6773. if ($counter == $countQuestionsInsideMedia) {
  6774. $isLastQuestionInMedia = true;
  6775. }
  6776. $this->renderQuestion(
  6777. $questionIdInsideMedia,
  6778. $attemptList,
  6779. $remindList,
  6780. chr($letterCounter),
  6781. $currentQuestion,
  6782. $mediaQuestionList,
  6783. $isLastQuestionInMedia,
  6784. $questionList
  6785. );
  6786. $letterCounter++;
  6787. $counter++;
  6788. }
  6789. }
  6790. } else {
  6791. $this->renderQuestion(
  6792. $questionId,
  6793. $attemptList,
  6794. $remindList,
  6795. $i,
  6796. $currentQuestion,
  6797. null,
  6798. null,
  6799. $questionList
  6800. );
  6801. $i++;
  6802. }
  6803. } else {
  6804. // Normal question render.
  6805. $this->renderQuestion(
  6806. $questionId,
  6807. $attemptList,
  6808. $remindList,
  6809. $i,
  6810. $currentQuestion,
  6811. null,
  6812. null,
  6813. $questionList
  6814. );
  6815. }
  6816. // For sequential exercises.
  6817. if ($this->type == ONE_PER_PAGE) {
  6818. // quits the loop
  6819. break;
  6820. }
  6821. }
  6822. // end foreach()
  6823. if ($this->type == ALL_ON_ONE_PAGE) {
  6824. $exercise_actions = $this->show_button($questionId, $currentQuestion);
  6825. echo Display::div($exercise_actions, ['class' => 'exercise_actions']);
  6826. }
  6827. }
  6828. /**
  6829. * @param int $questionId
  6830. * @param array $attemptList
  6831. * @param array $remindList
  6832. * @param int $i
  6833. * @param int $current_question
  6834. * @param array $questions_in_media
  6835. * @param bool $last_question_in_media
  6836. * @param array $realQuestionList
  6837. * @param bool $generateJS
  6838. */
  6839. public function renderQuestion(
  6840. $questionId,
  6841. $attemptList,
  6842. $remindList,
  6843. $i,
  6844. $current_question,
  6845. $questions_in_media = [],
  6846. $last_question_in_media = false,
  6847. $realQuestionList,
  6848. $generateJS = true
  6849. ) {
  6850. // With this option on the question is loaded via AJAX
  6851. //$generateJS = true;
  6852. //$this->loadQuestionAJAX = true;
  6853. if ($generateJS && $this->loadQuestionAJAX) {
  6854. $url = api_get_path(WEB_AJAX_PATH).'exercise.ajax.php?a=get_question&id='.$questionId.'&'.api_get_cidreq();
  6855. $params = [
  6856. 'questionId' => $questionId,
  6857. 'attemptList' => $attemptList,
  6858. 'remindList' => $remindList,
  6859. 'i' => $i,
  6860. 'current_question' => $current_question,
  6861. 'questions_in_media' => $questions_in_media,
  6862. 'last_question_in_media' => $last_question_in_media,
  6863. ];
  6864. $params = json_encode($params);
  6865. $script = '<script>
  6866. $(function(){
  6867. var params = '.$params.';
  6868. $.ajax({
  6869. type: "GET",
  6870. async: false,
  6871. data: params,
  6872. url: "'.$url.'",
  6873. success: function(return_value) {
  6874. $("#ajaxquestiondiv'.$questionId.'").html(return_value);
  6875. }
  6876. });
  6877. });
  6878. </script>
  6879. <div id="ajaxquestiondiv'.$questionId.'"></div>';
  6880. echo $script;
  6881. } else {
  6882. global $origin;
  6883. $question_obj = Question::read($questionId);
  6884. $user_choice = isset($attemptList[$questionId]) ? $attemptList[$questionId] : null;
  6885. $remind_highlight = null;
  6886. // Hides questions when reviewing a ALL_ON_ONE_PAGE exercise
  6887. // see #4542 no_remind_highlight class hide with jquery
  6888. if ($this->type == ALL_ON_ONE_PAGE && isset($_GET['reminder']) && $_GET['reminder'] == 2) {
  6889. $remind_highlight = 'no_remind_highlight';
  6890. if (in_array($question_obj->type, Question::question_type_no_review())) {
  6891. return null;
  6892. }
  6893. }
  6894. $attributes = ['id' => 'remind_list['.$questionId.']'];
  6895. // Showing the question
  6896. $exercise_actions = null;
  6897. echo '<a id="questionanchor'.$questionId.'"></a><br />';
  6898. echo '<div id="question_div_'.$questionId.'" class="main_question '.$remind_highlight.'" >';
  6899. // Shows the question + possible answers
  6900. $showTitle = $this->getHideQuestionTitle() == 1 ? false : true;
  6901. echo $this->showQuestion(
  6902. $question_obj,
  6903. false,
  6904. $origin,
  6905. $i,
  6906. $showTitle,
  6907. false,
  6908. $user_choice,
  6909. false,
  6910. null,
  6911. false,
  6912. $this->getModelType(),
  6913. $this->categoryMinusOne
  6914. );
  6915. // Button save and continue
  6916. switch ($this->type) {
  6917. case ONE_PER_PAGE:
  6918. $exercise_actions .= $this->show_button(
  6919. $questionId,
  6920. $current_question,
  6921. null,
  6922. $remindList
  6923. );
  6924. break;
  6925. case ALL_ON_ONE_PAGE:
  6926. if (api_is_allowed_to_session_edit()) {
  6927. $button = [
  6928. Display::button(
  6929. 'save_now',
  6930. get_lang('SaveForNow'),
  6931. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6932. ),
  6933. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>',
  6934. ];
  6935. $exercise_actions .= Display::div(
  6936. implode(PHP_EOL, $button),
  6937. ['class' => 'exercise_save_now_button']
  6938. );
  6939. }
  6940. break;
  6941. }
  6942. if (!empty($questions_in_media)) {
  6943. $count_of_questions_inside_media = count($questions_in_media);
  6944. if ($count_of_questions_inside_media > 1 && api_is_allowed_to_session_edit()) {
  6945. $button = [
  6946. Display::button(
  6947. 'save_now',
  6948. get_lang('SaveForNow'),
  6949. ['type' => 'button', 'class' => 'btn btn-primary', 'data-question' => $questionId]
  6950. ),
  6951. '<span id="save_for_now_'.$questionId.'" class="exercise_save_mini_message"></span>&nbsp;',
  6952. ];
  6953. $exercise_actions = Display::div(
  6954. implode(PHP_EOL, $button),
  6955. ['class' => 'exercise_save_now_button']
  6956. );
  6957. }
  6958. if ($last_question_in_media && $this->type == ONE_PER_PAGE) {
  6959. $exercise_actions = $this->show_button($questionId, $current_question, $questions_in_media);
  6960. }
  6961. }
  6962. // Checkbox review answers
  6963. if ($this->review_answers &&
  6964. !in_array($question_obj->type, Question::question_type_no_review())
  6965. ) {
  6966. $remind_question_div = Display::tag(
  6967. 'label',
  6968. Display::input(
  6969. 'checkbox',
  6970. 'remind_list['.$questionId.']',
  6971. '',
  6972. $attributes
  6973. ).get_lang('ReviewQuestionLater'),
  6974. [
  6975. 'class' => 'checkbox',
  6976. 'for' => 'remind_list['.$questionId.']',
  6977. ]
  6978. );
  6979. $exercise_actions .= Display::div(
  6980. $remind_question_div,
  6981. ['class' => 'exercise_save_now_button']
  6982. );
  6983. }
  6984. echo Display::div(' ', ['class' => 'clear']);
  6985. $paginationCounter = null;
  6986. if ($this->type == ONE_PER_PAGE) {
  6987. if (empty($questions_in_media)) {
  6988. $paginationCounter = Display::paginationIndicator(
  6989. $current_question,
  6990. count($realQuestionList)
  6991. );
  6992. } else {
  6993. if ($last_question_in_media) {
  6994. $paginationCounter = Display::paginationIndicator(
  6995. $current_question,
  6996. count($realQuestionList)
  6997. );
  6998. }
  6999. }
  7000. }
  7001. echo '<div class="row"><div class="pull-right">'.$paginationCounter.'</div></div>';
  7002. echo Display::div($exercise_actions, ['class' => 'form-actions']);
  7003. echo '</div>';
  7004. }
  7005. }
  7006. /**
  7007. * Returns an array of categories details for the questions of the current
  7008. * exercise.
  7009. *
  7010. * @return array
  7011. */
  7012. public function getQuestionWithCategories()
  7013. {
  7014. $categoryTable = Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
  7015. $categoryRelTable = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  7016. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  7017. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  7018. $sql = "SELECT DISTINCT cat.*
  7019. FROM $TBL_EXERCICE_QUESTION e
  7020. INNER JOIN $TBL_QUESTIONS q
  7021. ON (e.question_id = q.id AND e.c_id = q.c_id)
  7022. INNER JOIN $categoryRelTable catRel
  7023. ON (catRel.question_id = e.question_id AND catRel.c_id = e.c_id)
  7024. INNER JOIN $categoryTable cat
  7025. ON (cat.id = catRel.category_id AND cat.c_id = e.c_id)
  7026. WHERE
  7027. e.c_id = {$this->course_id} AND
  7028. e.exercice_id = ".intval($this->id);
  7029. $result = Database::query($sql);
  7030. $categoriesInExercise = [];
  7031. if (Database::num_rows($result)) {
  7032. $categoriesInExercise = Database::store_result($result, 'ASSOC');
  7033. }
  7034. return $categoriesInExercise;
  7035. }
  7036. /**
  7037. * Calculate the max_score of the quiz, depending of question inside, and quiz advanced option.
  7038. */
  7039. public function get_max_score()
  7040. {
  7041. $out_max_score = 0;
  7042. // list of question's id !!! the array key start at 1 !!!
  7043. $questionList = $this->selectQuestionList(true);
  7044. // test is randomQuestions - see field random of test
  7045. if ($this->random > 0 && $this->randomByCat == 0) {
  7046. $numberRandomQuestions = $this->random;
  7047. $questionScoreList = [];
  7048. foreach ($questionList as $questionId) {
  7049. $tmpobj_question = Question::read($questionId);
  7050. if (is_object($tmpobj_question)) {
  7051. $questionScoreList[] = $tmpobj_question->weighting;
  7052. }
  7053. }
  7054. rsort($questionScoreList);
  7055. // add the first $numberRandomQuestions value of score array to get max_score
  7056. for ($i = 0; $i < min($numberRandomQuestions, count($questionScoreList)); $i++) {
  7057. $out_max_score += $questionScoreList[$i];
  7058. }
  7059. } elseif ($this->random > 0 && $this->randomByCat > 0) {
  7060. // test is random by category
  7061. // get the $numberRandomQuestions best score question of each category
  7062. $numberRandomQuestions = $this->random;
  7063. $tab_categories_scores = [];
  7064. foreach ($questionList as $questionId) {
  7065. $question_category_id = TestCategory::getCategoryForQuestion($questionId);
  7066. if (!is_array($tab_categories_scores[$question_category_id])) {
  7067. $tab_categories_scores[$question_category_id] = [];
  7068. }
  7069. $tmpobj_question = Question::read($questionId);
  7070. if (is_object($tmpobj_question)) {
  7071. $tab_categories_scores[$question_category_id][] = $tmpobj_question->weighting;
  7072. }
  7073. }
  7074. // here we've got an array with first key, the category_id, second key, score of question for this cat
  7075. foreach ($tab_categories_scores as $tab_scores) {
  7076. rsort($tab_scores);
  7077. for ($i = 0; $i < min($numberRandomQuestions, count($tab_scores)); $i++) {
  7078. $out_max_score += $tab_scores[$i];
  7079. }
  7080. }
  7081. } else {
  7082. // standard test, just add each question score
  7083. foreach ($questionList as $questionId) {
  7084. $question = Question::read($questionId, $this->course);
  7085. $out_max_score += $question->weighting;
  7086. }
  7087. }
  7088. return $out_max_score;
  7089. }
  7090. /**
  7091. * @return string
  7092. */
  7093. public function get_formated_title()
  7094. {
  7095. if (api_get_configuration_value('save_titles_as_html')) {
  7096. }
  7097. return api_html_entity_decode($this->selectTitle());
  7098. }
  7099. /**
  7100. * @param string $title
  7101. *
  7102. * @return string
  7103. */
  7104. public static function get_formated_title_variable($title)
  7105. {
  7106. return api_html_entity_decode($title);
  7107. }
  7108. /**
  7109. * @return string
  7110. */
  7111. public function format_title()
  7112. {
  7113. return api_htmlentities($this->title);
  7114. }
  7115. /**
  7116. * @param string $title
  7117. *
  7118. * @return string
  7119. */
  7120. public static function format_title_variable($title)
  7121. {
  7122. return api_htmlentities($title);
  7123. }
  7124. /**
  7125. * @param int $courseId
  7126. * @param int $sessionId
  7127. *
  7128. * @return array exercises
  7129. */
  7130. public function getExercisesByCourseSession($courseId, $sessionId)
  7131. {
  7132. $courseId = (int) $courseId;
  7133. $sessionId = (int) $sessionId;
  7134. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7135. $sql = "SELECT * FROM $tbl_quiz cq
  7136. WHERE
  7137. cq.c_id = %s AND
  7138. (cq.session_id = %s OR cq.session_id = 0) AND
  7139. cq.active = 0
  7140. ORDER BY cq.id";
  7141. $sql = sprintf($sql, $courseId, $sessionId);
  7142. $result = Database::query($sql);
  7143. $rows = [];
  7144. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7145. $rows[] = $row;
  7146. }
  7147. return $rows;
  7148. }
  7149. /**
  7150. * @param int $courseId
  7151. * @param int $sessionId
  7152. * @param array $quizId
  7153. *
  7154. * @return array exercises
  7155. */
  7156. public function getExerciseAndResult($courseId, $sessionId, $quizId = [])
  7157. {
  7158. if (empty($quizId)) {
  7159. return [];
  7160. }
  7161. $sessionId = (int) $sessionId;
  7162. $courseId = (int) $courseId;
  7163. $ids = is_array($quizId) ? $quizId : [$quizId];
  7164. $ids = array_map('intval', $ids);
  7165. $ids = implode(',', $ids);
  7166. $track_exercises = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7167. if ($sessionId != 0) {
  7168. $sql = "SELECT * FROM $track_exercises te
  7169. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  7170. WHERE
  7171. te.id = %s AND
  7172. te.session_id = %s AND
  7173. cq.id IN (%s)
  7174. ORDER BY cq.id";
  7175. $sql = sprintf($sql, $courseId, $sessionId, $ids);
  7176. } else {
  7177. $sql = "SELECT * FROM $track_exercises te
  7178. INNER JOIN c_quiz cq ON cq.id = te.exe_exo_id AND te.c_id = cq.c_id
  7179. WHERE
  7180. te.id = %s AND
  7181. cq.id IN (%s)
  7182. ORDER BY cq.id";
  7183. $sql = sprintf($sql, $courseId, $ids);
  7184. }
  7185. $result = Database::query($sql);
  7186. $rows = [];
  7187. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7188. $rows[] = $row;
  7189. }
  7190. return $rows;
  7191. }
  7192. /**
  7193. * @param $exeId
  7194. * @param $exercise_stat_info
  7195. * @param $remindList
  7196. * @param $currentQuestion
  7197. *
  7198. * @return int|null
  7199. */
  7200. public static function getNextQuestionId(
  7201. $exeId,
  7202. $exercise_stat_info,
  7203. $remindList,
  7204. $currentQuestion
  7205. ) {
  7206. $result = Event::get_exercise_results_by_attempt($exeId, 'incomplete');
  7207. if (isset($result[$exeId])) {
  7208. $result = $result[$exeId];
  7209. } else {
  7210. return null;
  7211. }
  7212. $data_tracking = $exercise_stat_info['data_tracking'];
  7213. $data_tracking = explode(',', $data_tracking);
  7214. // if this is the final question do nothing.
  7215. if ($currentQuestion == count($data_tracking)) {
  7216. return null;
  7217. }
  7218. $currentQuestion = $currentQuestion - 1;
  7219. if (!empty($result['question_list'])) {
  7220. $answeredQuestions = [];
  7221. foreach ($result['question_list'] as $question) {
  7222. if (!empty($question['answer'])) {
  7223. $answeredQuestions[] = $question['question_id'];
  7224. }
  7225. }
  7226. // Checking answered questions
  7227. $counterAnsweredQuestions = 0;
  7228. foreach ($data_tracking as $questionId) {
  7229. if (!in_array($questionId, $answeredQuestions)) {
  7230. if ($currentQuestion != $counterAnsweredQuestions) {
  7231. break;
  7232. }
  7233. }
  7234. $counterAnsweredQuestions++;
  7235. }
  7236. $counterRemindListQuestions = 0;
  7237. // Checking questions saved in the reminder list
  7238. if (!empty($remindList)) {
  7239. foreach ($data_tracking as $questionId) {
  7240. if (in_array($questionId, $remindList)) {
  7241. // Skip the current question
  7242. if ($currentQuestion != $counterRemindListQuestions) {
  7243. break;
  7244. }
  7245. }
  7246. $counterRemindListQuestions++;
  7247. }
  7248. if ($counterRemindListQuestions < $currentQuestion) {
  7249. return null;
  7250. }
  7251. if (!empty($counterRemindListQuestions)) {
  7252. if ($counterRemindListQuestions > $counterAnsweredQuestions) {
  7253. return $counterAnsweredQuestions;
  7254. } else {
  7255. return $counterRemindListQuestions;
  7256. }
  7257. }
  7258. }
  7259. return $counterAnsweredQuestions;
  7260. }
  7261. }
  7262. /**
  7263. * Gets the position of a questionId in the question list.
  7264. *
  7265. * @param $questionId
  7266. *
  7267. * @return int
  7268. */
  7269. public function getPositionInCompressedQuestionList($questionId)
  7270. {
  7271. $questionList = $this->getQuestionListWithMediasCompressed();
  7272. $mediaQuestions = $this->getMediaList();
  7273. $position = 1;
  7274. foreach ($questionList as $id) {
  7275. if (isset($mediaQuestions[$id]) && in_array($questionId, $mediaQuestions[$id])) {
  7276. $mediaQuestionList = $mediaQuestions[$id];
  7277. if (in_array($questionId, $mediaQuestionList)) {
  7278. return $position;
  7279. } else {
  7280. $position++;
  7281. }
  7282. } else {
  7283. if ($id == $questionId) {
  7284. return $position;
  7285. } else {
  7286. $position++;
  7287. }
  7288. }
  7289. }
  7290. return 1;
  7291. }
  7292. /**
  7293. * Get the correct answers in all attempts.
  7294. *
  7295. * @param int $learnPathId
  7296. * @param int $learnPathItemId
  7297. * @param bool $onlyCorrect
  7298. *
  7299. * @return array
  7300. */
  7301. public function getAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0, $onlyCorrect = true)
  7302. {
  7303. $attempts = Event::getExerciseResultsByUser(
  7304. api_get_user_id(),
  7305. $this->id,
  7306. api_get_course_int_id(),
  7307. api_get_session_id(),
  7308. $learnPathId,
  7309. $learnPathItemId,
  7310. 'DESC'
  7311. );
  7312. $list = [];
  7313. foreach ($attempts as $attempt) {
  7314. foreach ($attempt['question_list'] as $answers) {
  7315. foreach ($answers as $answer) {
  7316. $objAnswer = new Answer($answer['question_id']);
  7317. if ($onlyCorrect) {
  7318. switch ($objAnswer->getQuestionType()) {
  7319. case FILL_IN_BLANKS:
  7320. $isCorrect = FillBlanks::isCorrect($answer['answer']);
  7321. break;
  7322. case MATCHING:
  7323. case DRAGGABLE:
  7324. case MATCHING_DRAGGABLE:
  7325. $isCorrect = Matching::isCorrect(
  7326. $answer['position'],
  7327. $answer['answer'],
  7328. $answer['question_id']
  7329. );
  7330. break;
  7331. case ORAL_EXPRESSION:
  7332. $isCorrect = false;
  7333. break;
  7334. default:
  7335. $isCorrect = $objAnswer->isCorrectByAutoId($answer['answer']);
  7336. }
  7337. if ($isCorrect) {
  7338. $list[$answer['question_id']][] = $answer;
  7339. }
  7340. } else {
  7341. $list[$answer['question_id']][] = $answer;
  7342. }
  7343. }
  7344. }
  7345. if ($onlyCorrect === false) {
  7346. // Only take latest attempt
  7347. break;
  7348. }
  7349. }
  7350. return $list;
  7351. }
  7352. /**
  7353. * Get the correct answers in all attempts.
  7354. *
  7355. * @param int $learnPathId
  7356. * @param int $learnPathItemId
  7357. *
  7358. * @return array
  7359. */
  7360. public function getCorrectAnswersInAllAttempts($learnPathId = 0, $learnPathItemId = 0)
  7361. {
  7362. return $this->getAnswersInAllAttempts($learnPathId, $learnPathItemId);
  7363. }
  7364. /**
  7365. * @return bool
  7366. */
  7367. public function showPreviousButton()
  7368. {
  7369. $allow = api_get_configuration_value('allow_quiz_show_previous_button_setting');
  7370. if ($allow === false) {
  7371. return true;
  7372. }
  7373. return $this->showPreviousButton;
  7374. }
  7375. /**
  7376. * @return int
  7377. */
  7378. public function getExerciseCategoryId()
  7379. {
  7380. return (int) $this->exerciseCategoryId;
  7381. }
  7382. /**
  7383. * @param int $value
  7384. */
  7385. public function setExerciseCategoryId($value)
  7386. {
  7387. $this->exerciseCategoryId = (int) $value;
  7388. }
  7389. /**
  7390. * @param array $values
  7391. *
  7392. * @throws \Doctrine\DBAL\DBALException
  7393. */
  7394. public function setPageResultConfiguration($values)
  7395. {
  7396. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  7397. if ($pageConfig) {
  7398. $params = [
  7399. 'hide_expected_answer' => isset($values['hide_expected_answer']) ? $values['hide_expected_answer'] : '',
  7400. 'hide_question_score' => isset($values['hide_question_score']) ? $values['hide_question_score'] : '',
  7401. 'hide_total_score' => isset($values['hide_total_score']) ? $values['hide_total_score'] : '',
  7402. ];
  7403. $type = Type::getType('array');
  7404. $platform = Database::getManager()->getConnection()->getDatabasePlatform();
  7405. $this->pageResultConfiguration = $type->convertToDatabaseValue($params, $platform);
  7406. }
  7407. }
  7408. /**
  7409. * @param array $defaults
  7410. */
  7411. public function setPageResultConfigurationDefaults(&$defaults)
  7412. {
  7413. $configuration = $this->getPageResultConfiguration();
  7414. if (!empty($configuration) && !empty($defaults)) {
  7415. $defaults = array_merge($defaults, $configuration);
  7416. }
  7417. }
  7418. /**
  7419. * @return array
  7420. */
  7421. public function getPageResultConfiguration()
  7422. {
  7423. $pageConfig = api_get_configuration_value('allow_quiz_results_page_config');
  7424. if ($pageConfig) {
  7425. /*$params = [
  7426. 'hide_expected_answer' => isset($values['hide_expected_answer']) ? $values['hide_expected_answer'] : '',
  7427. 'hide_question_score' => isset($values['hide_question_score']) ? $values['hide_question_score'] : '',
  7428. 'hide_total_score' => isset($values['hide_total_score']) ? $values['hide_total_score'] : ''
  7429. ];*/
  7430. $type = Type::getType('array');
  7431. $platform = Database::getManager()->getConnection()->getDatabasePlatform();
  7432. $result = $type->convertToPHPValue($this->pageResultConfiguration, $platform);
  7433. return $result;
  7434. }
  7435. return [];
  7436. }
  7437. /**
  7438. * @param string $attribute
  7439. *
  7440. * @return mixed|null
  7441. */
  7442. public function getPageConfigurationAttribute($attribute)
  7443. {
  7444. $result = $this->getPageResultConfiguration();
  7445. if (!empty($result)) {
  7446. $value = isset($result[$attribute]) ? $result[$attribute] : null;
  7447. return $value;
  7448. }
  7449. return null;
  7450. }
  7451. /**
  7452. * @param bool $showPreviousButton
  7453. *
  7454. * @return Exercise
  7455. */
  7456. public function setShowPreviousButton($showPreviousButton)
  7457. {
  7458. $this->showPreviousButton = $showPreviousButton;
  7459. return $this;
  7460. }
  7461. /**
  7462. * @param array $notifications
  7463. */
  7464. public function setNotifications($notifications)
  7465. {
  7466. $this->notifications = $notifications;
  7467. }
  7468. /**
  7469. * @return array
  7470. */
  7471. public function getNotifications()
  7472. {
  7473. return $this->notifications;
  7474. }
  7475. /**
  7476. * @return bool
  7477. */
  7478. public function showExpectedChoice()
  7479. {
  7480. return api_get_configuration_value('show_exercise_expected_choice');
  7481. }
  7482. /**
  7483. * @return bool
  7484. */
  7485. public function showExpectedChoiceColumn()
  7486. {
  7487. if (!in_array($this->results_disabled, [
  7488. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  7489. ])
  7490. ) {
  7491. $hide = (int) $this->getPageConfigurationAttribute('hide_expected_answer');
  7492. if ($hide === 1) {
  7493. return false;
  7494. }
  7495. return true;
  7496. }
  7497. return false;
  7498. }
  7499. /**
  7500. * @param string $class
  7501. * @param string $scoreLabel
  7502. * @param string $result
  7503. * @param array
  7504. *
  7505. * @return string
  7506. */
  7507. public function getQuestionRibbon($class, $scoreLabel, $result, $array)
  7508. {
  7509. $hide = (int) $this->getPageConfigurationAttribute('hide_question_score');
  7510. if ($hide === 1) {
  7511. return '';
  7512. }
  7513. if ($this->showExpectedChoice()) {
  7514. $html = null;
  7515. $hideLabel = api_get_configuration_value('exercise_hide_label');
  7516. $label = '<div class="rib rib-'.$class.'">
  7517. <h3>'.$scoreLabel.'</h3>
  7518. </div>';
  7519. if (!empty($result)) {
  7520. $label .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
  7521. }
  7522. if ($hideLabel === true) {
  7523. $answerUsed = (int) $array['used'];
  7524. $answerMissing = (int) $array['missing'] - $answerUsed;
  7525. for ($i = 1; $i <= $answerUsed; $i++) {
  7526. $html .= '<span class="score-img">'.
  7527. Display::return_icon('attempt-check.png', null, null, ICON_SIZE_SMALL).
  7528. '</span>';
  7529. }
  7530. for ($i = 1; $i <= $answerMissing; $i++) {
  7531. $html .= '<span class="score-img">'.
  7532. Display::return_icon('attempt-nocheck.png', null, null, ICON_SIZE_SMALL).
  7533. '</span>';
  7534. }
  7535. $label = '<div class="score-title">'.get_lang('CorrectAnswers').': '.$result.'</div>';
  7536. $label .= '<div class="score-limits">';
  7537. $label .= $html;
  7538. $label .= '</div>';
  7539. }
  7540. return '<div class="ribbon">
  7541. '.$label.'
  7542. </div>'
  7543. ;
  7544. } else {
  7545. $html = '<div class="ribbon">
  7546. <div class="rib rib-'.$class.'">
  7547. <h3>'.$scoreLabel.'</h3>
  7548. </div>';
  7549. if (!empty($result)) {
  7550. $html .= '<h4>'.get_lang('Score').': '.$result.'</h4>';
  7551. }
  7552. $html .= '</div>';
  7553. return $html;
  7554. }
  7555. }
  7556. /**
  7557. * @return int
  7558. */
  7559. public function getAutoLaunch()
  7560. {
  7561. return $this->autolaunch;
  7562. }
  7563. /**
  7564. * Clean auto launch settings for all exercise in course/course-session.
  7565. */
  7566. public function enableAutoLaunch()
  7567. {
  7568. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  7569. $sql = "UPDATE $table SET autolaunch = 1
  7570. WHERE iid = ".$this->iId;
  7571. Database::query($sql);
  7572. }
  7573. /**
  7574. * Clean auto launch settings for all exercise in course/course-session.
  7575. */
  7576. public function cleanCourseLaunchSettings()
  7577. {
  7578. $table = Database::get_course_table(TABLE_QUIZ_TEST);
  7579. $sql = "UPDATE $table SET autolaunch = 0
  7580. WHERE c_id = ".$this->course_id." AND session_id = ".$this->sessionId;
  7581. Database::query($sql);
  7582. }
  7583. /**
  7584. * Get the title without HTML tags.
  7585. *
  7586. * @return string
  7587. */
  7588. public function getUnformattedTitle()
  7589. {
  7590. return strip_tags(api_html_entity_decode($this->title));
  7591. }
  7592. /**
  7593. * @param int $start
  7594. * @param int $length
  7595. *
  7596. * @return array
  7597. */
  7598. public function getQuestionForTeacher($start = 0, $length = 10)
  7599. {
  7600. $start = (int) $start;
  7601. if ($start < 0) {
  7602. $start = 0;
  7603. }
  7604. $length = (int) $length;
  7605. $quizRelQuestion = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  7606. $question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  7607. $sql = "SELECT DISTINCT e.question_id
  7608. FROM $quizRelQuestion e
  7609. INNER JOIN $question q
  7610. ON (e.question_id = q.iid AND e.c_id = q.c_id)
  7611. WHERE
  7612. e.c_id = {$this->course_id} AND
  7613. e.exercice_id = '".$this->id."'
  7614. ORDER BY question_order
  7615. LIMIT $start, $length
  7616. ";
  7617. $result = Database::query($sql);
  7618. $questionList = [];
  7619. while ($object = Database::fetch_object($result)) {
  7620. $questionList[] = $object->question_id;
  7621. }
  7622. return $questionList;
  7623. }
  7624. /**
  7625. * @param int $exerciseId
  7626. * @param array $courseInfo
  7627. * @param int $sessionId
  7628. *
  7629. * @throws \Doctrine\ORM\OptimisticLockException
  7630. *
  7631. * @return bool
  7632. */
  7633. public function generateStats($exerciseId, $courseInfo, $sessionId)
  7634. {
  7635. $allowStats = api_get_configuration_value('allow_gradebook_stats');
  7636. if (!$allowStats) {
  7637. return false;
  7638. }
  7639. if (empty($courseInfo)) {
  7640. return false;
  7641. }
  7642. $courseId = $courseInfo['real_id'];
  7643. $sessionId = (int) $sessionId;
  7644. $exerciseId = (int) $exerciseId;
  7645. $result = $this->read($exerciseId);
  7646. if (empty($result)) {
  7647. api_not_allowed(true);
  7648. }
  7649. $statusToFilter = empty($sessionId) ? STUDENT : 0;
  7650. $studentList = CourseManager::get_user_list_from_course_code(
  7651. $courseInfo['code'],
  7652. $sessionId,
  7653. null,
  7654. null,
  7655. $statusToFilter
  7656. );
  7657. if (empty($studentList)) {
  7658. Display::addFlash(Display::return_message(get_lang('NoUsersInCourse')));
  7659. header('Location: '.api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq());
  7660. exit;
  7661. }
  7662. $tblStats = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7663. $studentIdList = [];
  7664. if (!empty($studentList)) {
  7665. $studentIdList = array_column($studentList, 'user_id');
  7666. }
  7667. if ($this->exercise_was_added_in_lp == false) {
  7668. $sql = "SELECT * FROM $tblStats
  7669. WHERE
  7670. exe_exo_id = $exerciseId AND
  7671. orig_lp_id = 0 AND
  7672. orig_lp_item_id = 0 AND
  7673. status <> 'incomplete' AND
  7674. session_id = $sessionId AND
  7675. c_id = $courseId
  7676. ";
  7677. } else {
  7678. $lpId = null;
  7679. if (!empty($this->lpList)) {
  7680. // Taking only the first LP
  7681. $lpId = current($this->lpList);
  7682. $lpId = $lpId['lp_id'];
  7683. }
  7684. $sql = "SELECT *
  7685. FROM $tblStats
  7686. WHERE
  7687. exe_exo_id = $exerciseId AND
  7688. orig_lp_id = $lpId AND
  7689. status <> 'incomplete' AND
  7690. session_id = $sessionId AND
  7691. c_id = $courseId ";
  7692. }
  7693. $sql .= ' ORDER BY exe_id DESC';
  7694. $studentCount = 0;
  7695. $sum = 0;
  7696. $bestResult = 0;
  7697. $weight = 0;
  7698. $sumResult = 0;
  7699. $result = Database::query($sql);
  7700. while ($data = Database::fetch_array($result, 'ASSOC')) {
  7701. // Only take into account users in the current student list.
  7702. if (!empty($studentIdList)) {
  7703. if (!in_array($data['exe_user_id'], $studentIdList)) {
  7704. continue;
  7705. }
  7706. }
  7707. if (!isset($students[$data['exe_user_id']])) {
  7708. if ($data['exe_weighting'] != 0) {
  7709. $students[$data['exe_user_id']] = $data['exe_result'];
  7710. $studentCount++;
  7711. if ($data['exe_result'] > $bestResult) {
  7712. $bestResult = $data['exe_result'];
  7713. }
  7714. $sum += $data['exe_result'] / $data['exe_weighting'];
  7715. $sumResult += $data['exe_result'];
  7716. $weight = $data['exe_weighting'];
  7717. }
  7718. }
  7719. }
  7720. $count = count($studentList);
  7721. $average = $sumResult / $count;
  7722. $em = Database::getManager();
  7723. $links = AbstractLink::getGradebookLinksFromItem(
  7724. $this->id,
  7725. LINK_EXERCISE,
  7726. $courseInfo['code'],
  7727. $sessionId
  7728. );
  7729. if (empty($links)) {
  7730. $links = AbstractLink::getGradebookLinksFromItem(
  7731. $this->iId,
  7732. LINK_EXERCISE,
  7733. $courseInfo['code'],
  7734. $sessionId
  7735. );
  7736. }
  7737. if (!empty($links)) {
  7738. $repo = $em->getRepository('ChamiloCoreBundle:GradebookLink');
  7739. foreach ($links as $link) {
  7740. $linkId = $link['id'];
  7741. /** @var GradebookLink $exerciseLink */
  7742. $exerciseLink = $repo->find($linkId);
  7743. if ($exerciseLink) {
  7744. $exerciseLink
  7745. ->setUserScoreList($students)
  7746. ->setBestScore($bestResult)
  7747. ->setAverageScore($average)
  7748. ->setScoreWeight($this->get_max_score());
  7749. $em->persist($exerciseLink);
  7750. $em->flush();
  7751. }
  7752. }
  7753. }
  7754. }
  7755. /**
  7756. * @param int $categoryId
  7757. * @param int $page
  7758. * @param int $from
  7759. * @param int $limit
  7760. * @param string $keyword
  7761. *
  7762. * @throws \Doctrine\ORM\Query\QueryException
  7763. *
  7764. * @return string
  7765. */
  7766. public static function exerciseGrid($categoryId, $page, $from, $limit, $keyword = '')
  7767. {
  7768. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7769. $TBL_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  7770. $TBL_EXERCISE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  7771. $TBL_EXERCISES = Database::get_course_table(TABLE_QUIZ_TEST);
  7772. $TBL_TRACK_EXERCISES = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
  7773. $page = (int) $page;
  7774. $from = (int) $from;
  7775. $limit = (int) $limit;
  7776. $autoLaunchAvailable = false;
  7777. if (api_get_course_setting('enable_exercise_auto_launch') == 1 &&
  7778. api_get_configuration_value('allow_exercise_auto_launch')
  7779. ) {
  7780. $autoLaunchAvailable = true;
  7781. }
  7782. $is_allowedToEdit = api_is_allowed_to_edit(null, true);
  7783. $courseInfo = api_get_course_info();
  7784. $sessionId = api_get_session_id();
  7785. $courseId = $courseInfo['real_id'];
  7786. $tableRows = [];
  7787. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7788. $exercisePath = api_get_self();
  7789. $origin = api_get_origin();
  7790. $userInfo = api_get_user_info();
  7791. $charset = 'utf-8';
  7792. $token = Security::get_token();
  7793. $userId = api_get_user_id();
  7794. $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
  7795. $userId,
  7796. $courseInfo
  7797. );
  7798. $documentPath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  7799. $limitTeacherAccess = api_get_configuration_value('limit_exercise_teacher_access');
  7800. $learnpath_id = isset($_REQUEST['learnpath_id']) ? (int) $_REQUEST['learnpath_id'] : null;
  7801. $learnpath_item_id = isset($_REQUEST['learnpath_item_id']) ? (int) $_REQUEST['learnpath_item_id'] : null;
  7802. // Condition for the session
  7803. $condition_session = api_get_session_condition($sessionId, true, true);
  7804. $content = '';
  7805. $categoryCondition = '';
  7806. $categoryId = (int) $categoryId;
  7807. if (api_get_configuration_value('allow_exercise_categories')) {
  7808. $categoryCondition = " AND exercise_category_id = $categoryId ";
  7809. }
  7810. $keywordCondition = '';
  7811. if (!empty($keyword)) {
  7812. $keyword = Database::escape_string($keyword);
  7813. $keywordCondition = " AND title LIKE '%$keyword%' ";
  7814. }
  7815. // Only for administrators
  7816. if ($is_allowedToEdit) {
  7817. $total_sql = "SELECT count(iid) as count
  7818. FROM $TBL_EXERCISES
  7819. WHERE
  7820. c_id = $courseId AND
  7821. active<>'-1'
  7822. $condition_session
  7823. $categoryCondition
  7824. $keywordCondition
  7825. ";
  7826. $sql = "SELECT * FROM $TBL_EXERCISES
  7827. WHERE
  7828. c_id = $courseId AND
  7829. active <> '-1'
  7830. $condition_session
  7831. $categoryCondition
  7832. $keywordCondition
  7833. ORDER BY title
  7834. LIMIT $from , $limit";
  7835. } else {
  7836. // Only for students
  7837. $total_sql = "SELECT count(iid) as count
  7838. FROM $TBL_EXERCISES
  7839. WHERE
  7840. c_id = $courseId AND
  7841. active = '1'
  7842. $condition_session
  7843. $categoryCondition
  7844. $keywordCondition
  7845. ";
  7846. $sql = "SELECT * FROM $TBL_EXERCISES
  7847. WHERE c_id = $courseId AND
  7848. active='1' $condition_session
  7849. $categoryCondition
  7850. $keywordCondition
  7851. ORDER BY title LIMIT $from , $limit";
  7852. }
  7853. $result = Database::query($sql);
  7854. $result_total = Database::query($total_sql);
  7855. $total_exercises = 0;
  7856. if (Database :: num_rows($result_total)) {
  7857. $result_total = Database::fetch_array($result_total);
  7858. $total_exercises = $result_total['count'];
  7859. }
  7860. //get HotPotatoes files (active and inactive)
  7861. if ($is_allowedToEdit) {
  7862. $sql = "SELECT * FROM $TBL_DOCUMENT
  7863. WHERE
  7864. c_id = $courseId AND
  7865. path LIKE '".Database::escape_string($uploadPath.'/%/%')."'";
  7866. $res = Database::query($sql);
  7867. $hp_count = Database :: num_rows($res);
  7868. } else {
  7869. $sql = "SELECT * FROM $TBL_DOCUMENT d
  7870. INNER JOIN $TBL_ITEM_PROPERTY ip
  7871. ON (d.id = ip.ref AND d.c_id = ip.c_id)
  7872. WHERE
  7873. ip.tool = '".TOOL_DOCUMENT."' AND
  7874. d.path LIKE '".Database::escape_string($uploadPath.'/%/%')."' AND
  7875. ip.visibility ='1' AND
  7876. d.c_id = $courseId AND
  7877. ip.c_id = $courseId";
  7878. $res = Database::query($sql);
  7879. $hp_count = Database::num_rows($res);
  7880. }
  7881. $total = $total_exercises + $hp_count;
  7882. $exerciseList = [];
  7883. $list_ordered = null;
  7884. while ($row = Database::fetch_array($result, 'ASSOC')) {
  7885. $exerciseList[$row['iid']] = $row;
  7886. }
  7887. if (!empty($exerciseList) &&
  7888. api_get_setting('exercise_invisible_in_session') === 'true'
  7889. ) {
  7890. if (!empty($sessionId)) {
  7891. $changeDefaultVisibility = true;
  7892. if (api_get_setting('configure_exercise_visibility_in_course') === 'true') {
  7893. $changeDefaultVisibility = false;
  7894. if (api_get_course_setting('exercise_invisible_in_session') == 1) {
  7895. $changeDefaultVisibility = true;
  7896. }
  7897. }
  7898. if ($changeDefaultVisibility) {
  7899. // Check exercise
  7900. foreach ($exerciseList as $exercise) {
  7901. if ($exercise['session_id'] == 0) {
  7902. $visibilityInfo = api_get_item_property_info(
  7903. $courseId,
  7904. TOOL_QUIZ,
  7905. $exercise['iid'],
  7906. $sessionId
  7907. );
  7908. if (empty($visibilityInfo)) {
  7909. // Create a record for this
  7910. api_item_property_update(
  7911. $courseInfo,
  7912. TOOL_QUIZ,
  7913. $exercise['iid'],
  7914. 'invisible',
  7915. api_get_user_id(),
  7916. 0,
  7917. null,
  7918. '',
  7919. '',
  7920. $sessionId
  7921. );
  7922. }
  7923. }
  7924. }
  7925. }
  7926. }
  7927. }
  7928. if (isset($list_ordered) && !empty($list_ordered)) {
  7929. $new_question_list = [];
  7930. foreach ($list_ordered as $exercise_id) {
  7931. if (isset($exerciseList[$exercise_id])) {
  7932. $new_question_list[] = $exerciseList[$exercise_id];
  7933. }
  7934. }
  7935. $exerciseList = $new_question_list;
  7936. }
  7937. if (!empty($exerciseList)) {
  7938. if ($origin !== 'learnpath') {
  7939. //avoid sending empty parameters
  7940. $mylpid = empty($learnpath_id) ? '' : '&learnpath_id='.$learnpath_id;
  7941. $mylpitemid = empty($learnpath_item_id) ? '' : '&learnpath_item_id='.$learnpath_item_id;
  7942. foreach ($exerciseList as $row) {
  7943. $currentRow = [];
  7944. $my_exercise_id = $row['id'];
  7945. $attempt_text = '';
  7946. $actions = '';
  7947. $exercise = new Exercise();
  7948. $exercise->read($my_exercise_id, false);
  7949. if (empty($exercise->id)) {
  7950. continue;
  7951. }
  7952. $locked = $exercise->is_gradebook_locked;
  7953. // Validation when belongs to a session
  7954. $session_img = api_get_session_image($row['session_id'], $userInfo['status']);
  7955. $time_limits = false;
  7956. if (!empty($row['start_time']) || !empty($row['end_time'])) {
  7957. $time_limits = true;
  7958. }
  7959. $is_actived_time = false;
  7960. if ($time_limits) {
  7961. // check if start time
  7962. $start_time = false;
  7963. if (!empty($row['start_time'])) {
  7964. $start_time = api_strtotime($row['start_time'], 'UTC');
  7965. }
  7966. $end_time = false;
  7967. if (!empty($row['end_time'])) {
  7968. $end_time = api_strtotime($row['end_time'], 'UTC');
  7969. }
  7970. $now = time();
  7971. //If both "clocks" are enable
  7972. if ($start_time && $end_time) {
  7973. if ($now > $start_time && $end_time > $now) {
  7974. $is_actived_time = true;
  7975. }
  7976. } else {
  7977. //we check the start and end
  7978. if ($start_time) {
  7979. if ($now > $start_time) {
  7980. $is_actived_time = true;
  7981. }
  7982. }
  7983. if ($end_time) {
  7984. if ($end_time > $now) {
  7985. $is_actived_time = true;
  7986. }
  7987. }
  7988. }
  7989. }
  7990. // Blocking empty start times see BT#2800
  7991. global $_custom;
  7992. if (isset($_custom['exercises_hidden_when_no_start_date']) &&
  7993. $_custom['exercises_hidden_when_no_start_date']
  7994. ) {
  7995. if (empty($row['start_time'])) {
  7996. $time_limits = true;
  7997. $is_actived_time = false;
  7998. }
  7999. }
  8000. $cut_title = $exercise->getCutTitle();
  8001. $alt_title = '';
  8002. if ($cut_title != $row['title']) {
  8003. $alt_title = ' title = "'.$exercise->getUnformattedTitle().'" ';
  8004. }
  8005. // Teacher only
  8006. if ($is_allowedToEdit) {
  8007. $lp_blocked = null;
  8008. if ($exercise->exercise_was_added_in_lp == true) {
  8009. $lp_blocked = Display::div(
  8010. get_lang('AddedToLPCannotBeAccessed'),
  8011. ['class' => 'lp_content_type_label']
  8012. );
  8013. }
  8014. $visibility = api_get_item_visibility(
  8015. $courseInfo,
  8016. TOOL_QUIZ,
  8017. $my_exercise_id,
  8018. 0
  8019. );
  8020. if (!empty($sessionId)) {
  8021. $setting = api_get_configuration_value('show_hidden_exercise_added_to_lp');
  8022. if ($setting) {
  8023. if ($exercise->exercise_was_added_in_lp == false) {
  8024. if ($visibility == 0) {
  8025. continue;
  8026. }
  8027. }
  8028. } else {
  8029. if ($visibility == 0) {
  8030. continue;
  8031. }
  8032. }
  8033. $visibility = api_get_item_visibility(
  8034. $courseInfo,
  8035. TOOL_QUIZ,
  8036. $my_exercise_id,
  8037. $sessionId
  8038. );
  8039. }
  8040. if ($row['active'] == 0 || $visibility == 0) {
  8041. $title = Display::tag('font', $cut_title, ['style' => 'color:grey']);
  8042. } else {
  8043. $title = $cut_title;
  8044. }
  8045. $count_exercise_not_validated = (int) Event::count_exercise_result_not_validated(
  8046. $my_exercise_id,
  8047. $courseId,
  8048. $sessionId
  8049. );
  8050. /*$move = Display::return_icon(
  8051. 'all_directions.png',
  8052. get_lang('Move'),
  8053. ['class' => 'moved', 'style' => 'margin-bottom:-0.5em;']
  8054. );*/
  8055. $move = null;
  8056. $class_tip = '';
  8057. if (!empty($count_exercise_not_validated)) {
  8058. $results_text = $count_exercise_not_validated == 1 ? get_lang('ResultNotRevised') : get_lang('ResultsNotRevised');
  8059. $title .= '<span class="exercise_tooltip" style="display: none;">'.$count_exercise_not_validated.' '.$results_text.' </span>';
  8060. $class_tip = 'link_tooltip';
  8061. }
  8062. $url = $move.'<a '.$alt_title.' class="'.$class_tip.'" id="tooltip_'.$row['id'].'" href="overview.php?'.api_get_cidreq().$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">
  8063. '.Display::return_icon('quiz.png', $row['title']).'
  8064. '.$title.' </a>'.PHP_EOL;
  8065. if (ExerciseLib::isQuizEmbeddable($row)) {
  8066. $embeddableIcon = Display::return_icon('om_integration.png', get_lang('ThisQuizCanBeEmbeddable'));
  8067. $url .= Display::div($embeddableIcon, ['class' => 'pull-right']);
  8068. }
  8069. $currentRow['title'] = $url.' '.$session_img.$lp_blocked;
  8070. // Count number exercise - teacher
  8071. $sql = "SELECT count(*) count FROM $TBL_EXERCISE_QUESTION
  8072. WHERE c_id = $courseId AND exercice_id = $my_exercise_id";
  8073. $sqlresult = Database::query($sql);
  8074. $rowi = (int) Database::result($sqlresult, 0, 0);
  8075. if ($sessionId == $row['session_id']) {
  8076. // Questions list
  8077. $actions = Display::url(
  8078. Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL),
  8079. 'admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']
  8080. );
  8081. // Test settings
  8082. $settings = Display::url(
  8083. Display::return_icon('settings.png', get_lang('Configure'), '', ICON_SIZE_SMALL),
  8084. 'exercise_admin.php?'.api_get_cidreq().'&exerciseId='.$row['id']
  8085. );
  8086. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8087. $settings = '';
  8088. }
  8089. $actions .= $settings;
  8090. // Exercise results
  8091. $resultsLink = '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8092. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8093. if ($limitTeacherAccess) {
  8094. if (api_is_platform_admin()) {
  8095. $actions .= $resultsLink;
  8096. }
  8097. } else {
  8098. // Exercise results
  8099. $actions .= $resultsLink;
  8100. }
  8101. // Auto launch
  8102. if ($autoLaunchAvailable) {
  8103. $autoLaunch = $exercise->getAutoLaunch();
  8104. if (empty($autoLaunch)) {
  8105. $actions .= Display::url(
  8106. Display::return_icon(
  8107. 'launch_na.png',
  8108. get_lang('Enable'),
  8109. '',
  8110. ICON_SIZE_SMALL
  8111. ),
  8112. 'exercise.php?'.api_get_cidreq().'&choice=enable_launch&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8113. );
  8114. } else {
  8115. $actions .= Display::url(
  8116. Display::return_icon(
  8117. 'launch.png',
  8118. get_lang('Disable'),
  8119. '',
  8120. ICON_SIZE_SMALL
  8121. ),
  8122. 'exercise.php?'.api_get_cidreq().'&choice=disable_launch&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8123. );
  8124. }
  8125. }
  8126. // Export
  8127. $actions .= Display::url(
  8128. Display::return_icon('cd.png', get_lang('CopyExercise')),
  8129. '',
  8130. [
  8131. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8132. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id'],
  8133. ]
  8134. );
  8135. // Clean exercise
  8136. if ($locked == false) {
  8137. $clean = Display::url(
  8138. Display::return_icon(
  8139. 'clean.png',
  8140. get_lang('CleanStudentResults'),
  8141. '',
  8142. ICON_SIZE_SMALL
  8143. ),
  8144. '',
  8145. [
  8146. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteResults'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8147. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=clean_results&sec_token='.$token.'&exerciseId='.$row['id'],
  8148. ]
  8149. );
  8150. } else {
  8151. $clean = Display::return_icon(
  8152. 'clean_na.png',
  8153. get_lang('ResourceLockedByGradebook'),
  8154. '',
  8155. ICON_SIZE_SMALL
  8156. );
  8157. }
  8158. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8159. $clean = '';
  8160. }
  8161. $actions .= $clean;
  8162. // Visible / invisible
  8163. // Check if this exercise was added in a LP
  8164. if ($exercise->exercise_was_added_in_lp == true) {
  8165. $visibility = Display::return_icon(
  8166. 'invisible.png',
  8167. get_lang('AddedToLPCannotBeAccessed'),
  8168. '',
  8169. ICON_SIZE_SMALL
  8170. );
  8171. } else {
  8172. if ($row['active'] == 0 || $visibility == 0) {
  8173. $visibility = Display::url(
  8174. Display::return_icon(
  8175. 'invisible.png',
  8176. get_lang('Activate'),
  8177. '',
  8178. ICON_SIZE_SMALL
  8179. ),
  8180. 'exercise.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8181. );
  8182. } else {
  8183. // else if not active
  8184. $visibility = Display::url(
  8185. Display::return_icon(
  8186. 'visible.png',
  8187. get_lang('Deactivate'),
  8188. '',
  8189. ICON_SIZE_SMALL
  8190. ),
  8191. 'exercise.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8192. );
  8193. }
  8194. }
  8195. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8196. $visibility = '';
  8197. }
  8198. $actions .= $visibility;
  8199. // Export qti ...
  8200. $export = Display::url(
  8201. Display::return_icon(
  8202. 'export_qti2.png',
  8203. 'IMS/QTI',
  8204. '',
  8205. ICON_SIZE_SMALL
  8206. ),
  8207. 'exercise.php?action=exportqti2&exerciseId='.$row['id'].'&'.api_get_cidreq()
  8208. );
  8209. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8210. $export = '';
  8211. }
  8212. $actions .= $export;
  8213. } else {
  8214. // not session
  8215. $actions = Display::return_icon(
  8216. 'edit_na.png',
  8217. get_lang('ExerciseEditionNotAvailableInSession')
  8218. );
  8219. // Check if this exercise was added in a LP
  8220. if ($exercise->exercise_was_added_in_lp == true) {
  8221. $visibility = Display::return_icon(
  8222. 'invisible.png',
  8223. get_lang('AddedToLPCannotBeAccessed'),
  8224. '',
  8225. ICON_SIZE_SMALL
  8226. );
  8227. } else {
  8228. if ($row['active'] == 0 || $visibility == 0) {
  8229. $visibility = Display::url(
  8230. Display::return_icon(
  8231. 'invisible.png',
  8232. get_lang('Activate'),
  8233. '',
  8234. ICON_SIZE_SMALL
  8235. ),
  8236. 'exercise.php?'.api_get_cidreq().'&choice=enable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8237. );
  8238. } else {
  8239. // else if not active
  8240. $visibility = Display::url(
  8241. Display::return_icon(
  8242. 'visible.png',
  8243. get_lang('Deactivate'),
  8244. '',
  8245. ICON_SIZE_SMALL
  8246. ),
  8247. 'exercise.php?'.api_get_cidreq().'&choice=disable&sec_token='.$token.'&page='.$page.'&exerciseId='.$row['id']
  8248. );
  8249. }
  8250. }
  8251. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8252. $visibility = '';
  8253. }
  8254. $actions .= $visibility;
  8255. $actions .= '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8256. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8257. $actions .= Display::url(
  8258. Display::return_icon('cd.gif', get_lang('CopyExercise')),
  8259. '',
  8260. [
  8261. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToCopy'), ENT_QUOTES, $charset))." ".addslashes($row['title'])."?"."')) return false;",
  8262. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=copy_exercise&sec_token='.$token.'&exerciseId='.$row['id'],
  8263. ]
  8264. );
  8265. }
  8266. // Delete
  8267. $delete = '';
  8268. if ($sessionId == $row['session_id']) {
  8269. if ($locked == false) {
  8270. $delete = Display::url(
  8271. Display::return_icon(
  8272. 'delete.png',
  8273. get_lang('Delete'),
  8274. '',
  8275. ICON_SIZE_SMALL
  8276. ),
  8277. '',
  8278. [
  8279. 'onclick' => "javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('AreYouSureToDeleteJS'), ENT_QUOTES, $charset))." ".addslashes($exercise->getUnformattedTitle())."?"."')) return false;",
  8280. 'href' => 'exercise.php?'.api_get_cidreq().'&choice=delete&sec_token='.$token.'&exerciseId='.$row['id'],
  8281. ]
  8282. );
  8283. } else {
  8284. $delete = Display::return_icon(
  8285. 'delete_na.png',
  8286. get_lang('ResourceLockedByGradebook'),
  8287. '',
  8288. ICON_SIZE_SMALL
  8289. );
  8290. }
  8291. }
  8292. if ($limitTeacherAccess && !api_is_platform_admin()) {
  8293. $delete = '';
  8294. }
  8295. $actions .= $delete;
  8296. // Number of questions
  8297. $random_label = null;
  8298. if ($row['random'] > 0 || $row['random'] == -1) {
  8299. // if random == -1 means use random questions with all questions
  8300. $random_number_of_question = $row['random'];
  8301. if ($random_number_of_question == -1) {
  8302. $random_number_of_question = $rowi;
  8303. }
  8304. if ($row['random_by_category'] > 0) {
  8305. $nbQuestionsTotal = TestCategory::getNumberOfQuestionRandomByCategory(
  8306. $my_exercise_id,
  8307. $random_number_of_question
  8308. );
  8309. $number_of_questions = $nbQuestionsTotal.' ';
  8310. $number_of_questions .= ($nbQuestionsTotal > 1) ? get_lang('QuestionsLowerCase') : get_lang('QuestionLowerCase');
  8311. $number_of_questions .= ' - ';
  8312. $number_of_questions .= min(
  8313. TestCategory::getNumberMaxQuestionByCat($my_exercise_id), $random_number_of_question
  8314. ).' '.get_lang('QuestionByCategory');
  8315. } else {
  8316. $random_label = ' ('.get_lang('Random').') ';
  8317. $number_of_questions = $random_number_of_question.' '.$random_label.' / '.$rowi;
  8318. // Bug if we set a random value bigger than the real number of questions
  8319. if ($random_number_of_question > $rowi) {
  8320. $number_of_questions = $rowi.' '.$random_label;
  8321. }
  8322. }
  8323. } else {
  8324. $number_of_questions = $rowi;
  8325. }
  8326. $currentRow['count_questions'] = $number_of_questions;
  8327. } else {
  8328. // Student only.
  8329. $visibility = api_get_item_visibility(
  8330. $courseInfo,
  8331. TOOL_QUIZ,
  8332. $my_exercise_id,
  8333. $sessionId
  8334. );
  8335. if ($visibility == 0) {
  8336. continue;
  8337. }
  8338. $url = '<a '.$alt_title.' href="overview.php?'.api_get_cidreq().$mylpid.$mylpitemid.'&exerciseId='.$row['id'].'">'.
  8339. $cut_title.'</a>';
  8340. // Link of the exercise.
  8341. $currentRow['title'] = $url.' '.$session_img;
  8342. // This query might be improved later on by ordering by the new "tms" field rather than by exe_id
  8343. // Don't remove this marker: note-query-exe-results
  8344. $sql = "SELECT * FROM $TBL_TRACK_EXERCISES
  8345. WHERE
  8346. exe_exo_id = ".$row['id']." AND
  8347. exe_user_id = $userId AND
  8348. c_id = ".api_get_course_int_id()." AND
  8349. status <> 'incomplete' AND
  8350. orig_lp_id = 0 AND
  8351. orig_lp_item_id = 0 AND
  8352. session_id = '".api_get_session_id()."'
  8353. ORDER BY exe_id DESC";
  8354. $qryres = Database::query($sql);
  8355. $num = Database :: num_rows($qryres);
  8356. // Hide the results.
  8357. $my_result_disabled = $row['results_disabled'];
  8358. $attempt_text = '-';
  8359. // Time limits are on
  8360. if ($time_limits) {
  8361. // Exam is ready to be taken
  8362. if ($is_actived_time) {
  8363. // Show results
  8364. if (
  8365. in_array(
  8366. $my_result_disabled,
  8367. [
  8368. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
  8369. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  8370. RESULT_DISABLE_SHOW_SCORE_ONLY,
  8371. RESULT_DISABLE_RANKING,
  8372. ]
  8373. )
  8374. ) {
  8375. // More than one attempt
  8376. if ($num > 0) {
  8377. $row_track = Database :: fetch_array($qryres);
  8378. $attempt_text = get_lang('LatestAttempt').' : ';
  8379. $attempt_text .= ExerciseLib::show_score(
  8380. $row_track['exe_result'],
  8381. $row_track['exe_weighting']
  8382. );
  8383. } else {
  8384. //No attempts
  8385. $attempt_text = get_lang('NotAttempted');
  8386. }
  8387. } else {
  8388. $attempt_text = '-';
  8389. }
  8390. } else {
  8391. // Quiz not ready due to time limits
  8392. //@todo use the is_visible function
  8393. if (!empty($row['start_time']) && !empty($row['end_time'])) {
  8394. $today = time();
  8395. $start_time = api_strtotime($row['start_time'], 'UTC');
  8396. $end_time = api_strtotime($row['end_time'], 'UTC');
  8397. if ($today < $start_time) {
  8398. $attempt_text = sprintf(
  8399. get_lang('ExerciseWillBeActivatedFromXToY'),
  8400. api_convert_and_format_date($row['start_time']),
  8401. api_convert_and_format_date($row['end_time'])
  8402. );
  8403. } else {
  8404. if ($today > $end_time) {
  8405. $attempt_text = sprintf(
  8406. get_lang('ExerciseWasActivatedFromXToY'),
  8407. api_convert_and_format_date($row['start_time']),
  8408. api_convert_and_format_date($row['end_time'])
  8409. );
  8410. }
  8411. }
  8412. } else {
  8413. //$attempt_text = get_lang('ExamNotAvailableAtThisTime');
  8414. if (!empty($row['start_time'])) {
  8415. $attempt_text = sprintf(
  8416. get_lang('ExerciseAvailableFromX'),
  8417. api_convert_and_format_date($row['start_time'])
  8418. );
  8419. }
  8420. if (!empty($row['end_time'])) {
  8421. $attempt_text = sprintf(
  8422. get_lang('ExerciseAvailableUntilX'),
  8423. api_convert_and_format_date($row['end_time'])
  8424. );
  8425. }
  8426. }
  8427. }
  8428. } else {
  8429. // Normal behaviour.
  8430. // Show results.
  8431. if (
  8432. in_array(
  8433. $my_result_disabled,
  8434. [
  8435. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS,
  8436. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  8437. RESULT_DISABLE_SHOW_SCORE_ONLY,
  8438. RESULT_DISABLE_RANKING,
  8439. ]
  8440. )
  8441. ) {
  8442. if ($num > 0) {
  8443. $row_track = Database :: fetch_array($qryres);
  8444. $attempt_text = get_lang('LatestAttempt').' : ';
  8445. $attempt_text .= ExerciseLib::show_score(
  8446. $row_track['exe_result'],
  8447. $row_track['exe_weighting']
  8448. );
  8449. } else {
  8450. $attempt_text = get_lang('NotAttempted');
  8451. }
  8452. }
  8453. }
  8454. }
  8455. $currentRow['attempt'] = $attempt_text;
  8456. if ($is_allowedToEdit) {
  8457. $additionalActions = ExerciseLib::getAdditionalTeacherActions($row['id']);
  8458. if (!empty($additionalActions)) {
  8459. $actions .= $additionalActions.PHP_EOL;
  8460. }
  8461. $currentRow = [
  8462. $row['iid'],
  8463. $currentRow['title'],
  8464. $currentRow['count_questions'],
  8465. $actions,
  8466. ];
  8467. } else {
  8468. $currentRow = [
  8469. $currentRow['title'],
  8470. $currentRow['attempt'],
  8471. ];
  8472. if ($isDrhOfCourse) {
  8473. $currentRow[] = '<a href="exercise_report.php?'.api_get_cidreq().'&exerciseId='.$row['id'].'">'.
  8474. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8475. }
  8476. }
  8477. $tableRows[] = $currentRow;
  8478. }
  8479. }
  8480. }
  8481. // end exercise list
  8482. // Hotpotatoes results
  8483. if ($is_allowedToEdit) {
  8484. $sql = "SELECT d.iid, d.path as path, d.comment as comment
  8485. FROM $TBL_DOCUMENT d
  8486. WHERE
  8487. d.c_id = $courseId AND
  8488. (d.path LIKE '%htm%') AND
  8489. d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'
  8490. LIMIT $from , $limit"; // only .htm or .html files listed
  8491. } else {
  8492. $sql = "SELECT d.iid, d.path as path, d.comment as comment
  8493. FROM $TBL_DOCUMENT d
  8494. WHERE
  8495. d.c_id = $courseId AND
  8496. (d.path LIKE '%htm%') AND
  8497. d.path LIKE '".Database :: escape_string($uploadPath.'/%/%')."'
  8498. LIMIT $from , $limit";
  8499. }
  8500. $result = Database::query($sql);
  8501. $attributes = [];
  8502. while ($row = Database :: fetch_array($result, 'ASSOC')) {
  8503. $attributes[$row['iid']] = $row;
  8504. }
  8505. $nbrActiveTests = 0;
  8506. if (!empty($attributes)) {
  8507. foreach ($attributes as $item) {
  8508. $id = $item['iid'];
  8509. $path = $item['path'];
  8510. $title = GetQuizName($path, $documentPath);
  8511. if ($title == '') {
  8512. $title = basename($path);
  8513. }
  8514. // prof only
  8515. if ($is_allowedToEdit) {
  8516. $visibility = api_get_item_visibility(
  8517. ['real_id' => $courseId],
  8518. TOOL_DOCUMENT,
  8519. $id,
  8520. 0
  8521. );
  8522. if (!empty($sessionId)) {
  8523. if (0 == $visibility) {
  8524. continue;
  8525. }
  8526. $visibility = api_get_item_visibility(
  8527. ['real_id' => $courseId],
  8528. TOOL_DOCUMENT,
  8529. $id,
  8530. $sessionId
  8531. );
  8532. }
  8533. $title =
  8534. implode(PHP_EOL, [
  8535. Display::return_icon('hotpotatoes_s.png', 'HotPotatoes'),
  8536. Display::url(
  8537. $title,
  8538. 'showinframes.php?'.api_get_cidreq().'&'.http_build_query([
  8539. 'file' => $path,
  8540. 'uid' => $userId,
  8541. ]),
  8542. ['class' => $visibility == 0 ? 'text-muted' : null]
  8543. ),
  8544. ]);
  8545. $actions = Display::url(
  8546. Display::return_icon(
  8547. 'edit.png',
  8548. get_lang('Edit'),
  8549. '',
  8550. ICON_SIZE_SMALL
  8551. ),
  8552. 'adminhp.php?'.api_get_cidreq().'&hotpotatoesName='.$path
  8553. );
  8554. $actions .= '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
  8555. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).
  8556. '</a>';
  8557. // if active
  8558. if ($visibility != 0) {
  8559. $nbrActiveTests = $nbrActiveTests + 1;
  8560. $actions .= ' <a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=disable&page='.$page.'&file='.$path.'">'.
  8561. Display::return_icon('visible.png', get_lang('Deactivate'), '', ICON_SIZE_SMALL).'</a>';
  8562. } else { // else if not active
  8563. $actions .= ' <a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=enable&page='.$page.'&file='.$path.'">'.
  8564. Display::return_icon('invisible.png', get_lang('Activate'), '', ICON_SIZE_SMALL).'</a>';
  8565. }
  8566. $actions .= '<a href="'.$exercisePath.'?'.api_get_cidreq().'&hpchoice=delete&file='.$path.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang('AreYouSureToDeleteJS'), ENT_QUOTES, $charset)).'\')) return false;">'.
  8567. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>';
  8568. $currentRow = [
  8569. '',
  8570. $title,
  8571. '',
  8572. $actions,
  8573. ];
  8574. } else {
  8575. $visibility = api_get_item_visibility(
  8576. ['real_id' => $courseId],
  8577. TOOL_DOCUMENT,
  8578. $id,
  8579. $sessionId
  8580. );
  8581. if (0 == $visibility) {
  8582. continue;
  8583. }
  8584. // Student only
  8585. $attempt = ExerciseLib::getLatestHotPotatoResult(
  8586. $path,
  8587. $userId,
  8588. api_get_course_int_id(),
  8589. api_get_session_id()
  8590. );
  8591. $nbrActiveTests = $nbrActiveTests + 1;
  8592. $title = Display::url(
  8593. $title,
  8594. 'showinframes.php?'.api_get_cidreq().'&'.http_build_query(
  8595. [
  8596. 'file' => $path,
  8597. 'cid' => api_get_course_id(),
  8598. 'uid' => $userId,
  8599. ]
  8600. )
  8601. );
  8602. $actions = '';
  8603. if (!empty($attempt)) {
  8604. $actions = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'&filter_by_user='.$userId.'">'.Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8605. $attemptText = get_lang('LatestAttempt').' : ';
  8606. $attemptText .= ExerciseLib::show_score(
  8607. $attempt['exe_result'],
  8608. $attempt['exe_weighting']
  8609. ).' ';
  8610. $attemptText .= $actions;
  8611. } else {
  8612. // No attempts.
  8613. $attemptText = get_lang('NotAttempted').' ';
  8614. }
  8615. $currentRow = [
  8616. $title,
  8617. $attemptText,
  8618. ];
  8619. if ($isDrhOfCourse) {
  8620. $currentRow[] = '<a href="hotpotatoes_exercise_report.php?'.api_get_cidreq().'&path='.$path.'">'.
  8621. Display::return_icon('test_results.png', get_lang('Results'), '', ICON_SIZE_SMALL).'</a>';
  8622. }
  8623. }
  8624. $tableRows[] = $currentRow;
  8625. }
  8626. }
  8627. if (empty($tableRows) && empty($categoryId)) {
  8628. if ($is_allowedToEdit && $origin != 'learnpath') {
  8629. $content .= '<div id="no-data-view">';
  8630. $content .= '<h3>'.get_lang('Quiz').'</h3>';
  8631. $content .= Display::return_icon('quiz.png', '', [], 64);
  8632. $content .= '<div class="controls">';
  8633. $content .= Display::url(
  8634. '<em class="fa fa-plus"></em> '.get_lang('NewEx'),
  8635. 'exercise_admin.php?'.api_get_cidreq(),
  8636. ['class' => 'btn btn-primary']
  8637. );
  8638. $content .= '</div>';
  8639. $content .= '</div>';
  8640. }
  8641. } else {
  8642. if (empty($tableRows)) {
  8643. return '';
  8644. }
  8645. $table = new SortableTableFromArrayConfig(
  8646. $tableRows,
  8647. 0,
  8648. 20,
  8649. 'exercises_cat'.$categoryId,
  8650. [],
  8651. []
  8652. );
  8653. $table->setTotalNumberOfItems($total);
  8654. $table->set_additional_parameters([
  8655. 'cidReq' => api_get_course_id(),
  8656. 'id_session' => api_get_session_id(),
  8657. 'category_id' => $categoryId,
  8658. ]);
  8659. if ($is_allowedToEdit) {
  8660. $formActions = [];
  8661. $formActions['visible'] = get_lang('Activate');
  8662. $formActions['invisible'] = get_lang('Deactivate');
  8663. $formActions['delete'] = get_lang('Delete');
  8664. $table->set_form_actions($formActions);
  8665. }
  8666. $i = 0;
  8667. if ($is_allowedToEdit) {
  8668. $table->set_header($i++, '', false, 'width="18px"');
  8669. }
  8670. $table->set_header($i++, get_lang('ExerciseName'), false);
  8671. if ($is_allowedToEdit) {
  8672. $table->set_header($i++, get_lang('QuantityQuestions'), false);
  8673. $table->set_header($i++, get_lang('Actions'), false);
  8674. } else {
  8675. $table->set_header($i++, get_lang('Status'), false);
  8676. if ($isDrhOfCourse) {
  8677. $table->set_header($i++, get_lang('Actions'), false);
  8678. }
  8679. }
  8680. $content .= $table->return_table();
  8681. }
  8682. return $content;
  8683. }
  8684. /**
  8685. * @return int value in minutes
  8686. */
  8687. public function getResultAccess()
  8688. {
  8689. $extraFieldValue = new ExtraFieldValue('exercise');
  8690. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  8691. $this->iId,
  8692. 'results_available_for_x_minutes'
  8693. );
  8694. if (!empty($value) && isset($value['value'])) {
  8695. return (int) $value['value'];
  8696. }
  8697. return 0;
  8698. }
  8699. /**
  8700. * @param array $exerciseResultInfo
  8701. *
  8702. * @return bool
  8703. */
  8704. public function getResultAccessTimeDiff($exerciseResultInfo)
  8705. {
  8706. $value = $this->getResultAccess();
  8707. if (!empty($value)) {
  8708. $endDate = new DateTime($exerciseResultInfo['exe_date'], new DateTimeZone('UTC'));
  8709. $endDate->add(new DateInterval('PT'.$value.'M'));
  8710. $now = time();
  8711. if ($endDate->getTimestamp() > $now) {
  8712. return (int) $endDate->getTimestamp() - $now;
  8713. }
  8714. }
  8715. return 0;
  8716. }
  8717. /**
  8718. * @param array $exerciseResultInfo
  8719. *
  8720. * @return bool
  8721. */
  8722. public function hasResultsAccess($exerciseResultInfo)
  8723. {
  8724. $diff = $this->getResultAccessTimeDiff($exerciseResultInfo);
  8725. if ($diff === 0) {
  8726. return false;
  8727. }
  8728. return true;
  8729. }
  8730. /**
  8731. * @return int
  8732. */
  8733. public function getResultsAccess()
  8734. {
  8735. $extraFieldValue = new ExtraFieldValue('exercise');
  8736. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  8737. $this->iId,
  8738. 'results_available_for_x_minutes'
  8739. );
  8740. if (!empty($value)) {
  8741. return (int) $value;
  8742. }
  8743. return 0;
  8744. }
  8745. /**
  8746. * Gets the question list ordered by the question_order setting (drag and drop).
  8747. *
  8748. * @return array
  8749. */
  8750. private function getQuestionOrderedList()
  8751. {
  8752. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  8753. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  8754. // Getting question_order to verify that the question
  8755. // list is correct and all question_order's were set
  8756. $sql = "SELECT DISTINCT count(e.question_order) as count
  8757. FROM $TBL_EXERCICE_QUESTION e
  8758. INNER JOIN $TBL_QUESTIONS q
  8759. ON (e.question_id = q.id AND e.c_id = q.c_id)
  8760. WHERE
  8761. e.c_id = {$this->course_id} AND
  8762. e.exercice_id = ".$this->id;
  8763. $result = Database::query($sql);
  8764. $row = Database::fetch_array($result);
  8765. $count_question_orders = $row['count'];
  8766. // Getting question list from the order (question list drag n drop interface).
  8767. $sql = "SELECT DISTINCT e.question_id, e.question_order
  8768. FROM $TBL_EXERCICE_QUESTION e
  8769. INNER JOIN $TBL_QUESTIONS q
  8770. ON (e.question_id = q.id AND e.c_id = q.c_id)
  8771. WHERE
  8772. e.c_id = {$this->course_id} AND
  8773. e.exercice_id = '".$this->id."'
  8774. ORDER BY question_order";
  8775. $result = Database::query($sql);
  8776. // Fills the array with the question ID for this exercise
  8777. // the key of the array is the question position
  8778. $temp_question_list = [];
  8779. $counter = 1;
  8780. $questionList = [];
  8781. while ($new_object = Database::fetch_object($result)) {
  8782. // Correct order.
  8783. $questionList[$new_object->question_order] = $new_object->question_id;
  8784. // Just in case we save the order in other array
  8785. $temp_question_list[$counter] = $new_object->question_id;
  8786. $counter++;
  8787. }
  8788. if (!empty($temp_question_list)) {
  8789. /* If both array don't match it means that question_order was not correctly set
  8790. for all questions using the default mysql order */
  8791. if (count($temp_question_list) != $count_question_orders) {
  8792. $questionList = $temp_question_list;
  8793. }
  8794. }
  8795. return $questionList;
  8796. }
  8797. /**
  8798. * Select N values from the questions per category array.
  8799. *
  8800. * @param array $categoriesAddedInExercise
  8801. * @param array $question_list
  8802. * @param array $questions_by_category per category
  8803. * @param bool $flatResult
  8804. * @param bool $randomizeQuestions
  8805. *
  8806. * @return array
  8807. */
  8808. private function pickQuestionsPerCategory(
  8809. $categoriesAddedInExercise,
  8810. $question_list,
  8811. &$questions_by_category,
  8812. $flatResult = true,
  8813. $randomizeQuestions = false
  8814. ) {
  8815. $addAll = true;
  8816. $categoryCountArray = [];
  8817. // Getting how many questions will be selected per category.
  8818. if (!empty($categoriesAddedInExercise)) {
  8819. $addAll = false;
  8820. // Parsing question according the category rel exercise settings
  8821. foreach ($categoriesAddedInExercise as $category_info) {
  8822. $category_id = $category_info['category_id'];
  8823. if (isset($questions_by_category[$category_id])) {
  8824. // How many question will be picked from this category.
  8825. $count = $category_info['count_questions'];
  8826. // -1 means all questions
  8827. $categoryCountArray[$category_id] = $count;
  8828. if ($count == -1) {
  8829. $categoryCountArray[$category_id] = 999;
  8830. }
  8831. }
  8832. }
  8833. }
  8834. if (!empty($questions_by_category)) {
  8835. $temp_question_list = [];
  8836. foreach ($questions_by_category as $category_id => &$categoryQuestionList) {
  8837. if (isset($categoryCountArray) && !empty($categoryCountArray)) {
  8838. $numberOfQuestions = 0;
  8839. if (isset($categoryCountArray[$category_id])) {
  8840. $numberOfQuestions = $categoryCountArray[$category_id];
  8841. }
  8842. }
  8843. if ($addAll) {
  8844. $numberOfQuestions = 999;
  8845. }
  8846. if (!empty($numberOfQuestions)) {
  8847. $elements = TestCategory::getNElementsFromArray(
  8848. $categoryQuestionList,
  8849. $numberOfQuestions,
  8850. $randomizeQuestions
  8851. );
  8852. if (!empty($elements)) {
  8853. $temp_question_list[$category_id] = $elements;
  8854. $categoryQuestionList = $elements;
  8855. }
  8856. }
  8857. }
  8858. if (!empty($temp_question_list)) {
  8859. if ($flatResult) {
  8860. $temp_question_list = array_flatten($temp_question_list);
  8861. }
  8862. $question_list = $temp_question_list;
  8863. }
  8864. }
  8865. return $question_list;
  8866. }
  8867. /**
  8868. * Changes the exercise id.
  8869. *
  8870. * @param int $id - exercise id
  8871. */
  8872. private function updateId($id)
  8873. {
  8874. $this->id = $id;
  8875. }
  8876. /**
  8877. * Sends a notification when a user ends an examn.
  8878. *
  8879. * @param array $question_list_answers
  8880. * @param string $origin
  8881. * @param array $user_info
  8882. * @param string $url_email
  8883. * @param array $teachers
  8884. */
  8885. private function sendNotificationForOpenQuestions(
  8886. $question_list_answers,
  8887. $origin,
  8888. $user_info,
  8889. $url_email,
  8890. $teachers
  8891. ) {
  8892. // Email configuration settings
  8893. $courseCode = api_get_course_id();
  8894. $courseInfo = api_get_course_info($courseCode);
  8895. $sessionId = api_get_session_id();
  8896. $sessionData = '';
  8897. if (!empty($sessionId)) {
  8898. $sessionInfo = api_get_session_info($sessionId);
  8899. if (!empty($sessionInfo)) {
  8900. $sessionData = '<tr>'
  8901. .'<td><em>'.get_lang('SessionName').'</em></td>'
  8902. .'<td>&nbsp;<b>'.$sessionInfo['name'].'</b></td>'
  8903. .'</tr>';
  8904. }
  8905. }
  8906. $msg = get_lang('OpenQuestionsAttempted').'<br /><br />'
  8907. .get_lang('AttemptDetails').' : <br /><br />'
  8908. .'<table>'
  8909. .'<tr>'
  8910. .'<td><em>'.get_lang('CourseName').'</em></td>'
  8911. .'<td>&nbsp;<b>#course#</b></td>'
  8912. .'</tr>'
  8913. .$sessionData
  8914. .'<tr>'
  8915. .'<td>'.get_lang('TestAttempted').'</td>'
  8916. .'<td>&nbsp;#exercise#</td>'
  8917. .'</tr>'
  8918. .'<tr>'
  8919. .'<td>'.get_lang('StudentName').'</td>'
  8920. .'<td>&nbsp;#firstName# #lastName#</td>'
  8921. .'</tr>'
  8922. .'<tr>'
  8923. .'<td>'.get_lang('StudentEmail').'</td>'
  8924. .'<td>&nbsp;#mail#</td>'
  8925. .'</tr>'
  8926. .'</table>';
  8927. $open_question_list = null;
  8928. foreach ($question_list_answers as $item) {
  8929. $question = $item['question'];
  8930. $answer = $item['answer'];
  8931. $answer_type = $item['answer_type'];
  8932. if (!empty($question) && !empty($answer) && $answer_type == FREE_ANSWER) {
  8933. $open_question_list .=
  8934. '<tr>'
  8935. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>'
  8936. .'<td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>'
  8937. .'</tr>'
  8938. .'<tr>'
  8939. .'<td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>'
  8940. .'<td valign="top" bgcolor="#F3F3F3">'.$answer.'</td>'
  8941. .'</tr>';
  8942. }
  8943. }
  8944. if (!empty($open_question_list)) {
  8945. $msg .= '<p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>'.
  8946. '<table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  8947. $msg .= $open_question_list;
  8948. $msg .= '</table><br />';
  8949. $msg = str_replace('#exercise#', $this->exercise, $msg);
  8950. $msg = str_replace('#firstName#', $user_info['firstname'], $msg);
  8951. $msg = str_replace('#lastName#', $user_info['lastname'], $msg);
  8952. $msg = str_replace('#mail#', $user_info['email'], $msg);
  8953. $msg = str_replace(
  8954. '#course#',
  8955. Display::url($courseInfo['title'], $courseInfo['course_public_url'].'?id_session='.$sessionId),
  8956. $msg
  8957. );
  8958. if ($origin != 'learnpath') {
  8959. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  8960. }
  8961. $msg = str_replace('#url#', $url_email, $msg);
  8962. $subject = get_lang('OpenQuestionsAttempted');
  8963. if (!empty($teachers)) {
  8964. foreach ($teachers as $user_id => $teacher_data) {
  8965. MessageManager::send_message_simple(
  8966. $user_id,
  8967. $subject,
  8968. $msg
  8969. );
  8970. }
  8971. }
  8972. }
  8973. }
  8974. /**
  8975. * Send notification for oral questions.
  8976. *
  8977. * @param array $question_list_answers
  8978. * @param string $origin
  8979. * @param int $exe_id
  8980. * @param array $user_info
  8981. * @param string $url_email
  8982. * @param array $teachers
  8983. */
  8984. private function sendNotificationForOralQuestions(
  8985. $question_list_answers,
  8986. $origin,
  8987. $exe_id,
  8988. $user_info,
  8989. $url_email,
  8990. $teachers
  8991. ) {
  8992. // Email configuration settings
  8993. $courseCode = api_get_course_id();
  8994. $courseInfo = api_get_course_info($courseCode);
  8995. $oral_question_list = null;
  8996. foreach ($question_list_answers as $item) {
  8997. $question = $item['question'];
  8998. $file = $item['generated_oral_file'];
  8999. $answer = $item['answer'];
  9000. if ($answer == 0) {
  9001. $answer = '';
  9002. }
  9003. $answer_type = $item['answer_type'];
  9004. if (!empty($question) && (!empty($answer) || !empty($file)) && $answer_type == ORAL_EXPRESSION) {
  9005. if (!empty($file)) {
  9006. $file = Display::url($file, $file);
  9007. }
  9008. $oral_question_list .= '<br />
  9009. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">
  9010. <tr>
  9011. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Question').'</td>
  9012. <td width="473" valign="top" bgcolor="#F3F3F3">'.$question.'</td>
  9013. </tr>
  9014. <tr>
  9015. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;'.get_lang('Answer').'</td>
  9016. <td valign="top" bgcolor="#F3F3F3">'.$answer.$file.'</td>
  9017. </tr></table>';
  9018. }
  9019. }
  9020. if (!empty($oral_question_list)) {
  9021. $msg = get_lang('OralQuestionsAttempted').'<br /><br />
  9022. '.get_lang('AttemptDetails').' : <br /><br />
  9023. <table>
  9024. <tr>
  9025. <td><em>'.get_lang('CourseName').'</em></td>
  9026. <td>&nbsp;<b>#course#</b></td>
  9027. </tr>
  9028. <tr>
  9029. <td>'.get_lang('TestAttempted').'</td>
  9030. <td>&nbsp;#exercise#</td>
  9031. </tr>
  9032. <tr>
  9033. <td>'.get_lang('StudentName').'</td>
  9034. <td>&nbsp;#firstName# #lastName#</td>
  9035. </tr>
  9036. <tr>
  9037. <td>'.get_lang('StudentEmail').'</td>
  9038. <td>&nbsp;#mail#</td>
  9039. </tr>
  9040. </table>';
  9041. $msg .= '<br />'.sprintf(get_lang('OralQuestionsAttemptedAreX'), $oral_question_list).'<br />';
  9042. $msg1 = str_replace("#exercise#", $this->exercise, $msg);
  9043. $msg = str_replace("#firstName#", $user_info['firstname'], $msg1);
  9044. $msg1 = str_replace("#lastName#", $user_info['lastname'], $msg);
  9045. $msg = str_replace("#mail#", $user_info['email'], $msg1);
  9046. $msg = str_replace("#course#", $courseInfo['name'], $msg1);
  9047. if (!in_array($origin, ['learnpath', 'embeddable'])) {
  9048. $msg .= '<br /><a href="#url#">'.get_lang('ClickToCommentAndGiveFeedback').'</a>';
  9049. }
  9050. $msg1 = str_replace("#url#", $url_email, $msg);
  9051. $mail_content = $msg1;
  9052. $subject = get_lang('OralQuestionsAttempted');
  9053. if (!empty($teachers)) {
  9054. foreach ($teachers as $user_id => $teacher_data) {
  9055. MessageManager::send_message_simple(
  9056. $user_id,
  9057. $subject,
  9058. $mail_content
  9059. );
  9060. }
  9061. }
  9062. }
  9063. }
  9064. /**
  9065. * Returns an array with the media list.
  9066. *
  9067. * @param array question list
  9068. *
  9069. * @example there's 1 question with iid 5 that belongs to the media question with iid = 100
  9070. * <code>
  9071. * array (size=2)
  9072. * 999 =>
  9073. * array (size=3)
  9074. * 0 => int 7
  9075. * 1 => int 6
  9076. * 2 => int 3254
  9077. * 100 =>
  9078. * array (size=1)
  9079. * 0 => int 5
  9080. * </code>
  9081. */
  9082. private function setMediaList($questionList)
  9083. {
  9084. $mediaList = [];
  9085. /*
  9086. * Media feature is not activated in 1.11.x
  9087. if (!empty($questionList)) {
  9088. foreach ($questionList as $questionId) {
  9089. $objQuestionTmp = Question::read($questionId, $this->course_id);
  9090. // If a media question exists
  9091. if (isset($objQuestionTmp->parent_id) && $objQuestionTmp->parent_id != 0) {
  9092. $mediaList[$objQuestionTmp->parent_id][] = $objQuestionTmp->id;
  9093. } else {
  9094. // Always the last item
  9095. $mediaList[999][] = $objQuestionTmp->id;
  9096. }
  9097. }
  9098. }*/
  9099. $this->mediaList = $mediaList;
  9100. }
  9101. /**
  9102. * @param FormValidator $form
  9103. *
  9104. * @return HTML_QuickForm_group
  9105. */
  9106. private function setResultDisabledGroup(FormValidator $form)
  9107. {
  9108. $resultDisabledGroup = [];
  9109. $resultDisabledGroup[] = $form->createElement(
  9110. 'radio',
  9111. 'results_disabled',
  9112. null,
  9113. get_lang('ShowScoreAndRightAnswer'),
  9114. '0',
  9115. ['id' => 'result_disabled_0']
  9116. );
  9117. $resultDisabledGroup[] = $form->createElement(
  9118. 'radio',
  9119. 'results_disabled',
  9120. null,
  9121. get_lang('DoNotShowScoreNorRightAnswer'),
  9122. '1',
  9123. ['id' => 'result_disabled_1', 'onclick' => 'check_results_disabled()']
  9124. );
  9125. $resultDisabledGroup[] = $form->createElement(
  9126. 'radio',
  9127. 'results_disabled',
  9128. null,
  9129. get_lang('OnlyShowScore'),
  9130. '2',
  9131. ['id' => 'result_disabled_2', 'onclick' => 'check_results_disabled()']
  9132. );
  9133. if (in_array($this->getFeedbackType(), [EXERCISE_FEEDBACK_TYPE_DIRECT, EXERCISE_FEEDBACK_TYPE_POPUP])) {
  9134. $group = $form->addGroup(
  9135. $resultDisabledGroup,
  9136. null,
  9137. get_lang('ShowResultsToStudents')
  9138. );
  9139. return $group;
  9140. }
  9141. $resultDisabledGroup[] = $form->createElement(
  9142. 'radio',
  9143. 'results_disabled',
  9144. null,
  9145. get_lang('ShowScoreEveryAttemptShowAnswersLastAttempt'),
  9146. '4',
  9147. ['id' => 'result_disabled_4']
  9148. );
  9149. $resultDisabledGroup[] = $form->createElement(
  9150. 'radio',
  9151. 'results_disabled',
  9152. null,
  9153. get_lang('DontShowScoreOnlyWhenUserFinishesAllAttemptsButShowFeedbackEachAttempt'),
  9154. '5',
  9155. ['id' => 'result_disabled_5', 'onclick' => 'check_results_disabled()']
  9156. );
  9157. $resultDisabledGroup[] = $form->createElement(
  9158. 'radio',
  9159. 'results_disabled',
  9160. null,
  9161. get_lang('ExerciseRankingMode'),
  9162. RESULT_DISABLE_RANKING,
  9163. ['id' => 'result_disabled_6']
  9164. );
  9165. $resultDisabledGroup[] = $form->createElement(
  9166. 'radio',
  9167. 'results_disabled',
  9168. null,
  9169. get_lang('ExerciseShowOnlyGlobalScoreAndCorrectAnswers'),
  9170. RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER,
  9171. ['id' => 'result_disabled_7']
  9172. );
  9173. $resultDisabledGroup[] = $form->createElement(
  9174. 'radio',
  9175. 'results_disabled',
  9176. null,
  9177. get_lang('ExerciseAutoEvaluationAndRankingMode'),
  9178. RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS_AND_RANKING,
  9179. ['id' => 'result_disabled_8']
  9180. );
  9181. $group = $form->addGroup(
  9182. $resultDisabledGroup,
  9183. null,
  9184. get_lang('ShowResultsToStudents')
  9185. );
  9186. return $group;
  9187. }
  9188. }