exercise.class.php 339 KB

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