learnpath.class.php 494 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. use Chamilo\CourseBundle\Entity\CItemProperty;
  8. use Chamilo\CourseBundle\Entity\CLp;
  9. use Chamilo\CourseBundle\Entity\CLpCategory;
  10. use Chamilo\CourseBundle\Entity\CLpItem;
  11. use Chamilo\CourseBundle\Entity\CLpItemView;
  12. use Chamilo\CourseBundle\Entity\CTool;
  13. use Chamilo\UserBundle\Entity\User;
  14. use ChamiloSession as Session;
  15. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  16. use Symfony\Component\Filesystem\Filesystem;
  17. use Symfony\Component\Finder\Finder;
  18. /**
  19. * Class learnpath
  20. * This class defines the parent attributes and methods for Chamilo learnpaths
  21. * and SCORM learnpaths. It is used by the scorm class.
  22. *
  23. * @todo decouple class
  24. *
  25. * @package chamilo.learnpath
  26. *
  27. * @author Yannick Warnier <ywarnier@beeznest.org>
  28. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  29. */
  30. class learnpath
  31. {
  32. public $attempt = 0; // The number for the current ID view.
  33. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  34. public $current; // Id of the current item the user is viewing.
  35. public $current_score; // The score of the current item.
  36. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  37. public $current_time_stop; // The time the user closed this resource.
  38. public $default_status = 'not attempted';
  39. public $encoding = 'UTF-8';
  40. public $error = '';
  41. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  42. public $index; // The index of the active learnpath_item in $ordered_items array.
  43. public $items = [];
  44. public $last; // item_id of last item viewed in the learning path.
  45. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  46. public $license; // Which license this course has been given - not used yet on 20060522.
  47. public $lp_id; // DB iid for this learnpath.
  48. public $lp_view_id; // DB ID for lp_view
  49. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  50. public $message = '';
  51. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  52. public $name; // Learnpath name (they generally have one).
  53. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  54. public $path = ''; // Path inside the scorm directory (if scorm).
  55. public $theme; // The current theme of the learning path.
  56. public $preview_image; // The current image of the learning path.
  57. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  58. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  59. public $prevent_reinit = 1;
  60. // Describes the mode of progress bar display.
  61. public $seriousgame_mode = 0;
  62. public $progress_bar_mode = '%';
  63. // Percentage progress as saved in the db.
  64. public $progress_db = 0;
  65. public $proximity; // Wether the content is distant or local or unknown.
  66. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  67. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  68. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  69. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  70. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  71. public $user_id; //ID of the user that is viewing/using the course
  72. public $update_queue = [];
  73. public $scorm_debug = 0;
  74. public $arrMenu = []; // Array for the menu items.
  75. public $debug = 0; // Logging level.
  76. public $lp_session_id = 0;
  77. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  78. public $prerequisite = 0;
  79. public $use_max_score = 1; // 1 or 0
  80. public $subscribeUsers = 0; // Subscribe users or not
  81. public $created_on = '';
  82. public $modified_on = '';
  83. public $publicated_on = '';
  84. public $expired_on = '';
  85. public $ref = null;
  86. public $course_int_id;
  87. public $course_info = [];
  88. public $categoryId;
  89. /**
  90. * Constructor.
  91. * Needs a database handler, a course code and a learnpath id from the database.
  92. * Also builds the list of items into $this->items.
  93. *
  94. * @param string $course Course code
  95. * @param int $lp_id
  96. * @param int $user_id
  97. */
  98. public function __construct($course, $lp_id, $user_id)
  99. {
  100. $debug = $this->debug;
  101. $this->encoding = api_get_system_encoding();
  102. if ($debug) {
  103. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  104. }
  105. if (empty($course)) {
  106. $course = api_get_course_id();
  107. }
  108. $course_info = api_get_course_info($course);
  109. if (!empty($course_info)) {
  110. $this->cc = $course_info['code'];
  111. $this->course_info = $course_info;
  112. $course_id = $course_info['real_id'];
  113. } else {
  114. $this->error = 'Course code does not exist in database.';
  115. }
  116. $lp_id = (int) $lp_id;
  117. $course_id = (int) $course_id;
  118. $this->set_course_int_id($course_id);
  119. // Check learnpath ID.
  120. if (empty($lp_id) || empty($course_id)) {
  121. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  122. } else {
  123. // TODO: Make it flexible to use any course_code (still using env course code here).
  124. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  125. $sql = "SELECT * FROM $lp_table
  126. WHERE iid = $lp_id";
  127. if ($debug) {
  128. error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  129. }
  130. $res = Database::query($sql);
  131. if (Database::num_rows($res) > 0) {
  132. $this->lp_id = $lp_id;
  133. $row = Database::fetch_array($res);
  134. $this->type = $row['lp_type'];
  135. $this->name = stripslashes($row['name']);
  136. $this->proximity = $row['content_local'];
  137. $this->theme = $row['theme'];
  138. $this->maker = $row['content_maker'];
  139. $this->prevent_reinit = $row['prevent_reinit'];
  140. $this->seriousgame_mode = $row['seriousgame_mode'];
  141. $this->license = $row['content_license'];
  142. $this->scorm_debug = $row['debug'];
  143. $this->js_lib = $row['js_lib'];
  144. $this->path = $row['path'];
  145. $this->preview_image = $row['preview_image'];
  146. $this->author = $row['author'];
  147. $this->hide_toc_frame = $row['hide_toc_frame'];
  148. $this->lp_session_id = $row['session_id'];
  149. $this->use_max_score = $row['use_max_score'];
  150. $this->subscribeUsers = $row['subscribe_users'];
  151. $this->created_on = $row['created_on'];
  152. $this->modified_on = $row['modified_on'];
  153. $this->ref = $row['ref'];
  154. $this->categoryId = $row['category_id'];
  155. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  156. if (!empty($row['publicated_on'])) {
  157. $this->publicated_on = $row['publicated_on'];
  158. }
  159. if (!empty($row['expired_on'])) {
  160. $this->expired_on = $row['expired_on'];
  161. }
  162. if ($this->type == 2) {
  163. if ($row['force_commit'] == 1) {
  164. $this->force_commit = true;
  165. }
  166. }
  167. $this->mode = $row['default_view_mod'];
  168. // Check user ID.
  169. if (empty($user_id)) {
  170. $this->error = 'User ID is empty';
  171. } else {
  172. $userInfo = api_get_user_info($user_id);
  173. if (!empty($userInfo)) {
  174. $this->user_id = $userInfo['user_id'];
  175. } else {
  176. $this->error = 'User ID does not exist in database #'.$user_id;
  177. }
  178. }
  179. // End of variables checking.
  180. $session_id = api_get_session_id();
  181. // Get the session condition for learning paths of the base + session.
  182. $session = api_get_session_condition($session_id);
  183. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  184. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  185. // Selecting by view_count descending allows to get the highest view_count first.
  186. $sql = "SELECT * FROM $lp_table
  187. WHERE
  188. c_id = $course_id AND
  189. lp_id = $lp_id AND
  190. user_id = $user_id
  191. $session
  192. ORDER BY view_count DESC";
  193. $res = Database::query($sql);
  194. if ($debug) {
  195. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  196. }
  197. if (Database::num_rows($res) > 0) {
  198. if ($debug) {
  199. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  200. }
  201. $row = Database::fetch_array($res);
  202. $this->attempt = $row['view_count'];
  203. $this->lp_view_id = $row['id'];
  204. $this->last_item_seen = $row['last_item'];
  205. $this->progress_db = $row['progress'];
  206. $this->lp_view_session_id = $row['session_id'];
  207. } elseif (!api_is_invitee()) {
  208. if ($debug) {
  209. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  210. }
  211. $this->attempt = 1;
  212. $params = [
  213. 'c_id' => $course_id,
  214. 'lp_id' => $lp_id,
  215. 'user_id' => $user_id,
  216. 'view_count' => 1,
  217. 'session_id' => $session_id,
  218. 'last_item' => 0,
  219. ];
  220. $this->last_item_seen = 0;
  221. $this->lp_view_session_id = $session_id;
  222. $this->lp_view_id = Database::insert($lp_table, $params);
  223. if (!empty($this->lp_view_id)) {
  224. $sql = "UPDATE $lp_table SET id = iid
  225. WHERE iid = ".$this->lp_view_id;
  226. Database::query($sql);
  227. }
  228. }
  229. // Initialise items.
  230. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  231. $sql = "SELECT * FROM $lp_item_table
  232. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  233. ORDER BY parent_item_id, display_order";
  234. $res = Database::query($sql);
  235. if ($debug) {
  236. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  237. error_log('-- Start while--');
  238. }
  239. $lp_item_id_list = [];
  240. while ($row = Database::fetch_array($res)) {
  241. $lp_item_id_list[] = $row['iid'];
  242. switch ($this->type) {
  243. case 3: //aicc
  244. $oItem = new aiccItem('db', $row['iid'], $course_id);
  245. if (is_object($oItem)) {
  246. $my_item_id = $oItem->get_id();
  247. $oItem->set_lp_view($this->lp_view_id, $course_id);
  248. $oItem->set_prevent_reinit($this->prevent_reinit);
  249. // Don't use reference here as the next loop will make the pointed object change.
  250. $this->items[$my_item_id] = $oItem;
  251. $this->refs_list[$oItem->ref] = $my_item_id;
  252. if ($debug) {
  253. error_log(
  254. 'learnpath::__construct() - '.
  255. 'aicc object with id '.$my_item_id.
  256. ' set in items[]',
  257. 0
  258. );
  259. }
  260. }
  261. break;
  262. case 2:
  263. $oItem = new scormItem('db', $row['iid'], $course_id);
  264. if (is_object($oItem)) {
  265. $my_item_id = $oItem->get_id();
  266. $oItem->set_lp_view($this->lp_view_id, $course_id);
  267. $oItem->set_prevent_reinit($this->prevent_reinit);
  268. // Don't use reference here as the next loop will make the pointed object change.
  269. $this->items[$my_item_id] = $oItem;
  270. $this->refs_list[$oItem->ref] = $my_item_id;
  271. if ($debug) {
  272. error_log('object with id '.$my_item_id.' set in items[]');
  273. }
  274. }
  275. break;
  276. case 1:
  277. default:
  278. if ($debug) {
  279. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  280. }
  281. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  282. if ($debug) {
  283. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  284. }
  285. if (is_object($oItem)) {
  286. $my_item_id = $oItem->get_id();
  287. // Moved down to when we are sure the item_view exists.
  288. //$oItem->set_lp_view($this->lp_view_id);
  289. $oItem->set_prevent_reinit($this->prevent_reinit);
  290. // Don't use reference here as the next loop will make the pointed object change.
  291. $this->items[$my_item_id] = $oItem;
  292. $this->refs_list[$my_item_id] = $my_item_id;
  293. if ($debug) {
  294. error_log(
  295. 'learnpath::__construct() '.__LINE__.
  296. ' - object with id '.$my_item_id.' set in items[]'
  297. );
  298. }
  299. }
  300. break;
  301. }
  302. // Setting the object level with variable $this->items[$i][parent]
  303. foreach ($this->items as $itemLPObject) {
  304. $level = self::get_level_for_item(
  305. $this->items,
  306. $itemLPObject->db_id
  307. );
  308. $itemLPObject->level = $level;
  309. }
  310. // Setting the view in the item object.
  311. if (is_object($this->items[$row['iid']])) {
  312. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  313. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  314. $this->items[$row['iid']]->current_start_time = 0;
  315. $this->items[$row['iid']]->current_stop_time = 0;
  316. }
  317. }
  318. }
  319. if ($debug) {
  320. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  321. }
  322. if (!empty($lp_item_id_list)) {
  323. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  324. if (!empty($lp_item_id_list_to_string)) {
  325. // Get last viewing vars.
  326. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  327. // This query should only return one or zero result.
  328. $sql = "SELECT lp_item_id, status
  329. FROM $itemViewTable
  330. WHERE
  331. c_id = $course_id AND
  332. lp_view_id = ".$this->lp_view_id." AND
  333. lp_item_id IN ('".$lp_item_id_list_to_string."')
  334. ORDER BY view_count DESC ";
  335. if ($debug) {
  336. error_log(
  337. 'learnpath::__construct() - Selecting item_views: '.$sql,
  338. 0
  339. );
  340. }
  341. $status_list = [];
  342. $res = Database::query($sql);
  343. while ($row = Database:: fetch_array($res)) {
  344. $status_list[$row['lp_item_id']] = $row['status'];
  345. }
  346. foreach ($lp_item_id_list as $item_id) {
  347. if (isset($status_list[$item_id])) {
  348. $status = $status_list[$item_id];
  349. if (is_object($this->items[$item_id])) {
  350. $this->items[$item_id]->set_status($status);
  351. if (empty($status)) {
  352. $this->items[$item_id]->set_status(
  353. $this->default_status
  354. );
  355. }
  356. }
  357. } else {
  358. if (!api_is_invitee()) {
  359. if (is_object($this->items[$item_id])) {
  360. $this->items[$item_id]->set_status(
  361. $this->default_status
  362. );
  363. }
  364. if (!empty($this->lp_view_id)) {
  365. // Add that row to the lp_item_view table so that
  366. // we have something to show in the stats page.
  367. $params = [
  368. 'c_id' => $course_id,
  369. 'lp_item_id' => $item_id,
  370. 'lp_view_id' => $this->lp_view_id,
  371. 'view_count' => 1,
  372. 'status' => 'not attempted',
  373. 'start_time' => time(),
  374. 'total_time' => 0,
  375. 'score' => 0,
  376. ];
  377. $insertId = Database::insert($itemViewTable, $params);
  378. if ($insertId) {
  379. $sql = "UPDATE $itemViewTable SET id = iid
  380. WHERE iid = $insertId";
  381. Database::query($sql);
  382. }
  383. $this->items[$item_id]->set_lp_view(
  384. $this->lp_view_id,
  385. $course_id
  386. );
  387. }
  388. }
  389. }
  390. }
  391. }
  392. }
  393. $this->ordered_items = self::get_flat_ordered_items_list(
  394. $this->get_id(),
  395. 0,
  396. $course_id
  397. );
  398. $this->max_ordered_items = 0;
  399. foreach ($this->ordered_items as $index => $dummy) {
  400. if ($index > $this->max_ordered_items && !empty($dummy)) {
  401. $this->max_ordered_items = $index;
  402. }
  403. }
  404. // TODO: Define the current item better.
  405. $this->first();
  406. if ($debug) {
  407. error_log('lp_view_session_id '.$this->lp_view_session_id);
  408. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  409. }
  410. } else {
  411. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  412. }
  413. }
  414. }
  415. /**
  416. * @return string
  417. */
  418. public function getCourseCode()
  419. {
  420. return $this->cc;
  421. }
  422. /**
  423. * @return int
  424. */
  425. public function get_course_int_id()
  426. {
  427. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  428. }
  429. /**
  430. * @param $course_id
  431. *
  432. * @return int
  433. */
  434. public function set_course_int_id($course_id)
  435. {
  436. return $this->course_int_id = (int) $course_id;
  437. }
  438. /**
  439. * Function rewritten based on old_add_item() from Yannick Warnier.
  440. * Due the fact that users can decide where the item should come, I had to overlook this function and
  441. * I found it better to rewrite it. Old function is still available.
  442. * Added also the possibility to add a description.
  443. *
  444. * @param int $parent
  445. * @param int $previous
  446. * @param string $type
  447. * @param int $id resource ID (ref)
  448. * @param string $title
  449. * @param string $description
  450. * @param int $prerequisites
  451. * @param int $max_time_allowed
  452. * @param int $userId
  453. *
  454. * @return int
  455. */
  456. public function add_item(
  457. $parent,
  458. $previous,
  459. $type = 'dir',
  460. $id,
  461. $title,
  462. $description,
  463. $prerequisites = 0,
  464. $max_time_allowed = 0,
  465. $userId = 0
  466. ) {
  467. $course_id = $this->course_info['real_id'];
  468. if ($this->debug > 0) {
  469. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  470. }
  471. if (empty($course_id)) {
  472. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  473. $this->course_info = api_get_course_info($this->cc);
  474. $course_id = $this->course_info['real_id'];
  475. }
  476. $userId = empty($userId) ? api_get_user_id() : $userId;
  477. $sessionId = api_get_session_id();
  478. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  479. $_course = $this->course_info;
  480. $parent = intval($parent);
  481. $previous = intval($previous);
  482. $id = intval($id);
  483. $max_time_allowed = htmlentities($max_time_allowed);
  484. if (empty($max_time_allowed)) {
  485. $max_time_allowed = 0;
  486. }
  487. $sql = "SELECT COUNT(iid) AS num
  488. FROM $tbl_lp_item
  489. WHERE
  490. c_id = $course_id AND
  491. lp_id = ".$this->get_id()." AND
  492. parent_item_id = ".$parent;
  493. $res_count = Database::query($sql);
  494. $row = Database::fetch_array($res_count);
  495. $num = $row['num'];
  496. if ($num > 0) {
  497. if (empty($previous)) {
  498. $sql = "SELECT iid, next_item_id, display_order
  499. FROM $tbl_lp_item
  500. WHERE
  501. c_id = $course_id AND
  502. lp_id = ".$this->get_id()." AND
  503. parent_item_id = $parent AND
  504. previous_item_id = 0 OR
  505. previous_item_id = $parent";
  506. $result = Database::query($sql);
  507. $row = Database::fetch_array($result);
  508. $tmp_previous = 0;
  509. $next = $row['iid'];
  510. $display_order = 0;
  511. } else {
  512. $previous = (int) $previous;
  513. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  514. FROM $tbl_lp_item
  515. WHERE
  516. c_id = $course_id AND
  517. lp_id = ".$this->get_id()." AND
  518. id = $previous";
  519. $result = Database::query($sql);
  520. $row = Database:: fetch_array($result);
  521. $tmp_previous = $row['iid'];
  522. $next = $row['next_item_id'];
  523. $display_order = $row['display_order'];
  524. }
  525. } else {
  526. $tmp_previous = 0;
  527. $next = 0;
  528. $display_order = 0;
  529. }
  530. $id = intval($id);
  531. $typeCleaned = Database::escape_string($type);
  532. $max_score = 100;
  533. if ($type == 'quiz') {
  534. $sql = 'SELECT SUM(ponderation)
  535. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  536. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  537. ON
  538. quiz_question.id = quiz_rel_question.question_id AND
  539. quiz_question.c_id = quiz_rel_question.c_id
  540. WHERE
  541. quiz_rel_question.exercice_id = '.$id." AND
  542. quiz_question.c_id = $course_id AND
  543. quiz_rel_question.c_id = $course_id ";
  544. $rsQuiz = Database::query($sql);
  545. $max_score = Database::result($rsQuiz, 0, 0);
  546. // Disabling the exercise if we add it inside a LP
  547. $exercise = new Exercise($course_id);
  548. $exercise->read($id);
  549. $exercise->disable();
  550. $exercise->save();
  551. }
  552. $params = [
  553. "c_id" => $course_id,
  554. "lp_id" => $this->get_id(),
  555. "item_type" => $typeCleaned,
  556. "ref" => '',
  557. "title" => $title,
  558. "description" => $description,
  559. "path" => $id,
  560. "max_score" => $max_score,
  561. "parent_item_id" => $parent,
  562. "previous_item_id" => $previous,
  563. "next_item_id" => intval($next),
  564. "display_order" => $display_order + 1,
  565. "prerequisite" => $prerequisites,
  566. "max_time_allowed" => $max_time_allowed,
  567. 'min_score' => 0,
  568. 'launch_data' => '',
  569. ];
  570. if ($prerequisites != 0) {
  571. $params['prerequisite'] = $prerequisites;
  572. }
  573. $new_item_id = Database::insert($tbl_lp_item, $params);
  574. if ($this->debug > 2) {
  575. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  576. }
  577. if ($new_item_id) {
  578. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  579. Database::query($sql);
  580. $sql = "UPDATE $tbl_lp_item
  581. SET previous_item_id = $new_item_id
  582. WHERE c_id = $course_id AND id = $next";
  583. Database::query($sql);
  584. // Update the item that should be before the new item.
  585. $sql = "UPDATE $tbl_lp_item
  586. SET next_item_id = $new_item_id
  587. WHERE c_id = $course_id AND id = $tmp_previous";
  588. Database::query($sql);
  589. // Update all the items after the new item.
  590. $sql = "UPDATE $tbl_lp_item
  591. SET display_order = display_order + 1
  592. WHERE
  593. c_id = $course_id AND
  594. lp_id = ".$this->get_id()." AND
  595. iid <> $new_item_id AND
  596. parent_item_id = $parent AND
  597. display_order > $display_order";
  598. Database::query($sql);
  599. // Update the item that should come after the new item.
  600. $sql = "UPDATE $tbl_lp_item
  601. SET ref = $new_item_id
  602. WHERE c_id = $course_id AND iid = $new_item_id";
  603. Database::query($sql);
  604. // Upload audio.
  605. if (!empty($_FILES['mp3']['name'])) {
  606. // Create the audio folder if it does not exist yet.
  607. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  608. if (!is_dir($filepath.'audio')) {
  609. mkdir(
  610. $filepath.'audio',
  611. api_get_permissions_for_new_directories()
  612. );
  613. $audio_id = add_document(
  614. $_course,
  615. '/audio',
  616. 'folder',
  617. 0,
  618. 'audio',
  619. '',
  620. 0,
  621. true,
  622. null,
  623. $sessionId,
  624. $userId
  625. );
  626. api_item_property_update(
  627. $_course,
  628. TOOL_DOCUMENT,
  629. $audio_id,
  630. 'FolderCreated',
  631. $userId,
  632. null,
  633. null,
  634. null,
  635. null,
  636. $sessionId
  637. );
  638. api_item_property_update(
  639. $_course,
  640. TOOL_DOCUMENT,
  641. $audio_id,
  642. 'invisible',
  643. $userId,
  644. null,
  645. null,
  646. null,
  647. null,
  648. $sessionId
  649. );
  650. }
  651. $file_path = handle_uploaded_document(
  652. $_course,
  653. $_FILES['mp3'],
  654. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  655. '/audio',
  656. $userId,
  657. '',
  658. '',
  659. '',
  660. '',
  661. false
  662. );
  663. // Getting the filename only.
  664. $file_components = explode('/', $file_path);
  665. $file = $file_components[count($file_components) - 1];
  666. // Store the mp3 file in the lp_item table.
  667. $sql = "UPDATE $tbl_lp_item SET
  668. audio = '".Database::escape_string($file)."'
  669. WHERE iid = '".intval($new_item_id)."'";
  670. Database::query($sql);
  671. }
  672. }
  673. return $new_item_id;
  674. }
  675. /**
  676. * Static admin function allowing addition of a learnpath to a course.
  677. *
  678. * @param string Course code
  679. * @param string Learnpath name
  680. * @param string Learnpath description string, if provided
  681. * @param string Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  682. * @param string Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  683. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  684. * @param string $publicated_on
  685. * @param string $expired_on
  686. * @param int $categoryId
  687. * @param int $userId
  688. *
  689. * @return int The new learnpath ID on success, 0 on failure
  690. */
  691. public static function add_lp(
  692. $courseCode,
  693. $name,
  694. $description = '',
  695. $learnpath = 'guess',
  696. $origin = 'zip',
  697. $zipname = '',
  698. $publicated_on = '',
  699. $expired_on = '',
  700. $categoryId = 0,
  701. $userId = 0
  702. ) {
  703. global $charset;
  704. if (!empty($courseCode)) {
  705. $courseInfo = api_get_course_info($courseCode);
  706. $course_id = $courseInfo['real_id'];
  707. } else {
  708. $course_id = api_get_course_int_id();
  709. $courseInfo = api_get_course_info();
  710. }
  711. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  712. // Check course code exists.
  713. // Check lp_name doesn't exist, otherwise append something.
  714. $i = 0;
  715. $name = Database::escape_string($name);
  716. $categoryId = intval($categoryId);
  717. // Session id.
  718. $session_id = api_get_session_id();
  719. $userId = empty($userId) ? api_get_user_id() : $userId;
  720. $check_name = "SELECT * FROM $tbl_lp
  721. WHERE c_id = $course_id AND name = '$name'";
  722. $res_name = Database::query($check_name);
  723. if (empty($publicated_on)) {
  724. $publicated_on = null;
  725. } else {
  726. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  727. }
  728. if (empty($expired_on)) {
  729. $expired_on = null;
  730. } else {
  731. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  732. }
  733. while (Database::num_rows($res_name)) {
  734. // There is already one such name, update the current one a bit.
  735. $i++;
  736. $name = $name.' - '.$i;
  737. $check_name = "SELECT * FROM $tbl_lp
  738. WHERE c_id = $course_id AND name = '$name'";
  739. $res_name = Database::query($check_name);
  740. }
  741. // New name does not exist yet; keep it.
  742. // Escape description.
  743. // Kevin: added htmlentities().
  744. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  745. $type = 1;
  746. switch ($learnpath) {
  747. case 'guess':
  748. break;
  749. case 'dokeos':
  750. case 'chamilo':
  751. $type = 1;
  752. break;
  753. case 'aicc':
  754. break;
  755. }
  756. switch ($origin) {
  757. case 'zip':
  758. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  759. break;
  760. case 'manual':
  761. default:
  762. $get_max = "SELECT MAX(display_order)
  763. FROM $tbl_lp WHERE c_id = $course_id";
  764. $res_max = Database::query($get_max);
  765. if (Database::num_rows($res_max) < 1) {
  766. $dsp = 1;
  767. } else {
  768. $row = Database::fetch_array($res_max);
  769. $dsp = $row[0] + 1;
  770. }
  771. $params = [
  772. 'c_id' => $course_id,
  773. 'lp_type' => $type,
  774. 'name' => $name,
  775. 'description' => $description,
  776. 'path' => '',
  777. 'default_view_mod' => 'embedded',
  778. 'default_encoding' => 'UTF-8',
  779. 'display_order' => $dsp,
  780. 'content_maker' => 'Chamilo',
  781. 'content_local' => 'local',
  782. 'js_lib' => '',
  783. 'session_id' => $session_id,
  784. 'created_on' => api_get_utc_datetime(),
  785. 'modified_on' => api_get_utc_datetime(),
  786. 'publicated_on' => $publicated_on,
  787. 'expired_on' => $expired_on,
  788. 'category_id' => $categoryId,
  789. 'force_commit' => 0,
  790. 'content_license' => '',
  791. 'debug' => 0,
  792. 'theme' => '',
  793. 'preview_image' => '',
  794. 'author' => '',
  795. 'prerequisite' => 0,
  796. 'hide_toc_frame' => 0,
  797. 'seriousgame_mode' => 0,
  798. 'autolaunch' => 0,
  799. 'max_attempts' => 0,
  800. 'subscribe_users' => 0,
  801. 'accumulate_scorm_time' => 1,
  802. ];
  803. $id = Database::insert($tbl_lp, $params);
  804. if ($id > 0) {
  805. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  806. Database::query($sql);
  807. // Insert into item_property.
  808. api_item_property_update(
  809. $courseInfo,
  810. TOOL_LEARNPATH,
  811. $id,
  812. 'LearnpathAdded',
  813. $userId
  814. );
  815. api_set_default_visibility(
  816. $id,
  817. TOOL_LEARNPATH,
  818. 0,
  819. $courseInfo,
  820. $session_id,
  821. $userId
  822. );
  823. return $id;
  824. }
  825. break;
  826. }
  827. }
  828. /**
  829. * Auto completes the parents of an item in case it's been completed or passed.
  830. *
  831. * @param int $item Optional ID of the item from which to look for parents
  832. */
  833. public function autocomplete_parents($item)
  834. {
  835. $debug = $this->debug;
  836. if ($debug) {
  837. error_log('Learnpath::autocomplete_parents()');
  838. }
  839. if (empty($item)) {
  840. $item = $this->current;
  841. }
  842. $currentItem = $this->getItem($item);
  843. if ($currentItem) {
  844. $parent_id = $currentItem->get_parent();
  845. $parent = $this->getItem($parent_id);
  846. if ($parent) {
  847. // if $item points to an object and there is a parent.
  848. if ($debug) {
  849. error_log(
  850. 'Autocompleting parent of item '.$item.' '.
  851. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  852. 0
  853. );
  854. }
  855. // New experiment including failed and browsed in completed status.
  856. //$current_status = $currentItem->get_status();
  857. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  858. // Fixes chapter auto complete
  859. if (true) {
  860. // If the current item is completed or passes or succeeded.
  861. $updateParentStatus = true;
  862. if ($debug) {
  863. error_log('Status of current item is alright');
  864. }
  865. foreach ($parent->get_children() as $childItemId) {
  866. $childItem = $this->getItem($childItemId);
  867. // If children was not set try to get the info
  868. if (empty($childItem->db_item_view_id)) {
  869. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  870. }
  871. // Check all his brothers (parent's children) for completion status.
  872. if ($childItemId != $item) {
  873. if ($debug) {
  874. error_log(
  875. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  876. 0
  877. );
  878. }
  879. // Trying completing parents of failed and browsed items as well.
  880. if ($childItem->status_is(
  881. [
  882. 'completed',
  883. 'passed',
  884. 'succeeded',
  885. 'browsed',
  886. 'failed',
  887. ]
  888. )
  889. ) {
  890. // Keep completion status to true.
  891. continue;
  892. } else {
  893. if ($debug > 2) {
  894. error_log(
  895. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
  896. 0
  897. );
  898. }
  899. $updateParentStatus = false;
  900. break;
  901. }
  902. }
  903. }
  904. if ($updateParentStatus) {
  905. // If all the children were completed:
  906. $parent->set_status('completed');
  907. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  908. // Force the status to "completed"
  909. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  910. $this->update_queue[$parent->get_id()] = 'completed';
  911. if ($debug) {
  912. error_log(
  913. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  914. print_r($this->update_queue, 1),
  915. 0
  916. );
  917. }
  918. // Recursive call.
  919. $this->autocomplete_parents($parent->get_id());
  920. }
  921. }
  922. } else {
  923. if ($debug) {
  924. error_log("Parent #$parent_id does not exists");
  925. }
  926. }
  927. } else {
  928. if ($debug) {
  929. error_log("#$item is an item that doesn't have parents");
  930. }
  931. }
  932. }
  933. /**
  934. * Closes the current resource.
  935. *
  936. * Stops the timer
  937. * Saves into the database if required
  938. * Clears the current resource data from this object
  939. *
  940. * @return bool True on success, false on failure
  941. */
  942. public function close()
  943. {
  944. if ($this->debug > 0) {
  945. error_log('In learnpath::close()', 0);
  946. }
  947. if (empty($this->lp_id)) {
  948. $this->error = 'Trying to close this learnpath but no ID is set';
  949. return false;
  950. }
  951. $this->current_time_stop = time();
  952. $this->ordered_items = [];
  953. $this->index = 0;
  954. unset($this->lp_id);
  955. //unset other stuff
  956. return true;
  957. }
  958. /**
  959. * Static admin function allowing removal of a learnpath.
  960. *
  961. * @param array $courseInfo
  962. * @param int $id Learnpath ID
  963. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  964. *
  965. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  966. */
  967. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  968. {
  969. $course_id = api_get_course_int_id();
  970. if (!empty($courseInfo)) {
  971. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  972. }
  973. // TODO: Implement a way of getting this to work when the current object is not set.
  974. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  975. // If an ID is specifically given and the current LP is not the same, prevent delete.
  976. if (!empty($id) && ($id != $this->lp_id)) {
  977. return false;
  978. }
  979. $lp = Database::get_course_table(TABLE_LP_MAIN);
  980. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  981. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  982. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  983. // Delete lp item id.
  984. foreach ($this->items as $id => $dummy) {
  985. $sql = "DELETE FROM $lp_item_view
  986. WHERE c_id = $course_id AND lp_item_id = '".$id."'";
  987. Database::query($sql);
  988. }
  989. // Proposed by Christophe (nickname: clefevre)
  990. $sql = "DELETE FROM $lp_item
  991. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  992. Database::query($sql);
  993. $sql = "DELETE FROM $lp_view
  994. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  995. Database::query($sql);
  996. self::toggle_publish($this->lp_id, 'i');
  997. if ($this->type == 2 || $this->type == 3) {
  998. // This is a scorm learning path, delete the files as well.
  999. $sql = "SELECT path FROM $lp
  1000. WHERE iid = ".$this->lp_id;
  1001. $res = Database::query($sql);
  1002. if (Database::num_rows($res) > 0) {
  1003. $row = Database::fetch_array($res);
  1004. $path = $row['path'];
  1005. $sql = "SELECT id FROM $lp
  1006. WHERE
  1007. c_id = $course_id AND
  1008. path = '$path' AND
  1009. iid != ".$this->lp_id;
  1010. $res = Database::query($sql);
  1011. if (Database::num_rows($res) > 0) {
  1012. // Another learning path uses this directory, so don't delete it.
  1013. if ($this->debug > 2) {
  1014. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1015. }
  1016. } else {
  1017. // No other LP uses that directory, delete it.
  1018. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1019. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // The absolute system path for this course.
  1020. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1021. if ($this->debug > 2) {
  1022. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1023. }
  1024. // Proposed by Christophe (clefevre).
  1025. if (strcmp(substr($path, -2), "/.") == 0) {
  1026. $path = substr($path, 0, -1); // Remove "." at the end.
  1027. }
  1028. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1029. rmdirr($course_scorm_dir.$path);
  1030. }
  1031. }
  1032. }
  1033. }
  1034. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1035. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1036. // Delete tools
  1037. $sql = "DELETE FROM $tbl_tool
  1038. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1039. Database::query($sql);
  1040. $sql = "DELETE FROM $lp
  1041. WHERE iid = ".$this->lp_id;
  1042. Database::query($sql);
  1043. // Updates the display order of all lps.
  1044. $this->update_display_order();
  1045. api_item_property_update(
  1046. api_get_course_info(),
  1047. TOOL_LEARNPATH,
  1048. $this->lp_id,
  1049. 'delete',
  1050. api_get_user_id()
  1051. );
  1052. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1053. api_get_course_id(),
  1054. 4,
  1055. $id,
  1056. api_get_session_id()
  1057. );
  1058. if ($link_info !== false) {
  1059. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1060. }
  1061. if (api_get_setting('search_enabled') == 'true') {
  1062. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1063. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1064. }
  1065. }
  1066. /**
  1067. * Removes all the children of one item - dangerous!
  1068. *
  1069. * @param int $id Element ID of which children have to be removed
  1070. *
  1071. * @return int Total number of children removed
  1072. */
  1073. public function delete_children_items($id)
  1074. {
  1075. $course_id = $this->course_info['real_id'];
  1076. if ($this->debug > 0) {
  1077. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1078. }
  1079. $num = 0;
  1080. if (empty($id) || $id != strval(intval($id))) {
  1081. return false;
  1082. }
  1083. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1084. $sql = "SELECT * FROM $lp_item
  1085. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1086. $res = Database::query($sql);
  1087. while ($row = Database::fetch_array($res)) {
  1088. $num += $this->delete_children_items($row['iid']);
  1089. $sql = "DELETE FROM $lp_item
  1090. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1091. Database::query($sql);
  1092. $num++;
  1093. }
  1094. return $num;
  1095. }
  1096. /**
  1097. * Removes an item from the current learnpath.
  1098. *
  1099. * @param int $id Elem ID (0 if first)
  1100. * @param int $remove Whether to remove the resource/data from the
  1101. * system or leave it (default: 'keep', others 'remove')
  1102. *
  1103. * @return int Number of elements moved
  1104. *
  1105. * @todo implement resource removal
  1106. */
  1107. public function delete_item($id, $remove = 'keep')
  1108. {
  1109. $course_id = api_get_course_int_id();
  1110. if ($this->debug > 0) {
  1111. error_log('In learnpath::delete_item()', 0);
  1112. }
  1113. // TODO: Implement the resource removal.
  1114. if (empty($id) || $id != strval(intval($id))) {
  1115. return false;
  1116. }
  1117. // First select item to get previous, next, and display order.
  1118. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1119. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1120. $res_sel = Database::query($sql_sel);
  1121. if (Database::num_rows($res_sel) < 1) {
  1122. return false;
  1123. }
  1124. $row = Database::fetch_array($res_sel);
  1125. $previous = $row['previous_item_id'];
  1126. $next = $row['next_item_id'];
  1127. $display = $row['display_order'];
  1128. $parent = $row['parent_item_id'];
  1129. $lp = $row['lp_id'];
  1130. // Delete children items.
  1131. $num = $this->delete_children_items($id);
  1132. if ($this->debug > 2) {
  1133. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1134. }
  1135. // Now delete the item.
  1136. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1137. if ($this->debug > 2) {
  1138. error_log('Deleting item: '.$sql_del, 0);
  1139. }
  1140. Database::query($sql_del);
  1141. // Now update surrounding items.
  1142. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1143. WHERE iid = $previous";
  1144. Database::query($sql_upd);
  1145. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1146. WHERE iid = $next";
  1147. Database::query($sql_upd);
  1148. // Now update all following items with new display order.
  1149. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1150. WHERE
  1151. c_id = $course_id AND
  1152. lp_id = $lp AND
  1153. parent_item_id = $parent AND
  1154. display_order > $display";
  1155. Database::query($sql_all);
  1156. //Removing prerequisites since the item will not longer exist
  1157. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1158. WHERE c_id = $course_id AND prerequisite = $id";
  1159. Database::query($sql_all);
  1160. // Remove from search engine if enabled.
  1161. if (api_get_setting('search_enabled') == 'true') {
  1162. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1163. $sql = 'SELECT * FROM %s
  1164. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1165. LIMIT 1';
  1166. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1167. $res = Database::query($sql);
  1168. if (Database::num_rows($res) > 0) {
  1169. $row2 = Database::fetch_array($res);
  1170. $di = new ChamiloIndexer();
  1171. $di->remove_document($row2['search_did']);
  1172. }
  1173. $sql = 'DELETE FROM %s
  1174. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1175. LIMIT 1';
  1176. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1177. Database::query($sql);
  1178. }
  1179. }
  1180. /**
  1181. * Updates an item's content in place.
  1182. *
  1183. * @param int $id Element ID
  1184. * @param int $parent Parent item ID
  1185. * @param int $previous Previous item ID
  1186. * @param string $title Item title
  1187. * @param string $description Item description
  1188. * @param string $prerequisites Prerequisites (optional)
  1189. * @param array $audio The array resulting of the $_FILES[mp3] element
  1190. * @param int $max_time_allowed
  1191. * @param string $url
  1192. *
  1193. * @return bool True on success, false on error
  1194. */
  1195. public function edit_item(
  1196. $id,
  1197. $parent,
  1198. $previous,
  1199. $title,
  1200. $description,
  1201. $prerequisites = '0',
  1202. $audio = [],
  1203. $max_time_allowed = 0,
  1204. $url = ''
  1205. ) {
  1206. $course_id = api_get_course_int_id();
  1207. $_course = api_get_course_info();
  1208. if ($this->debug > 0) {
  1209. error_log('In learnpath::edit_item()', 0);
  1210. }
  1211. if (empty($max_time_allowed)) {
  1212. $max_time_allowed = 0;
  1213. }
  1214. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1215. return false;
  1216. }
  1217. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1218. $sql = "SELECT * FROM $tbl_lp_item
  1219. WHERE iid = $id";
  1220. $res_select = Database::query($sql);
  1221. $row_select = Database::fetch_array($res_select);
  1222. $audio_update_sql = '';
  1223. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1224. // Create the audio folder if it does not exist yet.
  1225. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1226. if (!is_dir($filepath.'audio')) {
  1227. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1228. $audio_id = add_document(
  1229. $_course,
  1230. '/audio',
  1231. 'folder',
  1232. 0,
  1233. 'audio'
  1234. );
  1235. api_item_property_update(
  1236. $_course,
  1237. TOOL_DOCUMENT,
  1238. $audio_id,
  1239. 'FolderCreated',
  1240. api_get_user_id(),
  1241. null,
  1242. null,
  1243. null,
  1244. null,
  1245. api_get_session_id()
  1246. );
  1247. api_item_property_update(
  1248. $_course,
  1249. TOOL_DOCUMENT,
  1250. $audio_id,
  1251. 'invisible',
  1252. api_get_user_id(),
  1253. null,
  1254. null,
  1255. null,
  1256. null,
  1257. api_get_session_id()
  1258. );
  1259. }
  1260. // Upload file in documents.
  1261. $pi = pathinfo($audio['name']);
  1262. if ($pi['extension'] == 'mp3') {
  1263. $c_det = api_get_course_info($this->cc);
  1264. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1265. $path = handle_uploaded_document(
  1266. $c_det,
  1267. $audio,
  1268. $bp,
  1269. '/audio',
  1270. api_get_user_id(),
  1271. 0,
  1272. null,
  1273. 0,
  1274. 'rename',
  1275. false,
  1276. 0
  1277. );
  1278. $path = substr($path, 7);
  1279. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1280. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1281. }
  1282. }
  1283. $same_parent = ($row_select['parent_item_id'] == $parent) ? true : false;
  1284. $same_previous = ($row_select['previous_item_id'] == $previous) ? true : false;
  1285. // TODO: htmlspecialchars to be checked for encoding related problems.
  1286. if ($same_parent && $same_previous) {
  1287. // Only update title and description.
  1288. $sql = "UPDATE $tbl_lp_item
  1289. SET title = '".Database::escape_string($title)."',
  1290. prerequisite = '".$prerequisites."',
  1291. description = '".Database::escape_string($description)."'
  1292. ".$audio_update_sql.",
  1293. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1294. WHERE iid = $id";
  1295. Database::query($sql);
  1296. } else {
  1297. $old_parent = $row_select['parent_item_id'];
  1298. $old_previous = $row_select['previous_item_id'];
  1299. $old_next = $row_select['next_item_id'];
  1300. $old_order = $row_select['display_order'];
  1301. $old_prerequisite = $row_select['prerequisite'];
  1302. $old_max_time_allowed = $row_select['max_time_allowed'];
  1303. /* BEGIN -- virtually remove the current item id */
  1304. /* for the next and previous item it is like the current item doesn't exist anymore */
  1305. if ($old_previous != 0) {
  1306. // Next
  1307. $sql = "UPDATE $tbl_lp_item
  1308. SET next_item_id = $old_next
  1309. WHERE iid = $old_previous";
  1310. Database::query($sql);
  1311. }
  1312. if ($old_next != 0) {
  1313. // Previous
  1314. $sql = "UPDATE $tbl_lp_item
  1315. SET previous_item_id = $old_previous
  1316. WHERE iid = $old_next";
  1317. Database::query($sql);
  1318. }
  1319. // display_order - 1 for every item with a display_order
  1320. // bigger then the display_order of the current item.
  1321. $sql = "UPDATE $tbl_lp_item
  1322. SET display_order = display_order - 1
  1323. WHERE
  1324. c_id = $course_id AND
  1325. display_order > $old_order AND
  1326. lp_id = ".$this->lp_id." AND
  1327. parent_item_id = $old_parent";
  1328. Database::query($sql);
  1329. /* END -- virtually remove the current item id */
  1330. /* BEGIN -- update the current item id to his new location */
  1331. if ($previous == 0) {
  1332. // Select the data of the item that should come after the current item.
  1333. $sql = "SELECT id, display_order
  1334. FROM $tbl_lp_item
  1335. WHERE
  1336. c_id = $course_id AND
  1337. lp_id = ".$this->lp_id." AND
  1338. parent_item_id = $parent AND
  1339. previous_item_id = $previous";
  1340. $res_select_old = Database::query($sql);
  1341. $row_select_old = Database::fetch_array($res_select_old);
  1342. // If the new parent didn't have children before.
  1343. if (Database::num_rows($res_select_old) == 0) {
  1344. $new_next = 0;
  1345. $new_order = 1;
  1346. } else {
  1347. $new_next = $row_select_old['id'];
  1348. $new_order = $row_select_old['display_order'];
  1349. }
  1350. } else {
  1351. // Select the data of the item that should come before the current item.
  1352. $sql = "SELECT next_item_id, display_order
  1353. FROM $tbl_lp_item
  1354. WHERE iid = $previous";
  1355. $res_select_old = Database::query($sql);
  1356. $row_select_old = Database::fetch_array($res_select_old);
  1357. $new_next = $row_select_old['next_item_id'];
  1358. $new_order = $row_select_old['display_order'] + 1;
  1359. }
  1360. // TODO: htmlspecialchars to be checked for encoding related problems.
  1361. // Update the current item with the new data.
  1362. $sql = "UPDATE $tbl_lp_item
  1363. SET
  1364. title = '".Database::escape_string($title)."',
  1365. description = '".Database::escape_string($description)."',
  1366. parent_item_id = $parent,
  1367. previous_item_id = $previous,
  1368. next_item_id = $new_next,
  1369. display_order = $new_order
  1370. $audio_update_sql
  1371. WHERE iid = $id";
  1372. Database::query($sql);
  1373. if ($previous != 0) {
  1374. // Update the previous item's next_item_id.
  1375. $sql = "UPDATE $tbl_lp_item
  1376. SET next_item_id = $id
  1377. WHERE iid = $previous";
  1378. Database::query($sql);
  1379. }
  1380. if ($new_next != 0) {
  1381. // Update the next item's previous_item_id.
  1382. $sql = "UPDATE $tbl_lp_item
  1383. SET previous_item_id = $id
  1384. WHERE iid = $new_next";
  1385. Database::query($sql);
  1386. }
  1387. if ($old_prerequisite != $prerequisites) {
  1388. $sql = "UPDATE $tbl_lp_item
  1389. SET prerequisite = '$prerequisites'
  1390. WHERE iid = $id";
  1391. Database::query($sql);
  1392. }
  1393. if ($old_max_time_allowed != $max_time_allowed) {
  1394. // update max time allowed
  1395. $sql = "UPDATE $tbl_lp_item
  1396. SET max_time_allowed = $max_time_allowed
  1397. WHERE iid = $id";
  1398. Database::query($sql);
  1399. }
  1400. // Update all the items with the same or a bigger display_order than the current item.
  1401. $sql = "UPDATE $tbl_lp_item
  1402. SET display_order = display_order + 1
  1403. WHERE
  1404. c_id = $course_id AND
  1405. lp_id = ".$this->get_id()." AND
  1406. iid <> $id AND
  1407. parent_item_id = $parent AND
  1408. display_order >= $new_order";
  1409. Database::query($sql);
  1410. }
  1411. if ($row_select['item_type'] == 'link') {
  1412. $link = new Link();
  1413. $linkId = $row_select['path'];
  1414. $link->updateLink($linkId, $url);
  1415. }
  1416. }
  1417. /**
  1418. * Updates an item's prereq in place.
  1419. *
  1420. * @param int $id Element ID
  1421. * @param string $prerequisite_id Prerequisite Element ID
  1422. * @param int $mastery_score Prerequisite min score
  1423. * @param int $max_score Prerequisite max score
  1424. *
  1425. * @return bool True on success, false on error
  1426. */
  1427. public function edit_item_prereq(
  1428. $id,
  1429. $prerequisite_id,
  1430. $mastery_score = 0,
  1431. $max_score = 100
  1432. ) {
  1433. $course_id = api_get_course_int_id();
  1434. if ($this->debug > 0) {
  1435. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','.$max_score.')', 0);
  1436. }
  1437. if (empty($id) || ($id != strval(intval($id))) || empty($prerequisite_id)) {
  1438. return false;
  1439. }
  1440. $prerequisite_id = intval($prerequisite_id);
  1441. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1442. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1443. $mastery_score = 0;
  1444. }
  1445. if (!is_numeric($max_score) || $max_score < 0) {
  1446. $max_score = 100;
  1447. }
  1448. /*if ($mastery_score > $max_score) {
  1449. $max_score = $mastery_score;
  1450. }*/
  1451. if (!is_numeric($prerequisite_id)) {
  1452. $prerequisite_id = 'NULL';
  1453. }
  1454. $mastery_score = floatval($mastery_score);
  1455. $max_score = floatval($max_score);
  1456. $sql = " UPDATE $tbl_lp_item
  1457. SET
  1458. prerequisite = $prerequisite_id ,
  1459. prerequisite_min_score = $mastery_score ,
  1460. prerequisite_max_score = $max_score
  1461. WHERE iid = $id";
  1462. Database::query($sql);
  1463. // TODO: Update the item object (can be ignored for now because refreshed).
  1464. return true;
  1465. }
  1466. /**
  1467. * Gets all the chapters belonging to the same parent as the item/chapter given
  1468. * Can also be called as abstract method.
  1469. *
  1470. * @param int $id Item ID
  1471. *
  1472. * @return array A list of all the "brother items" (or an empty array on failure)
  1473. */
  1474. public function getSiblingDirectories($id)
  1475. {
  1476. $course_id = api_get_course_int_id();
  1477. if ($this->debug > 0) {
  1478. error_log('In learnpath::getSiblingDirectories()', 0);
  1479. }
  1480. if (empty($id) || $id != strval(intval($id))) {
  1481. return [];
  1482. }
  1483. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1484. $sql_parent = "SELECT * FROM $lp_item
  1485. WHERE iid = $id AND item_type='dir'";
  1486. $res_parent = Database::query($sql_parent);
  1487. if (Database::num_rows($res_parent) > 0) {
  1488. $row_parent = Database::fetch_array($res_parent);
  1489. $parent = $row_parent['parent_item_id'];
  1490. $sql = "SELECT * FROM $lp_item
  1491. WHERE
  1492. parent_item_id = $parent AND
  1493. iid = $id AND
  1494. item_type='dir'
  1495. ORDER BY display_order";
  1496. $res_bros = Database::query($sql);
  1497. $list = [];
  1498. while ($row_bro = Database::fetch_array($res_bros)) {
  1499. $list[] = $row_bro;
  1500. }
  1501. return $list;
  1502. }
  1503. return [];
  1504. }
  1505. /**
  1506. * Gets all the items belonging to the same parent as the item given
  1507. * Can also be called as abstract method.
  1508. *
  1509. * @param int $id Item ID
  1510. *
  1511. * @return array A list of all the "brother items" (or an empty array on failure)
  1512. */
  1513. public function get_brother_items($id)
  1514. {
  1515. $course_id = api_get_course_int_id();
  1516. if ($this->debug > 0) {
  1517. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1518. }
  1519. if (empty($id) || $id != strval(intval($id))) {
  1520. return [];
  1521. }
  1522. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1523. $sql_parent = "SELECT * FROM $lp_item
  1524. WHERE iid = $id";
  1525. $res_parent = Database::query($sql_parent);
  1526. if (Database::num_rows($res_parent) > 0) {
  1527. $row_parent = Database::fetch_array($res_parent);
  1528. $parent = $row_parent['parent_item_id'];
  1529. $sql = "SELECT * FROM $lp_item
  1530. WHERE c_id = $course_id AND parent_item_id = $parent
  1531. ORDER BY display_order";
  1532. $res_bros = Database::query($sql);
  1533. $list = [];
  1534. while ($row_bro = Database::fetch_array($res_bros)) {
  1535. $list[] = $row_bro;
  1536. }
  1537. return $list;
  1538. }
  1539. return [];
  1540. }
  1541. /**
  1542. * Get the specific prefix index terms of this learning path.
  1543. *
  1544. * @param string $prefix
  1545. *
  1546. * @return array Array of terms
  1547. */
  1548. public function get_common_index_terms_by_prefix($prefix)
  1549. {
  1550. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1551. $terms = get_specific_field_values_list_by_prefix(
  1552. $prefix,
  1553. $this->cc,
  1554. TOOL_LEARNPATH,
  1555. $this->lp_id
  1556. );
  1557. $prefix_terms = [];
  1558. if (!empty($terms)) {
  1559. foreach ($terms as $term) {
  1560. $prefix_terms[] = $term['value'];
  1561. }
  1562. }
  1563. return $prefix_terms;
  1564. }
  1565. /**
  1566. * Gets the number of items currently completed.
  1567. *
  1568. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1569. *
  1570. * @return int The number of items currently completed
  1571. */
  1572. public function get_complete_items_count($failedStatusException = false)
  1573. {
  1574. if ($this->debug > 0) {
  1575. error_log('In learnpath::get_complete_items_count()', 0);
  1576. }
  1577. $i = 0;
  1578. $completedStatusList = [
  1579. 'completed',
  1580. 'passed',
  1581. 'succeeded',
  1582. 'browsed',
  1583. ];
  1584. if (!$failedStatusException) {
  1585. $completedStatusList[] = 'failed';
  1586. }
  1587. foreach ($this->items as $id => $dummy) {
  1588. // Trying failed and browsed considered "progressed" as well.
  1589. if ($this->items[$id]->status_is($completedStatusList) &&
  1590. $this->items[$id]->get_type() != 'dir'
  1591. ) {
  1592. $i++;
  1593. }
  1594. }
  1595. return $i;
  1596. }
  1597. /**
  1598. * Gets the current item ID.
  1599. *
  1600. * @return int The current learnpath item id
  1601. */
  1602. public function get_current_item_id()
  1603. {
  1604. $current = 0;
  1605. if ($this->debug > 0) {
  1606. error_log('In learnpath::get_current_item_id()', 0);
  1607. }
  1608. if (!empty($this->current)) {
  1609. $current = $this->current;
  1610. }
  1611. if ($this->debug > 2) {
  1612. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1613. }
  1614. return $current;
  1615. }
  1616. /**
  1617. * Force to get the first learnpath item id.
  1618. *
  1619. * @return int The current learnpath item id
  1620. */
  1621. public function get_first_item_id()
  1622. {
  1623. $current = 0;
  1624. if (is_array($this->ordered_items)) {
  1625. $current = $this->ordered_items[0];
  1626. }
  1627. return $current;
  1628. }
  1629. /**
  1630. * Gets the total number of items available for viewing in this SCORM.
  1631. *
  1632. * @return int The total number of items
  1633. */
  1634. public function get_total_items_count()
  1635. {
  1636. if ($this->debug > 0) {
  1637. error_log('In learnpath::get_total_items_count()', 0);
  1638. }
  1639. return count($this->items);
  1640. }
  1641. /**
  1642. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1643. *
  1644. * @return int The total no-chapters number of items
  1645. */
  1646. public function getTotalItemsCountWithoutDirs()
  1647. {
  1648. if ($this->debug > 0) {
  1649. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1650. }
  1651. $total = 0;
  1652. $typeListNotToCount = self::getChapterTypes();
  1653. foreach ($this->items as $temp2) {
  1654. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1655. $total++;
  1656. }
  1657. }
  1658. return $total;
  1659. }
  1660. /**
  1661. * Sets the first element URL.
  1662. */
  1663. public function first()
  1664. {
  1665. if ($this->debug > 0) {
  1666. error_log('In learnpath::first()', 0);
  1667. error_log('$this->last_item_seen '.$this->last_item_seen);
  1668. }
  1669. // Test if the last_item_seen exists and is not a dir.
  1670. if (count($this->ordered_items) == 0) {
  1671. $this->index = 0;
  1672. }
  1673. if (!empty($this->last_item_seen) &&
  1674. !empty($this->items[$this->last_item_seen]) &&
  1675. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1676. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1677. //&& !$this->items[$this->last_item_seen]->is_done()
  1678. ) {
  1679. if ($this->debug > 2) {
  1680. error_log('In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.$this->items[$this->last_item_seen]->get_type(), 0);
  1681. }
  1682. $index = -1;
  1683. foreach ($this->ordered_items as $myindex => $item_id) {
  1684. if ($item_id == $this->last_item_seen) {
  1685. $index = $myindex;
  1686. break;
  1687. }
  1688. }
  1689. if ($index == -1) {
  1690. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1691. if ($this->debug > 2) {
  1692. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1693. }
  1694. return false;
  1695. } else {
  1696. $this->last = $this->last_item_seen;
  1697. $this->current = $this->last_item_seen;
  1698. $this->index = $index;
  1699. }
  1700. } else {
  1701. if ($this->debug > 2) {
  1702. error_log('In learnpath::first() - No last item seen', 0);
  1703. }
  1704. $index = 0;
  1705. // Loop through all ordered items and stop at the first item that is
  1706. // not a directory *and* that has not been completed yet.
  1707. while (!empty($this->ordered_items[$index]) &&
  1708. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1709. (
  1710. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1711. $this->items[$this->ordered_items[$index]]->is_done() === true
  1712. ) && $index < $this->max_ordered_items) {
  1713. $index++;
  1714. }
  1715. $this->last = $this->current;
  1716. // current is
  1717. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1718. $this->index = $index;
  1719. if ($this->debug > 2) {
  1720. error_log('$index '.$index);
  1721. error_log('In learnpath::first() - No last item seen');
  1722. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1723. }
  1724. }
  1725. if ($this->debug > 2) {
  1726. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1727. }
  1728. }
  1729. /**
  1730. * Gets the information about an item in a format usable as JavaScript to update
  1731. * the JS API by just printing this content into the <head> section of the message frame.
  1732. *
  1733. * @param int $item_id
  1734. *
  1735. * @return string
  1736. */
  1737. public function get_js_info($item_id = 0)
  1738. {
  1739. if ($this->debug > 0) {
  1740. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1741. }
  1742. $info = '';
  1743. $item_id = intval($item_id);
  1744. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1745. //if item is defined, return values from DB
  1746. $oItem = $this->items[$item_id];
  1747. $info .= '<script language="javascript">';
  1748. $info .= "top.set_score(".$oItem->get_score().");\n";
  1749. $info .= "top.set_max(".$oItem->get_max().");\n";
  1750. $info .= "top.set_min(".$oItem->get_min().");\n";
  1751. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1752. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1753. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1754. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1755. $info .= "top.set_flag_synchronized();";
  1756. $info .= '</script>';
  1757. if ($this->debug > 2) {
  1758. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1759. }
  1760. return $info;
  1761. } else {
  1762. // If item_id is empty, just update to default SCORM data.
  1763. $info .= '<script language="javascript">';
  1764. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1765. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1766. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1767. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1768. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1769. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1770. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1771. $info .= "top.set_flag_synchronized();";
  1772. $info .= '</script>';
  1773. if ($this->debug > 2) {
  1774. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1775. }
  1776. return $info;
  1777. }
  1778. }
  1779. /**
  1780. * Gets the js library from the database.
  1781. *
  1782. * @return string The name of the javascript library to be used
  1783. */
  1784. public function get_js_lib()
  1785. {
  1786. $lib = '';
  1787. if (!empty($this->js_lib)) {
  1788. $lib = $this->js_lib;
  1789. }
  1790. return $lib;
  1791. }
  1792. /**
  1793. * Gets the learnpath database ID.
  1794. *
  1795. * @return int Learnpath ID in the lp table
  1796. */
  1797. public function get_id()
  1798. {
  1799. if (!empty($this->lp_id)) {
  1800. return $this->lp_id;
  1801. } else {
  1802. return 0;
  1803. }
  1804. }
  1805. /**
  1806. * Gets the last element URL.
  1807. *
  1808. * @return string URL to load into the viewer
  1809. */
  1810. public function get_last()
  1811. {
  1812. if ($this->debug > 0) {
  1813. error_log('In learnpath::get_last()', 0);
  1814. }
  1815. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1816. if (count($this->ordered_items) > 0) {
  1817. $this->index = count($this->ordered_items) - 1;
  1818. return $this->ordered_items[$this->index];
  1819. }
  1820. return false;
  1821. }
  1822. /**
  1823. * Gets the navigation bar for the learnpath display screen.
  1824. *
  1825. * @return string The HTML string to use as a navigation bar
  1826. */
  1827. public function get_navigation_bar($idBar = null, $display = null)
  1828. {
  1829. if ($this->debug > 0) {
  1830. error_log('In learnpath::get_navigation_bar()', 0);
  1831. }
  1832. if (empty($idBar)) {
  1833. $idBar = 'control-top';
  1834. }
  1835. $lpId = $this->lp_id;
  1836. $mycurrentitemid = $this->get_current_item_id();
  1837. $reportingText = get_lang('Reporting');
  1838. $previousText = get_lang('ScormPrevious');
  1839. $nextText = get_lang('ScormNext');
  1840. $fullScreenText = get_lang('ScormExitFullScreen');
  1841. $settings = api_get_configuration_value('lp_view_settings');
  1842. $display = isset($settings['display']) ? $settings['display'] : false;
  1843. $reportingIcon = '
  1844. <a class="icon-toolbar"
  1845. id="stats_link"
  1846. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1847. onclick="window.parent.API.save_asset(); return true;"
  1848. target="content_name" title="'.$reportingText.'">
  1849. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1850. </a>';
  1851. if (!empty($display)) {
  1852. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1853. if ($showReporting == false) {
  1854. $reportingIcon = '';
  1855. }
  1856. }
  1857. $previousIcon = '
  1858. <a class="icon-toolbar" id="scorm-previous" href="#"
  1859. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1860. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1861. </a>';
  1862. $nextIcon = '
  1863. <a class="icon-toolbar" id="scorm-next" href="#"
  1864. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1865. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1866. </a>';
  1867. if ($this->mode == 'fullscreen') {
  1868. $navbar = '
  1869. <span id="'.$idBar.'" class="buttons">
  1870. '.$reportingIcon.'
  1871. '.$previousIcon.'
  1872. '.$nextIcon.'
  1873. <a class="icon-toolbar" id="view-embedded"
  1874. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1875. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1876. </a>
  1877. </span>';
  1878. } else {
  1879. $navbar = '
  1880. <span id="'.$idBar.'" class="buttons text-right">
  1881. '.$reportingIcon.'
  1882. '.$previousIcon.'
  1883. '.$nextIcon.'
  1884. </span>';
  1885. }
  1886. return $navbar;
  1887. }
  1888. /**
  1889. * Gets the next resource in queue (url).
  1890. *
  1891. * @return string URL to load into the viewer
  1892. */
  1893. public function get_next_index()
  1894. {
  1895. if ($this->debug > 0) {
  1896. error_log('In learnpath::get_next_index()', 0);
  1897. }
  1898. // TODO
  1899. $index = $this->index;
  1900. $index++;
  1901. if ($this->debug > 2) {
  1902. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1903. }
  1904. while (
  1905. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1906. $index < $this->max_ordered_items
  1907. ) {
  1908. $index++;
  1909. if ($index == $this->max_ordered_items) {
  1910. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1911. return $this->index;
  1912. } else {
  1913. return $index;
  1914. }
  1915. }
  1916. }
  1917. if (empty($this->ordered_items[$index])) {
  1918. return $this->index;
  1919. }
  1920. if ($this->debug > 2) {
  1921. error_log('index is now '.$index, 0);
  1922. }
  1923. return $index;
  1924. }
  1925. /**
  1926. * Gets item_id for the next element.
  1927. *
  1928. * @return int Next item (DB) ID
  1929. */
  1930. public function get_next_item_id()
  1931. {
  1932. if ($this->debug > 0) {
  1933. error_log('In learnpath::get_next_item_id()', 0);
  1934. }
  1935. $new_index = $this->get_next_index();
  1936. if (!empty($new_index)) {
  1937. if (isset($this->ordered_items[$new_index])) {
  1938. if ($this->debug > 2) {
  1939. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1940. }
  1941. return $this->ordered_items[$new_index];
  1942. }
  1943. }
  1944. if ($this->debug > 2) {
  1945. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1946. }
  1947. return 0;
  1948. }
  1949. /**
  1950. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1951. *
  1952. * Generally, the package provided is in the form of a zip file, so the function
  1953. * has been written to test a zip file. If not a zip, the function will return the
  1954. * default return value: ''
  1955. *
  1956. * @param string the path to the file
  1957. * @param string the original name of the file
  1958. *
  1959. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1960. */
  1961. public static function get_package_type($file_path, $file_name)
  1962. {
  1963. // Get name of the zip file without the extension.
  1964. $file_info = pathinfo($file_name);
  1965. $filename = $file_info['basename']; // Name including extension.
  1966. $extension = $file_info['extension']; // Extension only.
  1967. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1968. 'dll',
  1969. 'exe',
  1970. ])) {
  1971. return 'oogie';
  1972. }
  1973. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1974. 'dll',
  1975. 'exe',
  1976. ])) {
  1977. return 'woogie';
  1978. }
  1979. $zipFile = new PclZip($file_path);
  1980. // Check the zip content (real size and file extension).
  1981. $zipContentArray = $zipFile->listContent();
  1982. $package_type = '';
  1983. $at_root = false;
  1984. $manifest = '';
  1985. $aicc_match_crs = 0;
  1986. $aicc_match_au = 0;
  1987. $aicc_match_des = 0;
  1988. $aicc_match_cst = 0;
  1989. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1990. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1991. foreach ($zipContentArray as $thisContent) {
  1992. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1993. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1994. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1995. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1996. $package_type = 'scorm';
  1997. break; // Exit the foreach loop.
  1998. } elseif (
  1999. preg_match('/aicc\//i', $thisContent['filename']) ||
  2000. in_array(
  2001. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2002. ['crs', 'au', 'des', 'cst']
  2003. )
  2004. ) {
  2005. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2006. switch ($ext) {
  2007. case 'crs':
  2008. $aicc_match_crs = 1;
  2009. break;
  2010. case 'au':
  2011. $aicc_match_au = 1;
  2012. break;
  2013. case 'des':
  2014. $aicc_match_des = 1;
  2015. break;
  2016. case 'cst':
  2017. $aicc_match_cst = 1;
  2018. break;
  2019. default:
  2020. break;
  2021. }
  2022. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2023. } else {
  2024. $package_type = '';
  2025. }
  2026. }
  2027. }
  2028. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2029. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2030. $package_type = 'aicc';
  2031. }
  2032. return $package_type;
  2033. }
  2034. /**
  2035. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2036. *
  2037. * @return string URL to load into the viewer
  2038. */
  2039. public function get_previous_index()
  2040. {
  2041. if ($this->debug > 0) {
  2042. error_log('In learnpath::get_previous_index()', 0);
  2043. }
  2044. $index = $this->index;
  2045. if (isset($this->ordered_items[$index - 1])) {
  2046. $index--;
  2047. while (isset($this->ordered_items[$index]) &&
  2048. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2049. ) {
  2050. $index--;
  2051. if ($index < 0) {
  2052. return $this->index;
  2053. }
  2054. }
  2055. } else {
  2056. if ($this->debug > 2) {
  2057. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2058. }
  2059. // There is no previous item.
  2060. }
  2061. return $index;
  2062. }
  2063. /**
  2064. * Gets item_id for the next element.
  2065. *
  2066. * @return int Previous item (DB) ID
  2067. */
  2068. public function get_previous_item_id()
  2069. {
  2070. if ($this->debug > 0) {
  2071. error_log('In learnpath::get_previous_item_id()', 0);
  2072. }
  2073. $new_index = $this->get_previous_index();
  2074. return $this->ordered_items[$new_index];
  2075. }
  2076. /**
  2077. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2078. *
  2079. * @param int $lpItemId
  2080. * @param string $autostart
  2081. *
  2082. * @return string The mediaplayer HTML
  2083. */
  2084. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2085. {
  2086. $course_id = api_get_course_int_id();
  2087. $_course = api_get_course_info();
  2088. if (empty($_course)) {
  2089. return '';
  2090. }
  2091. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2092. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2093. $lpItemId = (int) $lpItemId;
  2094. // Getting all the information about the item.
  2095. $sql = "SELECT * FROM $tbl_lp_item as lpi
  2096. INNER JOIN $tbl_lp_item_view as lp_view
  2097. ON (lpi.iid = lp_view.lp_item_id)
  2098. WHERE
  2099. lpi.iid = $lpItemId AND
  2100. lp_view.c_id = $course_id";
  2101. $result = Database::query($sql);
  2102. $row = Database::fetch_assoc($result);
  2103. $output = '';
  2104. if (!empty($row['audio'])) {
  2105. $list = $_SESSION['oLP']->get_toc();
  2106. $type_quiz = false;
  2107. foreach ($list as $toc) {
  2108. if ($toc['id'] == $_SESSION['oLP']->current && ($toc['type'] == 'quiz')) {
  2109. $type_quiz = true;
  2110. }
  2111. }
  2112. if ($type_quiz) {
  2113. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2114. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2115. } else {
  2116. $autostart_audio = $autostart;
  2117. }
  2118. } else {
  2119. $autostart_audio = 'true';
  2120. }
  2121. $courseInfo = api_get_course_info();
  2122. $audio = $row['audio'];
  2123. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2124. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2125. if (!file_exists($file)) {
  2126. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2127. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2128. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2129. }
  2130. $player = Display::getMediaPlayer(
  2131. $file,
  2132. [
  2133. 'id' => 'lp_audio_media_player',
  2134. 'url' => $url,
  2135. 'autoplay' => $autostart_audio,
  2136. 'width' => '100%',
  2137. ]
  2138. );
  2139. // The mp3 player.
  2140. $output = '<div id="container">';
  2141. $output .= $player;
  2142. $output .= '</div>';
  2143. }
  2144. return $output;
  2145. }
  2146. /**
  2147. * @param int $studentId
  2148. * @param int $prerequisite
  2149. * @param array $courseInfo
  2150. * @param int $sessionId
  2151. *
  2152. * @return bool
  2153. */
  2154. public static function isBlockedByPrerequisite(
  2155. $studentId,
  2156. $prerequisite,
  2157. $courseInfo,
  2158. $sessionId
  2159. ) {
  2160. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2161. if ($allow) {
  2162. if (api_is_allowed_to_edit() || api_is_platform_admin() || api_is_drh()) {
  2163. return false;
  2164. }
  2165. }
  2166. $isBlocked = false;
  2167. if (!empty($prerequisite)) {
  2168. $progress = self::getProgress(
  2169. $prerequisite,
  2170. $studentId,
  2171. $courseInfo['real_id'],
  2172. $sessionId
  2173. );
  2174. if ($progress < 100) {
  2175. $isBlocked = true;
  2176. }
  2177. }
  2178. return $isBlocked;
  2179. }
  2180. /**
  2181. * Checks if the learning path is visible for student after the progress
  2182. * of its prerequisite is completed, considering the time availability and
  2183. * the LP visibility.
  2184. *
  2185. * @param int $lp_id
  2186. * @param int $student_id
  2187. * @param string Course code (optional)
  2188. * @param int $sessionId
  2189. *
  2190. * @return bool
  2191. */
  2192. public static function is_lp_visible_for_student(
  2193. $lp_id,
  2194. $student_id,
  2195. $courseCode = null,
  2196. $sessionId = 0
  2197. ) {
  2198. $courseInfo = api_get_course_info($courseCode);
  2199. $lp_id = (int) $lp_id;
  2200. $sessionId = (int) $sessionId;
  2201. if (empty($courseInfo)) {
  2202. return false;
  2203. }
  2204. if (empty($sessionId)) {
  2205. $sessionId = api_get_session_id();
  2206. }
  2207. $itemInfo = api_get_item_property_info(
  2208. $courseInfo['real_id'],
  2209. TOOL_LEARNPATH,
  2210. $lp_id,
  2211. $sessionId
  2212. );
  2213. // If the item was deleted.
  2214. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2215. return false;
  2216. }
  2217. // @todo remove this query and load the row info as a parameter
  2218. $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
  2219. // Get current prerequisite
  2220. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2221. FROM $tbl_learnpath
  2222. WHERE iid = $lp_id";
  2223. $rs = Database::query($sql);
  2224. $now = time();
  2225. if (Database::num_rows($rs) > 0) {
  2226. $row = Database::fetch_array($rs, 'ASSOC');
  2227. $prerequisite = $row['prerequisite'];
  2228. $is_visible = true;
  2229. $isBlocked = self::isBlockedByPrerequisite(
  2230. $student_id,
  2231. $prerequisite,
  2232. $courseInfo,
  2233. $sessionId
  2234. );
  2235. if ($isBlocked) {
  2236. $is_visible = false;
  2237. }
  2238. // Also check the time availability of the LP
  2239. if ($is_visible) {
  2240. // Adding visibility restrictions
  2241. if (!empty($row['publicated_on'])) {
  2242. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2243. $is_visible = false;
  2244. }
  2245. }
  2246. // Blocking empty start times see BT#2800
  2247. global $_custom;
  2248. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2249. $_custom['lps_hidden_when_no_start_date']
  2250. ) {
  2251. if (empty($row['publicated_on'])) {
  2252. $is_visible = false;
  2253. }
  2254. }
  2255. if (!empty($row['expired_on'])) {
  2256. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2257. $is_visible = false;
  2258. }
  2259. }
  2260. }
  2261. // Check if the subscription users/group to a LP is ON
  2262. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1) {
  2263. // Try group
  2264. $is_visible = false;
  2265. // Checking only the user visibility
  2266. $userVisibility = api_get_item_visibility(
  2267. $courseInfo,
  2268. 'learnpath',
  2269. $row['id'],
  2270. $sessionId,
  2271. $student_id,
  2272. 'LearnpathSubscription'
  2273. );
  2274. if ($userVisibility == 1) {
  2275. $is_visible = true;
  2276. } else {
  2277. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2278. if (!empty($userGroups)) {
  2279. foreach ($userGroups as $groupInfo) {
  2280. $groupId = $groupInfo['iid'];
  2281. $userVisibility = api_get_item_visibility(
  2282. $courseInfo,
  2283. 'learnpath',
  2284. $row['id'],
  2285. $sessionId,
  2286. null,
  2287. 'LearnpathSubscription',
  2288. $groupId
  2289. );
  2290. if ($userVisibility == 1) {
  2291. $is_visible = true;
  2292. break;
  2293. }
  2294. }
  2295. }
  2296. }
  2297. }
  2298. return $is_visible;
  2299. }
  2300. return false;
  2301. }
  2302. /**
  2303. * @param int $lpId
  2304. * @param int $userId
  2305. * @param int $courseId
  2306. * @param int $sessionId
  2307. *
  2308. * @return int
  2309. */
  2310. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2311. {
  2312. $lpId = intval($lpId);
  2313. $userId = intval($userId);
  2314. $courseId = intval($courseId);
  2315. $sessionId = intval($sessionId);
  2316. $progress = 0;
  2317. $sessionCondition = api_get_session_condition($sessionId);
  2318. $table = Database::get_course_table(TABLE_LP_VIEW);
  2319. $sql = "SELECT * FROM $table
  2320. WHERE
  2321. c_id = $courseId AND
  2322. lp_id = $lpId AND
  2323. user_id = $userId $sessionCondition ";
  2324. $res = Database::query($sql);
  2325. if (Database::num_rows($res) > 0) {
  2326. $row = Database:: fetch_array($res);
  2327. $progress = $row['progress'];
  2328. }
  2329. return (int) $progress;
  2330. }
  2331. /**
  2332. * Displays a progress bar
  2333. * completed so far.
  2334. *
  2335. * @param int $percentage Progress value to display
  2336. * @param string $text_add Text to display near the progress value
  2337. *
  2338. * @return string HTML string containing the progress bar
  2339. */
  2340. public static function get_progress_bar($percentage = -1, $text_add = '')
  2341. {
  2342. $text = $percentage.$text_add;
  2343. $output = '<div class="progress">
  2344. <div id="progress_bar_value"
  2345. class="progress-bar progress-bar-success" role="progressbar"
  2346. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2347. '.$text.'
  2348. </div>
  2349. </div>';
  2350. return $output;
  2351. }
  2352. /**
  2353. * @param string $mode can be '%' or 'abs'
  2354. * otherwise this value will be used $this->progress_bar_mode
  2355. *
  2356. * @return string
  2357. */
  2358. public function getProgressBar($mode = null)
  2359. {
  2360. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2361. return self::get_progress_bar($percentage, $text_add);
  2362. }
  2363. /**
  2364. * Gets the progress bar info to display inside the progress bar.
  2365. * Also used by scorm_api.php.
  2366. *
  2367. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2368. * we display a number of completed elements per total elements
  2369. * @param int $add Additional steps to fake as completed
  2370. *
  2371. * @return array Percentage or number and symbol (% or /xx)
  2372. */
  2373. public function get_progress_bar_text($mode = '', $add = 0)
  2374. {
  2375. if ($this->debug > 0) {
  2376. error_log('In learnpath::get_progress_bar_text()', 0);
  2377. }
  2378. if (empty($mode)) {
  2379. $mode = $this->progress_bar_mode;
  2380. }
  2381. $total_items = $this->getTotalItemsCountWithoutDirs();
  2382. if ($this->debug > 2) {
  2383. error_log('Total items available in this learnpath: '.$total_items, 0);
  2384. }
  2385. $completeItems = $this->get_complete_items_count();
  2386. if ($this->debug > 2) {
  2387. error_log('Items completed so far: '.$completeItems, 0);
  2388. }
  2389. if ($add != 0) {
  2390. $completeItems += $add;
  2391. if ($this->debug > 2) {
  2392. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2393. }
  2394. }
  2395. $text = '';
  2396. if ($completeItems > $total_items) {
  2397. $completeItems = $total_items;
  2398. }
  2399. $percentage = 0;
  2400. if ($mode == '%') {
  2401. if ($total_items > 0) {
  2402. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2403. } else {
  2404. $percentage = 0;
  2405. }
  2406. $percentage = number_format($percentage, 0);
  2407. $text = '%';
  2408. } elseif ($mode == 'abs') {
  2409. $percentage = $completeItems;
  2410. $text = '/'.$total_items;
  2411. }
  2412. return [
  2413. $percentage,
  2414. $text,
  2415. ];
  2416. }
  2417. /**
  2418. * Gets the progress bar mode.
  2419. *
  2420. * @return string The progress bar mode attribute
  2421. */
  2422. public function get_progress_bar_mode()
  2423. {
  2424. if ($this->debug > 0) {
  2425. error_log('In learnpath::get_progress_bar_mode()', 0);
  2426. }
  2427. if (!empty($this->progress_bar_mode)) {
  2428. return $this->progress_bar_mode;
  2429. } else {
  2430. return '%';
  2431. }
  2432. }
  2433. /**
  2434. * Gets the learnpath theme (remote or local).
  2435. *
  2436. * @return string Learnpath theme
  2437. */
  2438. public function get_theme()
  2439. {
  2440. if ($this->debug > 0) {
  2441. error_log('In learnpath::get_theme()', 0);
  2442. }
  2443. if (!empty($this->theme)) {
  2444. return $this->theme;
  2445. } else {
  2446. return '';
  2447. }
  2448. }
  2449. /**
  2450. * Gets the learnpath session id.
  2451. *
  2452. * @return int
  2453. */
  2454. public function get_lp_session_id()
  2455. {
  2456. if ($this->debug > 0) {
  2457. error_log('In learnpath::get_lp_session_id()', 0);
  2458. }
  2459. if (!empty($this->lp_session_id)) {
  2460. return (int) $this->lp_session_id;
  2461. } else {
  2462. return 0;
  2463. }
  2464. }
  2465. /**
  2466. * Gets the learnpath image.
  2467. *
  2468. * @return string Web URL of the LP image
  2469. */
  2470. public function get_preview_image()
  2471. {
  2472. if ($this->debug > 0) {
  2473. error_log('In learnpath::get_preview_image()', 0);
  2474. }
  2475. if (!empty($this->preview_image)) {
  2476. return $this->preview_image;
  2477. } else {
  2478. return '';
  2479. }
  2480. }
  2481. /**
  2482. * @param string $size
  2483. * @param string $path_type
  2484. *
  2485. * @return bool|string
  2486. */
  2487. public function get_preview_image_path($size = null, $path_type = 'web')
  2488. {
  2489. $preview_image = $this->get_preview_image();
  2490. if (isset($preview_image) && !empty($preview_image)) {
  2491. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2492. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2493. if (isset($size)) {
  2494. $info = pathinfo($preview_image);
  2495. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2496. if (file_exists($image_sys_path.$image_custom_size)) {
  2497. if ($path_type == 'web') {
  2498. return $image_path.$image_custom_size;
  2499. } else {
  2500. return $image_sys_path.$image_custom_size;
  2501. }
  2502. }
  2503. } else {
  2504. if ($path_type == 'web') {
  2505. return $image_path.$preview_image;
  2506. } else {
  2507. return $image_sys_path.$preview_image;
  2508. }
  2509. }
  2510. }
  2511. return false;
  2512. }
  2513. /**
  2514. * Gets the learnpath author.
  2515. *
  2516. * @return string LP's author
  2517. */
  2518. public function get_author()
  2519. {
  2520. if ($this->debug > 0) {
  2521. error_log('In learnpath::get_author()', 0);
  2522. }
  2523. if (!empty($this->author)) {
  2524. return $this->author;
  2525. } else {
  2526. return '';
  2527. }
  2528. }
  2529. /**
  2530. * Gets hide table of contents.
  2531. *
  2532. * @return int
  2533. */
  2534. public function getHideTableOfContents()
  2535. {
  2536. return (int) $this->hide_toc_frame;
  2537. }
  2538. /**
  2539. * Generate a new prerequisites string for a given item. If this item was a sco and
  2540. * its prerequisites were strings (instead of IDs), then transform those strings into
  2541. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2542. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2543. * same rule as the scorm_export() method.
  2544. *
  2545. * @param int Item ID
  2546. *
  2547. * @return string Prerequisites string ready for the export as SCORM
  2548. */
  2549. public function get_scorm_prereq_string($item_id)
  2550. {
  2551. if ($this->debug > 0) {
  2552. error_log('In learnpath::get_scorm_prereq_string()');
  2553. }
  2554. if (!is_object($this->items[$item_id])) {
  2555. return false;
  2556. }
  2557. /** @var learnpathItem $oItem */
  2558. $oItem = $this->items[$item_id];
  2559. $prereq = $oItem->get_prereq_string();
  2560. if (empty($prereq)) {
  2561. return '';
  2562. }
  2563. if (preg_match('/^\d+$/', $prereq) && is_object($this->items[$prereq])) {
  2564. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2565. // then simply return it (with the ITEM_ prefix).
  2566. //return 'ITEM_' . $prereq;
  2567. return $this->items[$prereq]->ref;
  2568. } else {
  2569. if (isset($this->refs_list[$prereq])) {
  2570. // It's a simple string item from which the ID can be found in the refs list,
  2571. // so we can transform it directly to an ID for export.
  2572. return $this->items[$this->refs_list[$prereq]]->ref;
  2573. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2574. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2575. } else {
  2576. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2577. // and replace them, one by one, by the internal IDs (chamilo db)
  2578. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2579. // by a space as well.
  2580. $find = [
  2581. '&',
  2582. '|',
  2583. '~',
  2584. '=',
  2585. '<>',
  2586. '{',
  2587. '}',
  2588. '*',
  2589. '(',
  2590. ')',
  2591. ];
  2592. $replace = [
  2593. ' ',
  2594. ' ',
  2595. ' ',
  2596. ' ',
  2597. ' ',
  2598. ' ',
  2599. ' ',
  2600. ' ',
  2601. ' ',
  2602. ' ',
  2603. ];
  2604. $prereq_mod = str_replace($find, $replace, $prereq);
  2605. $ids = explode(' ', $prereq_mod);
  2606. foreach ($ids as $id) {
  2607. $id = trim($id);
  2608. if (isset($this->refs_list[$id])) {
  2609. $prereq = preg_replace(
  2610. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2611. 'ITEM_'.$this->refs_list[$id],
  2612. $prereq
  2613. );
  2614. }
  2615. }
  2616. return $prereq;
  2617. }
  2618. }
  2619. }
  2620. /**
  2621. * Returns the XML DOM document's node.
  2622. *
  2623. * @param resource Reference to a list of objects to search for the given ITEM_*
  2624. * @param string The identifier to look for
  2625. *
  2626. * @return mixed The reference to the element found with that identifier. False if not found
  2627. */
  2628. public function get_scorm_xml_node(&$children, $id)
  2629. {
  2630. for ($i = 0; $i < $children->length; $i++) {
  2631. $item_temp = $children->item($i);
  2632. if ($item_temp->nodeName == 'item') {
  2633. if ($item_temp->getAttribute('identifier') == $id) {
  2634. return $item_temp;
  2635. }
  2636. }
  2637. $subchildren = $item_temp->childNodes;
  2638. if ($subchildren && $subchildren->length > 0) {
  2639. $val = $this->get_scorm_xml_node($subchildren, $id);
  2640. if (is_object($val)) {
  2641. return $val;
  2642. }
  2643. }
  2644. }
  2645. return false;
  2646. }
  2647. /**
  2648. * Gets the status list for all LP's items.
  2649. *
  2650. * @return array Array of [index] => [item ID => current status]
  2651. */
  2652. public function get_items_status_list()
  2653. {
  2654. if ($this->debug > 0) {
  2655. error_log('In learnpath::get_items_status_list()', 0);
  2656. }
  2657. $list = [];
  2658. foreach ($this->ordered_items as $item_id) {
  2659. $list[] = [
  2660. $item_id => $this->items[$item_id]->get_status(),
  2661. ];
  2662. }
  2663. return $list;
  2664. }
  2665. /**
  2666. * Return the number of interactions for the given learnpath Item View ID.
  2667. * This method can be used as static.
  2668. *
  2669. * @param int Item View ID
  2670. * @param int course id
  2671. *
  2672. * @return int Number of interactions
  2673. */
  2674. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2675. {
  2676. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2677. $lp_iv_id = intval($lp_iv_id);
  2678. $course_id = intval($course_id);
  2679. $sql = "SELECT count(*) FROM $table
  2680. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2681. $res = Database::query($sql);
  2682. $num = 0;
  2683. if (Database::num_rows($res)) {
  2684. $row = Database::fetch_array($res);
  2685. $num = $row[0];
  2686. }
  2687. return $num;
  2688. }
  2689. /**
  2690. * Return the interactions as an array for the given lp_iv_id.
  2691. * This method can be used as static.
  2692. *
  2693. * @param int Learnpath Item View ID
  2694. *
  2695. * @return array
  2696. *
  2697. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2698. */
  2699. public static function get_iv_interactions_array($lp_iv_id)
  2700. {
  2701. $course_id = api_get_course_int_id();
  2702. $list = [];
  2703. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2704. if (empty($lp_iv_id)) {
  2705. return [];
  2706. }
  2707. $sql = "SELECT * FROM $table
  2708. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2709. ORDER BY order_id ASC";
  2710. $res = Database::query($sql);
  2711. $num = Database::num_rows($res);
  2712. if ($num > 0) {
  2713. $list[] = [
  2714. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2715. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2716. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2717. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2718. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2719. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2720. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2721. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2722. ];
  2723. while ($row = Database::fetch_array($res)) {
  2724. $list[] = [
  2725. 'order_id' => ($row['order_id'] + 1),
  2726. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2727. 'type' => $row['interaction_type'],
  2728. 'time' => $row['completion_time'],
  2729. //'correct_responses' => $row['correct_responses'],
  2730. 'correct_responses' => '', // Hide correct responses from students.
  2731. 'student_response' => $row['student_response'],
  2732. 'result' => $row['result'],
  2733. 'latency' => $row['latency'],
  2734. ];
  2735. }
  2736. }
  2737. return $list;
  2738. }
  2739. /**
  2740. * Return the number of objectives for the given learnpath Item View ID.
  2741. * This method can be used as static.
  2742. *
  2743. * @param int Item View ID
  2744. *
  2745. * @return int Number of objectives
  2746. */
  2747. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2748. {
  2749. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2750. $course_id = intval($course_id);
  2751. $lp_iv_id = intval($lp_iv_id);
  2752. $sql = "SELECT count(*) FROM $table
  2753. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2754. //@todo seems that this always returns 0
  2755. $res = Database::query($sql);
  2756. $num = 0;
  2757. if (Database::num_rows($res)) {
  2758. $row = Database::fetch_array($res);
  2759. $num = $row[0];
  2760. }
  2761. return $num;
  2762. }
  2763. /**
  2764. * Return the objectives as an array for the given lp_iv_id.
  2765. * This method can be used as static.
  2766. *
  2767. * @param int $lpItemViewId Learnpath Item View ID
  2768. *
  2769. * @return array
  2770. *
  2771. * @todo Translate labels
  2772. */
  2773. public static function get_iv_objectives_array($lpItemViewId = 0)
  2774. {
  2775. $course_id = api_get_course_int_id();
  2776. $lpItemViewId = (int) $lpItemViewId;
  2777. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2778. $sql = "SELECT * FROM $table
  2779. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2780. ORDER BY order_id ASC";
  2781. $res = Database::query($sql);
  2782. $num = Database::num_rows($res);
  2783. $list = [];
  2784. if ($num > 0) {
  2785. $list[] = [
  2786. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2787. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2788. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2789. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2790. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2791. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2792. ];
  2793. while ($row = Database::fetch_array($res)) {
  2794. $list[] = [
  2795. 'order_id' => ($row['order_id'] + 1),
  2796. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2797. 'score_raw' => $row['score_raw'],
  2798. 'score_max' => $row['score_max'],
  2799. 'score_min' => $row['score_min'],
  2800. 'status' => $row['status'],
  2801. ];
  2802. }
  2803. }
  2804. return $list;
  2805. }
  2806. /**
  2807. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2808. * used by get_html_toc() to be ready to display.
  2809. *
  2810. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2811. */
  2812. public function get_toc()
  2813. {
  2814. if ($this->debug > 0) {
  2815. error_log('learnpath::get_toc()', 0);
  2816. }
  2817. $toc = [];
  2818. foreach ($this->ordered_items as $item_id) {
  2819. if ($this->debug > 2) {
  2820. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2821. }
  2822. // TODO: Change this link generation and use new function instead.
  2823. $toc[] = [
  2824. 'id' => $item_id,
  2825. 'title' => $this->items[$item_id]->get_title(),
  2826. 'status' => $this->items[$item_id]->get_status(),
  2827. 'level' => $this->items[$item_id]->get_level(),
  2828. 'type' => $this->items[$item_id]->get_type(),
  2829. 'description' => $this->items[$item_id]->get_description(),
  2830. 'path' => $this->items[$item_id]->get_path(),
  2831. 'parent' => $this->items[$item_id]->get_parent(),
  2832. ];
  2833. }
  2834. if ($this->debug > 2) {
  2835. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2836. }
  2837. return $toc;
  2838. }
  2839. /**
  2840. * Generate and return the table of contents for this learnpath. The JS
  2841. * table returned is used inside of scorm_api.php.
  2842. *
  2843. * @param string $varname
  2844. *
  2845. * @return string A JS array variable construction
  2846. */
  2847. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2848. {
  2849. if ($this->debug > 0) {
  2850. error_log('In learnpath::get_items_details_as_js()', 0);
  2851. }
  2852. $toc = $varname.' = new Array();';
  2853. foreach ($this->ordered_items as $item_id) {
  2854. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2855. }
  2856. if ($this->debug > 2) {
  2857. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2858. }
  2859. return $toc;
  2860. }
  2861. /**
  2862. * Gets the learning path type.
  2863. *
  2864. * @param bool Return the name? If false, return the ID. Default is false.
  2865. *
  2866. * @return mixed Type ID or name, depending on the parameter
  2867. */
  2868. public function get_type($get_name = false)
  2869. {
  2870. $res = false;
  2871. if ($this->debug > 0) {
  2872. error_log('In learnpath::get_type()', 0);
  2873. }
  2874. if (!empty($this->type) && (!$get_name)) {
  2875. $res = $this->type;
  2876. }
  2877. if ($this->debug > 2) {
  2878. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2879. }
  2880. return $res;
  2881. }
  2882. /**
  2883. * Gets the learning path type as static method.
  2884. *
  2885. * @param int $lp_id
  2886. *
  2887. * @return mixed Type ID or name, depending on the parameter
  2888. */
  2889. public static function get_type_static($lp_id = 0)
  2890. {
  2891. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2892. $lp_id = intval($lp_id);
  2893. $sql = "SELECT lp_type FROM $tbl_lp
  2894. WHERE iid = $lp_id";
  2895. $res = Database::query($sql);
  2896. if ($res === false) {
  2897. return null;
  2898. }
  2899. if (Database::num_rows($res) <= 0) {
  2900. return null;
  2901. }
  2902. $row = Database::fetch_array($res);
  2903. return $row['lp_type'];
  2904. }
  2905. /**
  2906. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2907. * This method can be used as abstract and is recursive.
  2908. *
  2909. * @param int Learnpath ID
  2910. * @param int Parent ID of the items to look for
  2911. *
  2912. * @return array Ordered list of item IDs (empty array on error)
  2913. */
  2914. public static function get_flat_ordered_items_list($lp, $parent = 0, $course_id = 0)
  2915. {
  2916. if (empty($course_id)) {
  2917. $course_id = api_get_course_int_id();
  2918. } else {
  2919. $course_id = intval($course_id);
  2920. }
  2921. $list = [];
  2922. if (empty($lp)) {
  2923. return $list;
  2924. }
  2925. $lp = intval($lp);
  2926. $parent = intval($parent);
  2927. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2928. $sql = "SELECT iid FROM $tbl_lp_item
  2929. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2930. ORDER BY display_order";
  2931. $res = Database::query($sql);
  2932. while ($row = Database::fetch_array($res)) {
  2933. $sublist = self::get_flat_ordered_items_list(
  2934. $lp,
  2935. $row['iid'],
  2936. $course_id
  2937. );
  2938. $list[] = $row['iid'];
  2939. foreach ($sublist as $item) {
  2940. $list[] = $item;
  2941. }
  2942. }
  2943. return $list;
  2944. }
  2945. /**
  2946. * @return array
  2947. */
  2948. public static function getChapterTypes()
  2949. {
  2950. return [
  2951. 'dir',
  2952. ];
  2953. }
  2954. /**
  2955. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2956. *
  2957. * @return string HTML TOC ready to display
  2958. */
  2959. public function getParentToc($tree)
  2960. {
  2961. if ($this->debug > 0) {
  2962. error_log('In learnpath::get_html_toc()', 0);
  2963. }
  2964. if (empty($tree)) {
  2965. $tree = $this->get_toc();
  2966. }
  2967. $dirTypes = self::getChapterTypes();
  2968. $myCurrentId = $this->get_current_item_id();
  2969. $listParent = [];
  2970. $listChildren = [];
  2971. $listNotParent = [];
  2972. $list = [];
  2973. foreach ($tree as $subtree) {
  2974. if (in_array($subtree['type'], $dirTypes)) {
  2975. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2976. $subtree['children'] = $listChildren;
  2977. if (!empty($subtree['children'])) {
  2978. foreach ($subtree['children'] as $subItem) {
  2979. if ($subItem['id'] == $this->current) {
  2980. $subtree['parent_current'] = 'in';
  2981. $subtree['current'] = 'on';
  2982. }
  2983. }
  2984. }
  2985. $listParent[] = $subtree;
  2986. }
  2987. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2988. $classStatus = [
  2989. 'not attempted' => 'scorm_not_attempted',
  2990. 'incomplete' => 'scorm_not_attempted',
  2991. 'failed' => 'scorm_failed',
  2992. 'completed' => 'scorm_completed',
  2993. 'passed' => 'scorm_completed',
  2994. 'succeeded' => 'scorm_completed',
  2995. 'browsed' => 'scorm_completed',
  2996. ];
  2997. if (isset($classStatus[$subtree['status']])) {
  2998. $cssStatus = $classStatus[$subtree['status']];
  2999. }
  3000. $title = Security::remove_XSS($subtree['title']);
  3001. unset($subtree['title']);
  3002. if (empty($title)) {
  3003. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3004. }
  3005. $classStyle = null;
  3006. if ($subtree['id'] == $this->current) {
  3007. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3008. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3009. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3010. }
  3011. $subtree['title'] = $title;
  3012. $subtree['class'] = $cssStatus.' '.$classStyle;
  3013. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3014. $subtree['current_id'] = $myCurrentId;
  3015. $listNotParent[] = $subtree;
  3016. }
  3017. }
  3018. $list['are_parents'] = $listParent;
  3019. $list['not_parents'] = $listNotParent;
  3020. return $list;
  3021. }
  3022. /**
  3023. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3024. *
  3025. * @return string HTML TOC ready to display
  3026. */
  3027. public function getChildrenToc($tree, $id, $parent = true)
  3028. {
  3029. if ($this->debug > 0) {
  3030. error_log('In learnpath::get_html_toc()', 0);
  3031. }
  3032. if (empty($tree)) {
  3033. $tree = $this->get_toc();
  3034. }
  3035. $dirTypes = self::getChapterTypes();
  3036. $mycurrentitemid = $this->get_current_item_id();
  3037. $list = [];
  3038. $classStatus = [
  3039. 'not attempted' => 'scorm_not_attempted',
  3040. 'incomplete' => 'scorm_not_attempted',
  3041. 'failed' => 'scorm_failed',
  3042. 'completed' => 'scorm_completed',
  3043. 'passed' => 'scorm_completed',
  3044. 'succeeded' => 'scorm_completed',
  3045. 'browsed' => 'scorm_completed',
  3046. ];
  3047. foreach ($tree as $subtree) {
  3048. $subtree['tree'] = null;
  3049. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3050. if ($subtree['id'] == $this->current) {
  3051. $subtree['current'] = 'active';
  3052. } else {
  3053. $subtree['current'] = null;
  3054. }
  3055. if (isset($classStatus[$subtree['status']])) {
  3056. $cssStatus = $classStatus[$subtree['status']];
  3057. }
  3058. $title = Security::remove_XSS($subtree['title']);
  3059. unset($subtree['title']);
  3060. if (empty($title)) {
  3061. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3062. }
  3063. $classStyle = null;
  3064. if ($subtree['id'] == $this->current) {
  3065. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3066. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3067. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3068. }
  3069. if (in_array($subtree['type'], $dirTypes)) {
  3070. $subtree['title'] = stripslashes($title);
  3071. } else {
  3072. $subtree['title'] = $title;
  3073. $subtree['class'] = $cssStatus.' '.$classStyle;
  3074. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3075. $subtree['current_id'] = $mycurrentitemid;
  3076. }
  3077. $list[] = $subtree;
  3078. }
  3079. }
  3080. return $list;
  3081. }
  3082. /**
  3083. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3084. *
  3085. * @param array $toc_list
  3086. *
  3087. * @return string HTML TOC ready to display
  3088. */
  3089. public function getListArrayToc($toc_list = [])
  3090. {
  3091. if ($this->debug > 0) {
  3092. error_log('In learnpath::get_html_toc()', 0);
  3093. }
  3094. if (empty($toc_list)) {
  3095. $toc_list = $this->get_toc();
  3096. }
  3097. // Temporary variables.
  3098. $mycurrentitemid = $this->get_current_item_id();
  3099. $list = [];
  3100. $arrayList = [];
  3101. $classStatus = [
  3102. 'not attempted' => 'scorm_not_attempted',
  3103. 'incomplete' => 'scorm_not_attempted',
  3104. 'failed' => 'scorm_failed',
  3105. 'completed' => 'scorm_completed',
  3106. 'passed' => 'scorm_completed',
  3107. 'succeeded' => 'scorm_completed',
  3108. 'browsed' => 'scorm_completed',
  3109. ];
  3110. foreach ($toc_list as $item) {
  3111. $list['id'] = $item['id'];
  3112. $list['status'] = $item['status'];
  3113. $cssStatus = null;
  3114. if (isset($classStatus[$item['status']])) {
  3115. $cssStatus = $classStatus[$item['status']];
  3116. }
  3117. $classStyle = ' ';
  3118. $dirTypes = self::getChapterTypes();
  3119. if (in_array($item['type'], $dirTypes)) {
  3120. $classStyle = 'scorm_item_section ';
  3121. }
  3122. if ($item['id'] == $this->current) {
  3123. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3124. } elseif (!in_array($item['type'], $dirTypes)) {
  3125. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3126. }
  3127. $title = $item['title'];
  3128. if (empty($title)) {
  3129. $title = self::rl_get_resource_name(
  3130. api_get_course_id(),
  3131. $this->get_id(),
  3132. $item['id']
  3133. );
  3134. }
  3135. $title = Security::remove_XSS($item['title']);
  3136. if (empty($item['description'])) {
  3137. $list['description'] = $title;
  3138. } else {
  3139. $list['description'] = $item['description'];
  3140. }
  3141. $list['class'] = $classStyle.' '.$cssStatus;
  3142. $list['level'] = $item['level'];
  3143. $list['type'] = $item['type'];
  3144. if (in_array($item['type'], $dirTypes)) {
  3145. $list['css_level'] = 'level_'.$item['level'];
  3146. } else {
  3147. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.learnpath::format_scorm_type_item($item['type']);
  3148. }
  3149. if (in_array($item['type'], $dirTypes)) {
  3150. $list['title'] = stripslashes($title);
  3151. } else {
  3152. $list['title'] = stripslashes($title);
  3153. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3154. $list['current_id'] = $mycurrentitemid;
  3155. }
  3156. $arrayList[] = $list;
  3157. }
  3158. return $arrayList;
  3159. }
  3160. /**
  3161. * Returns an HTML-formatted string ready to display with teacher buttons
  3162. * in LP view menu.
  3163. *
  3164. * @return string HTML TOC ready to display
  3165. */
  3166. public function get_teacher_toc_buttons()
  3167. {
  3168. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3169. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3170. $html = '';
  3171. if ($isAllow && $hideIcons == false) {
  3172. if ($this->get_lp_session_id() == api_get_session_id()) {
  3173. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3174. $html .= '<div class="btn-group">';
  3175. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=build&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3176. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3177. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=add_item&type=step&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3178. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3179. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3180. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3181. $html .= '</div>';
  3182. $html .= '</div>';
  3183. }
  3184. }
  3185. return $html;
  3186. }
  3187. /**
  3188. * Gets the learnpath maker name - generally the editor's name.
  3189. *
  3190. * @return string Learnpath maker name
  3191. */
  3192. public function get_maker()
  3193. {
  3194. if ($this->debug > 0) {
  3195. error_log('In learnpath::get_maker()', 0);
  3196. }
  3197. if (!empty($this->maker)) {
  3198. return $this->maker;
  3199. } else {
  3200. return '';
  3201. }
  3202. }
  3203. /**
  3204. * Gets the learnpath name/title.
  3205. *
  3206. * @return string Learnpath name/title
  3207. */
  3208. public function get_name()
  3209. {
  3210. if ($this->debug > 0) {
  3211. error_log('In learnpath::get_name()', 0);
  3212. }
  3213. if (!empty($this->name)) {
  3214. return $this->name;
  3215. } else {
  3216. return 'N/A';
  3217. }
  3218. }
  3219. /**
  3220. * Gets a link to the resource from the present location, depending on item ID.
  3221. *
  3222. * @param string $type Type of link expected
  3223. * @param int $item_id Learnpath item ID
  3224. *
  3225. * @return string $provided_toc Link to the lp_item resource
  3226. */
  3227. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3228. {
  3229. $course_id = $this->get_course_int_id();
  3230. if ($this->debug > 0) {
  3231. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3232. }
  3233. if (empty($item_id)) {
  3234. if ($this->debug > 2) {
  3235. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3236. error_log('using current: '.$this->get_current_item_id(), 0);
  3237. }
  3238. $item_id = $this->get_current_item_id();
  3239. }
  3240. if (empty($item_id)) {
  3241. if ($this->debug > 2) {
  3242. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3243. }
  3244. //still empty, this means there was no item_id given and we are not in an object context or
  3245. //the object property is empty, return empty link
  3246. $this->first();
  3247. return '';
  3248. }
  3249. $file = '';
  3250. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3251. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3252. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3253. $item_id = intval($item_id);
  3254. $sql = "SELECT
  3255. l.lp_type as ltype,
  3256. l.path as lpath,
  3257. li.item_type as litype,
  3258. li.path as lipath,
  3259. li.parameters as liparams
  3260. FROM $lp_table l
  3261. INNER JOIN $lp_item_table li
  3262. ON (li.lp_id = l.iid)
  3263. WHERE
  3264. li.iid = $item_id
  3265. ";
  3266. if ($this->debug > 2) {
  3267. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3268. }
  3269. $res = Database::query($sql);
  3270. if (Database::num_rows($res) > 0) {
  3271. $row = Database::fetch_array($res);
  3272. $lp_type = $row['ltype'];
  3273. $lp_path = $row['lpath'];
  3274. $lp_item_type = $row['litype'];
  3275. $lp_item_path = $row['lipath'];
  3276. $lp_item_params = $row['liparams'];
  3277. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3278. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3279. }
  3280. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3281. if ($type == 'http') {
  3282. //web path
  3283. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3284. } else {
  3285. $course_path = $sys_course_path; //system path
  3286. }
  3287. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3288. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3289. if (in_array(
  3290. $lp_item_type,
  3291. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3292. )
  3293. ) {
  3294. $lp_type = 1;
  3295. }
  3296. if ($this->debug > 2) {
  3297. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3298. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3299. }
  3300. // Now go through the specific cases to get the end of the path
  3301. // @todo Use constants instead of int values.
  3302. switch ($lp_type) {
  3303. case 1:
  3304. $file = self::rl_get_resource_link_for_learnpath(
  3305. $course_id,
  3306. $this->get_id(),
  3307. $item_id,
  3308. $this->get_view_id()
  3309. );
  3310. if ($this->debug > 0) {
  3311. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3312. }
  3313. switch ($lp_item_type) {
  3314. case 'dir':
  3315. $file = 'lp_content.php?type=dir';
  3316. break;
  3317. case 'link':
  3318. if (Link::is_youtube_link($file)) {
  3319. $src = Link::get_youtube_video_id($file);
  3320. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3321. } elseif (Link::isVimeoLink($file)) {
  3322. $src = Link::getVimeoLinkId($file);
  3323. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3324. } else {
  3325. // If the current site is HTTPS and the link is
  3326. // HTTP, browsers will refuse opening the link
  3327. $urlId = api_get_current_access_url_id();
  3328. $url = api_get_access_url($urlId, false);
  3329. $protocol = substr($url['url'], 0, 5);
  3330. if ($protocol === 'https') {
  3331. $linkProtocol = substr($file, 0, 5);
  3332. if ($linkProtocol === 'http:') {
  3333. //this is the special intervention case
  3334. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3335. }
  3336. }
  3337. }
  3338. break;
  3339. case 'quiz':
  3340. // Check how much attempts of a exercise exits in lp
  3341. $lp_item_id = $this->get_current_item_id();
  3342. $lp_view_id = $this->get_view_id();
  3343. $prevent_reinit = null;
  3344. if (isset($this->items[$this->current])) {
  3345. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3346. }
  3347. if (empty($provided_toc)) {
  3348. if ($this->debug > 0) {
  3349. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3350. }
  3351. $list = $this->get_toc();
  3352. } else {
  3353. if ($this->debug > 0) {
  3354. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3355. }
  3356. $list = $provided_toc;
  3357. }
  3358. $type_quiz = false;
  3359. foreach ($list as $toc) {
  3360. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3361. $type_quiz = true;
  3362. }
  3363. }
  3364. if ($type_quiz) {
  3365. $lp_item_id = intval($lp_item_id);
  3366. $lp_view_id = intval($lp_view_id);
  3367. $sql = "SELECT count(*) FROM $lp_item_view_table
  3368. WHERE
  3369. c_id = $course_id AND
  3370. lp_item_id='".$lp_item_id."' AND
  3371. lp_view_id ='".$lp_view_id."' AND
  3372. status='completed'";
  3373. $result = Database::query($sql);
  3374. $row_count = Database:: fetch_row($result);
  3375. $count_item_view = (int) $row_count[0];
  3376. $not_multiple_attempt = 0;
  3377. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3378. $not_multiple_attempt = 1;
  3379. }
  3380. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3381. }
  3382. break;
  3383. }
  3384. $tmp_array = explode('/', $file);
  3385. $document_name = $tmp_array[count($tmp_array) - 1];
  3386. if (strpos($document_name, '_DELETED_')) {
  3387. $file = 'blank.php?error=document_deleted';
  3388. }
  3389. break;
  3390. case 2:
  3391. if ($this->debug > 2) {
  3392. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3393. }
  3394. if ($lp_item_type != 'dir') {
  3395. // Quite complex here:
  3396. // We want to make sure 'http://' (and similar) links can
  3397. // be loaded as is (withouth the Chamilo path in front) but
  3398. // some contents use this form: resource.htm?resource=http://blablabla
  3399. // which means we have to find a protocol at the path's start, otherwise
  3400. // it should not be considered as an external URL.
  3401. // if ($this->prerequisites_match($item_id)) {
  3402. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3403. if ($this->debug > 2) {
  3404. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3405. }
  3406. // Distant url, return as is.
  3407. $file = $lp_item_path;
  3408. } else {
  3409. if ($this->debug > 2) {
  3410. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3411. }
  3412. // Prevent getting untranslatable urls.
  3413. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3414. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3415. // Prepare the path.
  3416. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3417. // TODO: Fix this for urls with protocol header.
  3418. $file = str_replace('//', '/', $file);
  3419. $file = str_replace(':/', '://', $file);
  3420. if (substr($lp_path, -1) == '/') {
  3421. $lp_path = substr($lp_path, 0, -1);
  3422. }
  3423. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3424. // if file not found.
  3425. $decoded = html_entity_decode($lp_item_path);
  3426. list($decoded) = explode('?', $decoded);
  3427. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3428. $file = self::rl_get_resource_link_for_learnpath(
  3429. $course_id,
  3430. $this->get_id(),
  3431. $item_id,
  3432. $this->get_view_id()
  3433. );
  3434. if (empty($file)) {
  3435. $file = 'blank.php?error=document_not_found';
  3436. } else {
  3437. $tmp_array = explode('/', $file);
  3438. $document_name = $tmp_array[count($tmp_array) - 1];
  3439. if (strpos($document_name, '_DELETED_')) {
  3440. $file = 'blank.php?error=document_deleted';
  3441. } else {
  3442. $file = 'blank.php?error=document_not_found';
  3443. }
  3444. }
  3445. } else {
  3446. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3447. }
  3448. }
  3449. }
  3450. // We want to use parameters if they were defined in the imsmanifest
  3451. if (strpos($file, 'blank.php') === false) {
  3452. $lp_item_params = ltrim($lp_item_params, '?');
  3453. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3454. }
  3455. } else {
  3456. $file = 'lp_content.php?type=dir';
  3457. }
  3458. break;
  3459. case 3:
  3460. if ($this->debug > 2) {
  3461. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3462. }
  3463. // Formatting AICC HACP append URL.
  3464. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3465. if (!empty($lp_item_params)) {
  3466. $aicc_append .= $lp_item_params.'&';
  3467. }
  3468. if ($lp_item_type != 'dir') {
  3469. // Quite complex here:
  3470. // We want to make sure 'http://' (and similar) links can
  3471. // be loaded as is (withouth the Chamilo path in front) but
  3472. // some contents use this form: resource.htm?resource=http://blablabla
  3473. // which means we have to find a protocol at the path's start, otherwise
  3474. // it should not be considered as an external URL.
  3475. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3476. if ($this->debug > 2) {
  3477. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3478. }
  3479. // Distant url, return as is.
  3480. $file = $lp_item_path;
  3481. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3482. /*
  3483. if (stristr($file,'<servername>') !== false) {
  3484. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3485. }
  3486. */
  3487. if (stripos($file, '<servername>') !== false) {
  3488. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3489. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3490. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3491. }
  3492. $file .= $aicc_append;
  3493. } else {
  3494. if ($this->debug > 2) {
  3495. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3496. }
  3497. // Prevent getting untranslatable urls.
  3498. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3499. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3500. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3501. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3502. // TODO: Fix this for urls with protocol header.
  3503. $file = str_replace('//', '/', $file);
  3504. $file = str_replace(':/', '://', $file);
  3505. $file .= $aicc_append;
  3506. }
  3507. } else {
  3508. $file = 'lp_content.php?type=dir';
  3509. }
  3510. break;
  3511. case 4:
  3512. break;
  3513. default:
  3514. break;
  3515. }
  3516. // Replace &amp; by & because &amp; will break URL with params
  3517. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3518. }
  3519. if ($this->debug > 2) {
  3520. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3521. }
  3522. return $file;
  3523. }
  3524. /**
  3525. * Gets the latest usable view or generate a new one.
  3526. *
  3527. * @param int Optional attempt number. If none given, takes the highest from the lp_view table
  3528. *
  3529. * @return int DB lp_view id
  3530. */
  3531. public function get_view($attempt_num = 0)
  3532. {
  3533. if ($this->debug > 0) {
  3534. error_log('In learnpath::get_view()', 0);
  3535. }
  3536. $search = '';
  3537. // Use $attempt_num to enable multi-views management (disabled so far).
  3538. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3539. $search = 'AND view_count = '.$attempt_num;
  3540. }
  3541. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3542. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3543. $course_id = api_get_course_int_id();
  3544. $sessionId = api_get_session_id();
  3545. $sql = "SELECT iid, view_count FROM $lp_view_table
  3546. WHERE
  3547. c_id = $course_id AND
  3548. lp_id = ".$this->get_id()." AND
  3549. user_id = ".$this->get_user_id()." AND
  3550. session_id = $sessionId
  3551. $search
  3552. ORDER BY view_count DESC";
  3553. $res = Database::query($sql);
  3554. if (Database::num_rows($res) > 0) {
  3555. $row = Database::fetch_array($res);
  3556. $this->lp_view_id = $row['iid'];
  3557. } elseif (!api_is_invitee()) {
  3558. // There is no database record, create one.
  3559. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3560. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3561. Database::query($sql);
  3562. $id = Database::insert_id();
  3563. $this->lp_view_id = $id;
  3564. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3565. Database::query($sql);
  3566. }
  3567. return $this->lp_view_id;
  3568. }
  3569. /**
  3570. * Gets the current view id.
  3571. *
  3572. * @return int View ID (from lp_view)
  3573. */
  3574. public function get_view_id()
  3575. {
  3576. if ($this->debug > 0) {
  3577. error_log('In learnpath::get_view_id()', 0);
  3578. }
  3579. if (!empty($this->lp_view_id)) {
  3580. return $this->lp_view_id;
  3581. } else {
  3582. return 0;
  3583. }
  3584. }
  3585. /**
  3586. * Gets the update queue.
  3587. *
  3588. * @return array Array containing IDs of items to be updated by JavaScript
  3589. */
  3590. public function get_update_queue()
  3591. {
  3592. if ($this->debug > 0) {
  3593. error_log('In learnpath::get_update_queue()', 0);
  3594. }
  3595. return $this->update_queue;
  3596. }
  3597. /**
  3598. * Gets the user ID.
  3599. *
  3600. * @return int User ID
  3601. */
  3602. public function get_user_id()
  3603. {
  3604. if ($this->debug > 0) {
  3605. error_log('In learnpath::get_user_id()', 0);
  3606. }
  3607. if (!empty($this->user_id)) {
  3608. return $this->user_id;
  3609. } else {
  3610. return false;
  3611. }
  3612. }
  3613. /**
  3614. * Checks if any of the items has an audio element attached.
  3615. *
  3616. * @return bool True or false
  3617. */
  3618. public function has_audio()
  3619. {
  3620. if ($this->debug > 1) {
  3621. error_log('In learnpath::has_audio()', 0);
  3622. }
  3623. $has = false;
  3624. foreach ($this->items as $i => $item) {
  3625. if (!empty($this->items[$i]->audio)) {
  3626. $has = true;
  3627. break;
  3628. }
  3629. }
  3630. return $has;
  3631. }
  3632. /**
  3633. * Moves an item up and down at its level.
  3634. *
  3635. * @param int Item to move up and down
  3636. * @param string Direction 'up' or 'down'
  3637. *
  3638. * @return int New display order, or false on error
  3639. */
  3640. public function move_item($id, $direction)
  3641. {
  3642. $course_id = api_get_course_int_id();
  3643. if ($this->debug > 0) {
  3644. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3645. }
  3646. if (empty($id) || empty($direction)) {
  3647. return false;
  3648. }
  3649. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3650. $sql_sel = "SELECT *
  3651. FROM $tbl_lp_item
  3652. WHERE
  3653. iid = $id
  3654. ";
  3655. $res_sel = Database::query($sql_sel);
  3656. // Check if elem exists.
  3657. if (Database::num_rows($res_sel) < 1) {
  3658. return false;
  3659. }
  3660. // Gather data.
  3661. $row = Database::fetch_array($res_sel);
  3662. $previous = $row['previous_item_id'];
  3663. $next = $row['next_item_id'];
  3664. $display = $row['display_order'];
  3665. $parent = $row['parent_item_id'];
  3666. $lp = $row['lp_id'];
  3667. // Update the item (switch with previous/next one).
  3668. switch ($direction) {
  3669. case 'up':
  3670. if ($this->debug > 2) {
  3671. error_log('Movement up detected', 0);
  3672. }
  3673. if ($display > 1) {
  3674. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3675. WHERE iid = $previous";
  3676. if ($this->debug > 2) {
  3677. error_log('Selecting previous: '.$sql_sel2, 0);
  3678. }
  3679. $res_sel2 = Database::query($sql_sel2);
  3680. if (Database::num_rows($res_sel2) < 1) {
  3681. $previous_previous = 0;
  3682. }
  3683. // Gather data.
  3684. $row2 = Database::fetch_array($res_sel2);
  3685. $previous_previous = $row2['previous_item_id'];
  3686. // Update previous_previous item (switch "next" with current).
  3687. if ($previous_previous != 0) {
  3688. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3689. next_item_id = $id
  3690. WHERE iid = $previous_previous";
  3691. if ($this->debug > 2) {
  3692. error_log($sql_upd2, 0);
  3693. }
  3694. Database::query($sql_upd2);
  3695. }
  3696. // Update previous item (switch with current).
  3697. if ($previous != 0) {
  3698. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3699. next_item_id = $next,
  3700. previous_item_id = $id,
  3701. display_order = display_order +1
  3702. WHERE iid = $previous";
  3703. if ($this->debug > 2) {
  3704. error_log($sql_upd2, 0);
  3705. }
  3706. Database::query($sql_upd2);
  3707. }
  3708. // Update current item (switch with previous).
  3709. if ($id != 0) {
  3710. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3711. next_item_id = $previous,
  3712. previous_item_id = $previous_previous,
  3713. display_order = display_order-1
  3714. WHERE c_id = ".$course_id." AND id = $id";
  3715. if ($this->debug > 2) {
  3716. error_log($sql_upd2, 0);
  3717. }
  3718. Database::query($sql_upd2);
  3719. }
  3720. // Update next item (new previous item).
  3721. if ($next != 0) {
  3722. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3723. WHERE iid = $next";
  3724. if ($this->debug > 2) {
  3725. error_log($sql_upd2, 0);
  3726. }
  3727. Database::query($sql_upd2);
  3728. }
  3729. $display = $display - 1;
  3730. }
  3731. break;
  3732. case 'down':
  3733. if ($this->debug > 2) {
  3734. error_log('Movement down detected', 0);
  3735. }
  3736. if ($next != 0) {
  3737. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3738. WHERE iid = $next";
  3739. if ($this->debug > 2) {
  3740. error_log('Selecting next: '.$sql_sel2, 0);
  3741. }
  3742. $res_sel2 = Database::query($sql_sel2);
  3743. if (Database::num_rows($res_sel2) < 1) {
  3744. $next_next = 0;
  3745. }
  3746. // Gather data.
  3747. $row2 = Database::fetch_array($res_sel2);
  3748. $next_next = $row2['next_item_id'];
  3749. // Update previous item (switch with current).
  3750. if ($previous != 0) {
  3751. $sql_upd2 = "UPDATE $tbl_lp_item
  3752. SET next_item_id = $next
  3753. WHERE iid = $previous";
  3754. Database::query($sql_upd2);
  3755. }
  3756. // Update current item (switch with previous).
  3757. if ($id != 0) {
  3758. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3759. previous_item_id = $next,
  3760. next_item_id = $next_next,
  3761. display_order = display_order + 1
  3762. WHERE iid = $id";
  3763. Database::query($sql_upd2);
  3764. }
  3765. // Update next item (new previous item).
  3766. if ($next != 0) {
  3767. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3768. previous_item_id = $previous,
  3769. next_item_id = $id,
  3770. display_order = display_order-1
  3771. WHERE iid = $next";
  3772. Database::query($sql_upd2);
  3773. }
  3774. // Update next_next item (switch "previous" with current).
  3775. if ($next_next != 0) {
  3776. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3777. previous_item_id = $id
  3778. WHERE iid = $next_next";
  3779. Database::query($sql_upd2);
  3780. }
  3781. $display = $display + 1;
  3782. }
  3783. break;
  3784. default:
  3785. return false;
  3786. }
  3787. return $display;
  3788. }
  3789. /**
  3790. * Move a LP up (display_order).
  3791. *
  3792. * @param int $lp_id Learnpath ID
  3793. * @param int $categoryId
  3794. *
  3795. * @return bool
  3796. */
  3797. public static function move_up($lp_id, $categoryId = 0)
  3798. {
  3799. $courseId = api_get_course_int_id();
  3800. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3801. $categoryCondition = '';
  3802. if (!empty($categoryId)) {
  3803. $categoryId = (int) $categoryId;
  3804. $categoryCondition = " AND category_id = $categoryId";
  3805. }
  3806. $sql = "SELECT * FROM $lp_table
  3807. WHERE c_id = $courseId
  3808. $categoryCondition
  3809. ORDER BY display_order";
  3810. $res = Database::query($sql);
  3811. if ($res === false) {
  3812. return false;
  3813. }
  3814. $lps = [];
  3815. $lp_order = [];
  3816. $num = Database::num_rows($res);
  3817. // First check the order is correct, globally (might be wrong because
  3818. // of versions < 1.8.4)
  3819. if ($num > 0) {
  3820. $i = 1;
  3821. while ($row = Database::fetch_array($res)) {
  3822. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3823. $sql = "UPDATE $lp_table SET display_order = $i
  3824. WHERE iid = ".$row['iid'];
  3825. Database::query($sql);
  3826. }
  3827. $row['display_order'] = $i;
  3828. $lps[$row['iid']] = $row;
  3829. $lp_order[$i] = $row['iid'];
  3830. $i++;
  3831. }
  3832. }
  3833. if ($num > 1) { // If there's only one element, no need to sort.
  3834. $order = $lps[$lp_id]['display_order'];
  3835. if ($order > 1) { // If it's the first element, no need to move up.
  3836. $sql = "UPDATE $lp_table SET display_order = $order
  3837. WHERE iid = ".$lp_order[$order - 1];
  3838. Database::query($sql);
  3839. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3840. WHERE iid = $lp_id";
  3841. Database::query($sql);
  3842. }
  3843. }
  3844. return true;
  3845. }
  3846. /**
  3847. * Move a learnpath down (display_order).
  3848. *
  3849. * @param int $lp_id Learnpath ID
  3850. * @param int $categoryId
  3851. *
  3852. * @return bool
  3853. */
  3854. public static function move_down($lp_id, $categoryId = 0)
  3855. {
  3856. $courseId = api_get_course_int_id();
  3857. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3858. $categoryCondition = '';
  3859. if (!empty($categoryId)) {
  3860. $categoryId = (int) $categoryId;
  3861. $categoryCondition = " AND category_id = $categoryId";
  3862. }
  3863. $sql = "SELECT * FROM $lp_table
  3864. WHERE c_id = $courseId
  3865. $categoryCondition
  3866. ORDER BY display_order";
  3867. $res = Database::query($sql);
  3868. if ($res === false) {
  3869. return false;
  3870. }
  3871. $lps = [];
  3872. $lp_order = [];
  3873. $num = Database::num_rows($res);
  3874. $max = 0;
  3875. // First check the order is correct, globally (might be wrong because
  3876. // of versions < 1.8.4).
  3877. if ($num > 0) {
  3878. $i = 1;
  3879. while ($row = Database::fetch_array($res)) {
  3880. $max = $i;
  3881. if ($row['display_order'] != $i) {
  3882. // If we find a gap in the order, we need to fix it.
  3883. $sql = "UPDATE $lp_table SET display_order = $i
  3884. WHERE iid = ".$row['iid'];
  3885. Database::query($sql);
  3886. }
  3887. $row['display_order'] = $i;
  3888. $lps[$row['iid']] = $row;
  3889. $lp_order[$i] = $row['iid'];
  3890. $i++;
  3891. }
  3892. }
  3893. if ($num > 1) { // If there's only one element, no need to sort.
  3894. $order = $lps[$lp_id]['display_order'];
  3895. if ($order < $max) { // If it's the first element, no need to move up.
  3896. $sql = "UPDATE $lp_table SET display_order = $order
  3897. WHERE iid = ".$lp_order[$order + 1];
  3898. Database::query($sql);
  3899. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3900. WHERE iid = $lp_id";
  3901. Database::query($sql);
  3902. }
  3903. }
  3904. return true;
  3905. }
  3906. /**
  3907. * Updates learnpath attributes to point to the next element
  3908. * The last part is similar to set_current_item but processing the other way around.
  3909. */
  3910. public function next()
  3911. {
  3912. if ($this->debug > 0) {
  3913. error_log('In learnpath::next()', 0);
  3914. }
  3915. $this->last = $this->get_current_item_id();
  3916. $this->items[$this->last]->save(
  3917. false,
  3918. $this->prerequisites_match($this->last)
  3919. );
  3920. $this->autocomplete_parents($this->last);
  3921. $new_index = $this->get_next_index();
  3922. if ($this->debug > 2) {
  3923. error_log('New index: '.$new_index, 0);
  3924. }
  3925. $this->index = $new_index;
  3926. if ($this->debug > 2) {
  3927. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3928. }
  3929. $this->current = $this->ordered_items[$new_index];
  3930. if ($this->debug > 2) {
  3931. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3932. }
  3933. }
  3934. /**
  3935. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3936. * class, this might be redefined to allow several behaviours depending on the document type.
  3937. *
  3938. * @param int Resource ID
  3939. */
  3940. public function open($id)
  3941. {
  3942. if ($this->debug > 0) {
  3943. error_log('In learnpath::open()', 0);
  3944. }
  3945. // TODO:
  3946. // set the current resource attribute to this resource
  3947. // switch on element type (redefine in child class?)
  3948. // set status for this item to "opened"
  3949. // start timer
  3950. // initialise score
  3951. $this->index = 0; //or = the last item seen (see $this->last)
  3952. }
  3953. /**
  3954. * Check that all prerequisites are fulfilled. Returns true and an
  3955. * empty string on success, returns false
  3956. * and the prerequisite string on error.
  3957. * This function is based on the rules for aicc_script language as
  3958. * described in the SCORM 1.2 CAM documentation page 108.
  3959. *
  3960. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3961. *
  3962. * @return bool true if prerequisites are matched, false otherwise -
  3963. * Empty string if true returned, prerequisites string otherwise
  3964. */
  3965. public function prerequisites_match($itemId = null)
  3966. {
  3967. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3968. if ($allow) {
  3969. if (api_is_allowed_to_edit() || api_is_platform_admin() || api_is_drh()) {
  3970. return true;
  3971. }
  3972. }
  3973. $debug = $this->debug;
  3974. if ($debug > 0) {
  3975. error_log('In learnpath::prerequisites_match()', 0);
  3976. }
  3977. if (empty($itemId)) {
  3978. $itemId = $this->current;
  3979. }
  3980. $currentItem = $this->getItem($itemId);
  3981. if ($currentItem) {
  3982. if ($this->type == 2) {
  3983. // Getting prereq from scorm
  3984. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3985. } else {
  3986. $prereq_string = $currentItem->get_prereq_string();
  3987. }
  3988. if (empty($prereq_string)) {
  3989. if ($debug > 0) {
  3990. error_log('Found prereq_string is empty return true');
  3991. }
  3992. return true;
  3993. }
  3994. // Clean spaces.
  3995. $prereq_string = str_replace(' ', '', $prereq_string);
  3996. if ($debug > 0) {
  3997. error_log('Found prereq_string: '.$prereq_string, 0);
  3998. }
  3999. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4000. $result = $currentItem->parse_prereq(
  4001. $prereq_string,
  4002. $this->items,
  4003. $this->refs_list,
  4004. $this->get_user_id()
  4005. );
  4006. if ($result === false) {
  4007. $this->set_error_msg($currentItem->prereq_alert);
  4008. }
  4009. } else {
  4010. $result = true;
  4011. if ($debug > 1) {
  4012. error_log('$this->items['.$itemId.'] was not an object', 0);
  4013. }
  4014. }
  4015. if ($debug > 1) {
  4016. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4017. }
  4018. return $result;
  4019. }
  4020. /**
  4021. * Updates learnpath attributes to point to the previous element
  4022. * The last part is similar to set_current_item but processing the other way around.
  4023. */
  4024. public function previous()
  4025. {
  4026. if ($this->debug > 0) {
  4027. error_log('In learnpath::previous()', 0);
  4028. }
  4029. $this->last = $this->get_current_item_id();
  4030. $this->items[$this->last]->save(
  4031. false,
  4032. $this->prerequisites_match($this->last)
  4033. );
  4034. $this->autocomplete_parents($this->last);
  4035. $new_index = $this->get_previous_index();
  4036. $this->index = $new_index;
  4037. $this->current = $this->ordered_items[$new_index];
  4038. }
  4039. /**
  4040. * Publishes a learnpath. This basically means show or hide the learnpath
  4041. * to normal users.
  4042. * Can be used as abstract.
  4043. *
  4044. * @param int Learnpath ID
  4045. * @param int New visibility
  4046. *
  4047. * @return bool
  4048. */
  4049. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4050. {
  4051. $action = 'visible';
  4052. if ($set_visibility != 1) {
  4053. $action = 'invisible';
  4054. self::toggle_publish($lp_id, 'i');
  4055. }
  4056. return api_item_property_update(
  4057. api_get_course_info(),
  4058. TOOL_LEARNPATH,
  4059. $lp_id,
  4060. $action,
  4061. api_get_user_id()
  4062. );
  4063. }
  4064. /**
  4065. * Publishes a learnpath category.
  4066. * This basically means show or hide the learnpath category to normal users.
  4067. *
  4068. * @param int $id
  4069. * @param int $visibility
  4070. *
  4071. * @return bool
  4072. */
  4073. public static function toggleCategoryVisibility($id, $visibility = 1)
  4074. {
  4075. $action = 'visible';
  4076. if ($visibility != 1) {
  4077. $action = 'invisible';
  4078. $list = new LearnpathList(
  4079. api_get_user_id(),
  4080. null,
  4081. null,
  4082. null,
  4083. false,
  4084. $id
  4085. );
  4086. $lpList = $list->get_flat_list();
  4087. foreach ($lpList as $lp) {
  4088. learnpath::toggle_visibility($lp['iid'], 0);
  4089. }
  4090. learnpath::toggleCategoryPublish($id, 0);
  4091. }
  4092. return api_item_property_update(
  4093. api_get_course_info(),
  4094. TOOL_LEARNPATH_CATEGORY,
  4095. $id,
  4096. $action,
  4097. api_get_user_id()
  4098. );
  4099. }
  4100. /**
  4101. * Publishes a learnpath. This basically means show or hide the learnpath
  4102. * on the course homepage
  4103. * Can be used as abstract.
  4104. *
  4105. * @param int $lp_id Learnpath id
  4106. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4107. *
  4108. * @return bool
  4109. */
  4110. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4111. {
  4112. $course_id = api_get_course_int_id();
  4113. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4114. $lp_id = (int) $lp_id;
  4115. $sql = "SELECT * FROM $tbl_lp
  4116. WHERE iid = $lp_id";
  4117. $result = Database::query($sql);
  4118. if (Database::num_rows($result)) {
  4119. $row = Database::fetch_array($result);
  4120. $name = Database::escape_string($row['name']);
  4121. if ($set_visibility == 'i') {
  4122. $v = 0;
  4123. }
  4124. if ($set_visibility == 'v') {
  4125. $v = 1;
  4126. }
  4127. $session_id = api_get_session_id();
  4128. $session_condition = api_get_session_condition($session_id);
  4129. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4130. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4131. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4132. $sql = "SELECT * FROM $tbl_tool
  4133. WHERE
  4134. c_id = $course_id AND
  4135. (link = '$link' OR link = '$oldLink') AND
  4136. image = 'scormbuilder.gif' AND
  4137. (
  4138. link LIKE '$link%' OR
  4139. link LIKE '$oldLink%'
  4140. )
  4141. $session_condition
  4142. ";
  4143. $result = Database::query($sql);
  4144. $num = Database::num_rows($result);
  4145. if ($set_visibility == 'i' && $num > 0) {
  4146. $sql = "DELETE FROM $tbl_tool
  4147. WHERE
  4148. c_id = $course_id AND
  4149. (link = '$link' OR link = '$oldLink') AND
  4150. image='scormbuilder.gif'
  4151. $session_condition";
  4152. Database::query($sql);
  4153. } elseif ($set_visibility == 'v' && $num == 0) {
  4154. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4155. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4156. Database::query($sql);
  4157. $insertId = Database::insert_id();
  4158. if ($insertId) {
  4159. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4160. Database::query($sql);
  4161. }
  4162. } elseif ($set_visibility == 'v' && $num > 0) {
  4163. $sql = "UPDATE $tbl_tool SET
  4164. c_id = $course_id,
  4165. name = '$name',
  4166. link = '$link',
  4167. image = 'scormbuilder.gif',
  4168. visibility = '$v',
  4169. admin = '0',
  4170. address = 'pastillegris.gif',
  4171. added_tool = 0,
  4172. session_id = $session_id
  4173. WHERE
  4174. c_id = ".$course_id." AND
  4175. (link = '$link' OR link = '$oldLink') AND
  4176. image='scormbuilder.gif'
  4177. $session_condition
  4178. ";
  4179. Database::query($sql);
  4180. } else {
  4181. // Parameter and database incompatible, do nothing, exit.
  4182. return false;
  4183. }
  4184. } else {
  4185. return false;
  4186. }
  4187. }
  4188. /**
  4189. * Publishes a learnpath.
  4190. * Show or hide the learnpath category on the course homepage.
  4191. *
  4192. * @param int $id
  4193. * @param int $setVisibility
  4194. *
  4195. * @return bool
  4196. */
  4197. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4198. {
  4199. $courseId = api_get_course_int_id();
  4200. $sessionId = api_get_session_id();
  4201. $sessionCondition = api_get_session_condition(
  4202. $sessionId,
  4203. true,
  4204. false,
  4205. 't.sessionId'
  4206. );
  4207. $em = Database::getManager();
  4208. /** @var CLpCategory $category */
  4209. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4210. if (!$category) {
  4211. return false;
  4212. }
  4213. $link = self::getCategoryLinkForTool($id);
  4214. /** @var CTool $tool */
  4215. $tool = $em->createQuery("
  4216. SELECT t FROM ChamiloCourseBundle:CTool t
  4217. WHERE
  4218. t.cId = :course AND
  4219. t.link = :link1 AND
  4220. t.image = 'lp_category.gif' AND
  4221. t.link LIKE :link2
  4222. $sessionCondition
  4223. ")
  4224. ->setParameters([
  4225. 'course' => (int) $courseId,
  4226. 'link1' => $link,
  4227. 'link2' => "$link%",
  4228. ])
  4229. ->getOneOrNullResult();
  4230. if ($setVisibility == 0 && $tool) {
  4231. $em->remove($tool);
  4232. $em->flush();
  4233. return true;
  4234. }
  4235. if ($setVisibility == 1 && !$tool) {
  4236. $tool = new CTool();
  4237. $tool
  4238. ->setCategory('authoring')
  4239. ->setCId($courseId)
  4240. ->setName(strip_tags($category->getName()))
  4241. ->setLink($link)
  4242. ->setImage('lp_category.gif')
  4243. ->setVisibility(1)
  4244. ->setAdmin(0)
  4245. ->setAddress('pastillegris.gif')
  4246. ->setAddedTool(0)
  4247. ->setSessionId($sessionId)
  4248. ->setTarget('_self');
  4249. $em->persist($tool);
  4250. $em->flush();
  4251. $tool->setId($tool->getIid());
  4252. $em->persist($tool);
  4253. $em->flush();
  4254. return true;
  4255. }
  4256. if ($setVisibility == 1 && $tool) {
  4257. $tool
  4258. ->setName(strip_tags($category->getName()))
  4259. ->setVisibility(1);
  4260. $em->persist($tool);
  4261. $em->flush();
  4262. return true;
  4263. }
  4264. return false;
  4265. }
  4266. /**
  4267. * Check if the learnpath category is visible for a user.
  4268. *
  4269. * @param CLpCategory $category
  4270. * @param User $user
  4271. *
  4272. * @return bool
  4273. */
  4274. public static function categoryIsVisibleForStudent(
  4275. CLpCategory $category,
  4276. User $user
  4277. ) {
  4278. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4279. if ($isAllowedToEdit) {
  4280. return true;
  4281. }
  4282. if (empty($category)) {
  4283. return false;
  4284. }
  4285. $users = $category->getUsers();
  4286. if (empty($users) || !$users->count()) {
  4287. return true;
  4288. }
  4289. if ($category->hasUserAdded($user)) {
  4290. return true;
  4291. }
  4292. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4293. if (!empty($groups)) {
  4294. $em = Database::getManager();
  4295. /** @var ItemPropertyRepository $itemRepo */
  4296. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4297. /** @var CourseRepository $courseRepo */
  4298. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4299. $sessionId = api_get_session_id();
  4300. $session = null;
  4301. if (!empty($sessionId)) {
  4302. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4303. }
  4304. $course = $courseRepo->find(api_get_course_int_id());
  4305. // Subscribed groups to a LP
  4306. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4307. TOOL_LEARNPATH_CATEGORY,
  4308. $category->getId(),
  4309. $course,
  4310. $session
  4311. );
  4312. if (!empty($subscribedGroupsInLp)) {
  4313. $groups = array_column($groups, 'iid');
  4314. /** @var CItemProperty $item */
  4315. foreach ($subscribedGroupsInLp as $item) {
  4316. if ($item->getGroup() &&
  4317. in_array($item->getGroup()->getId(), $groups)
  4318. ) {
  4319. return true;
  4320. }
  4321. }
  4322. }
  4323. }
  4324. return false;
  4325. }
  4326. /**
  4327. * Check if a learnpath category is published as course tool.
  4328. *
  4329. * @param CLpCategory $category
  4330. * @param int $courseId
  4331. *
  4332. * @return bool
  4333. */
  4334. public static function categoryIsPublished(
  4335. CLpCategory $category,
  4336. $courseId
  4337. ) {
  4338. $link = self::getCategoryLinkForTool($category->getId());
  4339. $em = Database::getManager();
  4340. $tools = $em
  4341. ->createQuery("
  4342. SELECT t FROM ChamiloCourseBundle:CTool t
  4343. WHERE t.cId = :course AND
  4344. t.name = :name AND
  4345. t.image = 'lp_category.gif' AND
  4346. t.link LIKE :link
  4347. ")
  4348. ->setParameters([
  4349. 'course' => $courseId,
  4350. 'name' => strip_tags($category->getName()),
  4351. 'link' => "$link%",
  4352. ])
  4353. ->getResult();
  4354. /** @var CTool $tool */
  4355. $tool = current($tools);
  4356. return $tool ? $tool->getVisibility() : false;
  4357. }
  4358. /**
  4359. * Restart the whole learnpath. Return the URL of the first element.
  4360. * Make sure the results are saved with anoter method. This method should probably be
  4361. * redefined in children classes.
  4362. * To use a similar method statically, use the create_new_attempt() method.
  4363. *
  4364. * @return bool
  4365. */
  4366. public function restart()
  4367. {
  4368. if ($this->debug > 0) {
  4369. error_log('In learnpath::restart()', 0);
  4370. }
  4371. // TODO
  4372. // Call autosave method to save the current progress.
  4373. //$this->index = 0;
  4374. if (api_is_invitee()) {
  4375. return false;
  4376. }
  4377. $session_id = api_get_session_id();
  4378. $course_id = api_get_course_int_id();
  4379. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4380. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4381. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4382. if ($this->debug > 2) {
  4383. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4384. }
  4385. Database::query($sql);
  4386. $view_id = Database::insert_id();
  4387. if ($view_id) {
  4388. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4389. Database::query($sql);
  4390. $this->lp_view_id = $view_id;
  4391. $this->attempt = $this->attempt + 1;
  4392. } else {
  4393. $this->error = 'Could not insert into item_view table...';
  4394. return false;
  4395. }
  4396. $this->autocomplete_parents($this->current);
  4397. foreach ($this->items as $index => $dummy) {
  4398. $this->items[$index]->restart();
  4399. $this->items[$index]->set_lp_view($this->lp_view_id);
  4400. }
  4401. $this->first();
  4402. return true;
  4403. }
  4404. /**
  4405. * Saves the current item.
  4406. *
  4407. * @return bool
  4408. */
  4409. public function save_current()
  4410. {
  4411. $debug = $this->debug;
  4412. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4413. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4414. if ($debug) {
  4415. error_log('save_current() saving item '.$this->current, 0);
  4416. error_log(''.print_r($this->items, true), 0);
  4417. }
  4418. if (isset($this->items[$this->current]) &&
  4419. is_object($this->items[$this->current])
  4420. ) {
  4421. if ($debug) {
  4422. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4423. }
  4424. $res = $this->items[$this->current]->save(
  4425. false,
  4426. $this->prerequisites_match($this->current)
  4427. );
  4428. $this->autocomplete_parents($this->current);
  4429. $status = $this->items[$this->current]->get_status();
  4430. $this->update_queue[$this->current] = $status;
  4431. if ($debug) {
  4432. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4433. }
  4434. return $res;
  4435. }
  4436. return false;
  4437. }
  4438. /**
  4439. * Saves the given item.
  4440. *
  4441. * @param int $item_id Optional (will take from $_REQUEST if null)
  4442. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4443. *
  4444. * @return bool
  4445. */
  4446. public function save_item($item_id = null, $from_outside = true)
  4447. {
  4448. $debug = $this->debug;
  4449. if ($debug) {
  4450. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4451. }
  4452. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4453. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4454. if (empty($item_id)) {
  4455. $item_id = intval($_REQUEST['id']);
  4456. }
  4457. if (empty($item_id)) {
  4458. $item_id = $this->get_current_item_id();
  4459. }
  4460. if (isset($this->items[$item_id]) &&
  4461. is_object($this->items[$item_id])
  4462. ) {
  4463. if ($debug) {
  4464. error_log('Object exists');
  4465. }
  4466. // Saving the item.
  4467. $res = $this->items[$item_id]->save(
  4468. $from_outside,
  4469. $this->prerequisites_match($item_id)
  4470. );
  4471. if ($debug) {
  4472. error_log('update_queue before:');
  4473. error_log(print_r($this->update_queue, 1));
  4474. }
  4475. $this->autocomplete_parents($item_id);
  4476. $status = $this->items[$item_id]->get_status();
  4477. $this->update_queue[$item_id] = $status;
  4478. if ($debug) {
  4479. error_log('get_status(): '.$status);
  4480. error_log('update_queue after:');
  4481. error_log(print_r($this->update_queue, 1));
  4482. }
  4483. return $res;
  4484. }
  4485. return false;
  4486. }
  4487. /**
  4488. * Saves the last item seen's ID only in case.
  4489. */
  4490. public function save_last()
  4491. {
  4492. $course_id = api_get_course_int_id();
  4493. $debug = $this->debug;
  4494. if ($debug) {
  4495. error_log('In learnpath::save_last()', 0);
  4496. }
  4497. $session_condition = api_get_session_condition(
  4498. api_get_session_id(),
  4499. true,
  4500. false
  4501. );
  4502. $table = Database::get_course_table(TABLE_LP_VIEW);
  4503. if (isset($this->current) && !api_is_invitee()) {
  4504. if ($debug) {
  4505. error_log('Saving current item ('.$this->current.') for later review', 0);
  4506. }
  4507. $sql = "UPDATE $table SET
  4508. last_item = ".intval($this->get_current_item_id())."
  4509. WHERE
  4510. c_id = $course_id AND
  4511. lp_id = ".$this->get_id()." AND
  4512. user_id = ".$this->get_user_id()." ".$session_condition;
  4513. if ($debug) {
  4514. error_log('Saving last item seen : '.$sql, 0);
  4515. }
  4516. Database::query($sql);
  4517. }
  4518. if (!api_is_invitee()) {
  4519. // Save progress.
  4520. list($progress) = $this->get_progress_bar_text('%');
  4521. if ($progress >= 0 && $progress <= 100) {
  4522. $progress = (int) $progress;
  4523. $sql = "UPDATE $table SET
  4524. progress = $progress
  4525. WHERE
  4526. c_id = $course_id AND
  4527. lp_id = ".$this->get_id()." AND
  4528. user_id = ".$this->get_user_id()." ".$session_condition;
  4529. // Ignore errors as some tables might not have the progress field just yet.
  4530. Database::query($sql);
  4531. if ($debug) {
  4532. error_log($sql);
  4533. }
  4534. $this->progress_db = $progress;
  4535. }
  4536. }
  4537. }
  4538. /**
  4539. * Sets the current item ID (checks if valid and authorized first).
  4540. *
  4541. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4542. */
  4543. public function set_current_item($item_id = null)
  4544. {
  4545. $debug = $this->debug;
  4546. if ($debug) {
  4547. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4548. }
  4549. if (empty($item_id)) {
  4550. if ($debug) {
  4551. error_log('No new current item given, ignore...', 0);
  4552. }
  4553. // Do nothing.
  4554. } else {
  4555. if ($debug) {
  4556. error_log('New current item given is '.$item_id.'...', 0);
  4557. }
  4558. if (is_numeric($item_id)) {
  4559. $item_id = intval($item_id);
  4560. // TODO: Check in database here.
  4561. $this->last = $this->current;
  4562. $this->current = $item_id;
  4563. // TODO: Update $this->index as well.
  4564. foreach ($this->ordered_items as $index => $item) {
  4565. if ($item == $this->current) {
  4566. $this->index = $index;
  4567. break;
  4568. }
  4569. }
  4570. if ($debug) {
  4571. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4572. }
  4573. } else {
  4574. if ($debug) {
  4575. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4576. }
  4577. }
  4578. }
  4579. }
  4580. /**
  4581. * Sets the encoding.
  4582. *
  4583. * @param string New encoding
  4584. *
  4585. * @return bool
  4586. * TODO (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4587. */
  4588. public function set_encoding($enc = 'UTF-8')
  4589. {
  4590. if ($this->debug > 0) {
  4591. error_log('In learnpath::set_encoding()', 0);
  4592. }
  4593. $enc = api_refine_encoding_id($enc);
  4594. if (empty($enc)) {
  4595. $enc = api_get_system_encoding();
  4596. }
  4597. if (api_is_encoding_supported($enc)) {
  4598. $lp = $this->get_id();
  4599. if ($lp != 0) {
  4600. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4601. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4602. WHERE iid = ".$lp;
  4603. $res = Database::query($sql);
  4604. return $res;
  4605. }
  4606. }
  4607. return false;
  4608. }
  4609. /**
  4610. * Sets the JS lib setting in the database directly.
  4611. * This is the JavaScript library file this lp needs to load on startup.
  4612. *
  4613. * @param string Proximity setting
  4614. *
  4615. * @return bool True on update success. False otherwise.
  4616. */
  4617. public function set_jslib($lib = '')
  4618. {
  4619. if ($this->debug > 0) {
  4620. error_log('In learnpath::set_jslib()', 0);
  4621. }
  4622. $lp = $this->get_id();
  4623. $course_id = api_get_course_int_id();
  4624. if ($lp != 0) {
  4625. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4626. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4627. WHERE iid = $lp";
  4628. $res = Database::query($sql);
  4629. return $res;
  4630. } else {
  4631. return false;
  4632. }
  4633. }
  4634. /**
  4635. * Sets the name of the LP maker (publisher) (and save).
  4636. *
  4637. * @param string Optional string giving the new content_maker of this learnpath
  4638. *
  4639. * @return bool True
  4640. */
  4641. public function set_maker($name = '')
  4642. {
  4643. if ($this->debug > 0) {
  4644. error_log('In learnpath::set_maker()', 0);
  4645. }
  4646. if (empty($name)) {
  4647. return false;
  4648. }
  4649. $this->maker = $name;
  4650. $table = Database::get_course_table(TABLE_LP_MAIN);
  4651. $lp_id = $this->get_id();
  4652. $sql = "UPDATE $table SET
  4653. content_maker = '".Database::escape_string($this->maker)."'
  4654. WHERE iid = $lp_id";
  4655. if ($this->debug > 2) {
  4656. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4657. }
  4658. Database::query($sql);
  4659. return true;
  4660. }
  4661. /**
  4662. * Sets the name of the current learnpath (and save).
  4663. *
  4664. * @param string $name Optional string giving the new name of this learnpath
  4665. *
  4666. * @return bool True/False
  4667. */
  4668. public function set_name($name = null)
  4669. {
  4670. if ($this->debug > 0) {
  4671. error_log('In learnpath::set_name()', 0);
  4672. }
  4673. if (empty($name)) {
  4674. return false;
  4675. }
  4676. $this->name = Database::escape_string($name);
  4677. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4678. $lp_id = $this->get_id();
  4679. $course_id = $this->course_info['real_id'];
  4680. $sql = "UPDATE $lp_table SET
  4681. name = '".Database::escape_string($this->name)."'
  4682. WHERE iid = $lp_id";
  4683. if ($this->debug > 2) {
  4684. error_log('lp updated with new name : '.$this->name, 0);
  4685. }
  4686. $result = Database::query($sql);
  4687. // If the lp is visible on the homepage, change his name there.
  4688. if (Database::affected_rows($result)) {
  4689. $session_id = api_get_session_id();
  4690. $session_condition = api_get_session_condition($session_id);
  4691. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4692. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4693. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4694. WHERE
  4695. c_id = $course_id AND
  4696. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4697. Database::query($sql);
  4698. return true;
  4699. } else {
  4700. return false;
  4701. }
  4702. }
  4703. /**
  4704. * Set index specified prefix terms for all items in this path.
  4705. *
  4706. * @param string Comma-separated list of terms
  4707. * @param string Xapian term prefix
  4708. *
  4709. * @return bool False on error, true otherwise
  4710. */
  4711. public function set_terms_by_prefix($terms_string, $prefix)
  4712. {
  4713. $course_id = api_get_course_int_id();
  4714. if (api_get_setting('search_enabled') !== 'true') {
  4715. return false;
  4716. }
  4717. if (!extension_loaded('xapian')) {
  4718. return false;
  4719. }
  4720. $terms_string = trim($terms_string);
  4721. $terms = explode(',', $terms_string);
  4722. array_walk($terms, 'trim_value');
  4723. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4724. // Don't do anything if no change, verify only at DB, not the search engine.
  4725. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4726. return false;
  4727. }
  4728. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4729. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4730. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4731. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4732. $lp_id = intval($_POST['lp_id']);
  4733. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4734. $result = Database::query($sql);
  4735. $di = new ChamiloIndexer();
  4736. while ($lp_item = Database::fetch_array($result)) {
  4737. // Get search_did.
  4738. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4739. $sql = 'SELECT * FROM %s
  4740. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4741. LIMIT 1';
  4742. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4743. //echo $sql; echo '<br>';
  4744. $res = Database::query($sql);
  4745. if (Database::num_rows($res) > 0) {
  4746. $se_ref = Database::fetch_array($res);
  4747. // Compare terms.
  4748. $doc = $di->get_document($se_ref['search_did']);
  4749. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4750. $xterms = [];
  4751. foreach ($xapian_terms as $xapian_term) {
  4752. $xterms[] = substr($xapian_term['name'], 1);
  4753. }
  4754. $dterms = $terms;
  4755. $missing_terms = array_diff($dterms, $xterms);
  4756. $deprecated_terms = array_diff($xterms, $dterms);
  4757. // Save it to search engine.
  4758. foreach ($missing_terms as $term) {
  4759. $doc->add_term($prefix.$term, 1);
  4760. }
  4761. foreach ($deprecated_terms as $term) {
  4762. $doc->remove_term($prefix.$term);
  4763. }
  4764. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4765. $di->getDb()->flush();
  4766. }
  4767. }
  4768. return true;
  4769. }
  4770. /**
  4771. * Sets the theme of the LP (local/remote) (and save).
  4772. *
  4773. * @param string Optional string giving the new theme of this learnpath
  4774. *
  4775. * @return bool Returns true if theme name is not empty
  4776. */
  4777. public function set_theme($name = '')
  4778. {
  4779. if ($this->debug > 0) {
  4780. error_log('In learnpath::set_theme()', 0);
  4781. }
  4782. $this->theme = $name;
  4783. $table = Database::get_course_table(TABLE_LP_MAIN);
  4784. $lp_id = $this->get_id();
  4785. $sql = "UPDATE $table
  4786. SET theme = '".Database::escape_string($this->theme)."'
  4787. WHERE iid = $lp_id";
  4788. if ($this->debug > 2) {
  4789. error_log('lp updated with new theme : '.$this->theme, 0);
  4790. }
  4791. Database::query($sql);
  4792. return true;
  4793. }
  4794. /**
  4795. * Sets the image of an LP (and save).
  4796. *
  4797. * @param string Optional string giving the new image of this learnpath
  4798. *
  4799. * @return bool Returns true if theme name is not empty
  4800. */
  4801. public function set_preview_image($name = '')
  4802. {
  4803. if ($this->debug > 0) {
  4804. error_log('In learnpath::set_preview_image()', 0);
  4805. }
  4806. $this->preview_image = $name;
  4807. $table = Database::get_course_table(TABLE_LP_MAIN);
  4808. $lp_id = $this->get_id();
  4809. $sql = "UPDATE $table SET
  4810. preview_image = '".Database::escape_string($this->preview_image)."'
  4811. WHERE iid = $lp_id";
  4812. if ($this->debug > 2) {
  4813. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4814. }
  4815. Database::query($sql);
  4816. return true;
  4817. }
  4818. /**
  4819. * Sets the author of a LP (and save).
  4820. *
  4821. * @param string Optional string giving the new author of this learnpath
  4822. *
  4823. * @return bool Returns true if author's name is not empty
  4824. */
  4825. public function set_author($name = '')
  4826. {
  4827. if ($this->debug > 0) {
  4828. error_log('In learnpath::set_author()', 0);
  4829. }
  4830. $this->author = $name;
  4831. $table = Database::get_course_table(TABLE_LP_MAIN);
  4832. $lp_id = $this->get_id();
  4833. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4834. WHERE iid = $lp_id";
  4835. if ($this->debug > 2) {
  4836. error_log('lp updated with new preview author : '.$this->author, 0);
  4837. }
  4838. Database::query($sql);
  4839. return true;
  4840. }
  4841. /**
  4842. * Sets the hide_toc_frame parameter of a LP (and save).
  4843. *
  4844. * @param int 1 if frame is hidden 0 then else
  4845. *
  4846. * @return bool Returns true if author's name is not empty
  4847. */
  4848. public function set_hide_toc_frame($hide)
  4849. {
  4850. if ($this->debug > 0) {
  4851. error_log('In learnpath::set_hide_toc_frame()', 0);
  4852. }
  4853. if (intval($hide) == $hide) {
  4854. $this->hide_toc_frame = $hide;
  4855. $table = Database::get_course_table(TABLE_LP_MAIN);
  4856. $lp_id = $this->get_id();
  4857. $sql = "UPDATE $table SET
  4858. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4859. WHERE iid = $lp_id";
  4860. if ($this->debug > 2) {
  4861. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4862. }
  4863. Database::query($sql);
  4864. return true;
  4865. } else {
  4866. return false;
  4867. }
  4868. }
  4869. /**
  4870. * Sets the prerequisite of a LP (and save).
  4871. *
  4872. * @param int integer giving the new prerequisite of this learnpath
  4873. *
  4874. * @return bool returns true if prerequisite is not empty
  4875. */
  4876. public function set_prerequisite($prerequisite)
  4877. {
  4878. if ($this->debug > 0) {
  4879. error_log('In learnpath::set_prerequisite()', 0);
  4880. }
  4881. $this->prerequisite = intval($prerequisite);
  4882. $table = Database::get_course_table(TABLE_LP_MAIN);
  4883. $lp_id = $this->get_id();
  4884. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4885. WHERE iid = $lp_id";
  4886. if ($this->debug > 2) {
  4887. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  4888. }
  4889. Database::query($sql);
  4890. return true;
  4891. }
  4892. /**
  4893. * Sets the location/proximity of the LP (local/remote) (and save).
  4894. *
  4895. * @param string Optional string giving the new location of this learnpath
  4896. *
  4897. * @return bool True on success / False on error
  4898. */
  4899. public function set_proximity($name = '')
  4900. {
  4901. if ($this->debug > 0) {
  4902. error_log('In learnpath::set_proximity()', 0);
  4903. }
  4904. if (empty($name)) {
  4905. return false;
  4906. }
  4907. $this->proximity = $name;
  4908. $table = Database::get_course_table(TABLE_LP_MAIN);
  4909. $lp_id = $this->get_id();
  4910. $sql = "UPDATE $table SET
  4911. content_local = '".Database::escape_string($name)."'
  4912. WHERE iid = $lp_id";
  4913. if ($this->debug > 2) {
  4914. error_log('lp updated with new proximity : '.$this->proximity, 0);
  4915. }
  4916. Database::query($sql);
  4917. return true;
  4918. }
  4919. /**
  4920. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4921. *
  4922. * @param int DB ID of the item
  4923. */
  4924. public function set_previous_item($id)
  4925. {
  4926. if ($this->debug > 0) {
  4927. error_log('In learnpath::set_previous_item()', 0);
  4928. }
  4929. $this->last = $id;
  4930. }
  4931. /**
  4932. * Sets use_max_score.
  4933. *
  4934. * @param int $use_max_score Optional string giving the new location of this learnpath
  4935. *
  4936. * @return bool True on success / False on error
  4937. */
  4938. public function set_use_max_score($use_max_score = 1)
  4939. {
  4940. if ($this->debug > 0) {
  4941. error_log('In learnpath::set_use_max_score()', 0);
  4942. }
  4943. $use_max_score = intval($use_max_score);
  4944. $this->use_max_score = $use_max_score;
  4945. $table = Database::get_course_table(TABLE_LP_MAIN);
  4946. $lp_id = $this->get_id();
  4947. $sql = "UPDATE $table SET
  4948. use_max_score = '".$this->use_max_score."'
  4949. WHERE iid = $lp_id";
  4950. if ($this->debug > 2) {
  4951. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  4952. }
  4953. Database::query($sql);
  4954. return true;
  4955. }
  4956. /**
  4957. * Sets and saves the expired_on date.
  4958. *
  4959. * @param string $expired_on Optional string giving the new author of this learnpath
  4960. *
  4961. * @return bool Returns true if author's name is not empty
  4962. */
  4963. public function set_expired_on($expired_on)
  4964. {
  4965. if ($this->debug > 0) {
  4966. error_log('In learnpath::set_expired_on()', 0);
  4967. }
  4968. $em = Database::getManager();
  4969. /** @var CLp $lp */
  4970. $lp = $em
  4971. ->getRepository('ChamiloCourseBundle:CLp')
  4972. ->findOneBy(
  4973. [
  4974. 'iid' => $this->get_id(),
  4975. ]
  4976. );
  4977. if (!$lp) {
  4978. return false;
  4979. }
  4980. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4981. $lp->setExpiredOn($this->expired_on);
  4982. $em->persist($lp);
  4983. $em->flush();
  4984. if ($this->debug > 2) {
  4985. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  4986. }
  4987. return true;
  4988. }
  4989. /**
  4990. * Sets and saves the publicated_on date.
  4991. *
  4992. * @param string $publicated_on Optional string giving the new author of this learnpath
  4993. *
  4994. * @return bool Returns true if author's name is not empty
  4995. */
  4996. public function set_publicated_on($publicated_on)
  4997. {
  4998. if ($this->debug > 0) {
  4999. error_log('In learnpath::set_expired_on()', 0);
  5000. }
  5001. $em = Database::getManager();
  5002. /** @var CLp $lp */
  5003. $lp = $em
  5004. ->getRepository('ChamiloCourseBundle:CLp')
  5005. ->findOneBy(
  5006. [
  5007. 'iid' => $this->get_id(),
  5008. ]
  5009. );
  5010. if (!$lp) {
  5011. return false;
  5012. }
  5013. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5014. $lp->setPublicatedOn($this->publicated_on);
  5015. $em->persist($lp);
  5016. $em->flush();
  5017. if ($this->debug > 2) {
  5018. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5019. }
  5020. return true;
  5021. }
  5022. /**
  5023. * Sets and saves the expired_on date.
  5024. *
  5025. * @return bool Returns true if author's name is not empty
  5026. */
  5027. public function set_modified_on()
  5028. {
  5029. if ($this->debug > 0) {
  5030. error_log('In learnpath::set_expired_on()', 0);
  5031. }
  5032. $this->modified_on = api_get_utc_datetime();
  5033. $table = Database::get_course_table(TABLE_LP_MAIN);
  5034. $lp_id = $this->get_id();
  5035. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5036. WHERE iid = $lp_id";
  5037. if ($this->debug > 2) {
  5038. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5039. }
  5040. Database::query($sql);
  5041. return true;
  5042. }
  5043. /**
  5044. * Sets the object's error message.
  5045. *
  5046. * @param string Error message. If empty, reinits the error string
  5047. */
  5048. public function set_error_msg($error = '')
  5049. {
  5050. if ($this->debug > 0) {
  5051. error_log('In learnpath::set_error_msg()', 0);
  5052. }
  5053. if (empty($error)) {
  5054. $this->error = '';
  5055. } else {
  5056. $this->error .= $error;
  5057. }
  5058. }
  5059. /**
  5060. * Launches the current item if not 'sco'
  5061. * (starts timer and make sure there is a record ready in the DB).
  5062. *
  5063. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5064. *
  5065. * @return bool
  5066. */
  5067. public function start_current_item($allow_new_attempt = false)
  5068. {
  5069. $debug = $this->debug;
  5070. if ($debug) {
  5071. error_log('In learnpath::start_current_item()');
  5072. error_log('current: '.$this->current);
  5073. }
  5074. if ($this->current != 0 && is_object($this->items[$this->current])) {
  5075. $type = $this->get_type();
  5076. $item_type = $this->items[$this->current]->get_type();
  5077. if (($type == 2 && $item_type != 'sco') ||
  5078. ($type == 3 && $item_type != 'au') ||
  5079. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5080. ) {
  5081. if ($debug) {
  5082. error_log('item type: '.$item_type);
  5083. error_log('lp type: '.$type);
  5084. }
  5085. $this->items[$this->current]->open($allow_new_attempt);
  5086. $this->autocomplete_parents($this->current);
  5087. $prereq_check = $this->prerequisites_match($this->current);
  5088. if ($debug) {
  5089. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5090. }
  5091. $this->items[$this->current]->save(false, $prereq_check);
  5092. }
  5093. // If sco, then it is supposed to have been updated by some other call.
  5094. if ($item_type == 'sco') {
  5095. $this->items[$this->current]->restart();
  5096. }
  5097. }
  5098. if ($debug) {
  5099. error_log('lp_view_session_id');
  5100. error_log($this->lp_view_session_id);
  5101. error_log('api session id');
  5102. error_log(api_get_session_id());
  5103. error_log('New LP - End of learnpath::start_current_item()');
  5104. }
  5105. return true;
  5106. }
  5107. /**
  5108. * Stops the processing and counters for the old item (as held in $this->last).
  5109. *
  5110. * @return bool True/False
  5111. */
  5112. public function stop_previous_item()
  5113. {
  5114. $debug = $this->debug;
  5115. if ($debug) {
  5116. error_log('In learnpath::stop_previous_item()', 0);
  5117. }
  5118. if ($this->last != 0 && $this->last != $this->current && is_object($this->items[$this->last])) {
  5119. if ($debug) {
  5120. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5121. }
  5122. switch ($this->get_type()) {
  5123. case '3':
  5124. if ($this->items[$this->last]->get_type() != 'au') {
  5125. if ($debug) {
  5126. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5127. }
  5128. $this->items[$this->last]->close();
  5129. } else {
  5130. if ($debug) {
  5131. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5132. }
  5133. }
  5134. break;
  5135. case '2':
  5136. if ($this->items[$this->last]->get_type() != 'sco') {
  5137. if ($debug) {
  5138. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5139. }
  5140. $this->items[$this->last]->close();
  5141. } else {
  5142. if ($debug) {
  5143. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5144. }
  5145. }
  5146. break;
  5147. case '1':
  5148. default:
  5149. if ($debug) {
  5150. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5151. }
  5152. $this->items[$this->last]->close();
  5153. break;
  5154. }
  5155. } else {
  5156. if ($debug) {
  5157. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5158. }
  5159. return false;
  5160. }
  5161. return true;
  5162. }
  5163. /**
  5164. * Updates the default view mode from fullscreen to embedded and inversely.
  5165. *
  5166. * @return string The current default view mode ('fullscreen' or 'embedded')
  5167. */
  5168. public function update_default_view_mode()
  5169. {
  5170. if ($this->debug > 0) {
  5171. error_log('In learnpath::update_default_view_mode()', 0);
  5172. }
  5173. $table = Database::get_course_table(TABLE_LP_MAIN);
  5174. $sql = "SELECT * FROM $table
  5175. WHERE iid = ".$this->get_id();
  5176. $res = Database::query($sql);
  5177. if (Database::num_rows($res) > 0) {
  5178. $row = Database::fetch_array($res);
  5179. $default_view_mode = $row['default_view_mod'];
  5180. $view_mode = $default_view_mode;
  5181. switch ($default_view_mode) {
  5182. case 'fullscreen': // default with popup
  5183. $view_mode = 'embedded';
  5184. break;
  5185. case 'embedded': // default view with left menu
  5186. $view_mode = 'embedframe';
  5187. break;
  5188. case 'embedframe': //folded menu
  5189. $view_mode = 'impress';
  5190. break;
  5191. case 'impress':
  5192. $view_mode = 'fullscreen';
  5193. break;
  5194. }
  5195. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5196. WHERE iid = ".$this->get_id();
  5197. Database::query($sql);
  5198. $this->mode = $view_mode;
  5199. return $view_mode;
  5200. } else {
  5201. if ($this->debug > 2) {
  5202. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5203. }
  5204. }
  5205. return -1;
  5206. }
  5207. /**
  5208. * Updates the default behaviour about auto-commiting SCORM updates.
  5209. *
  5210. * @return bool True if auto-commit has been set to 'on', false otherwise
  5211. */
  5212. public function update_default_scorm_commit()
  5213. {
  5214. if ($this->debug > 0) {
  5215. error_log('In learnpath::update_default_scorm_commit()', 0);
  5216. }
  5217. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5218. $sql = "SELECT * FROM $lp_table
  5219. WHERE iid = ".$this->get_id();
  5220. $res = Database::query($sql);
  5221. if (Database::num_rows($res) > 0) {
  5222. $row = Database::fetch_array($res);
  5223. $force = $row['force_commit'];
  5224. if ($force == 1) {
  5225. $force = 0;
  5226. $force_return = false;
  5227. } elseif ($force == 0) {
  5228. $force = 1;
  5229. $force_return = true;
  5230. }
  5231. $sql = "UPDATE $lp_table SET force_commit = $force
  5232. WHERE iid = ".$this->get_id();
  5233. Database::query($sql);
  5234. $this->force_commit = $force_return;
  5235. return $force_return;
  5236. } else {
  5237. if ($this->debug > 2) {
  5238. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5239. }
  5240. }
  5241. return -1;
  5242. }
  5243. /**
  5244. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5245. *
  5246. * @return bool True on success, false on failure
  5247. */
  5248. public function update_display_order()
  5249. {
  5250. $course_id = api_get_course_int_id();
  5251. $table = Database::get_course_table(TABLE_LP_MAIN);
  5252. $sql = "SELECT * FROM $table
  5253. WHERE c_id = $course_id ORDER BY display_order";
  5254. $res = Database::query($sql);
  5255. if ($res === false) {
  5256. return false;
  5257. }
  5258. $num = Database::num_rows($res);
  5259. // First check the order is correct, globally (might be wrong because
  5260. // of versions < 1.8.4).
  5261. if ($num > 0) {
  5262. $i = 1;
  5263. while ($row = Database::fetch_array($res)) {
  5264. if ($row['display_order'] != $i) {
  5265. // If we find a gap in the order, we need to fix it.
  5266. $sql = "UPDATE $table SET display_order = $i
  5267. WHERE iid = ".$row['iid'];
  5268. Database::query($sql);
  5269. }
  5270. $i++;
  5271. }
  5272. }
  5273. return true;
  5274. }
  5275. /**
  5276. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5277. *
  5278. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5279. */
  5280. public function update_reinit()
  5281. {
  5282. $course_id = api_get_course_int_id();
  5283. if ($this->debug > 0) {
  5284. error_log('In learnpath::update_reinit()', 0);
  5285. }
  5286. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5287. $sql = "SELECT * FROM $lp_table
  5288. WHERE iid = ".$this->get_id();
  5289. $res = Database::query($sql);
  5290. if (Database::num_rows($res) > 0) {
  5291. $row = Database::fetch_array($res);
  5292. $force = $row['prevent_reinit'];
  5293. if ($force == 1) {
  5294. $force = 0;
  5295. } elseif ($force == 0) {
  5296. $force = 1;
  5297. }
  5298. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5299. WHERE iid = ".$this->get_id();
  5300. Database::query($sql);
  5301. $this->prevent_reinit = $force;
  5302. return $force;
  5303. } else {
  5304. if ($this->debug > 2) {
  5305. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5306. }
  5307. }
  5308. return -1;
  5309. }
  5310. /**
  5311. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5312. *
  5313. * @return string 'single', 'multi' or 'seriousgame'
  5314. *
  5315. * @author ndiechburg <noel@cblue.be>
  5316. */
  5317. public function get_attempt_mode()
  5318. {
  5319. //Set default value for seriousgame_mode
  5320. if (!isset($this->seriousgame_mode)) {
  5321. $this->seriousgame_mode = 0;
  5322. }
  5323. // Set default value for prevent_reinit
  5324. if (!isset($this->prevent_reinit)) {
  5325. $this->prevent_reinit = 1;
  5326. }
  5327. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5328. return 'seriousgame';
  5329. }
  5330. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5331. return 'single';
  5332. }
  5333. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5334. return 'multiple';
  5335. }
  5336. return 'single';
  5337. }
  5338. /**
  5339. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5340. *
  5341. * @param string 'seriousgame', 'single' or 'multiple'
  5342. *
  5343. * @return bool
  5344. *
  5345. * @author ndiechburg <noel@cblue.be>
  5346. */
  5347. public function set_attempt_mode($mode)
  5348. {
  5349. switch ($mode) {
  5350. case 'seriousgame':
  5351. $sg_mode = 1;
  5352. $prevent_reinit = 1;
  5353. break;
  5354. case 'single':
  5355. $sg_mode = 0;
  5356. $prevent_reinit = 1;
  5357. break;
  5358. case 'multiple':
  5359. $sg_mode = 0;
  5360. $prevent_reinit = 0;
  5361. break;
  5362. default:
  5363. $sg_mode = 0;
  5364. $prevent_reinit = 0;
  5365. break;
  5366. }
  5367. $this->prevent_reinit = $prevent_reinit;
  5368. $this->seriousgame_mode = $sg_mode;
  5369. $table = Database::get_course_table(TABLE_LP_MAIN);
  5370. $sql = "UPDATE $table SET
  5371. prevent_reinit = $prevent_reinit ,
  5372. seriousgame_mode = $sg_mode
  5373. WHERE iid = ".$this->get_id();
  5374. $res = Database::query($sql);
  5375. if ($res) {
  5376. return true;
  5377. } else {
  5378. return false;
  5379. }
  5380. }
  5381. /**
  5382. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5383. *
  5384. * @author ndiechburg <noel@cblue.be>
  5385. */
  5386. public function switch_attempt_mode()
  5387. {
  5388. if ($this->debug > 0) {
  5389. error_log('In learnpath::switch_attempt_mode()', 0);
  5390. }
  5391. $mode = $this->get_attempt_mode();
  5392. switch ($mode) {
  5393. case 'single':
  5394. $next_mode = 'multiple';
  5395. break;
  5396. case 'multiple':
  5397. $next_mode = 'seriousgame';
  5398. break;
  5399. case 'seriousgame':
  5400. $next_mode = 'single';
  5401. break;
  5402. default:
  5403. $next_mode = 'single';
  5404. break;
  5405. }
  5406. $this->set_attempt_mode($next_mode);
  5407. }
  5408. /**
  5409. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5410. * but possibility to do again a completed item.
  5411. *
  5412. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5413. *
  5414. * @author ndiechburg <noel@cblue.be>
  5415. */
  5416. public function set_seriousgame_mode()
  5417. {
  5418. if ($this->debug > 0) {
  5419. error_log('In learnpath::set_seriousgame_mode()', 0);
  5420. }
  5421. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5422. $sql = "SELECT * FROM $lp_table
  5423. WHERE iid = ".$this->get_id();
  5424. $res = Database::query($sql);
  5425. if (Database::num_rows($res) > 0) {
  5426. $row = Database::fetch_array($res);
  5427. $force = $row['seriousgame_mode'];
  5428. if ($force == 1) {
  5429. $force = 0;
  5430. } elseif ($force == 0) {
  5431. $force = 1;
  5432. }
  5433. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5434. WHERE iid = ".$this->get_id();
  5435. Database::query($sql);
  5436. $this->seriousgame_mode = $force;
  5437. return $force;
  5438. } else {
  5439. if ($this->debug > 2) {
  5440. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5441. }
  5442. }
  5443. return -1;
  5444. }
  5445. /**
  5446. * Updates the "scorm_debug" value that shows or hide the debug window.
  5447. *
  5448. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5449. */
  5450. public function update_scorm_debug()
  5451. {
  5452. if ($this->debug > 0) {
  5453. error_log('In learnpath::update_scorm_debug()', 0);
  5454. }
  5455. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5456. $sql = "SELECT * FROM $lp_table
  5457. WHERE iid = ".$this->get_id();
  5458. $res = Database::query($sql);
  5459. if (Database::num_rows($res) > 0) {
  5460. $row = Database::fetch_array($res);
  5461. $force = $row['debug'];
  5462. if ($force == 1) {
  5463. $force = 0;
  5464. } elseif ($force == 0) {
  5465. $force = 1;
  5466. }
  5467. $sql = "UPDATE $lp_table SET debug = $force
  5468. WHERE iid = ".$this->get_id();
  5469. Database::query($sql);
  5470. $this->scorm_debug = $force;
  5471. return $force;
  5472. } else {
  5473. if ($this->debug > 2) {
  5474. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5475. }
  5476. }
  5477. return -1;
  5478. }
  5479. /**
  5480. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5481. *
  5482. * @author Kevin Van Den Haute
  5483. *
  5484. * @param array
  5485. */
  5486. public function tree_array($array)
  5487. {
  5488. if ($this->debug > 1) {
  5489. error_log('In learnpath::tree_array()', 0);
  5490. }
  5491. $array = $this->sort_tree_array($array);
  5492. $this->create_tree_array($array);
  5493. }
  5494. /**
  5495. * Creates an array with the elements of the learning path tree in it.
  5496. *
  5497. * @author Kevin Van Den Haute
  5498. *
  5499. * @param array $array
  5500. * @param int $parent
  5501. * @param int $depth
  5502. * @param array $tmp
  5503. */
  5504. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5505. {
  5506. if ($this->debug > 1) {
  5507. error_log('In learnpath::create_tree_array())', 0);
  5508. }
  5509. if (is_array($array)) {
  5510. for ($i = 0; $i < count($array); $i++) {
  5511. if ($array[$i]['parent_item_id'] == $parent) {
  5512. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5513. $tmp[] = $array[$i]['parent_item_id'];
  5514. $depth++;
  5515. }
  5516. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5517. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5518. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5519. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5520. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5521. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5522. $this->arrMenu[] = [
  5523. 'id' => $array[$i]['id'],
  5524. 'ref' => $ref,
  5525. 'item_type' => $array[$i]['item_type'],
  5526. 'title' => $array[$i]['title'],
  5527. 'path' => $path,
  5528. 'description' => $array[$i]['description'],
  5529. 'parent_item_id' => $array[$i]['parent_item_id'],
  5530. 'previous_item_id' => $array[$i]['previous_item_id'],
  5531. 'next_item_id' => $array[$i]['next_item_id'],
  5532. 'min_score' => $array[$i]['min_score'],
  5533. 'max_score' => $array[$i]['max_score'],
  5534. 'mastery_score' => $array[$i]['mastery_score'],
  5535. 'display_order' => $array[$i]['display_order'],
  5536. 'prerequisite' => $preq,
  5537. 'depth' => $depth,
  5538. 'audio' => $audio,
  5539. 'prerequisite_min_score' => $prerequisiteMinScore,
  5540. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5541. ];
  5542. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5543. }
  5544. }
  5545. }
  5546. }
  5547. /**
  5548. * Sorts a multi dimensional array by parent id and display order.
  5549. *
  5550. * @author Kevin Van Den Haute
  5551. *
  5552. * @param array $array (array with al the learning path items in it)
  5553. *
  5554. * @return array
  5555. */
  5556. public function sort_tree_array($array)
  5557. {
  5558. foreach ($array as $key => $row) {
  5559. $parent[$key] = $row['parent_item_id'];
  5560. $position[$key] = $row['display_order'];
  5561. }
  5562. if (count($array) > 0) {
  5563. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5564. }
  5565. return $array;
  5566. }
  5567. /**
  5568. * Function that creates a html list of learning path items so that we can add audio files to them.
  5569. *
  5570. * @author Kevin Van Den Haute
  5571. *
  5572. * @return string
  5573. */
  5574. public function overview()
  5575. {
  5576. if ($this->debug > 0) {
  5577. error_log('In learnpath::overview()', 0);
  5578. }
  5579. $return = '';
  5580. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5581. // we need to start a form when we want to update all the mp3 files
  5582. if ($update_audio == 'true') {
  5583. $return .= '<form action="'.api_get_self().'?'.api_get_cidreq().'&updateaudio='.Security::remove_XSS($_GET['updateaudio']).'&action='.Security::remove_XSS($_GET['action']).'&lp_id='.$_SESSION['oLP']->lp_id.'" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
  5584. }
  5585. $return .= '<div id="message"></div>';
  5586. if (count($this->items) == 0) {
  5587. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5588. } else {
  5589. $return_audio = '<table class="data_table">';
  5590. $return_audio .= '<tr>';
  5591. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5592. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5593. $return_audio .= '</tr>';
  5594. if ($update_audio != 'true') {
  5595. $return .= '<div class="col-md-12">';
  5596. $return .= self::return_new_tree($update_audio);
  5597. $return .= '</div>';
  5598. $return .= Display::div(
  5599. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5600. ['style' => 'float:left; margin-top:15px;width:100%']
  5601. );
  5602. } else {
  5603. $return_audio .= self::return_new_tree($update_audio);
  5604. $return .= $return_audio.'</table>';
  5605. }
  5606. // We need to close the form when we are updating the mp3 files.
  5607. if ($update_audio == 'true') {
  5608. $return .= '<div class="footer-audio">';
  5609. $return .= Display::button(
  5610. 'save_audio',
  5611. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5612. ['class' => 'btn btn-primary', 'type' => 'submit']
  5613. );
  5614. $return .= '</div>';
  5615. }
  5616. }
  5617. // We need to close the form when we are updating the mp3 files.
  5618. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5619. $return .= '</form>';
  5620. }
  5621. return $return;
  5622. }
  5623. /**
  5624. * @param string string $update_audio
  5625. * @param bool $drop_element_here
  5626. *
  5627. * @return string
  5628. */
  5629. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5630. {
  5631. $return = '';
  5632. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5633. $course_id = api_get_course_int_id();
  5634. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  5635. $sql = "SELECT * FROM $tbl_lp_item
  5636. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5637. $result = Database::query($sql);
  5638. $arrLP = [];
  5639. while ($row = Database::fetch_array($result)) {
  5640. $arrLP[] = [
  5641. 'id' => $row['id'],
  5642. 'item_type' => $row['item_type'],
  5643. 'title' => Security::remove_XSS($row['title']),
  5644. 'path' => $row['path'],
  5645. 'description' => Security::remove_XSS($row['description']),
  5646. 'parent_item_id' => $row['parent_item_id'],
  5647. 'previous_item_id' => $row['previous_item_id'],
  5648. 'next_item_id' => $row['next_item_id'],
  5649. 'max_score' => $row['max_score'],
  5650. 'min_score' => $row['min_score'],
  5651. 'mastery_score' => $row['mastery_score'],
  5652. 'prerequisite' => $row['prerequisite'],
  5653. 'display_order' => $row['display_order'],
  5654. 'audio' => $row['audio'],
  5655. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5656. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5657. ];
  5658. }
  5659. $this->tree_array($arrLP);
  5660. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  5661. unset($this->arrMenu);
  5662. $default_data = null;
  5663. $default_content = null;
  5664. $elements = [];
  5665. $return_audio = null;
  5666. for ($i = 0; $i < count($arrLP); $i++) {
  5667. $title = $arrLP[$i]['title'];
  5668. $title_cut = cut($arrLP[$i]['title'], 25);
  5669. // Link for the documents
  5670. if ($arrLP[$i]['item_type'] == 'document') {
  5671. $url = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5672. $title_cut = Display::url(
  5673. $title_cut,
  5674. $url,
  5675. [
  5676. 'class' => 'ajax moved',
  5677. 'data-title' => $title,
  5678. 'title' => $title,
  5679. ]
  5680. );
  5681. }
  5682. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5683. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5684. Session::write('pathItem', $arrLP[$i]['path']);
  5685. }
  5686. if (($i % 2) == 0) {
  5687. $oddClass = 'row_odd';
  5688. } else {
  5689. $oddClass = 'row_even';
  5690. }
  5691. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5692. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5693. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  5694. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5695. } else {
  5696. if (file_exists('../img/lp_'.$icon_name.'.gif')) {
  5697. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5698. } else {
  5699. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5700. $icon = Display::return_icon('certificate.png');
  5701. } else {
  5702. $icon = Display::return_icon('folder_document.gif');
  5703. }
  5704. }
  5705. }
  5706. // The audio column.
  5707. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5708. $audio = '';
  5709. if (!$update_audio || $update_audio != 'true') {
  5710. if (empty($arrLP[$i]['audio'])) {
  5711. $audio .= '';
  5712. }
  5713. } else {
  5714. $types = self::getChapterTypes();
  5715. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5716. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5717. if (!empty($arrLP[$i]['audio'])) {
  5718. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5719. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5720. }
  5721. }
  5722. }
  5723. $return_audio .= Display::span($icon.' '.$title).
  5724. Display::tag(
  5725. 'td',
  5726. $audio,
  5727. ['style' => '']
  5728. );
  5729. $return_audio .= '</td>';
  5730. $move_icon = '';
  5731. $move_item_icon = '';
  5732. $edit_icon = '';
  5733. $delete_icon = '';
  5734. $audio_icon = '';
  5735. $prerequisities_icon = '';
  5736. $forumIcon = '';
  5737. $previewIcon = '';
  5738. if ($is_allowed_to_edit) {
  5739. if (!$update_audio || $update_audio != 'true') {
  5740. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5741. $move_icon .= '<a class="moved" href="#">';
  5742. $move_icon .= Display::return_icon(
  5743. 'move_everywhere.png',
  5744. get_lang('Move'),
  5745. [],
  5746. ICON_SIZE_TINY
  5747. );
  5748. $move_icon .= '</a>';
  5749. }
  5750. }
  5751. // No edit for this item types
  5752. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5753. if ($arrLP[$i]['item_type'] != 'dir') {
  5754. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5755. $edit_icon .= Display::return_icon(
  5756. 'edit.png',
  5757. get_lang('LearnpathEditModule'),
  5758. [],
  5759. ICON_SIZE_TINY
  5760. );
  5761. $edit_icon .= '</a>';
  5762. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5763. $forumThread = null;
  5764. if (isset($this->items[$arrLP[$i]['id']])) {
  5765. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5766. $this->course_int_id,
  5767. $this->lp_session_id
  5768. );
  5769. }
  5770. if ($forumThread) {
  5771. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5772. 'action' => 'dissociate_forum',
  5773. 'id' => $arrLP[$i]['id'],
  5774. 'lp_id' => $this->lp_id,
  5775. ]);
  5776. $forumIcon = Display::url(
  5777. Display::return_icon(
  5778. 'forum.png',
  5779. get_lang('DissociateForumToLPItem'),
  5780. [],
  5781. ICON_SIZE_TINY
  5782. ),
  5783. $forumIconUrl,
  5784. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5785. );
  5786. } else {
  5787. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5788. 'action' => 'create_forum',
  5789. 'id' => $arrLP[$i]['id'],
  5790. 'lp_id' => $this->lp_id,
  5791. ]);
  5792. $forumIcon = Display::url(
  5793. Display::return_icon(
  5794. 'forum.png',
  5795. get_lang('AssociateForumToLPItem'),
  5796. [],
  5797. ICON_SIZE_TINY
  5798. ),
  5799. $forumIconUrl,
  5800. ['class' => "btn btn-default lp-btn-associate-forum"]
  5801. );
  5802. }
  5803. }
  5804. } else {
  5805. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5806. $edit_icon .= Display::return_icon(
  5807. 'edit.png',
  5808. get_lang('LearnpathEditModule'),
  5809. [],
  5810. ICON_SIZE_TINY
  5811. );
  5812. $edit_icon .= '</a>';
  5813. }
  5814. } else {
  5815. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5816. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5817. $edit_icon .= Display::return_icon(
  5818. 'edit.png',
  5819. get_lang('Edit'),
  5820. [],
  5821. ICON_SIZE_TINY
  5822. );
  5823. $edit_icon .= '</a>';
  5824. }
  5825. }
  5826. $delete_icon .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" onclick="return confirmation(\''.addslashes($title).'\');" class="btn btn-default">';
  5827. $delete_icon .= Display::return_icon(
  5828. 'delete.png',
  5829. get_lang('LearnpathDeleteModule'),
  5830. [],
  5831. ICON_SIZE_TINY
  5832. );
  5833. $delete_icon .= '</a>';
  5834. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5835. $previewImage = Display::return_icon(
  5836. 'preview_view.png',
  5837. get_lang('Preview'),
  5838. [],
  5839. ICON_SIZE_TINY
  5840. );
  5841. switch ($arrLP[$i]['item_type']) {
  5842. case TOOL_DOCUMENT:
  5843. case TOOL_LP_FINAL_ITEM:
  5844. $urlPreviewLink = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5845. $previewIcon = Display::url(
  5846. $previewImage,
  5847. $urlPreviewLink,
  5848. [
  5849. 'target' => '_blank',
  5850. 'class' => 'btn btn-default',
  5851. 'data-title' => $arrLP[$i]['title'],
  5852. 'title' => $arrLP[$i]['title'],
  5853. ]
  5854. );
  5855. break;
  5856. case TOOL_THREAD:
  5857. case TOOL_FORUM:
  5858. case TOOL_QUIZ:
  5859. case TOOL_STUDENTPUBLICATION:
  5860. case TOOL_LP_FINAL_ITEM:
  5861. case TOOL_LINK:
  5862. //$target = '';
  5863. //$class = 'btn btn-default ajax';
  5864. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5865. $class = 'btn btn-default';
  5866. $target = '_blank';
  5867. //}
  5868. $link = self::rl_get_resource_link_for_learnpath(
  5869. $this->course_int_id,
  5870. $this->lp_id,
  5871. $arrLP[$i]['id'],
  5872. 0,
  5873. ''
  5874. );
  5875. $previewIcon = Display::url(
  5876. $previewImage,
  5877. $link,
  5878. [
  5879. 'class' => $class,
  5880. 'data-title' => $arrLP[$i]['title'],
  5881. 'title' => $arrLP[$i]['title'],
  5882. 'target' => $target,
  5883. ]
  5884. );
  5885. break;
  5886. default:
  5887. $previewIcon = Display::url(
  5888. $previewImage,
  5889. $url.'&action=view_item',
  5890. ['class' => 'btn btn-default', 'target' => '_blank']
  5891. );
  5892. break;
  5893. }
  5894. if ($arrLP[$i]['item_type'] != 'dir') {
  5895. $prerequisities_icon = Display::url(
  5896. Display::return_icon(
  5897. 'accept.png',
  5898. get_lang('LearnpathPrerequisites'),
  5899. [],
  5900. ICON_SIZE_TINY
  5901. ),
  5902. $url.'&action=edit_item_prereq',
  5903. ['class' => 'btn btn-default']
  5904. );
  5905. if ($arrLP[$i]['item_type'] != 'final_item') {
  5906. $move_item_icon = Display::url(
  5907. Display::return_icon(
  5908. 'move.png',
  5909. get_lang('Move'),
  5910. [],
  5911. ICON_SIZE_TINY
  5912. ),
  5913. $url.'&action=move_item',
  5914. ['class' => 'btn btn-default']
  5915. );
  5916. }
  5917. $audio_icon = Display::url(
  5918. Display::return_icon(
  5919. 'audio.png',
  5920. get_lang('UplUpload'),
  5921. [],
  5922. ICON_SIZE_TINY
  5923. ),
  5924. $url.'&action=add_audio',
  5925. ['class' => 'btn btn-default']
  5926. );
  5927. }
  5928. }
  5929. if ($update_audio != 'true') {
  5930. $row = $move_icon.' '.$icon.
  5931. Display::span($title_cut).
  5932. Display::tag(
  5933. 'div',
  5934. "<div class=\"btn-group btn-group-xs\">$previewIcon $audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
  5935. ['class' => 'btn-toolbar button_actions']
  5936. );
  5937. } else {
  5938. $row = Display::span($title.$icon).Display::span($audio, ['class' => 'button_actions']);
  5939. }
  5940. $parent_id = $arrLP[$i]['parent_item_id'];
  5941. $default_data[$arrLP[$i]['id']] = $row;
  5942. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5943. if (empty($parent_id)) {
  5944. $elements[$arrLP[$i]['id']]['data'] = $row;
  5945. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5946. } else {
  5947. $parent_arrays = [];
  5948. if ($arrLP[$i]['depth'] > 1) {
  5949. //Getting list of parents
  5950. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5951. foreach ($arrLP as $item) {
  5952. if ($item['id'] == $parent_id) {
  5953. if ($item['parent_item_id'] == 0) {
  5954. $parent_id = $item['id'];
  5955. break;
  5956. } else {
  5957. $parent_id = $item['parent_item_id'];
  5958. if (empty($parent_arrays)) {
  5959. $parent_arrays[] = intval($item['id']);
  5960. }
  5961. $parent_arrays[] = $parent_id;
  5962. break;
  5963. }
  5964. }
  5965. }
  5966. }
  5967. }
  5968. if (!empty($parent_arrays)) {
  5969. $parent_arrays = array_reverse($parent_arrays);
  5970. $val = '$elements';
  5971. $x = 0;
  5972. foreach ($parent_arrays as $item) {
  5973. if ($x != count($parent_arrays) - 1) {
  5974. $val .= '["'.$item.'"]["children"]';
  5975. } else {
  5976. $val .= '["'.$item.'"]["children"]';
  5977. }
  5978. $x++;
  5979. }
  5980. $val .= "";
  5981. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5982. eval($code_str);
  5983. } else {
  5984. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5985. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5986. }
  5987. }
  5988. }
  5989. $list = '<ul id="lp_item_list">';
  5990. $tree = self::print_recursive(
  5991. $elements,
  5992. $default_data,
  5993. $default_content
  5994. );
  5995. if (!empty($tree)) {
  5996. $list .= $tree;
  5997. } else {
  5998. if ($drop_element_here) {
  5999. $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
  6000. }
  6001. }
  6002. $list .= '</ul>';
  6003. $return .= Display::panelCollapse(
  6004. $this->name,
  6005. $list,
  6006. 'scorm-list',
  6007. null,
  6008. 'scorm-list-accordion',
  6009. 'scorm-list-collapse'
  6010. );
  6011. if ($update_audio == 'true') {
  6012. $return = $return_audio;
  6013. }
  6014. return $return;
  6015. }
  6016. /**
  6017. * @param array $elements
  6018. * @param array $default_data
  6019. * @param array $default_content
  6020. *
  6021. * @return string
  6022. */
  6023. public function print_recursive($elements, $default_data, $default_content)
  6024. {
  6025. $return = '';
  6026. foreach ($elements as $key => $item) {
  6027. if (isset($item['load_data']) || empty($item['data'])) {
  6028. $item['data'] = $default_data[$item['load_data']];
  6029. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6030. }
  6031. $sub_list = '';
  6032. if (isset($item['type']) && $item['type'] == 'dir') {
  6033. // empty value
  6034. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6035. }
  6036. if (empty($item['children'])) {
  6037. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6038. $active = null;
  6039. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6040. $active = 'active';
  6041. }
  6042. $return .= Display::tag(
  6043. 'li',
  6044. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6045. ['id' => $key, 'class' => 'record li_container']
  6046. );
  6047. } else {
  6048. // Sections
  6049. if (isset($item['children'])) {
  6050. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6051. }
  6052. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6053. $return .= Display::tag(
  6054. 'li',
  6055. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6056. ['id' => $key, 'class' => 'record li_container']
  6057. );
  6058. }
  6059. }
  6060. return $return;
  6061. }
  6062. /**
  6063. * This function builds the action menu.
  6064. *
  6065. * @param bool $returnContent Optional
  6066. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6067. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6068. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6069. *
  6070. * @return string
  6071. */
  6072. public function build_action_menu(
  6073. $returnContent = false,
  6074. $showRequirementButtons = true,
  6075. $isConfigPage = false,
  6076. $allowExpand = true
  6077. ) {
  6078. $actionsLeft = '';
  6079. $actionsRight = '';
  6080. $actionsLeft .= Display::url(
  6081. Display::return_icon(
  6082. 'preview_view.png',
  6083. get_lang('Preview'),
  6084. '',
  6085. ICON_SIZE_MEDIUM
  6086. ),
  6087. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6088. 'action' => 'view',
  6089. 'lp_id' => $this->lp_id,
  6090. 'isStudentView' => 'true',
  6091. ])
  6092. );
  6093. $actionsLeft .= Display::url(
  6094. Display::return_icon(
  6095. 'upload_audio.png',
  6096. get_lang('UpdateAllAudioFragments'),
  6097. '',
  6098. ICON_SIZE_MEDIUM
  6099. ),
  6100. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6101. 'action' => 'admin_view',
  6102. 'lp_id' => $this->lp_id,
  6103. 'updateaudio' => 'true',
  6104. ])
  6105. );
  6106. if (!$isConfigPage) {
  6107. $actionsLeft .= Display::url(
  6108. Display::return_icon(
  6109. 'settings.png',
  6110. get_lang('CourseSettings'),
  6111. '',
  6112. ICON_SIZE_MEDIUM
  6113. ),
  6114. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6115. 'action' => 'edit',
  6116. 'lp_id' => $this->lp_id,
  6117. ])
  6118. );
  6119. } else {
  6120. $actionsLeft .= Display::url(
  6121. Display::return_icon(
  6122. 'edit.png',
  6123. get_lang('Edit'),
  6124. '',
  6125. ICON_SIZE_MEDIUM
  6126. ),
  6127. 'lp_controller.php?'.http_build_query([
  6128. 'action' => 'build',
  6129. 'lp_id' => $this->lp_id,
  6130. ]).'&'.api_get_cidreq()
  6131. );
  6132. }
  6133. if ($allowExpand) {
  6134. $actionsLeft .= Display::url(
  6135. Display::return_icon(
  6136. 'expand.png',
  6137. get_lang('Expand'),
  6138. ['id' => 'expand'],
  6139. ICON_SIZE_MEDIUM
  6140. ).
  6141. Display::return_icon(
  6142. 'contract.png',
  6143. get_lang('Collapse'),
  6144. ['id' => 'contract', 'class' => 'hide'],
  6145. ICON_SIZE_MEDIUM
  6146. ),
  6147. '#',
  6148. ['role' => 'button', 'id' => 'hide_bar_template']
  6149. );
  6150. }
  6151. if ($showRequirementButtons) {
  6152. $buttons = [
  6153. [
  6154. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6155. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6156. 'action' => 'set_previous_step_as_prerequisite',
  6157. 'lp_id' => $this->lp_id,
  6158. ]),
  6159. ],
  6160. [
  6161. 'title' => get_lang('ClearAllPrerequisites'),
  6162. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6163. 'action' => 'clear_prerequisites',
  6164. 'lp_id' => $this->lp_id,
  6165. ]),
  6166. ],
  6167. ];
  6168. $actionsRight = Display::groupButtonWithDropDown(
  6169. get_lang('PrerequisitesOptions'),
  6170. $buttons,
  6171. true
  6172. );
  6173. }
  6174. $toolbar = Display::toolbarAction(
  6175. 'actions-lp-controller',
  6176. [$actionsLeft, $actionsRight]
  6177. );
  6178. if ($returnContent) {
  6179. return $toolbar;
  6180. }
  6181. echo $toolbar;
  6182. }
  6183. /**
  6184. * Creates the default learning path folder.
  6185. *
  6186. * @param array $course
  6187. * @param int $creatorId
  6188. *
  6189. * @return bool
  6190. */
  6191. public static function generate_learning_path_folder($course, $creatorId = 0)
  6192. {
  6193. // Creating learning_path folder
  6194. $dir = '/learning_path';
  6195. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6196. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6197. $folder = false;
  6198. if (!is_dir($filepath.'/'.$dir)) {
  6199. $folderData = create_unexisting_directory(
  6200. $course,
  6201. $creatorId,
  6202. 0,
  6203. null,
  6204. 0,
  6205. $filepath,
  6206. $dir,
  6207. get_lang('LearningPaths'),
  6208. 0
  6209. );
  6210. if (!empty($folderData)) {
  6211. $folder = true;
  6212. }
  6213. } else {
  6214. $folder = true;
  6215. }
  6216. return $folder;
  6217. }
  6218. /**
  6219. * @param array $course
  6220. * @param string $lp_name
  6221. * @param int $creatorId
  6222. *
  6223. * @return array
  6224. */
  6225. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6226. {
  6227. $filepath = '';
  6228. $dir = '/learning_path/';
  6229. if (empty($lp_name)) {
  6230. $lp_name = $this->name;
  6231. }
  6232. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6233. $folder = self::generate_learning_path_folder($course, $creatorId);
  6234. // Limits title size
  6235. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6236. $dir = $dir.$title;
  6237. // Creating LP folder
  6238. $documentId = null;
  6239. if ($folder) {
  6240. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6241. if (!is_dir($filepath.'/'.$dir)) {
  6242. $folderData = create_unexisting_directory(
  6243. $course,
  6244. $creatorId,
  6245. 0,
  6246. 0,
  6247. 0,
  6248. $filepath,
  6249. $dir,
  6250. $lp_name
  6251. );
  6252. if (!empty($folderData)) {
  6253. $folder = true;
  6254. }
  6255. $documentId = $folderData['id'];
  6256. } else {
  6257. $folder = true;
  6258. }
  6259. $dir = $dir.'/';
  6260. if ($folder) {
  6261. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6262. }
  6263. }
  6264. if (empty($documentId)) {
  6265. $dir = api_remove_trailing_slash($dir);
  6266. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6267. }
  6268. $array = [
  6269. 'dir' => $dir,
  6270. 'filepath' => $filepath,
  6271. 'folder' => $folder,
  6272. 'id' => $documentId,
  6273. ];
  6274. return $array;
  6275. }
  6276. /**
  6277. * Create a new document //still needs some finetuning.
  6278. *
  6279. * @param array $courseInfo
  6280. * @param string $content
  6281. * @param string $title
  6282. * @param string $extension
  6283. * @param int $parentId
  6284. * @param int $creatorId creator id
  6285. *
  6286. * @return int
  6287. */
  6288. public function create_document(
  6289. $courseInfo,
  6290. $content = '',
  6291. $title = '',
  6292. $extension = 'html',
  6293. $parentId = 0,
  6294. $creatorId = 0
  6295. ) {
  6296. if (!empty($courseInfo)) {
  6297. $course_id = $courseInfo['real_id'];
  6298. } else {
  6299. $course_id = api_get_course_int_id();
  6300. }
  6301. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6302. $sessionId = api_get_session_id();
  6303. // Generates folder
  6304. $result = $this->generate_lp_folder($courseInfo);
  6305. $dir = $result['dir'];
  6306. if (empty($parentId) || $parentId == '/') {
  6307. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6308. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6309. if ($parentId === '/') {
  6310. $dir = '/';
  6311. }
  6312. // Please, do not modify this dirname formatting.
  6313. if (strstr($dir, '..')) {
  6314. $dir = '/';
  6315. }
  6316. if (!empty($dir[0]) && $dir[0] == '.') {
  6317. $dir = substr($dir, 1);
  6318. }
  6319. if (!empty($dir[0]) && $dir[0] != '/') {
  6320. $dir = '/'.$dir;
  6321. }
  6322. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6323. $dir .= '/';
  6324. }
  6325. } else {
  6326. $parentInfo = DocumentManager::get_document_data_by_id(
  6327. $parentId,
  6328. $courseInfo['code']
  6329. );
  6330. if (!empty($parentInfo)) {
  6331. $dir = $parentInfo['path'].'/';
  6332. }
  6333. }
  6334. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6335. if (!is_dir($filepath)) {
  6336. $dir = '/';
  6337. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6338. }
  6339. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6340. // is already escaped twice when it gets here.
  6341. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6342. if (!empty($title)) {
  6343. $title = api_replace_dangerous_char(stripslashes($title));
  6344. } else {
  6345. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6346. }
  6347. $title = disable_dangerous_file($title);
  6348. $filename = $title;
  6349. $content = !empty($content) ? $content : $_POST['content_lp'];
  6350. $tmp_filename = $filename;
  6351. $i = 0;
  6352. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6353. $tmp_filename = $filename.'_'.++$i;
  6354. }
  6355. $filename = $tmp_filename.'.'.$extension;
  6356. if ($extension == 'html') {
  6357. $content = stripslashes($content);
  6358. $content = str_replace(
  6359. api_get_path(WEB_COURSE_PATH),
  6360. api_get_path(REL_PATH).'courses/',
  6361. $content
  6362. );
  6363. // Change the path of mp3 to absolute.
  6364. // The first regexp deals with :// urls.
  6365. $content = preg_replace(
  6366. "|(flashvars=\"file=)([^:/]+)/|",
  6367. "$1".api_get_path(
  6368. REL_COURSE_PATH
  6369. ).$courseInfo['path'].'/document/',
  6370. $content
  6371. );
  6372. // The second regexp deals with audio/ urls.
  6373. $content = preg_replace(
  6374. "|(flashvars=\"file=)([^/]+)/|",
  6375. "$1".api_get_path(
  6376. REL_COURSE_PATH
  6377. ).$courseInfo['path'].'/document/$2/',
  6378. $content
  6379. );
  6380. // For flv player: To prevent edition problem with firefox,
  6381. // we have to use a strange tip (don't blame me please).
  6382. $content = str_replace(
  6383. '</body>',
  6384. '<style type="text/css">body{}</style></body>',
  6385. $content
  6386. );
  6387. }
  6388. if (!file_exists($filepath.$filename)) {
  6389. if ($fp = @fopen($filepath.$filename, 'w')) {
  6390. fputs($fp, $content);
  6391. fclose($fp);
  6392. $file_size = filesize($filepath.$filename);
  6393. $save_file_path = $dir.$filename;
  6394. $document_id = add_document(
  6395. $courseInfo,
  6396. $save_file_path,
  6397. 'file',
  6398. $file_size,
  6399. $tmp_filename,
  6400. '',
  6401. 0, //readonly
  6402. true,
  6403. null,
  6404. $sessionId,
  6405. $creatorId
  6406. );
  6407. if ($document_id) {
  6408. api_item_property_update(
  6409. $courseInfo,
  6410. TOOL_DOCUMENT,
  6411. $document_id,
  6412. 'DocumentAdded',
  6413. $creatorId,
  6414. null,
  6415. null,
  6416. null,
  6417. null,
  6418. $sessionId
  6419. );
  6420. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6421. $new_title = $originalTitle;
  6422. if ($new_comment || $new_title) {
  6423. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6424. $ct = '';
  6425. if ($new_comment) {
  6426. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6427. }
  6428. if ($new_title) {
  6429. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6430. }
  6431. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6432. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6433. Database::query($sql);
  6434. }
  6435. }
  6436. return $document_id;
  6437. }
  6438. }
  6439. }
  6440. /**
  6441. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6442. *
  6443. * @param array $_course array
  6444. */
  6445. public function edit_document($_course)
  6446. {
  6447. $course_id = api_get_course_int_id();
  6448. $urlAppend = api_get_configuration_value('url_append');
  6449. // Please, do not modify this dirname formatting.
  6450. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6451. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6452. if (strstr($dir, '..')) {
  6453. $dir = '/';
  6454. }
  6455. if (isset($dir[0]) && $dir[0] == '.') {
  6456. $dir = substr($dir, 1);
  6457. }
  6458. if (isset($dir[0]) && $dir[0] != '/') {
  6459. $dir = '/'.$dir;
  6460. }
  6461. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6462. $dir .= '/';
  6463. }
  6464. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6465. if (!is_dir($filepath)) {
  6466. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6467. }
  6468. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6469. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6470. $document_id = intval($_POST['path']);
  6471. $sql = "SELECT path FROM ".$table_doc."
  6472. WHERE c_id = $course_id AND id = ".$document_id;
  6473. $res = Database::query($sql);
  6474. $row = Database::fetch_array($res);
  6475. $content = stripslashes($_POST['content_lp']);
  6476. $file = $filepath.$row['path'];
  6477. if ($fp = @fopen($file, 'w')) {
  6478. $content = str_replace(
  6479. api_get_path(WEB_COURSE_PATH),
  6480. $urlAppend.api_get_path(REL_COURSE_PATH),
  6481. $content
  6482. );
  6483. // Change the path of mp3 to absolute.
  6484. // The first regexp deals with :// urls.
  6485. $content = preg_replace(
  6486. "|(flashvars=\"file=)([^:/]+)/|",
  6487. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6488. $content
  6489. );
  6490. // The second regexp deals with audio/ urls.
  6491. $content = preg_replace(
  6492. "|(flashvars=\"file=)([^:/]+)/|",
  6493. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6494. $content
  6495. );
  6496. fputs($fp, $content);
  6497. fclose($fp);
  6498. $sql = "UPDATE ".$table_doc." SET
  6499. title='".Database::escape_string($_POST['title'])."'
  6500. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6501. Database::query($sql);
  6502. }
  6503. }
  6504. }
  6505. /**
  6506. * Displays the selected item, with a panel for manipulating the item.
  6507. *
  6508. * @param int $item_id
  6509. * @param string $msg
  6510. * @param bool $show_actions
  6511. *
  6512. * @return string
  6513. */
  6514. public function display_item($item_id, $msg = null, $show_actions = true)
  6515. {
  6516. $course_id = api_get_course_int_id();
  6517. $return = '';
  6518. if (is_numeric($item_id)) {
  6519. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6520. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6521. WHERE lp.iid = ".intval($item_id);
  6522. $result = Database::query($sql);
  6523. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6524. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6525. // Prevents wrong parent selection for document, see Bug#1251.
  6526. if ($row['item_type'] != 'dir') {
  6527. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6528. }
  6529. if ($show_actions) {
  6530. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6531. }
  6532. $return .= '<div style="padding:10px;">';
  6533. if ($msg != '') {
  6534. $return .= $msg;
  6535. }
  6536. $return .= '<h3>'.$row['title'].'</h3>';
  6537. switch ($row['item_type']) {
  6538. case TOOL_THREAD:
  6539. $link = $this->rl_get_resource_link_for_learnpath(
  6540. $course_id,
  6541. $row['lp_id'],
  6542. $item_id,
  6543. 0
  6544. );
  6545. $return .= Display::url(
  6546. get_lang('GoToThread'),
  6547. $link,
  6548. ['class' => 'btn btn-primary']
  6549. );
  6550. break;
  6551. case TOOL_FORUM:
  6552. $return .= Display::url(
  6553. get_lang('GoToForum'),
  6554. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6555. ['class' => 'btn btn-primary']
  6556. );
  6557. break;
  6558. case TOOL_QUIZ:
  6559. if (!empty($row['path'])) {
  6560. $exercise = new Exercise();
  6561. $exercise->read($row['path']);
  6562. $return .= $exercise->description.'<br />';
  6563. $return .= Display::url(
  6564. get_lang('GoToExercise'),
  6565. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6566. ['class' => 'btn btn-primary']
  6567. );
  6568. }
  6569. break;
  6570. case TOOL_LP_FINAL_ITEM:
  6571. $return .= $this->getSavedFinalItem();
  6572. break;
  6573. case TOOL_DOCUMENT:
  6574. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6575. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6576. WHERE c_id = ".$course_id." AND iid = ".intval($row['path']);
  6577. $result = Database::query($sql_doc);
  6578. $path_file = Database::result($result, 0, 0);
  6579. $path_parts = pathinfo($path_file);
  6580. // TODO: Correct the following naive comparisons.
  6581. if (in_array($path_parts['extension'], [
  6582. 'html',
  6583. 'txt',
  6584. 'png',
  6585. 'jpg',
  6586. 'JPG',
  6587. 'jpeg',
  6588. 'JPEG',
  6589. 'gif',
  6590. 'swf',
  6591. 'pdf',
  6592. 'htm',
  6593. ])) {
  6594. $return .= $this->display_document($row['path'], true, true);
  6595. }
  6596. break;
  6597. case TOOL_HOTPOTATOES:
  6598. $return .= $this->display_document($row['path'], false, true);
  6599. break;
  6600. }
  6601. $return .= '</div>';
  6602. }
  6603. }
  6604. return $return;
  6605. }
  6606. /**
  6607. * Shows the needed forms for editing a specific item.
  6608. *
  6609. * @param int $item_id
  6610. *
  6611. * @return string
  6612. */
  6613. public function display_edit_item($item_id)
  6614. {
  6615. $course_id = api_get_course_int_id();
  6616. $return = '';
  6617. if (is_numeric($item_id)) {
  6618. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6619. $sql = "SELECT * FROM $tbl_lp_item
  6620. WHERE iid = ".intval($item_id);
  6621. $res = Database::query($sql);
  6622. $row = Database::fetch_array($res);
  6623. switch ($row['item_type']) {
  6624. case 'dir':
  6625. case 'asset':
  6626. case 'sco':
  6627. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6628. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6629. $return .= $this->display_item_form(
  6630. $row['item_type'],
  6631. get_lang('EditCurrentChapter').' :',
  6632. 'edit',
  6633. $item_id,
  6634. $row
  6635. );
  6636. } else {
  6637. $return .= $this->display_item_small_form(
  6638. $row['item_type'],
  6639. get_lang('EditCurrentChapter').' :',
  6640. $row
  6641. );
  6642. }
  6643. break;
  6644. case TOOL_DOCUMENT:
  6645. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6646. $sql = "SELECT lp.*, doc.path as dir
  6647. FROM $tbl_lp_item as lp
  6648. LEFT JOIN $tbl_doc as doc
  6649. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6650. WHERE
  6651. doc.c_id = $course_id AND
  6652. lp.iid = ".intval($item_id);
  6653. $res_step = Database::query($sql);
  6654. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6655. $return .= $this->display_manipulate(
  6656. $item_id,
  6657. $row['item_type']
  6658. );
  6659. $return .= $this->display_document_form(
  6660. 'edit',
  6661. $item_id,
  6662. $row_step
  6663. );
  6664. break;
  6665. case TOOL_LINK:
  6666. $link_id = (string) $row['path'];
  6667. if (ctype_digit($link_id)) {
  6668. $tbl_link = Database::get_course_table(TABLE_LINK);
  6669. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6670. WHERE c_id = '.$course_id.' AND iid = '.intval($link_id);
  6671. $res_link = Database::query($sql_select);
  6672. $row_link = Database::fetch_array($res_link);
  6673. if (is_array($row_link)) {
  6674. $row['url'] = $row_link['url'];
  6675. }
  6676. }
  6677. $return .= $this->display_manipulate(
  6678. $item_id,
  6679. $row['item_type']
  6680. );
  6681. $return .= $this->display_link_form('edit', $item_id, $row);
  6682. break;
  6683. case TOOL_LP_FINAL_ITEM:
  6684. Session::write('finalItem', true);
  6685. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6686. $sql = "SELECT lp.*, doc.path as dir
  6687. FROM $tbl_lp_item as lp
  6688. LEFT JOIN $tbl_doc as doc
  6689. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6690. WHERE
  6691. doc.c_id = $course_id AND
  6692. lp.iid = ".intval($item_id);
  6693. $res_step = Database::query($sql);
  6694. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6695. $return .= $this->display_manipulate(
  6696. $item_id,
  6697. $row['item_type']
  6698. );
  6699. $return .= $this->display_document_form(
  6700. 'edit',
  6701. $item_id,
  6702. $row_step
  6703. );
  6704. break;
  6705. case TOOL_QUIZ:
  6706. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6707. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6708. break;
  6709. case TOOL_HOTPOTATOES:
  6710. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6711. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6712. break;
  6713. case TOOL_STUDENTPUBLICATION:
  6714. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6715. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6716. break;
  6717. case TOOL_FORUM:
  6718. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6719. $return .= $this->display_forum_form('edit', $item_id, $row);
  6720. break;
  6721. case TOOL_THREAD:
  6722. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6723. $return .= $this->display_thread_form('edit', $item_id, $row);
  6724. break;
  6725. }
  6726. }
  6727. return $return;
  6728. }
  6729. /**
  6730. * Function that displays a list with al the resources that
  6731. * could be added to the learning path.
  6732. *
  6733. * @return bool
  6734. */
  6735. public function display_resources()
  6736. {
  6737. $course_code = api_get_course_id();
  6738. // Get all the docs.
  6739. $documents = $this->get_documents(true);
  6740. // Get all the exercises.
  6741. $exercises = $this->get_exercises();
  6742. // Get all the links.
  6743. $links = $this->get_links();
  6744. // Get all the student publications.
  6745. $works = $this->get_student_publications();
  6746. // Get all the forums.
  6747. $forums = $this->get_forums(null, $course_code);
  6748. // Get the final item form (see BT#11048) .
  6749. $finish = $this->getFinalItemForm();
  6750. $headers = [
  6751. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6752. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6753. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6754. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6755. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6756. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6757. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6758. ];
  6759. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6760. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6761. echo Display::tabs(
  6762. $headers,
  6763. [
  6764. $documents,
  6765. $exercises,
  6766. $links,
  6767. $works,
  6768. $forums,
  6769. $dir,
  6770. $finish,
  6771. ],
  6772. 'resource_tab'
  6773. );
  6774. return true;
  6775. }
  6776. /**
  6777. * Returns the extension of a document.
  6778. *
  6779. * @param string $filename
  6780. *
  6781. * @return string Extension (part after the last dot)
  6782. */
  6783. public function get_extension($filename)
  6784. {
  6785. $explode = explode('.', $filename);
  6786. return $explode[count($explode) - 1];
  6787. }
  6788. /**
  6789. * Displays a document by id.
  6790. *
  6791. * @param int $id
  6792. *
  6793. * @return string
  6794. */
  6795. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6796. {
  6797. $_course = api_get_course_info();
  6798. $course_id = api_get_course_int_id();
  6799. $id = (int) $id;
  6800. $return = '';
  6801. $table = Database::get_course_table(TABLE_DOCUMENT);
  6802. $sql_doc = "SELECT * FROM $table
  6803. WHERE c_id = $course_id AND iid = $id";
  6804. $res_doc = Database::query($sql_doc);
  6805. $row_doc = Database::fetch_array($res_doc);
  6806. // TODO: Add a path filter.
  6807. if ($iframe) {
  6808. $return .= '<iframe id="learnpath_preview_frame" frameborder="0" height="400" width="100%" scrolling="auto" src="'.api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.str_replace('%2F', '/', urlencode($row_doc['path'])).'?'.api_get_cidreq().'"></iframe>';
  6809. } else {
  6810. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6811. }
  6812. return $return;
  6813. }
  6814. /**
  6815. * Return HTML form to add/edit a quiz.
  6816. *
  6817. * @param string $action Action (add/edit)
  6818. * @param int $id Item ID if already exists
  6819. * @param mixed $extra_info Extra information (quiz ID if integer)
  6820. *
  6821. * @return string HTML form
  6822. */
  6823. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6824. {
  6825. $course_id = api_get_course_int_id();
  6826. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6827. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6828. if ($id != 0 && is_array($extra_info)) {
  6829. $item_title = $extra_info['title'];
  6830. $item_description = $extra_info['description'];
  6831. } elseif (is_numeric($extra_info)) {
  6832. $sql = "SELECT title, description
  6833. FROM $tbl_quiz
  6834. WHERE c_id = $course_id AND iid = ".$extra_info;
  6835. $result = Database::query($sql);
  6836. $row = Database::fetch_array($result);
  6837. $item_title = $row['title'];
  6838. $item_description = $row['description'];
  6839. } else {
  6840. $item_title = '';
  6841. $item_description = '';
  6842. }
  6843. $item_title = Security::remove_XSS($item_title);
  6844. $item_description = Security::remove_XSS($item_description);
  6845. if ($id != 0 && is_array($extra_info)) {
  6846. $parent = $extra_info['parent_item_id'];
  6847. } else {
  6848. $parent = 0;
  6849. }
  6850. $sql = "SELECT * FROM $tbl_lp_item
  6851. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6852. $result = Database::query($sql);
  6853. $arrLP = [];
  6854. while ($row = Database::fetch_array($result)) {
  6855. $arrLP[] = [
  6856. 'id' => $row['id'],
  6857. 'item_type' => $row['item_type'],
  6858. 'title' => $row['title'],
  6859. 'path' => $row['path'],
  6860. 'description' => $row['description'],
  6861. 'parent_item_id' => $row['parent_item_id'],
  6862. 'previous_item_id' => $row['previous_item_id'],
  6863. 'next_item_id' => $row['next_item_id'],
  6864. 'display_order' => $row['display_order'],
  6865. 'max_score' => $row['max_score'],
  6866. 'min_score' => $row['min_score'],
  6867. 'mastery_score' => $row['mastery_score'],
  6868. 'prerequisite' => $row['prerequisite'],
  6869. 'max_time_allowed' => $row['max_time_allowed'],
  6870. ];
  6871. }
  6872. $this->tree_array($arrLP);
  6873. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  6874. unset($this->arrMenu);
  6875. $form = new FormValidator(
  6876. 'quiz_form',
  6877. 'POST',
  6878. $this->getCurrentBuildingModeURL()
  6879. );
  6880. $defaults = [];
  6881. if ($action == 'add') {
  6882. $legend = get_lang('CreateTheExercise');
  6883. } elseif ($action == 'move') {
  6884. $legend = get_lang('MoveTheCurrentExercise');
  6885. } else {
  6886. $legend = get_lang('EditCurrentExecice');
  6887. }
  6888. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6889. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6890. }
  6891. $form->addHeader($legend);
  6892. if ($action != 'move') {
  6893. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  6894. $defaults['title'] = $item_title;
  6895. }
  6896. // Select for Parent item, root or chapter
  6897. $selectParent = $form->addSelect(
  6898. 'parent',
  6899. get_lang('Parent'),
  6900. [],
  6901. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6902. );
  6903. $selectParent->addOption($this->name, 0);
  6904. $arrHide = [
  6905. $id,
  6906. ];
  6907. for ($i = 0; $i < count($arrLP); $i++) {
  6908. if ($action != 'add') {
  6909. if (
  6910. ($arrLP[$i]['item_type'] == 'dir') &&
  6911. !in_array($arrLP[$i]['id'], $arrHide) &&
  6912. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6913. ) {
  6914. $selectParent->addOption(
  6915. $arrLP[$i]['title'],
  6916. $arrLP[$i]['id'],
  6917. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6918. );
  6919. if ($parent == $arrLP[$i]['id']) {
  6920. $selectParent->setSelected($arrLP[$i]['id']);
  6921. }
  6922. } else {
  6923. $arrHide[] = $arrLP[$i]['id'];
  6924. }
  6925. } else {
  6926. if ($arrLP[$i]['item_type'] == 'dir') {
  6927. $selectParent->addOption(
  6928. $arrLP[$i]['title'],
  6929. $arrLP[$i]['id'],
  6930. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6931. );
  6932. if ($parent == $arrLP[$i]['id']) {
  6933. $selectParent->setSelected($arrLP[$i]['id']);
  6934. }
  6935. }
  6936. }
  6937. }
  6938. if (is_array($arrLP)) {
  6939. reset($arrLP);
  6940. }
  6941. $selectPrevious = $form->addSelect(
  6942. 'previous',
  6943. get_lang('Position'),
  6944. [],
  6945. ['id' => 'previous']
  6946. );
  6947. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6948. for ($i = 0; $i < count($arrLP); $i++) {
  6949. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6950. $arrLP[$i]['id'] != $id
  6951. ) {
  6952. $selectPrevious->addOption(
  6953. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6954. $arrLP[$i]['id']
  6955. );
  6956. if (is_array($extra_info)) {
  6957. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6958. $selectPrevious->setSelected($arrLP[$i]['id']);
  6959. }
  6960. } elseif ($action == 'add') {
  6961. $selectPrevious->setSelected($arrLP[$i]['id']);
  6962. }
  6963. }
  6964. }
  6965. if ($action != 'move') {
  6966. $id_prerequisite = 0;
  6967. if (is_array($arrLP)) {
  6968. foreach ($arrLP as $key => $value) {
  6969. if ($value['id'] == $id) {
  6970. $id_prerequisite = $value['prerequisite'];
  6971. break;
  6972. }
  6973. }
  6974. }
  6975. $arrHide = [];
  6976. for ($i = 0; $i < count($arrLP); $i++) {
  6977. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6978. if (is_array($extra_info)) {
  6979. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6980. $s_selected_position = $arrLP[$i]['id'];
  6981. }
  6982. } elseif ($action == 'add') {
  6983. $s_selected_position = 0;
  6984. }
  6985. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6986. }
  6987. }
  6988. }
  6989. if ($action == 'add') {
  6990. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6991. } else {
  6992. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6993. }
  6994. if ($action == 'move') {
  6995. $form->addHidden('title', $item_title);
  6996. $form->addHidden('description', $item_description);
  6997. }
  6998. if (is_numeric($extra_info)) {
  6999. $form->addHidden('path', $extra_info);
  7000. } elseif (is_array($extra_info)) {
  7001. $form->addHidden('path', $extra_info['path']);
  7002. }
  7003. $form->addHidden('type', TOOL_QUIZ);
  7004. $form->addHidden('post_time', time());
  7005. $form->setDefaults($defaults);
  7006. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7007. }
  7008. /**
  7009. * Addition of Hotpotatoes tests.
  7010. *
  7011. * @param string Action
  7012. * @param int Internal ID of the item
  7013. * @param mixed Extra information - can be an array with title and description indexes
  7014. *
  7015. * @return string HTML structure to display the hotpotatoes addition formular
  7016. */
  7017. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7018. {
  7019. $course_id = api_get_course_int_id();
  7020. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7021. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7022. if ($id != 0 && is_array($extra_info)) {
  7023. $item_title = stripslashes($extra_info['title']);
  7024. $item_description = stripslashes($extra_info['description']);
  7025. } elseif (is_numeric($extra_info)) {
  7026. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7027. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7028. WHERE
  7029. c_id = ".$course_id." AND
  7030. path LIKE '".$uploadPath."/%/%htm%' AND
  7031. iid = ".(int) $extra_info."
  7032. ORDER BY iid ASC";
  7033. $res_hot = Database::query($sql);
  7034. $row = Database::fetch_array($res_hot);
  7035. $item_title = $row['title'];
  7036. $item_description = $row['description'];
  7037. if (!empty($row['comment'])) {
  7038. $item_title = $row['comment'];
  7039. }
  7040. } else {
  7041. $item_title = '';
  7042. $item_description = '';
  7043. }
  7044. if ($id != 0 && is_array($extra_info)) {
  7045. $parent = $extra_info['parent_item_id'];
  7046. } else {
  7047. $parent = 0;
  7048. }
  7049. $sql = "SELECT * FROM $tbl_lp_item
  7050. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7051. $result = Database::query($sql);
  7052. $arrLP = [];
  7053. while ($row = Database::fetch_array($result)) {
  7054. $arrLP[] = [
  7055. 'id' => $row['id'],
  7056. 'item_type' => $row['item_type'],
  7057. 'title' => $row['title'],
  7058. 'path' => $row['path'],
  7059. 'description' => $row['description'],
  7060. 'parent_item_id' => $row['parent_item_id'],
  7061. 'previous_item_id' => $row['previous_item_id'],
  7062. 'next_item_id' => $row['next_item_id'],
  7063. 'display_order' => $row['display_order'],
  7064. 'max_score' => $row['max_score'],
  7065. 'min_score' => $row['min_score'],
  7066. 'mastery_score' => $row['mastery_score'],
  7067. 'prerequisite' => $row['prerequisite'],
  7068. 'max_time_allowed' => $row['max_time_allowed'],
  7069. ];
  7070. }
  7071. $legend = '<legend>';
  7072. if ($action == 'add') {
  7073. $legend .= get_lang('CreateTheExercise');
  7074. } elseif ($action == 'move') {
  7075. $legend .= get_lang('MoveTheCurrentExercise');
  7076. } else {
  7077. $legend .= get_lang('EditCurrentExecice');
  7078. }
  7079. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7080. $legend .= Display:: return_message(
  7081. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7082. );
  7083. }
  7084. $legend .= '</legend>';
  7085. $return = '<form method="POST">';
  7086. $return .= $legend;
  7087. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7088. $return .= '<tr>';
  7089. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7090. $return .= '<td class="input">';
  7091. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7092. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7093. $arrHide = [
  7094. $id,
  7095. ];
  7096. if (count($arrLP) > 0) {
  7097. for ($i = 0; $i < count($arrLP); $i++) {
  7098. if ($action != 'add') {
  7099. if ($arrLP[$i]['item_type'] == 'dir' &&
  7100. !in_array($arrLP[$i]['id'], $arrHide) &&
  7101. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7102. ) {
  7103. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7104. } else {
  7105. $arrHide[] = $arrLP[$i]['id'];
  7106. }
  7107. } else {
  7108. if ($arrLP[$i]['item_type'] == 'dir') {
  7109. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7110. }
  7111. }
  7112. }
  7113. reset($arrLP);
  7114. }
  7115. $return .= '</select>';
  7116. $return .= '</td>';
  7117. $return .= '</tr>';
  7118. $return .= '<tr>';
  7119. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7120. $return .= '<td class="input">';
  7121. $return .= '<select id="previous" name="previous" size="1">';
  7122. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7123. for ($i = 0; $i < count($arrLP); $i++) {
  7124. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7125. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7126. $selected = 'selected="selected" ';
  7127. } elseif ($action == 'add') {
  7128. $selected = 'selected="selected" ';
  7129. } else {
  7130. $selected = '';
  7131. }
  7132. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7133. }
  7134. }
  7135. $return .= '</select>';
  7136. $return .= '</td>';
  7137. $return .= '</tr>';
  7138. if ($action != 'move') {
  7139. $return .= '<tr>';
  7140. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7141. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7142. $return .= '</tr>';
  7143. $id_prerequisite = 0;
  7144. if (is_array($arrLP) && count($arrLP) > 0) {
  7145. foreach ($arrLP as $key => $value) {
  7146. if ($value['id'] == $id) {
  7147. $id_prerequisite = $value['prerequisite'];
  7148. break;
  7149. }
  7150. }
  7151. $arrHide = [];
  7152. for ($i = 0; $i < count($arrLP); $i++) {
  7153. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7154. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7155. $s_selected_position = $arrLP[$i]['id'];
  7156. } elseif ($action == 'add') {
  7157. $s_selected_position = 0;
  7158. }
  7159. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7160. }
  7161. }
  7162. }
  7163. }
  7164. $return .= '<tr>';
  7165. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.get_lang('SaveHotpotatoes').'</button></td>';
  7166. $return .= '</tr>';
  7167. $return .= '</table>';
  7168. if ($action == 'move') {
  7169. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7170. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7171. }
  7172. if (is_numeric($extra_info)) {
  7173. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7174. } elseif (is_array($extra_info)) {
  7175. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7176. }
  7177. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7178. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7179. $return .= '</form>';
  7180. return $return;
  7181. }
  7182. /**
  7183. * Return the form to display the forum edit/add option.
  7184. *
  7185. * @param string Action (add/edit)
  7186. * @param int ID of the lp_item if already exists
  7187. * @param mixed Forum ID or title
  7188. *
  7189. * @return string HTML form
  7190. */
  7191. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7192. {
  7193. $course_id = api_get_course_int_id();
  7194. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7195. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7196. if ($id != 0 && is_array($extra_info)) {
  7197. $item_title = stripslashes($extra_info['title']);
  7198. } elseif (is_numeric($extra_info)) {
  7199. $sql = "SELECT forum_title as title, forum_comment as comment
  7200. FROM ".$tbl_forum."
  7201. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7202. $result = Database::query($sql);
  7203. $row = Database::fetch_array($result);
  7204. $item_title = $row['title'];
  7205. $item_description = $row['comment'];
  7206. } else {
  7207. $item_title = '';
  7208. $item_description = '';
  7209. }
  7210. if ($id != 0 && is_array($extra_info)) {
  7211. $parent = $extra_info['parent_item_id'];
  7212. } else {
  7213. $parent = 0;
  7214. }
  7215. $sql = "SELECT * FROM $tbl_lp_item
  7216. WHERE
  7217. c_id = $course_id AND
  7218. lp_id = ".$this->lp_id;
  7219. $result = Database::query($sql);
  7220. $arrLP = [];
  7221. while ($row = Database::fetch_array($result)) {
  7222. $arrLP[] = [
  7223. 'id' => $row['iid'],
  7224. 'item_type' => $row['item_type'],
  7225. 'title' => $row['title'],
  7226. 'path' => $row['path'],
  7227. 'description' => $row['description'],
  7228. 'parent_item_id' => $row['parent_item_id'],
  7229. 'previous_item_id' => $row['previous_item_id'],
  7230. 'next_item_id' => $row['next_item_id'],
  7231. 'display_order' => $row['display_order'],
  7232. 'max_score' => $row['max_score'],
  7233. 'min_score' => $row['min_score'],
  7234. 'mastery_score' => $row['mastery_score'],
  7235. 'prerequisite' => $row['prerequisite'],
  7236. ];
  7237. }
  7238. $this->tree_array($arrLP);
  7239. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7240. unset($this->arrMenu);
  7241. if ($action == 'add') {
  7242. $legend = get_lang('CreateTheForum');
  7243. } elseif ($action == 'move') {
  7244. $legend = get_lang('MoveTheCurrentForum');
  7245. } else {
  7246. $legend = get_lang('EditCurrentForum');
  7247. }
  7248. $form = new FormValidator(
  7249. 'forum_form',
  7250. 'POST',
  7251. $this->getCurrentBuildingModeURL()
  7252. );
  7253. $defaults = [];
  7254. $form->addHeader($legend);
  7255. if ($action != 'move') {
  7256. $form->addText(
  7257. 'title',
  7258. get_lang('Title'),
  7259. true,
  7260. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7261. );
  7262. $defaults['title'] = $item_title;
  7263. }
  7264. $selectParent = $form->addSelect(
  7265. 'parent',
  7266. get_lang('Parent'),
  7267. [],
  7268. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7269. );
  7270. $selectParent->addOption($this->name, 0);
  7271. $arrHide = [
  7272. $id,
  7273. ];
  7274. for ($i = 0; $i < count($arrLP); $i++) {
  7275. if ($action != 'add') {
  7276. if ($arrLP[$i]['item_type'] == 'dir' &&
  7277. !in_array($arrLP[$i]['id'], $arrHide) &&
  7278. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7279. ) {
  7280. $selectParent->addOption(
  7281. $arrLP[$i]['title'],
  7282. $arrLP[$i]['id'],
  7283. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7284. );
  7285. if ($parent == $arrLP[$i]['id']) {
  7286. $selectParent->setSelected($arrLP[$i]['id']);
  7287. }
  7288. } else {
  7289. $arrHide[] = $arrLP[$i]['id'];
  7290. }
  7291. } else {
  7292. if ($arrLP[$i]['item_type'] == 'dir') {
  7293. $selectParent->addOption(
  7294. $arrLP[$i]['title'],
  7295. $arrLP[$i]['id'],
  7296. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7297. );
  7298. if ($parent == $arrLP[$i]['id']) {
  7299. $selectParent->setSelected($arrLP[$i]['id']);
  7300. }
  7301. }
  7302. }
  7303. }
  7304. if (is_array($arrLP)) {
  7305. reset($arrLP);
  7306. }
  7307. $selectPrevious = $form->addSelect(
  7308. 'previous',
  7309. get_lang('Position'),
  7310. [],
  7311. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7312. );
  7313. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7314. for ($i = 0; $i < count($arrLP); $i++) {
  7315. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7316. $arrLP[$i]['id'] != $id
  7317. ) {
  7318. $selectPrevious->addOption(
  7319. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7320. $arrLP[$i]['id']
  7321. );
  7322. if (isset($extra_info['previous_item_id']) &&
  7323. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7324. ) {
  7325. $selectPrevious->setSelected($arrLP[$i]['id']);
  7326. } elseif ($action == 'add') {
  7327. $selectPrevious->setSelected($arrLP[$i]['id']);
  7328. }
  7329. }
  7330. }
  7331. if ($action != 'move') {
  7332. $id_prerequisite = 0;
  7333. if (is_array($arrLP)) {
  7334. foreach ($arrLP as $key => $value) {
  7335. if ($value['id'] == $id) {
  7336. $id_prerequisite = $value['prerequisite'];
  7337. break;
  7338. }
  7339. }
  7340. }
  7341. $arrHide = [];
  7342. for ($i = 0; $i < count($arrLP); $i++) {
  7343. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7344. if (isset($extra_info['previous_item_id']) &&
  7345. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7346. ) {
  7347. $s_selected_position = $arrLP[$i]['id'];
  7348. } elseif ($action == 'add') {
  7349. $s_selected_position = 0;
  7350. }
  7351. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7352. }
  7353. }
  7354. }
  7355. if ($action == 'add') {
  7356. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7357. } else {
  7358. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7359. }
  7360. if ($action == 'move') {
  7361. $form->addHidden('title', $item_title);
  7362. $form->addHidden('description', $item_description);
  7363. }
  7364. if (is_numeric($extra_info)) {
  7365. $form->addHidden('path', $extra_info);
  7366. } elseif (is_array($extra_info)) {
  7367. $form->addHidden('path', $extra_info['path']);
  7368. }
  7369. $form->addHidden('type', TOOL_FORUM);
  7370. $form->addHidden('post_time', time());
  7371. $form->setDefaults($defaults);
  7372. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7373. }
  7374. /**
  7375. * Return HTML form to add/edit forum threads.
  7376. *
  7377. * @param string Action (add/edit)
  7378. * @param int Item ID if already exists in learning path
  7379. * @param mixed Extra information (thread ID if integer)
  7380. *
  7381. * @return string HTML form
  7382. */
  7383. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7384. {
  7385. $course_id = api_get_course_int_id();
  7386. if (empty($course_id)) {
  7387. return null;
  7388. }
  7389. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7390. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7391. if ($id != 0 && is_array($extra_info)) {
  7392. $item_title = stripslashes($extra_info['title']);
  7393. } elseif (is_numeric($extra_info)) {
  7394. $sql = "SELECT thread_title as title FROM $tbl_forum
  7395. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7396. $result = Database::query($sql);
  7397. $row = Database::fetch_array($result);
  7398. $item_title = $row['title'];
  7399. $item_description = '';
  7400. } else {
  7401. $item_title = '';
  7402. $item_description = '';
  7403. }
  7404. if ($id != 0 && is_array($extra_info)) {
  7405. $parent = $extra_info['parent_item_id'];
  7406. } else {
  7407. $parent = 0;
  7408. }
  7409. $sql = "SELECT * FROM $tbl_lp_item
  7410. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7411. $result = Database::query($sql);
  7412. $arrLP = [];
  7413. while ($row = Database::fetch_array($result)) {
  7414. $arrLP[] = [
  7415. 'id' => $row['iid'],
  7416. 'item_type' => $row['item_type'],
  7417. 'title' => $row['title'],
  7418. 'path' => $row['path'],
  7419. 'description' => $row['description'],
  7420. 'parent_item_id' => $row['parent_item_id'],
  7421. 'previous_item_id' => $row['previous_item_id'],
  7422. 'next_item_id' => $row['next_item_id'],
  7423. 'display_order' => $row['display_order'],
  7424. 'max_score' => $row['max_score'],
  7425. 'min_score' => $row['min_score'],
  7426. 'mastery_score' => $row['mastery_score'],
  7427. 'prerequisite' => $row['prerequisite'],
  7428. ];
  7429. }
  7430. $this->tree_array($arrLP);
  7431. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7432. unset($this->arrMenu);
  7433. $form = new FormValidator(
  7434. 'thread_form',
  7435. 'POST',
  7436. $this->getCurrentBuildingModeURL()
  7437. );
  7438. $defaults = [];
  7439. if ($action == 'add') {
  7440. $legend = get_lang('CreateTheForum');
  7441. } elseif ($action == 'move') {
  7442. $legend = get_lang('MoveTheCurrentForum');
  7443. } else {
  7444. $legend = get_lang('EditCurrentForum');
  7445. }
  7446. $form->addHeader($legend);
  7447. $selectParent = $form->addSelect(
  7448. 'parent',
  7449. get_lang('Parent'),
  7450. [],
  7451. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7452. );
  7453. $selectParent->addOption($this->name, 0);
  7454. $arrHide = [
  7455. $id,
  7456. ];
  7457. for ($i = 0; $i < count($arrLP); $i++) {
  7458. if ($action != 'add') {
  7459. if (
  7460. ($arrLP[$i]['item_type'] == 'dir') &&
  7461. !in_array($arrLP[$i]['id'], $arrHide) &&
  7462. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7463. ) {
  7464. $selectParent->addOption(
  7465. $arrLP[$i]['title'],
  7466. $arrLP[$i]['id'],
  7467. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7468. );
  7469. if ($parent == $arrLP[$i]['id']) {
  7470. $selectParent->setSelected($arrLP[$i]['id']);
  7471. }
  7472. } else {
  7473. $arrHide[] = $arrLP[$i]['id'];
  7474. }
  7475. } else {
  7476. if ($arrLP[$i]['item_type'] == 'dir') {
  7477. $selectParent->addOption(
  7478. $arrLP[$i]['title'],
  7479. $arrLP[$i]['id'],
  7480. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7481. );
  7482. if ($parent == $arrLP[$i]['id']) {
  7483. $selectParent->setSelected($arrLP[$i]['id']);
  7484. }
  7485. }
  7486. }
  7487. }
  7488. if ($arrLP != null) {
  7489. reset($arrLP);
  7490. }
  7491. $selectPrevious = $form->addSelect(
  7492. 'previous',
  7493. get_lang('Position'),
  7494. [],
  7495. ['id' => 'previous']
  7496. );
  7497. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7498. for ($i = 0; $i < count($arrLP); $i++) {
  7499. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7500. $selectPrevious->addOption(
  7501. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7502. $arrLP[$i]['id']
  7503. );
  7504. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7505. $selectPrevious->setSelected($arrLP[$i]['id']);
  7506. } elseif ($action == 'add') {
  7507. $selectPrevious->setSelected($arrLP[$i]['id']);
  7508. }
  7509. }
  7510. }
  7511. if ($action != 'move') {
  7512. $form->addText(
  7513. 'title',
  7514. get_lang('Title'),
  7515. true,
  7516. ['id' => 'idTitle']
  7517. );
  7518. $defaults['title'] = $item_title;
  7519. $id_prerequisite = 0;
  7520. if ($arrLP != null) {
  7521. foreach ($arrLP as $key => $value) {
  7522. if ($value['id'] == $id) {
  7523. $id_prerequisite = $value['prerequisite'];
  7524. break;
  7525. }
  7526. }
  7527. }
  7528. $arrHide = [];
  7529. $s_selected_position = 0;
  7530. for ($i = 0; $i < count($arrLP); $i++) {
  7531. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7532. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7533. $s_selected_position = $arrLP[$i]['id'];
  7534. } elseif ($action == 'add') {
  7535. $s_selected_position = 0;
  7536. }
  7537. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7538. }
  7539. }
  7540. $selectPrerequisites = $form->addSelect(
  7541. 'prerequisites',
  7542. get_lang('LearnpathPrerequisites'),
  7543. [],
  7544. ['id' => 'prerequisites']
  7545. );
  7546. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7547. foreach ($arrHide as $key => $value) {
  7548. $selectPrerequisites->addOption($value['value'], $key);
  7549. if ($key == $s_selected_position && $action == 'add') {
  7550. $selectPrerequisites->setSelected($key);
  7551. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7552. $selectPrerequisites->setSelected($key);
  7553. }
  7554. }
  7555. }
  7556. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7557. if ($action == 'move') {
  7558. $form->addHidden('title', $item_title);
  7559. $form->addHidden('description', $item_description);
  7560. }
  7561. if (is_numeric($extra_info)) {
  7562. $form->addHidden('path', $extra_info);
  7563. } elseif (is_array($extra_info)) {
  7564. $form->addHidden('path', $extra_info['path']);
  7565. }
  7566. $form->addHidden('type', TOOL_THREAD);
  7567. $form->addHidden('post_time', time());
  7568. $form->setDefaults($defaults);
  7569. return $form->returnForm();
  7570. }
  7571. /**
  7572. * Return the HTML form to display an item (generally a dir item).
  7573. *
  7574. * @param string Item type (dir)
  7575. * @param string Title (optional, only when creating)
  7576. * @param string Action ('add'/'edit')
  7577. * @param int lp_item ID
  7578. * @param mixed Extra info
  7579. *
  7580. * @return string HTML form
  7581. */
  7582. public function display_item_form(
  7583. $item_type,
  7584. $title = '',
  7585. $action = 'add_item',
  7586. $id = 0,
  7587. $extra_info = 'new'
  7588. ) {
  7589. $_course = api_get_course_info();
  7590. global $charset;
  7591. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7592. if ($id != 0 && is_array($extra_info)) {
  7593. $item_title = $extra_info['title'];
  7594. $item_description = $extra_info['description'];
  7595. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7596. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7597. } else {
  7598. $item_title = '';
  7599. $item_description = '';
  7600. $item_path_fck = '';
  7601. }
  7602. if ($id != 0 && is_array($extra_info)) {
  7603. $parent = $extra_info['parent_item_id'];
  7604. } else {
  7605. $parent = 0;
  7606. }
  7607. $id = intval($id);
  7608. $sql = "SELECT * FROM $tbl_lp_item
  7609. WHERE
  7610. lp_id = ".$this->lp_id." AND
  7611. iid != $id";
  7612. if ($item_type == 'dir') {
  7613. $sql .= " AND parent_item_id = 0";
  7614. }
  7615. $result = Database::query($sql);
  7616. $arrLP = [];
  7617. while ($row = Database::fetch_array($result)) {
  7618. $arrLP[] = [
  7619. 'id' => $row['iid'],
  7620. 'item_type' => $row['item_type'],
  7621. 'title' => $row['title'],
  7622. 'path' => $row['path'],
  7623. 'description' => $row['description'],
  7624. 'parent_item_id' => $row['parent_item_id'],
  7625. 'previous_item_id' => $row['previous_item_id'],
  7626. 'next_item_id' => $row['next_item_id'],
  7627. 'max_score' => $row['max_score'],
  7628. 'min_score' => $row['min_score'],
  7629. 'mastery_score' => $row['mastery_score'],
  7630. 'prerequisite' => $row['prerequisite'],
  7631. 'display_order' => $row['display_order'],
  7632. ];
  7633. }
  7634. $this->tree_array($arrLP);
  7635. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7636. unset($this->arrMenu);
  7637. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7638. $form = new FormValidator('form', 'POST', $url);
  7639. $defaults['title'] = api_html_entity_decode(
  7640. $item_title,
  7641. ENT_QUOTES,
  7642. $charset
  7643. );
  7644. $defaults['description'] = $item_description;
  7645. $form->addElement('header', $title);
  7646. //$arrHide = array($id);
  7647. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7648. $arrHide[0]['padding'] = 20;
  7649. $charset = api_get_system_encoding();
  7650. for ($i = 0; $i < count($arrLP); $i++) {
  7651. if ($action != 'add') {
  7652. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7653. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7654. ) {
  7655. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7656. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7657. if ($parent == $arrLP[$i]['id']) {
  7658. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7659. }
  7660. }
  7661. } else {
  7662. if ($arrLP[$i]['item_type'] == 'dir') {
  7663. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7664. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7665. if ($parent == $arrLP[$i]['id']) {
  7666. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7667. }
  7668. }
  7669. }
  7670. }
  7671. if ($action != 'move') {
  7672. $form->addElement('text', 'title', get_lang('Title'));
  7673. $form->applyFilter('title', 'html_filter');
  7674. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7675. } else {
  7676. $form->addElement('hidden', 'title');
  7677. }
  7678. $parent_select = $form->addElement(
  7679. 'select',
  7680. 'parent',
  7681. get_lang('Parent'),
  7682. '',
  7683. [
  7684. 'id' => 'idParent',
  7685. 'onchange' => "javascript: load_cbo(this.value);",
  7686. ]
  7687. );
  7688. foreach ($arrHide as $key => $value) {
  7689. $parent_select->addOption(
  7690. $value['value'],
  7691. $key,
  7692. 'style="padding-left:'.$value['padding'].'px;"'
  7693. );
  7694. }
  7695. if (!empty($s_selected_parent)) {
  7696. $parent_select->setSelected($s_selected_parent);
  7697. }
  7698. if (is_array($arrLP)) {
  7699. reset($arrLP);
  7700. }
  7701. $arrHide = [];
  7702. // POSITION
  7703. for ($i = 0; $i < count($arrLP); $i++) {
  7704. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7705. //this is the same!
  7706. if (isset($extra_info['previous_item_id']) &&
  7707. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7708. ) {
  7709. $s_selected_position = $arrLP[$i]['id'];
  7710. } elseif ($action == 'add') {
  7711. $s_selected_position = $arrLP[$i]['id'];
  7712. }
  7713. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7714. }
  7715. }
  7716. $position = $form->addElement(
  7717. 'select',
  7718. 'previous',
  7719. get_lang('Position'),
  7720. '',
  7721. ['id' => 'previous']
  7722. );
  7723. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7724. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7725. foreach ($arrHide as $key => $value) {
  7726. $position->addOption($value['value'].'"', $key, 'style="padding-left:'.$padding.'px;"');
  7727. }
  7728. if (!empty($s_selected_position)) {
  7729. $position->setSelected($s_selected_position);
  7730. }
  7731. if (is_array($arrLP)) {
  7732. reset($arrLP);
  7733. }
  7734. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7735. //fix in order to use the tab
  7736. if ($item_type == 'dir') {
  7737. $form->addElement('hidden', 'type', 'dir');
  7738. }
  7739. $extension = null;
  7740. if (!empty($item_path)) {
  7741. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7742. }
  7743. //assets can't be modified
  7744. //$item_type == 'asset' ||
  7745. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7746. if ($item_type == 'sco') {
  7747. $form->addElement(
  7748. 'html',
  7749. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7750. );
  7751. }
  7752. $renderer = $form->defaultRenderer();
  7753. $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
  7754. $relative_prefix = '';
  7755. $editor_config = [
  7756. 'ToolbarSet' => 'LearningPathDocuments',
  7757. 'Width' => '100%',
  7758. 'Height' => '500',
  7759. 'FullPage' => true,
  7760. 'CreateDocumentDir' => $relative_prefix,
  7761. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7762. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7763. ];
  7764. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7765. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7766. $defaults['content_lp'] = file_get_contents($content_path);
  7767. }
  7768. $form->addElement('hidden', 'type', $item_type);
  7769. $form->addElement('hidden', 'post_time', time());
  7770. $form->setDefaults($defaults);
  7771. return $form->returnForm();
  7772. }
  7773. /**
  7774. * @return string
  7775. */
  7776. public function getCurrentBuildingModeURL()
  7777. {
  7778. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7779. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7780. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7781. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7782. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7783. return $currentUrl;
  7784. }
  7785. /**
  7786. * Returns the form to update or create a document.
  7787. *
  7788. * @param string $action (add/edit)
  7789. * @param int $id ID of the lp_item (if already exists)
  7790. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7791. *
  7792. * @return string HTML form
  7793. */
  7794. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7795. {
  7796. $course_id = api_get_course_int_id();
  7797. $_course = api_get_course_info();
  7798. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7799. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7800. $no_display_edit_textarea = false;
  7801. $item_description = '';
  7802. //If action==edit document
  7803. //We don't display the document form if it's not an editable document (html or txt file)
  7804. if ($action == 'edit') {
  7805. if (is_array($extra_info)) {
  7806. $path_parts = pathinfo($extra_info['dir']);
  7807. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7808. $no_display_edit_textarea = true;
  7809. }
  7810. }
  7811. }
  7812. $no_display_add = false;
  7813. // If action==add an existing document
  7814. // We don't display the document form if it's not an editable document (html or txt file).
  7815. if ($action == 'add') {
  7816. if (is_numeric($extra_info)) {
  7817. $sql_doc = "SELECT path FROM $tbl_doc
  7818. WHERE c_id = $course_id AND iid = ".intval($extra_info);
  7819. $result = Database::query($sql_doc);
  7820. $path_file = Database::result($result, 0, 0);
  7821. $path_parts = pathinfo($path_file);
  7822. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7823. $no_display_add = true;
  7824. }
  7825. }
  7826. }
  7827. if ($id != 0 && is_array($extra_info)) {
  7828. $item_title = stripslashes($extra_info['title']);
  7829. $item_description = stripslashes($extra_info['description']);
  7830. $item_terms = stripslashes($extra_info['terms']);
  7831. if (empty($item_title)) {
  7832. $path_parts = pathinfo($extra_info['path']);
  7833. $item_title = stripslashes($path_parts['filename']);
  7834. }
  7835. } elseif (is_numeric($extra_info)) {
  7836. $sql = "SELECT path, title FROM $tbl_doc
  7837. WHERE
  7838. c_id = ".$course_id." AND
  7839. iid = ".intval($extra_info);
  7840. $result = Database::query($sql);
  7841. $row = Database::fetch_array($result);
  7842. $item_title = $row['title'];
  7843. $item_title = str_replace('_', ' ', $item_title);
  7844. if (empty($item_title)) {
  7845. $path_parts = pathinfo($row['path']);
  7846. $item_title = stripslashes($path_parts['filename']);
  7847. }
  7848. } else {
  7849. $item_title = '';
  7850. $item_description = '';
  7851. }
  7852. $return = '<legend>';
  7853. if ($id != 0 && is_array($extra_info)) {
  7854. $parent = $extra_info['parent_item_id'];
  7855. } else {
  7856. $parent = 0;
  7857. }
  7858. $sql = "SELECT * FROM $tbl_lp_item
  7859. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7860. $result = Database::query($sql);
  7861. $arrLP = [];
  7862. while ($row = Database::fetch_array($result)) {
  7863. $arrLP[] = [
  7864. 'id' => $row['id'],
  7865. 'item_type' => $row['item_type'],
  7866. 'title' => $row['title'],
  7867. 'path' => $row['path'],
  7868. 'description' => $row['description'],
  7869. 'parent_item_id' => $row['parent_item_id'],
  7870. 'previous_item_id' => $row['previous_item_id'],
  7871. 'next_item_id' => $row['next_item_id'],
  7872. 'display_order' => $row['display_order'],
  7873. 'max_score' => $row['max_score'],
  7874. 'min_score' => $row['min_score'],
  7875. 'mastery_score' => $row['mastery_score'],
  7876. 'prerequisite' => $row['prerequisite'],
  7877. ];
  7878. }
  7879. $this->tree_array($arrLP);
  7880. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7881. unset($this->arrMenu);
  7882. if ($action == 'add') {
  7883. $return .= get_lang('CreateTheDocument');
  7884. } elseif ($action == 'move') {
  7885. $return .= get_lang('MoveTheCurrentDocument');
  7886. } else {
  7887. $return .= get_lang('EditTheCurrentDocument');
  7888. }
  7889. $return .= '</legend>';
  7890. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7891. $return .= Display::return_message(
  7892. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7893. false
  7894. );
  7895. }
  7896. $form = new FormValidator(
  7897. 'form',
  7898. 'POST',
  7899. $this->getCurrentBuildingModeURL(),
  7900. '',
  7901. ['enctype' => 'multipart/form-data']
  7902. );
  7903. $defaults['title'] = Security::remove_XSS($item_title);
  7904. if (empty($item_title)) {
  7905. $defaults['title'] = Security::remove_XSS($item_title);
  7906. }
  7907. $defaults['description'] = $item_description;
  7908. $form->addElement('html', $return);
  7909. if ($action != 'move') {
  7910. $data = $this->generate_lp_folder($_course);
  7911. if ($action != 'edit') {
  7912. $folders = DocumentManager::get_all_document_folders(
  7913. $_course,
  7914. 0,
  7915. true
  7916. );
  7917. DocumentManager::build_directory_selector(
  7918. $folders,
  7919. '',
  7920. [],
  7921. true,
  7922. $form,
  7923. 'directory_parent_id'
  7924. );
  7925. }
  7926. if (isset($data['id'])) {
  7927. $defaults['directory_parent_id'] = $data['id'];
  7928. }
  7929. $form->addElement(
  7930. 'text',
  7931. 'title',
  7932. get_lang('Title'),
  7933. ['id' => 'idTitle', 'class' => 'col-md-4']
  7934. );
  7935. $form->applyFilter('title', 'html_filter');
  7936. }
  7937. $arrHide[0]['value'] = $this->name;
  7938. $arrHide[0]['padding'] = 20;
  7939. for ($i = 0; $i < count($arrLP); $i++) {
  7940. if ($action != 'add') {
  7941. if ($arrLP[$i]['item_type'] == 'dir' &&
  7942. !in_array($arrLP[$i]['id'], $arrHide) &&
  7943. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7944. ) {
  7945. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7946. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7947. if ($parent == $arrLP[$i]['id']) {
  7948. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7949. }
  7950. }
  7951. } else {
  7952. if ($arrLP[$i]['item_type'] == 'dir') {
  7953. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7954. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7955. if ($parent == $arrLP[$i]['id']) {
  7956. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7957. }
  7958. }
  7959. }
  7960. }
  7961. $parent_select = $form->addSelect(
  7962. 'parent',
  7963. get_lang('Parent'),
  7964. [],
  7965. [
  7966. 'id' => 'idParent',
  7967. 'onchange' => 'javascript: load_cbo(this.value);',
  7968. ]
  7969. );
  7970. $my_count = 0;
  7971. foreach ($arrHide as $key => $value) {
  7972. if ($my_count != 0) {
  7973. // The LP name is also the first section and is not in the same charset like the other sections.
  7974. $value['value'] = Security::remove_XSS($value['value']);
  7975. $parent_select->addOption(
  7976. $value['value'],
  7977. $key,
  7978. 'style="padding-left:'.$value['padding'].'px;"'
  7979. );
  7980. } else {
  7981. $value['value'] = Security::remove_XSS($value['value']);
  7982. $parent_select->addOption(
  7983. $value['value'],
  7984. $key,
  7985. 'style="padding-left:'.$value['padding'].'px;"'
  7986. );
  7987. }
  7988. $my_count++;
  7989. }
  7990. if (!empty($id)) {
  7991. $parent_select->setSelected($parent);
  7992. } else {
  7993. $parent_item_id = Session::read('parent_item_id', 0);
  7994. $parent_select->setSelected($parent_item_id);
  7995. }
  7996. if (is_array($arrLP)) {
  7997. reset($arrLP);
  7998. }
  7999. $arrHide = [];
  8000. $s_selected_position = null;
  8001. // POSITION
  8002. $lastPosition = null;
  8003. for ($i = 0; $i < count($arrLP); $i++) {
  8004. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8005. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8006. ) {
  8007. if ((isset($extra_info['previous_item_id']) &&
  8008. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8009. ) {
  8010. $s_selected_position = $arrLP[$i]['id'];
  8011. }
  8012. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8013. }
  8014. $lastPosition = $arrLP[$i]['id'];
  8015. }
  8016. if (empty($s_selected_position)) {
  8017. $s_selected_position = $lastPosition;
  8018. }
  8019. $position = $form->addSelect(
  8020. 'previous',
  8021. get_lang('Position'),
  8022. [],
  8023. ['id' => 'previous']
  8024. );
  8025. $position->addOption(get_lang('FirstPosition'), 0);
  8026. foreach ($arrHide as $key => $value) {
  8027. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8028. $position->addOption(
  8029. $value['value'],
  8030. $key,
  8031. 'style="padding-left:'.$padding.'px;"'
  8032. );
  8033. }
  8034. $position->setSelected($s_selected_position);
  8035. if (is_array($arrLP)) {
  8036. reset($arrLP);
  8037. }
  8038. if ($action != 'move') {
  8039. $id_prerequisite = 0;
  8040. if (is_array($arrLP)) {
  8041. foreach ($arrLP as $key => $value) {
  8042. if ($value['id'] == $id) {
  8043. $id_prerequisite = $value['prerequisite'];
  8044. break;
  8045. }
  8046. }
  8047. }
  8048. $arrHide = [];
  8049. for ($i = 0; $i < count($arrLP); $i++) {
  8050. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8051. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8052. ) {
  8053. if (isset($extra_info['previous_item_id']) &&
  8054. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  8055. ) {
  8056. $s_selected_position = $arrLP[$i]['id'];
  8057. } elseif ($action == 'add') {
  8058. $s_selected_position = $arrLP[$i]['id'];
  8059. }
  8060. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8061. }
  8062. }
  8063. if (!$no_display_add) {
  8064. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8065. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8066. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8067. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8068. ) {
  8069. if (isset($_POST['content'])) {
  8070. $content = stripslashes($_POST['content']);
  8071. } elseif (is_array($extra_info)) {
  8072. //If it's an html document or a text file
  8073. if (!$no_display_edit_textarea) {
  8074. $content = $this->display_document(
  8075. $extra_info['path'],
  8076. false,
  8077. false
  8078. );
  8079. }
  8080. } elseif (is_numeric($extra_info)) {
  8081. $content = $this->display_document(
  8082. $extra_info,
  8083. false,
  8084. false
  8085. );
  8086. } else {
  8087. $content = '';
  8088. }
  8089. if (!$no_display_edit_textarea) {
  8090. // We need to calculate here some specific settings for the online editor.
  8091. // The calculated settings work for documents in the Documents tool
  8092. // (on the root or in subfolders).
  8093. // For documents in native scorm packages it is unclear whether the
  8094. // online editor should be activated or not.
  8095. // A new document, it is in the root of the repository.
  8096. $relative_path = '';
  8097. $relative_prefix = '';
  8098. if (is_array($extra_info) && $extra_info != 'new') {
  8099. // The document already exists. Whe have to determine its relative path towards the repository root.
  8100. $relative_path = explode('/', $extra_info['dir']);
  8101. $cnt = count($relative_path) - 2;
  8102. if ($cnt < 0) {
  8103. $cnt = 0;
  8104. }
  8105. $relative_prefix = str_repeat('../', $cnt);
  8106. $relative_path = array_slice($relative_path, 1, $cnt);
  8107. $relative_path = implode('/', $relative_path);
  8108. if (strlen($relative_path) > 0) {
  8109. $relative_path = $relative_path.'/';
  8110. }
  8111. } else {
  8112. $result = $this->generate_lp_folder($_course);
  8113. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8114. $relative_prefix = '../../';
  8115. }
  8116. $editor_config = [
  8117. 'ToolbarSet' => 'LearningPathDocuments',
  8118. 'Width' => '100%',
  8119. 'Height' => '500',
  8120. 'FullPage' => true,
  8121. 'CreateDocumentDir' => $relative_prefix,
  8122. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8123. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8124. ];
  8125. if ($_GET['action'] == 'add_item') {
  8126. $class = 'add';
  8127. $text = get_lang('LPCreateDocument');
  8128. } else {
  8129. if ($_GET['action'] == 'edit_item') {
  8130. $class = 'save';
  8131. $text = get_lang('SaveDocument');
  8132. }
  8133. }
  8134. $form->addButtonSave($text, 'submit_button');
  8135. $renderer = $form->defaultRenderer();
  8136. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8137. $form->addElement('html', '<div class="editor-lp">');
  8138. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8139. $form->addElement('html', '</div>');
  8140. $defaults['content_lp'] = $content;
  8141. }
  8142. } elseif (is_numeric($extra_info)) {
  8143. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8144. $return = $this->display_document($extra_info, true, true, true);
  8145. $form->addElement('html', $return);
  8146. }
  8147. }
  8148. }
  8149. if (isset($extra_info['item_type']) &&
  8150. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8151. ) {
  8152. $parent_select->freeze();
  8153. $position->freeze();
  8154. }
  8155. if ($action == 'move') {
  8156. $form->addElement('hidden', 'title', $item_title);
  8157. $form->addElement('hidden', 'description', $item_description);
  8158. }
  8159. if (is_numeric($extra_info)) {
  8160. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8161. $form->addElement('hidden', 'path', $extra_info);
  8162. } elseif (is_array($extra_info)) {
  8163. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8164. $form->addElement('hidden', 'path', $extra_info['path']);
  8165. }
  8166. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8167. $form->addElement('hidden', 'post_time', time());
  8168. $form->setDefaults($defaults);
  8169. return $form->returnForm();
  8170. }
  8171. /**
  8172. * Return HTML form to add/edit a link item.
  8173. *
  8174. * @param string $action (add/edit)
  8175. * @param int $id Item ID if exists
  8176. * @param mixed $extra_info
  8177. *
  8178. * @return string HTML form
  8179. */
  8180. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8181. {
  8182. $course_id = api_get_course_int_id();
  8183. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8184. $tbl_link = Database::get_course_table(TABLE_LINK);
  8185. if ($id != 0 && is_array($extra_info)) {
  8186. $item_title = stripslashes($extra_info['title']);
  8187. $item_description = stripslashes($extra_info['description']);
  8188. $item_url = stripslashes($extra_info['url']);
  8189. } elseif (is_numeric($extra_info)) {
  8190. $extra_info = intval($extra_info);
  8191. $sql = "SELECT title, description, url FROM ".$tbl_link."
  8192. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  8193. $result = Database::query($sql);
  8194. $row = Database::fetch_array($result);
  8195. $item_title = $row['title'];
  8196. $item_description = $row['description'];
  8197. $item_url = $row['url'];
  8198. } else {
  8199. $item_title = '';
  8200. $item_description = '';
  8201. $item_url = '';
  8202. }
  8203. $form = new FormValidator(
  8204. 'edit_link',
  8205. 'POST',
  8206. $this->getCurrentBuildingModeURL()
  8207. );
  8208. $defaults = [];
  8209. if ($id != 0 && is_array($extra_info)) {
  8210. $parent = $extra_info['parent_item_id'];
  8211. } else {
  8212. $parent = 0;
  8213. }
  8214. $sql = "SELECT * FROM $tbl_lp_item
  8215. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8216. $result = Database::query($sql);
  8217. $arrLP = [];
  8218. while ($row = Database::fetch_array($result)) {
  8219. $arrLP[] = [
  8220. 'id' => $row['id'],
  8221. 'item_type' => $row['item_type'],
  8222. 'title' => $row['title'],
  8223. 'path' => $row['path'],
  8224. 'description' => $row['description'],
  8225. 'parent_item_id' => $row['parent_item_id'],
  8226. 'previous_item_id' => $row['previous_item_id'],
  8227. 'next_item_id' => $row['next_item_id'],
  8228. 'display_order' => $row['display_order'],
  8229. 'max_score' => $row['max_score'],
  8230. 'min_score' => $row['min_score'],
  8231. 'mastery_score' => $row['mastery_score'],
  8232. 'prerequisite' => $row['prerequisite'],
  8233. ];
  8234. }
  8235. $this->tree_array($arrLP);
  8236. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8237. unset($this->arrMenu);
  8238. if ($action == 'add') {
  8239. $legend = get_lang('CreateTheLink');
  8240. } elseif ($action == 'move') {
  8241. $legend = get_lang('MoveCurrentLink');
  8242. } else {
  8243. $legend = get_lang('EditCurrentLink');
  8244. }
  8245. $form->addHeader($legend);
  8246. if ($action != 'move') {
  8247. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8248. $defaults['title'] = $item_title;
  8249. }
  8250. $selectParent = $form->addSelect(
  8251. 'parent',
  8252. get_lang('Parent'),
  8253. [],
  8254. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8255. );
  8256. $selectParent->addOption($this->name, 0);
  8257. $arrHide = [
  8258. $id,
  8259. ];
  8260. $parent_item_id = Session::read('parent_item_id', 0);
  8261. for ($i = 0; $i < count($arrLP); $i++) {
  8262. if ($action != 'add') {
  8263. if (
  8264. ($arrLP[$i]['item_type'] == 'dir') &&
  8265. !in_array($arrLP[$i]['id'], $arrHide) &&
  8266. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8267. ) {
  8268. $selectParent->addOption(
  8269. $arrLP[$i]['title'],
  8270. $arrLP[$i]['id'],
  8271. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8272. );
  8273. if ($parent == $arrLP[$i]['id']) {
  8274. $selectParent->setSelected($arrLP[$i]['id']);
  8275. }
  8276. } else {
  8277. $arrHide[] = $arrLP[$i]['id'];
  8278. }
  8279. } else {
  8280. if ($arrLP[$i]['item_type'] == 'dir') {
  8281. $selectParent->addOption(
  8282. $arrLP[$i]['title'],
  8283. $arrLP[$i]['id'],
  8284. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8285. );
  8286. if ($parent_item_id == $arrLP[$i]['id']) {
  8287. $selectParent->setSelected($arrLP[$i]['id']);
  8288. }
  8289. }
  8290. }
  8291. }
  8292. if (is_array($arrLP)) {
  8293. reset($arrLP);
  8294. }
  8295. $selectPrevious = $form->addSelect(
  8296. 'previous',
  8297. get_lang('Position'),
  8298. [],
  8299. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8300. );
  8301. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8302. for ($i = 0; $i < count($arrLP); $i++) {
  8303. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8304. $selectPrevious->addOption(
  8305. $arrLP[$i]['title'],
  8306. $arrLP[$i]['id']
  8307. );
  8308. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8309. $selectPrevious->setSelected($arrLP[$i]['id']);
  8310. } elseif ($action == 'add') {
  8311. $selectPrevious->setSelected($arrLP[$i]['id']);
  8312. }
  8313. }
  8314. }
  8315. if ($action != 'move') {
  8316. $urlAttributes = ['class' => 'learnpath_item_form'];
  8317. if (is_numeric($extra_info)) {
  8318. $urlAttributes['disabled'] = 'disabled';
  8319. }
  8320. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8321. $defaults['url'] = $item_url;
  8322. $id_prerequisite = 0;
  8323. if (is_array($arrLP)) {
  8324. foreach ($arrLP as $key => $value) {
  8325. if ($value['id'] == $id) {
  8326. $id_prerequisite = $value['prerequisite'];
  8327. break;
  8328. }
  8329. }
  8330. }
  8331. $arrHide = [];
  8332. for ($i = 0; $i < count($arrLP); $i++) {
  8333. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8334. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8335. $s_selected_position = $arrLP[$i]['id'];
  8336. } elseif ($action == 'add') {
  8337. $s_selected_position = 0;
  8338. }
  8339. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8340. }
  8341. }
  8342. }
  8343. if ($action == 'add') {
  8344. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8345. } else {
  8346. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8347. }
  8348. if ($action == 'move') {
  8349. $form->addHidden('title', $item_title);
  8350. $form->addHidden('description', $item_description);
  8351. }
  8352. if (is_numeric($extra_info)) {
  8353. $form->addHidden('path', $extra_info);
  8354. } elseif (is_array($extra_info)) {
  8355. $form->addHidden('path', $extra_info['path']);
  8356. }
  8357. $form->addHidden('type', TOOL_LINK);
  8358. $form->addHidden('post_time', time());
  8359. $form->setDefaults($defaults);
  8360. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8361. }
  8362. /**
  8363. * Return HTML form to add/edit a student publication (work).
  8364. *
  8365. * @param string Action (add/edit)
  8366. * @param int Item ID if already exists
  8367. * @param mixed Extra info (work ID if integer)
  8368. *
  8369. * @return string HTML form
  8370. */
  8371. public function display_student_publication_form(
  8372. $action = 'add',
  8373. $id = 0,
  8374. $extra_info = ''
  8375. ) {
  8376. $course_id = api_get_course_int_id();
  8377. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8378. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8379. if ($id != 0 && is_array($extra_info)) {
  8380. $item_title = stripslashes($extra_info['title']);
  8381. $item_description = stripslashes($extra_info['description']);
  8382. } elseif (is_numeric($extra_info)) {
  8383. $extra_info = intval($extra_info);
  8384. $sql = "SELECT title, description
  8385. FROM $tbl_publication
  8386. WHERE c_id = $course_id AND id = ".$extra_info;
  8387. $result = Database::query($sql);
  8388. $row = Database::fetch_array($result);
  8389. $item_title = $row['title'];
  8390. } else {
  8391. $item_title = get_lang('Student_publication');
  8392. }
  8393. if ($id != 0 && is_array($extra_info)) {
  8394. $parent = $extra_info['parent_item_id'];
  8395. } else {
  8396. $parent = 0;
  8397. }
  8398. $sql = "SELECT * FROM $tbl_lp_item
  8399. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8400. $result = Database::query($sql);
  8401. $arrLP = [];
  8402. while ($row = Database::fetch_array($result)) {
  8403. $arrLP[] = [
  8404. 'id' => $row['iid'],
  8405. 'item_type' => $row['item_type'],
  8406. 'title' => $row['title'],
  8407. 'path' => $row['path'],
  8408. 'description' => $row['description'],
  8409. 'parent_item_id' => $row['parent_item_id'],
  8410. 'previous_item_id' => $row['previous_item_id'],
  8411. 'next_item_id' => $row['next_item_id'],
  8412. 'display_order' => $row['display_order'],
  8413. 'max_score' => $row['max_score'],
  8414. 'min_score' => $row['min_score'],
  8415. 'mastery_score' => $row['mastery_score'],
  8416. 'prerequisite' => $row['prerequisite'],
  8417. ];
  8418. }
  8419. $this->tree_array($arrLP);
  8420. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8421. unset($this->arrMenu);
  8422. $form = new FormValidator('frm_student_publication', 'post', '#');
  8423. if ($action == 'add') {
  8424. $form->addHeader(get_lang('Student_publication'));
  8425. } elseif ($action == 'move') {
  8426. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8427. } else {
  8428. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8429. }
  8430. if ($action != 'move') {
  8431. $form->addText(
  8432. 'title',
  8433. get_lang('Title'),
  8434. true,
  8435. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8436. );
  8437. }
  8438. $parentSelect = $form->addSelect(
  8439. 'parent',
  8440. get_lang('Parent'),
  8441. ['0' => $this->name],
  8442. [
  8443. 'onchange' => 'javascript: load_cbo(this.value);',
  8444. 'class' => 'learnpath_item_form',
  8445. 'id' => 'idParent',
  8446. ]
  8447. );
  8448. $arrHide = [$id];
  8449. for ($i = 0; $i < count($arrLP); $i++) {
  8450. if ($action != 'add') {
  8451. if (
  8452. ($arrLP[$i]['item_type'] == 'dir') &&
  8453. !in_array($arrLP[$i]['id'], $arrHide) &&
  8454. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8455. ) {
  8456. $parentSelect->addOption(
  8457. $arrLP[$i]['title'],
  8458. $arrLP[$i]['id'],
  8459. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8460. );
  8461. if ($parent == $arrLP[$i]['id']) {
  8462. $parentSelect->setSelected($arrLP[$i]['id']);
  8463. }
  8464. } else {
  8465. $arrHide[] = $arrLP[$i]['id'];
  8466. }
  8467. } else {
  8468. if ($arrLP[$i]['item_type'] == 'dir') {
  8469. $parentSelect->addOption(
  8470. $arrLP[$i]['title'],
  8471. $arrLP[$i]['id'],
  8472. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8473. );
  8474. if ($parent == $arrLP[$i]['id']) {
  8475. $parentSelect->setSelected($arrLP[$i]['id']);
  8476. }
  8477. }
  8478. }
  8479. }
  8480. if (is_array($arrLP)) {
  8481. reset($arrLP);
  8482. }
  8483. $previousSelect = $form->addSelect(
  8484. 'previous',
  8485. get_lang('Position'),
  8486. ['0' => get_lang('FirstPosition')],
  8487. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8488. );
  8489. for ($i = 0; $i < count($arrLP); $i++) {
  8490. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8491. $previousSelect->addOption(
  8492. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8493. $arrLP[$i]['id']
  8494. );
  8495. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8496. $previousSelect->setSelected($arrLP[$i]['id']);
  8497. } elseif ($action == 'add') {
  8498. $previousSelect->setSelected($arrLP[$i]['id']);
  8499. }
  8500. }
  8501. }
  8502. if ($action != 'move') {
  8503. $id_prerequisite = 0;
  8504. if (is_array($arrLP)) {
  8505. foreach ($arrLP as $key => $value) {
  8506. if ($value['id'] == $id) {
  8507. $id_prerequisite = $value['prerequisite'];
  8508. break;
  8509. }
  8510. }
  8511. }
  8512. $arrHide = [];
  8513. for ($i = 0; $i < count($arrLP); $i++) {
  8514. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8515. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8516. $s_selected_position = $arrLP[$i]['id'];
  8517. } elseif ($action == 'add') {
  8518. $s_selected_position = 0;
  8519. }
  8520. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8521. }
  8522. }
  8523. }
  8524. if ($action == 'add') {
  8525. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8526. } else {
  8527. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8528. }
  8529. if ($action == 'move') {
  8530. $form->addHidden('title', $item_title);
  8531. $form->addHidden('description', $item_description);
  8532. }
  8533. if (is_numeric($extra_info)) {
  8534. $form->addHidden('path', $extra_info);
  8535. } elseif (is_array($extra_info)) {
  8536. $form->addHidden('path', $extra_info['path']);
  8537. }
  8538. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8539. $form->addHidden('post_time', time());
  8540. $form->setDefaults(['title' => $item_title]);
  8541. $return = '<div class="sectioncomment">';
  8542. $return .= $form->returnForm();
  8543. $return .= '</div>';
  8544. return $return;
  8545. }
  8546. /**
  8547. * Displays the menu for manipulating a step.
  8548. *
  8549. * @param $item_id
  8550. * @param string $item_type
  8551. *
  8552. * @return string
  8553. */
  8554. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8555. {
  8556. $_course = api_get_course_info();
  8557. $course_code = api_get_course_id();
  8558. $return = '<div class="actions">';
  8559. switch ($item_type) {
  8560. case 'dir':
  8561. // Commented the message cause should not show it.
  8562. //$lang = get_lang('TitleManipulateChapter');
  8563. break;
  8564. case TOOL_LP_FINAL_ITEM:
  8565. case TOOL_DOCUMENT:
  8566. // Commented the message cause should not show it.
  8567. //$lang = get_lang('TitleManipulateDocument');
  8568. break;
  8569. case TOOL_LINK:
  8570. case 'link':
  8571. // Commented the message cause should not show it.
  8572. //$lang = get_lang('TitleManipulateLink');
  8573. break;
  8574. case TOOL_QUIZ:
  8575. // Commented the message cause should not show it.
  8576. //$lang = get_lang('TitleManipulateQuiz');
  8577. break;
  8578. case TOOL_STUDENTPUBLICATION:
  8579. // Commented the message cause should not show it.
  8580. //$lang = get_lang('TitleManipulateStudentPublication');
  8581. break;
  8582. }
  8583. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8584. $item_id = intval($item_id);
  8585. $sql = "SELECT * FROM $tbl_lp_item
  8586. WHERE iid = ".$item_id;
  8587. $result = Database::query($sql);
  8588. $row = Database::fetch_assoc($result);
  8589. $audio_player = null;
  8590. // We display an audio player if needed.
  8591. if (!empty($row['audio'])) {
  8592. $audio_player .= '<div class="lp_mediaplayer" id="container">
  8593. <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
  8594. </div>';
  8595. $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
  8596. $audio_player .= '<script>
  8597. var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
  8598. s1.addParam("allowscriptaccess","always");
  8599. s1.addParam("flashvars","file=../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'].'&autostart=true");
  8600. s1.write("container");
  8601. </script>';
  8602. }
  8603. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8604. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8605. $return .= Display::url(
  8606. Display::return_icon(
  8607. 'edit.png',
  8608. get_lang('Edit'),
  8609. [],
  8610. ICON_SIZE_SMALL
  8611. ),
  8612. $url.'&action=edit_item&path_item='.$row['path']
  8613. );
  8614. $return .= Display::url(
  8615. Display::return_icon(
  8616. 'move.png',
  8617. get_lang('Move'),
  8618. [],
  8619. ICON_SIZE_SMALL
  8620. ),
  8621. $url.'&action=move_item'
  8622. );
  8623. }
  8624. // Commented for now as prerequisites cannot be added to chapters.
  8625. if ($item_type != 'dir') {
  8626. $return .= Display::url(
  8627. Display::return_icon(
  8628. 'accept.png',
  8629. get_lang('LearnpathPrerequisites'),
  8630. [],
  8631. ICON_SIZE_SMALL
  8632. ),
  8633. $url.'&action=edit_item_prereq'
  8634. );
  8635. }
  8636. $return .= Display::url(
  8637. Display::return_icon(
  8638. 'delete.png',
  8639. get_lang('Delete'),
  8640. [],
  8641. ICON_SIZE_SMALL
  8642. ),
  8643. $url.'&action=delete_item'
  8644. );
  8645. if ($item_type == TOOL_HOTPOTATOES) {
  8646. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8647. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8648. }
  8649. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  8650. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8651. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8652. }
  8653. $return .= '</div>';
  8654. if (!empty($audio_player)) {
  8655. $return .= '<br />'.$audio_player;
  8656. }
  8657. return $return;
  8658. }
  8659. /**
  8660. * Creates the javascript needed for filling up the checkboxes without page reload.
  8661. *
  8662. * @return string
  8663. */
  8664. public function get_js_dropdown_array()
  8665. {
  8666. $course_id = api_get_course_int_id();
  8667. $return = 'var child_name = new Array();'."\n";
  8668. $return .= 'var child_value = new Array();'."\n\n";
  8669. $return .= 'child_name[0] = new Array();'."\n";
  8670. $return .= 'child_value[0] = new Array();'."\n\n";
  8671. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8672. $sql = "SELECT * FROM ".$tbl_lp_item."
  8673. WHERE
  8674. c_id = $course_id AND
  8675. lp_id = ".$this->lp_id." AND
  8676. parent_item_id = 0
  8677. ORDER BY display_order ASC";
  8678. $res_zero = Database::query($sql);
  8679. $i = 0;
  8680. while ($row_zero = Database::fetch_array($res_zero)) {
  8681. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8682. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8683. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8684. }
  8685. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8686. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8687. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8688. }
  8689. }
  8690. $return .= "\n";
  8691. $sql = "SELECT * FROM $tbl_lp_item
  8692. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8693. $res = Database::query($sql);
  8694. while ($row = Database::fetch_array($res)) {
  8695. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8696. WHERE
  8697. c_id = ".$course_id." AND
  8698. parent_item_id = ".$row['iid']."
  8699. ORDER BY display_order ASC";
  8700. $res_parent = Database::query($sql_parent);
  8701. $i = 0;
  8702. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8703. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8704. while ($row_parent = Database::fetch_array($res_parent)) {
  8705. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  8706. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8707. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8708. }
  8709. $return .= "\n";
  8710. }
  8711. return $return;
  8712. }
  8713. /**
  8714. * Display the form to allow moving an item.
  8715. *
  8716. * @param int $item_id Item ID
  8717. *
  8718. * @return string HTML form
  8719. */
  8720. public function display_move_item($item_id)
  8721. {
  8722. $return = '';
  8723. if (is_numeric($item_id)) {
  8724. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8725. $sql = "SELECT * FROM $tbl_lp_item
  8726. WHERE iid = $item_id";
  8727. $res = Database::query($sql);
  8728. $row = Database::fetch_array($res);
  8729. switch ($row['item_type']) {
  8730. case 'dir':
  8731. case 'asset':
  8732. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8733. $return .= $this->display_item_form(
  8734. $row['item_type'],
  8735. get_lang('MoveCurrentChapter'),
  8736. 'move',
  8737. $item_id,
  8738. $row
  8739. );
  8740. break;
  8741. case TOOL_DOCUMENT:
  8742. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8743. $return .= $this->display_document_form('move', $item_id, $row);
  8744. break;
  8745. case TOOL_LINK:
  8746. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8747. $return .= $this->display_link_form('move', $item_id, $row);
  8748. break;
  8749. case TOOL_HOTPOTATOES:
  8750. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8751. $return .= $this->display_link_form('move', $item_id, $row);
  8752. break;
  8753. case TOOL_QUIZ:
  8754. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8755. $return .= $this->display_quiz_form('move', $item_id, $row);
  8756. break;
  8757. case TOOL_STUDENTPUBLICATION:
  8758. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8759. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8760. break;
  8761. case TOOL_FORUM:
  8762. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8763. $return .= $this->display_forum_form('move', $item_id, $row);
  8764. break;
  8765. case TOOL_THREAD:
  8766. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8767. $return .= $this->display_forum_form('move', $item_id, $row);
  8768. break;
  8769. }
  8770. }
  8771. return $return;
  8772. }
  8773. /**
  8774. * Displays a basic form on the overview page for changing the item title and the item description.
  8775. *
  8776. * @param string $item_type
  8777. * @param string $title
  8778. * @param array $data
  8779. *
  8780. * @return string
  8781. */
  8782. public function display_item_small_form($item_type, $title = '', $data = [])
  8783. {
  8784. $url = api_get_self().'?'.api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
  8785. $form = new FormValidator('small_form', 'post', $url);
  8786. $form->addElement('header', $title);
  8787. $form->addElement('text', 'title', get_lang('Title'));
  8788. $form->addButtonSave(get_lang('Save'), 'submit_button');
  8789. $form->addElement('hidden', 'id', $data['id']);
  8790. $form->addElement('hidden', 'parent', $data['parent_item_id']);
  8791. $form->addElement('hidden', 'previous', $data['previous_item_id']);
  8792. $form->setDefaults(['title' => $data['title']]);
  8793. return $form->toHtml();
  8794. }
  8795. /**
  8796. * Return HTML form to allow prerequisites selection.
  8797. *
  8798. * @todo use FormValidator
  8799. *
  8800. * @param int Item ID
  8801. *
  8802. * @return string HTML form
  8803. */
  8804. public function display_item_prerequisites_form($item_id)
  8805. {
  8806. $course_id = api_get_course_int_id();
  8807. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8808. $item_id = intval($item_id);
  8809. /* Current prerequisite */
  8810. $sql = "SELECT * FROM $tbl_lp_item
  8811. WHERE iid = $item_id";
  8812. $result = Database::query($sql);
  8813. $row = Database::fetch_array($result);
  8814. $prerequisiteId = $row['prerequisite'];
  8815. $return = '<legend>';
  8816. $return .= get_lang('AddEditPrerequisites');
  8817. $return .= '</legend>';
  8818. $return .= '<form method="POST">';
  8819. $return .= '<div class="table-responsive">';
  8820. $return .= '<table class="table table-hover">';
  8821. $return .= '<thead>';
  8822. $return .= '<tr>';
  8823. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8824. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8825. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8826. $return .= '</tr>';
  8827. $return .= '</thead>';
  8828. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8829. $return .= '<tbody>';
  8830. $return .= '<tr>';
  8831. $return .= '<td colspan="3">';
  8832. $return .= '<div class="radio learnpath"><label for="idNone">';
  8833. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8834. $return .= get_lang('None').'</label>';
  8835. $return .= '</div>';
  8836. $return .= '</tr>';
  8837. $sql = "SELECT * FROM $tbl_lp_item
  8838. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8839. $result = Database::query($sql);
  8840. $arrLP = [];
  8841. $selectedMinScore = [];
  8842. $selectedMaxScore = [];
  8843. while ($row = Database::fetch_array($result)) {
  8844. if ($row['id'] == $item_id) {
  8845. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8846. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8847. }
  8848. $arrLP[] = [
  8849. 'id' => $row['iid'],
  8850. 'item_type' => $row['item_type'],
  8851. 'title' => $row['title'],
  8852. 'ref' => $row['ref'],
  8853. 'description' => $row['description'],
  8854. 'parent_item_id' => $row['parent_item_id'],
  8855. 'previous_item_id' => $row['previous_item_id'],
  8856. 'next_item_id' => $row['next_item_id'],
  8857. 'max_score' => $row['max_score'],
  8858. 'min_score' => $row['min_score'],
  8859. 'mastery_score' => $row['mastery_score'],
  8860. 'prerequisite' => $row['prerequisite'],
  8861. 'next_item_id' => $row['next_item_id'],
  8862. 'display_order' => $row['display_order'],
  8863. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  8864. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  8865. ];
  8866. }
  8867. $this->tree_array($arrLP);
  8868. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8869. unset($this->arrMenu);
  8870. for ($i = 0; $i < count($arrLP); $i++) {
  8871. $item = $arrLP[$i];
  8872. if ($item['id'] == $item_id) {
  8873. break;
  8874. }
  8875. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8876. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8877. $return .= '<tr>';
  8878. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8879. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8880. $return .= '<label for="id'.$item['id'].'">';
  8881. $return .= '<input'.(in_array($prerequisiteId, [$item['id'], $item['ref']]) ? ' checked="checked" ' : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id'].'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  8882. $icon_name = str_replace(' ', '', $item['item_type']);
  8883. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8884. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8885. } else {
  8886. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8887. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8888. } else {
  8889. $return .= Display::return_icon('folder_document.png');
  8890. }
  8891. }
  8892. $return .= $item['title'].'</label>';
  8893. $return .= '</div>';
  8894. $return .= '</td>';
  8895. if ($item['item_type'] == TOOL_QUIZ) {
  8896. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8897. $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
  8898. $tmp_obj_exercice = new Exercise($course_id);
  8899. $tmp_obj_exercice->read($tmp_obj_lp_item->path);
  8900. $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
  8901. $tmp_obj_lp_item->update();
  8902. $item['max_score'] = $tmp_obj_lp_item->max_score;
  8903. $return .= '<td>';
  8904. $return .= '<input class="form-control" size="4" maxlength="3" name="min_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue.'" />';
  8905. $return .= '</td>';
  8906. $return .= '<td>';
  8907. $return .= '<input class="form-control" size="4" maxlength="3" readonly name="max_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue.'" />';
  8908. $return .= '</td>';
  8909. }
  8910. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8911. $return .= '<td>';
  8912. $return .= '<input size="4" maxlength="3" name="min_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue.'" />';
  8913. $return .= '</td>';
  8914. $return .= '<td>';
  8915. $return .= '<input size="4" maxlength="3" name="max_'.$item['id'].'" readonly type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue.'" />';
  8916. $return .= '</td>';
  8917. }
  8918. $return .= '</tr>';
  8919. }
  8920. $return .= '<tr>';
  8921. $return .= '</tr>';
  8922. $return .= '</tbody>';
  8923. $return .= '</table>';
  8924. $return .= '</div>';
  8925. $return .= '<div class="form-group">';
  8926. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.get_lang('ModifyPrerequisites').'</button>';
  8927. $return .= '</form>';
  8928. return $return;
  8929. }
  8930. /**
  8931. * Return HTML list to allow prerequisites selection for lp.
  8932. *
  8933. * @param int Item ID
  8934. *
  8935. * @return string HTML form
  8936. */
  8937. public function display_lp_prerequisites_list()
  8938. {
  8939. $course_id = api_get_course_int_id();
  8940. $lp_id = $this->lp_id;
  8941. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  8942. // get current prerequisite
  8943. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  8944. $result = Database::query($sql);
  8945. $row = Database::fetch_array($result);
  8946. $prerequisiteId = $row['prerequisite'];
  8947. $session_id = api_get_session_id();
  8948. $session_condition = api_get_session_condition($session_id, true, true);
  8949. $sql = "SELECT * FROM $tbl_lp
  8950. WHERE c_id = $course_id $session_condition
  8951. ORDER BY display_order ";
  8952. $rs = Database::query($sql);
  8953. $return = '';
  8954. $return .= '<select name="prerequisites" class="form-control">';
  8955. $return .= '<option value="0">'.get_lang('None').'</option>';
  8956. if (Database::num_rows($rs) > 0) {
  8957. while ($row = Database::fetch_array($rs)) {
  8958. if ($row['id'] == $lp_id) {
  8959. continue;
  8960. }
  8961. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  8962. }
  8963. }
  8964. $return .= '</select>';
  8965. return $return;
  8966. }
  8967. /**
  8968. * Creates a list with all the documents in it.
  8969. *
  8970. * @param bool $showInvisibleFiles
  8971. *
  8972. * @return string
  8973. */
  8974. public function get_documents($showInvisibleFiles = false)
  8975. {
  8976. $course_info = api_get_course_info();
  8977. $sessionId = api_get_session_id();
  8978. $documentTree = DocumentManager::get_document_preview(
  8979. $course_info,
  8980. $this->lp_id,
  8981. null,
  8982. $sessionId,
  8983. true,
  8984. null,
  8985. null,
  8986. $showInvisibleFiles,
  8987. true
  8988. );
  8989. $headers = [
  8990. get_lang('Files'),
  8991. get_lang('CreateTheDocument'),
  8992. get_lang('Upload'),
  8993. ];
  8994. $form = new FormValidator(
  8995. 'form_upload',
  8996. 'POST',
  8997. $this->getCurrentBuildingModeURL(),
  8998. '',
  8999. ['enctype' => 'multipart/form-data']
  9000. );
  9001. $folders = DocumentManager::get_all_document_folders(
  9002. api_get_course_info(),
  9003. 0,
  9004. true
  9005. );
  9006. DocumentManager::build_directory_selector(
  9007. $folders,
  9008. '',
  9009. [],
  9010. true,
  9011. $form,
  9012. 'directory_parent_id'
  9013. );
  9014. $group = [
  9015. $form->createElement(
  9016. 'radio',
  9017. 'if_exists',
  9018. get_lang("UplWhatIfFileExists"),
  9019. get_lang('UplDoNothing'),
  9020. 'nothing'
  9021. ),
  9022. $form->createElement(
  9023. 'radio',
  9024. 'if_exists',
  9025. null,
  9026. get_lang('UplOverwriteLong'),
  9027. 'overwrite'
  9028. ),
  9029. $form->createElement(
  9030. 'radio',
  9031. 'if_exists',
  9032. null,
  9033. get_lang('UplRenameLong'),
  9034. 'rename'
  9035. ),
  9036. ];
  9037. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9038. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9039. $defaultFileExistsOption = 'rename';
  9040. if (!empty($fileExistsOption)) {
  9041. $defaultFileExistsOption = $fileExistsOption;
  9042. }
  9043. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9044. // Check box options
  9045. $form->addElement(
  9046. 'checkbox',
  9047. 'unzip',
  9048. get_lang('Options'),
  9049. get_lang('Uncompress')
  9050. );
  9051. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9052. $form->addMultipleUpload($url);
  9053. $new = $this->display_document_form('add', 0);
  9054. $tabs = Display::tabs(
  9055. $headers,
  9056. [$documentTree, $new, $form->returnForm()],
  9057. 'subtab'
  9058. );
  9059. return $tabs;
  9060. }
  9061. /**
  9062. * Creates a list with all the exercises (quiz) in it.
  9063. *
  9064. * @return string
  9065. */
  9066. public function get_exercises()
  9067. {
  9068. $course_id = api_get_course_int_id();
  9069. $session_id = api_get_session_id();
  9070. $userInfo = api_get_user_info();
  9071. // New for hotpotatoes.
  9072. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9073. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9074. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9075. $condition_session = api_get_session_condition($session_id, true, true);
  9076. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9077. $activeCondition = ' active <> -1 ';
  9078. if ($setting) {
  9079. $activeCondition = ' active = 1 ';
  9080. }
  9081. $sql_quiz = "SELECT * FROM $tbl_quiz
  9082. WHERE c_id = $course_id AND $activeCondition $condition_session
  9083. ORDER BY title ASC";
  9084. $sql_hot = "SELECT * FROM $tbl_doc
  9085. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9086. ORDER BY id ASC";
  9087. $res_quiz = Database::query($sql_quiz);
  9088. $res_hot = Database::query($sql_hot);
  9089. $return = '<ul class="lp_resource">';
  9090. $return .= '<li class="lp_resource_element">';
  9091. $return .= Display::return_icon('new_exercice.png');
  9092. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9093. get_lang('NewExercise').'</a>';
  9094. $return .= '</li>';
  9095. $previewIcon = Display::return_icon(
  9096. 'preview_view.png',
  9097. get_lang('Preview')
  9098. );
  9099. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9100. // Display hotpotatoes
  9101. while ($row_hot = Database::fetch_array($res_hot)) {
  9102. $link = Display::url(
  9103. $previewIcon,
  9104. $exerciseUrl.'&file='.$row_hot['path'],
  9105. ['target' => '_blank']
  9106. );
  9107. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9108. $return .= '<a class="moved" href="#">';
  9109. $return .= Display::return_icon(
  9110. 'move_everywhere.png',
  9111. get_lang('Move'),
  9112. [],
  9113. ICON_SIZE_TINY
  9114. );
  9115. $return .= '</a> ';
  9116. $return .= Display::return_icon('hotpotatoes_s.png');
  9117. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9118. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9119. $return .= '</li>';
  9120. }
  9121. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9122. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9123. $title = strip_tags(
  9124. api_html_entity_decode($row_quiz['title'])
  9125. );
  9126. $link = Display::url(
  9127. $previewIcon,
  9128. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9129. ['target' => '_blank']
  9130. );
  9131. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9132. $return .= '<a class="moved" href="#">';
  9133. $return .= Display::return_icon(
  9134. 'move_everywhere.png',
  9135. get_lang('Move'),
  9136. [],
  9137. ICON_SIZE_TINY
  9138. );
  9139. $return .= '</a> ';
  9140. $return .= Display::return_icon(
  9141. 'quizz_small.gif',
  9142. '',
  9143. [],
  9144. ICON_SIZE_TINY
  9145. );
  9146. $sessionStar = api_get_session_image(
  9147. $row_quiz['session_id'],
  9148. $userInfo['status']
  9149. );
  9150. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id.'">'.
  9151. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  9152. '</a>';
  9153. $return .= '</li>';
  9154. }
  9155. $return .= '</ul>';
  9156. return $return;
  9157. }
  9158. /**
  9159. * Creates a list with all the links in it.
  9160. *
  9161. * @return string
  9162. */
  9163. public function get_links()
  9164. {
  9165. $selfUrl = api_get_self();
  9166. $courseIdReq = api_get_cidreq();
  9167. $course = api_get_course_info();
  9168. $userInfo = api_get_user_info();
  9169. $course_id = $course['real_id'];
  9170. $tbl_link = Database::get_course_table(TABLE_LINK);
  9171. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9172. $moveEverywhereIcon = Display::return_icon(
  9173. 'move_everywhere.png',
  9174. get_lang('Move'),
  9175. [],
  9176. ICON_SIZE_TINY
  9177. );
  9178. $session_id = api_get_session_id();
  9179. $condition_session = api_get_session_condition(
  9180. $session_id,
  9181. true,
  9182. true,
  9183. "link.session_id"
  9184. );
  9185. $sql = "SELECT
  9186. link.id as link_id,
  9187. link.title as link_title,
  9188. link.session_id as link_session_id,
  9189. link.category_id as category_id,
  9190. link_category.category_title as category_title
  9191. FROM $tbl_link as link
  9192. LEFT JOIN $linkCategoryTable as link_category
  9193. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9194. WHERE link.c_id = ".$course_id." $condition_session
  9195. ORDER BY link_category.category_title ASC, link.title ASC";
  9196. $result = Database::query($sql);
  9197. $categorizedLinks = [];
  9198. $categories = [];
  9199. while ($link = Database::fetch_array($result)) {
  9200. if (!$link['category_id']) {
  9201. $link['category_title'] = get_lang('Uncategorized');
  9202. }
  9203. $categories[$link['category_id']] = $link['category_title'];
  9204. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9205. }
  9206. $linksHtmlCode =
  9207. '<script>
  9208. function toggle_tool(tool, id) {
  9209. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9210. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9211. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9212. } else {
  9213. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9214. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9215. }
  9216. }
  9217. </script>
  9218. <ul class="lp_resource">
  9219. <li class="lp_resource_element">
  9220. '.Display::return_icon('linksnew.gif').'
  9221. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9222. get_lang('LinkAdd').'
  9223. </a>
  9224. </li>';
  9225. foreach ($categorizedLinks as $categoryId => $links) {
  9226. $linkNodes = null;
  9227. foreach ($links as $key => $linkInfo) {
  9228. $title = $linkInfo['link_title'];
  9229. $linkSessionId = $linkInfo['link_session_id'];
  9230. $link = Display::url(
  9231. Display::return_icon('preview_view.png', get_lang('Preview')),
  9232. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9233. ['target' => '_blank']
  9234. );
  9235. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9236. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9237. $linkNodes .=
  9238. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9239. <a class="moved" href="#">'.
  9240. $moveEverywhereIcon.
  9241. '</a>
  9242. '.Display::return_icon('lp_link.png').'
  9243. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9244. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9245. Security::remove_XSS($title).$sessionStar.$link.
  9246. '</a>
  9247. </li>';
  9248. }
  9249. }
  9250. $linksHtmlCode .=
  9251. '<li>
  9252. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9253. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9254. align="absbottom" />
  9255. </a>
  9256. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9257. </li>
  9258. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9259. }
  9260. $linksHtmlCode .= '</ul>';
  9261. return $linksHtmlCode;
  9262. }
  9263. /**
  9264. * Creates a list with all the student publications in it.
  9265. *
  9266. * @return string
  9267. */
  9268. public function get_student_publications()
  9269. {
  9270. $sessionId = api_get_session_id();
  9271. $return = '<ul class="lp_resource">';
  9272. $return .= '<li class="lp_resource_element">';
  9273. $return .= Display::return_icon('works_new.gif');
  9274. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9275. get_lang('AddAssignmentPage').'</a>';
  9276. $return .= '</li>';
  9277. if (empty($sessionId)) {
  9278. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9279. $works = getWorkListTeacher(0, 100, null, null, null);
  9280. if (!empty($works)) {
  9281. foreach ($works as $work) {
  9282. $link = Display::url(
  9283. Display::return_icon('preview_view.png', get_lang('Preview')),
  9284. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9285. ['target' => '_blank']
  9286. );
  9287. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9288. $return .= '<a class="moved" href="#">';
  9289. $return .= Display::return_icon(
  9290. 'move_everywhere.png',
  9291. get_lang('Move'),
  9292. [],
  9293. ICON_SIZE_TINY
  9294. );
  9295. $return .= '</a> ';
  9296. $return .= Display::return_icon('works.gif');
  9297. $return .= ' <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id.'">'.
  9298. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9299. </a>';
  9300. $return .= '</li>';
  9301. }
  9302. }
  9303. }
  9304. $return .= '</ul>';
  9305. return $return;
  9306. }
  9307. /**
  9308. * Creates a list with all the forums in it.
  9309. *
  9310. * @return string
  9311. */
  9312. public function get_forums()
  9313. {
  9314. require_once '../forum/forumfunction.inc.php';
  9315. require_once '../forum/forumconfig.inc.php';
  9316. $forumCategories = get_forum_categories();
  9317. $forumsInNoCategory = get_forums_in_category(0);
  9318. if (!empty($forumsInNoCategory)) {
  9319. $forumCategories = array_merge(
  9320. $forumCategories,
  9321. [
  9322. [
  9323. 'cat_id' => 0,
  9324. 'session_id' => 0,
  9325. 'visibility' => 1,
  9326. 'cat_comment' => null,
  9327. ],
  9328. ]
  9329. );
  9330. }
  9331. $forumList = get_forums();
  9332. $a_forums = [];
  9333. foreach ($forumCategories as $forumCategory) {
  9334. // The forums in this category.
  9335. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9336. if (!empty($forumsInCategory)) {
  9337. foreach ($forumList as $forum) {
  9338. if (isset($forum['forum_category']) &&
  9339. $forum['forum_category'] == $forumCategory['cat_id']
  9340. ) {
  9341. $a_forums[] = $forum;
  9342. }
  9343. }
  9344. }
  9345. }
  9346. $return = '<ul class="lp_resource">';
  9347. // First add link
  9348. $return .= '<li class="lp_resource_element">';
  9349. $return .= Display::return_icon('new_forum.png');
  9350. $return .= Display::url(
  9351. get_lang('CreateANewForum'),
  9352. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9353. 'action' => 'add',
  9354. 'content' => 'forum',
  9355. 'lp_id' => $this->lp_id,
  9356. ]),
  9357. ['title' => get_lang('CreateANewForum')]
  9358. );
  9359. $return .= '</li>';
  9360. $return .= '<script>
  9361. function toggle_forum(forum_id) {
  9362. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9363. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9364. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9365. } else {
  9366. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9367. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9368. }
  9369. }
  9370. </script>';
  9371. foreach ($a_forums as $forum) {
  9372. if (!empty($forum['forum_id'])) {
  9373. $link = Display::url(
  9374. Display::return_icon('preview_view.png', get_lang('Preview')),
  9375. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9376. ['target' => '_blank']
  9377. );
  9378. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9379. $return .= '<a class="moved" href="#">';
  9380. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9381. $return .= ' </a>';
  9382. $return .= Display::return_icon('lp_forum.png', '', [], ICON_SIZE_TINY);
  9383. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9384. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9385. </a>
  9386. <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_FORUM.'&forum_id='.$forum['forum_id'].'&lp_id='.$this->lp_id.'" style="vertical-align:middle">'.
  9387. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9388. $return .= '</li>';
  9389. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9390. $a_threads = get_threads($forum['forum_id']);
  9391. if (is_array($a_threads)) {
  9392. foreach ($a_threads as $thread) {
  9393. $link = Display::url(
  9394. Display::return_icon('preview_view.png', get_lang('Preview')),
  9395. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9396. ['target' => '_blank']
  9397. );
  9398. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9399. $return .= '&nbsp;<a class="moved" href="#">';
  9400. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9401. $return .= ' </a>';
  9402. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9403. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_THREAD.'&thread_id='.$thread['thread_id'].'&lp_id='.$this->lp_id.'">'.
  9404. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9405. $return .= '</li>';
  9406. }
  9407. }
  9408. $return .= '</div>';
  9409. }
  9410. }
  9411. $return .= '</ul>';
  9412. return $return;
  9413. }
  9414. /**
  9415. * // TODO: The output encoding should be equal to the system encoding.
  9416. *
  9417. * Exports the learning path as a SCORM package. This is the main function that
  9418. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9419. * whole thing and returns the zip.
  9420. *
  9421. * This method needs to be called in PHP5, as it will fail with non-adequate
  9422. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9423. * you need to call it on a learnpath object.
  9424. *
  9425. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9426. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9427. * path has been modified, it should use the generic method here below.
  9428. *
  9429. * @param string Optional name of zip file. If none, title of learnpath is
  9430. * domesticated and trailed with ".zip"
  9431. *
  9432. * @return string Returns the zip package string, or null if error
  9433. */
  9434. public function scorm_export()
  9435. {
  9436. $_course = api_get_course_info();
  9437. $course_id = $_course['real_id'];
  9438. // Remove memory and time limits as much as possible as this might be a long process...
  9439. if (function_exists('ini_set')) {
  9440. api_set_memory_limit('256M');
  9441. ini_set('max_execution_time', 600);
  9442. }
  9443. // Create the zip handler (this will remain available throughout the method).
  9444. $archive_path = api_get_path(SYS_ARCHIVE_PATH);
  9445. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9446. $temp_dir_short = uniqid();
  9447. $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
  9448. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9449. $zip_folder = new PclZip($temp_zip_file);
  9450. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9451. $root_path = $main_path = api_get_path(SYS_PATH);
  9452. $files_cleanup = [];
  9453. // Place to temporarily stash the zip file.
  9454. // create the temp dir if it doesn't exist
  9455. // or do a cleanup before creating the zip file.
  9456. if (!is_dir($temp_zip_dir)) {
  9457. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9458. } else {
  9459. // Cleanup: Check the temp dir for old files and delete them.
  9460. $handle = opendir($temp_zip_dir);
  9461. while (false !== ($file = readdir($handle))) {
  9462. if ($file != '.' && $file != '..') {
  9463. unlink("$temp_zip_dir/$file");
  9464. }
  9465. }
  9466. closedir($handle);
  9467. }
  9468. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9469. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9470. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9471. ) {
  9472. // Remove the possible . at the end of the path.
  9473. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9474. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9475. mkdir(
  9476. $dest_path_to_scorm_folder,
  9477. api_get_permissions_for_new_directories(),
  9478. true
  9479. );
  9480. copyr(
  9481. $current_course_path.'/scorm/'.$this->path,
  9482. $dest_path_to_scorm_folder,
  9483. ['imsmanifest'],
  9484. $zip_files
  9485. );
  9486. }
  9487. // Build a dummy imsmanifest structure.
  9488. // Do not add to the zip yet (we still need it).
  9489. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9490. // Aggregation Model official document, section "2.3 Content Packaging".
  9491. // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
  9492. $xmldoc = new DOMDocument('1.0');
  9493. $root = $xmldoc->createElement('manifest');
  9494. $root->setAttribute('identifier', 'SingleCourseManifest');
  9495. $root->setAttribute('version', '1.1');
  9496. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9497. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9498. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9499. $root->setAttribute('xsi:schemaLocation', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd');
  9500. // Build mandatory sub-root container elements.
  9501. $metadata = $xmldoc->createElement('metadata');
  9502. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9503. $metadata->appendChild($md_schema);
  9504. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9505. $metadata->appendChild($md_schemaversion);
  9506. $root->appendChild($metadata);
  9507. $organizations = $xmldoc->createElement('organizations');
  9508. $resources = $xmldoc->createElement('resources');
  9509. // Build the only organization we will use in building our learnpaths.
  9510. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9511. $organization = $xmldoc->createElement('organization');
  9512. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9513. // To set the title of the SCORM entity (=organization), we take the name given
  9514. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9515. // learning path charset) as it is the encoding that defines how it is stored
  9516. // in the database. Then we convert it to HTML entities again as the "&" character
  9517. // alone is not authorized in XML (must be &amp;).
  9518. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9519. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9520. $organization->appendChild($org_title);
  9521. $folder_name = 'document';
  9522. // Removes the learning_path/scorm_folder path when exporting see #4841
  9523. $path_to_remove = null;
  9524. $result = $this->generate_lp_folder($_course);
  9525. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9526. $path_to_remove = 'document'.$result['dir'];
  9527. $path_to_replace = $folder_name.'/';
  9528. }
  9529. // Fixes chamilo scorm exports
  9530. if ($this->ref === 'chamilo_scorm_export') {
  9531. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9532. }
  9533. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9534. // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
  9535. $link_updates = [];
  9536. $links_to_create = [];
  9537. //foreach ($this->items as $index => $item) {
  9538. foreach ($this->ordered_items as $index => $itemId) {
  9539. $item = $this->items[$itemId];
  9540. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9541. // Get included documents from this item.
  9542. if ($item->type === 'sco') {
  9543. $inc_docs = $item->get_resources_from_source(
  9544. null,
  9545. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.'scorm/'.$this->path.'/'.$item->get_path()
  9546. );
  9547. } else {
  9548. $inc_docs = $item->get_resources_from_source();
  9549. }
  9550. // Give a child element <item> to the <organization> element.
  9551. $my_item_id = $item->get_id();
  9552. $my_item = $xmldoc->createElement('item');
  9553. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9554. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9555. $my_item->setAttribute('isvisible', 'true');
  9556. // Give a child element <title> to the <item> element.
  9557. $my_title = $xmldoc->createElement(
  9558. 'title',
  9559. htmlspecialchars(
  9560. api_utf8_encode($item->get_title()),
  9561. ENT_QUOTES,
  9562. 'UTF-8'
  9563. )
  9564. );
  9565. $my_item->appendChild($my_title);
  9566. // Give a child element <adlcp:prerequisites> to the <item> element.
  9567. $my_prereqs = $xmldoc->createElement(
  9568. 'adlcp:prerequisites',
  9569. $this->get_scorm_prereq_string($my_item_id)
  9570. );
  9571. $my_prereqs->setAttribute('type', 'aicc_script');
  9572. $my_item->appendChild($my_prereqs);
  9573. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9574. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9575. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9576. //$xmldoc->createElement('adlcp:timelimitaction','');
  9577. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9578. //$xmldoc->createElement('adlcp:datafromlms','');
  9579. // Give a child element <adlcp:masteryscore> to the <item> element.
  9580. $my_masteryscore = $xmldoc->createElement(
  9581. 'adlcp:masteryscore',
  9582. $item->get_mastery_score()
  9583. );
  9584. $my_item->appendChild($my_masteryscore);
  9585. // Attach this item to the organization element or hits parent if there is one.
  9586. if (!empty($item->parent) && $item->parent != 0) {
  9587. $children = $organization->childNodes;
  9588. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9589. if (is_object($possible_parent)) {
  9590. $possible_parent->appendChild($my_item);
  9591. } else {
  9592. if ($this->debug > 0) {
  9593. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9594. }
  9595. }
  9596. } else {
  9597. if ($this->debug > 0) {
  9598. error_log('No parent');
  9599. }
  9600. $organization->appendChild($my_item);
  9601. }
  9602. // Get the path of the file(s) from the course directory root.
  9603. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9604. if (!empty($path_to_remove)) {
  9605. //From docs
  9606. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9607. //From quiz
  9608. if ($this->ref === 'chamilo_scorm_export') {
  9609. $path_to_remove = 'scorm/'.$this->path.'/';
  9610. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9611. }
  9612. } else {
  9613. $my_xml_file_path = $my_file_path;
  9614. }
  9615. $my_sub_dir = dirname($my_file_path);
  9616. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9617. $my_xml_sub_dir = $my_sub_dir;
  9618. // Give a <resource> child to the <resources> element
  9619. $my_resource = $xmldoc->createElement('resource');
  9620. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9621. $my_resource->setAttribute('type', 'webcontent');
  9622. $my_resource->setAttribute('href', $my_xml_file_path);
  9623. // adlcp:scormtype can be either 'sco' or 'asset'.
  9624. if ($item->type === 'sco') {
  9625. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9626. } else {
  9627. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9628. }
  9629. // xml:base is the base directory to find the files declared in this resource.
  9630. $my_resource->setAttribute('xml:base', '');
  9631. // Give a <file> child to the <resource> element.
  9632. $my_file = $xmldoc->createElement('file');
  9633. $my_file->setAttribute('href', $my_xml_file_path);
  9634. $my_resource->appendChild($my_file);
  9635. // Dependency to other files - not yet supported.
  9636. $i = 1;
  9637. if ($inc_docs) {
  9638. foreach ($inc_docs as $doc_info) {
  9639. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9640. continue;
  9641. }
  9642. $my_dep = $xmldoc->createElement('resource');
  9643. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9644. $my_dep->setAttribute('identifier', $res_id);
  9645. $my_dep->setAttribute('type', 'webcontent');
  9646. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9647. $my_dep_file = $xmldoc->createElement('file');
  9648. // Check type of URL.
  9649. if ($doc_info[1] == 'remote') {
  9650. // Remote file. Save url as is.
  9651. $my_dep_file->setAttribute('href', $doc_info[0]);
  9652. $my_dep->setAttribute('xml:base', '');
  9653. } elseif ($doc_info[1] === 'local') {
  9654. switch ($doc_info[2]) {
  9655. case 'url': // Local URL - save path as url for now, don't zip file.
  9656. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9657. $current_dir = dirname($abs_path);
  9658. $current_dir = str_replace('\\', '/', $current_dir);
  9659. $file_path = realpath($abs_path);
  9660. $file_path = str_replace('\\', '/', $file_path);
  9661. $my_dep_file->setAttribute('href', $file_path);
  9662. $my_dep->setAttribute('xml:base', '');
  9663. if (strstr($file_path, $main_path) !== false) {
  9664. // The calculated real path is really inside Chamilo's root path.
  9665. // Reduce file path to what's under the DocumentRoot.
  9666. $file_path = substr($file_path, strlen($root_path) - 1);
  9667. //echo $file_path;echo '<br /><br />';
  9668. //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
  9669. $zip_files_abs[] = $file_path;
  9670. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9671. $my_dep_file->setAttribute('href', $file_path);
  9672. $my_dep->setAttribute('xml:base', '');
  9673. } elseif (empty($file_path)) {
  9674. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9675. if (strpos($document_root, -1) == '/') {
  9676. $document_root = substr(0, -1, $document_root);
  9677. }*/
  9678. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9679. $file_path = str_replace('//', '/', $file_path);
  9680. if (file_exists($file_path)) {
  9681. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9682. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9683. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9684. $my_dep_file->setAttribute('href', $file_path);
  9685. $my_dep->setAttribute('xml:base', '');
  9686. }
  9687. }
  9688. break;
  9689. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9690. $my_dep_file->setAttribute('href', $doc_info[0]);
  9691. $my_dep->setAttribute('xml:base', '');
  9692. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9693. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9694. $abs_img_path_without_subdir = $doc_info[0];
  9695. $relp = api_get_path(REL_PATH); // The url-append config param.
  9696. $pos = strpos($abs_img_path_without_subdir, $relp);
  9697. if ($pos === 0) {
  9698. $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir, strlen($relp));
  9699. }
  9700. //$file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
  9701. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9702. $file_path = str_replace('\\', '/', $file_path);
  9703. $file_path = str_replace('//', '/', $file_path);
  9704. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9705. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9706. // Check if the current document is in that path.
  9707. if (strstr($file_path, $cur_path) !== false) {
  9708. // The document is in that path, now get the relative path
  9709. // to the containing document.
  9710. $orig_file_path = dirname($cur_path.$my_file_path).'/';
  9711. $orig_file_path = str_replace('\\', '/', $orig_file_path);
  9712. $relative_path = '';
  9713. if (strstr($file_path, $cur_path) !== false) {
  9714. //$relative_path = substr($file_path, strlen($orig_file_path));
  9715. $relative_path = str_replace($cur_path, '', $file_path);
  9716. $file_path = substr($file_path, strlen($cur_path));
  9717. } else {
  9718. // This case is still a problem as it's difficult to calculate a relative path easily
  9719. // might still generate wrong links.
  9720. //$file_path = substr($file_path,strlen($cur_path));
  9721. // Calculate the directory path to the current file (without trailing slash).
  9722. $my_relative_path = dirname($file_path);
  9723. $my_relative_path = str_replace('\\', '/', $my_relative_path);
  9724. $my_relative_file = basename($file_path);
  9725. // Calculate the directory path to the containing file (without trailing slash).
  9726. $my_orig_file_path = substr($orig_file_path, 0, -1);
  9727. $dotdot = '';
  9728. $subdir = '';
  9729. while (strstr($my_relative_path, $my_orig_file_path) === false && (strlen($my_orig_file_path) > 1) && (strlen($my_relative_path) > 1)) {
  9730. $my_relative_path2 = dirname($my_relative_path);
  9731. $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
  9732. $my_orig_file_path = dirname($my_orig_file_path);
  9733. $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
  9734. $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'.$subdir;
  9735. $dotdot += '../';
  9736. $my_relative_path = $my_relative_path2;
  9737. }
  9738. $relative_path = $dotdot.$subdir.$my_relative_file;
  9739. }
  9740. // Put the current document in the zip (this array is the array
  9741. // that will manage documents already in the course folder - relative).
  9742. $zip_files[] = $file_path;
  9743. // Update the links to the current document in the containing document (make them relative).
  9744. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $relative_path];
  9745. $my_dep_file->setAttribute('href', $file_path);
  9746. $my_dep->setAttribute('xml:base', '');
  9747. } elseif (strstr($file_path, $main_path) !== false) {
  9748. // The calculated real path is really inside Chamilo's root path.
  9749. // Reduce file path to what's under the DocumentRoot.
  9750. $file_path = substr($file_path, strlen($root_path));
  9751. //echo $file_path;echo '<br /><br />';
  9752. //error_log('Reduced path: '.$file_path, 0);
  9753. $zip_files_abs[] = $file_path;
  9754. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9755. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9756. $my_dep->setAttribute('xml:base', '');
  9757. } elseif (empty($file_path)) {
  9758. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9759. $file_path = str_replace('//', '/', $file_path);
  9760. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9761. $current_dir = dirname($abs_path);
  9762. $current_dir = str_replace('\\', '/', $current_dir);
  9763. if (file_exists($file_path)) {
  9764. // We get the relative path.
  9765. $file_path = substr($file_path, strlen($current_dir));
  9766. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9767. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9768. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9769. $my_dep->setAttribute('xml:base', '');
  9770. }
  9771. }
  9772. break;
  9773. case 'rel':
  9774. // Path relative to the current document.
  9775. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9776. if (substr($doc_info[0], 0, 2) == '..') {
  9777. // Relative path going up.
  9778. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9779. $current_dir = str_replace('\\', '/', $current_dir);
  9780. $file_path = realpath($current_dir.$doc_info[0]);
  9781. $file_path = str_replace('\\', '/', $file_path);
  9782. if (strstr($file_path, $main_path) !== false) {
  9783. // The calculated real path is really inside Chamilo's root path.
  9784. // Reduce file path to what's under the DocumentRoot.
  9785. $file_path = substr($file_path, strlen($root_path));
  9786. $zip_files_abs[] = $file_path;
  9787. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9788. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9789. $my_dep->setAttribute('xml:base', '');
  9790. }
  9791. } else {
  9792. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9793. $my_dep_file->setAttribute('href', $doc_info[0]);
  9794. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9795. }
  9796. break;
  9797. default:
  9798. $my_dep_file->setAttribute('href', $doc_info[0]);
  9799. $my_dep->setAttribute('xml:base', '');
  9800. break;
  9801. }
  9802. }
  9803. $my_dep->appendChild($my_dep_file);
  9804. $resources->appendChild($my_dep);
  9805. $dependency = $xmldoc->createElement('dependency');
  9806. $dependency->setAttribute('identifierref', $res_id);
  9807. $my_resource->appendChild($dependency);
  9808. $i++;
  9809. }
  9810. }
  9811. $resources->appendChild($my_resource);
  9812. $zip_files[] = $my_file_path;
  9813. } else {
  9814. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9815. switch ($item->type) {
  9816. case TOOL_LINK:
  9817. $my_item = $xmldoc->createElement('item');
  9818. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9819. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9820. $my_item->setAttribute('isvisible', 'true');
  9821. // Give a child element <title> to the <item> element.
  9822. $my_title = $xmldoc->createElement(
  9823. 'title',
  9824. htmlspecialchars(
  9825. api_utf8_encode($item->get_title()),
  9826. ENT_QUOTES,
  9827. 'UTF-8'
  9828. )
  9829. );
  9830. $my_item->appendChild($my_title);
  9831. // Give a child element <adlcp:prerequisites> to the <item> element.
  9832. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9833. $my_prereqs->setAttribute('type', 'aicc_script');
  9834. $my_item->appendChild($my_prereqs);
  9835. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9836. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9837. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9838. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9839. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9840. //$xmldoc->createElement('adlcp:datafromlms', '');
  9841. // Give a child element <adlcp:masteryscore> to the <item> element.
  9842. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9843. $my_item->appendChild($my_masteryscore);
  9844. // Attach this item to the organization element or its parent if there is one.
  9845. if (!empty($item->parent) && $item->parent != 0) {
  9846. $children = $organization->childNodes;
  9847. for ($i = 0; $i < $children->length; $i++) {
  9848. $item_temp = $children->item($i);
  9849. if ($item_temp->nodeName == 'item') {
  9850. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9851. $item_temp->appendChild($my_item);
  9852. }
  9853. }
  9854. }
  9855. } else {
  9856. $organization->appendChild($my_item);
  9857. }
  9858. $my_file_path = 'link_'.$item->get_id().'.html';
  9859. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9860. WHERE c_id = '.$course_id.' AND id='.$item->path;
  9861. $rs = Database::query($sql);
  9862. if ($link = Database::fetch_array($rs)) {
  9863. $url = $link['url'];
  9864. $title = stripslashes($link['title']);
  9865. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9866. $my_xml_file_path = $my_file_path;
  9867. $my_sub_dir = dirname($my_file_path);
  9868. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9869. $my_xml_sub_dir = $my_sub_dir;
  9870. // Give a <resource> child to the <resources> element.
  9871. $my_resource = $xmldoc->createElement('resource');
  9872. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9873. $my_resource->setAttribute('type', 'webcontent');
  9874. $my_resource->setAttribute('href', $my_xml_file_path);
  9875. // adlcp:scormtype can be either 'sco' or 'asset'.
  9876. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9877. // xml:base is the base directory to find the files declared in this resource.
  9878. $my_resource->setAttribute('xml:base', '');
  9879. // give a <file> child to the <resource> element.
  9880. $my_file = $xmldoc->createElement('file');
  9881. $my_file->setAttribute('href', $my_xml_file_path);
  9882. $my_resource->appendChild($my_file);
  9883. $resources->appendChild($my_resource);
  9884. }
  9885. break;
  9886. case TOOL_QUIZ:
  9887. $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
  9888. $exe = new Exercise();
  9889. $exe->read($exe_id);
  9890. $my_item = $xmldoc->createElement('item');
  9891. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9892. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9893. $my_item->setAttribute('isvisible', 'true');
  9894. // Give a child element <title> to the <item> element.
  9895. $my_title = $xmldoc->createElement(
  9896. 'title',
  9897. htmlspecialchars(
  9898. api_utf8_encode($item->get_title()),
  9899. ENT_QUOTES,
  9900. 'UTF-8'
  9901. )
  9902. );
  9903. $my_item->appendChild($my_title);
  9904. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  9905. //$my_item->appendChild($my_max_score);
  9906. // Give a child element <adlcp:prerequisites> to the <item> element.
  9907. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9908. $my_prereqs->setAttribute('type', 'aicc_script');
  9909. $my_item->appendChild($my_prereqs);
  9910. // Give a child element <adlcp:masteryscore> to the <item> element.
  9911. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9912. $my_item->appendChild($my_masteryscore);
  9913. // Attach this item to the organization element or hits parent if there is one.
  9914. if (!empty($item->parent) && $item->parent != 0) {
  9915. $children = $organization->childNodes;
  9916. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9917. if ($possible_parent) {
  9918. if ($possible_parent->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9919. $possible_parent->appendChild($my_item);
  9920. }
  9921. }
  9922. } else {
  9923. $organization->appendChild($my_item);
  9924. }
  9925. // Get the path of the file(s) from the course directory root
  9926. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9927. $my_file_path = 'quiz_'.$item->get_id().'.html';
  9928. // Write the contents of the exported exercise into a (big) html file
  9929. // to later pack it into the exported SCORM. The file will be removed afterwards.
  9930. $contents = ScormSection::export_exercise_to_scorm(
  9931. $exe,
  9932. true
  9933. );
  9934. $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
  9935. $res = file_put_contents($tmp_file_path, $contents);
  9936. if ($res === false) {
  9937. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  9938. }
  9939. $files_cleanup[] = $tmp_file_path;
  9940. $my_xml_file_path = $my_file_path;
  9941. $my_sub_dir = dirname($my_file_path);
  9942. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9943. $my_xml_sub_dir = $my_sub_dir;
  9944. // Give a <resource> child to the <resources> element.
  9945. $my_resource = $xmldoc->createElement('resource');
  9946. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9947. $my_resource->setAttribute('type', 'webcontent');
  9948. $my_resource->setAttribute('href', $my_xml_file_path);
  9949. // adlcp:scormtype can be either 'sco' or 'asset'.
  9950. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9951. // xml:base is the base directory to find the files declared in this resource.
  9952. $my_resource->setAttribute('xml:base', '');
  9953. // Give a <file> child to the <resource> element.
  9954. $my_file = $xmldoc->createElement('file');
  9955. $my_file->setAttribute('href', $my_xml_file_path);
  9956. $my_resource->appendChild($my_file);
  9957. // Get included docs.
  9958. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  9959. // Dependency to other files - not yet supported.
  9960. $i = 1;
  9961. foreach ($inc_docs as $doc_info) {
  9962. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9963. continue;
  9964. }
  9965. $my_dep = $xmldoc->createElement('resource');
  9966. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9967. $my_dep->setAttribute('identifier', $res_id);
  9968. $my_dep->setAttribute('type', 'webcontent');
  9969. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9970. $my_dep_file = $xmldoc->createElement('file');
  9971. // Check type of URL.
  9972. if ($doc_info[1] == 'remote') {
  9973. // Remote file. Save url as is.
  9974. $my_dep_file->setAttribute('href', $doc_info[0]);
  9975. $my_dep->setAttribute('xml:base', '');
  9976. } elseif ($doc_info[1] == 'local') {
  9977. switch ($doc_info[2]) {
  9978. case 'url': // Local URL - save path as url for now, don't zip file.
  9979. // Save file but as local file (retrieve from URL).
  9980. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9981. $current_dir = dirname($abs_path);
  9982. $current_dir = str_replace('\\', '/', $current_dir);
  9983. $file_path = realpath($abs_path);
  9984. $file_path = str_replace('\\', '/', $file_path);
  9985. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9986. $my_dep->setAttribute('xml:base', '');
  9987. if (strstr($file_path, $main_path) !== false) {
  9988. // The calculated real path is really inside the chamilo root path.
  9989. // Reduce file path to what's under the DocumentRoot.
  9990. $file_path = substr($file_path, strlen($root_path));
  9991. $zip_files_abs[] = $file_path;
  9992. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => 'document/'.$file_path];
  9993. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9994. $my_dep->setAttribute('xml:base', '');
  9995. } elseif (empty($file_path)) {
  9996. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
  9997. if (strpos($document_root,-1) == '/') {
  9998. $document_root = substr(0, -1, $document_root);
  9999. }*/
  10000. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10001. $file_path = str_replace('//', '/', $file_path);
  10002. if (file_exists($file_path)) {
  10003. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  10004. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10005. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => 'document/'.$file_path];
  10006. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10007. $my_dep->setAttribute('xml:base', '');
  10008. }
  10009. }
  10010. break;
  10011. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10012. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10013. $current_dir = str_replace('\\', '/', $current_dir);
  10014. $file_path = realpath($doc_info[0]);
  10015. $file_path = str_replace('\\', '/', $file_path);
  10016. $my_dep_file->setAttribute('href', $file_path);
  10017. $my_dep->setAttribute('xml:base', '');
  10018. if (strstr($file_path, $main_path) !== false) {
  10019. // The calculated real path is really inside the chamilo root path.
  10020. // Reduce file path to what's under the DocumentRoot.
  10021. $file_path = substr($file_path, strlen($root_path));
  10022. $zip_files_abs[] = $file_path;
  10023. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10024. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10025. $my_dep->setAttribute('xml:base', '');
  10026. } elseif (empty($file_path)) {
  10027. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  10028. $file_path = str_replace('//', '/', $file_path);
  10029. if (file_exists($file_path)) {
  10030. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  10031. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10032. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10033. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10034. $my_dep->setAttribute('xml:base', '');
  10035. }
  10036. }
  10037. break;
  10038. case 'rel':
  10039. // Path relative to the current document. Save xml:base as current document's
  10040. // directory and save file in zip as subdir.file_path
  10041. if (substr($doc_info[0], 0, 2) == '..') {
  10042. // Relative path going up.
  10043. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10044. $current_dir = str_replace('\\', '/', $current_dir);
  10045. $file_path = realpath($current_dir.$doc_info[0]);
  10046. $file_path = str_replace('\\', '/', $file_path);
  10047. //error_log($file_path.' <-> '.$main_path, 0);
  10048. if (strstr($file_path, $main_path) !== false) {
  10049. // The calculated real path is really inside Chamilo's root path.
  10050. // Reduce file path to what's under the DocumentRoot.
  10051. $file_path = substr($file_path, strlen($root_path));
  10052. $file_path_dest = $file_path;
  10053. // File path is courses/CHAMILO/document/....
  10054. $info_file_path = explode('/', $file_path);
  10055. if ($info_file_path[0] == 'courses') {
  10056. // Add character "/" in file path.
  10057. $file_path_dest = 'document/'.$file_path;
  10058. }
  10059. //error_log('Reduced path: '.$file_path, 0);
  10060. $zip_files_abs[] = $file_path;
  10061. $link_updates[$my_file_path][] = [
  10062. 'orig' => $doc_info[0],
  10063. 'dest' => $file_path_dest,
  10064. ];
  10065. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10066. $my_dep->setAttribute('xml:base', '');
  10067. }
  10068. } else {
  10069. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10070. $my_dep_file->setAttribute('href', $doc_info[0]);
  10071. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10072. }
  10073. break;
  10074. default:
  10075. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10076. $my_dep->setAttribute('xml:base', '');
  10077. break;
  10078. }
  10079. }
  10080. $my_dep->appendChild($my_dep_file);
  10081. $resources->appendChild($my_dep);
  10082. $dependency = $xmldoc->createElement('dependency');
  10083. $dependency->setAttribute('identifierref', $res_id);
  10084. $my_resource->appendChild($dependency);
  10085. $i++;
  10086. }
  10087. $resources->appendChild($my_resource);
  10088. $zip_files[] = $my_file_path;
  10089. break;
  10090. default:
  10091. // Get the path of the file(s) from the course directory root
  10092. $my_file_path = 'non_exportable.html';
  10093. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10094. $my_xml_file_path = $my_file_path;
  10095. $my_sub_dir = dirname($my_file_path);
  10096. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10097. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10098. $my_xml_sub_dir = $my_sub_dir;
  10099. // Give a <resource> child to the <resources> element.
  10100. $my_resource = $xmldoc->createElement('resource');
  10101. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10102. $my_resource->setAttribute('type', 'webcontent');
  10103. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10104. // adlcp:scormtype can be either 'sco' or 'asset'.
  10105. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10106. // xml:base is the base directory to find the files declared in this resource.
  10107. $my_resource->setAttribute('xml:base', '');
  10108. // Give a <file> child to the <resource> element.
  10109. $my_file = $xmldoc->createElement('file');
  10110. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10111. $my_resource->appendChild($my_file);
  10112. $resources->appendChild($my_resource);
  10113. break;
  10114. }
  10115. }
  10116. }
  10117. $organizations->appendChild($organization);
  10118. $root->appendChild($organizations);
  10119. $root->appendChild($resources);
  10120. $xmldoc->appendChild($root);
  10121. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10122. // TODO: Add a readme file here, with a short description and a link to the Reload player
  10123. // then add the file to the zip, then destroy the file (this is done automatically).
  10124. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10125. foreach ($zip_files as $file_path) {
  10126. if (empty($file_path)) {
  10127. continue;
  10128. }
  10129. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10130. $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
  10131. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10132. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10133. }
  10134. $this->create_path($dest_file);
  10135. @copy($filePath, $dest_file);
  10136. // Check if the file needs a link update.
  10137. if (in_array($file_path, array_keys($link_updates))) {
  10138. $string = file_get_contents($dest_file);
  10139. unlink($dest_file);
  10140. foreach ($link_updates[$file_path] as $old_new) {
  10141. // This is an ugly hack that allows .flv files to be found by the flv player that
  10142. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10143. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10144. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10145. if (substr($old_new['dest'], -3) == 'flv' &&
  10146. substr($old_new['dest'], 0, 5) == 'main/'
  10147. ) {
  10148. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10149. } elseif (substr($old_new['dest'], -3) == 'flv' &&
  10150. substr($old_new['dest'], 0, 6) == 'video/'
  10151. ) {
  10152. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10153. }
  10154. //Fix to avoid problems with default_course_document
  10155. if (strpos("main/default_course_document", $old_new['dest'] === false)) {
  10156. //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
  10157. $newDestination = $old_new['dest'];
  10158. } else {
  10159. $newDestination = str_replace('document/', '', $old_new['dest']);
  10160. }
  10161. $string = str_replace($old_new['orig'], $newDestination, $string);
  10162. // Add files inside the HTMLs
  10163. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10164. $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
  10165. if (file_exists($sys_course_path.$new_path)) {
  10166. copy($sys_course_path.$new_path, $destinationFile);
  10167. }
  10168. }
  10169. file_put_contents($dest_file, $string);
  10170. }
  10171. if (file_exists($filePath) && $copyAll) {
  10172. $extension = $this->get_extension($filePath);
  10173. if (in_array($extension, ['html', 'html'])) {
  10174. $containerOrigin = dirname($filePath);
  10175. $containerDestination = dirname($dest_file);
  10176. $finder = new Finder();
  10177. $finder->files()->in($containerOrigin)
  10178. ->notName('*_DELETED_*')
  10179. ->exclude('share_folder')
  10180. ->exclude('chat_files')
  10181. ->exclude('certificates')
  10182. ;
  10183. if (is_dir($containerOrigin) &&
  10184. is_dir($containerDestination)
  10185. ) {
  10186. $fs = new Filesystem();
  10187. $fs->mirror(
  10188. $containerOrigin,
  10189. $containerDestination,
  10190. $finder
  10191. );
  10192. }
  10193. }
  10194. }
  10195. }
  10196. foreach ($zip_files_abs as $file_path) {
  10197. if (empty($file_path)) {
  10198. continue;
  10199. }
  10200. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10201. continue;
  10202. }
  10203. $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
  10204. $this->create_path($dest_file);
  10205. copy($main_path.$file_path, $dest_file);
  10206. // Check if the file needs a link update.
  10207. if (in_array($file_path, array_keys($link_updates))) {
  10208. $string = file_get_contents($dest_file);
  10209. unlink($dest_file);
  10210. foreach ($link_updates[$file_path] as $old_new) {
  10211. // This is an ugly hack that allows .flv files to be found by the flv player that
  10212. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10213. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10214. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10215. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  10216. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10217. }
  10218. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10219. }
  10220. file_put_contents($dest_file, $string);
  10221. }
  10222. }
  10223. if (is_array($links_to_create)) {
  10224. foreach ($links_to_create as $file => $link) {
  10225. $file_content = '<!DOCTYPE html><head>
  10226. <meta charset="'.api_get_language_isocode().'" />
  10227. <title>'.$link['title'].'</title>
  10228. </head>
  10229. <body dir="'.api_get_text_direction().'">
  10230. <div style="text-align:center">
  10231. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10232. </body>
  10233. </html>';
  10234. file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
  10235. }
  10236. }
  10237. // Add non exportable message explanation.
  10238. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10239. $file_content = '<!DOCTYPE html><head>
  10240. <meta charset="'.api_get_language_isocode().'" />
  10241. <title>'.$lang_not_exportable.'</title>
  10242. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10243. </head>
  10244. <body dir="'.api_get_text_direction().'">';
  10245. $file_content .=
  10246. <<<EOD
  10247. <style>
  10248. .error-message {
  10249. font-family: arial, verdana, helvetica, sans-serif;
  10250. border-width: 1px;
  10251. border-style: solid;
  10252. left: 50%;
  10253. margin: 10px auto;
  10254. min-height: 30px;
  10255. padding: 5px;
  10256. right: 50%;
  10257. width: 500px;
  10258. background-color: #FFD1D1;
  10259. border-color: #FF0000;
  10260. color: #000;
  10261. }
  10262. </style>
  10263. <body>
  10264. <div class="error-message">
  10265. $lang_not_exportable
  10266. </div>
  10267. </body>
  10268. </html>
  10269. EOD;
  10270. if (!is_dir($archive_path.$temp_dir_short.'/document')) {
  10271. @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10272. }
  10273. file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10274. // Add the extra files that go along with a SCORM package.
  10275. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10276. $fs = new Filesystem();
  10277. $fs->mirror($main_code_path, $archive_path.$temp_dir_short);
  10278. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10279. $manifest = @$xmldoc->saveXML();
  10280. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10281. file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10282. $zip_folder->add(
  10283. $archive_path.'/'.$temp_dir_short,
  10284. PCLZIP_OPT_REMOVE_PATH,
  10285. $archive_path.'/'.$temp_dir_short.'/'
  10286. );
  10287. // Clean possible temporary files.
  10288. foreach ($files_cleanup as $file) {
  10289. $res = unlink($file);
  10290. if ($res === false) {
  10291. error_log(
  10292. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10293. 0
  10294. );
  10295. }
  10296. }
  10297. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10298. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10299. }
  10300. /**
  10301. * @param int $lp_id
  10302. *
  10303. * @return bool
  10304. */
  10305. public function scorm_export_to_pdf($lp_id)
  10306. {
  10307. $lp_id = intval($lp_id);
  10308. $files_to_export = [];
  10309. $course_data = api_get_course_info($this->cc);
  10310. if (!empty($course_data)) {
  10311. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10312. $list = self::get_flat_ordered_items_list($lp_id);
  10313. if (!empty($list)) {
  10314. foreach ($list as $item_id) {
  10315. $item = $this->items[$item_id];
  10316. switch ($item->type) {
  10317. case 'document':
  10318. //Getting documents from a LP with chamilo documents
  10319. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10320. // Try loading document from the base course.
  10321. if (empty($file_data) && !empty($sessionId)) {
  10322. $file_data = DocumentManager::get_document_data_by_id(
  10323. $item->path,
  10324. $this->cc,
  10325. false,
  10326. 0
  10327. );
  10328. }
  10329. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10330. if (file_exists($file_path)) {
  10331. $files_to_export[] = [
  10332. 'title' => $item->get_title(),
  10333. 'path' => $file_path,
  10334. ];
  10335. }
  10336. break;
  10337. case 'asset': //commes from a scorm package generated by chamilo
  10338. case 'sco':
  10339. $file_path = $scorm_path.'/'.$item->path;
  10340. if (file_exists($file_path)) {
  10341. $files_to_export[] = [
  10342. 'title' => $item->get_title(),
  10343. 'path' => $file_path,
  10344. ];
  10345. }
  10346. break;
  10347. case 'dir':
  10348. $files_to_export[] = [
  10349. 'title' => $item->get_title(),
  10350. 'path' => null,
  10351. ];
  10352. break;
  10353. }
  10354. }
  10355. }
  10356. $pdf = new PDF();
  10357. $result = $pdf->html_to_pdf(
  10358. $files_to_export,
  10359. $this->name,
  10360. $this->cc,
  10361. true
  10362. );
  10363. return $result;
  10364. }
  10365. return false;
  10366. }
  10367. /**
  10368. * Temp function to be moved in main_api or the best place around for this.
  10369. * Creates a file path if it doesn't exist.
  10370. *
  10371. * @param string $path
  10372. */
  10373. public function create_path($path)
  10374. {
  10375. $path_bits = explode('/', dirname($path));
  10376. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10377. $path_built = IS_WINDOWS_OS ? '' : '/';
  10378. foreach ($path_bits as $bit) {
  10379. if (!empty($bit)) {
  10380. $new_path = $path_built.$bit;
  10381. if (is_dir($new_path)) {
  10382. $path_built = $new_path.'/';
  10383. } else {
  10384. mkdir($new_path, api_get_permissions_for_new_directories());
  10385. $path_built = $new_path.'/';
  10386. }
  10387. }
  10388. }
  10389. }
  10390. /**
  10391. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10392. *
  10393. * @return bool The results of the unlink function, or false if there was no image to start with
  10394. */
  10395. public function delete_lp_image()
  10396. {
  10397. $img = $this->get_preview_image();
  10398. if ($img != '') {
  10399. $del_file = $this->get_preview_image_path(null, 'sys');
  10400. if (isset($del_file) && file_exists($del_file)) {
  10401. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10402. if (file_exists($del_file_2)) {
  10403. unlink($del_file_2);
  10404. }
  10405. $this->set_preview_image('');
  10406. return @unlink($del_file);
  10407. }
  10408. }
  10409. return false;
  10410. }
  10411. /**
  10412. * Uploads an author image to the upload/learning_path/images directory.
  10413. *
  10414. * @param array The image array, coming from the $_FILES superglobal
  10415. *
  10416. * @return bool True on success, false on error
  10417. */
  10418. public function upload_image($image_array)
  10419. {
  10420. if (!empty($image_array['name'])) {
  10421. $upload_ok = process_uploaded_file($image_array);
  10422. $has_attachment = true;
  10423. }
  10424. if ($upload_ok && $has_attachment) {
  10425. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10426. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10427. $updir = $sys_course_path.$courseDir;
  10428. // Try to add an extension to the file if it hasn't one.
  10429. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10430. if (filter_extension($new_file_name)) {
  10431. $file_extension = explode('.', $image_array['name']);
  10432. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10433. $filename = uniqid('');
  10434. $new_file_name = $filename.'.'.$file_extension;
  10435. $new_path = $updir.'/'.$new_file_name;
  10436. // Resize the image.
  10437. $temp = new Image($image_array['tmp_name']);
  10438. $temp->resize(104);
  10439. $result = $temp->send_image($new_path);
  10440. // Storing the image filename.
  10441. if ($result) {
  10442. $this->set_preview_image($new_file_name);
  10443. //Resize to 64px to use on course homepage
  10444. $temp->resize(64);
  10445. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10446. return true;
  10447. }
  10448. }
  10449. }
  10450. return false;
  10451. }
  10452. /**
  10453. * @param int $lp_id
  10454. * @param string $status
  10455. */
  10456. public function set_autolaunch($lp_id, $status)
  10457. {
  10458. $course_id = api_get_course_int_id();
  10459. $lp_id = intval($lp_id);
  10460. $status = intval($status);
  10461. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10462. // Setting everything to autolaunch = 0
  10463. $attributes['autolaunch'] = 0;
  10464. $where = [
  10465. 'session_id = ? AND c_id = ? ' => [
  10466. api_get_session_id(),
  10467. $course_id,
  10468. ],
  10469. ];
  10470. Database::update($lp_table, $attributes, $where);
  10471. if ($status == 1) {
  10472. //Setting my lp_id to autolaunch = 1
  10473. $attributes['autolaunch'] = 1;
  10474. $where = [
  10475. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10476. $lp_id,
  10477. api_get_session_id(),
  10478. $course_id,
  10479. ],
  10480. ];
  10481. Database::update($lp_table, $attributes, $where);
  10482. }
  10483. }
  10484. /**
  10485. * Gets previous_item_id for the next element of the lp_item table.
  10486. *
  10487. * @author Isaac flores paz
  10488. *
  10489. * @return int Previous item ID
  10490. */
  10491. public function select_previous_item_id()
  10492. {
  10493. $course_id = api_get_course_int_id();
  10494. if ($this->debug > 0) {
  10495. error_log('In learnpath::select_previous_item_id()', 0);
  10496. }
  10497. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10498. // Get the max order of the items
  10499. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10500. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10501. $rs_max_order = Database::query($sql);
  10502. $row_max_order = Database::fetch_object($rs_max_order);
  10503. $max_order = $row_max_order->display_order;
  10504. // Get the previous item ID
  10505. $sql = "SELECT iid as previous FROM $table_lp_item
  10506. WHERE
  10507. c_id = $course_id AND
  10508. lp_id = ".$this->lp_id." AND
  10509. display_order = '$max_order' ";
  10510. $rs_max = Database::query($sql);
  10511. $row_max = Database::fetch_object($rs_max);
  10512. // Return the previous item ID
  10513. return $row_max->previous;
  10514. }
  10515. /**
  10516. * Copies an LP.
  10517. */
  10518. public function copy()
  10519. {
  10520. // Course builder
  10521. $cb = new CourseBuilder();
  10522. //Setting tools that will be copied
  10523. $cb->set_tools_to_build(['learnpaths']);
  10524. //Setting elements that will be copied
  10525. $cb->set_tools_specific_id_list(
  10526. ['learnpaths' => [$this->lp_id]]
  10527. );
  10528. $course = $cb->build();
  10529. //Course restorer
  10530. $course_restorer = new CourseRestorer($course);
  10531. $course_restorer->set_add_text_in_items(true);
  10532. $course_restorer->set_tool_copy_settings(
  10533. ['learnpaths' => ['reset_dates' => true]]
  10534. );
  10535. $course_restorer->restore(
  10536. api_get_course_id(),
  10537. api_get_session_id(),
  10538. false,
  10539. false
  10540. );
  10541. }
  10542. /**
  10543. * Verify document size.
  10544. *
  10545. * @param string $s
  10546. *
  10547. * @return bool
  10548. */
  10549. public static function verify_document_size($s)
  10550. {
  10551. $post_max = ini_get('post_max_size');
  10552. if (substr($post_max, -1, 1) == 'M') {
  10553. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10554. } elseif (substr($post_max, -1, 1) == 'G') {
  10555. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10556. }
  10557. $upl_max = ini_get('upload_max_filesize');
  10558. if (substr($upl_max, -1, 1) == 'M') {
  10559. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10560. } elseif (substr($upl_max, -1, 1) == 'G') {
  10561. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10562. }
  10563. $documents_total_space = DocumentManager::documents_total_space();
  10564. $course_max_space = DocumentManager::get_course_quota();
  10565. $total_size = filesize($s) + $documents_total_space;
  10566. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10567. return true;
  10568. } else {
  10569. return false;
  10570. }
  10571. }
  10572. /**
  10573. * Clear LP prerequisites.
  10574. */
  10575. public function clear_prerequisites()
  10576. {
  10577. $course_id = $this->get_course_int_id();
  10578. if ($this->debug > 0) {
  10579. error_log('In learnpath::clear_prerequisites()', 0);
  10580. }
  10581. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10582. $lp_id = $this->get_id();
  10583. //Cleaning prerequisites
  10584. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10585. WHERE c_id = $course_id AND lp_id = $lp_id";
  10586. Database::query($sql);
  10587. //Cleaning mastery score for exercises
  10588. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10589. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10590. Database::query($sql);
  10591. }
  10592. public function set_previous_step_as_prerequisite_for_all_items()
  10593. {
  10594. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10595. $course_id = $this->get_course_int_id();
  10596. $lp_id = $this->get_id();
  10597. if (!empty($this->items)) {
  10598. $previous_item_id = null;
  10599. $previous_item_max = 0;
  10600. $previous_item_type = null;
  10601. $last_item_not_dir = null;
  10602. $last_item_not_dir_type = null;
  10603. $last_item_not_dir_max = null;
  10604. foreach ($this->ordered_items as $itemId) {
  10605. $item = $this->getItem($itemId);
  10606. // if there was a previous item... (otherwise jump to set it)
  10607. if (!empty($previous_item_id)) {
  10608. $current_item_id = $item->get_id(); //save current id
  10609. if ($item->get_type() != 'dir') {
  10610. // Current item is not a folder, so it qualifies to get a prerequisites
  10611. if ($last_item_not_dir_type == 'quiz') {
  10612. // if previous is quiz, mark its max score as default score to be achieved
  10613. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10614. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10615. Database::query($sql);
  10616. }
  10617. // now simply update the prerequisite to set it to the last non-chapter item
  10618. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10619. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10620. Database::query($sql);
  10621. // record item as 'non-chapter' reference
  10622. $last_item_not_dir = $item->get_id();
  10623. $last_item_not_dir_type = $item->get_type();
  10624. $last_item_not_dir_max = $item->get_max();
  10625. }
  10626. } else {
  10627. if ($item->get_type() != 'dir') {
  10628. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10629. $last_item_not_dir = $item->get_id();
  10630. $last_item_not_dir_type = $item->get_type();
  10631. $last_item_not_dir_max = $item->get_max();
  10632. }
  10633. }
  10634. // Saving the item as "previous item" for the next loop
  10635. $previous_item_id = $item->get_id();
  10636. $previous_item_max = $item->get_max();
  10637. $previous_item_type = $item->get_type();
  10638. }
  10639. }
  10640. }
  10641. /**
  10642. * @param array $params
  10643. */
  10644. public static function createCategory($params)
  10645. {
  10646. $em = Database::getManager();
  10647. $item = new CLpCategory();
  10648. $item->setName($params['name']);
  10649. $item->setCId($params['c_id']);
  10650. $em->persist($item);
  10651. $em->flush();
  10652. }
  10653. /**
  10654. * @param array $params
  10655. */
  10656. public static function updateCategory($params)
  10657. {
  10658. $em = Database::getManager();
  10659. /** @var CLpCategory $item */
  10660. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10661. if ($item) {
  10662. $item->setName($params['name']);
  10663. $em->merge($item);
  10664. $em->flush();
  10665. }
  10666. }
  10667. /**
  10668. * @param int $id
  10669. */
  10670. public static function moveUpCategory($id)
  10671. {
  10672. $id = (int) $id;
  10673. $em = Database::getManager();
  10674. /** @var CLpCategory $item */
  10675. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10676. if ($item) {
  10677. $position = $item->getPosition() - 1;
  10678. $item->setPosition($position);
  10679. $em->persist($item);
  10680. $em->flush();
  10681. }
  10682. }
  10683. /**
  10684. * @param int $id
  10685. */
  10686. public static function moveDownCategory($id)
  10687. {
  10688. $id = (int) $id;
  10689. $em = Database::getManager();
  10690. /** @var CLpCategory $item */
  10691. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10692. if ($item) {
  10693. $position = $item->getPosition() + 1;
  10694. $item->setPosition($position);
  10695. $em->persist($item);
  10696. $em->flush();
  10697. }
  10698. }
  10699. /**
  10700. * @param int $courseId
  10701. *
  10702. * @return int|mixed
  10703. */
  10704. public static function getCountCategories($courseId)
  10705. {
  10706. if (empty($course_id)) {
  10707. return 0;
  10708. }
  10709. $em = Database::getManager();
  10710. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10711. $query->setParameter('id', $courseId);
  10712. return $query->getSingleScalarResult();
  10713. }
  10714. /**
  10715. * @param int $courseId
  10716. *
  10717. * @return mixed
  10718. */
  10719. public static function getCategories($courseId)
  10720. {
  10721. $em = Database::getManager();
  10722. //Default behaviour
  10723. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10724. array('cId' => $course_id),
  10725. array('name' => 'ASC')
  10726. );*/
  10727. // Using doctrine extensions
  10728. /** @var SortableRepository $repo */
  10729. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10730. $items = $repo
  10731. ->getBySortableGroupsQuery(['cId' => $courseId])
  10732. ->getResult();
  10733. return $items;
  10734. }
  10735. /**
  10736. * @param int $id
  10737. *
  10738. * @return CLpCategory
  10739. */
  10740. public static function getCategory($id)
  10741. {
  10742. $id = (int) $id;
  10743. $em = Database::getManager();
  10744. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10745. return $item;
  10746. }
  10747. /**
  10748. * @param int $courseId
  10749. *
  10750. * @return array
  10751. */
  10752. public static function getCategoryByCourse($courseId)
  10753. {
  10754. $em = Database::getManager();
  10755. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10756. ['cId' => $courseId]
  10757. );
  10758. return $items;
  10759. }
  10760. /**
  10761. * @param int $id
  10762. *
  10763. * @return mixed
  10764. */
  10765. public static function deleteCategory($id)
  10766. {
  10767. $em = Database::getManager();
  10768. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10769. if ($item) {
  10770. $courseId = $item->getCId();
  10771. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10772. $query->setParameter('id', $courseId);
  10773. $query->setParameter('catId', $item->getId());
  10774. $lps = $query->getResult();
  10775. // Setting category = 0.
  10776. if ($lps) {
  10777. foreach ($lps as $lpItem) {
  10778. $lpItem->setCategoryId(0);
  10779. }
  10780. }
  10781. // Removing category.
  10782. $em->remove($item);
  10783. $em->flush();
  10784. $courseInfo = api_get_course_info_by_id($courseId);
  10785. $sessionId = api_get_session_id();
  10786. // Delete link tool
  10787. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10788. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10789. // Delete tools
  10790. $sql = "DELETE FROM $tbl_tool
  10791. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10792. Database::query($sql);
  10793. }
  10794. }
  10795. /**
  10796. * @param int $courseId
  10797. * @param bool $addSelectOption
  10798. *
  10799. * @return mixed
  10800. */
  10801. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10802. {
  10803. $items = self::getCategoryByCourse($courseId);
  10804. $cats = [];
  10805. if ($addSelectOption) {
  10806. $cats = [get_lang('SelectACategory')];
  10807. }
  10808. if (!empty($items)) {
  10809. foreach ($items as $cat) {
  10810. $cats[$cat->getId()] = $cat->getName();
  10811. }
  10812. }
  10813. return $cats;
  10814. }
  10815. /**
  10816. * @param string $courseCode
  10817. * @param int $lpId
  10818. * @param int $user_id
  10819. *
  10820. * @return learnpath
  10821. */
  10822. public static function getLpFromSession($courseCode, $lpId, $user_id)
  10823. {
  10824. $debug = 0;
  10825. $learnPath = null;
  10826. $lpObject = Session::read('lpobject');
  10827. if ($lpObject !== null) {
  10828. if ($debug) {
  10829. error_log('getLpFromSession: unserialize');
  10830. }
  10831. $learnPath = unserialize($lpObject);
  10832. }
  10833. if (!is_object($learnPath)) {
  10834. if ($debug) {
  10835. error_log('------getLpFromSession------');
  10836. error_log('getLpFromSession: create new learnpath');
  10837. error_log("create new LP with $courseCode - $lpId - $user_id");
  10838. }
  10839. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  10840. }
  10841. return $learnPath;
  10842. }
  10843. /**
  10844. * @param int $itemId
  10845. *
  10846. * @return learnpathItem|false
  10847. */
  10848. public function getItem($itemId)
  10849. {
  10850. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  10851. return $this->items[$itemId];
  10852. }
  10853. return false;
  10854. }
  10855. /**
  10856. * @return int
  10857. */
  10858. public function getCategoryId()
  10859. {
  10860. return $this->categoryId;
  10861. }
  10862. /**
  10863. * @param int $categoryId
  10864. *
  10865. * @return bool
  10866. */
  10867. public function setCategoryId($categoryId)
  10868. {
  10869. $this->categoryId = intval($categoryId);
  10870. $table = Database::get_course_table(TABLE_LP_MAIN);
  10871. $lp_id = $this->get_id();
  10872. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  10873. WHERE iid = $lp_id";
  10874. Database::query($sql);
  10875. return true;
  10876. }
  10877. /**
  10878. * Get whether this is a learning path with the possibility to subscribe
  10879. * users or not.
  10880. *
  10881. * @return int
  10882. */
  10883. public function getSubscribeUsers()
  10884. {
  10885. return $this->subscribeUsers;
  10886. }
  10887. /**
  10888. * Set whether this is a learning path with the possibility to subscribe
  10889. * users or not.
  10890. *
  10891. * @param int $value (0 = false, 1 = true)
  10892. *
  10893. * @return bool
  10894. */
  10895. public function setSubscribeUsers($value)
  10896. {
  10897. if ($this->debug > 0) {
  10898. error_log('In learnpath::set_subscribe_users()', 0);
  10899. }
  10900. $this->subscribeUsers = (int) $value;
  10901. $table = Database::get_course_table(TABLE_LP_MAIN);
  10902. $lp_id = $this->get_id();
  10903. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  10904. WHERE iid = $lp_id";
  10905. Database::query($sql);
  10906. return true;
  10907. }
  10908. /**
  10909. * Calculate the count of stars for a user in this LP
  10910. * This calculation is based on the following rules:
  10911. * - the student gets one star when he gets to 50% of the learning path
  10912. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  10913. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  10914. * - the student gets the final star when the score for the *last* test is >= 80%.
  10915. *
  10916. * @param int $sessionId Optional. The session ID
  10917. *
  10918. * @return int The count of stars
  10919. */
  10920. public function getCalculateStars($sessionId = 0)
  10921. {
  10922. $stars = 0;
  10923. $progress = self::getProgress(
  10924. $this->lp_id,
  10925. $this->user_id,
  10926. $this->course_int_id,
  10927. $sessionId
  10928. );
  10929. if ($progress >= 50) {
  10930. $stars++;
  10931. }
  10932. // Calculate stars chapters evaluation
  10933. $exercisesItems = $this->getExercisesItems();
  10934. if (!empty($exercisesItems)) {
  10935. $totalResult = 0;
  10936. foreach ($exercisesItems as $exerciseItem) {
  10937. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10938. $this->user_id,
  10939. $exerciseItem->path,
  10940. $this->course_int_id,
  10941. $sessionId,
  10942. $this->lp_id,
  10943. $exerciseItem->db_id
  10944. );
  10945. $exerciseResultInfo = end($exerciseResultInfo);
  10946. if (!$exerciseResultInfo) {
  10947. continue;
  10948. }
  10949. if (!empty($exerciseResultInfo['exe_weighting'])) {
  10950. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  10951. } else {
  10952. $exerciseResult = 0;
  10953. }
  10954. $totalResult += $exerciseResult;
  10955. }
  10956. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  10957. if ($totalExerciseAverage >= 50) {
  10958. $stars++;
  10959. }
  10960. if ($totalExerciseAverage >= 80) {
  10961. $stars++;
  10962. }
  10963. }
  10964. // Calculate star for final evaluation
  10965. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10966. if (!empty($finalEvaluationItem)) {
  10967. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10968. $this->user_id,
  10969. $finalEvaluationItem->path,
  10970. $this->course_int_id,
  10971. $sessionId,
  10972. $this->lp_id,
  10973. $finalEvaluationItem->db_id
  10974. );
  10975. $evaluationResultInfo = end($evaluationResultInfo);
  10976. if ($evaluationResultInfo) {
  10977. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  10978. if ($evaluationResult >= 80) {
  10979. $stars++;
  10980. }
  10981. }
  10982. }
  10983. return $stars;
  10984. }
  10985. /**
  10986. * Get the items of exercise type.
  10987. *
  10988. * @return array The items. Otherwise return false
  10989. */
  10990. public function getExercisesItems()
  10991. {
  10992. $exercises = [];
  10993. foreach ($this->items as $item) {
  10994. if ($item->type != 'quiz') {
  10995. continue;
  10996. }
  10997. $exercises[] = $item;
  10998. }
  10999. array_pop($exercises);
  11000. return $exercises;
  11001. }
  11002. /**
  11003. * Get the item of exercise type (evaluation type).
  11004. *
  11005. * @return array The final evaluation. Otherwise return false
  11006. */
  11007. public function getFinalEvaluationItem()
  11008. {
  11009. $exercises = [];
  11010. foreach ($this->items as $item) {
  11011. if ($item->type != 'quiz') {
  11012. continue;
  11013. }
  11014. $exercises[] = $item;
  11015. }
  11016. return array_pop($exercises);
  11017. }
  11018. /**
  11019. * Calculate the total points achieved for the current user in this learning path.
  11020. *
  11021. * @param int $sessionId Optional. The session Id
  11022. *
  11023. * @return int
  11024. */
  11025. public function getCalculateScore($sessionId = 0)
  11026. {
  11027. // Calculate stars chapters evaluation
  11028. $exercisesItems = $this->getExercisesItems();
  11029. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11030. $totalExercisesResult = 0;
  11031. $totalEvaluationResult = 0;
  11032. if ($exercisesItems !== false) {
  11033. foreach ($exercisesItems as $exerciseItem) {
  11034. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11035. $this->user_id,
  11036. $exerciseItem->path,
  11037. $this->course_int_id,
  11038. $sessionId,
  11039. $this->lp_id,
  11040. $exerciseItem->db_id
  11041. );
  11042. $exerciseResultInfo = end($exerciseResultInfo);
  11043. if (!$exerciseResultInfo) {
  11044. continue;
  11045. }
  11046. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11047. }
  11048. }
  11049. if (!empty($finalEvaluationItem)) {
  11050. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11051. $this->user_id,
  11052. $finalEvaluationItem->path,
  11053. $this->course_int_id,
  11054. $sessionId,
  11055. $this->lp_id,
  11056. $finalEvaluationItem->db_id
  11057. );
  11058. $evaluationResultInfo = end($evaluationResultInfo);
  11059. if ($evaluationResultInfo) {
  11060. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11061. }
  11062. }
  11063. return $totalExercisesResult + $totalEvaluationResult;
  11064. }
  11065. /**
  11066. * Check if URL is not allowed to be show in a iframe.
  11067. *
  11068. * @param string $src
  11069. *
  11070. * @return string
  11071. */
  11072. public function fixBlockedLinks($src)
  11073. {
  11074. $urlInfo = parse_url($src);
  11075. $platformProtocol = 'https';
  11076. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11077. $platformProtocol = 'http';
  11078. }
  11079. $protocolFixApplied = false;
  11080. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11081. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11082. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11083. if ($platformProtocol != $scheme) {
  11084. Session::write('x_frame_source', $src);
  11085. $src = 'blank.php?error=x_frames_options';
  11086. $protocolFixApplied = true;
  11087. }
  11088. if ($protocolFixApplied == false) {
  11089. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11090. // Check X-Frame-Options
  11091. $ch = curl_init();
  11092. $options = [
  11093. CURLOPT_URL => $src,
  11094. CURLOPT_RETURNTRANSFER => true,
  11095. CURLOPT_HEADER => true,
  11096. CURLOPT_FOLLOWLOCATION => true,
  11097. CURLOPT_ENCODING => "",
  11098. CURLOPT_AUTOREFERER => true,
  11099. CURLOPT_CONNECTTIMEOUT => 120,
  11100. CURLOPT_TIMEOUT => 120,
  11101. CURLOPT_MAXREDIRS => 10,
  11102. ];
  11103. curl_setopt_array($ch, $options);
  11104. $response = curl_exec($ch);
  11105. $httpCode = curl_getinfo($ch);
  11106. $headers = substr($response, 0, $httpCode['header_size']);
  11107. $error = false;
  11108. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11109. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11110. ) {
  11111. $error = true;
  11112. }
  11113. if ($error) {
  11114. Session::write('x_frame_source', $src);
  11115. $src = 'blank.php?error=x_frames_options';
  11116. }
  11117. }
  11118. }
  11119. return $src;
  11120. }
  11121. /**
  11122. * Check if this LP has a created forum in the basis course.
  11123. *
  11124. * @return bool
  11125. */
  11126. public function lpHasForum()
  11127. {
  11128. $forumTable = Database::get_course_table(TABLE_FORUM);
  11129. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11130. $fakeFrom = "
  11131. $forumTable f
  11132. INNER JOIN $itemProperty ip
  11133. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11134. ";
  11135. $resultData = Database::select(
  11136. 'COUNT(f.iid) AS qty',
  11137. $fakeFrom,
  11138. [
  11139. 'where' => [
  11140. 'ip.visibility != ? AND ' => 2,
  11141. 'ip.tool = ? AND ' => TOOL_FORUM,
  11142. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11143. 'f.lp_id = ?' => intval($this->lp_id),
  11144. ],
  11145. ],
  11146. 'first'
  11147. );
  11148. return $resultData['qty'] > 0;
  11149. }
  11150. /**
  11151. * Get the forum for this learning path.
  11152. *
  11153. * @param int $sessionId
  11154. *
  11155. * @return bool
  11156. */
  11157. public function getForum($sessionId = 0)
  11158. {
  11159. $forumTable = Database::get_course_table(TABLE_FORUM);
  11160. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11161. $fakeFrom = "$forumTable f
  11162. INNER JOIN $itemProperty ip ";
  11163. if ($this->lp_session_id == 0) {
  11164. $fakeFrom .= "
  11165. ON (
  11166. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11167. f.session_id = ip.session_id OR ip.session_id IS NULL
  11168. )
  11169. )
  11170. ";
  11171. } else {
  11172. $fakeFrom .= "
  11173. ON (
  11174. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11175. )
  11176. ";
  11177. }
  11178. $resultData = Database::select(
  11179. 'f.*',
  11180. $fakeFrom,
  11181. [
  11182. 'where' => [
  11183. 'ip.visibility != ? AND ' => 2,
  11184. 'ip.tool = ? AND ' => TOOL_FORUM,
  11185. 'f.session_id = ? AND ' => $sessionId,
  11186. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11187. 'f.lp_id = ?' => intval($this->lp_id),
  11188. ],
  11189. ],
  11190. 'first'
  11191. );
  11192. if (empty($resultData)) {
  11193. return false;
  11194. }
  11195. return $resultData;
  11196. }
  11197. /**
  11198. * Create a forum for this learning path.
  11199. *
  11200. * @param int $forumCategoryId
  11201. *
  11202. * @return int The forum ID if was created. Otherwise return false
  11203. */
  11204. public function createForum($forumCategoryId)
  11205. {
  11206. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11207. $forumId = store_forum(
  11208. [
  11209. 'lp_id' => $this->lp_id,
  11210. 'forum_title' => $this->name,
  11211. 'forum_comment' => null,
  11212. 'forum_category' => intval($forumCategoryId),
  11213. 'students_can_edit_group' => ['students_can_edit' => 0],
  11214. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11215. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11216. 'group_forum' => 0,
  11217. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11218. ],
  11219. [],
  11220. true
  11221. );
  11222. return $forumId;
  11223. }
  11224. /**
  11225. * Get the LP Final Item form.
  11226. *
  11227. * @return string
  11228. */
  11229. public function getFinalItemForm()
  11230. {
  11231. $finalItem = $this->getFinalItem();
  11232. $title = '';
  11233. if ($finalItem) {
  11234. $title = $finalItem->get_title();
  11235. $buttonText = get_lang('Save');
  11236. $content = $this->getSavedFinalItem();
  11237. } else {
  11238. $buttonText = get_lang('LPCreateDocument');
  11239. $content = $this->getFinalItemTemplate();
  11240. }
  11241. $courseInfo = api_get_course_info();
  11242. $result = $this->generate_lp_folder($courseInfo);
  11243. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11244. $relative_prefix = '../../';
  11245. $editorConfig = [
  11246. 'ToolbarSet' => 'LearningPathDocuments',
  11247. 'Width' => '100%',
  11248. 'Height' => '500',
  11249. 'FullPage' => true,
  11250. 'CreateDocumentDir' => $relative_prefix,
  11251. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11252. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11253. ];
  11254. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11255. 'type' => 'document',
  11256. 'lp_id' => $this->lp_id,
  11257. ]);
  11258. $form = new FormValidator('final_item', 'POST', $url);
  11259. $form->addText('title', get_lang('Title'));
  11260. $form->addButtonSave($buttonText);
  11261. $form->addHtml(
  11262. Display::return_message(
  11263. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11264. 'normal',
  11265. false
  11266. )
  11267. );
  11268. $renderer = $form->defaultRenderer();
  11269. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11270. $form->addHtmlEditor(
  11271. 'content_lp_certificate',
  11272. null,
  11273. true,
  11274. false,
  11275. $editorConfig,
  11276. true
  11277. );
  11278. $form->addHidden('action', 'add_final_item');
  11279. $form->addHidden('path', Session::read('pathItem'));
  11280. $form->addHidden('previous', $this->get_last());
  11281. $form->setDefaults(
  11282. ['title' => $title, 'content_lp_certificate' => $content]
  11283. );
  11284. if ($form->validate()) {
  11285. $values = $form->exportValues();
  11286. $lastItemId = $this->get_last();
  11287. if (!$finalItem) {
  11288. $documentId = $this->create_document(
  11289. $this->course_info,
  11290. $values['content_lp_certificate'],
  11291. $values['title']
  11292. );
  11293. $this->add_item(
  11294. 0,
  11295. $lastItemId,
  11296. 'final_item',
  11297. $documentId,
  11298. $values['title'],
  11299. ''
  11300. );
  11301. Display::addFlash(
  11302. Display::return_message(get_lang('Added'))
  11303. );
  11304. } else {
  11305. $this->edit_document($this->course_info);
  11306. }
  11307. }
  11308. return $form->returnForm();
  11309. }
  11310. /**
  11311. * Check if the current lp item is first, both, last or none from lp list.
  11312. *
  11313. * @param int $currentItemId
  11314. *
  11315. * @return string
  11316. */
  11317. public function isFirstOrLastItem($currentItemId)
  11318. {
  11319. if ($this->debug > 0) {
  11320. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11321. }
  11322. $lpItemId = [];
  11323. $typeListNotToVerify = self::getChapterTypes();
  11324. // Using get_toc() function instead $this->items because returns the correct order of the items
  11325. foreach ($this->get_toc() as $item) {
  11326. if (!in_array($item['type'], $typeListNotToVerify)) {
  11327. $lpItemId[] = $item['id'];
  11328. }
  11329. }
  11330. $lastLpItemIndex = count($lpItemId) - 1;
  11331. $position = array_search($currentItemId, $lpItemId);
  11332. switch ($position) {
  11333. case 0:
  11334. if (!$lastLpItemIndex) {
  11335. $answer = 'both';
  11336. break;
  11337. }
  11338. $answer = 'first';
  11339. break;
  11340. case $lastLpItemIndex:
  11341. $answer = 'last';
  11342. break;
  11343. default:
  11344. $answer = 'none';
  11345. }
  11346. return $answer;
  11347. }
  11348. /**
  11349. * Get whether this is a learning path with the accumulated SCORM time or not.
  11350. *
  11351. * @return int
  11352. */
  11353. public function getAccumulateScormTime()
  11354. {
  11355. return $this->accumulateScormTime;
  11356. }
  11357. /**
  11358. * Set whether this is a learning path with the accumulated SCORM time or not.
  11359. *
  11360. * @param int $value (0 = false, 1 = true)
  11361. *
  11362. * @return bool Always returns true
  11363. */
  11364. public function setAccumulateScormTime($value)
  11365. {
  11366. if ($this->debug > 0) {
  11367. error_log('In learnpath::setAccumulateScormTime()', 0);
  11368. }
  11369. $this->accumulateScormTime = intval($value);
  11370. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11371. $lp_id = $this->get_id();
  11372. $sql = "UPDATE $lp_table
  11373. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11374. WHERE iid = $lp_id";
  11375. Database::query($sql);
  11376. return true;
  11377. }
  11378. /**
  11379. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11380. * the new learning path tool.
  11381. *
  11382. * The function is a big switch on tool type.
  11383. * In each case, we query the corresponding table for information and build the link
  11384. * with that information.
  11385. *
  11386. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11387. * previous work (display_addedresource_link_in_learnpath())
  11388. *
  11389. * @param int $course_id Course code
  11390. * @param int $learningPathId The learning path ID (in lp table)
  11391. * @param int $id_in_path the unique index in the items table
  11392. * @param int $lpViewId
  11393. *
  11394. * @return string
  11395. */
  11396. public static function rl_get_resource_link_for_learnpath(
  11397. $course_id,
  11398. $learningPathId,
  11399. $id_in_path,
  11400. $lpViewId
  11401. ) {
  11402. $session_id = api_get_session_id();
  11403. $course_info = api_get_course_info_by_id($course_id);
  11404. $learningPathId = intval($learningPathId);
  11405. $id_in_path = intval($id_in_path);
  11406. $lpViewId = intval($lpViewId);
  11407. $em = Database::getManager();
  11408. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11409. /** @var CLpItem $rowItem */
  11410. $rowItem = $lpItemRepo->findOneBy([
  11411. 'cId' => $course_id,
  11412. 'lpId' => $learningPathId,
  11413. 'id' => $id_in_path,
  11414. ]);
  11415. if (!$rowItem) {
  11416. // Try one more time with iid
  11417. /** @var CLpItem $rowItem */
  11418. $rowItem = $lpItemRepo->findOneBy([
  11419. 'cId' => $course_id,
  11420. 'lpId' => $learningPathId,
  11421. 'iid' => $id_in_path,
  11422. ]);
  11423. if (!$rowItem) {
  11424. return -1;
  11425. }
  11426. }
  11427. $course_code = $course_info['code'];
  11428. $type = $rowItem->getItemType();
  11429. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11430. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11431. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11432. $link = '';
  11433. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11434. switch ($type) {
  11435. case 'dir':
  11436. return $main_dir_path.'lp/blank.php';
  11437. case TOOL_CALENDAR_EVENT:
  11438. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11439. case TOOL_ANNOUNCEMENT:
  11440. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11441. case TOOL_LINK:
  11442. $linkInfo = Link::getLinkInfo($id);
  11443. if (isset($linkInfo['url'])) {
  11444. return $linkInfo['url'];
  11445. }
  11446. return '';
  11447. case TOOL_QUIZ:
  11448. if (empty($id)) {
  11449. return '';
  11450. }
  11451. // Get the lp_item_view with the highest view_count.
  11452. $learnpathItemViewResult = $em
  11453. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11454. ->findBy(
  11455. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11456. ['viewCount' => 'DESC'],
  11457. 1
  11458. );
  11459. /** @var CLpItemView $learnpathItemViewData */
  11460. $learnpathItemViewData = current($learnpathItemViewResult);
  11461. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11462. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11463. .http_build_query([
  11464. 'lp_init' => 1,
  11465. 'learnpath_item_view_id' => $learnpathItemViewId,
  11466. 'learnpath_id' => $learningPathId,
  11467. 'learnpath_item_id' => $id_in_path,
  11468. 'exerciseId' => $id,
  11469. ]);
  11470. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11471. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11472. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11473. $myrow = Database::fetch_array($result);
  11474. $path = $myrow['path'];
  11475. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11476. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11477. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11478. case TOOL_FORUM:
  11479. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11480. case TOOL_THREAD: //forum post
  11481. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11482. if (empty($id)) {
  11483. return '';
  11484. }
  11485. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11486. $result = Database::query($sql);
  11487. $myrow = Database::fetch_array($result);
  11488. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11489. .$extraParams;
  11490. case TOOL_POST:
  11491. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11492. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11493. $myrow = Database::fetch_array($result);
  11494. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11495. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11496. case TOOL_DOCUMENT:
  11497. $document = $em
  11498. ->getRepository('ChamiloCourseBundle:CDocument')
  11499. ->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11500. if (!$document) {
  11501. return '';
  11502. }
  11503. $documentPathInfo = pathinfo($document->getPath());
  11504. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  11505. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11506. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  11507. $openmethod = 2;
  11508. $officedoc = false;
  11509. Session::write('openmethod', $openmethod);
  11510. Session::write('officedoc', $officedoc);
  11511. if ($showDirectUrl) {
  11512. return $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11513. }
  11514. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11515. case TOOL_LP_FINAL_ITEM:
  11516. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11517. .$extraParams;
  11518. case 'assignments':
  11519. return $main_dir_path.'work/work.php?'.$extraParams;
  11520. case TOOL_DROPBOX:
  11521. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11522. case 'introduction_text': //DEPRECATED
  11523. return '';
  11524. case TOOL_COURSE_DESCRIPTION:
  11525. return $main_dir_path.'course_description?'.$extraParams;
  11526. case TOOL_GROUP:
  11527. return $main_dir_path.'group/group.php?'.$extraParams;
  11528. case TOOL_USER:
  11529. return $main_dir_path.'user/user.php?'.$extraParams;
  11530. case TOOL_STUDENTPUBLICATION:
  11531. if (!empty($rowItem->getPath())) {
  11532. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11533. }
  11534. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11535. } //end switch
  11536. return $link;
  11537. }
  11538. /**
  11539. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11540. *
  11541. * @author Yannick Warnier <ywarnier@beeznest.org>
  11542. *
  11543. * @param string Course code
  11544. * @param string The tool type (using constants declared in main_api.lib.php)
  11545. * @param int The resource ID
  11546. *
  11547. * @return string
  11548. */
  11549. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11550. {
  11551. $_course = api_get_course_info($course_code);
  11552. $course_id = $_course['real_id'];
  11553. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11554. $learningPathId = intval($learningPathId);
  11555. $id_in_path = intval($id_in_path);
  11556. $sql_item = "SELECT item_type, title, ref FROM $tbl_lp_item
  11557. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11558. $res_item = Database::query($sql_item);
  11559. if (Database::num_rows($res_item) < 1) {
  11560. return '';
  11561. }
  11562. $row_item = Database::fetch_array($res_item);
  11563. $type = strtolower($row_item['item_type']);
  11564. $id = $row_item['ref'];
  11565. $output = '';
  11566. switch ($type) {
  11567. case TOOL_CALENDAR_EVENT:
  11568. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11569. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11570. $myrow = Database::fetch_array($result);
  11571. $output = $myrow['title'];
  11572. break;
  11573. case TOOL_ANNOUNCEMENT:
  11574. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11575. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11576. $myrow = Database::fetch_array($result);
  11577. $output = $myrow['title'];
  11578. break;
  11579. case TOOL_LINK:
  11580. // Doesn't take $target into account.
  11581. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11582. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11583. $myrow = Database::fetch_array($result);
  11584. $output = $myrow['title'];
  11585. break;
  11586. case TOOL_QUIZ:
  11587. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11588. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
  11589. $myrow = Database::fetch_array($result);
  11590. $output = $myrow['title'];
  11591. break;
  11592. case TOOL_FORUM:
  11593. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11594. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
  11595. $myrow = Database::fetch_array($result);
  11596. $output = $myrow['forum_name'];
  11597. break;
  11598. case TOOL_THREAD: //=topics
  11599. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11600. // Grabbing the title of the post.
  11601. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11602. $result_title = Database::query($sql_title);
  11603. $myrow_title = Database::fetch_array($result_title);
  11604. $output = $myrow_title['post_title'];
  11605. break;
  11606. case TOOL_POST:
  11607. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11608. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  11609. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11610. $result = Database::query($sql);
  11611. $post = Database::fetch_array($result);
  11612. $output = $post['post_title'];
  11613. break;
  11614. case 'dir':
  11615. $title = $row_item['title'];
  11616. if (!empty($title)) {
  11617. $output = $title;
  11618. } else {
  11619. $output = '-';
  11620. }
  11621. break;
  11622. case TOOL_DOCUMENT:
  11623. $title = $row_item['title'];
  11624. if (!empty($title)) {
  11625. $output = $title;
  11626. } else {
  11627. $output = '-';
  11628. }
  11629. break;
  11630. case 'hotpotatoes':
  11631. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11632. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11633. $myrow = Database::fetch_array($result);
  11634. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11635. $last = count($pathname) - 1; // Making a correct name for the link.
  11636. $filename = $pathname[$last]; // Making a correct name for the link.
  11637. $ext = explode('.', $filename);
  11638. $ext = strtolower($ext[sizeof($ext) - 1]);
  11639. $myrow['path'] = rawurlencode($myrow['path']);
  11640. $output = $filename;
  11641. break;
  11642. }
  11643. return stripslashes($output);
  11644. }
  11645. /**
  11646. * Get the parent names for the current item.
  11647. *
  11648. * @param int $newItemId Optional. The item ID
  11649. *
  11650. * @return array
  11651. */
  11652. public function getCurrentItemParentNames($newItemId = 0)
  11653. {
  11654. $newItemId = $newItemId ?: $this->get_current_item_id();
  11655. $return = [];
  11656. $item = $this->getItem($newItemId);
  11657. $parent = $this->getItem($item->get_parent());
  11658. while ($parent) {
  11659. $return[] = $parent->get_title();
  11660. $parent = $this->getItem($parent->get_parent());
  11661. }
  11662. return array_reverse($return);
  11663. }
  11664. /**
  11665. * Reads and process "lp_subscription_settings" setting.
  11666. *
  11667. * @return array
  11668. */
  11669. public static function getSubscriptionSettings()
  11670. {
  11671. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11672. if (empty($subscriptionSettings)) {
  11673. // By default allow both settings
  11674. $subscriptionSettings = [
  11675. 'allow_add_users_to_lp' => true,
  11676. 'allow_add_users_to_lp_category' => true,
  11677. ];
  11678. } else {
  11679. $subscriptionSettings = $subscriptionSettings['options'];
  11680. }
  11681. return $subscriptionSettings;
  11682. }
  11683. /**
  11684. * Get the depth level of LP item.
  11685. *
  11686. * @param array $items
  11687. * @param int $currentItemId
  11688. *
  11689. * @return int
  11690. */
  11691. private static function get_level_for_item($items, $currentItemId)
  11692. {
  11693. $parentItemId = $items[$currentItemId]->parent;
  11694. if ($parentItemId == 0) {
  11695. return 0;
  11696. } else {
  11697. return self::get_level_for_item($items, $parentItemId) + 1;
  11698. }
  11699. }
  11700. /**
  11701. * Generate the link for a learnpath category as course tool.
  11702. *
  11703. * @param int $categoryId
  11704. *
  11705. * @return string
  11706. */
  11707. private static function getCategoryLinkForTool($categoryId)
  11708. {
  11709. $categoryId = (int) $categoryId;
  11710. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  11711. .http_build_query(
  11712. [
  11713. 'action' => 'view_category',
  11714. 'id' => $categoryId,
  11715. ]
  11716. );
  11717. return $link;
  11718. }
  11719. /**
  11720. * Return the scorm item type object with spaces replaced with _
  11721. * The return result is use to build a css classname like scorm_type_$return.
  11722. *
  11723. * @param $in_type
  11724. *
  11725. * @return mixed
  11726. */
  11727. private static function format_scorm_type_item($in_type)
  11728. {
  11729. return str_replace(' ', '_', $in_type);
  11730. }
  11731. /**
  11732. * Check and obtain the lp final item if exist.
  11733. *
  11734. * @return learnpathItem
  11735. */
  11736. private function getFinalItem()
  11737. {
  11738. if (empty($this->items)) {
  11739. return null;
  11740. }
  11741. foreach ($this->items as $item) {
  11742. if ($item->type !== 'final_item') {
  11743. continue;
  11744. }
  11745. return $item;
  11746. }
  11747. }
  11748. /**
  11749. * Get the LP Final Item Template.
  11750. *
  11751. * @return string
  11752. */
  11753. private function getFinalItemTemplate()
  11754. {
  11755. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  11756. }
  11757. /**
  11758. * Get the LP Final Item Url.
  11759. *
  11760. * @return string
  11761. */
  11762. private function getSavedFinalItem()
  11763. {
  11764. $finalItem = $this->getFinalItem();
  11765. $doc = DocumentManager::get_document_data_by_id(
  11766. $finalItem->path,
  11767. $this->cc
  11768. );
  11769. if ($doc && file_exists($doc['absolute_path'])) {
  11770. return file_get_contents($doc['absolute_path']);
  11771. }
  11772. return '';
  11773. }
  11774. }