exercise.class.php 338 KB

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