learnpath.class.php 492 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CourseBundle\Entity\CLpCategory;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  8. use Symfony\Component\Filesystem\Filesystem;
  9. use Symfony\Component\Finder\Finder;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CTool;
  12. use Chamilo\UserBundle\Entity\User;
  13. use Chamilo\CourseBundle\Entity\CLpItem;
  14. use Chamilo\CourseBundle\Entity\CLpItemView;
  15. use Chamilo\CourseBundle\Entity\CItemProperty;
  16. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  17. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  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. * @todo decouple class
  23. * @package chamilo.learnpath
  24. * @author Yannick Warnier <ywarnier@beeznest.org>
  25. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  26. */
  27. class learnpath
  28. {
  29. public $attempt = 0; // The number for the current ID view.
  30. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  31. public $current; // Id of the current item the user is viewing.
  32. public $current_score; // The score of the current item.
  33. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  34. public $current_time_stop; // The time the user closed this resource.
  35. public $default_status = 'not attempted';
  36. public $encoding = 'UTF-8';
  37. public $error = '';
  38. public $extra_information = ''; // This string can be used by proprietary SCORM contents to store data about the current learnpath.
  39. public $force_commit = false; // For SCORM only - if set to true, will send a scorm LMSCommit() request on each LMSSetValue().
  40. public $index; // The index of the active learnpath_item in $ordered_items array.
  41. public $items = array();
  42. public $last; // item_id of last item viewed in the learning path.
  43. public $last_item_seen = 0; // In case we have already come in this learnpath, reuse the last item seen if authorized.
  44. public $license; // Which license this course has been given - not used yet on 20060522.
  45. public $lp_id; // DB ID for this learnpath.
  46. public $lp_view_id; // DB ID for lp_view
  47. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  48. public $message = '';
  49. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  50. public $name; // Learnpath name (they generally have one).
  51. public $ordered_items = array(); // List of the learnpath items in the order they are to be read.
  52. public $path = ''; // Path inside the scorm directory (if scorm).
  53. public $theme; // The current theme of the learning path.
  54. public $preview_image; // The current image of the learning path.
  55. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  56. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  57. public $prevent_reinit = 1;
  58. // Describes the mode of progress bar display.
  59. public $seriousgame_mode = 0;
  60. public $progress_bar_mode = '%';
  61. // Percentage progress as saved in the db.
  62. public $progress_db = 0;
  63. public $proximity; // Wether the content is distant or local or unknown.
  64. public $refs_list = array(); //list of items by ref => db_id. Used only for prerequisites match.
  65. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  66. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  67. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  68. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  69. public $user_id; //ID of the user that is viewing/using the course
  70. public $update_queue = array();
  71. public $scorm_debug = 0;
  72. public $arrMenu = array(); // Array for the menu items.
  73. public $debug = 0; // Logging level.
  74. public $lp_session_id = 0;
  75. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  76. public $prerequisite = 0;
  77. public $use_max_score = 1; // 1 or 0
  78. public $subscribeUsers = 0; // Subscribe users or not
  79. public $created_on = '';
  80. public $modified_on = '';
  81. public $publicated_on = '';
  82. public $expired_on = '';
  83. public $ref = null;
  84. public $course_int_id;
  85. public $course_info = array();
  86. public $categoryId;
  87. /**
  88. * Constructor.
  89. * Needs a database handler, a course code and a learnpath id from the database.
  90. * Also builds the list of items into $this->items.
  91. * @param string $course Course code
  92. * @param integer $lp_id
  93. * @param integer $user_id
  94. * @return mixed True on success, false on error
  95. */
  96. public function __construct($course, $lp_id, $user_id)
  97. {
  98. $this->encoding = api_get_system_encoding();
  99. if ($this->debug > 0) {
  100. error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0);
  101. }
  102. if (empty($course)) {
  103. $course = api_get_course_id();
  104. }
  105. $course_info = api_get_course_info($course);
  106. if (!empty($course_info)) {
  107. $this->cc = $course_info['code'];
  108. $this->course_info = $course_info;
  109. $course_id = $course_info['real_id'];
  110. } else {
  111. $this->error = 'Course code does not exist in database.';
  112. }
  113. $lp_id = (int) $lp_id;
  114. $course_id = (int) $course_id;
  115. $this->set_course_int_id($course_id);
  116. // Check learnpath ID.
  117. if (empty($lp_id) || empty($course_id)) {
  118. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  119. } else {
  120. // TODO: Make it flexible to use any course_code (still using env course code here).
  121. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  122. $sql = "SELECT * FROM $lp_table
  123. WHERE id = '$lp_id' AND c_id = $course_id";
  124. if ($this->debug > 2) {
  125. error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  126. }
  127. $res = Database::query($sql);
  128. if (Database::num_rows($res) > 0) {
  129. $this->lp_id = $lp_id;
  130. $row = Database::fetch_array($res);
  131. $this->type = $row['lp_type'];
  132. $this->name = stripslashes($row['name']);
  133. $this->proximity = $row['content_local'];
  134. $this->theme = $row['theme'];
  135. $this->maker = $row['content_maker'];
  136. $this->prevent_reinit = $row['prevent_reinit'];
  137. $this->seriousgame_mode = $row['seriousgame_mode'];
  138. $this->license = $row['content_license'];
  139. $this->scorm_debug = $row['debug'];
  140. $this->js_lib = $row['js_lib'];
  141. $this->path = $row['path'];
  142. $this->preview_image = $row['preview_image'];
  143. $this->author = $row['author'];
  144. $this->hide_toc_frame = $row['hide_toc_frame'];
  145. $this->lp_session_id = $row['session_id'];
  146. $this->use_max_score = $row['use_max_score'];
  147. $this->subscribeUsers = $row['subscribe_users'];
  148. $this->created_on = $row['created_on'];
  149. $this->modified_on = $row['modified_on'];
  150. $this->ref = $row['ref'];
  151. $this->categoryId = $row['category_id'];
  152. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  153. if (!empty($row['publicated_on'])) {
  154. $this->publicated_on = $row['publicated_on'];
  155. }
  156. if (!empty($row['expired_on'])) {
  157. $this->expired_on = $row['expired_on'];
  158. }
  159. if ($this->type == 2) {
  160. if ($row['force_commit'] == 1) {
  161. $this->force_commit = true;
  162. }
  163. }
  164. $this->mode = $row['default_view_mod'];
  165. // Check user ID.
  166. if (empty($user_id)) {
  167. $this->error = 'User ID is empty';
  168. } else {
  169. $user_info = api_get_user_info($user_id);
  170. if (!empty($user_info)) {
  171. $this->user_id = $user_info['user_id'];
  172. } else {
  173. $this->error = 'User ID does not exist in database ('.$sql.')';
  174. }
  175. }
  176. // End of variables checking.
  177. $session_id = api_get_session_id();
  178. // Get the session condition for learning paths of the base + session.
  179. $session = api_get_session_condition($session_id);
  180. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  181. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  182. // Selecting by view_count descending allows to get the highest view_count first.
  183. $sql = "SELECT * FROM $lp_table
  184. WHERE
  185. c_id = $course_id AND
  186. lp_id = '$lp_id' AND
  187. user_id = '$user_id'
  188. $session
  189. ORDER BY view_count DESC";
  190. $res = Database::query($sql);
  191. if ($this->debug > 2) {
  192. error_log('New LP - learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  193. }
  194. if (Database::num_rows($res) > 0) {
  195. if ($this->debug > 2) {
  196. error_log('New LP - learnpath::__construct() '.__LINE__.' - Found previous view', 0);
  197. }
  198. $row = Database::fetch_array($res);
  199. $this->attempt = $row['view_count'];
  200. $this->lp_view_id = $row['id'];
  201. $this->last_item_seen = $row['last_item'];
  202. $this->progress_db = $row['progress'];
  203. $this->lp_view_session_id = $row['session_id'];
  204. } elseif (!api_is_invitee()) {
  205. if ($this->debug > 2) {
  206. error_log('New LP - learnpath::__construct() '.__LINE__.' - NOT Found previous view', 0);
  207. }
  208. $this->attempt = 1;
  209. $params = [
  210. 'c_id' => $course_id,
  211. 'lp_id' => $lp_id,
  212. 'user_id' => $user_id,
  213. 'view_count' => 1,
  214. 'session_id' => $session_id,
  215. 'last_item' => 0
  216. ];
  217. $this->lp_view_id = Database::insert($lp_table, $params);
  218. if (!empty($this->lp_view_id)) {
  219. $sql = "UPDATE $lp_table SET id = iid
  220. WHERE iid = ".$this->lp_view_id;
  221. Database::query($sql);
  222. }
  223. }
  224. // Initialise items.
  225. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  226. $sql = "SELECT * FROM $lp_item_table
  227. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  228. ORDER BY parent_item_id, display_order";
  229. $res = Database::query($sql);
  230. if ($this->debug > 2) {
  231. error_log('New LP - learnpath::__construct() '.__LINE__.' - query lp items: '.$sql, 0);
  232. error_log('-- Start while--', 0);
  233. }
  234. $lp_item_id_list = array();
  235. while ($row = Database::fetch_array($res)) {
  236. $lp_item_id_list[] = $row['id'];
  237. switch ($this->type) {
  238. case 3: //aicc
  239. $oItem = new aiccItem('db', $row['id'], $course_id);
  240. if (is_object($oItem)) {
  241. $my_item_id = $oItem->get_id();
  242. $oItem->set_lp_view($this->lp_view_id, $course_id);
  243. $oItem->set_prevent_reinit($this->prevent_reinit);
  244. // Don't use reference here as the next loop will make the pointed object change.
  245. $this->items[$my_item_id] = $oItem;
  246. $this->refs_list[$oItem->ref] = $my_item_id;
  247. if ($this->debug > 2) {
  248. error_log(
  249. 'New LP - learnpath::__construct() - '.
  250. 'aicc object with id '.$my_item_id.
  251. ' set in items[]',
  252. 0
  253. );
  254. }
  255. }
  256. break;
  257. case 2:
  258. $oItem = new scormItem('db', $row['id'], $course_id);
  259. if (is_object($oItem)) {
  260. $my_item_id = $oItem->get_id();
  261. $oItem->set_lp_view($this->lp_view_id, $course_id);
  262. $oItem->set_prevent_reinit($this->prevent_reinit);
  263. // Don't use reference here as the next loop will make the pointed object change.
  264. $this->items[$my_item_id] = $oItem;
  265. $this->refs_list[$oItem->ref] = $my_item_id;
  266. if ($this->debug > 2) {
  267. error_log('New LP - object with id '.$my_item_id.' set in items[]', 0);
  268. }
  269. }
  270. break;
  271. case 1:
  272. default:
  273. if ($this->debug > 2) {
  274. error_log('New LP - learnpath::__construct() '.__LINE__.' - calling learnpathItem', 0);
  275. }
  276. $oItem = new learnpathItem($row['id'], $user_id, $course_id, $row);
  277. if ($this->debug > 2) {
  278. error_log('New LP - learnpath::__construct() '.__LINE__.' - end calling learnpathItem', 0);
  279. }
  280. if (is_object($oItem)) {
  281. $my_item_id = $oItem->get_id();
  282. //$oItem->set_lp_view($this->lp_view_id); // Moved down to when we are sure the item_view exists.
  283. $oItem->set_prevent_reinit($this->prevent_reinit);
  284. // Don't use reference here as the next loop will make the pointed object change.
  285. $this->items[$my_item_id] = $oItem;
  286. $this->refs_list[$my_item_id] = $my_item_id;
  287. if ($this->debug > 2) {
  288. error_log(
  289. 'New LP - learnpath::__construct() '.__LINE__.
  290. ' - object with id '.$my_item_id.' set in items[]',
  291. 0
  292. );
  293. }
  294. }
  295. break;
  296. }
  297. // Setting the object level with variable $this->items[$i][parent]
  298. foreach ($this->items as $itemLPObject) {
  299. $level = self::get_level_for_item(
  300. $this->items,
  301. $itemLPObject->db_id
  302. );
  303. $itemLPObject->level = $level;
  304. }
  305. // Setting the view in the item object.
  306. if (is_object($this->items[$row['id']])) {
  307. $this->items[$row['id']]->set_lp_view($this->lp_view_id, $course_id);
  308. if ($this->items[$row['id']]->get_type() == TOOL_HOTPOTATOES) {
  309. $this->items[$row['id']]->current_start_time = 0;
  310. $this->items[$row['id']]->current_stop_time = 0;
  311. }
  312. }
  313. }
  314. if ($this->debug > 2) {
  315. error_log('New LP - learnpath::__construct() '.__LINE__.' ----- end while ----', 0);
  316. }
  317. if (!empty($lp_item_id_list)) {
  318. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  319. if (!empty($lp_item_id_list_to_string)) {
  320. // Get last viewing vars.
  321. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  322. // This query should only return one or zero result.
  323. $sql = "SELECT lp_item_id, status
  324. FROM $itemViewTable
  325. WHERE
  326. c_id = $course_id AND
  327. lp_view_id = ".$this->lp_view_id." AND
  328. lp_item_id IN ('".$lp_item_id_list_to_string."')
  329. ORDER BY view_count DESC ";
  330. if ($this->debug > 2) {
  331. error_log(
  332. 'New LP - learnpath::__construct() - Selecting item_views: '.$sql,
  333. 0
  334. );
  335. }
  336. $status_list = array();
  337. $res = Database::query($sql);
  338. while ($row = Database:: fetch_array($res)) {
  339. $status_list[$row['lp_item_id']] = $row['status'];
  340. }
  341. foreach ($lp_item_id_list as $item_id) {
  342. if (isset($status_list[$item_id])) {
  343. $status = $status_list[$item_id];
  344. if (is_object($this->items[$item_id])) {
  345. $this->items[$item_id]->set_status($status);
  346. if (empty($status)) {
  347. $this->items[$item_id]->set_status(
  348. $this->default_status
  349. );
  350. }
  351. }
  352. } else {
  353. if (!api_is_invitee()) {
  354. if (is_object($this->items[$item_id])) {
  355. $this->items[$item_id]->set_status(
  356. $this->default_status
  357. );
  358. }
  359. if (!empty($this->lp_view_id)) {
  360. // Add that row to the lp_item_view table so that we have something to show in the stats page.
  361. $params = [
  362. 'c_id' => $course_id,
  363. 'lp_item_id' => $item_id,
  364. 'lp_view_id' => $this->lp_view_id,
  365. 'view_count' => 1,
  366. 'status' => 'not attempted',
  367. 'start_time' => time(),
  368. 'total_time' => 0,
  369. 'score' => 0
  370. ];
  371. $insertId = Database::insert($itemViewTable, $params);
  372. if ($insertId) {
  373. $sql = "UPDATE $itemViewTable SET id = iid
  374. WHERE iid = $insertId";
  375. Database::query($sql);
  376. }
  377. $this->items[$item_id]->set_lp_view(
  378. $this->lp_view_id,
  379. $course_id
  380. );
  381. }
  382. }
  383. }
  384. }
  385. }
  386. }
  387. $this->ordered_items = self::get_flat_ordered_items_list(
  388. $this->get_id(),
  389. 0,
  390. $course_id
  391. );
  392. $this->max_ordered_items = 0;
  393. foreach ($this->ordered_items as $index => $dummy) {
  394. if ($index > $this->max_ordered_items && !empty($dummy)) {
  395. $this->max_ordered_items = $index;
  396. }
  397. }
  398. // TODO: Define the current item better.
  399. $this->first();
  400. if ($this->debug > 2) {
  401. error_log('New LP - learnpath::__construct() '.__LINE__.' - End of learnpath constructor for learnpath '.$this->get_id(), 0);
  402. }
  403. } else {
  404. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  405. }
  406. }
  407. }
  408. /**
  409. * @return string
  410. */
  411. public function getCourseCode()
  412. {
  413. return $this->cc;
  414. }
  415. /**
  416. * @return int
  417. */
  418. public function get_course_int_id()
  419. {
  420. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  421. }
  422. /**
  423. * @param $course_id
  424. * @return int
  425. */
  426. public function set_course_int_id($course_id)
  427. {
  428. return $this->course_int_id = (int) $course_id;
  429. }
  430. /**
  431. * Get the depth level of LP item
  432. * @param array $items
  433. * @param int $currentItemId
  434. * @return int
  435. */
  436. private static function get_level_for_item($items, $currentItemId)
  437. {
  438. $parentItemId = $items[$currentItemId]->parent;
  439. if ($parentItemId == 0) {
  440. return 0;
  441. } else {
  442. return self::get_level_for_item($items, $parentItemId) + 1;
  443. }
  444. }
  445. /**
  446. * Function rewritten based on old_add_item() from Yannick Warnier.
  447. * Due the fact that users can decide where the item should come, I had to overlook this function and
  448. * I found it better to rewrite it. Old function is still available.
  449. * Added also the possibility to add a description.
  450. *
  451. * @param int $parent
  452. * @param int $previous
  453. * @param string $type
  454. * @param int $id resource ID (ref)
  455. * @param string $title
  456. * @param string $description
  457. * @param int $prerequisites
  458. * @param int $max_time_allowed
  459. * @param int $userId
  460. *
  461. * @return int
  462. */
  463. public function add_item(
  464. $parent,
  465. $previous,
  466. $type = 'dir',
  467. $id,
  468. $title,
  469. $description,
  470. $prerequisites = 0,
  471. $max_time_allowed = 0,
  472. $userId = 0
  473. ) {
  474. $course_id = $this->course_info['real_id'];
  475. if ($this->debug > 0) {
  476. error_log('New LP - In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')', 0);
  477. }
  478. if (empty($course_id)) {
  479. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  480. $this->course_info = api_get_course_info($this->cc);
  481. $course_id = $this->course_info['real_id'];
  482. }
  483. $userId = empty($userId) ? api_get_user_id() : $userId;
  484. $sessionId = api_get_session_id();
  485. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  486. $_course = $this->course_info;
  487. $parent = intval($parent);
  488. $previous = intval($previous);
  489. $id = intval($id);
  490. $max_time_allowed = htmlentities($max_time_allowed);
  491. if (empty($max_time_allowed)) {
  492. $max_time_allowed = 0;
  493. }
  494. $sql = "SELECT COUNT(id) AS num
  495. FROM $tbl_lp_item
  496. WHERE
  497. c_id = $course_id AND
  498. lp_id = ".$this->get_id()." AND
  499. parent_item_id = ".$parent;
  500. $res_count = Database::query($sql);
  501. $row = Database::fetch_array($res_count);
  502. $num = $row['num'];
  503. if ($num > 0) {
  504. if (empty($previous)) {
  505. $sql = "SELECT id, next_item_id, display_order
  506. FROM $tbl_lp_item
  507. WHERE
  508. c_id = $course_id AND
  509. lp_id = ".$this->get_id()." AND
  510. parent_item_id = ".$parent." AND
  511. previous_item_id = 0 OR
  512. previous_item_id= ".$parent;
  513. $result = Database::query($sql);
  514. $row = Database::fetch_array($result);
  515. $tmp_previous = 0;
  516. $next = $row['id'];
  517. $display_order = 0;
  518. } else {
  519. $previous = (int) $previous;
  520. $sql = "SELECT id, previous_item_id, next_item_id, display_order
  521. FROM $tbl_lp_item
  522. WHERE
  523. c_id = $course_id AND
  524. lp_id = ".$this->get_id()." AND
  525. id = ".$previous;
  526. $result = Database::query($sql);
  527. $row = Database:: fetch_array($result);
  528. $tmp_previous = $row['id'];
  529. $next = $row['next_item_id'];
  530. $display_order = $row['display_order'];
  531. }
  532. } else {
  533. $tmp_previous = 0;
  534. $next = 0;
  535. $display_order = 0;
  536. }
  537. $id = intval($id);
  538. $typeCleaned = Database::escape_string($type);
  539. if ($type == 'quiz') {
  540. $sql = 'SELECT SUM(ponderation)
  541. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  542. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  543. ON
  544. quiz_question.id = quiz_rel_question.question_id AND
  545. quiz_question.c_id = quiz_rel_question.c_id
  546. WHERE
  547. quiz_rel_question.exercice_id = '.$id." AND
  548. quiz_question.c_id = $course_id AND
  549. quiz_rel_question.c_id = $course_id ";
  550. $rsQuiz = Database::query($sql);
  551. $max_score = Database::result($rsQuiz, 0, 0);
  552. // Disabling the exercise if we add it inside a LP
  553. $exercise = new Exercise($course_id);
  554. $exercise->read($id);
  555. $exercise->disable();
  556. $exercise->save();
  557. } else {
  558. $max_score = 100;
  559. }
  560. $params = array(
  561. "c_id" => $course_id,
  562. "lp_id" => $this->get_id(),
  563. "item_type" => $typeCleaned,
  564. "ref" => '',
  565. "title" => $title,
  566. "description" => $description,
  567. "path" => $id,
  568. "max_score" => $max_score,
  569. "parent_item_id" => $parent,
  570. "previous_item_id" => $previous,
  571. "next_item_id" => intval($next),
  572. "display_order" => $display_order + 1,
  573. "prerequisite" => $prerequisites,
  574. "max_time_allowed" => $max_time_allowed,
  575. 'min_score' => 0,
  576. 'launch_data' => ''
  577. );
  578. if ($prerequisites != 0) {
  579. $params['prerequisite'] = $prerequisites;
  580. }
  581. $new_item_id = Database::insert($tbl_lp_item, $params);
  582. if ($this->debug > 2) {
  583. error_log('New LP - Inserting dir/chapter: '.$new_item_id, 0);
  584. }
  585. if ($new_item_id) {
  586. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  587. Database::query($sql);
  588. $sql = "UPDATE $tbl_lp_item
  589. SET previous_item_id = $new_item_id
  590. WHERE c_id = $course_id AND id = $next";
  591. Database::query($sql);
  592. // Update the item that should be before the new item.
  593. $sql = "UPDATE $tbl_lp_item
  594. SET next_item_id = $new_item_id
  595. WHERE c_id = $course_id AND id = $tmp_previous";
  596. Database::query($sql);
  597. // Update all the items after the new item.
  598. $sql = "UPDATE ".$tbl_lp_item."
  599. SET display_order = display_order + 1
  600. WHERE
  601. c_id = $course_id AND
  602. lp_id = ".$this->get_id()." AND
  603. id <> " . $new_item_id." AND
  604. parent_item_id = " . $parent." AND
  605. display_order > " . $display_order;
  606. Database::query($sql);
  607. // Update the item that should come after the new item.
  608. $sql = "UPDATE ".$tbl_lp_item."
  609. SET ref = " . $new_item_id."
  610. WHERE c_id = $course_id AND id = ".$new_item_id;
  611. Database::query($sql);
  612. // Upload audio.
  613. if (!empty($_FILES['mp3']['name'])) {
  614. // Create the audio folder if it does not exist yet.
  615. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  616. if (!is_dir($filepath.'audio')) {
  617. mkdir(
  618. $filepath.'audio',
  619. api_get_permissions_for_new_directories()
  620. );
  621. $audio_id = add_document(
  622. $_course,
  623. '/audio',
  624. 'folder',
  625. 0,
  626. 'audio',
  627. '',
  628. 0,
  629. true,
  630. null,
  631. $sessionId,
  632. $userId
  633. );
  634. api_item_property_update(
  635. $_course,
  636. TOOL_DOCUMENT,
  637. $audio_id,
  638. 'FolderCreated',
  639. $userId,
  640. null,
  641. null,
  642. null,
  643. null,
  644. $sessionId
  645. );
  646. api_item_property_update(
  647. $_course,
  648. TOOL_DOCUMENT,
  649. $audio_id,
  650. 'invisible',
  651. $userId,
  652. null,
  653. null,
  654. null,
  655. null,
  656. $sessionId
  657. );
  658. }
  659. $file_path = handle_uploaded_document(
  660. $_course,
  661. $_FILES['mp3'],
  662. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  663. '/audio',
  664. $userId,
  665. '',
  666. '',
  667. '',
  668. '',
  669. false
  670. );
  671. // Getting the filename only.
  672. $file_components = explode('/', $file_path);
  673. $file = $file_components[count($file_components) - 1];
  674. // Store the mp3 file in the lp_item table.
  675. $sql = "UPDATE $tbl_lp_item SET
  676. audio = '".Database::escape_string($file)."'
  677. WHERE id = '" . intval($new_item_id)."'";
  678. Database::query($sql);
  679. }
  680. }
  681. return $new_item_id;
  682. }
  683. /**
  684. * Static admin function allowing addition of a learnpath to a course.
  685. * @param string Course code
  686. * @param string Learnpath name
  687. * @param string Learnpath description string, if provided
  688. * @param string Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  689. * @param string Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  690. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  691. * @param string $publicated_on
  692. * @param string $expired_on
  693. * @param int $categoryId
  694. * @param int $userId
  695. * @return integer The new learnpath ID on success, 0 on failure
  696. */
  697. public static function add_lp(
  698. $courseCode,
  699. $name,
  700. $description = '',
  701. $learnpath = 'guess',
  702. $origin = 'zip',
  703. $zipname = '',
  704. $publicated_on = '',
  705. $expired_on = '',
  706. $categoryId = 0,
  707. $userId = 0
  708. ) {
  709. global $charset;
  710. if (!empty($courseCode)) {
  711. $courseInfo = api_get_course_info($courseCode);
  712. $course_id = $courseInfo['real_id'];
  713. } else {
  714. $course_id = api_get_course_int_id();
  715. $courseInfo = api_get_course_info();
  716. }
  717. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  718. // Check course code exists.
  719. // Check lp_name doesn't exist, otherwise append something.
  720. $i = 0;
  721. $name = Database::escape_string($name);
  722. $categoryId = intval($categoryId);
  723. // Session id.
  724. $session_id = api_get_session_id();
  725. $userId = empty($userId) ? api_get_user_id() : $userId;
  726. $check_name = "SELECT * FROM $tbl_lp
  727. WHERE c_id = $course_id AND name = '$name'";
  728. $res_name = Database::query($check_name);
  729. if (empty($publicated_on)) {
  730. $publicated_on = null;
  731. } else {
  732. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  733. }
  734. if (empty($expired_on)) {
  735. $expired_on = null;
  736. } else {
  737. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  738. }
  739. while (Database::num_rows($res_name)) {
  740. // There is already one such name, update the current one a bit.
  741. $i++;
  742. $name = $name.' - '.$i;
  743. $check_name = "SELECT * FROM $tbl_lp
  744. WHERE c_id = $course_id AND name = '$name'";
  745. $res_name = Database::query($check_name);
  746. }
  747. // New name does not exist yet; keep it.
  748. // Escape description.
  749. // Kevin: added htmlentities().
  750. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  751. $type = 1;
  752. switch ($learnpath) {
  753. case 'guess':
  754. break;
  755. case 'dokeos':
  756. case 'chamilo':
  757. $type = 1;
  758. break;
  759. case 'aicc':
  760. break;
  761. }
  762. switch ($origin) {
  763. case 'zip':
  764. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  765. break;
  766. case 'manual':
  767. default:
  768. $get_max = "SELECT MAX(display_order)
  769. FROM $tbl_lp WHERE c_id = $course_id";
  770. $res_max = Database::query($get_max);
  771. if (Database::num_rows($res_max) < 1) {
  772. $dsp = 1;
  773. } else {
  774. $row = Database::fetch_array($res_max);
  775. $dsp = $row[0] + 1;
  776. }
  777. $params = [
  778. 'c_id' => $course_id,
  779. 'lp_type' => $type,
  780. 'name' => $name,
  781. 'description' => $description,
  782. 'path' => '',
  783. 'default_view_mod' => 'embedded',
  784. 'default_encoding' => 'UTF-8',
  785. 'display_order' => $dsp,
  786. 'content_maker' => 'Chamilo',
  787. 'content_local' => 'local',
  788. 'js_lib' => '',
  789. 'session_id' => $session_id,
  790. 'created_on' => api_get_utc_datetime(),
  791. 'modified_on' => api_get_utc_datetime(),
  792. 'publicated_on' => $publicated_on,
  793. 'expired_on' => $expired_on,
  794. 'category_id' => $categoryId,
  795. 'force_commit' => 0,
  796. 'content_license' => '',
  797. 'debug' => 0,
  798. 'theme' => '',
  799. 'preview_image' => '',
  800. 'author' => '',
  801. 'prerequisite' => 0,
  802. 'hide_toc_frame' => 0,
  803. 'seriousgame_mode' => 0,
  804. 'autolaunch' => 0,
  805. 'max_attempts' => 0,
  806. 'subscribe_users' => 0,
  807. 'accumulate_scorm_time' => 1
  808. ];
  809. $id = Database::insert($tbl_lp, $params);
  810. if ($id > 0) {
  811. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  812. Database::query($sql);
  813. // Insert into item_property.
  814. api_item_property_update(
  815. $courseInfo,
  816. TOOL_LEARNPATH,
  817. $id,
  818. 'LearnpathAdded',
  819. $userId
  820. );
  821. api_set_default_visibility(
  822. $id,
  823. TOOL_LEARNPATH,
  824. 0,
  825. $courseInfo,
  826. $session_id,
  827. $userId
  828. );
  829. return $id;
  830. }
  831. break;
  832. }
  833. }
  834. /**
  835. * Auto completes the parents of an item in case it's been completed or passed
  836. * @param int $item Optional ID of the item from which to look for parents
  837. */
  838. public function autocomplete_parents($item)
  839. {
  840. $debug = $this->debug;
  841. if ($debug) {
  842. error_log('Learnpath::autocomplete_parents()', 0);
  843. }
  844. if (empty($item)) {
  845. $item = $this->current;
  846. }
  847. $currentItem = $this->getItem($item);
  848. if ($currentItem) {
  849. $parent_id = $currentItem->get_parent();
  850. $parent = $this->getItem($parent_id);
  851. if ($parent) {
  852. // if $item points to an object and there is a parent.
  853. if ($debug) {
  854. error_log(
  855. 'Autocompleting parent of item '.$item.' "'.$currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  856. 0
  857. );
  858. }
  859. // New experiment including failed and browsed in completed status.
  860. //$current_status = $currentItem->get_status();
  861. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  862. // Fixes chapter auto complete
  863. if (true) {
  864. // If the current item is completed or passes or succeeded.
  865. $updateParentStatus = true;
  866. if ($debug) {
  867. error_log('Status of current item is alright', 0);
  868. }
  869. foreach ($parent->get_children() as $childItemId) {
  870. $childItem = $this->getItem($childItemId);
  871. // If children was not set try to get the info
  872. if (empty($childItem->db_item_view_id)) {
  873. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  874. }
  875. // Check all his brothers (parent's children) for completion status.
  876. if ($childItemId != $item) {
  877. if ($debug) {
  878. error_log(
  879. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  880. 0
  881. );
  882. }
  883. // Trying completing parents of failed and browsed items as well.
  884. if ($childItem->status_is(
  885. array(
  886. 'completed',
  887. 'passed',
  888. 'succeeded',
  889. 'browsed',
  890. 'failed'
  891. )
  892. )
  893. ) {
  894. // Keep completion status to true.
  895. continue;
  896. } else {
  897. if ($debug > 2) {
  898. error_log(
  899. '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,
  900. 0
  901. );
  902. }
  903. $updateParentStatus = false;
  904. break;
  905. }
  906. }
  907. }
  908. if ($updateParentStatus) {
  909. // If all the children were completed:
  910. $parent->set_status('completed');
  911. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  912. // Force the status to "completed"
  913. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  914. $this->update_queue[$parent->get_id()] = 'completed';
  915. if ($debug) {
  916. error_log(
  917. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  918. print_r($this->update_queue, 1),
  919. 0
  920. );
  921. }
  922. // Recursive call.
  923. $this->autocomplete_parents($parent->get_id());
  924. }
  925. }
  926. } else {
  927. if ($debug) {
  928. error_log("Parent #$parent_id does not exists");
  929. }
  930. }
  931. } else {
  932. if ($debug) {
  933. error_log("#$item is an item that doesn't have parents");
  934. }
  935. }
  936. }
  937. /**
  938. * Auto saves the current results into the database for the whole learnpath
  939. * @todo: Add save operations for the learnpath itself.
  940. */
  941. public function autosave()
  942. {
  943. if ($this->debug > 0) {
  944. error_log('New LP - In learnpath::autosave()', 0);
  945. }
  946. }
  947. /**
  948. * Closes the current resource
  949. *
  950. * Stops the timer
  951. * Saves into the database if required
  952. * Clears the current resource data from this object
  953. * @return boolean True on success, false on failure
  954. */
  955. public function close()
  956. {
  957. if ($this->debug > 0) {
  958. error_log('New LP - In learnpath::close()', 0);
  959. }
  960. if (empty($this->lp_id)) {
  961. $this->error = 'Trying to close this learnpath but no ID is set';
  962. return false;
  963. }
  964. $this->current_time_stop = time();
  965. $this->ordered_items = array();
  966. $this->index = 0;
  967. unset($this->lp_id);
  968. //unset other stuff
  969. return true;
  970. }
  971. /**
  972. * Static admin function allowing removal of a learnpath
  973. * @param array $courseInfo
  974. * @param integer $id Learnpath ID
  975. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  976. * @return boolean True on success, false on failure (might change that to return number of elements deleted)
  977. */
  978. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  979. {
  980. $course_id = api_get_course_int_id();
  981. if (!empty($courseInfo)) {
  982. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  983. }
  984. // TODO: Implement a way of getting this to work when the current object is not set.
  985. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  986. // If an ID is specifically given and the current LP is not the same, prevent delete.
  987. if (!empty($id) && ($id != $this->lp_id)) {
  988. return false;
  989. }
  990. $lp = Database::get_course_table(TABLE_LP_MAIN);
  991. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  992. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  993. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  994. // Delete lp item id.
  995. foreach ($this->items as $id => $dummy) {
  996. $sql = "DELETE FROM $lp_item_view
  997. WHERE c_id = $course_id AND lp_item_id = '".$id."'";
  998. Database::query($sql);
  999. }
  1000. // Proposed by Christophe (nickname: clefevre)
  1001. $sql = "DELETE FROM $lp_item
  1002. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  1003. Database::query($sql);
  1004. $sql = "DELETE FROM $lp_view
  1005. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  1006. Database::query($sql);
  1007. self::toggle_publish($this->lp_id, 'i');
  1008. if ($this->type == 2 || $this->type == 3) {
  1009. // This is a scorm learning path, delete the files as well.
  1010. $sql = "SELECT path FROM $lp
  1011. WHERE c_id = ".$course_id." AND id = ".$this->lp_id;
  1012. $res = Database::query($sql);
  1013. if (Database::num_rows($res) > 0) {
  1014. $row = Database::fetch_array($res);
  1015. $path = $row['path'];
  1016. $sql = "SELECT id FROM $lp
  1017. WHERE
  1018. c_id = ".$course_id." AND
  1019. path = '$path' AND
  1020. id != ".$this->lp_id;
  1021. $res = Database::query($sql);
  1022. if (Database::num_rows($res) > 0) {
  1023. // Another learning path uses this directory, so don't delete it.
  1024. if ($this->debug > 2) {
  1025. error_log('New LP - In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1026. }
  1027. } else {
  1028. // No other LP uses that directory, delete it.
  1029. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1030. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // The absolute system path for this course.
  1031. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1032. if ($this->debug > 2) {
  1033. error_log('New LP - In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1034. }
  1035. // Proposed by Christophe (clefevre).
  1036. if (strcmp(substr($path, -2), "/.") == 0) {
  1037. $path = substr($path, 0, -1); // Remove "." at the end.
  1038. }
  1039. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1040. rmdirr($course_scorm_dir.$path);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1046. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1047. // Delete tools
  1048. $sql = "DELETE FROM $tbl_tool
  1049. WHERE c_id = ".$course_id." AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1050. Database::query($sql);
  1051. $sql = "DELETE FROM $lp
  1052. WHERE c_id = ".$course_id." AND id = ".$this->lp_id;
  1053. Database::query($sql);
  1054. // Updates the display order of all lps.
  1055. $this->update_display_order();
  1056. api_item_property_update(
  1057. api_get_course_info(),
  1058. TOOL_LEARNPATH,
  1059. $this->lp_id,
  1060. 'delete',
  1061. api_get_user_id()
  1062. );
  1063. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1064. api_get_course_int_id(),
  1065. 4,
  1066. $id,
  1067. api_get_session_id()
  1068. );
  1069. if ($link_info !== false) {
  1070. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1071. }
  1072. if (api_get_setting('search_enabled') == 'true') {
  1073. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1074. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1075. }
  1076. }
  1077. /**
  1078. * Removes all the children of one item - dangerous!
  1079. * @param integer $id Element ID of which children have to be removed
  1080. * @return integer Total number of children removed
  1081. */
  1082. public function delete_children_items($id)
  1083. {
  1084. $course_id = $this->course_info['real_id'];
  1085. if ($this->debug > 0) {
  1086. error_log('New LP - In learnpath::delete_children_items('.$id.')', 0);
  1087. }
  1088. $num = 0;
  1089. if (empty($id) || $id != strval(intval($id))) {
  1090. return false;
  1091. }
  1092. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1093. $sql = "SELECT * FROM $lp_item
  1094. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1095. $res = Database::query($sql);
  1096. while ($row = Database::fetch_array($res)) {
  1097. $num += $this->delete_children_items($row['id']);
  1098. $sql = "DELETE FROM $lp_item
  1099. WHERE c_id = ".$course_id." AND id = ".$row['id'];
  1100. Database::query($sql);
  1101. $num++;
  1102. }
  1103. return $num;
  1104. }
  1105. /**
  1106. * Removes an item from the current learnpath
  1107. * @param integer $id Elem ID (0 if first)
  1108. * @param integer $remove Whether to remove the resource/data from the
  1109. * system or leave it (default: 'keep', others 'remove')
  1110. * @return integer Number of elements moved
  1111. * @todo implement resource removal
  1112. */
  1113. public function delete_item($id, $remove = 'keep')
  1114. {
  1115. $course_id = api_get_course_int_id();
  1116. if ($this->debug > 0) {
  1117. error_log('New LP - In learnpath::delete_item()', 0);
  1118. }
  1119. // TODO: Implement the resource removal.
  1120. if (empty($id) || $id != strval(intval($id))) {
  1121. return false;
  1122. }
  1123. // First select item to get previous, next, and display order.
  1124. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1125. $sql_sel = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND id = $id";
  1126. $res_sel = Database::query($sql_sel);
  1127. if (Database::num_rows($res_sel) < 1) {
  1128. return false;
  1129. }
  1130. $row = Database::fetch_array($res_sel);
  1131. $previous = $row['previous_item_id'];
  1132. $next = $row['next_item_id'];
  1133. $display = $row['display_order'];
  1134. $parent = $row['parent_item_id'];
  1135. $lp = $row['lp_id'];
  1136. // Delete children items.
  1137. $num = $this->delete_children_items($id);
  1138. if ($this->debug > 2) {
  1139. error_log('New LP - learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1140. }
  1141. // Now delete the item.
  1142. $sql_del = "DELETE FROM $lp_item WHERE c_id = $course_id AND id = $id";
  1143. if ($this->debug > 2) {
  1144. error_log('New LP - Deleting item: '.$sql_del, 0);
  1145. }
  1146. Database::query($sql_del);
  1147. // Now update surrounding items.
  1148. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1149. WHERE c_id = ".$course_id." AND id = $previous";
  1150. Database::query($sql_upd);
  1151. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1152. WHERE c_id = ".$course_id." AND id = $next";
  1153. Database::query($sql_upd);
  1154. // Now update all following items with new display order.
  1155. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1156. WHERE
  1157. c_id = ".$course_id." AND
  1158. lp_id = $lp AND
  1159. parent_item_id = $parent AND
  1160. display_order > $display";
  1161. Database::query($sql_all);
  1162. //Removing prerequisites since the item will not longer exist
  1163. $sql_all = "UPDATE $lp_item SET prerequisite = '' WHERE c_id = ".$course_id." AND prerequisite = $id";
  1164. Database::query($sql_all);
  1165. // Remove from search engine if enabled.
  1166. if (api_get_setting('search_enabled') == 'true') {
  1167. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1168. $sql = 'SELECT * FROM %s
  1169. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1170. LIMIT 1';
  1171. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1172. $res = Database::query($sql);
  1173. if (Database::num_rows($res) > 0) {
  1174. $row2 = Database::fetch_array($res);
  1175. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  1176. $di = new ChamiloIndexer();
  1177. $di->remove_document((int) $row2['search_did']);
  1178. }
  1179. $sql = 'DELETE FROM %s
  1180. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1181. LIMIT 1';
  1182. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1183. Database::query($sql);
  1184. }
  1185. }
  1186. /**
  1187. * Updates an item's content in place
  1188. * @param integer $id Element ID
  1189. * @param integer $parent Parent item ID
  1190. * @param integer $previous Previous item ID
  1191. * @param string $title Item title
  1192. * @param string $description Item description
  1193. * @param string $prerequisites Prerequisites (optional)
  1194. * @param array $audio The array resulting of the $_FILES[mp3] element
  1195. * @param int $max_time_allowed
  1196. * @param string $url
  1197. * @return boolean True on success, false on error
  1198. */
  1199. public function edit_item(
  1200. $id,
  1201. $parent,
  1202. $previous,
  1203. $title,
  1204. $description,
  1205. $prerequisites = '0',
  1206. $audio = array(),
  1207. $max_time_allowed = 0,
  1208. $url = ''
  1209. ) {
  1210. $course_id = api_get_course_int_id();
  1211. $_course = api_get_course_info();
  1212. if ($this->debug > 0) {
  1213. error_log('New LP - In learnpath::edit_item()', 0);
  1214. }
  1215. if (empty($max_time_allowed)) {
  1216. $max_time_allowed = 0;
  1217. }
  1218. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1219. return false;
  1220. }
  1221. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1222. $sql = "SELECT * FROM $tbl_lp_item
  1223. WHERE c_id = ".$course_id." AND id = ".$id;
  1224. $res_select = Database::query($sql);
  1225. $row_select = Database::fetch_array($res_select);
  1226. $audio_update_sql = '';
  1227. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1228. // Create the audio folder if it does not exist yet.
  1229. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1230. if (!is_dir($filepath.'audio')) {
  1231. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1232. $audio_id = add_document(
  1233. $_course,
  1234. '/audio',
  1235. 'folder',
  1236. 0,
  1237. 'audio'
  1238. );
  1239. api_item_property_update(
  1240. $_course,
  1241. TOOL_DOCUMENT,
  1242. $audio_id,
  1243. 'FolderCreated',
  1244. api_get_user_id(),
  1245. null,
  1246. null,
  1247. null,
  1248. null,
  1249. api_get_session_id()
  1250. );
  1251. api_item_property_update(
  1252. $_course,
  1253. TOOL_DOCUMENT,
  1254. $audio_id,
  1255. 'invisible',
  1256. api_get_user_id(),
  1257. null,
  1258. null,
  1259. null,
  1260. null,
  1261. api_get_session_id()
  1262. );
  1263. }
  1264. // Upload file in documents.
  1265. $pi = pathinfo($audio['name']);
  1266. if ($pi['extension'] == 'mp3') {
  1267. $c_det = api_get_course_info($this->cc);
  1268. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1269. $path = handle_uploaded_document(
  1270. $c_det,
  1271. $audio,
  1272. $bp,
  1273. '/audio',
  1274. api_get_user_id(),
  1275. 0,
  1276. null,
  1277. 0,
  1278. 'rename',
  1279. false,
  1280. 0
  1281. );
  1282. $path = substr($path, 7);
  1283. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1284. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1285. }
  1286. }
  1287. $same_parent = ($row_select['parent_item_id'] == $parent) ? true : false;
  1288. $same_previous = ($row_select['previous_item_id'] == $previous) ? true : false;
  1289. // TODO: htmlspecialchars to be checked for encoding related problems.
  1290. if ($same_parent && $same_previous) {
  1291. // Only update title and description.
  1292. $sql = "UPDATE ".$tbl_lp_item."
  1293. SET title = '" . Database::escape_string($title)."',
  1294. prerequisite = '".$prerequisites."',
  1295. description = '".Database::escape_string($description)."'
  1296. ".$audio_update_sql.",
  1297. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1298. WHERE c_id = ".$course_id." AND id = ".$id;
  1299. Database::query($sql);
  1300. } else {
  1301. $old_parent = $row_select['parent_item_id'];
  1302. $old_previous = $row_select['previous_item_id'];
  1303. $old_next = $row_select['next_item_id'];
  1304. $old_order = $row_select['display_order'];
  1305. $old_prerequisite = $row_select['prerequisite'];
  1306. $old_max_time_allowed = $row_select['max_time_allowed'];
  1307. /* BEGIN -- virtually remove the current item id */
  1308. /* for the next and previous item it is like the current item doesn't exist anymore */
  1309. if ($old_previous != 0) {
  1310. // Next
  1311. $sql = "UPDATE ".$tbl_lp_item."
  1312. SET next_item_id = " . $old_next."
  1313. WHERE c_id = ".$course_id." AND id = ".$old_previous;
  1314. Database::query($sql);
  1315. }
  1316. if ($old_next != 0) {
  1317. // Previous
  1318. $sql = "UPDATE ".$tbl_lp_item."
  1319. SET previous_item_id = " . $old_previous."
  1320. WHERE c_id = ".$course_id." AND id = ".$old_next;
  1321. Database::query($sql);
  1322. }
  1323. // display_order - 1 for every item with a display_order
  1324. // bigger then the display_order of the current item.
  1325. $sql = "UPDATE ".$tbl_lp_item."
  1326. SET display_order = display_order - 1
  1327. WHERE
  1328. c_id = ".$course_id." AND
  1329. display_order > " . $old_order." AND
  1330. lp_id = " . $this->lp_id." AND
  1331. parent_item_id = " . $old_parent;
  1332. Database::query($sql);
  1333. /* END -- virtually remove the current item id */
  1334. /* BEGIN -- update the current item id to his new location */
  1335. if ($previous == 0) {
  1336. // Select the data of the item that should come after the current item.
  1337. $sql = "SELECT id, display_order
  1338. FROM " . $tbl_lp_item."
  1339. WHERE
  1340. c_id = ".$course_id." AND
  1341. lp_id = " . $this->lp_id." AND
  1342. parent_item_id = " . $parent." AND
  1343. previous_item_id = " . $previous;
  1344. $res_select_old = Database::query($sql);
  1345. $row_select_old = Database::fetch_array($res_select_old);
  1346. // If the new parent didn't have children before.
  1347. if (Database::num_rows($res_select_old) == 0) {
  1348. $new_next = 0;
  1349. $new_order = 1;
  1350. } else {
  1351. $new_next = $row_select_old['id'];
  1352. $new_order = $row_select_old['display_order'];
  1353. }
  1354. } else {
  1355. // Select the data of the item that should come before the current item.
  1356. $sql = "SELECT next_item_id, display_order
  1357. FROM " . $tbl_lp_item."
  1358. WHERE c_id = ".$course_id." AND id = ".$previous;
  1359. $res_select_old = Database::query($sql);
  1360. $row_select_old = Database::fetch_array($res_select_old);
  1361. $new_next = $row_select_old['next_item_id'];
  1362. $new_order = $row_select_old['display_order'] + 1;
  1363. }
  1364. // TODO: htmlspecialchars to be checked for encoding related problems.
  1365. // Update the current item with the new data.
  1366. $sql = "UPDATE $tbl_lp_item
  1367. SET
  1368. title = '".Database::escape_string($title)."',
  1369. description = '".Database::escape_string($description)."',
  1370. parent_item_id = ".$parent.",
  1371. previous_item_id = ".$previous.",
  1372. next_item_id = ".$new_next.",
  1373. display_order = ".$new_order."
  1374. ".$audio_update_sql."
  1375. WHERE c_id = ".$course_id." AND id = ".$id;
  1376. Database::query($sql);
  1377. if ($previous != 0) {
  1378. // Update the previous item's next_item_id.
  1379. $sql = "UPDATE ".$tbl_lp_item."
  1380. SET next_item_id = " . $id."
  1381. WHERE c_id = ".$course_id." AND id = ".$previous;
  1382. Database::query($sql);
  1383. }
  1384. if ($new_next != 0) {
  1385. // Update the next item's previous_item_id.
  1386. $sql = "UPDATE ".$tbl_lp_item."
  1387. SET previous_item_id = " . $id."
  1388. WHERE c_id = ".$course_id." AND id = ".$new_next;
  1389. Database::query($sql);
  1390. }
  1391. if ($old_prerequisite != $prerequisites) {
  1392. $sql = "UPDATE ".$tbl_lp_item."
  1393. SET prerequisite = '" . $prerequisites."'
  1394. WHERE c_id = ".$course_id." AND id = ".$id;
  1395. Database::query($sql);
  1396. }
  1397. if ($old_max_time_allowed != $max_time_allowed) {
  1398. // update max time allowed
  1399. $sql = "UPDATE ".$tbl_lp_item."
  1400. SET max_time_allowed = " . $max_time_allowed."
  1401. WHERE c_id = ".$course_id." AND id = ".$id;
  1402. Database::query($sql);
  1403. }
  1404. // Update all the items with the same or a bigger display_order than the current item.
  1405. $sql = "UPDATE ".$tbl_lp_item."
  1406. SET display_order = display_order + 1
  1407. WHERE
  1408. c_id = ".$course_id." AND
  1409. lp_id = " . $this->get_id()." AND
  1410. id <> " . $id." AND
  1411. parent_item_id = " . $parent." AND
  1412. display_order >= " . $new_order;
  1413. Database::query($sql);
  1414. }
  1415. if ($row_select['item_type'] == 'link') {
  1416. $link = new Link();
  1417. $linkId = $row_select['path'];
  1418. $link->updateLink($linkId, $url);
  1419. }
  1420. }
  1421. /**
  1422. * Updates an item's prereq in place
  1423. * @param integer $id Element ID
  1424. * @param string $prerequisite_id Prerequisite Element ID
  1425. * @param int $mastery_score Prerequisite min score
  1426. * @param int $max_score Prerequisite max score
  1427. *
  1428. * @return boolean True on success, false on error
  1429. */
  1430. public function edit_item_prereq(
  1431. $id,
  1432. $prerequisite_id,
  1433. $mastery_score = 0,
  1434. $max_score = 100
  1435. ) {
  1436. $course_id = api_get_course_int_id();
  1437. if ($this->debug > 0) {
  1438. error_log('New LP - In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','.$max_score.')', 0);
  1439. }
  1440. if (empty($id) || ($id != strval(intval($id))) || empty($prerequisite_id)) {
  1441. return false;
  1442. }
  1443. $prerequisite_id = intval($prerequisite_id);
  1444. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1445. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1446. $mastery_score = 0;
  1447. }
  1448. if (!is_numeric($max_score) || $max_score < 0) {
  1449. $max_score = 100;
  1450. }
  1451. /*if ($mastery_score > $max_score) {
  1452. $max_score = $mastery_score;
  1453. }*/
  1454. if (!is_numeric($prerequisite_id)) {
  1455. $prerequisite_id = 'NULL';
  1456. }
  1457. $mastery_score = floatval($mastery_score);
  1458. $max_score = floatval($max_score);
  1459. $sql = " UPDATE $tbl_lp_item
  1460. SET
  1461. prerequisite = $prerequisite_id ,
  1462. prerequisite_min_score = $mastery_score ,
  1463. prerequisite_max_score = $max_score
  1464. WHERE c_id = $course_id AND id = $id";
  1465. Database::query($sql);
  1466. // TODO: Update the item object (can be ignored for now because refreshed).
  1467. return true;
  1468. }
  1469. /**
  1470. * Static admin function exporting a learnpath into a zip file
  1471. * @param string Export type (scorm, zip, cd)
  1472. * @param string Course code
  1473. * @param integer Learnpath ID
  1474. * @param string Zip file name
  1475. * @return string Zip file path (or false on error)
  1476. */
  1477. public function export_lp($type, $course, $id, $zipname)
  1478. {
  1479. if (empty($type) || empty($course) || empty($id) || empty($zipname)) {
  1480. return false;
  1481. }
  1482. $url = '';
  1483. switch ($type) {
  1484. case 'scorm':
  1485. break;
  1486. case 'zip':
  1487. break;
  1488. case 'cdrom':
  1489. break;
  1490. }
  1491. return $url;
  1492. }
  1493. /**
  1494. * Gets all the chapters belonging to the same parent as the item/chapter given
  1495. * Can also be called as abstract method
  1496. * @param integer $id Item ID
  1497. * @return array A list of all the "brother items" (or an empty array on failure)
  1498. */
  1499. public function getSiblingDirectories($id)
  1500. {
  1501. $course_id = api_get_course_int_id();
  1502. if ($this->debug > 0) {
  1503. error_log('New LP - In learnpath::getSiblingDirectories()', 0);
  1504. }
  1505. if (empty($id) || $id != strval(intval($id))) {
  1506. return array();
  1507. }
  1508. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1509. $sql_parent = "SELECT * FROM $lp_item
  1510. WHERE c_id = ".$course_id." AND id = $id AND item_type='dir'";
  1511. $res_parent = Database::query($sql_parent);
  1512. if (Database::num_rows($res_parent) > 0) {
  1513. $row_parent = Database::fetch_array($res_parent);
  1514. $parent = $row_parent['parent_item_id'];
  1515. $sql = "SELECT * FROM $lp_item
  1516. WHERE
  1517. c_id = ".$course_id." AND
  1518. parent_item_id = $parent AND
  1519. id = $id AND
  1520. item_type='dir'
  1521. ORDER BY display_order";
  1522. $res_bros = Database::query($sql);
  1523. $list = array();
  1524. while ($row_bro = Database::fetch_array($res_bros)) {
  1525. $list[] = $row_bro;
  1526. }
  1527. return $list;
  1528. }
  1529. return array();
  1530. }
  1531. /**
  1532. * Gets all the items belonging to the same parent as the item given
  1533. * Can also be called as abstract method
  1534. * @param integer $id Item ID
  1535. * @return array A list of all the "brother items" (or an empty array on failure)
  1536. */
  1537. public function get_brother_items($id)
  1538. {
  1539. $course_id = api_get_course_int_id();
  1540. if ($this->debug > 0) {
  1541. error_log('New LP - In learnpath::get_brother_items('.$id.')', 0);
  1542. }
  1543. if (empty($id) || $id != strval(intval($id))) {
  1544. return array();
  1545. }
  1546. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1547. $sql_parent = "SELECT * FROM $lp_item
  1548. WHERE c_id = $course_id AND id = $id";
  1549. $res_parent = Database::query($sql_parent);
  1550. if (Database::num_rows($res_parent) > 0) {
  1551. $row_parent = Database::fetch_array($res_parent);
  1552. $parent = $row_parent['parent_item_id'];
  1553. $sql = "SELECT * FROM $lp_item
  1554. WHERE c_id = ".$course_id." AND parent_item_id = $parent
  1555. ORDER BY display_order";
  1556. $res_bros = Database::query($sql);
  1557. $list = [];
  1558. while ($row_bro = Database::fetch_array($res_bros)) {
  1559. $list[] = $row_bro;
  1560. }
  1561. return $list;
  1562. }
  1563. return [];
  1564. }
  1565. /**
  1566. * Get the specific prefix index terms of this learning path
  1567. * @param string $prefix
  1568. * @return array Array of terms
  1569. */
  1570. public function get_common_index_terms_by_prefix($prefix)
  1571. {
  1572. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1573. $terms = get_specific_field_values_list_by_prefix(
  1574. $prefix,
  1575. $this->cc,
  1576. TOOL_LEARNPATH,
  1577. $this->lp_id
  1578. );
  1579. $prefix_terms = array();
  1580. if (!empty($terms)) {
  1581. foreach ($terms as $term) {
  1582. $prefix_terms[] = $term['value'];
  1583. }
  1584. }
  1585. return $prefix_terms;
  1586. }
  1587. /**
  1588. * Gets the number of items currently completed
  1589. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1590. * @return integer The number of items currently completed
  1591. */
  1592. public function get_complete_items_count($failedStatusException = false)
  1593. {
  1594. if ($this->debug > 0) {
  1595. error_log('New LP - In learnpath::get_complete_items_count()', 0);
  1596. }
  1597. $i = 0;
  1598. $completedStatusList = array(
  1599. 'completed',
  1600. 'passed',
  1601. 'succeeded',
  1602. 'browsed'
  1603. );
  1604. if (!$failedStatusException) {
  1605. $completedStatusList[] = 'failed';
  1606. }
  1607. foreach ($this->items as $id => $dummy) {
  1608. // Trying failed and browsed considered "progressed" as well.
  1609. if ($this->items[$id]->status_is($completedStatusList) &&
  1610. $this->items[$id]->get_type() != 'dir'
  1611. ) {
  1612. $i++;
  1613. }
  1614. }
  1615. return $i;
  1616. }
  1617. /**
  1618. * Gets the current item ID
  1619. * @return integer The current learnpath item id
  1620. */
  1621. public function get_current_item_id()
  1622. {
  1623. $current = 0;
  1624. if ($this->debug > 0) {
  1625. error_log('New LP - In learnpath::get_current_item_id()', 0);
  1626. }
  1627. if (!empty($this->current)) {
  1628. $current = $this->current;
  1629. }
  1630. if ($this->debug > 2) {
  1631. error_log('New LP - In learnpath::get_current_item_id() - Returning '.$current, 0);
  1632. }
  1633. return $current;
  1634. }
  1635. /**
  1636. * Force to get the first learnpath item id
  1637. * @return integer The current learnpath item id
  1638. */
  1639. public function get_first_item_id()
  1640. {
  1641. $current = 0;
  1642. if (is_array($this->ordered_items)) {
  1643. $current = $this->ordered_items[0];
  1644. }
  1645. return $current;
  1646. }
  1647. /**
  1648. * Gets the total number of items available for viewing in this SCORM
  1649. * @return integer The total number of items
  1650. */
  1651. public function get_total_items_count()
  1652. {
  1653. if ($this->debug > 0) {
  1654. error_log('New LP - In learnpath::get_total_items_count()', 0);
  1655. }
  1656. return count($this->items);
  1657. }
  1658. /**
  1659. * Gets the total number of items available for viewing in this SCORM but without chapters
  1660. * @return integer The total no-chapters number of items
  1661. */
  1662. public function getTotalItemsCountWithoutDirs()
  1663. {
  1664. if ($this->debug > 0) {
  1665. error_log('New LP - In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1666. }
  1667. $total = 0;
  1668. $typeListNotToCount = self::getChapterTypes();
  1669. foreach ($this->items as $temp2) {
  1670. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1671. $total++;
  1672. }
  1673. }
  1674. return $total;
  1675. }
  1676. /**
  1677. * Gets the first element URL.
  1678. * @return string URL to load into the viewer
  1679. */
  1680. public function first()
  1681. {
  1682. if ($this->debug > 0) {
  1683. error_log('New LP - In learnpath::first()', 0);
  1684. error_log('$this->last_item_seen '.$this->last_item_seen);
  1685. }
  1686. // Test if the last_item_seen exists and is not a dir.
  1687. if (count($this->ordered_items) == 0) {
  1688. $this->index = 0;
  1689. }
  1690. if ($this->debug > 0) {
  1691. if (isset($this->items[$this->last_item_seen])) {
  1692. $status = $this->items[$this->last_item_seen]->get_status();
  1693. }
  1694. error_log('status '.$status);
  1695. }
  1696. if (!empty($this->last_item_seen) &&
  1697. !empty($this->items[$this->last_item_seen]) &&
  1698. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1699. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1700. //&& !$this->items[$this->last_item_seen]->is_done()
  1701. ) {
  1702. if ($this->debug > 2) {
  1703. error_log('New LP - In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.$this->items[$this->last_item_seen]->get_type(), 0);
  1704. }
  1705. $index = -1;
  1706. foreach ($this->ordered_items as $myindex => $item_id) {
  1707. if ($item_id == $this->last_item_seen) {
  1708. $index = $myindex;
  1709. break;
  1710. }
  1711. }
  1712. if ($index == -1) {
  1713. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1714. if ($this->debug > 2) {
  1715. error_log('New LP - Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1716. }
  1717. return false;
  1718. } else {
  1719. $this->last = $this->last_item_seen;
  1720. $this->current = $this->last_item_seen;
  1721. $this->index = $index;
  1722. }
  1723. } else {
  1724. if ($this->debug > 2) {
  1725. error_log('New LP - In learnpath::first() - No last item seen', 0);
  1726. }
  1727. $index = 0;
  1728. // Loop through all ordered items and stop at the first item that is
  1729. // not a directory *and* that has not been completed yet.
  1730. while (!empty($this->ordered_items[$index]) &&
  1731. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1732. (
  1733. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1734. $this->items[$this->ordered_items[$index]]->is_done() === true
  1735. ) && $index < $this->max_ordered_items) {
  1736. $index++;
  1737. }
  1738. $this->last = $this->current;
  1739. // current is
  1740. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1741. $this->index = $index;
  1742. if ($this->debug > 2) {
  1743. error_log('$index '.$index);
  1744. }
  1745. if ($this->debug > 2) {
  1746. error_log('New LP - In learnpath::first() - No last item seen. New last = '.$this->last.'('.$this->ordered_items[$index].')', 0);
  1747. }
  1748. }
  1749. if ($this->debug > 2) {
  1750. error_log('New LP - In learnpath::first() - First item is '.$this->get_current_item_id());
  1751. }
  1752. }
  1753. /**
  1754. * Gets the information about an item in a format usable as JavaScript to update
  1755. * the JS API by just printing this content into the <head> section of the message frame
  1756. * @param int $item_id
  1757. * @return string
  1758. */
  1759. public function get_js_info($item_id = 0)
  1760. {
  1761. if ($this->debug > 0) {
  1762. error_log('New LP - In learnpath::get_js_info('.$item_id.')', 0);
  1763. }
  1764. $info = '';
  1765. $item_id = intval($item_id);
  1766. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1767. //if item is defined, return values from DB
  1768. $oItem = $this->items[$item_id];
  1769. $info .= '<script language="javascript">';
  1770. $info .= "top.set_score(".$oItem->get_score().");\n";
  1771. $info .= "top.set_max(".$oItem->get_max().");\n";
  1772. $info .= "top.set_min(".$oItem->get_min().");\n";
  1773. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1774. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1775. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1776. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1777. $info .= "top.set_flag_synchronized();";
  1778. $info .= '</script>';
  1779. if ($this->debug > 2) {
  1780. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1781. }
  1782. return $info;
  1783. } else {
  1784. // If item_id is empty, just update to default SCORM data.
  1785. $info .= '<script language="javascript">';
  1786. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1787. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1788. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1789. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1790. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1791. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1792. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1793. $info .= "top.set_flag_synchronized();";
  1794. $info .= '</script>';
  1795. if ($this->debug > 2) {
  1796. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1797. }
  1798. return $info;
  1799. }
  1800. }
  1801. /**
  1802. * Gets the js library from the database
  1803. * @return string The name of the javascript library to be used
  1804. */
  1805. public function get_js_lib()
  1806. {
  1807. $lib = '';
  1808. if (!empty($this->js_lib)) {
  1809. $lib = $this->js_lib;
  1810. }
  1811. return $lib;
  1812. }
  1813. /**
  1814. * Gets the learnpath database ID
  1815. * @return integer Learnpath ID in the lp table
  1816. */
  1817. public function get_id()
  1818. {
  1819. if (!empty($this->lp_id)) {
  1820. return $this->lp_id;
  1821. } else {
  1822. return 0;
  1823. }
  1824. }
  1825. /**
  1826. * Gets the last element URL.
  1827. * @return string URL to load into the viewer
  1828. */
  1829. public function get_last()
  1830. {
  1831. if ($this->debug > 0) {
  1832. error_log('New LP - In learnpath::get_last()', 0);
  1833. }
  1834. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1835. if (count($this->ordered_items) > 0) {
  1836. $this->index = count($this->ordered_items) - 1;
  1837. return $this->ordered_items[$this->index];
  1838. }
  1839. return false;
  1840. }
  1841. /**
  1842. * Gets the navigation bar for the learnpath display screen
  1843. * @return string The HTML string to use as a navigation bar
  1844. */
  1845. public function get_navigation_bar($idBar = null, $display = null)
  1846. {
  1847. if ($this->debug > 0) {
  1848. error_log('New LP - In learnpath::get_navigation_bar()', 0);
  1849. }
  1850. if (empty($idBar)) {
  1851. $idBar = 'control-top';
  1852. }
  1853. $navbar = null;
  1854. $lp_id = $this->lp_id;
  1855. $mycurrentitemid = $this->get_current_item_id();
  1856. $reportingText = get_lang('Reporting');
  1857. $previousText = get_lang('ScormPrevious');
  1858. $nextText = get_lang('ScormNext');
  1859. $fullScreenText = get_lang('ScormExitFullScreen');
  1860. if ($this->mode == 'fullscreen') {
  1861. $navbar = '
  1862. <span id="'.$idBar.'" class="buttons">
  1863. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1864. <span class="fa fa-info"></span><span class="sr-only">' . $reportingText.'</span>
  1865. </a>
  1866. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1867. <span class="fa fa-chevron-left"></span><span class="sr-only">' . $previousText.'</span>
  1868. </a>
  1869. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1870. <span class="fa fa-chevron-right"></span><span class="sr-only">' . $nextText.'</span>
  1871. </a>
  1872. <a class="icon-toolbar" id="view-embedded" href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1873. <span class="fa fa-columns"></span><span class="sr-only">' . $fullScreenText.'</span>
  1874. </a>
  1875. </span>';
  1876. } else {
  1877. $navbar = '
  1878. <span id="'.$idBar.'" class="buttons text-right">
  1879. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1880. <span class="fa fa-info"></span><span class="sr-only">' . $reportingText.'</span>
  1881. </a>
  1882. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1883. <span class="fa fa-chevron-left"></span><span class="sr-only">' . $previousText.'</span>
  1884. </a>
  1885. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1886. <span class="fa fa-chevron-right"></span><span class="sr-only">' . $nextText.'</span>
  1887. </a>
  1888. </span>';
  1889. }
  1890. return $navbar;
  1891. }
  1892. /**
  1893. * Gets the next resource in queue (url).
  1894. * @return string URL to load into the viewer
  1895. */
  1896. public function get_next_index()
  1897. {
  1898. if ($this->debug > 0) {
  1899. error_log('New LP - In learnpath::get_next_index()', 0);
  1900. }
  1901. // TODO
  1902. $index = $this->index;
  1903. $index++;
  1904. if ($this->debug > 2) {
  1905. error_log('New LP - Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1906. }
  1907. while (!empty ($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') && $index < $this->max_ordered_items) {
  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('New LP - index is now '.$index, 0);
  1922. }
  1923. return $index;
  1924. }
  1925. /**
  1926. * Gets item_id for the next element
  1927. * @return integer Next item (DB) ID
  1928. */
  1929. public function get_next_item_id()
  1930. {
  1931. if ($this->debug > 0) {
  1932. error_log('New LP - In learnpath::get_next_item_id()', 0);
  1933. }
  1934. $new_index = $this->get_next_index();
  1935. if (!empty ($new_index)) {
  1936. if (isset ($this->ordered_items[$new_index])) {
  1937. if ($this->debug > 2) {
  1938. error_log('New LP - In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1939. }
  1940. return $this->ordered_items[$new_index];
  1941. }
  1942. }
  1943. if ($this->debug > 2) {
  1944. error_log('New LP - In learnpath::get_next_index() - Problem - Returning 0', 0);
  1945. }
  1946. return 0;
  1947. }
  1948. /**
  1949. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...)
  1950. *
  1951. * Generally, the package provided is in the form of a zip file, so the function
  1952. * has been written to test a zip file. If not a zip, the function will return the
  1953. * default return value: ''
  1954. * @param string the path to the file
  1955. * @param string the original name of the file
  1956. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1957. */
  1958. public static function get_package_type($file_path, $file_name)
  1959. {
  1960. // Get name of the zip file without the extension.
  1961. $file_info = pathinfo($file_name);
  1962. $filename = $file_info['basename']; // Name including extension.
  1963. $extension = $file_info['extension']; // Extension only.
  1964. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), array(
  1965. 'dll',
  1966. 'exe'
  1967. ))) {
  1968. return 'oogie';
  1969. }
  1970. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), array(
  1971. 'dll',
  1972. 'exe'
  1973. ))) {
  1974. return 'woogie';
  1975. }
  1976. $zipFile = new PclZip($file_path);
  1977. // Check the zip content (real size and file extension).
  1978. $zipContentArray = $zipFile->listContent();
  1979. $package_type = '';
  1980. $at_root = false;
  1981. $manifest = '';
  1982. $aicc_match_crs = 0;
  1983. $aicc_match_au = 0;
  1984. $aicc_match_des = 0;
  1985. $aicc_match_cst = 0;
  1986. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1987. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1988. foreach ($zipContentArray as $thisContent) {
  1989. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1990. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1991. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1992. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1993. $package_type = 'scorm';
  1994. break; // Exit the foreach loop.
  1995. } elseif (
  1996. preg_match('/aicc\//i', $thisContent['filename']) ||
  1997. in_array(
  1998. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1999. array('crs', 'au', 'des', 'cst')
  2000. )
  2001. ) {
  2002. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2003. switch ($ext) {
  2004. case 'crs':
  2005. $aicc_match_crs = 1;
  2006. break;
  2007. case 'au':
  2008. $aicc_match_au = 1;
  2009. break;
  2010. case 'des':
  2011. $aicc_match_des = 1;
  2012. break;
  2013. case 'cst':
  2014. $aicc_match_cst = 1;
  2015. break;
  2016. default:
  2017. break;
  2018. }
  2019. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2020. } else {
  2021. $package_type = '';
  2022. }
  2023. }
  2024. }
  2025. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2026. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2027. $package_type = 'aicc';
  2028. }
  2029. return $package_type;
  2030. }
  2031. /**
  2032. * Gets the previous resource in queue (url). Also initialises time values for this viewing
  2033. * @return string URL to load into the viewer
  2034. */
  2035. public function get_previous_index()
  2036. {
  2037. if ($this->debug > 0) {
  2038. error_log('New LP - In learnpath::get_previous_index()', 0);
  2039. }
  2040. $index = $this->index;
  2041. if (isset ($this->ordered_items[$index - 1])) {
  2042. $index--;
  2043. while (isset($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')) {
  2044. $index--;
  2045. if ($index < 0) {
  2046. return $this->index;
  2047. }
  2048. }
  2049. } else {
  2050. if ($this->debug > 2) {
  2051. error_log('New LP - get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2052. }
  2053. // There is no previous item.
  2054. }
  2055. return $index;
  2056. }
  2057. /**
  2058. * Gets item_id for the next element
  2059. * @return integer Previous item (DB) ID
  2060. */
  2061. public function get_previous_item_id()
  2062. {
  2063. if ($this->debug > 0) {
  2064. error_log('New LP - In learnpath::get_previous_item_id()', 0);
  2065. }
  2066. $new_index = $this->get_previous_index();
  2067. return $this->ordered_items[$new_index];
  2068. }
  2069. /**
  2070. * Gets the progress value from the progress_db attribute
  2071. * @return integer Current progress value
  2072. * @deprecated This method does not seem to be used as of 20170514
  2073. */
  2074. public function get_progress()
  2075. {
  2076. if ($this->debug > 0) {
  2077. error_log('New LP - In learnpath::get_progress()', 0);
  2078. }
  2079. if (!empty ($this->progress_db)) {
  2080. return $this->progress_db;
  2081. }
  2082. return 0;
  2083. }
  2084. /**
  2085. * Returns the HTML necessary to print a mediaplayer block inside a page
  2086. * @param int $lpItemId
  2087. * @param string $autostart
  2088. * @return string The mediaplayer HTML
  2089. */
  2090. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2091. {
  2092. $course_id = api_get_course_int_id();
  2093. $_course = api_get_course_info();
  2094. if (empty($_course)) {
  2095. return '';
  2096. }
  2097. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2098. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2099. // Getting all the information about the item.
  2100. $sql = "SELECT * FROM $tbl_lp_item as lp
  2101. INNER JOIN $tbl_lp_item_view as lp_view
  2102. ON (lp.id = lp_view.lp_item_id AND lp.c_id = lp_view.c_id)
  2103. WHERE
  2104. lp.id = '$lpItemId' AND
  2105. lp.c_id = $course_id AND
  2106. lp_view.c_id = $course_id";
  2107. $result = Database::query($sql);
  2108. $row = Database::fetch_assoc($result);
  2109. $output = '';
  2110. if (!empty ($row['audio'])) {
  2111. $list = $_SESSION['oLP']->get_toc();
  2112. $type_quiz = false;
  2113. foreach ($list as $toc) {
  2114. if ($toc['id'] == $_SESSION['oLP']->current && ($toc['type'] == 'quiz')) {
  2115. $type_quiz = true;
  2116. }
  2117. }
  2118. if ($type_quiz) {
  2119. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2120. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2121. } else {
  2122. $autostart_audio = $autostart;
  2123. }
  2124. } else {
  2125. $autostart_audio = 'true';
  2126. }
  2127. $courseInfo = api_get_course_info();
  2128. $audio = $row['audio'];
  2129. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2130. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2131. if (!file_exists($file)) {
  2132. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2133. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2134. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2135. }
  2136. $player = Display::getMediaPlayer(
  2137. $file,
  2138. array(
  2139. 'id' => 'lp_audio_media_player',
  2140. 'url' => $url,
  2141. 'autoplay' => $autostart_audio,
  2142. 'width' => '100%'
  2143. )
  2144. );
  2145. // The mp3 player.
  2146. $output = '<div id="container">';
  2147. $output .= $player;
  2148. $output .= '</div>';
  2149. }
  2150. return $output;
  2151. }
  2152. /**
  2153. * @param int $studentId
  2154. * @param int $prerequisite
  2155. * @param array $courseInfo
  2156. * @return bool
  2157. *
  2158. */
  2159. public static function isBlockedByPrerequisite(
  2160. $studentId,
  2161. $prerequisite,
  2162. $courseInfo,
  2163. $sessionId
  2164. ) {
  2165. $isBlocked = false;
  2166. if (!empty($prerequisite)) {
  2167. $progress = self::getProgress(
  2168. $prerequisite,
  2169. $studentId,
  2170. $courseInfo['real_id'],
  2171. $sessionId
  2172. );
  2173. if ($progress < 100) {
  2174. $isBlocked = true;
  2175. }
  2176. }
  2177. return $isBlocked;
  2178. }
  2179. /**
  2180. * Checks if the learning path is visible for student after the progress
  2181. * of its prerequisite is completed, considering the time availability and
  2182. * the LP visibility.
  2183. * @param int $lp_id
  2184. * @param int $student_id
  2185. * @param string Course code (optional)
  2186. * @param int $sessionId
  2187. * @return bool
  2188. */
  2189. public static function is_lp_visible_for_student(
  2190. $lp_id,
  2191. $student_id,
  2192. $courseCode = null,
  2193. $sessionId = 0
  2194. ) {
  2195. $courseInfo = api_get_course_info($courseCode);
  2196. $lp_id = (int) $lp_id;
  2197. $sessionId = (int) $sessionId;
  2198. if (empty($courseInfo)) {
  2199. return false;
  2200. }
  2201. if (empty($sessionId)) {
  2202. $sessionId = api_get_session_id();
  2203. }
  2204. $itemInfo = api_get_item_property_info(
  2205. $courseInfo['real_id'],
  2206. TOOL_LEARNPATH,
  2207. $lp_id,
  2208. $sessionId
  2209. );
  2210. // If the item was deleted.
  2211. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2212. return false;
  2213. }
  2214. // @todo remove this query and load the row info as a parameter
  2215. $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
  2216. // Get current prerequisite
  2217. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2218. FROM $tbl_learnpath
  2219. WHERE c_id = ".$courseInfo['real_id']." AND id = $lp_id";
  2220. $rs = Database::query($sql);
  2221. $now = time();
  2222. if (Database::num_rows($rs) > 0) {
  2223. $row = Database::fetch_array($rs, 'ASSOC');
  2224. $prerequisite = $row['prerequisite'];
  2225. $is_visible = true;
  2226. $isBlocked = self::isBlockedByPrerequisite(
  2227. $student_id,
  2228. $prerequisite,
  2229. $courseInfo,
  2230. $sessionId
  2231. );
  2232. if ($isBlocked) {
  2233. $is_visible = false;
  2234. }
  2235. // Also check the time availability of the LP
  2236. if ($is_visible) {
  2237. // Adding visibility restrictions
  2238. if (!empty($row['publicated_on'])) {
  2239. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2240. $is_visible = false;
  2241. }
  2242. }
  2243. // Blocking empty start times see BT#2800
  2244. global $_custom;
  2245. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2246. $_custom['lps_hidden_when_no_start_date']
  2247. ) {
  2248. if (empty($row['publicated_on'])) {
  2249. $is_visible = false;
  2250. }
  2251. }
  2252. if (!empty($row['expired_on'])) {
  2253. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2254. $is_visible = false;
  2255. }
  2256. }
  2257. }
  2258. // Check if the subscription users/group to a LP is ON
  2259. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1) {
  2260. // Try group
  2261. $is_visible = false;
  2262. // Checking only the user visibility
  2263. $userVisibility = api_get_item_visibility(
  2264. $courseInfo,
  2265. 'learnpath',
  2266. $row['id'],
  2267. $sessionId,
  2268. $student_id,
  2269. 'LearnpathSubscription'
  2270. );
  2271. if ($userVisibility == 1) {
  2272. $is_visible = true;
  2273. } else {
  2274. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2275. if (!empty($userGroups)) {
  2276. foreach ($userGroups as $groupInfo) {
  2277. $groupId = $groupInfo['iid'];
  2278. $userVisibility = api_get_item_visibility(
  2279. $courseInfo,
  2280. 'learnpath',
  2281. $row['id'],
  2282. $sessionId,
  2283. null,
  2284. 'LearnpathSubscription',
  2285. $groupId
  2286. );
  2287. if ($userVisibility == 1) {
  2288. $is_visible = true;
  2289. break;
  2290. }
  2291. }
  2292. }
  2293. }
  2294. }
  2295. return $is_visible;
  2296. }
  2297. return false;
  2298. }
  2299. /**
  2300. * @param int $lpId
  2301. * @param int $userId
  2302. * @param int $courseId
  2303. * @param int $sessionId
  2304. * @return int
  2305. */
  2306. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2307. {
  2308. $lpId = intval($lpId);
  2309. $userId = intval($userId);
  2310. $courseId = intval($courseId);
  2311. $sessionId = intval($sessionId);
  2312. $progress = 0;
  2313. $sessionCondition = api_get_session_condition($sessionId);
  2314. $table = Database::get_course_table(TABLE_LP_VIEW);
  2315. $sql = "SELECT * FROM $table
  2316. WHERE
  2317. c_id = ".$courseId." AND
  2318. lp_id = $lpId AND
  2319. user_id = $userId $sessionCondition";
  2320. $res = Database::query($sql);
  2321. if (Database::num_rows($res) > 0) {
  2322. $row = Database:: fetch_array($res);
  2323. $progress = $row['progress'];
  2324. }
  2325. return (int) $progress;
  2326. }
  2327. /**
  2328. * Displays a progress bar
  2329. * completed so far.
  2330. * @param integer $percentage Progress value to display
  2331. * @param string $text_add Text to display near the progress value
  2332. * @return string HTML string containing the progress bar
  2333. */
  2334. public static function get_progress_bar($percentage = -1, $text_add = '')
  2335. {
  2336. $text = $percentage.$text_add;
  2337. $output = '<div class="progress">
  2338. <div id="progress_bar_value" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="' .$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2339. '. $text.'
  2340. </div>
  2341. </div>';
  2342. return $output;
  2343. }
  2344. /**
  2345. * @param string $mode can be '%' or 'abs'
  2346. * otherwise this value will be used $this->progress_bar_mode
  2347. * @return string
  2348. */
  2349. public function getProgressBar($mode = null)
  2350. {
  2351. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2352. return self::get_progress_bar($percentage, $text_add);
  2353. }
  2354. /**
  2355. * Gets the progress bar info to display inside the progress bar.
  2356. * Also used by scorm_api.php
  2357. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2358. * we display a number of completed elements per total elements
  2359. * @param integer $add Additional steps to fake as completed
  2360. * @return list array Percentage or number and symbol (% or /xx)
  2361. */
  2362. public function get_progress_bar_text($mode = '', $add = 0)
  2363. {
  2364. if ($this->debug > 0) {
  2365. error_log('New LP - In learnpath::get_progress_bar_text()', 0);
  2366. }
  2367. if (empty($mode)) {
  2368. $mode = $this->progress_bar_mode;
  2369. }
  2370. $total_items = $this->getTotalItemsCountWithoutDirs();
  2371. if ($this->debug > 2) {
  2372. error_log('New LP - Total items available in this learnpath: '.$total_items, 0);
  2373. }
  2374. $completeItems = $this->get_complete_items_count();
  2375. if ($this->debug > 2) {
  2376. error_log('New LP - Items completed so far: '.$completeItems, 0);
  2377. }
  2378. if ($add != 0) {
  2379. $completeItems += $add;
  2380. if ($this->debug > 2) {
  2381. error_log('New LP - Items completed so far (+modifier): '.$completeItems, 0);
  2382. }
  2383. }
  2384. $text = '';
  2385. if ($completeItems > $total_items) {
  2386. $completeItems = $total_items;
  2387. }
  2388. $percentage = 0;
  2389. if ($mode == '%') {
  2390. if ($total_items > 0) {
  2391. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2392. } else {
  2393. $percentage = 0;
  2394. }
  2395. $percentage = number_format($percentage, 0);
  2396. $text = '%';
  2397. } elseif ($mode == 'abs') {
  2398. $percentage = $completeItems;
  2399. $text = '/'.$total_items;
  2400. }
  2401. return array(
  2402. $percentage,
  2403. $text
  2404. );
  2405. }
  2406. /**
  2407. * Gets the progress bar mode
  2408. * @return string The progress bar mode attribute
  2409. */
  2410. public function get_progress_bar_mode()
  2411. {
  2412. if ($this->debug > 0) {
  2413. error_log('New LP - In learnpath::get_progress_bar_mode()', 0);
  2414. }
  2415. if (!empty ($this->progress_bar_mode)) {
  2416. return $this->progress_bar_mode;
  2417. } else {
  2418. return '%';
  2419. }
  2420. }
  2421. /**
  2422. * Gets the learnpath proximity (remote or local)
  2423. * @return string Learnpath proximity
  2424. */
  2425. public function get_proximity()
  2426. {
  2427. if ($this->debug > 0) {
  2428. error_log('New LP - In learnpath::get_proximity()', 0);
  2429. }
  2430. if (!empty ($this->proximity)) {
  2431. return $this->proximity;
  2432. } else {
  2433. return '';
  2434. }
  2435. }
  2436. /**
  2437. * Gets the learnpath theme (remote or local)
  2438. * @return string Learnpath theme
  2439. */
  2440. public function get_theme()
  2441. {
  2442. if ($this->debug > 0) {
  2443. error_log('New LP - In learnpath::get_theme()', 0);
  2444. }
  2445. if (!empty ($this->theme)) {
  2446. return $this->theme;
  2447. } else {
  2448. return '';
  2449. }
  2450. }
  2451. /**
  2452. * Gets the learnpath session id
  2453. * @return int
  2454. */
  2455. public function get_lp_session_id()
  2456. {
  2457. if ($this->debug > 0) {
  2458. error_log('New LP - In learnpath::get_lp_session_id()', 0);
  2459. }
  2460. if (!empty ($this->lp_session_id)) {
  2461. return (int) $this->lp_session_id;
  2462. } else {
  2463. return 0;
  2464. }
  2465. }
  2466. /**
  2467. * Gets the learnpath image
  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('New LP - 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. * @return bool|string
  2485. */
  2486. public function get_preview_image_path($size = null, $path_type = 'web')
  2487. {
  2488. $preview_image = $this->get_preview_image();
  2489. if (isset($preview_image) && !empty($preview_image)) {
  2490. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2491. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2492. if (isset($size)) {
  2493. $info = pathinfo($preview_image);
  2494. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2495. if (file_exists($image_sys_path.$image_custom_size)) {
  2496. if ($path_type == 'web') {
  2497. return $image_path.$image_custom_size;
  2498. } else {
  2499. return $image_sys_path.$image_custom_size;
  2500. }
  2501. }
  2502. } else {
  2503. if ($path_type == 'web') {
  2504. return $image_path.$preview_image;
  2505. } else {
  2506. return $image_sys_path.$preview_image;
  2507. }
  2508. }
  2509. }
  2510. return false;
  2511. }
  2512. /**
  2513. * Gets the learnpath author
  2514. * @return string LP's author
  2515. */
  2516. public function get_author()
  2517. {
  2518. if ($this->debug > 0) {
  2519. error_log('New LP - In learnpath::get_author()', 0);
  2520. }
  2521. if (!empty ($this->author)) {
  2522. return $this->author;
  2523. } else {
  2524. return '';
  2525. }
  2526. }
  2527. /**
  2528. * Gets the learnpath author
  2529. * @return string LP's author
  2530. */
  2531. public function get_hide_toc_frame()
  2532. {
  2533. if ($this->debug > 0) {
  2534. error_log('New LP - In learnpath::get_author()', 0);
  2535. }
  2536. if (!empty ($this->hide_toc_frame)) {
  2537. return $this->hide_toc_frame;
  2538. } else {
  2539. return '';
  2540. }
  2541. }
  2542. /**
  2543. * Generate a new prerequisites string for a given item. If this item was a sco and
  2544. * its prerequisites were strings (instead of IDs), then transform those strings into
  2545. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2546. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2547. * same rule as the scorm_export() method
  2548. * @param integer Item ID
  2549. * @return string Prerequisites string ready for the export as SCORM
  2550. */
  2551. public function get_scorm_prereq_string($item_id)
  2552. {
  2553. if ($this->debug > 0) {
  2554. error_log('New LP - In learnpath::get_scorm_prereq_string()', 0);
  2555. }
  2556. if (!is_object($this->items[$item_id])) {
  2557. return false;
  2558. }
  2559. /** @var learnpathItem $oItem */
  2560. $oItem = $this->items[$item_id];
  2561. $prereq = $oItem->get_prereq_string();
  2562. if (empty($prereq)) {
  2563. return '';
  2564. }
  2565. if (preg_match('/^\d+$/', $prereq) && is_object($this->items[$prereq])) {
  2566. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2567. // then simply return it (with the ITEM_ prefix).
  2568. //return 'ITEM_' . $prereq;
  2569. return $this->items[$prereq]->ref;
  2570. } else {
  2571. if (isset($this->refs_list[$prereq])) {
  2572. // It's a simple string item from which the ID can be found in the refs list,
  2573. // so we can transform it directly to an ID for export.
  2574. return $this->items[$this->refs_list[$prereq]]->ref;
  2575. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2576. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2577. } else {
  2578. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2579. // and replace them, one by one, by the internal IDs (chamilo db)
  2580. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2581. // by a space as well.
  2582. $find = array(
  2583. '&',
  2584. '|',
  2585. '~',
  2586. '=',
  2587. '<>',
  2588. '{',
  2589. '}',
  2590. '*',
  2591. '(',
  2592. ')'
  2593. );
  2594. $replace = array(
  2595. ' ',
  2596. ' ',
  2597. ' ',
  2598. ' ',
  2599. ' ',
  2600. ' ',
  2601. ' ',
  2602. ' ',
  2603. ' ',
  2604. ' '
  2605. );
  2606. $prereq_mod = str_replace($find, $replace, $prereq);
  2607. $ids = explode(' ', $prereq_mod);
  2608. foreach ($ids as $id) {
  2609. $id = trim($id);
  2610. if (isset ($this->refs_list[$id])) {
  2611. $prereq = preg_replace('/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/', 'ITEM_'.$this->refs_list[$id], $prereq);
  2612. }
  2613. }
  2614. return $prereq;
  2615. }
  2616. }
  2617. }
  2618. /**
  2619. * Returns the XML DOM document's node
  2620. * @param resource Reference to a list of objects to search for the given ITEM_*
  2621. * @param string The identifier to look for
  2622. * @return mixed The reference to the element found with that identifier. False if not found
  2623. */
  2624. public function get_scorm_xml_node(& $children, $id)
  2625. {
  2626. for ($i = 0; $i < $children->length; $i++) {
  2627. $item_temp = $children->item($i);
  2628. if ($item_temp->nodeName == 'item') {
  2629. if ($item_temp->getAttribute('identifier') == $id) {
  2630. return $item_temp;
  2631. }
  2632. }
  2633. $subchildren = $item_temp->childNodes;
  2634. if ($subchildren && $subchildren->length > 0) {
  2635. $val = $this->get_scorm_xml_node($subchildren, $id);
  2636. if (is_object($val)) {
  2637. return $val;
  2638. }
  2639. }
  2640. }
  2641. return false;
  2642. }
  2643. /**
  2644. * Gets the status list for all LP's items
  2645. * @return array Array of [index] => [item ID => current status]
  2646. */
  2647. public function get_items_status_list()
  2648. {
  2649. if ($this->debug > 0) {
  2650. error_log('New LP - In learnpath::get_items_status_list()', 0);
  2651. }
  2652. $list = array();
  2653. foreach ($this->ordered_items as $item_id) {
  2654. $list[] = array(
  2655. $item_id => $this->items[$item_id]->get_status()
  2656. );
  2657. }
  2658. return $list;
  2659. }
  2660. /**
  2661. * Return the number of interactions for the given learnpath Item View ID.
  2662. * This method can be used as static.
  2663. * @param integer Item View ID
  2664. * @param integer course id
  2665. * @return integer Number of interactions
  2666. */
  2667. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2668. {
  2669. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2670. $lp_iv_id = intval($lp_iv_id);
  2671. $course_id = intval($course_id);
  2672. $sql = "SELECT count(*) FROM $table
  2673. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2674. $res = Database::query($sql);
  2675. $num = 0;
  2676. if (Database::num_rows($res)) {
  2677. $row = Database::fetch_array($res);
  2678. $num = $row[0];
  2679. }
  2680. return $num;
  2681. }
  2682. /**
  2683. * Return the interactions as an array for the given lp_iv_id.
  2684. * This method can be used as static.
  2685. * @param integer Learnpath Item View ID
  2686. * @return array
  2687. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2688. */
  2689. public static function get_iv_interactions_array($lp_iv_id)
  2690. {
  2691. $course_id = api_get_course_int_id();
  2692. $list = array();
  2693. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2694. if (empty($lp_iv_id)) {
  2695. return array();
  2696. }
  2697. $sql = "SELECT * FROM $table
  2698. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2699. ORDER BY order_id ASC";
  2700. $res = Database::query($sql);
  2701. $num = Database::num_rows($res);
  2702. if ($num > 0) {
  2703. $list[] = array(
  2704. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2705. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2706. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2707. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2708. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2709. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2710. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2711. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES)
  2712. );
  2713. while ($row = Database::fetch_array($res)) {
  2714. $list[] = array(
  2715. 'order_id' => ($row['order_id'] + 1),
  2716. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2717. 'type' => $row['interaction_type'],
  2718. 'time' => $row['completion_time'],
  2719. //'correct_responses' => $row['correct_responses'],
  2720. 'correct_responses' => '', // Hide correct responses from students.
  2721. 'student_response' => $row['student_response'],
  2722. 'result' => $row['result'],
  2723. 'latency' => $row['latency']
  2724. );
  2725. }
  2726. }
  2727. return $list;
  2728. }
  2729. /**
  2730. * Return the number of objectives for the given learnpath Item View ID.
  2731. * This method can be used as static.
  2732. * @param integer Item View ID
  2733. * @return integer Number of objectives
  2734. */
  2735. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2736. {
  2737. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2738. $course_id = intval($course_id);
  2739. $lp_iv_id = intval($lp_iv_id);
  2740. $sql = "SELECT count(*) FROM $table
  2741. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2742. //@todo seems that this always returns 0
  2743. $res = Database::query($sql);
  2744. $num = 0;
  2745. if (Database::num_rows($res)) {
  2746. $row = Database::fetch_array($res);
  2747. $num = $row[0];
  2748. }
  2749. return $num;
  2750. }
  2751. /**
  2752. * Return the objectives as an array for the given lp_iv_id.
  2753. * This method can be used as static.
  2754. * @param integer Learnpath Item View ID
  2755. * @return array
  2756. * @todo Translate labels
  2757. */
  2758. public static function get_iv_objectives_array($lp_iv_id = 0)
  2759. {
  2760. $course_id = api_get_course_int_id();
  2761. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2762. $sql = "SELECT * FROM $table
  2763. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id
  2764. ORDER BY order_id ASC";
  2765. $res = Database::query($sql);
  2766. $num = Database::num_rows($res);
  2767. $list = array();
  2768. if ($num > 0) {
  2769. $list[] = array(
  2770. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2771. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2772. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2773. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2774. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2775. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES)
  2776. );
  2777. while ($row = Database::fetch_array($res)) {
  2778. $list[] = array(
  2779. 'order_id' => ($row['order_id'] + 1),
  2780. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F or stuff like that.
  2781. 'score_raw' => $row['score_raw'],
  2782. 'score_max' => $row['score_max'],
  2783. 'score_min' => $row['score_min'],
  2784. 'status' => $row['status']
  2785. );
  2786. }
  2787. }
  2788. return $list;
  2789. }
  2790. /**
  2791. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2792. * used by get_html_toc() to be ready to display
  2793. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2794. */
  2795. public function get_toc()
  2796. {
  2797. if ($this->debug > 0) {
  2798. error_log('learnpath::get_toc()', 0);
  2799. }
  2800. $toc = array();
  2801. foreach ($this->ordered_items as $item_id) {
  2802. if ($this->debug > 2) {
  2803. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2804. }
  2805. // TODO: Change this link generation and use new function instead.
  2806. $toc[] = array(
  2807. 'id' => $item_id,
  2808. 'title' => $this->items[$item_id]->get_title(),
  2809. 'status' => $this->items[$item_id]->get_status(),
  2810. 'level' => $this->items[$item_id]->get_level(),
  2811. 'type' => $this->items[$item_id]->get_type(),
  2812. 'description' => $this->items[$item_id]->get_description(),
  2813. 'path' => $this->items[$item_id]->get_path(),
  2814. );
  2815. }
  2816. if ($this->debug > 2) {
  2817. error_log('New LP - In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2818. }
  2819. return $toc;
  2820. }
  2821. /**
  2822. * Generate and return the table of contents for this learnpath. The JS
  2823. * table returned is used inside of scorm_api.php
  2824. * @return string A JS array vairiable construction
  2825. */
  2826. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2827. {
  2828. if ($this->debug > 0) {
  2829. error_log('New LP - In learnpath::get_items_details_as_js()', 0);
  2830. }
  2831. $toc = $varname.' = new Array();';
  2832. foreach ($this->ordered_items as $item_id) {
  2833. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2834. }
  2835. if ($this->debug > 2) {
  2836. error_log('New LP - In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2837. }
  2838. return $toc;
  2839. }
  2840. /**
  2841. * Gets the learning path type
  2842. * @param boolean Return the name? If false, return the ID. Default is false.
  2843. * @return mixed Type ID or name, depending on the parameter
  2844. */
  2845. public function get_type($get_name = false)
  2846. {
  2847. $res = false;
  2848. if ($this->debug > 0) {
  2849. error_log('New LP - In learnpath::get_type()', 0);
  2850. }
  2851. if (!empty($this->type)) {
  2852. if ($get_name) {
  2853. // Get it from the lp_type table in main db.
  2854. } else {
  2855. $res = $this->type;
  2856. }
  2857. }
  2858. if ($this->debug > 2) {
  2859. error_log('New LP - In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2860. }
  2861. return $res;
  2862. }
  2863. /**
  2864. * Gets the learning path type as static method
  2865. * @param int $lp_id
  2866. * @return mixed Type ID or name, depending on the parameter
  2867. */
  2868. public static function get_type_static($lp_id = 0)
  2869. {
  2870. $course_id = api_get_course_int_id();
  2871. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2872. $lp_id = intval($lp_id);
  2873. $sql = "SELECT lp_type FROM $tbl_lp
  2874. WHERE c_id = $course_id AND id = '".$lp_id."'";
  2875. $res = Database::query($sql);
  2876. if ($res === false) {
  2877. return null;
  2878. }
  2879. if (Database::num_rows($res) <= 0) {
  2880. return null;
  2881. }
  2882. $row = Database::fetch_array($res);
  2883. return $row['lp_type'];
  2884. }
  2885. /**
  2886. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2887. * This method can be used as abstract and is recursive
  2888. * @param integer Learnpath ID
  2889. * @param integer Parent ID of the items to look for
  2890. * @return array Ordered list of item IDs (empty array on error)
  2891. */
  2892. public static function get_flat_ordered_items_list($lp, $parent = 0, $course_id = 0)
  2893. {
  2894. if (empty($course_id)) {
  2895. $course_id = api_get_course_int_id();
  2896. } else {
  2897. $course_id = intval($course_id);
  2898. }
  2899. $list = array();
  2900. if (empty($lp)) {
  2901. return $list;
  2902. }
  2903. $lp = intval($lp);
  2904. $parent = intval($parent);
  2905. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2906. $sql = "SELECT id FROM $tbl_lp_item
  2907. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2908. ORDER BY display_order";
  2909. $res = Database::query($sql);
  2910. while ($row = Database::fetch_array($res)) {
  2911. $sublist = self::get_flat_ordered_items_list(
  2912. $lp,
  2913. $row['id'],
  2914. $course_id
  2915. );
  2916. $list[] = $row['id'];
  2917. foreach ($sublist as $item) {
  2918. $list[] = $item;
  2919. }
  2920. }
  2921. return $list;
  2922. }
  2923. /**
  2924. * @return array
  2925. */
  2926. public static function getChapterTypes()
  2927. {
  2928. return array(
  2929. 'dir'
  2930. );
  2931. }
  2932. /**
  2933. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display
  2934. * @return string HTML TOC ready to display
  2935. */
  2936. public function getListArrayToc($toc_list = null)
  2937. {
  2938. if ($this->debug > 0) {
  2939. error_log('In learnpath::get_html_toc()', 0);
  2940. }
  2941. if (empty($toc_list)) {
  2942. $toc_list = $this->get_toc();
  2943. }
  2944. // Temporary variables.
  2945. $mycurrentitemid = $this->get_current_item_id();
  2946. $list = [];
  2947. $arrayList = [];
  2948. $classStatus = [
  2949. 'not attempted' => 'scorm_not_attempted',
  2950. 'incomplete' => 'scorm_not_attempted',
  2951. 'failed' => 'scorm_failed',
  2952. 'completed' => 'scorm_completed',
  2953. 'passed' => 'scorm_completed',
  2954. 'succeeded' => 'scorm_completed',
  2955. 'browsed' => 'scorm_completed',
  2956. ];
  2957. foreach ($toc_list as $item) {
  2958. $list['id'] = $item['id'];
  2959. $list['status'] = $item['status'];
  2960. $cssStatus = null;
  2961. if (isset($classStatus[$item['status']])) {
  2962. $cssStatus = $classStatus[$item['status']];
  2963. }
  2964. $classStyle = ' ';
  2965. $dirTypes = self::getChapterTypes();
  2966. if (in_array($item['type'], $dirTypes)) {
  2967. $classStyle = 'scorm_item_section ';
  2968. }
  2969. if ($item['id'] == $this->current) {
  2970. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2971. } elseif (!in_array($item['type'], $dirTypes)) {
  2972. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2973. }
  2974. $title = $item['title'];
  2975. if (empty($title)) {
  2976. $title = self::rl_get_resource_name(
  2977. api_get_course_id(),
  2978. $this->get_id(),
  2979. $item['id']
  2980. );
  2981. }
  2982. $title = Security::remove_XSS($item['title']);
  2983. if (empty($item['description'])) {
  2984. $list['description'] = $title;
  2985. } else {
  2986. $list['description'] = $item['description'];
  2987. }
  2988. $list['class'] = $classStyle.' '.$cssStatus;
  2989. $list['level'] = $item['level'];
  2990. $list['type'] = $item['type'];
  2991. if (in_array($item['type'], $dirTypes)) {
  2992. $list['css_level'] = 'level_'.$item['level'];
  2993. } else {
  2994. $list['css_level'] = 'level_'.$item['level']
  2995. .' scorm_type_'
  2996. .learnpath::format_scorm_type_item($item['type']);
  2997. }
  2998. if (in_array($item['type'], $dirTypes)) {
  2999. $list['title'] = stripslashes($title);
  3000. } else {
  3001. $list['title'] = stripslashes($title);
  3002. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3003. $list['current_id'] = $mycurrentitemid;
  3004. }
  3005. $arrayList[] = $list;
  3006. }
  3007. return $arrayList;
  3008. }
  3009. /**
  3010. * Returns an HTML-formatted string ready to display with teacher buttons
  3011. * in LP view menu
  3012. * @return string HTML TOC ready to display
  3013. */
  3014. public function get_teacher_toc_buttons()
  3015. {
  3016. $is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
  3017. $hide_teacher_icons_lp = api_get_configuration_value('hide_teacher_icons_lp');
  3018. $html = '';
  3019. if ($is_allowed_to_edit && $hide_teacher_icons_lp == false) {
  3020. if ($this->get_lp_session_id() == api_get_session_id()) {
  3021. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3022. $html .= '<div class="btn-group">';
  3023. $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'>".
  3024. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3025. $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'>".
  3026. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3027. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3028. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3029. $html .= '</div>';
  3030. $html .= '</div>';
  3031. }
  3032. }
  3033. return $html;
  3034. }
  3035. /**
  3036. * Gets the learnpath maker name - generally the editor's name
  3037. * @return string Learnpath maker name
  3038. */
  3039. public function get_maker()
  3040. {
  3041. if ($this->debug > 0) {
  3042. error_log('New LP - In learnpath::get_maker()', 0);
  3043. }
  3044. if (!empty ($this->maker)) {
  3045. return $this->maker;
  3046. } else {
  3047. return '';
  3048. }
  3049. }
  3050. /**
  3051. * Gets the learnpath name/title
  3052. * @return string Learnpath name/title
  3053. */
  3054. public function get_name()
  3055. {
  3056. if ($this->debug > 0) {
  3057. error_log('New LP - In learnpath::get_name()', 0);
  3058. }
  3059. if (!empty ($this->name)) {
  3060. return $this->name;
  3061. } else {
  3062. return 'N/A';
  3063. }
  3064. }
  3065. /**
  3066. * Gets a link to the resource from the present location, depending on item ID.
  3067. * @param string $type Type of link expected
  3068. * @param integer $item_id Learnpath item ID
  3069. * @return string $provided_toc Link to the lp_item resource
  3070. */
  3071. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3072. {
  3073. $course_id = $this->get_course_int_id();
  3074. if ($this->debug > 0) {
  3075. error_log('New LP - In learnpath::get_link('.$type.','.$item_id.')', 0);
  3076. }
  3077. if (empty($item_id)) {
  3078. if ($this->debug > 2) {
  3079. error_log('New LP - In learnpath::get_link() - no item id given in learnpath::get_link(), using current: '.$this->get_current_item_id(), 0);
  3080. }
  3081. $item_id = $this->get_current_item_id();
  3082. }
  3083. if (empty($item_id)) {
  3084. if ($this->debug > 2) {
  3085. error_log('New LP - In learnpath::get_link() - no current item id found in learnpath object', 0);
  3086. }
  3087. //still empty, this means there was no item_id given and we are not in an object context or
  3088. //the object property is empty, return empty link
  3089. $item_id = $this->first();
  3090. return '';
  3091. }
  3092. $file = '';
  3093. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3094. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3095. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3096. $item_id = intval($item_id);
  3097. $sql = "SELECT
  3098. l.lp_type as ltype,
  3099. l.path as lpath,
  3100. li.item_type as litype,
  3101. li.path as lipath,
  3102. li.parameters as liparams
  3103. FROM $lp_table l
  3104. INNER JOIN $lp_item_table li
  3105. ON (li.lp_id = l.id AND l.c_id = li.c_id)
  3106. WHERE
  3107. li.id = $item_id AND
  3108. li.c_id = $course_id
  3109. ";
  3110. if ($this->debug > 2) {
  3111. error_log('New LP - In learnpath::get_link() - selecting item '.$sql, 0);
  3112. }
  3113. $res = Database::query($sql);
  3114. if (Database::num_rows($res) > 0) {
  3115. $row = Database::fetch_array($res);
  3116. $lp_type = $row['ltype'];
  3117. $lp_path = $row['lpath'];
  3118. $lp_item_type = $row['litype'];
  3119. $lp_item_path = $row['lipath'];
  3120. $lp_item_params = $row['liparams'];
  3121. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3122. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3123. }
  3124. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3125. if ($type == 'http') {
  3126. //web path
  3127. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3128. } else {
  3129. $course_path = $sys_course_path; //system path
  3130. }
  3131. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3132. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3133. if (in_array($lp_item_type,
  3134. array('quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication'))
  3135. ) {
  3136. $lp_type = 1;
  3137. }
  3138. if ($this->debug > 2) {
  3139. error_log('New LP - In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3140. error_log('New LP - In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3141. }
  3142. // Now go through the specific cases to get the end of the path
  3143. // @todo Use constants instead of int values.
  3144. switch ($lp_type) {
  3145. case 1 :
  3146. $file = self::rl_get_resource_link_for_learnpath(
  3147. $course_id,
  3148. $this->get_id(),
  3149. $item_id,
  3150. $this->get_view_id()
  3151. );
  3152. if ($this->debug > 0) {
  3153. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3154. }
  3155. switch ($lp_item_type) {
  3156. case 'dir':
  3157. $file = 'lp_content.php?type=dir';
  3158. break;
  3159. case 'link':
  3160. if (Link::is_youtube_link($file)) {
  3161. $src = Link::get_youtube_video_id($file);
  3162. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3163. } elseif (Link::isVimeoLink($file)) {
  3164. $src = Link::getVimeoLinkId($file);
  3165. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3166. } else {
  3167. // If the current site is HTTPS and the link is
  3168. // HTTP, browsers will refuse opening the link
  3169. $urlId = api_get_current_access_url_id();
  3170. $url = api_get_access_url($urlId, false);
  3171. $protocol = substr($url['url'], 0, 5);
  3172. if ($protocol === 'https') {
  3173. $linkProtocol = substr($file, 0, 5);
  3174. if ($linkProtocol === 'http:') {
  3175. //this is the special intervention case
  3176. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3177. }
  3178. }
  3179. }
  3180. break;
  3181. case 'quiz':
  3182. // Check how much attempts of a exercise exits in lp
  3183. $lp_item_id = $this->get_current_item_id();
  3184. $lp_view_id = $this->get_view_id();
  3185. $prevent_reinit = null;
  3186. if (isset($this->items[$this->current])) {
  3187. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3188. }
  3189. if (empty($provided_toc)) {
  3190. if ($this->debug > 0) {
  3191. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3192. }
  3193. $list = $this->get_toc();
  3194. } else {
  3195. if ($this->debug > 0) {
  3196. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3197. }
  3198. $list = $provided_toc;
  3199. }
  3200. $type_quiz = false;
  3201. foreach ($list as $toc) {
  3202. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3203. $type_quiz = true;
  3204. }
  3205. }
  3206. if ($type_quiz) {
  3207. $lp_item_id = intval($lp_item_id);
  3208. $lp_view_id = intval($lp_view_id);
  3209. $sql = "SELECT count(*) FROM $lp_item_view_table
  3210. WHERE
  3211. c_id = $course_id AND
  3212. lp_item_id='".$lp_item_id."' AND
  3213. lp_view_id ='".$lp_view_id."' AND
  3214. status='completed'";
  3215. $result = Database::query($sql);
  3216. $row_count = Database:: fetch_row($result);
  3217. $count_item_view = (int) $row_count[0];
  3218. $not_multiple_attempt = 0;
  3219. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3220. $not_multiple_attempt = 1;
  3221. }
  3222. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3223. }
  3224. break;
  3225. }
  3226. $tmp_array = explode('/', $file);
  3227. $document_name = $tmp_array[count($tmp_array) - 1];
  3228. if (strpos($document_name, '_DELETED_')) {
  3229. $file = 'blank.php?error=document_deleted';
  3230. }
  3231. break;
  3232. case 2 :
  3233. if ($this->debug > 2) {
  3234. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3235. }
  3236. if ($lp_item_type != 'dir') {
  3237. // Quite complex here:
  3238. // We want to make sure 'http://' (and similar) links can
  3239. // be loaded as is (withouth the Chamilo path in front) but
  3240. // some contents use this form: resource.htm?resource=http://blablabla
  3241. // which means we have to find a protocol at the path's start, otherwise
  3242. // it should not be considered as an external URL.
  3243. //if ($this->prerequisites_match($item_id)) {
  3244. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3245. if ($this->debug > 2) {
  3246. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3247. }
  3248. // Distant url, return as is.
  3249. $file = $lp_item_path;
  3250. } else {
  3251. if ($this->debug > 2) {
  3252. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3253. }
  3254. // Prevent getting untranslatable urls.
  3255. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3256. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3257. // Prepare the path.
  3258. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3259. // TODO: Fix this for urls with protocol header.
  3260. $file = str_replace('//', '/', $file);
  3261. $file = str_replace(':/', '://', $file);
  3262. if (substr($lp_path, -1) == '/') {
  3263. $lp_path = substr($lp_path, 0, -1);
  3264. }
  3265. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3266. // if file not found.
  3267. $decoded = html_entity_decode($lp_item_path);
  3268. list ($decoded) = explode('?', $decoded);
  3269. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3270. $file = self::rl_get_resource_link_for_learnpath(
  3271. $course_id,
  3272. $this->get_id(),
  3273. $item_id,
  3274. $this->get_view_id()
  3275. );
  3276. if (empty($file)) {
  3277. $file = 'blank.php?error=document_not_found';
  3278. } else {
  3279. $tmp_array = explode('/', $file);
  3280. $document_name = $tmp_array[count($tmp_array) - 1];
  3281. if (strpos($document_name, '_DELETED_')) {
  3282. $file = 'blank.php?error=document_deleted';
  3283. } else {
  3284. $file = 'blank.php?error=document_not_found';
  3285. }
  3286. }
  3287. } else {
  3288. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3289. }
  3290. }
  3291. }
  3292. // We want to use parameters if they were defined in the imsmanifest
  3293. if (strpos($file, 'blank.php') === false) {
  3294. $lp_item_params = ltrim($lp_item_params, '?');
  3295. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3296. }
  3297. } else {
  3298. $file = 'lp_content.php?type=dir';
  3299. }
  3300. break;
  3301. case 3 :
  3302. if ($this->debug > 2) {
  3303. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3304. }
  3305. // Formatting AICC HACP append URL.
  3306. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3307. if (!empty($lp_item_params)) {
  3308. $aicc_append .= $lp_item_params.'&';
  3309. }
  3310. if ($lp_item_type != 'dir') {
  3311. // Quite complex here:
  3312. // We want to make sure 'http://' (and similar) links can
  3313. // be loaded as is (withouth the Chamilo path in front) but
  3314. // some contents use this form: resource.htm?resource=http://blablabla
  3315. // which means we have to find a protocol at the path's start, otherwise
  3316. // it should not be considered as an external URL.
  3317. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3318. if ($this->debug > 2) {
  3319. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3320. }
  3321. // Distant url, return as is.
  3322. $file = $lp_item_path;
  3323. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3324. /*
  3325. if (stristr($file,'<servername>') !== false) {
  3326. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3327. }
  3328. */
  3329. if (stripos($file, '<servername>') !== false) {
  3330. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3331. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3332. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3333. }
  3334. //
  3335. $file .= $aicc_append;
  3336. } else {
  3337. if ($this->debug > 2) {
  3338. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3339. }
  3340. // Prevent getting untranslatable urls.
  3341. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3342. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3343. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3344. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3345. // TODO: Fix this for urls with protocol header.
  3346. $file = str_replace('//', '/', $file);
  3347. $file = str_replace(':/', '://', $file);
  3348. $file .= $aicc_append;
  3349. }
  3350. } else {
  3351. $file = 'lp_content.php?type=dir';
  3352. }
  3353. break;
  3354. case 4 :
  3355. break;
  3356. default:
  3357. break;
  3358. }
  3359. // Replace &amp; by & because &amp; will break URL with params
  3360. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3361. }
  3362. if ($this->debug > 2) {
  3363. error_log('New LP - In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3364. }
  3365. return $file;
  3366. }
  3367. /**
  3368. * Gets the latest usable view or generate a new one
  3369. * @param integer Optional attempt number. If none given, takes the highest from the lp_view table
  3370. * @return integer DB lp_view id
  3371. */
  3372. public function get_view($attempt_num = 0)
  3373. {
  3374. if ($this->debug > 0) {
  3375. error_log('New LP - In learnpath::get_view()', 0);
  3376. }
  3377. $search = '';
  3378. // Use $attempt_num to enable multi-views management (disabled so far).
  3379. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3380. $search = 'AND view_count = '.$attempt_num;
  3381. }
  3382. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3383. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3384. $course_id = api_get_course_int_id();
  3385. $sessionId = api_get_session_id();
  3386. $sql = "SELECT id, view_count FROM $lp_view_table
  3387. WHERE
  3388. c_id = ".$course_id." AND
  3389. lp_id = " . $this->get_id()." AND
  3390. user_id = " . $this->get_user_id()." AND
  3391. session_id = $sessionId
  3392. $search
  3393. ORDER BY view_count DESC";
  3394. $res = Database::query($sql);
  3395. if (Database::num_rows($res) > 0) {
  3396. $row = Database::fetch_array($res);
  3397. $this->lp_view_id = $row['id'];
  3398. } elseif (!api_is_invitee()) {
  3399. // There is no database record, create one.
  3400. $sql = "INSERT INTO $lp_view_table (c_id, lp_id,user_id, view_count, session_id) VALUES
  3401. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3402. Database::query($sql);
  3403. $id = Database::insert_id();
  3404. $this->lp_view_id = $id;
  3405. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3406. Database::query($sql);
  3407. }
  3408. return $this->lp_view_id;
  3409. }
  3410. /**
  3411. * Gets the current view id
  3412. * @return integer View ID (from lp_view)
  3413. */
  3414. public function get_view_id()
  3415. {
  3416. if ($this->debug > 0) {
  3417. error_log('New LP - In learnpath::get_view_id()', 0);
  3418. }
  3419. if (!empty ($this->lp_view_id)) {
  3420. return $this->lp_view_id;
  3421. } else {
  3422. return 0;
  3423. }
  3424. }
  3425. /**
  3426. * Gets the update queue
  3427. * @return array Array containing IDs of items to be updated by JavaScript
  3428. */
  3429. public function get_update_queue()
  3430. {
  3431. if ($this->debug > 0) {
  3432. error_log('New LP - In learnpath::get_update_queue()', 0);
  3433. }
  3434. return $this->update_queue;
  3435. }
  3436. /**
  3437. * Gets the user ID
  3438. * @return integer User ID
  3439. */
  3440. public function get_user_id()
  3441. {
  3442. if ($this->debug > 0) {
  3443. error_log('New LP - In learnpath::get_user_id()', 0);
  3444. }
  3445. if (!empty ($this->user_id)) {
  3446. return $this->user_id;
  3447. } else {
  3448. return false;
  3449. }
  3450. }
  3451. /**
  3452. * Checks if any of the items has an audio element attached
  3453. * @return bool True or false
  3454. */
  3455. public function has_audio()
  3456. {
  3457. if ($this->debug > 1) {
  3458. error_log('New LP - In learnpath::has_audio()', 0);
  3459. }
  3460. $has = false;
  3461. foreach ($this->items as $i => $item) {
  3462. if (!empty ($this->items[$i]->audio)) {
  3463. $has = true;
  3464. break;
  3465. }
  3466. }
  3467. return $has;
  3468. }
  3469. /**
  3470. * Logs a message into a file
  3471. * @param string Message to log
  3472. * @return boolean True on success, false on error or if msg empty
  3473. */
  3474. public function log($msg)
  3475. {
  3476. if ($this->debug > 0) {
  3477. error_log('New LP - In learnpath::log()', 0);
  3478. }
  3479. // TODO
  3480. $this->error .= $msg;
  3481. return true;
  3482. }
  3483. /**
  3484. * Moves an item up and down at its level
  3485. * @param integer Item to move up and down
  3486. * @param string Direction 'up' or 'down'
  3487. * @return integer New display order, or false on error
  3488. */
  3489. public function move_item($id, $direction)
  3490. {
  3491. $course_id = api_get_course_int_id();
  3492. if ($this->debug > 0) {
  3493. error_log('New LP - In learnpath::move_item('.$id.','.$direction.')', 0);
  3494. }
  3495. if (empty($id) || empty($direction)) {
  3496. return false;
  3497. }
  3498. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3499. $sql_sel = "SELECT *
  3500. FROM $tbl_lp_item
  3501. WHERE
  3502. c_id = $course_id AND
  3503. id = $id
  3504. ";
  3505. $res_sel = Database::query($sql_sel);
  3506. // Check if elem exists.
  3507. if (Database::num_rows($res_sel) < 1) {
  3508. return false;
  3509. }
  3510. // Gather data.
  3511. $row = Database::fetch_array($res_sel);
  3512. $previous = $row['previous_item_id'];
  3513. $next = $row['next_item_id'];
  3514. $display = $row['display_order'];
  3515. $parent = $row['parent_item_id'];
  3516. $lp = $row['lp_id'];
  3517. // Update the item (switch with previous/next one).
  3518. switch ($direction) {
  3519. case 'up':
  3520. if ($this->debug > 2) {
  3521. error_log('Movement up detected', 0);
  3522. }
  3523. if ($display > 1) {
  3524. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3525. WHERE c_id = ".$course_id." AND id = $previous";
  3526. if ($this->debug > 2) {
  3527. error_log('Selecting previous: '.$sql_sel2, 0);
  3528. }
  3529. $res_sel2 = Database::query($sql_sel2);
  3530. if (Database::num_rows($res_sel2) < 1) {
  3531. $previous_previous = 0;
  3532. }
  3533. // Gather data.
  3534. $row2 = Database::fetch_array($res_sel2);
  3535. $previous_previous = $row2['previous_item_id'];
  3536. // Update previous_previous item (switch "next" with current).
  3537. if ($previous_previous != 0) {
  3538. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3539. next_item_id = $id
  3540. WHERE c_id = ".$course_id." AND id = $previous_previous";
  3541. if ($this->debug > 2) {
  3542. error_log($sql_upd2, 0);
  3543. }
  3544. Database::query($sql_upd2);
  3545. }
  3546. // Update previous item (switch with current).
  3547. if ($previous != 0) {
  3548. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3549. next_item_id = $next,
  3550. previous_item_id = $id,
  3551. display_order = display_order +1
  3552. WHERE c_id = ".$course_id." AND id = $previous";
  3553. if ($this->debug > 2) {
  3554. error_log($sql_upd2, 0);
  3555. }
  3556. Database::query($sql_upd2);
  3557. }
  3558. // Update current item (switch with previous).
  3559. if ($id != 0) {
  3560. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3561. next_item_id = $previous,
  3562. previous_item_id = $previous_previous,
  3563. display_order = display_order-1
  3564. WHERE c_id = ".$course_id." AND id = $id";
  3565. if ($this->debug > 2) {
  3566. error_log($sql_upd2, 0);
  3567. }
  3568. Database::query($sql_upd2);
  3569. }
  3570. // Update next item (new previous item).
  3571. if ($next != 0) {
  3572. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3573. WHERE c_id = ".$course_id." AND id = $next";
  3574. if ($this->debug > 2) {
  3575. error_log($sql_upd2, 0);
  3576. }
  3577. Database::query($sql_upd2);
  3578. }
  3579. $display = $display - 1;
  3580. }
  3581. break;
  3582. case 'down':
  3583. if ($this->debug > 2) {
  3584. error_log('Movement down detected', 0);
  3585. }
  3586. if ($next != 0) {
  3587. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3588. WHERE c_id = ".$course_id." AND id = $next";
  3589. if ($this->debug > 2) {
  3590. error_log('Selecting next: '.$sql_sel2, 0);
  3591. }
  3592. $res_sel2 = Database::query($sql_sel2);
  3593. if (Database::num_rows($res_sel2) < 1) {
  3594. $next_next = 0;
  3595. }
  3596. // Gather data.
  3597. $row2 = Database::fetch_array($res_sel2);
  3598. $next_next = $row2['next_item_id'];
  3599. // Update previous item (switch with current).
  3600. if ($previous != 0) {
  3601. $sql_upd2 = "UPDATE $tbl_lp_item
  3602. SET next_item_id = $next
  3603. WHERE c_id = ".$course_id." AND id = $previous";
  3604. Database::query($sql_upd2);
  3605. }
  3606. // Update current item (switch with previous).
  3607. if ($id != 0) {
  3608. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3609. previous_item_id = $next,
  3610. next_item_id = $next_next,
  3611. display_order = display_order + 1
  3612. WHERE c_id = ".$course_id." AND id = $id";
  3613. Database::query($sql_upd2);
  3614. }
  3615. // Update next item (new previous item).
  3616. if ($next != 0) {
  3617. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3618. previous_item_id = $previous,
  3619. next_item_id = $id,
  3620. display_order = display_order-1
  3621. WHERE c_id = ".$course_id." AND id = $next";
  3622. Database::query($sql_upd2);
  3623. }
  3624. // Update next_next item (switch "previous" with current).
  3625. if ($next_next != 0) {
  3626. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3627. previous_item_id = $id
  3628. WHERE c_id = ".$course_id." AND id = $next_next";
  3629. Database::query($sql_upd2);
  3630. }
  3631. $display = $display + 1;
  3632. }
  3633. break;
  3634. default:
  3635. return false;
  3636. }
  3637. return $display;
  3638. }
  3639. /**
  3640. * Move a LP up (display_order)
  3641. * @param int $lp_id Learnpath ID
  3642. * @param int $categoryId
  3643. * @return bool
  3644. */
  3645. public static function move_up($lp_id, $categoryId = 0)
  3646. {
  3647. $courseId = api_get_course_int_id();
  3648. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3649. $categoryCondition = '';
  3650. if (!empty($categoryId)) {
  3651. $categoryId = (int) $categoryId;
  3652. $categoryCondition = " AND category_id = $categoryId";
  3653. }
  3654. $sql = "SELECT * FROM $lp_table
  3655. WHERE c_id = $courseId
  3656. $categoryCondition
  3657. ORDER BY display_order";
  3658. $res = Database::query($sql);
  3659. if ($res === false) {
  3660. return false;
  3661. }
  3662. $lps = [];
  3663. $lp_order = [];
  3664. $num = Database::num_rows($res);
  3665. // First check the order is correct, globally (might be wrong because
  3666. // of versions < 1.8.4)
  3667. if ($num > 0) {
  3668. $i = 1;
  3669. while ($row = Database::fetch_array($res)) {
  3670. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3671. $sql = "UPDATE $lp_table SET display_order = $i
  3672. WHERE c_id = $courseId AND id = ".$row['id'];
  3673. Database::query($sql);
  3674. }
  3675. $row['display_order'] = $i;
  3676. $lps[$row['id']] = $row;
  3677. $lp_order[$i] = $row['id'];
  3678. $i++;
  3679. }
  3680. }
  3681. if ($num > 1) { // If there's only one element, no need to sort.
  3682. $order = $lps[$lp_id]['display_order'];
  3683. if ($order > 1) { // If it's the first element, no need to move up.
  3684. $sql = "UPDATE $lp_table SET display_order = $order
  3685. WHERE c_id = $courseId AND id = ".$lp_order[$order - 1];
  3686. Database::query($sql);
  3687. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3688. WHERE c_id = $courseId AND id = ".$lp_id;
  3689. Database::query($sql);
  3690. }
  3691. }
  3692. return true;
  3693. }
  3694. /**
  3695. * Move a learnpath down (display_order)
  3696. * @param int $lp_id Learnpath ID
  3697. * @param int $categoryId
  3698. * @return bool
  3699. */
  3700. public static function move_down($lp_id, $categoryId = 0)
  3701. {
  3702. $courseId = api_get_course_int_id();
  3703. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3704. $categoryCondition = '';
  3705. if (!empty($categoryId)) {
  3706. $categoryId = (int) $categoryId;
  3707. $categoryCondition = " AND category_id = $categoryId";
  3708. }
  3709. $sql = "SELECT * FROM $lp_table
  3710. WHERE c_id = $courseId
  3711. $categoryCondition
  3712. ORDER BY display_order";
  3713. $res = Database::query($sql);
  3714. if ($res === false) {
  3715. return false;
  3716. }
  3717. $lps = [];
  3718. $lp_order = [];
  3719. $num = Database::num_rows($res);
  3720. $max = 0;
  3721. // First check the order is correct, globally (might be wrong because
  3722. // of versions < 1.8.4).
  3723. if ($num > 0) {
  3724. $i = 1;
  3725. while ($row = Database::fetch_array($res)) {
  3726. $max = $i;
  3727. if ($row['display_order'] != $i) {
  3728. // If we find a gap in the order, we need to fix it.
  3729. $sql_u = "UPDATE $lp_table SET display_order = $i
  3730. WHERE c_id = ".$courseId." AND id = ".$row['id'];
  3731. Database::query($sql_u);
  3732. }
  3733. $row['display_order'] = $i;
  3734. $lps[$row['id']] = $row;
  3735. $lp_order[$i] = $row['id'];
  3736. $i++;
  3737. }
  3738. }
  3739. if ($num > 1) { // If there's only one element, no need to sort.
  3740. $order = $lps[$lp_id]['display_order'];
  3741. if ($order < $max) { // If it's the first element, no need to move up.
  3742. $sql_u1 = "UPDATE $lp_table SET display_order = $order
  3743. WHERE c_id = ".$courseId." AND id = ".$lp_order[$order + 1];
  3744. Database::query($sql_u1);
  3745. $sql_u2 = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3746. WHERE c_id = ".$courseId." AND id = ".$lp_id;
  3747. Database::query($sql_u2);
  3748. }
  3749. }
  3750. return true;
  3751. }
  3752. /**
  3753. * Updates learnpath attributes to point to the next element
  3754. * The last part is similar to set_current_item but processing the other way around
  3755. */
  3756. public function next()
  3757. {
  3758. if ($this->debug > 0) {
  3759. error_log('New LP - In learnpath::next()', 0);
  3760. }
  3761. $this->last = $this->get_current_item_id();
  3762. $this->items[$this->last]->save(
  3763. false,
  3764. $this->prerequisites_match($this->last)
  3765. );
  3766. $this->autocomplete_parents($this->last);
  3767. $new_index = $this->get_next_index();
  3768. if ($this->debug > 2) {
  3769. error_log('New LP - New index: '.$new_index, 0);
  3770. }
  3771. $this->index = $new_index;
  3772. if ($this->debug > 2) {
  3773. error_log('New LP - Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3774. }
  3775. $this->current = $this->ordered_items[$new_index];
  3776. if ($this->debug > 2) {
  3777. error_log('New LP - new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3778. }
  3779. }
  3780. /**
  3781. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3782. * class, this might be redefined to allow several behaviours depending on the document type.
  3783. * @param integer Resource ID
  3784. * @return boolean True on success, false otherwise
  3785. */
  3786. public function open($id)
  3787. {
  3788. if ($this->debug > 0) {
  3789. error_log('New LP - In learnpath::open()', 0);
  3790. }
  3791. // TODO:
  3792. // set the current resource attribute to this resource
  3793. // switch on element type (redefine in child class?)
  3794. // set status for this item to "opened"
  3795. // start timer
  3796. // initialise score
  3797. $this->index = 0; //or = the last item seen (see $this->last)
  3798. }
  3799. /**
  3800. * Check that all prerequisites are fulfilled. Returns true and an
  3801. * empty string on success, returns false
  3802. * and the prerequisite string on error.
  3803. * This function is based on the rules for aicc_script language as
  3804. * described in the SCORM 1.2 CAM documentation page 108.
  3805. * @param integer $itemId Optional item ID. If none given, uses the current open item.
  3806. * @return boolean True if prerequisites are matched, false otherwise -
  3807. * Empty string if true returned, prerequisites string otherwise.
  3808. */
  3809. public function prerequisites_match($itemId = null)
  3810. {
  3811. $debug = $this->debug;
  3812. if ($debug > 0) {
  3813. error_log('In learnpath::prerequisites_match()', 0);
  3814. }
  3815. if (empty($itemId)) {
  3816. $itemId = $this->current;
  3817. }
  3818. $currentItem = $this->getItem($itemId);
  3819. if ($currentItem) {
  3820. if ($this->type == 2) {
  3821. // Getting prereq from scorm
  3822. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3823. } else {
  3824. $prereq_string = $currentItem->get_prereq_string();
  3825. }
  3826. if (empty($prereq_string)) {
  3827. if ($debug > 0) {
  3828. error_log('Found prereq_string is empty return true');
  3829. }
  3830. return true;
  3831. }
  3832. // Clean spaces.
  3833. $prereq_string = str_replace(' ', '', $prereq_string);
  3834. if ($debug > 0) {
  3835. error_log('Found prereq_string: '.$prereq_string, 0);
  3836. }
  3837. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3838. $result = $currentItem->parse_prereq(
  3839. $prereq_string,
  3840. $this->items,
  3841. $this->refs_list,
  3842. $this->get_user_id()
  3843. );
  3844. if ($result === false) {
  3845. $this->set_error_msg($currentItem->prereq_alert);
  3846. }
  3847. } else {
  3848. $result = true;
  3849. if ($debug > 1) {
  3850. error_log('$this->items['.$itemId.'] was not an object', 0);
  3851. }
  3852. }
  3853. if ($debug > 1) {
  3854. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3855. }
  3856. return $result;
  3857. }
  3858. /**
  3859. * Updates learnpath attributes to point to the previous element
  3860. * The last part is similar to set_current_item but processing the other way around
  3861. */
  3862. public function previous()
  3863. {
  3864. if ($this->debug > 0) {
  3865. error_log('New LP - In learnpath::previous()', 0);
  3866. }
  3867. $this->last = $this->get_current_item_id();
  3868. $this->items[$this->last]->save(
  3869. false,
  3870. $this->prerequisites_match($this->last)
  3871. );
  3872. $this->autocomplete_parents($this->last);
  3873. $new_index = $this->get_previous_index();
  3874. $this->index = $new_index;
  3875. $this->current = $this->ordered_items[$new_index];
  3876. }
  3877. /**
  3878. * Publishes a learnpath. This basically means show or hide the learnpath
  3879. * to normal users.
  3880. * Can be used as abstract
  3881. * @param integer Learnpath ID
  3882. * @param string New visibility
  3883. * @return bool
  3884. */
  3885. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3886. {
  3887. $action = 'visible';
  3888. if ($set_visibility != 1) {
  3889. $action = 'invisible';
  3890. self::toggle_publish($lp_id, 'i');
  3891. }
  3892. return api_item_property_update(
  3893. api_get_course_info(),
  3894. TOOL_LEARNPATH,
  3895. $lp_id,
  3896. $action,
  3897. api_get_user_id()
  3898. );
  3899. }
  3900. /**
  3901. * Publishes a learnpath category.
  3902. * This basically means show or hide the learnpath category to normal users.
  3903. * @param int $id
  3904. * @param int $visibility
  3905. * @return bool
  3906. */
  3907. public static function toggleCategoryVisibility($id, $visibility = 1)
  3908. {
  3909. $action = 'visible';
  3910. if ($visibility != 1) {
  3911. $action = 'invisible';
  3912. $list = new LearnpathList(
  3913. api_get_user_id(),
  3914. null,
  3915. null,
  3916. null,
  3917. false,
  3918. $id
  3919. );
  3920. $lpList = $list->get_flat_list();
  3921. foreach ($lpList as $lp) {
  3922. learnpath::toggle_visibility($lp['iid'], 0);
  3923. }
  3924. learnpath::toggleCategoryPublish($id, 0);
  3925. }
  3926. return api_item_property_update(
  3927. api_get_course_info(),
  3928. TOOL_LEARNPATH_CATEGORY,
  3929. $id,
  3930. $action,
  3931. api_get_user_id()
  3932. );
  3933. }
  3934. /**
  3935. * Publishes a learnpath. This basically means show or hide the learnpath
  3936. * on the course homepage
  3937. * Can be used as abstract
  3938. * @param integer $lp_id Learnpath id
  3939. * @param string $set_visibility New visibility (v/i - visible/invisible)
  3940. * @return bool
  3941. */
  3942. public static function toggle_publish($lp_id, $set_visibility = 'v')
  3943. {
  3944. $course_id = api_get_course_int_id();
  3945. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  3946. $lp_id = intval($lp_id);
  3947. $sql = "SELECT * FROM $tbl_lp
  3948. WHERE c_id = $course_id AND id = $lp_id";
  3949. $result = Database::query($sql);
  3950. if (Database::num_rows($result)) {
  3951. $row = Database::fetch_array($result);
  3952. $name = Database::escape_string($row['name']);
  3953. if ($set_visibility == 'i') {
  3954. $v = 0;
  3955. }
  3956. if ($set_visibility == 'v') {
  3957. $v = 1;
  3958. }
  3959. $session_id = api_get_session_id();
  3960. $session_condition = api_get_session_condition($session_id);
  3961. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  3962. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  3963. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  3964. $sql = "SELECT * FROM $tbl_tool
  3965. WHERE
  3966. c_id = $course_id AND
  3967. (link = '$link' OR link = '$oldLink') AND
  3968. image = 'scormbuilder.gif' AND
  3969. (
  3970. link LIKE '$link%' OR
  3971. link LIKE '$oldLink%'
  3972. )
  3973. $session_condition
  3974. ";
  3975. $result = Database::query($sql);
  3976. $num = Database::num_rows($result);
  3977. if ($set_visibility == 'i' && $num > 0) {
  3978. $sql = "DELETE FROM $tbl_tool
  3979. WHERE
  3980. c_id = $course_id AND
  3981. (link = '$link' OR link = '$oldLink') AND
  3982. image='scormbuilder.gif'
  3983. $session_condition";
  3984. Database::query($sql);
  3985. } elseif ($set_visibility == 'v' && $num == 0) {
  3986. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  3987. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  3988. Database::query($sql);
  3989. $insertId = Database::insert_id();
  3990. if ($insertId) {
  3991. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  3992. Database::query($sql);
  3993. }
  3994. } elseif ($set_visibility == 'v' && $num > 0) {
  3995. $sql = "UPDATE $tbl_tool SET
  3996. c_id = $course_id,
  3997. name = '$name',
  3998. link = '$link',
  3999. image = 'scormbuilder.gif',
  4000. visibility = '$v',
  4001. admin = '0',
  4002. address = 'pastillegris.gif',
  4003. added_tool = 0,
  4004. session_id = $session_id
  4005. WHERE
  4006. c_id = ".$course_id." AND
  4007. (link = '$link' OR link = '$oldLink') AND
  4008. image='scormbuilder.gif'
  4009. $session_condition
  4010. ";
  4011. Database::query($sql);
  4012. } else {
  4013. // Parameter and database incompatible, do nothing, exit.
  4014. return false;
  4015. }
  4016. } else {
  4017. return false;
  4018. }
  4019. }
  4020. /**
  4021. * Generate the link for a learnpath category as course tool
  4022. * @param int $categoryId
  4023. * @return string
  4024. */
  4025. private static function getCategoryLinkForTool($categoryId)
  4026. {
  4027. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  4028. .http_build_query(
  4029. [
  4030. 'action' => 'view_category',
  4031. 'id' => $categoryId
  4032. ]
  4033. );
  4034. return $link;
  4035. }
  4036. /**
  4037. * Publishes a learnpath.
  4038. * Show or hide the learnpath category on the course homepage
  4039. * @param int $id
  4040. * @param int $setVisibility
  4041. * @return bool
  4042. */
  4043. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4044. {
  4045. $courseId = api_get_course_int_id();
  4046. $sessionId = api_get_session_id();
  4047. $sessionCondition = api_get_session_condition(
  4048. $sessionId,
  4049. true,
  4050. false,
  4051. 't.sessionId'
  4052. );
  4053. $em = Database::getManager();
  4054. /** @var CLpCategory $category */
  4055. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4056. if (!$category) {
  4057. return false;
  4058. }
  4059. $link = self::getCategoryLinkForTool($id);
  4060. /** @var CTool $tool */
  4061. $tool = $em
  4062. ->createQuery("
  4063. SELECT t FROM ChamiloCourseBundle:CTool t
  4064. WHERE
  4065. t.cId = :course AND
  4066. t.link = :link1 AND
  4067. t.image = 'lp_category.gif' AND
  4068. t.link LIKE :link2
  4069. $sessionCondition
  4070. ")
  4071. ->setParameters([
  4072. 'course' => (int) $courseId,
  4073. 'link1' => $link,
  4074. 'link2' => "$link%"
  4075. ])
  4076. ->getOneOrNullResult();
  4077. if ($setVisibility == 0 && $tool) {
  4078. $em->remove($tool);
  4079. $em->flush();
  4080. return true;
  4081. }
  4082. if ($setVisibility == 1 && !$tool) {
  4083. $tool = new CTool();
  4084. $tool
  4085. ->setCategory('authoring')
  4086. ->setCId($courseId)
  4087. ->setName(strip_tags($category->getName()))
  4088. ->setLink($link)
  4089. ->setImage('lp_category.gif')
  4090. ->setVisibility(1)
  4091. ->setAdmin(0)
  4092. ->setAddress('pastillegris.gif')
  4093. ->setAddedTool(0)
  4094. ->setSessionId($sessionId)
  4095. ->setTarget('_self');
  4096. $em->persist($tool);
  4097. $em->flush();
  4098. $tool->setId($tool->getIid());
  4099. $em->persist($tool);
  4100. $em->flush();
  4101. return true;
  4102. }
  4103. if ($setVisibility == 1 && $tool) {
  4104. $tool
  4105. ->setName(strip_tags($category->getName()))
  4106. ->setVisibility(1);
  4107. $em->persist($tool);
  4108. $em->flush();
  4109. return true;
  4110. }
  4111. return false;
  4112. }
  4113. /**
  4114. * Check if the learnpath category is visible for a user
  4115. * @param CLpCategory $category
  4116. * @param User $user
  4117. * @return bool
  4118. */
  4119. public static function categoryIsVisibleForStudent(
  4120. CLpCategory $category,
  4121. User $user
  4122. ) {
  4123. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4124. if ($isAllowedToEdit) {
  4125. return true;
  4126. }
  4127. $users = $category->getUsers();
  4128. if (empty($users) || !$users->count()) {
  4129. return true;
  4130. }
  4131. if ($category->hasUserAdded($user)) {
  4132. return true;
  4133. }
  4134. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4135. if (!empty($groups)) {
  4136. $em = Database::getManager();
  4137. /** @var ItemPropertyRepository $itemRepo */
  4138. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4139. /** @var CourseRepository $courseRepo */
  4140. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4141. $sessionId = api_get_session_id();
  4142. $session = null;
  4143. if (!empty($sessionId)) {
  4144. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4145. }
  4146. $course = $courseRepo->find(api_get_course_int_id());
  4147. // Subscribed groups to a LP
  4148. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4149. 'learnpath_category',
  4150. $category->getId(),
  4151. $course,
  4152. $session
  4153. );
  4154. if (!empty($subscribedGroupsInLp)) {
  4155. $groups = array_column($groups, 'iid');
  4156. /** @var CItemProperty $item */
  4157. foreach ($subscribedGroupsInLp as $item) {
  4158. if ($item->getGroup() &&
  4159. in_array($item->getGroup()->getId(), $groups)
  4160. ) {
  4161. return true;
  4162. }
  4163. }
  4164. }
  4165. }
  4166. return false;
  4167. }
  4168. /**
  4169. * Check if a learnpath category is published as course tool
  4170. * @param CLpCategory $category
  4171. * @param int $courseId
  4172. * @return bool
  4173. */
  4174. public static function categoryIsPublished(
  4175. CLpCategory $category,
  4176. $courseId
  4177. ) {
  4178. $link = self::getCategoryLinkForTool($category->getId());
  4179. $em = Database::getManager();
  4180. $tools = $em
  4181. ->createQuery("
  4182. SELECT t FROM ChamiloCourseBundle:CTool t
  4183. WHERE t.cId = :course AND
  4184. t.name = :name AND
  4185. t.image = 'lp_category.gif' AND
  4186. t.link LIKE :link
  4187. ")
  4188. ->setParameters([
  4189. 'course' => $courseId,
  4190. 'name' => strip_tags($category->getName()),
  4191. 'link' => "$link%"
  4192. ])
  4193. ->getResult();
  4194. /** @var CTool $tool */
  4195. $tool = current($tools);
  4196. return $tool ? $tool->getVisibility() : false;
  4197. }
  4198. /**
  4199. * Restart the whole learnpath. Return the URL of the first element.
  4200. * Make sure the results are saved with anoter method. This method should probably be
  4201. * redefined in children classes.
  4202. * To use a similar method statically, use the create_new_attempt() method
  4203. * @return string URL to load in the viewer
  4204. */
  4205. public function restart()
  4206. {
  4207. if ($this->debug > 0) {
  4208. error_log('New LP - In learnpath::restart()', 0);
  4209. }
  4210. // TODO
  4211. // Call autosave method to save the current progress.
  4212. //$this->index = 0;
  4213. if (api_is_invitee()) {
  4214. return false;
  4215. }
  4216. $session_id = api_get_session_id();
  4217. $course_id = api_get_course_int_id();
  4218. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4219. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4220. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4221. if ($this->debug > 2) {
  4222. error_log('New LP - Inserting new lp_view for restart: '.$sql, 0);
  4223. }
  4224. Database::query($sql);
  4225. $view_id = Database::insert_id();
  4226. if ($view_id) {
  4227. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4228. Database::query($sql);
  4229. $this->lp_view_id = $view_id;
  4230. $this->attempt = $this->attempt + 1;
  4231. } else {
  4232. $this->error = 'Could not insert into item_view table...';
  4233. return false;
  4234. }
  4235. $this->autocomplete_parents($this->current);
  4236. foreach ($this->items as $index => $dummy) {
  4237. $this->items[$index]->restart();
  4238. $this->items[$index]->set_lp_view($this->lp_view_id);
  4239. }
  4240. $this->first();
  4241. return true;
  4242. }
  4243. /**
  4244. * Saves the current item
  4245. * @return boolean
  4246. */
  4247. public function save_current()
  4248. {
  4249. if ($this->debug > 0) {
  4250. error_log('learnpath::save_current()', 0);
  4251. }
  4252. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4253. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4254. if ($this->debug > 2) {
  4255. error_log('New LP - save_current() saving item '.$this->current, 0);
  4256. }
  4257. if ($this->debug > 2) {
  4258. error_log(''.print_r($this->items, true), 0);
  4259. }
  4260. if (isset($this->items[$this->current]) &&
  4261. is_object($this->items[$this->current])
  4262. ) {
  4263. $res = $this->items[$this->current]->save(
  4264. false,
  4265. $this->prerequisites_match($this->current)
  4266. );
  4267. $this->autocomplete_parents($this->current);
  4268. $status = $this->items[$this->current]->get_status();
  4269. $this->update_queue[$this->current] = $status;
  4270. return $res;
  4271. }
  4272. return false;
  4273. }
  4274. /**
  4275. * Saves the given item
  4276. * @param integer $item_id Optional (will take from $_REQUEST if null)
  4277. * @param boolean $from_outside Save from url params (true) or from current attributes (false). Optional. Defaults to true
  4278. * @return boolean
  4279. */
  4280. public function save_item($item_id = null, $from_outside = true)
  4281. {
  4282. $debug = $this->debug;
  4283. if ($debug) {
  4284. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4285. }
  4286. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4287. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4288. if (empty($item_id)) {
  4289. $item_id = intval($_REQUEST['id']);
  4290. }
  4291. if (empty($item_id)) {
  4292. $item_id = $this->get_current_item_id();
  4293. }
  4294. if (isset($this->items[$item_id]) &&
  4295. is_object($this->items[$item_id])
  4296. ) {
  4297. if ($debug) {
  4298. error_log('Object exists');
  4299. }
  4300. // Saving the item.
  4301. $res = $this->items[$item_id]->save(
  4302. $from_outside,
  4303. $this->prerequisites_match($item_id)
  4304. );
  4305. if ($debug) {
  4306. error_log('update_queue before:');
  4307. error_log(print_r($this->update_queue, 1));
  4308. }
  4309. $this->autocomplete_parents($item_id);
  4310. $status = $this->items[$item_id]->get_status();
  4311. $this->update_queue[$item_id] = $status;
  4312. if ($debug) {
  4313. error_log('get_status(): '.$status);
  4314. error_log('update_queue after:');
  4315. error_log(print_r($this->update_queue, 1));
  4316. }
  4317. return $res;
  4318. }
  4319. return false;
  4320. }
  4321. /**
  4322. * Saves the last item seen's ID only in case
  4323. */
  4324. public function save_last()
  4325. {
  4326. $course_id = api_get_course_int_id();
  4327. if ($this->debug > 0) {
  4328. error_log('New LP - In learnpath::save_last()', 0);
  4329. }
  4330. $session_condition = api_get_session_condition(
  4331. api_get_session_id(),
  4332. true,
  4333. false
  4334. );
  4335. $table = Database::get_course_table(TABLE_LP_VIEW);
  4336. if (isset($this->current) && !api_is_invitee()) {
  4337. if ($this->debug > 2) {
  4338. error_log('New LP - Saving current item ('.$this->current.') for later review', 0);
  4339. }
  4340. $sql = "UPDATE $table SET
  4341. last_item = ".intval($this->get_current_item_id())."
  4342. WHERE
  4343. c_id = $course_id AND
  4344. lp_id = ".$this->get_id()." AND
  4345. user_id = " . $this->get_user_id()." ".$session_condition;
  4346. if ($this->debug > 2) {
  4347. error_log('New LP - Saving last item seen : '.$sql, 0);
  4348. }
  4349. Database::query($sql);
  4350. }
  4351. if (!api_is_invitee()) {
  4352. // Save progress.
  4353. list($progress,) = $this->get_progress_bar_text('%');
  4354. if ($progress >= 0 && $progress <= 100) {
  4355. $progress = (int) $progress;
  4356. $sql = "UPDATE $table SET
  4357. progress = $progress
  4358. WHERE
  4359. c_id = ".$course_id." AND
  4360. lp_id = " . $this->get_id()." AND
  4361. user_id = " . $this->get_user_id()." ".$session_condition;
  4362. // Ignore errors as some tables might not have the progress field just yet.
  4363. Database::query($sql);
  4364. $this->progress_db = $progress;
  4365. }
  4366. }
  4367. }
  4368. /**
  4369. * Sets the current item ID (checks if valid and authorized first)
  4370. * @param integer $item_id New item ID. If not given or not authorized, defaults to current
  4371. */
  4372. public function set_current_item($item_id = null)
  4373. {
  4374. if ($this->debug > 0) {
  4375. error_log('New LP - In learnpath::set_current_item('.$item_id.')', 0);
  4376. }
  4377. if (empty ($item_id)) {
  4378. if ($this->debug > 2) {
  4379. error_log('New LP - No new current item given, ignore...', 0);
  4380. }
  4381. // Do nothing.
  4382. } else {
  4383. if ($this->debug > 2) {
  4384. error_log('New LP - New current item given is '.$item_id.'...', 0);
  4385. }
  4386. if (is_numeric($item_id)) {
  4387. $item_id = intval($item_id);
  4388. // TODO: Check in database here.
  4389. $this->last = $this->current;
  4390. $this->current = $item_id;
  4391. // TODO: Update $this->index as well.
  4392. foreach ($this->ordered_items as $index => $item) {
  4393. if ($item == $this->current) {
  4394. $this->index = $index;
  4395. break;
  4396. }
  4397. }
  4398. if ($this->debug > 2) {
  4399. error_log('New LP - set_current_item('.$item_id.') done. Index is now : '.$this->index, 0);
  4400. }
  4401. } else {
  4402. error_log('New LP - set_current_item('.$item_id.') failed. Not a numeric value: ', 0);
  4403. }
  4404. }
  4405. }
  4406. /**
  4407. * Sets the encoding
  4408. * @param string New encoding
  4409. * @return bool
  4410. * TODO (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4411. */
  4412. public function set_encoding($enc = 'UTF-8')
  4413. {
  4414. if ($this->debug > 0) {
  4415. error_log('New LP - In learnpath::set_encoding()', 0);
  4416. }
  4417. $course_id = api_get_course_int_id();
  4418. $enc = api_refine_encoding_id($enc);
  4419. if (empty($enc)) {
  4420. $enc = api_get_system_encoding();
  4421. }
  4422. if (api_is_encoding_supported($enc)) {
  4423. $lp = $this->get_id();
  4424. if ($lp != 0) {
  4425. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4426. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4427. WHERE c_id = ".$course_id." AND id = ".$lp;
  4428. $res = Database::query($sql);
  4429. return $res;
  4430. }
  4431. }
  4432. return false;
  4433. }
  4434. /**
  4435. * Sets the JS lib setting in the database directly.
  4436. * This is the JavaScript library file this lp needs to load on startup
  4437. * @param string Proximity setting
  4438. * @return boolean True on update success. False otherwise.
  4439. */
  4440. public function set_jslib($lib = '')
  4441. {
  4442. if ($this->debug > 0) {
  4443. error_log('New LP - In learnpath::set_jslib()', 0);
  4444. }
  4445. $lp = $this->get_id();
  4446. $course_id = api_get_course_int_id();
  4447. if ($lp != 0) {
  4448. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4449. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4450. WHERE c_id = ".$course_id." AND id = ".$lp;
  4451. $res = Database::query($sql);
  4452. return $res;
  4453. } else {
  4454. return false;
  4455. }
  4456. }
  4457. /**
  4458. * Sets the name of the LP maker (publisher) (and save)
  4459. * @param string Optional string giving the new content_maker of this learnpath
  4460. * @return boolean True
  4461. */
  4462. public function set_maker($name = '')
  4463. {
  4464. if ($this->debug > 0) {
  4465. error_log('New LP - In learnpath::set_maker()', 0);
  4466. }
  4467. if (empty ($name))
  4468. return false;
  4469. $this->maker = $name;
  4470. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4471. $course_id = api_get_course_int_id();
  4472. $lp_id = $this->get_id();
  4473. $sql = "UPDATE $lp_table SET
  4474. content_maker = '".Database::escape_string($this->maker)."'
  4475. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4476. if ($this->debug > 2) {
  4477. error_log('New LP - lp updated with new content_maker : '.$this->maker, 0);
  4478. }
  4479. Database::query($sql);
  4480. return true;
  4481. }
  4482. /**
  4483. * Sets the name of the current learnpath (and save)
  4484. * @param string $name Optional string giving the new name of this learnpath
  4485. * @return boolean True/False
  4486. */
  4487. public function set_name($name = null)
  4488. {
  4489. if ($this->debug > 0) {
  4490. error_log('New LP - In learnpath::set_name()', 0);
  4491. }
  4492. if (empty($name)) {
  4493. return false;
  4494. }
  4495. $this->name = Database::escape_string($name);
  4496. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4497. $lp_id = $this->get_id();
  4498. $course_id = $this->course_info['real_id'];
  4499. $sql = "UPDATE $lp_table SET
  4500. name = '".Database::escape_string($this->name)."'
  4501. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4502. if ($this->debug > 2) {
  4503. error_log('New LP - lp updated with new name : '.$this->name, 0);
  4504. }
  4505. $result = Database::query($sql);
  4506. // If the lp is visible on the homepage, change his name there.
  4507. if (Database::affected_rows($result)) {
  4508. $session_id = api_get_session_id();
  4509. $session_condition = api_get_session_condition($session_id);
  4510. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4511. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4512. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4513. WHERE
  4514. c_id = $course_id AND
  4515. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4516. Database::query($sql);
  4517. return true;
  4518. } else {
  4519. return false;
  4520. }
  4521. }
  4522. /**
  4523. * Set index specified prefix terms for all items in this path
  4524. * @param string Comma-separated list of terms
  4525. * @param char Xapian term prefix
  4526. * @return boolean False on error, true otherwise
  4527. */
  4528. public function set_terms_by_prefix($terms_string, $prefix)
  4529. {
  4530. $course_id = api_get_course_int_id();
  4531. if (api_get_setting('search_enabled') !== 'true')
  4532. return false;
  4533. if (!extension_loaded('xapian')) {
  4534. return false;
  4535. }
  4536. $terms_string = trim($terms_string);
  4537. $terms = explode(',', $terms_string);
  4538. array_walk($terms, 'trim_value');
  4539. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4540. // Don't do anything if no change, verify only at DB, not the search engine.
  4541. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0))
  4542. return false;
  4543. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4544. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  4545. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4546. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  4547. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4548. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4549. $lp_id = intval($_POST['lp_id']);
  4550. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4551. $result = Database::query($sql);
  4552. $di = new ChamiloIndexer();
  4553. while ($lp_item = Database::fetch_array($result)) {
  4554. // Get search_did.
  4555. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4556. $sql = 'SELECT * FROM %s
  4557. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4558. LIMIT 1';
  4559. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4560. //echo $sql; echo '<br>';
  4561. $res = Database::query($sql);
  4562. if (Database::num_rows($res) > 0) {
  4563. $se_ref = Database::fetch_array($res);
  4564. // Compare terms.
  4565. $doc = $di->get_document($se_ref['search_did']);
  4566. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4567. $xterms = array();
  4568. foreach ($xapian_terms as $xapian_term) {
  4569. $xterms[] = substr($xapian_term['name'], 1);
  4570. }
  4571. $dterms = $terms;
  4572. $missing_terms = array_diff($dterms, $xterms);
  4573. $deprecated_terms = array_diff($xterms, $dterms);
  4574. // Save it to search engine.
  4575. foreach ($missing_terms as $term) {
  4576. $doc->add_term($prefix.$term, 1);
  4577. }
  4578. foreach ($deprecated_terms as $term) {
  4579. $doc->remove_term($prefix.$term);
  4580. }
  4581. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4582. $di->getDb()->flush();
  4583. }
  4584. }
  4585. return true;
  4586. }
  4587. /**
  4588. * Sets the theme of the LP (local/remote) (and save)
  4589. * @param string Optional string giving the new theme of this learnpath
  4590. * @return bool Returns true if theme name is not empty
  4591. */
  4592. public function set_theme($name = '')
  4593. {
  4594. $course_id = api_get_course_int_id();
  4595. if ($this->debug > 0) {
  4596. error_log('New LP - In learnpath::set_theme()', 0);
  4597. }
  4598. $this->theme = $name;
  4599. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4600. $lp_id = $this->get_id();
  4601. $sql = "UPDATE $lp_table SET theme = '".Database::escape_string($this->theme)."'
  4602. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4603. if ($this->debug > 2) {
  4604. error_log('New LP - lp updated with new theme : '.$this->theme, 0);
  4605. }
  4606. Database::query($sql);
  4607. return true;
  4608. }
  4609. /**
  4610. * Sets the image of an LP (and save)
  4611. * @param string Optional string giving the new image of this learnpath
  4612. * @return bool Returns true if theme name is not empty
  4613. */
  4614. public function set_preview_image($name = '')
  4615. {
  4616. $course_id = api_get_course_int_id();
  4617. if ($this->debug > 0) {
  4618. error_log('New LP - In learnpath::set_preview_image()', 0);
  4619. }
  4620. $this->preview_image = $name;
  4621. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4622. $lp_id = $this->get_id();
  4623. $sql = "UPDATE $lp_table SET
  4624. preview_image = '".Database::escape_string($this->preview_image)."'
  4625. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4626. if ($this->debug > 2) {
  4627. error_log('New LP - lp updated with new preview image : '.$this->preview_image, 0);
  4628. }
  4629. Database::query($sql);
  4630. return true;
  4631. }
  4632. /**
  4633. * Sets the author of a LP (and save)
  4634. * @param string Optional string giving the new author of this learnpath
  4635. * @return bool Returns true if author's name is not empty
  4636. */
  4637. public function set_author($name = '')
  4638. {
  4639. $course_id = api_get_course_int_id();
  4640. if ($this->debug > 0) {
  4641. error_log('New LP - In learnpath::set_author()', 0);
  4642. }
  4643. $this->author = $name;
  4644. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4645. $lp_id = $this->get_id();
  4646. $sql = "UPDATE $lp_table SET author = '".Database::escape_string($name)."'
  4647. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4648. if ($this->debug > 2) {
  4649. error_log('New LP - lp updated with new preview author : '.$this->author, 0);
  4650. }
  4651. Database::query($sql);
  4652. return true;
  4653. }
  4654. /**
  4655. * Sets the hide_toc_frame parameter of a LP (and save)
  4656. * @param int 1 if frame is hidden 0 then else
  4657. * @return bool Returns true if author's name is not empty
  4658. */
  4659. public function set_hide_toc_frame($hide)
  4660. {
  4661. $course_id = api_get_course_int_id();
  4662. if ($this->debug > 0) {
  4663. error_log('New LP - In learnpath::set_hide_toc_frame()', 0);
  4664. }
  4665. if (intval($hide) == $hide) {
  4666. $this->hide_toc_frame = $hide;
  4667. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4668. $lp_id = $this->get_id();
  4669. $sql = "UPDATE $lp_table SET
  4670. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4671. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4672. if ($this->debug > 2) {
  4673. error_log('New LP - lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4674. }
  4675. Database::query($sql);
  4676. return true;
  4677. } else {
  4678. return false;
  4679. }
  4680. }
  4681. /**
  4682. * Sets the prerequisite of a LP (and save)
  4683. * @param int integer giving the new prerequisite of this learnpath
  4684. * @return bool returns true if prerequisite is not empty
  4685. */
  4686. public function set_prerequisite($prerequisite)
  4687. {
  4688. $course_id = api_get_course_int_id();
  4689. if ($this->debug > 0) {
  4690. error_log('New LP - In learnpath::set_prerequisite()', 0);
  4691. }
  4692. $this->prerequisite = intval($prerequisite);
  4693. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4694. $lp_id = $this->get_id();
  4695. $sql = "UPDATE $lp_table SET prerequisite = '".$this->prerequisite."'
  4696. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4697. if ($this->debug > 2) {
  4698. error_log('New LP - lp updated with new preview requisite : '.$this->requisite, 0);
  4699. }
  4700. Database::query($sql);
  4701. return true;
  4702. }
  4703. /**
  4704. * Sets the location/proximity of the LP (local/remote) (and save)
  4705. * @param string Optional string giving the new location of this learnpath
  4706. * @return boolean True on success / False on error
  4707. */
  4708. public function set_proximity($name = '')
  4709. {
  4710. $course_id = api_get_course_int_id();
  4711. if ($this->debug > 0) {
  4712. error_log('New LP - In learnpath::set_proximity()', 0);
  4713. }
  4714. if (empty ($name))
  4715. return false;
  4716. $this->proximity = $name;
  4717. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4718. $lp_id = $this->get_id();
  4719. $sql = "UPDATE $lp_table SET
  4720. content_local = '".Database::escape_string($name)."'
  4721. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4722. if ($this->debug > 2) {
  4723. error_log('New LP - lp updated with new proximity : '.$this->proximity, 0);
  4724. }
  4725. Database::query($sql);
  4726. return true;
  4727. }
  4728. /**
  4729. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item
  4730. * @param integer DB ID of the item
  4731. */
  4732. public function set_previous_item($id)
  4733. {
  4734. if ($this->debug > 0) {
  4735. error_log('New LP - In learnpath::set_previous_item()', 0);
  4736. }
  4737. $this->last = $id;
  4738. }
  4739. /**
  4740. * Sets use_max_score
  4741. * @param string $use_max_score Optional string giving the new location of this learnpath
  4742. * @return boolean True on success / False on error
  4743. */
  4744. public function set_use_max_score($use_max_score = 1)
  4745. {
  4746. $course_id = api_get_course_int_id();
  4747. if ($this->debug > 0) {
  4748. error_log('New LP - In learnpath::set_use_max_score()', 0);
  4749. }
  4750. $use_max_score = intval($use_max_score);
  4751. $this->use_max_score = $use_max_score;
  4752. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4753. $lp_id = $this->get_id();
  4754. $sql = "UPDATE $lp_table SET
  4755. use_max_score = '".$this->use_max_score."'
  4756. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4757. if ($this->debug > 2) {
  4758. error_log('New LP - lp updated with new use_max_score : '.$this->use_max_score, 0);
  4759. }
  4760. Database::query($sql);
  4761. return true;
  4762. }
  4763. /**
  4764. * Sets and saves the expired_on date
  4765. * @param string $expired_on Optional string giving the new author of this learnpath
  4766. * @return bool Returns true if author's name is not empty
  4767. */
  4768. public function set_expired_on($expired_on)
  4769. {
  4770. if ($this->debug > 0) {
  4771. error_log('New LP - In learnpath::set_expired_on()', 0);
  4772. }
  4773. $em = Database::getManager();
  4774. /** @var CLp $lp */
  4775. $lp = $em
  4776. ->getRepository('ChamiloCourseBundle:CLp')
  4777. ->findOneBy(
  4778. [
  4779. 'id' => $this->get_id(),
  4780. 'cId' => api_get_course_int_id()
  4781. ]
  4782. );
  4783. if (!$lp) {
  4784. return false;
  4785. }
  4786. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4787. $lp->setExpiredOn($this->expired_on);
  4788. $em->persist($lp);
  4789. $em->flush();
  4790. if ($this->debug > 2) {
  4791. error_log('New LP - lp updated with new expired_on : '.$this->expired_on, 0);
  4792. }
  4793. return true;
  4794. }
  4795. /**
  4796. * Sets and saves the publicated_on date
  4797. * @param string $publicated_on Optional string giving the new author of this learnpath
  4798. * @return bool Returns true if author's name is not empty
  4799. */
  4800. public function set_publicated_on($publicated_on)
  4801. {
  4802. if ($this->debug > 0) {
  4803. error_log('New LP - In learnpath::set_expired_on()', 0);
  4804. }
  4805. $em = Database::getManager();
  4806. /** @var CLp $lp */
  4807. $lp = $em
  4808. ->getRepository('ChamiloCourseBundle:CLp')
  4809. ->findOneBy(
  4810. [
  4811. 'id' => $this->get_id(),
  4812. 'cId' => api_get_course_int_id()
  4813. ]
  4814. );
  4815. if (!$lp) {
  4816. return false;
  4817. }
  4818. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4819. $lp->setPublicatedOn($this->publicated_on);
  4820. $em->persist($lp);
  4821. $em->flush();
  4822. if ($this->debug > 2) {
  4823. error_log('New LP - lp updated with new publicated_on : '.$this->publicated_on, 0);
  4824. }
  4825. return true;
  4826. }
  4827. /**
  4828. * Sets and saves the expired_on date
  4829. * @return bool Returns true if author's name is not empty
  4830. */
  4831. public function set_modified_on()
  4832. {
  4833. $course_id = api_get_course_int_id();
  4834. if ($this->debug > 0) {
  4835. error_log('New LP - In learnpath::set_expired_on()', 0);
  4836. }
  4837. $this->modified_on = api_get_utc_datetime();
  4838. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4839. $lp_id = $this->get_id();
  4840. $sql = "UPDATE $lp_table SET modified_on = '".$this->modified_on."'
  4841. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4842. if ($this->debug > 2) {
  4843. error_log('New LP - lp updated with new expired_on : '.$this->modified_on, 0);
  4844. }
  4845. Database::query($sql);
  4846. return true;
  4847. }
  4848. /**
  4849. * Sets the object's error message
  4850. * @param string Error message. If empty, reinits the error string
  4851. * @return void
  4852. */
  4853. public function set_error_msg($error = '')
  4854. {
  4855. if ($this->debug > 0) {
  4856. error_log('New LP - In learnpath::set_error_msg()', 0);
  4857. }
  4858. if (empty ($error)) {
  4859. $this->error = '';
  4860. } else {
  4861. $this->error .= $error;
  4862. }
  4863. }
  4864. /**
  4865. * Launches the current item if not 'sco'
  4866. * (starts timer and make sure there is a record ready in the DB)
  4867. * @param boolean $allow_new_attempt Whether to allow a new attempt or not
  4868. * @return boolean
  4869. */
  4870. public function start_current_item($allow_new_attempt = false)
  4871. {
  4872. if ($this->debug > 0) {
  4873. error_log('New LP - In learnpath::start_current_item()', 0);
  4874. }
  4875. if ($this->current != 0 && is_object($this->items[$this->current])) {
  4876. $type = $this->get_type();
  4877. $item_type = $this->items[$this->current]->get_type();
  4878. if (($type == 2 && $item_type != 'sco') ||
  4879. ($type == 3 && $item_type != 'au') ||
  4880. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4881. ) {
  4882. $this->items[$this->current]->open($allow_new_attempt);
  4883. $this->autocomplete_parents($this->current);
  4884. $prereq_check = $this->prerequisites_match($this->current);
  4885. $this->items[$this->current]->save(false, $prereq_check);
  4886. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  4887. }
  4888. // If sco, then it is supposed to have been updated by some other call.
  4889. if ($item_type == 'sco') {
  4890. $this->items[$this->current]->restart();
  4891. }
  4892. }
  4893. if ($this->debug > 0) {
  4894. error_log('New LP - End of learnpath::start_current_item()', 0);
  4895. }
  4896. return true;
  4897. }
  4898. /**
  4899. * Stops the processing and counters for the old item (as held in $this->last)
  4900. * @return boolean True/False
  4901. */
  4902. public function stop_previous_item()
  4903. {
  4904. if ($this->debug > 0) {
  4905. error_log('New LP - In learnpath::stop_previous_item()', 0);
  4906. }
  4907. if ($this->last != 0 && $this->last != $this->current && is_object($this->items[$this->last])) {
  4908. if ($this->debug > 2) {
  4909. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' is object', 0);
  4910. }
  4911. switch ($this->get_type()) {
  4912. case '3':
  4913. if ($this->items[$this->last]->get_type() != 'au') {
  4914. if ($this->debug > 2) {
  4915. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au', 0);
  4916. }
  4917. $this->items[$this->last]->close();
  4918. //$this->autocomplete_parents($this->last);
  4919. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  4920. } else {
  4921. if ($this->debug > 2) {
  4922. error_log('New LP - In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals', 0);
  4923. }
  4924. }
  4925. break;
  4926. case '2':
  4927. if ($this->items[$this->last]->get_type() != 'sco') {
  4928. if ($this->debug > 2) {
  4929. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco', 0);
  4930. }
  4931. $this->items[$this->last]->close();
  4932. //$this->autocomplete_parents($this->last);
  4933. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  4934. } else {
  4935. if ($this->debug > 2) {
  4936. error_log('New LP - In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals', 0);
  4937. }
  4938. }
  4939. break;
  4940. case '1':
  4941. default:
  4942. if ($this->debug > 2) {
  4943. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset', 0);
  4944. }
  4945. $this->items[$this->last]->close();
  4946. break;
  4947. }
  4948. } else {
  4949. if ($this->debug > 2) {
  4950. error_log('New LP - In learnpath::stop_previous_item() - No previous element found, ignoring...', 0);
  4951. }
  4952. return false;
  4953. }
  4954. return true;
  4955. }
  4956. /**
  4957. * Updates the default view mode from fullscreen to embedded and inversely
  4958. * @return string The current default view mode ('fullscreen' or 'embedded')
  4959. */
  4960. public function update_default_view_mode()
  4961. {
  4962. $course_id = api_get_course_int_id();
  4963. if ($this->debug > 0) {
  4964. error_log('New LP - In learnpath::update_default_view_mode()', 0);
  4965. }
  4966. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4967. $sql = "SELECT * FROM $lp_table
  4968. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  4969. $res = Database::query($sql);
  4970. if (Database::num_rows($res) > 0) {
  4971. $row = Database::fetch_array($res);
  4972. $default_view_mode = $row['default_view_mod'];
  4973. $view_mode = $default_view_mode;
  4974. switch ($default_view_mode) {
  4975. case 'fullscreen': // default with popup
  4976. $view_mode = 'embedded';
  4977. break;
  4978. case 'embedded': // default view with left menu
  4979. $view_mode = 'embedframe';
  4980. break;
  4981. case 'embedframe': //folded menu
  4982. $view_mode = 'impress';
  4983. break;
  4984. case 'impress':
  4985. $view_mode = 'fullscreen';
  4986. break;
  4987. }
  4988. $sql = "UPDATE $lp_table SET default_view_mod = '$view_mode'
  4989. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  4990. Database::query($sql);
  4991. $this->mode = $view_mode;
  4992. return $view_mode;
  4993. } else {
  4994. if ($this->debug > 2) {
  4995. error_log('New LP - Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  4996. }
  4997. }
  4998. return -1;
  4999. }
  5000. /**
  5001. * Updates the default behaviour about auto-commiting SCORM updates
  5002. * @return boolean True if auto-commit has been set to 'on', false otherwise
  5003. */
  5004. public function update_default_scorm_commit()
  5005. {
  5006. $course_id = api_get_course_int_id();
  5007. if ($this->debug > 0) {
  5008. error_log('New LP - In learnpath::update_default_scorm_commit()', 0);
  5009. }
  5010. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5011. $sql = "SELECT * FROM $lp_table
  5012. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5013. $res = Database::query($sql);
  5014. if (Database::num_rows($res) > 0) {
  5015. $row = Database::fetch_array($res);
  5016. $force = $row['force_commit'];
  5017. if ($force == 1) {
  5018. $force = 0;
  5019. $force_return = false;
  5020. } elseif ($force == 0) {
  5021. $force = 1;
  5022. $force_return = true;
  5023. }
  5024. $sql = "UPDATE $lp_table SET force_commit = $force
  5025. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5026. Database::query($sql);
  5027. $this->force_commit = $force_return;
  5028. return $force_return;
  5029. } else {
  5030. if ($this->debug > 2) {
  5031. error_log('New LP - Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5032. }
  5033. }
  5034. return -1;
  5035. }
  5036. /**
  5037. * Updates the order of learning paths (goes through all of them by order and fills the gaps)
  5038. * @return bool True on success, false on failure
  5039. */
  5040. public function update_display_order()
  5041. {
  5042. $course_id = api_get_course_int_id();
  5043. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5044. $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." ORDER BY display_order";
  5045. $res = Database::query($sql);
  5046. if ($res === false) {
  5047. return false;
  5048. }
  5049. $num = Database::num_rows($res);
  5050. // First check the order is correct, globally (might be wrong because
  5051. // of versions < 1.8.4).
  5052. if ($num > 0) {
  5053. $i = 1;
  5054. while ($row = Database::fetch_array($res)) {
  5055. if ($row['display_order'] != $i) {
  5056. // If we find a gap in the order, we need to fix it.
  5057. $sql = "UPDATE $lp_table SET display_order = $i
  5058. WHERE c_id = ".$course_id." AND id = ".$row['id'];
  5059. Database::query($sql);
  5060. }
  5061. $i++;
  5062. }
  5063. }
  5064. return true;
  5065. }
  5066. /**
  5067. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view
  5068. * @return boolean True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5069. */
  5070. public function update_reinit()
  5071. {
  5072. $course_id = api_get_course_int_id();
  5073. if ($this->debug > 0) {
  5074. error_log('New LP - In learnpath::update_reinit()', 0);
  5075. }
  5076. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5077. $sql = "SELECT * FROM $lp_table
  5078. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5079. $res = Database::query($sql);
  5080. if (Database::num_rows($res) > 0) {
  5081. $row = Database::fetch_array($res);
  5082. $force = $row['prevent_reinit'];
  5083. if ($force == 1) {
  5084. $force = 0;
  5085. } elseif ($force == 0) {
  5086. $force = 1;
  5087. }
  5088. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5089. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5090. Database::query($sql);
  5091. $this->prevent_reinit = $force;
  5092. return $force;
  5093. } else {
  5094. if ($this->debug > 2) {
  5095. error_log('New LP - Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5096. }
  5097. }
  5098. return -1;
  5099. }
  5100. /**
  5101. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag
  5102. *
  5103. * @return string 'single', 'multi' or 'seriousgame'
  5104. * @author ndiechburg <noel@cblue.be>
  5105. **/
  5106. public function get_attempt_mode()
  5107. {
  5108. //Set default value for seriousgame_mode
  5109. if (!isset($this->seriousgame_mode)) {
  5110. $this->seriousgame_mode = 0;
  5111. }
  5112. // Set default value for prevent_reinit
  5113. if (!isset($this->prevent_reinit)) {
  5114. $this->prevent_reinit = 1;
  5115. }
  5116. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5117. return 'seriousgame';
  5118. }
  5119. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5120. return 'single';
  5121. }
  5122. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5123. return 'multiple';
  5124. }
  5125. return 'single';
  5126. }
  5127. /**
  5128. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags
  5129. *
  5130. * @param string 'seriousgame', 'single' or 'multiple'
  5131. * @return boolean
  5132. * @author ndiechburg <noel@cblue.be>
  5133. **/
  5134. public function set_attempt_mode($mode)
  5135. {
  5136. $course_id = api_get_course_int_id();
  5137. switch ($mode) {
  5138. case 'seriousgame':
  5139. $sg_mode = 1;
  5140. $prevent_reinit = 1;
  5141. break;
  5142. case 'single':
  5143. $sg_mode = 0;
  5144. $prevent_reinit = 1;
  5145. break;
  5146. case 'multiple':
  5147. $sg_mode = 0;
  5148. $prevent_reinit = 0;
  5149. break;
  5150. default:
  5151. $sg_mode = 0;
  5152. $prevent_reinit = 0;
  5153. break;
  5154. }
  5155. $this->prevent_reinit = $prevent_reinit;
  5156. $this->seriousgame_mode = $sg_mode;
  5157. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5158. $sql = "UPDATE $lp_table SET
  5159. prevent_reinit = $prevent_reinit ,
  5160. seriousgame_mode = $sg_mode
  5161. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5162. $res = Database::query($sql);
  5163. if ($res) {
  5164. return true;
  5165. } else {
  5166. return false;
  5167. }
  5168. }
  5169. /**
  5170. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm)
  5171. *
  5172. * @return boolean
  5173. * @author ndiechburg <noel@cblue.be>
  5174. **/
  5175. public function switch_attempt_mode()
  5176. {
  5177. if ($this->debug > 0) {
  5178. error_log('New LP - In learnpath::switch_attempt_mode()', 0);
  5179. }
  5180. $mode = $this->get_attempt_mode();
  5181. switch ($mode) {
  5182. case 'single':
  5183. $next_mode = 'multiple';
  5184. break;
  5185. case 'multiple':
  5186. $next_mode = 'seriousgame';
  5187. break;
  5188. case 'seriousgame':
  5189. $next_mode = 'single';
  5190. break;
  5191. default:
  5192. $next_mode = 'single';
  5193. break;
  5194. }
  5195. $this->set_attempt_mode($next_mode);
  5196. }
  5197. /**
  5198. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5199. * but possibility to do again a completed item.
  5200. *
  5201. * @return boolean true if seriousgame_mode has been set to 1, false otherwise
  5202. * @author ndiechburg <noel@cblue.be>
  5203. **/
  5204. public function set_seriousgame_mode()
  5205. {
  5206. $course_id = api_get_course_int_id();
  5207. if ($this->debug > 0) {
  5208. error_log('New LP - In learnpath::set_seriousgame_mode()', 0);
  5209. }
  5210. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5211. $sql = "SELECT * FROM $lp_table
  5212. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5213. $res = Database::query($sql);
  5214. if (Database::num_rows($res) > 0) {
  5215. $row = Database::fetch_array($res);
  5216. $force = $row['seriousgame_mode'];
  5217. if ($force == 1) {
  5218. $force = 0;
  5219. } elseif ($force == 0) {
  5220. $force = 1;
  5221. }
  5222. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5223. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5224. Database::query($sql);
  5225. $this->seriousgame_mode = $force;
  5226. return $force;
  5227. } else {
  5228. if ($this->debug > 2) {
  5229. error_log('New LP - Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5230. }
  5231. }
  5232. return -1;
  5233. }
  5234. /**
  5235. * Updates the "scorm_debug" value that shows or hide the debug window
  5236. * @return boolean True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5237. */
  5238. public function update_scorm_debug()
  5239. {
  5240. $course_id = api_get_course_int_id();
  5241. if ($this->debug > 0) {
  5242. error_log('New LP - In learnpath::update_scorm_debug()', 0);
  5243. }
  5244. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5245. $sql = "SELECT * FROM $lp_table
  5246. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5247. $res = Database::query($sql);
  5248. if (Database::num_rows($res) > 0) {
  5249. $row = Database::fetch_array($res);
  5250. $force = $row['debug'];
  5251. if ($force == 1) {
  5252. $force = 0;
  5253. } elseif ($force == 0) {
  5254. $force = 1;
  5255. }
  5256. $sql = "UPDATE $lp_table SET debug = $force
  5257. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5258. Database::query($sql);
  5259. $this->scorm_debug = $force;
  5260. return $force;
  5261. } else {
  5262. if ($this->debug > 2) {
  5263. error_log('New LP - Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5264. }
  5265. }
  5266. return -1;
  5267. }
  5268. /**
  5269. * Function that makes a call to the function sort_tree_array and create_tree_array
  5270. * @author Kevin Van Den Haute
  5271. * @param array
  5272. */
  5273. public function tree_array($array)
  5274. {
  5275. if ($this->debug > 1) {
  5276. error_log('New LP - In learnpath::tree_array()', 0);
  5277. }
  5278. $array = $this->sort_tree_array($array);
  5279. $this->create_tree_array($array);
  5280. }
  5281. /**
  5282. * Creates an array with the elements of the learning path tree in it
  5283. *
  5284. * @author Kevin Van Den Haute
  5285. * @param array $array
  5286. * @param int $parent
  5287. * @param int $depth
  5288. * @param array $tmp
  5289. */
  5290. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = array())
  5291. {
  5292. if ($this->debug > 1) {
  5293. error_log('New LP - In learnpath::create_tree_array())', 0);
  5294. }
  5295. if (is_array($array)) {
  5296. for ($i = 0; $i < count($array); $i++) {
  5297. if ($array[$i]['parent_item_id'] == $parent) {
  5298. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5299. $tmp[] = $array[$i]['parent_item_id'];
  5300. $depth++;
  5301. }
  5302. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5303. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5304. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5305. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5306. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5307. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5308. $this->arrMenu[] = array(
  5309. 'id' => $array[$i]['id'],
  5310. 'ref' => $ref,
  5311. 'item_type' => $array[$i]['item_type'],
  5312. 'title' => $array[$i]['title'],
  5313. 'path' => $path,
  5314. 'description' => $array[$i]['description'],
  5315. 'parent_item_id' => $array[$i]['parent_item_id'],
  5316. 'previous_item_id' => $array[$i]['previous_item_id'],
  5317. 'next_item_id' => $array[$i]['next_item_id'],
  5318. 'min_score' => $array[$i]['min_score'],
  5319. 'max_score' => $array[$i]['max_score'],
  5320. 'mastery_score' => $array[$i]['mastery_score'],
  5321. 'display_order' => $array[$i]['display_order'],
  5322. 'prerequisite' => $preq,
  5323. 'depth' => $depth,
  5324. 'audio' => $audio,
  5325. 'prerequisite_min_score' => $prerequisiteMinScore,
  5326. 'prerequisite_max_score' => $prerequisiteMaxScore
  5327. );
  5328. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5329. }
  5330. }
  5331. }
  5332. }
  5333. /**
  5334. * Sorts a multi dimensional array by parent id and display order
  5335. * @author Kevin Van Den Haute
  5336. *
  5337. * @param array $array (array with al the learning path items in it)
  5338. *
  5339. * @return array
  5340. */
  5341. public function sort_tree_array($array)
  5342. {
  5343. foreach ($array as $key => $row) {
  5344. $parent[$key] = $row['parent_item_id'];
  5345. $position[$key] = $row['display_order'];
  5346. }
  5347. if (count($array) > 0) {
  5348. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5349. }
  5350. return $array;
  5351. }
  5352. /**
  5353. * Function that creates a html list of learning path items so that we can add audio files to them
  5354. * @author Kevin Van Den Haute
  5355. * @return string
  5356. */
  5357. public function overview()
  5358. {
  5359. if ($this->debug > 0) {
  5360. error_log('New LP - In learnpath::overview()', 0);
  5361. }
  5362. $return = '';
  5363. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5364. // we need to start a form when we want to update all the mp3 files
  5365. if ($update_audio == 'true') {
  5366. $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">';
  5367. }
  5368. $return .= '<div id="message"></div>';
  5369. if (count($this->items) == 0) {
  5370. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5371. } else {
  5372. $return_audio = '<table class="data_table">';
  5373. $return_audio .= '<tr>';
  5374. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5375. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5376. $return_audio .= '</tr>';
  5377. if ($update_audio != 'true') {
  5378. $return .= '<div class="col-md-12">';
  5379. $return .= self::return_new_tree($update_audio);
  5380. $return .= '</div>';
  5381. $return .= Display::div(
  5382. Display::url(get_lang('Save'), '#', array('id' => 'listSubmit', 'class' => 'btn btn-primary')),
  5383. array('style' => 'float:left; margin-top:15px;width:100%')
  5384. );
  5385. } else {
  5386. $return_audio .= self::return_new_tree($update_audio);
  5387. $return .= $return_audio.'</table>';
  5388. }
  5389. // We need to close the form when we are updating the mp3 files.
  5390. if ($update_audio == 'true') {
  5391. $return .= '<div class="footer-audio">';
  5392. $return .= Display::button(
  5393. 'save_audio',
  5394. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5395. array('class' => 'btn btn-primary', 'type' => 'submit')
  5396. );
  5397. $return .= '</div>';
  5398. }
  5399. }
  5400. // We need to close the form when we are updating the mp3 files.
  5401. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5402. $return .= '</form>';
  5403. }
  5404. return $return;
  5405. }
  5406. /**
  5407. * @param string string $update_audio
  5408. * @param bool $drop_element_here
  5409. * @return string
  5410. */
  5411. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5412. {
  5413. $return = '';
  5414. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5415. $course_id = api_get_course_int_id();
  5416. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  5417. $sql = "SELECT * FROM $tbl_lp_item
  5418. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5419. $result = Database::query($sql);
  5420. $arrLP = array();
  5421. while ($row = Database::fetch_array($result)) {
  5422. $arrLP[] = array(
  5423. 'id' => $row['id'],
  5424. 'item_type' => $row['item_type'],
  5425. 'title' => Security::remove_XSS($row['title']),
  5426. 'path' => $row['path'],
  5427. 'description' => Security::remove_XSS($row['description']),
  5428. 'parent_item_id' => $row['parent_item_id'],
  5429. 'previous_item_id' => $row['previous_item_id'],
  5430. 'next_item_id' => $row['next_item_id'],
  5431. 'max_score' => $row['max_score'],
  5432. 'min_score' => $row['min_score'],
  5433. 'mastery_score' => $row['mastery_score'],
  5434. 'prerequisite' => $row['prerequisite'],
  5435. 'display_order' => $row['display_order'],
  5436. 'audio' => $row['audio'],
  5437. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5438. 'prerequisite_min_score' => $row['prerequisite_min_score']
  5439. );
  5440. }
  5441. $this->tree_array($arrLP);
  5442. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  5443. unset($this->arrMenu);
  5444. $default_data = null;
  5445. $default_content = null;
  5446. $elements = array();
  5447. $return_audio = null;
  5448. for ($i = 0; $i < count($arrLP); $i++) {
  5449. $title = $arrLP[$i]['title'];
  5450. $title_cut = cut($arrLP[$i]['title'], 25);
  5451. // Link for the documents
  5452. if ($arrLP[$i]['item_type'] == 'document') {
  5453. $url = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5454. $title_cut = Display::url(
  5455. $title_cut,
  5456. $url,
  5457. array(
  5458. 'class' => 'ajax moved',
  5459. 'data-title' => $title_cut
  5460. )
  5461. );
  5462. }
  5463. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5464. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5465. Session::write('pathItem', $arrLP[$i]['path']);
  5466. }
  5467. if (($i % 2) == 0) {
  5468. $oddClass = 'row_odd';
  5469. } else {
  5470. $oddClass = 'row_even';
  5471. }
  5472. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5473. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5474. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  5475. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5476. } else {
  5477. if (file_exists('../img/lp_'.$icon_name.'.gif')) {
  5478. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5479. } else {
  5480. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5481. $icon = Display::return_icon('certificate.png');
  5482. } else {
  5483. $icon = Display::return_icon('folder_document.gif');
  5484. }
  5485. }
  5486. }
  5487. // The audio column.
  5488. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5489. $audio = '';
  5490. if (!$update_audio || $update_audio <> 'true') {
  5491. if (empty($arrLP[$i]['audio'])) {
  5492. $audio .= '';
  5493. }
  5494. } else {
  5495. $types = self::getChapterTypes();
  5496. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5497. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5498. if (!empty ($arrLP[$i]['audio'])) {
  5499. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5500. <input type="checkbox" name="removemp3' . $arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5501. }
  5502. }
  5503. }
  5504. $return_audio .= Display::span($icon.' '.$title).
  5505. Display::tag(
  5506. 'td',
  5507. $audio,
  5508. array('style' => '')
  5509. );
  5510. $return_audio .= '</td>';
  5511. $move_icon = '';
  5512. $move_item_icon = '';
  5513. $edit_icon = '';
  5514. $delete_icon = '';
  5515. $audio_icon = '';
  5516. $prerequisities_icon = '';
  5517. $forumIcon = '';
  5518. $previewIcon = '';
  5519. if ($is_allowed_to_edit) {
  5520. if (!$update_audio || $update_audio <> 'true') {
  5521. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5522. $move_icon .= '<a class="moved" href="#">';
  5523. $move_icon .= Display::return_icon(
  5524. 'move_everywhere.png',
  5525. get_lang('Move'),
  5526. array(),
  5527. ICON_SIZE_TINY
  5528. );
  5529. $move_icon .= '</a>';
  5530. }
  5531. }
  5532. // No edit for this item types
  5533. if (!in_array($arrLP[$i]['item_type'], array('sco', 'asset', 'final_item'))) {
  5534. if ($arrLP[$i]['item_type'] != 'dir') {
  5535. $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">';
  5536. $edit_icon .= Display::return_icon(
  5537. 'edit.png',
  5538. get_lang('LearnpathEditModule'),
  5539. array(),
  5540. ICON_SIZE_TINY
  5541. );
  5542. $edit_icon .= '</a>';
  5543. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5544. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5545. $this->course_int_id,
  5546. $this->lp_session_id
  5547. );
  5548. if ($forumThread) {
  5549. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5550. 'action' => 'dissociate_forum',
  5551. 'id' => $arrLP[$i]['id'],
  5552. 'lp_id' => $this->lp_id
  5553. ]);
  5554. $forumIcon = Display::url(
  5555. Display::return_icon('forum.png', get_lang('DissociateForumToLPItem'), [], ICON_SIZE_TINY),
  5556. $forumIconUrl,
  5557. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5558. );
  5559. } else {
  5560. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5561. 'action' => 'create_forum',
  5562. 'id' => $arrLP[$i]['id'],
  5563. 'lp_id' => $this->lp_id
  5564. ]);
  5565. $forumIcon = Display::url(
  5566. Display::return_icon('forum.png', get_lang('AssociateForumToLPItem'), [], ICON_SIZE_TINY),
  5567. $forumIconUrl,
  5568. ['class' => "btn btn-default lp-btn-associate-forum"]
  5569. );
  5570. }
  5571. }
  5572. } else {
  5573. $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">';
  5574. $edit_icon .= Display::return_icon(
  5575. 'edit.png',
  5576. get_lang('LearnpathEditModule'),
  5577. array(),
  5578. ICON_SIZE_TINY
  5579. );
  5580. $edit_icon .= '</a>';
  5581. }
  5582. } else {
  5583. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5584. $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">';
  5585. $edit_icon .= Display::return_icon(
  5586. 'edit.png',
  5587. get_lang('Edit'),
  5588. array(),
  5589. ICON_SIZE_TINY
  5590. );
  5591. $edit_icon .= '</a>';
  5592. }
  5593. }
  5594. $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">';
  5595. $delete_icon .= Display::return_icon(
  5596. 'delete.png',
  5597. get_lang('LearnpathDeleteModule'),
  5598. [],
  5599. ICON_SIZE_TINY
  5600. );
  5601. $delete_icon .= '</a>';
  5602. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5603. $previewImage = Display::return_icon(
  5604. 'preview_view.png',
  5605. get_lang('Preview'),
  5606. [],
  5607. ICON_SIZE_TINY
  5608. );
  5609. switch ($arrLP[$i]['item_type']) {
  5610. case TOOL_DOCUMENT:
  5611. case TOOL_LP_FINAL_ITEM:
  5612. $urlPreviewLink = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5613. $previewIcon = Display::url(
  5614. $previewImage,
  5615. $urlPreviewLink,
  5616. array(
  5617. 'target' => '_blank',
  5618. 'class' => 'btn btn-default',
  5619. 'data-title' => $arrLP[$i]['title']
  5620. )
  5621. );
  5622. break;
  5623. case TOOL_THREAD:
  5624. case TOOL_FORUM:
  5625. case TOOL_QUIZ:
  5626. case TOOL_STUDENTPUBLICATION:
  5627. case TOOL_LP_FINAL_ITEM:
  5628. case TOOL_LINK:
  5629. //$target = '';
  5630. //$class = 'btn btn-default ajax';
  5631. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5632. $class = 'btn btn-default';
  5633. $target = '_blank';
  5634. //}
  5635. $link = self::rl_get_resource_link_for_learnpath(
  5636. $this->course_int_id,
  5637. $this->lp_id,
  5638. $arrLP[$i]['id'],
  5639. 0,
  5640. ''
  5641. );
  5642. $previewIcon = Display::url(
  5643. $previewImage,
  5644. $link,
  5645. [
  5646. 'class' => $class,
  5647. 'data-title' => $arrLP[$i]['title'],
  5648. 'target' => $target
  5649. ]
  5650. );
  5651. break;
  5652. default:
  5653. $previewIcon = Display::url(
  5654. $previewImage,
  5655. $url.'&action=view_item',
  5656. ['class' => 'btn btn-default', 'target' => '_blank']
  5657. );
  5658. break;
  5659. }
  5660. if ($arrLP[$i]['item_type'] != 'dir') {
  5661. $prerequisities_icon = Display::url(
  5662. Display::return_icon(
  5663. 'accept.png',
  5664. get_lang('LearnpathPrerequisites'),
  5665. array(),
  5666. ICON_SIZE_TINY
  5667. ),
  5668. $url.'&action=edit_item_prereq', ['class' => 'btn btn-default']
  5669. );
  5670. if ($arrLP[$i]['item_type'] != 'final_item') {
  5671. $move_item_icon = Display::url(
  5672. Display::return_icon(
  5673. 'move.png',
  5674. get_lang('Move'),
  5675. array(),
  5676. ICON_SIZE_TINY
  5677. ),
  5678. $url.'&action=move_item',
  5679. ['class' => 'btn btn-default']
  5680. );
  5681. }
  5682. $audio_icon = Display::url(
  5683. Display::return_icon(
  5684. 'audio.png',
  5685. get_lang('UplUpload'),
  5686. array(),
  5687. ICON_SIZE_TINY
  5688. ),
  5689. $url.'&action=add_audio',
  5690. ['class' => 'btn btn-default']
  5691. );
  5692. }
  5693. }
  5694. if ($update_audio != 'true') {
  5695. $row = $move_icon.' '.$icon.
  5696. Display::span($title_cut).
  5697. Display::tag(
  5698. 'div',
  5699. "<div class=\"btn-group btn-group-xs\">$previewIcon $audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
  5700. array('class'=>'btn-toolbar button_actions')
  5701. );
  5702. } else {
  5703. $row = Display::span($title.$icon).Display::span($audio, array('class'=>'button_actions'));
  5704. }
  5705. $parent_id = $arrLP[$i]['parent_item_id'];
  5706. $default_data[$arrLP[$i]['id']] = $row;
  5707. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5708. if (empty($parent_id)) {
  5709. $elements[$arrLP[$i]['id']]['data'] = $row;
  5710. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5711. } else {
  5712. $parent_arrays = array();
  5713. if ($arrLP[$i]['depth'] > 1) {
  5714. //Getting list of parents
  5715. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5716. foreach ($arrLP as $item) {
  5717. if ($item['id'] == $parent_id) {
  5718. if ($item['parent_item_id'] == 0) {
  5719. $parent_id = $item['id'];
  5720. break;
  5721. } else {
  5722. $parent_id = $item['parent_item_id'];
  5723. if (empty($parent_arrays)) {
  5724. $parent_arrays[] = intval($item['id']);
  5725. }
  5726. $parent_arrays[] = $parent_id;
  5727. break;
  5728. }
  5729. }
  5730. }
  5731. }
  5732. }
  5733. if (!empty($parent_arrays)) {
  5734. $parent_arrays = array_reverse($parent_arrays);
  5735. $val = '$elements';
  5736. $x = 0;
  5737. foreach ($parent_arrays as $item) {
  5738. if ($x != count($parent_arrays) - 1) {
  5739. $val .= '["'.$item.'"]["children"]';
  5740. } else {
  5741. $val .= '["'.$item.'"]["children"]';
  5742. }
  5743. $x++;
  5744. }
  5745. $val .= "";
  5746. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5747. eval($code_str);
  5748. } else {
  5749. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5750. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5751. }
  5752. }
  5753. }
  5754. $list = '<ul id="lp_item_list">';
  5755. $tree = self::print_recursive(
  5756. $elements,
  5757. $default_data,
  5758. $default_content
  5759. );
  5760. if (!empty($tree)) {
  5761. $list .= $tree;
  5762. } else {
  5763. if ($drop_element_here) {
  5764. $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
  5765. }
  5766. }
  5767. $list .= '</ul>';
  5768. $return .= Display::panelCollapse(
  5769. $this->name,
  5770. $list,
  5771. 'scorm-list',
  5772. null,
  5773. 'scorm-list-accordion',
  5774. 'scorm-list-collapse'
  5775. );
  5776. if ($update_audio == 'true') {
  5777. $return = $return_audio;
  5778. }
  5779. return $return;
  5780. }
  5781. /**
  5782. * @param array $elements
  5783. * @param array $default_data
  5784. * @param array $default_content
  5785. * @return string
  5786. */
  5787. public function print_recursive($elements, $default_data, $default_content)
  5788. {
  5789. $return = '';
  5790. foreach ($elements as $key => $item) {
  5791. if (isset($item['load_data']) || empty($item['data'])) {
  5792. $item['data'] = $default_data[$item['load_data']];
  5793. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5794. }
  5795. $sub_list = '';
  5796. if (isset($item['type']) && $item['type'] == 'dir') {
  5797. $sub_list = Display::tag('li', '', array('class'=>'sub_item empty')); // empty value
  5798. }
  5799. if (empty($item['children'])) {
  5800. $sub_list = Display::tag('ul', $sub_list, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
  5801. $active = null;
  5802. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5803. $active = 'active';
  5804. }
  5805. $return .= Display::tag(
  5806. 'li',
  5807. Display::div($item['data'], array('class'=>"item_data $active")).$sub_list,
  5808. array('id'=>$key, 'class'=>'record li_container')
  5809. );
  5810. } else {
  5811. // Sections
  5812. if (isset($item['children'])) {
  5813. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5814. }
  5815. $sub_list = Display::tag('ul', $sub_list.$data, array('id'=>'UL_'.$key, 'class'=>'record li_container'));
  5816. $return .= Display::tag(
  5817. 'li',
  5818. Display::div($item['data'], array('class'=>'item_data')).$sub_list,
  5819. array('id'=>$key, 'class'=>'record li_container')
  5820. );
  5821. }
  5822. }
  5823. return $return;
  5824. }
  5825. /**
  5826. * This function builds the action menu
  5827. * @param bool $returnContent Optional
  5828. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5829. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5830. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5831. * @return string
  5832. */
  5833. public function build_action_menu(
  5834. $returnContent = false,
  5835. $showRequirementButtons = true,
  5836. $isConfigPage = false,
  5837. $allowExpand = true
  5838. ) {
  5839. $actionsLeft = '';
  5840. $actionsRight = '';
  5841. $actionsLeft .= Display::url(
  5842. Display::return_icon(
  5843. 'preview_view.png',
  5844. get_lang('Display'),
  5845. '',
  5846. ICON_SIZE_MEDIUM
  5847. ),
  5848. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5849. 'action' => 'view',
  5850. 'lp_id' => $this->lp_id,
  5851. 'isStudentView' => 'true'
  5852. ])
  5853. );
  5854. $actionsLeft .= Display::url(
  5855. Display::return_icon(
  5856. 'upload_audio.png',
  5857. get_lang('UpdateAllAudioFragments'),
  5858. '',
  5859. ICON_SIZE_MEDIUM
  5860. ),
  5861. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5862. 'action' => 'admin_view',
  5863. 'lp_id' => $this->lp_id,
  5864. 'updateaudio' => 'true'
  5865. ])
  5866. );
  5867. if (!$isConfigPage) {
  5868. $actionsLeft .= Display::url(
  5869. Display::return_icon(
  5870. 'settings.png',
  5871. get_lang('CourseSettings'),
  5872. '',
  5873. ICON_SIZE_MEDIUM
  5874. ),
  5875. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5876. 'action' => 'edit',
  5877. 'lp_id' => $this->lp_id
  5878. ])
  5879. );
  5880. } else {
  5881. $actionsLeft .= Display::url(
  5882. Display::return_icon(
  5883. 'edit.png',
  5884. get_lang('Edit'),
  5885. '',
  5886. ICON_SIZE_MEDIUM
  5887. ),
  5888. 'lp_controller.php?'.http_build_query([
  5889. 'action' => 'build',
  5890. 'lp_id' => $this->lp_id
  5891. ]).'&'.api_get_cidreq()
  5892. );
  5893. }
  5894. if ($allowExpand) {
  5895. $actionsLeft .= Display::url(
  5896. Display::return_icon(
  5897. 'expand.png',
  5898. get_lang('Expand'),
  5899. array('id' => 'expand'),
  5900. ICON_SIZE_MEDIUM
  5901. ).
  5902. Display::return_icon(
  5903. 'contract.png',
  5904. get_lang('Collapse'),
  5905. array('id' => 'contract', 'class' => 'hide'),
  5906. ICON_SIZE_MEDIUM
  5907. ),
  5908. '#',
  5909. ['role' => 'button', 'id' => 'hide_bar_template']
  5910. );
  5911. }
  5912. if ($showRequirementButtons) {
  5913. $buttons = array(
  5914. array(
  5915. 'title' => get_lang('SetPrerequisiteForEachItem'),
  5916. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5917. 'action' => 'set_previous_step_as_prerequisite',
  5918. 'lp_id' => $this->lp_id
  5919. ])
  5920. ),
  5921. array(
  5922. 'title' => get_lang('ClearAllPrerequisites'),
  5923. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5924. 'action' => 'clear_prerequisites',
  5925. 'lp_id' => $this->lp_id
  5926. ])
  5927. ),
  5928. );
  5929. $actionsRight = Display::groupButtonWithDropDown(
  5930. get_lang('PrerequisitesOptions'),
  5931. $buttons,
  5932. true
  5933. );
  5934. }
  5935. $toolbar = Display::toolbarAction(
  5936. 'actions-lp-controller',
  5937. [$actionsLeft, $actionsRight]
  5938. );
  5939. if ($returnContent) {
  5940. return $toolbar;
  5941. }
  5942. echo $toolbar;
  5943. }
  5944. /**
  5945. * Creates the default learning path folder
  5946. * @param array $course
  5947. * @param int $creatorId
  5948. *
  5949. * @return bool
  5950. */
  5951. public static function generate_learning_path_folder($course, $creatorId = 0)
  5952. {
  5953. // Creating learning_path folder
  5954. $dir = '/learning_path';
  5955. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  5956. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  5957. $folder = false;
  5958. if (!is_dir($filepath.'/'.$dir)) {
  5959. $folderData = create_unexisting_directory(
  5960. $course,
  5961. $creatorId,
  5962. 0,
  5963. 0,
  5964. 0,
  5965. $filepath,
  5966. $dir,
  5967. get_lang('LearningPaths'),
  5968. 0
  5969. );
  5970. if (!empty($folderData)) {
  5971. $folder = true;
  5972. }
  5973. } else {
  5974. $folder = true;
  5975. }
  5976. return $folder;
  5977. }
  5978. /**
  5979. * @param array $course
  5980. * @param string $lp_name
  5981. * @param int $creatorId
  5982. *
  5983. * @return array
  5984. */
  5985. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  5986. {
  5987. $filepath = '';
  5988. $dir = '/learning_path/';
  5989. if (empty($lp_name)) {
  5990. $lp_name = $this->name;
  5991. }
  5992. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  5993. $folder = self::generate_learning_path_folder($course, $creatorId);
  5994. // Limits title size
  5995. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  5996. $dir = $dir.$title;
  5997. // Creating LP folder
  5998. $documentId = null;
  5999. if ($folder) {
  6000. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6001. if (!is_dir($filepath.'/'.$dir)) {
  6002. $folderData = create_unexisting_directory(
  6003. $course,
  6004. $creatorId,
  6005. 0,
  6006. 0,
  6007. 0,
  6008. $filepath,
  6009. $dir,
  6010. $lp_name
  6011. );
  6012. if (!empty($folderData)) {
  6013. $folder = true;
  6014. }
  6015. $documentId = $folderData['id'];
  6016. } else {
  6017. $folder = true;
  6018. }
  6019. $dir = $dir.'/';
  6020. if ($folder) {
  6021. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6022. }
  6023. }
  6024. if (empty($documentId)) {
  6025. $dir = api_remove_trailing_slash($dir);
  6026. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6027. }
  6028. $array = array(
  6029. 'dir' => $dir,
  6030. 'filepath' => $filepath,
  6031. 'folder' => $folder,
  6032. 'id' => $documentId
  6033. );
  6034. return $array;
  6035. }
  6036. /**
  6037. * Create a new document //still needs some finetuning
  6038. * @param array $courseInfo
  6039. * @param string $content
  6040. * @param string $title
  6041. * @param string $extension
  6042. * @param int $parentId
  6043. * @param int $creatorId creator id
  6044. *
  6045. * @return string
  6046. */
  6047. public function create_document(
  6048. $courseInfo,
  6049. $content = '',
  6050. $title = '',
  6051. $extension = 'html',
  6052. $parentId = 0,
  6053. $creatorId = 0
  6054. ) {
  6055. if (!empty($courseInfo)) {
  6056. $course_id = $courseInfo['real_id'];
  6057. } else {
  6058. $course_id = api_get_course_int_id();
  6059. }
  6060. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6061. $sessionId = api_get_session_id();
  6062. // Generates folder
  6063. $result = $this->generate_lp_folder($courseInfo);
  6064. $dir = $result['dir'];
  6065. if (empty($parentId) || $parentId == '/') {
  6066. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6067. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6068. if ($parentId === '/') {
  6069. $dir = '/';
  6070. }
  6071. // Please, do not modify this dirname formatting.
  6072. if (strstr($dir, '..')) {
  6073. $dir = '/';
  6074. }
  6075. if (!empty($dir[0]) && $dir[0] == '.') {
  6076. $dir = substr($dir, 1);
  6077. }
  6078. if (!empty($dir[0]) && $dir[0] != '/') {
  6079. $dir = '/'.$dir;
  6080. }
  6081. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6082. $dir .= '/';
  6083. }
  6084. } else {
  6085. $parentInfo = DocumentManager::get_document_data_by_id(
  6086. $parentId,
  6087. $courseInfo['code']
  6088. );
  6089. if (!empty($parentInfo)) {
  6090. $dir = $parentInfo['path'].'/';
  6091. }
  6092. }
  6093. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6094. if (!is_dir($filepath)) {
  6095. $dir = '/';
  6096. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6097. }
  6098. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6099. // is already escaped twice when it gets here.
  6100. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6101. if (!empty($title)) {
  6102. $title = api_replace_dangerous_char(stripslashes($title));
  6103. } else {
  6104. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6105. }
  6106. $title = disable_dangerous_file($title);
  6107. $filename = $title;
  6108. $content = !empty($content) ? $content : $_POST['content_lp'];
  6109. $tmp_filename = $filename;
  6110. $i = 0;
  6111. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6112. $tmp_filename = $filename.'_'.++ $i;
  6113. }
  6114. $filename = $tmp_filename.'.'.$extension;
  6115. if ($extension == 'html') {
  6116. $content = stripslashes($content);
  6117. $content = str_replace(
  6118. api_get_path(WEB_COURSE_PATH),
  6119. api_get_path(REL_PATH).'courses/',
  6120. $content
  6121. );
  6122. // Change the path of mp3 to absolute.
  6123. // The first regexp deals with :// urls.
  6124. $content = preg_replace(
  6125. "|(flashvars=\"file=)([^:/]+)/|",
  6126. "$1".api_get_path(
  6127. REL_COURSE_PATH
  6128. ).$courseInfo['path'].'/document/',
  6129. $content
  6130. );
  6131. // The second regexp deals with audio/ urls.
  6132. $content = preg_replace(
  6133. "|(flashvars=\"file=)([^/]+)/|",
  6134. "$1".api_get_path(
  6135. REL_COURSE_PATH
  6136. ).$courseInfo['path'].'/document/$2/',
  6137. $content
  6138. );
  6139. // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
  6140. $content = str_replace(
  6141. '</body>',
  6142. '<style type="text/css">body{}</style></body>',
  6143. $content
  6144. );
  6145. }
  6146. if (!file_exists($filepath.$filename)) {
  6147. if ($fp = @ fopen($filepath.$filename, 'w')) {
  6148. fputs($fp, $content);
  6149. fclose($fp);
  6150. $file_size = filesize($filepath.$filename);
  6151. $save_file_path = $dir.$filename;
  6152. $document_id = add_document(
  6153. $courseInfo,
  6154. $save_file_path,
  6155. 'file',
  6156. $file_size,
  6157. $tmp_filename,
  6158. '',
  6159. 0, //readonly
  6160. true,
  6161. null,
  6162. $sessionId,
  6163. $creatorId
  6164. );
  6165. if ($document_id) {
  6166. api_item_property_update(
  6167. $courseInfo,
  6168. TOOL_DOCUMENT,
  6169. $document_id,
  6170. 'DocumentAdded',
  6171. $creatorId,
  6172. null,
  6173. null,
  6174. null,
  6175. null,
  6176. $sessionId
  6177. );
  6178. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6179. $new_title = $originalTitle;
  6180. if ($new_comment || $new_title) {
  6181. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6182. $ct = '';
  6183. if ($new_comment)
  6184. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6185. if ($new_title)
  6186. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6187. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6188. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6189. Database::query($sql);
  6190. }
  6191. }
  6192. return $document_id;
  6193. }
  6194. }
  6195. }
  6196. /**
  6197. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'
  6198. * @param array $_course array
  6199. * @return void
  6200. */
  6201. public function edit_document($_course)
  6202. {
  6203. $course_id = api_get_course_int_id();
  6204. $urlAppend = api_get_configuration_value('url_append');
  6205. // Please, do not modify this dirname formatting.
  6206. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6207. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6208. if (strstr($dir, '..')) {
  6209. $dir = '/';
  6210. }
  6211. if (isset($dir[0]) && $dir[0] == '.') {
  6212. $dir = substr($dir, 1);
  6213. }
  6214. if (isset($dir[0]) && $dir[0] != '/') {
  6215. $dir = '/'.$dir;
  6216. }
  6217. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6218. $dir .= '/';
  6219. }
  6220. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6221. if (!is_dir($filepath)) {
  6222. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6223. }
  6224. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6225. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6226. $document_id = intval($_POST['path']);
  6227. $sql = "SELECT path FROM ".$table_doc."
  6228. WHERE c_id = $course_id AND id = ".$document_id;
  6229. $res = Database::query($sql);
  6230. $row = Database::fetch_array($res);
  6231. $content = stripslashes($_POST['content_lp']);
  6232. $file = $filepath.$row['path'];
  6233. if ($fp = @fopen($file, 'w')) {
  6234. $content = str_replace(
  6235. api_get_path(WEB_COURSE_PATH),
  6236. $urlAppend.api_get_path(REL_COURSE_PATH),
  6237. $content
  6238. );
  6239. // Change the path of mp3 to absolute.
  6240. // The first regexp deals with :// urls.
  6241. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/', $content);
  6242. // The second regexp deals with audio/ urls.
  6243. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/', $content);
  6244. fputs($fp, $content);
  6245. fclose($fp);
  6246. $sql = "UPDATE ".$table_doc." SET
  6247. title='".Database::escape_string($_POST['title'])."'
  6248. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6249. Database::query($sql);
  6250. }
  6251. }
  6252. }
  6253. /**
  6254. * Displays the selected item, with a panel for manipulating the item
  6255. * @param int $item_id
  6256. * @param string $msg
  6257. * @return string
  6258. */
  6259. public function display_item($item_id, $msg = null, $show_actions = true)
  6260. {
  6261. $course_id = api_get_course_int_id();
  6262. $return = '';
  6263. if (is_numeric($item_id)) {
  6264. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6265. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6266. WHERE
  6267. c_id = $course_id AND
  6268. lp.id = ".intval($item_id);
  6269. $result = Database::query($sql);
  6270. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6271. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6272. // Prevents wrong parent selection for document, see Bug#1251.
  6273. if ($row['item_type'] != 'dir') {
  6274. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6275. }
  6276. if ($show_actions) {
  6277. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6278. }
  6279. $return .= '<div style="padding:10px;">';
  6280. if ($msg != '') {
  6281. $return .= $msg;
  6282. }
  6283. $return .= '<h3>'.$row['title'].'</h3>';
  6284. switch ($row['item_type']) {
  6285. case TOOL_THREAD:
  6286. $link = $this->rl_get_resource_link_for_learnpath(
  6287. $course_id,
  6288. $row['lp_id'],
  6289. $item_id,
  6290. 0
  6291. );
  6292. $return .= Display::url(
  6293. get_lang('GoToThread'),
  6294. $link,
  6295. ['class' => 'btn btn-primary']
  6296. );
  6297. break;
  6298. case TOOL_FORUM:
  6299. $return .= Display::url(
  6300. get_lang('GoToForum'),
  6301. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6302. ['class' => 'btn btn-primary']
  6303. );
  6304. break;
  6305. case TOOL_QUIZ:
  6306. if (!empty($row['path'])) {
  6307. $exercise = new Exercise();
  6308. $exercise->read($row['path']);
  6309. $return .= $exercise->description.'<br />';
  6310. $return .= Display::url(
  6311. get_lang('GoToExercise'),
  6312. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6313. ['class' => 'btn btn-primary']
  6314. );
  6315. }
  6316. break;
  6317. case TOOL_LP_FINAL_ITEM:
  6318. $return .= $this->getSavedFinalItem();
  6319. break;
  6320. case TOOL_DOCUMENT:
  6321. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6322. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6323. WHERE c_id = ".$course_id." AND id = ".intval($row['path']);
  6324. $result = Database::query($sql_doc);
  6325. $path_file = Database::result($result, 0, 0);
  6326. $path_parts = pathinfo($path_file);
  6327. // TODO: Correct the following naive comparisons.
  6328. if (in_array($path_parts['extension'], array(
  6329. 'html',
  6330. 'txt',
  6331. 'png',
  6332. 'jpg',
  6333. 'JPG',
  6334. 'jpeg',
  6335. 'JPEG',
  6336. 'gif',
  6337. 'swf',
  6338. 'pdf',
  6339. 'htm'
  6340. ))) {
  6341. $return .= $this->display_document($row['path'], true, true);
  6342. }
  6343. break;
  6344. case TOOL_HOTPOTATOES:
  6345. $return .= $this->display_document($row['path'], false, true);
  6346. break;
  6347. }
  6348. $return .= '</div>';
  6349. }
  6350. }
  6351. return $return;
  6352. }
  6353. /**
  6354. * Shows the needed forms for editing a specific item
  6355. * @param int $item_id
  6356. * @return string
  6357. */
  6358. public function display_edit_item($item_id)
  6359. {
  6360. $course_id = api_get_course_int_id();
  6361. $return = '';
  6362. if (is_numeric($item_id)) {
  6363. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6364. $sql = "SELECT * FROM $tbl_lp_item
  6365. WHERE c_id = ".$course_id." AND id = ".intval($item_id);
  6366. $res = Database::query($sql);
  6367. $row = Database::fetch_array($res);
  6368. switch ($row['item_type']) {
  6369. case 'dir':
  6370. case 'asset':
  6371. case 'sco':
  6372. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6373. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6374. $return .= $this->display_item_form(
  6375. $row['item_type'],
  6376. get_lang('EditCurrentChapter').' :',
  6377. 'edit',
  6378. $item_id,
  6379. $row
  6380. );
  6381. } else {
  6382. $return .= $this->display_item_small_form(
  6383. $row['item_type'],
  6384. get_lang('EditCurrentChapter').' :',
  6385. $row
  6386. );
  6387. }
  6388. break;
  6389. case TOOL_DOCUMENT:
  6390. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6391. $sql = "SELECT lp.*, doc.path as dir
  6392. FROM $tbl_lp_item as lp
  6393. LEFT JOIN $tbl_doc as doc
  6394. ON (doc.id = lp.path AND lp.c_id = doc.c_id)
  6395. WHERE
  6396. lp.c_id = $course_id AND
  6397. doc.c_id = $course_id AND
  6398. lp.id = ".intval($item_id);
  6399. $res_step = Database::query($sql);
  6400. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6401. $return .= $this->display_manipulate(
  6402. $item_id,
  6403. $row['item_type']
  6404. );
  6405. $return .= $this->display_document_form(
  6406. 'edit',
  6407. $item_id,
  6408. $row_step
  6409. );
  6410. break;
  6411. case TOOL_LINK:
  6412. $link_id = (string) $row['path'];
  6413. if (ctype_digit($link_id)) {
  6414. $tbl_link = Database::get_course_table(TABLE_LINK);
  6415. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6416. WHERE c_id = '.$course_id.' AND id = '.intval($link_id);
  6417. $res_link = Database::query($sql_select);
  6418. $row_link = Database::fetch_array($res_link);
  6419. if (is_array($row_link)) {
  6420. $row['url'] = $row_link['url'];
  6421. }
  6422. }
  6423. $return .= $this->display_manipulate(
  6424. $item_id,
  6425. $row['item_type']
  6426. );
  6427. $return .= $this->display_link_form('edit', $item_id, $row);
  6428. break;
  6429. case TOOL_LP_FINAL_ITEM:
  6430. Session::write('finalItem', true);
  6431. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6432. $sql = "SELECT lp.*, doc.path as dir
  6433. FROM $tbl_lp_item as lp
  6434. LEFT JOIN $tbl_doc as doc
  6435. ON (doc.id = lp.path AND lp.c_id = doc.c_id)
  6436. WHERE
  6437. lp.c_id = $course_id AND
  6438. doc.c_id = $course_id AND
  6439. lp.id = ".intval($item_id);
  6440. $res_step = Database::query($sql);
  6441. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6442. $return .= $this->display_manipulate(
  6443. $item_id,
  6444. $row['item_type']
  6445. );
  6446. $return .= $this->display_document_form(
  6447. 'edit',
  6448. $item_id,
  6449. $row_step
  6450. );
  6451. break;
  6452. case TOOL_QUIZ:
  6453. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6454. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6455. break;
  6456. case TOOL_HOTPOTATOES:
  6457. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6458. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6459. break;
  6460. case TOOL_STUDENTPUBLICATION:
  6461. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6462. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6463. break;
  6464. case TOOL_FORUM:
  6465. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6466. $return .= $this->display_forum_form('edit', $item_id, $row);
  6467. break;
  6468. case TOOL_THREAD:
  6469. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6470. $return .= $this->display_thread_form('edit', $item_id, $row);
  6471. break;
  6472. }
  6473. }
  6474. return $return;
  6475. }
  6476. /**
  6477. * Function that displays a list with al the resources that
  6478. * could be added to the learning path
  6479. * @return string
  6480. */
  6481. public function display_resources()
  6482. {
  6483. $course_code = api_get_course_id();
  6484. // Get all the docs.
  6485. $documents = $this->get_documents(true);
  6486. // Get all the exercises.
  6487. $exercises = $this->get_exercises();
  6488. // Get all the links.
  6489. $links = $this->get_links();
  6490. // Get all the student publications.
  6491. $works = $this->get_student_publications();
  6492. // Get all the forums.
  6493. $forums = $this->get_forums(null, $course_code);
  6494. // Get the final item form (see BT#11048) .
  6495. $finish = $this->getFinalItemForm();
  6496. $headers = array(
  6497. Display::return_icon('folder_document.png', get_lang('Documents'), array(), ICON_SIZE_BIG),
  6498. Display::return_icon('quiz.png', get_lang('Quiz'), array(), ICON_SIZE_BIG),
  6499. Display::return_icon('links.png', get_lang('Links'), array(), ICON_SIZE_BIG),
  6500. Display::return_icon('works.png', get_lang('Works'), array(), ICON_SIZE_BIG),
  6501. Display::return_icon('forum.png', get_lang('Forums'), array(), ICON_SIZE_BIG),
  6502. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), array(), ICON_SIZE_BIG),
  6503. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6504. );
  6505. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6506. $dir = $_SESSION['oLP']->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6507. echo Display::tabs(
  6508. $headers,
  6509. array(
  6510. $documents,
  6511. $exercises,
  6512. $links,
  6513. $works,
  6514. $forums,
  6515. $dir,
  6516. $finish,
  6517. ),
  6518. 'resource_tab'
  6519. );
  6520. return true;
  6521. }
  6522. /**
  6523. * Returns the extension of a document
  6524. * @param string $filename
  6525. * @return string Extension (part after the last dot)
  6526. */
  6527. public function get_extension($filename)
  6528. {
  6529. $explode = explode('.', $filename);
  6530. return $explode[count($explode) - 1];
  6531. }
  6532. /**
  6533. * Displays a document by id
  6534. *
  6535. * @param int $id
  6536. * @return string
  6537. */
  6538. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6539. {
  6540. $_course = api_get_course_info();
  6541. $course_id = api_get_course_int_id();
  6542. $return = '';
  6543. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6544. $sql_doc = "SELECT * FROM ".$tbl_doc."
  6545. WHERE c_id = ".$course_id." AND id = ".$id;
  6546. $res_doc = Database::query($sql_doc);
  6547. $row_doc = Database::fetch_array($res_doc);
  6548. // TODO: Add a path filter.
  6549. if ($iframe) {
  6550. $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>';
  6551. } else {
  6552. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6553. }
  6554. return $return;
  6555. }
  6556. /**
  6557. * Return HTML form to add/edit a quiz
  6558. * @param string $action Action (add/edit)
  6559. * @param integer $id Item ID if already exists
  6560. * @param mixed $extra_info Extra information (quiz ID if integer)
  6561. * @return string HTML form
  6562. */
  6563. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6564. {
  6565. $course_id = api_get_course_int_id();
  6566. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6567. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6568. if ($id != 0 && is_array($extra_info)) {
  6569. $item_title = $extra_info['title'];
  6570. $item_description = $extra_info['description'];
  6571. } elseif (is_numeric($extra_info)) {
  6572. $sql = "SELECT title, description
  6573. FROM $tbl_quiz
  6574. WHERE c_id = $course_id AND id = ".$extra_info;
  6575. $result = Database::query($sql);
  6576. $row = Database::fetch_array($result);
  6577. $item_title = $row['title'];
  6578. $item_description = $row['description'];
  6579. } else {
  6580. $item_title = '';
  6581. $item_description = '';
  6582. }
  6583. $item_title = Security::remove_XSS($item_title);
  6584. $item_description = Security::remove_XSS($item_description);
  6585. if ($id != 0 && is_array($extra_info)) {
  6586. $parent = $extra_info['parent_item_id'];
  6587. } else {
  6588. $parent = 0;
  6589. }
  6590. $sql = "SELECT * FROM $tbl_lp_item
  6591. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6592. $result = Database::query($sql);
  6593. $arrLP = array();
  6594. while ($row = Database::fetch_array($result)) {
  6595. $arrLP[] = array(
  6596. 'id' => $row['id'],
  6597. 'item_type' => $row['item_type'],
  6598. 'title' => $row['title'],
  6599. 'path' => $row['path'],
  6600. 'description' => $row['description'],
  6601. 'parent_item_id' => $row['parent_item_id'],
  6602. 'previous_item_id' => $row['previous_item_id'],
  6603. 'next_item_id' => $row['next_item_id'],
  6604. 'display_order' => $row['display_order'],
  6605. 'max_score' => $row['max_score'],
  6606. 'min_score' => $row['min_score'],
  6607. 'mastery_score' => $row['mastery_score'],
  6608. 'prerequisite' => $row['prerequisite'],
  6609. 'max_time_allowed' => $row['max_time_allowed']
  6610. );
  6611. }
  6612. $this->tree_array($arrLP);
  6613. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  6614. unset($this->arrMenu);
  6615. $form = new FormValidator(
  6616. 'quiz_form',
  6617. 'POST',
  6618. $this->getCurrentBuildingModeURL()
  6619. );
  6620. $defaults = [];
  6621. if ($action == 'add') {
  6622. $legend = get_lang('CreateTheExercise');
  6623. } elseif ($action == 'move') {
  6624. $legend = get_lang('MoveTheCurrentExercise');
  6625. } else {
  6626. $legend = get_lang('EditCurrentExecice');
  6627. }
  6628. if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
  6629. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6630. }
  6631. $form->addHeader($legend);
  6632. if ($action != 'move') {
  6633. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  6634. $defaults['title'] = $item_title;
  6635. }
  6636. // Select for Parent item, root or chapter
  6637. $selectParent = $form->addSelect(
  6638. 'parent',
  6639. get_lang('Parent'),
  6640. [],
  6641. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6642. );
  6643. $selectParent->addOption($this->name, 0);
  6644. $arrHide = array(
  6645. $id
  6646. );
  6647. for ($i = 0; $i < count($arrLP); $i++) {
  6648. if ($action != 'add') {
  6649. if (
  6650. ($arrLP[$i]['item_type'] == 'dir') &&
  6651. !in_array($arrLP[$i]['id'], $arrHide) &&
  6652. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6653. ) {
  6654. $selectParent->addOption(
  6655. $arrLP[$i]['title'],
  6656. $arrLP[$i]['id'],
  6657. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6658. );
  6659. if ($parent == $arrLP[$i]['id']) {
  6660. $selectParent->setSelected($arrLP[$i]['id']);
  6661. }
  6662. } else {
  6663. $arrHide[] = $arrLP[$i]['id'];
  6664. }
  6665. } else {
  6666. if ($arrLP[$i]['item_type'] == 'dir') {
  6667. $selectParent->addOption(
  6668. $arrLP[$i]['title'],
  6669. $arrLP[$i]['id'], ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6670. );
  6671. if ($parent == $arrLP[$i]['id']) {
  6672. $selectParent->setSelected($arrLP[$i]['id']);
  6673. }
  6674. }
  6675. }
  6676. }
  6677. if (is_array($arrLP)) {
  6678. reset($arrLP);
  6679. }
  6680. $selectPrevious = $form->addSelect(
  6681. 'previous',
  6682. get_lang('Position'),
  6683. [],
  6684. ['id' => 'previous']
  6685. );
  6686. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6687. for ($i = 0; $i < count($arrLP); $i++) {
  6688. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6689. $arrLP[$i]['id'] != $id
  6690. ) {
  6691. $selectPrevious->addOption(
  6692. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6693. $arrLP[$i]['id']
  6694. );
  6695. if (is_array($extra_info)) {
  6696. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6697. $selectPrevious->setSelected($arrLP[$i]['id']);
  6698. }
  6699. } elseif ($action == 'add') {
  6700. $selectPrevious->setSelected($arrLP[$i]['id']);
  6701. }
  6702. }
  6703. }
  6704. if ($action != 'move') {
  6705. $id_prerequisite = 0;
  6706. if (is_array($arrLP)) {
  6707. foreach ($arrLP as $key => $value) {
  6708. if ($value['id'] == $id) {
  6709. $id_prerequisite = $value['prerequisite'];
  6710. break;
  6711. }
  6712. }
  6713. }
  6714. $arrHide = array();
  6715. for ($i = 0; $i < count($arrLP); $i++) {
  6716. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6717. if (is_array($extra_info)) {
  6718. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6719. $s_selected_position = $arrLP[$i]['id'];
  6720. }
  6721. } elseif ($action == 'add') {
  6722. $s_selected_position = 0;
  6723. }
  6724. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6725. }
  6726. }
  6727. }
  6728. if ($action == 'add') {
  6729. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6730. } else {
  6731. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6732. }
  6733. if ($action == 'move') {
  6734. $form->addHidden('title', $item_title);
  6735. $form->addHidden('description', $item_description);
  6736. }
  6737. if (is_numeric($extra_info)) {
  6738. $form->addHidden('path', $extra_info);
  6739. } elseif (is_array($extra_info)) {
  6740. $form->addHidden('path', $extra_info['path']);
  6741. }
  6742. $form->addHidden('type', TOOL_QUIZ);
  6743. $form->addHidden('post_time', time());
  6744. $form->setDefaults($defaults);
  6745. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6746. }
  6747. /**
  6748. * Addition of Hotpotatoes tests
  6749. * @param string Action
  6750. * @param integer Internal ID of the item
  6751. * @param mixed Extra information - can be an array with title and description indexes
  6752. * @return string HTML structure to display the hotpotatoes addition formular
  6753. */
  6754. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6755. {
  6756. $course_id = api_get_course_int_id();
  6757. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  6758. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6759. if ($id != 0 && is_array($extra_info)) {
  6760. $item_title = stripslashes($extra_info['title']);
  6761. $item_description = stripslashes($extra_info['description']);
  6762. } elseif (is_numeric($extra_info)) {
  6763. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6764. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  6765. WHERE
  6766. c_id = ".$course_id." AND
  6767. path LIKE '" . $uploadPath."/%/%htm%' AND
  6768. id = " . (int) $extra_info."
  6769. ORDER BY id ASC";
  6770. $res_hot = Database::query($sql);
  6771. $row = Database::fetch_array($res_hot);
  6772. $item_title = $row['title'];
  6773. $item_description = $row['description'];
  6774. if (!empty ($row['comment'])) {
  6775. $item_title = $row['comment'];
  6776. }
  6777. } else {
  6778. $item_title = '';
  6779. $item_description = '';
  6780. }
  6781. if ($id != 0 && is_array($extra_info)) {
  6782. $parent = $extra_info['parent_item_id'];
  6783. } else {
  6784. $parent = 0;
  6785. }
  6786. $sql = "SELECT * FROM $tbl_lp_item
  6787. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  6788. $result = Database::query($sql);
  6789. $arrLP = array();
  6790. while ($row = Database::fetch_array($result)) {
  6791. $arrLP[] = array(
  6792. 'id' => $row['id'],
  6793. 'item_type' => $row['item_type'],
  6794. 'title' => $row['title'],
  6795. 'path' => $row['path'],
  6796. 'description' => $row['description'],
  6797. 'parent_item_id' => $row['parent_item_id'],
  6798. 'previous_item_id' => $row['previous_item_id'],
  6799. 'next_item_id' => $row['next_item_id'],
  6800. 'display_order' => $row['display_order'],
  6801. 'max_score' => $row['max_score'],
  6802. 'min_score' => $row['min_score'],
  6803. 'mastery_score' => $row['mastery_score'],
  6804. 'prerequisite' => $row['prerequisite'],
  6805. 'max_time_allowed' => $row['max_time_allowed']
  6806. );
  6807. }
  6808. $legend = '<legend>';
  6809. if ($action == 'add') {
  6810. $legend .= get_lang('CreateTheExercise');
  6811. } elseif ($action == 'move') {
  6812. $legend .= get_lang('MoveTheCurrentExercise');
  6813. } else {
  6814. $legend .= get_lang('EditCurrentExecice');
  6815. }
  6816. if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
  6817. $legend .= Display:: return_message(
  6818. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6819. );
  6820. }
  6821. $legend .= '</legend>';
  6822. $return = '<form method="POST">';
  6823. $return .= $legend;
  6824. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6825. $return .= '<tr>';
  6826. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6827. $return .= '<td class="input">';
  6828. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6829. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6830. $arrHide = array(
  6831. $id
  6832. );
  6833. if (count($arrLP) > 0) {
  6834. for ($i = 0; $i < count($arrLP); $i++) {
  6835. if ($action != 'add') {
  6836. if ($arrLP[$i]['item_type'] == 'dir' &&
  6837. !in_array($arrLP[$i]['id'], $arrHide) &&
  6838. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6839. ) {
  6840. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6841. } else {
  6842. $arrHide[] = $arrLP[$i]['id'];
  6843. }
  6844. } else {
  6845. if ($arrLP[$i]['item_type'] == 'dir')
  6846. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6847. }
  6848. }
  6849. reset($arrLP);
  6850. }
  6851. $return .= '</select>';
  6852. $return .= '</td>';
  6853. $return .= '</tr>';
  6854. $return .= '<tr>';
  6855. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6856. $return .= '<td class="input">';
  6857. $return .= '<select id="previous" name="previous" size="1">';
  6858. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6859. for ($i = 0; $i < count($arrLP); $i++) {
  6860. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6861. if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
  6862. $selected = 'selected="selected" ';
  6863. elseif ($action == 'add') $selected = 'selected="selected" ';
  6864. else
  6865. $selected = '';
  6866. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  6867. }
  6868. }
  6869. $return .= '</select>';
  6870. $return .= '</td>';
  6871. $return .= '</tr>';
  6872. if ($action != 'move') {
  6873. $return .= '<tr>';
  6874. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  6875. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  6876. $return .= '</tr>';
  6877. $id_prerequisite = 0;
  6878. if (is_array($arrLP) && count($arrLP) > 0) {
  6879. foreach ($arrLP as $key => $value) {
  6880. if ($value['id'] == $id) {
  6881. $id_prerequisite = $value['prerequisite'];
  6882. break;
  6883. }
  6884. }
  6885. $arrHide = array();
  6886. for ($i = 0; $i < count($arrLP); $i++) {
  6887. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6888. if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
  6889. $s_selected_position = $arrLP[$i]['id'];
  6890. elseif ($action == 'add') $s_selected_position = 0;
  6891. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6892. }
  6893. }
  6894. }
  6895. }
  6896. $return .= '<tr>';
  6897. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.get_lang('SaveHotpotatoes').'</button></td>';
  6898. $return .= '</tr>';
  6899. $return .= '</table>';
  6900. if ($action == 'move') {
  6901. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  6902. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  6903. }
  6904. if (is_numeric($extra_info)) {
  6905. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  6906. } elseif (is_array($extra_info)) {
  6907. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  6908. }
  6909. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  6910. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  6911. $return .= '</form>';
  6912. return $return;
  6913. }
  6914. /**
  6915. * Return the form to display the forum edit/add option
  6916. * @param string Action (add/edit)
  6917. * @param integer ID of the lp_item if already exists
  6918. * @param mixed Forum ID or title
  6919. * @return string HTML form
  6920. */
  6921. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  6922. {
  6923. $course_id = api_get_course_int_id();
  6924. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6925. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  6926. if ($id != 0 && is_array($extra_info)) {
  6927. $item_title = stripslashes($extra_info['title']);
  6928. } elseif (is_numeric($extra_info)) {
  6929. $sql = "SELECT forum_title as title, forum_comment as comment
  6930. FROM " . $tbl_forum."
  6931. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  6932. $result = Database::query($sql);
  6933. $row = Database::fetch_array($result);
  6934. $item_title = $row['title'];
  6935. $item_description = $row['comment'];
  6936. } else {
  6937. $item_title = '';
  6938. $item_description = '';
  6939. }
  6940. if ($id != 0 && is_array($extra_info)) {
  6941. $parent = $extra_info['parent_item_id'];
  6942. } else {
  6943. $parent = 0;
  6944. }
  6945. $sql = "SELECT * FROM ".$tbl_lp_item."
  6946. WHERE
  6947. c_id = ".$course_id." AND
  6948. lp_id = " . $this->lp_id;
  6949. $result = Database::query($sql);
  6950. $arrLP = array();
  6951. while ($row = Database::fetch_array($result)) {
  6952. $arrLP[] = array(
  6953. 'id' => $row['id'],
  6954. 'item_type' => $row['item_type'],
  6955. 'title' => $row['title'],
  6956. 'path' => $row['path'],
  6957. 'description' => $row['description'],
  6958. 'parent_item_id' => $row['parent_item_id'],
  6959. 'previous_item_id' => $row['previous_item_id'],
  6960. 'next_item_id' => $row['next_item_id'],
  6961. 'display_order' => $row['display_order'],
  6962. 'max_score' => $row['max_score'],
  6963. 'min_score' => $row['min_score'],
  6964. 'mastery_score' => $row['mastery_score'],
  6965. 'prerequisite' => $row['prerequisite']
  6966. );
  6967. }
  6968. $this->tree_array($arrLP);
  6969. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  6970. unset($this->arrMenu);
  6971. if ($action == 'add') {
  6972. $legend = get_lang('CreateTheForum');
  6973. } elseif ($action == 'move') {
  6974. $legend = get_lang('MoveTheCurrentForum');
  6975. } else {
  6976. $legend = get_lang('EditCurrentForum');
  6977. }
  6978. $form = new FormValidator(
  6979. 'forum_form',
  6980. 'POST',
  6981. $this->getCurrentBuildingModeURL()
  6982. );
  6983. $defaults = [];
  6984. $form->addHeader($legend);
  6985. if ($action != 'move') {
  6986. $form->addText(
  6987. 'title',
  6988. get_lang('Title'),
  6989. true,
  6990. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  6991. );
  6992. $defaults['title'] = $item_title;
  6993. }
  6994. $selectParent = $form->addSelect(
  6995. 'parent',
  6996. get_lang('Parent'),
  6997. [],
  6998. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  6999. );
  7000. $selectParent->addOption($this->name, 0);
  7001. $arrHide = array(
  7002. $id
  7003. );
  7004. //$parent_item_id = $_SESSION['parent_item_id'];
  7005. for ($i = 0; $i < count($arrLP); $i++) {
  7006. if ($action != 'add') {
  7007. if ($arrLP[$i]['item_type'] == 'dir' &&
  7008. !in_array($arrLP[$i]['id'], $arrHide) &&
  7009. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7010. ) {
  7011. $selectParent->addOption(
  7012. $arrLP[$i]['title'],
  7013. $arrLP[$i]['id'],
  7014. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7015. );
  7016. if ($parent == $arrLP[$i]['id']) {
  7017. $selectParent->setSelected($arrLP[$i]['id']);
  7018. }
  7019. } else {
  7020. $arrHide[] = $arrLP[$i]['id'];
  7021. }
  7022. } else {
  7023. if ($arrLP[$i]['item_type'] == 'dir') {
  7024. $selectParent->addOption(
  7025. $arrLP[$i]['title'],
  7026. $arrLP[$i]['id'],
  7027. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7028. );
  7029. if ($parent == $arrLP[$i]['id']) {
  7030. $selectParent->setSelected($arrLP[$i]['id']);
  7031. }
  7032. }
  7033. }
  7034. }
  7035. if (is_array($arrLP)) {
  7036. reset($arrLP);
  7037. }
  7038. $selectPrevious = $form->addSelect(
  7039. 'previous',
  7040. get_lang('Position'),
  7041. [],
  7042. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7043. );
  7044. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7045. for ($i = 0; $i < count($arrLP); $i++) {
  7046. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7047. $arrLP[$i]['id'] != $id
  7048. ) {
  7049. $selectPrevious->addOption(
  7050. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7051. $arrLP[$i]['id']
  7052. );
  7053. if (isset($extra_info['previous_item_id']) &&
  7054. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7055. ) {
  7056. $selectPrevious->setSelected($arrLP[$i]['id']);
  7057. } elseif ($action == 'add') {
  7058. $selectPrevious->setSelected($arrLP[$i]['id']);
  7059. }
  7060. }
  7061. }
  7062. if ($action != 'move') {
  7063. $id_prerequisite = 0;
  7064. if (is_array($arrLP)) {
  7065. foreach ($arrLP as $key => $value) {
  7066. if ($value['id'] == $id) {
  7067. $id_prerequisite = $value['prerequisite'];
  7068. break;
  7069. }
  7070. }
  7071. }
  7072. $arrHide = array();
  7073. for ($i = 0; $i < count($arrLP); $i++) {
  7074. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7075. if (isset($extra_info['previous_item_id']) &&
  7076. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7077. ) {
  7078. $s_selected_position = $arrLP[$i]['id'];
  7079. } elseif ($action == 'add') {
  7080. $s_selected_position = 0;
  7081. }
  7082. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7083. }
  7084. }
  7085. }
  7086. if ($action == 'add') {
  7087. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7088. } else {
  7089. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7090. }
  7091. if ($action == 'move') {
  7092. $form->addHidden('title', $item_title);
  7093. $form->addHidden('description', $item_description);
  7094. }
  7095. if (is_numeric($extra_info)) {
  7096. $form->addHidden('path', $extra_info);
  7097. } elseif (is_array($extra_info)) {
  7098. $form->addHidden('path', $extra_info['path']);
  7099. }
  7100. $form->addHidden('type', TOOL_FORUM);
  7101. $form->addHidden('post_time', time());
  7102. $form->setDefaults($defaults);
  7103. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7104. }
  7105. /**
  7106. * Return HTML form to add/edit forum threads
  7107. * @param string Action (add/edit)
  7108. * @param integer Item ID if already exists in learning path
  7109. * @param mixed Extra information (thread ID if integer)
  7110. * @return string HTML form
  7111. */
  7112. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7113. {
  7114. $course_id = api_get_course_int_id();
  7115. if (empty($course_id)) {
  7116. return null;
  7117. }
  7118. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7119. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7120. if ($id != 0 && is_array($extra_info)) {
  7121. $item_title = stripslashes($extra_info['title']);
  7122. } elseif (is_numeric($extra_info)) {
  7123. $sql = "SELECT thread_title as title FROM $tbl_forum
  7124. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7125. $result = Database::query($sql);
  7126. $row = Database::fetch_array($result);
  7127. $item_title = $row['title'];
  7128. $item_description = '';
  7129. } else {
  7130. $item_title = '';
  7131. $item_description = '';
  7132. }
  7133. if ($id != 0 && is_array($extra_info)) {
  7134. $parent = $extra_info['parent_item_id'];
  7135. } else {
  7136. $parent = 0;
  7137. }
  7138. $sql = "SELECT * FROM ".$tbl_lp_item."
  7139. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  7140. $result = Database::query($sql);
  7141. $arrLP = array();
  7142. while ($row = Database::fetch_array($result)) {
  7143. $arrLP[] = array(
  7144. 'id' => $row['id'],
  7145. 'item_type' => $row['item_type'],
  7146. 'title' => $row['title'],
  7147. 'path' => $row['path'],
  7148. 'description' => $row['description'],
  7149. 'parent_item_id' => $row['parent_item_id'],
  7150. 'previous_item_id' => $row['previous_item_id'],
  7151. 'next_item_id' => $row['next_item_id'],
  7152. 'display_order' => $row['display_order'],
  7153. 'max_score' => $row['max_score'],
  7154. 'min_score' => $row['min_score'],
  7155. 'mastery_score' => $row['mastery_score'],
  7156. 'prerequisite' => $row['prerequisite']
  7157. );
  7158. }
  7159. $this->tree_array($arrLP);
  7160. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7161. unset($this->arrMenu);
  7162. $form = new FormValidator(
  7163. 'thread_form',
  7164. 'POST',
  7165. $this->getCurrentBuildingModeURL()
  7166. );
  7167. $defaults = [];
  7168. if ($action == 'add') {
  7169. $legend = get_lang('CreateTheForum');
  7170. } elseif ($action == 'move') {
  7171. $legend = get_lang('MoveTheCurrentForum');
  7172. } else {
  7173. $legend = get_lang('EditCurrentForum');
  7174. }
  7175. $form->addHeader($legend);
  7176. $selectParent = $form->addSelect(
  7177. 'parent',
  7178. get_lang('Parent'),
  7179. [],
  7180. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7181. );
  7182. $selectParent->addOption($this->name, 0);
  7183. $arrHide = array(
  7184. $id
  7185. );
  7186. for ($i = 0; $i < count($arrLP); $i++) {
  7187. if ($action != 'add') {
  7188. if (
  7189. ($arrLP[$i]['item_type'] == 'dir') &&
  7190. !in_array($arrLP[$i]['id'], $arrHide) &&
  7191. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7192. ) {
  7193. $selectParent->addOption(
  7194. $arrLP[$i]['title'],
  7195. $arrLP[$i]['id'],
  7196. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7197. );
  7198. if ($parent == $arrLP[$i]['id']) {
  7199. $selectParent->setSelected($arrLP[$i]['id']);
  7200. }
  7201. } else {
  7202. $arrHide[] = $arrLP[$i]['id'];
  7203. }
  7204. } else {
  7205. if ($arrLP[$i]['item_type'] == 'dir') {
  7206. $selectParent->addOption(
  7207. $arrLP[$i]['title'],
  7208. $arrLP[$i]['id'],
  7209. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7210. );
  7211. if ($parent == $arrLP[$i]['id']) {
  7212. $selectParent->setSelected($arrLP[$i]['id']);
  7213. }
  7214. }
  7215. }
  7216. }
  7217. if ($arrLP != null) {
  7218. reset($arrLP);
  7219. }
  7220. $selectPrevious = $form->addSelect(
  7221. 'previous',
  7222. get_lang('Position'),
  7223. [],
  7224. ['id' => 'previous']
  7225. );
  7226. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7227. for ($i = 0; $i < count($arrLP); $i++) {
  7228. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7229. $selectPrevious->addOption(
  7230. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7231. $arrLP[$i]['id']
  7232. );
  7233. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7234. $selectPrevious->setSelected($arrLP[$i]['id']);
  7235. } elseif ($action == 'add') {
  7236. $selectPrevious->setSelected($arrLP[$i]['id']);
  7237. }
  7238. }
  7239. }
  7240. if ($action != 'move') {
  7241. $form->addText(
  7242. 'title',
  7243. get_lang('Title'),
  7244. true,
  7245. ['id' => 'idTitle']
  7246. );
  7247. $defaults['title'] = $item_title;
  7248. $id_prerequisite = 0;
  7249. if ($arrLP != null) {
  7250. foreach ($arrLP as $key => $value) {
  7251. if ($value['id'] == $id) {
  7252. $id_prerequisite = $value['prerequisite'];
  7253. break;
  7254. }
  7255. }
  7256. }
  7257. $arrHide = array();
  7258. $s_selected_position = 0;
  7259. for ($i = 0; $i < count($arrLP); $i++) {
  7260. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7261. if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
  7262. $s_selected_position = $arrLP[$i]['id'];
  7263. elseif ($action == 'add') $s_selected_position = 0;
  7264. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7265. }
  7266. }
  7267. $selectPrerequisites = $form->addSelect(
  7268. 'prerequisites',
  7269. get_lang('LearnpathPrerequisites'),
  7270. [],
  7271. ['id' => 'prerequisites']
  7272. );
  7273. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7274. foreach ($arrHide as $key => $value) {
  7275. $selectPrerequisites->addOption($value['value'], $key);
  7276. if ($key == $s_selected_position && $action == 'add') {
  7277. $selectPrerequisites->setSelected($key);
  7278. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7279. $selectPrerequisites->setSelected($key);
  7280. }
  7281. }
  7282. }
  7283. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7284. if ($action == 'move') {
  7285. $form->addHidden('title', $item_title);
  7286. $form->addHidden('description', $item_description);
  7287. }
  7288. if (is_numeric($extra_info)) {
  7289. $form->addHidden('path', $extra_info);
  7290. }
  7291. elseif (is_array($extra_info)) {
  7292. $form->addHidden('path', $extra_info['path']);
  7293. }
  7294. $form->addHidden('type', TOOL_THREAD);
  7295. $form->addHidden('post_time', time());
  7296. $form->setDefaults($defaults);
  7297. return $form->returnForm();
  7298. }
  7299. /**
  7300. * Return the HTML form to display an item (generally a dir item)
  7301. * @param string Item type (dir)
  7302. * @param string Title (optional, only when creating)
  7303. * @param string Action ('add'/'edit')
  7304. * @param integer lp_item ID
  7305. * @param mixed Extra info
  7306. * @return string HTML form
  7307. */
  7308. public function display_item_form(
  7309. $item_type,
  7310. $title = '',
  7311. $action = 'add_item',
  7312. $id = 0,
  7313. $extra_info = 'new'
  7314. ) {
  7315. $course_id = api_get_course_int_id();
  7316. $_course = api_get_course_info();
  7317. global $charset;
  7318. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7319. if ($id != 0 && is_array($extra_info)) {
  7320. $item_title = $extra_info['title'];
  7321. $item_description = $extra_info['description'];
  7322. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7323. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7324. } else {
  7325. $item_title = '';
  7326. $item_description = '';
  7327. $item_path_fck = '';
  7328. }
  7329. if ($id != 0 && is_array($extra_info)) {
  7330. $parent = $extra_info['parent_item_id'];
  7331. } else {
  7332. $parent = 0;
  7333. }
  7334. $id = intval($id);
  7335. $sql = "SELECT * FROM ".$tbl_lp_item."
  7336. WHERE
  7337. c_id = ".$course_id." AND
  7338. lp_id = " . $this->lp_id." AND
  7339. id != $id";
  7340. if ($item_type == 'dir') {
  7341. $sql .= " AND parent_item_id = 0";
  7342. }
  7343. $result = Database::query($sql);
  7344. $arrLP = [];
  7345. while ($row = Database::fetch_array($result)) {
  7346. $arrLP[] = array(
  7347. 'id' => $row['id'],
  7348. 'item_type' => $row['item_type'],
  7349. 'title' => $row['title'],
  7350. 'path' => $row['path'],
  7351. 'description' => $row['description'],
  7352. 'parent_item_id' => $row['parent_item_id'],
  7353. 'previous_item_id' => $row['previous_item_id'],
  7354. 'next_item_id' => $row['next_item_id'],
  7355. 'max_score' => $row['max_score'],
  7356. 'min_score' => $row['min_score'],
  7357. 'mastery_score' => $row['mastery_score'],
  7358. 'prerequisite' => $row['prerequisite'],
  7359. 'display_order' => $row['display_order']
  7360. );
  7361. }
  7362. $this->tree_array($arrLP);
  7363. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7364. unset($this->arrMenu);
  7365. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7366. $form = new FormValidator('form', 'POST', $url);
  7367. $defaults['title'] = api_html_entity_decode(
  7368. $item_title,
  7369. ENT_QUOTES,
  7370. $charset
  7371. );
  7372. $defaults['description'] = $item_description;
  7373. $form->addElement('header', $title);
  7374. //$arrHide = array($id);
  7375. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7376. $arrHide[0]['padding'] = 20;
  7377. $charset = api_get_system_encoding();
  7378. for ($i = 0; $i < count($arrLP); $i++) {
  7379. if ($action != 'add') {
  7380. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7381. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7382. ) {
  7383. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7384. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7385. if ($parent == $arrLP[$i]['id']) {
  7386. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7387. }
  7388. }
  7389. } else {
  7390. if ($arrLP[$i]['item_type'] == 'dir') {
  7391. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7392. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7393. if ($parent == $arrLP[$i]['id']) {
  7394. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7395. }
  7396. }
  7397. }
  7398. }
  7399. if ($action != 'move') {
  7400. $form->addElement('text', 'title', get_lang('Title'));
  7401. $form->applyFilter('title', 'html_filter');
  7402. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7403. } else {
  7404. $form->addElement('hidden', 'title');
  7405. }
  7406. $parent_select = $form->addElement(
  7407. 'select',
  7408. 'parent',
  7409. get_lang('Parent'),
  7410. '',
  7411. array(
  7412. 'id' => 'idParent',
  7413. 'onchange' => "javascript: load_cbo(this.value);",
  7414. )
  7415. );
  7416. foreach ($arrHide as $key => $value) {
  7417. $parent_select->addOption(
  7418. $value['value'],
  7419. $key,
  7420. 'style="padding-left:'.$value['padding'].'px;"'
  7421. );
  7422. }
  7423. if (!empty($s_selected_parent)) {
  7424. $parent_select->setSelected($s_selected_parent);
  7425. }
  7426. if (is_array($arrLP)) {
  7427. reset($arrLP);
  7428. }
  7429. $arrHide = array();
  7430. // POSITION
  7431. for ($i = 0; $i < count($arrLP); $i++) {
  7432. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7433. //this is the same!
  7434. if (isset($extra_info['previous_item_id']) &&
  7435. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7436. ) {
  7437. $s_selected_position = $arrLP[$i]['id'];
  7438. } elseif ($action == 'add') {
  7439. $s_selected_position = $arrLP[$i]['id'];
  7440. }
  7441. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7442. }
  7443. }
  7444. $position = $form->addElement(
  7445. 'select',
  7446. 'previous',
  7447. get_lang('Position'),
  7448. '',
  7449. array('id' => 'previous')
  7450. );
  7451. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7452. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7453. foreach ($arrHide as $key => $value) {
  7454. $position->addOption($value['value'].'"', $key, 'style="padding-left:'.$padding.'px;"');
  7455. }
  7456. if (!empty ($s_selected_position)) {
  7457. $position->setSelected($s_selected_position);
  7458. }
  7459. if (is_array($arrLP)) {
  7460. reset($arrLP);
  7461. }
  7462. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7463. //fix in order to use the tab
  7464. if ($item_type == 'dir') {
  7465. $form->addElement('hidden', 'type', 'dir');
  7466. }
  7467. $extension = null;
  7468. if (!empty($item_path)) {
  7469. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7470. }
  7471. //assets can't be modified
  7472. //$item_type == 'asset' ||
  7473. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7474. if ($item_type == 'sco') {
  7475. $form->addElement(
  7476. 'html',
  7477. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7478. );
  7479. }
  7480. $renderer = $form->defaultRenderer();
  7481. $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
  7482. $relative_prefix = '';
  7483. $editor_config = array(
  7484. 'ToolbarSet' => 'LearningPathDocuments',
  7485. 'Width' => '100%',
  7486. 'Height' => '500',
  7487. 'FullPage' => true,
  7488. 'CreateDocumentDir' => $relative_prefix,
  7489. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7490. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck
  7491. );
  7492. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7493. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7494. $defaults['content_lp'] = file_get_contents($content_path);
  7495. }
  7496. $form->addElement('hidden', 'type', $item_type);
  7497. $form->addElement('hidden', 'post_time', time());
  7498. $form->setDefaults($defaults);
  7499. return $form->return_form();
  7500. }
  7501. /**
  7502. * @return string
  7503. */
  7504. public function getCurrentBuildingModeURL()
  7505. {
  7506. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7507. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7508. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7509. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7510. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7511. return $currentUrl;
  7512. }
  7513. /**
  7514. * Returns the form to update or create a document
  7515. * @param string $action (add/edit)
  7516. * @param integer $id ID of the lp_item (if already exists)
  7517. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7518. * @return string HTML form
  7519. */
  7520. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7521. {
  7522. $course_id = api_get_course_int_id();
  7523. $_course = api_get_course_info();
  7524. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7525. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7526. $no_display_edit_textarea = false;
  7527. $item_description = '';
  7528. //If action==edit document
  7529. //We don't display the document form if it's not an editable document (html or txt file)
  7530. if ($action == 'edit') {
  7531. if (is_array($extra_info)) {
  7532. $path_parts = pathinfo($extra_info['dir']);
  7533. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7534. $no_display_edit_textarea = true;
  7535. }
  7536. }
  7537. }
  7538. $no_display_add = false;
  7539. // If action==add an existing document
  7540. // We don't display the document form if it's not an editable document (html or txt file).
  7541. if ($action == 'add') {
  7542. if (is_numeric($extra_info)) {
  7543. $sql_doc = "SELECT path FROM $tbl_doc
  7544. WHERE c_id = $course_id AND id = ".intval($extra_info);
  7545. $result = Database::query($sql_doc);
  7546. $path_file = Database::result($result, 0, 0);
  7547. $path_parts = pathinfo($path_file);
  7548. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7549. $no_display_add = true;
  7550. }
  7551. }
  7552. }
  7553. if ($id != 0 && is_array($extra_info)) {
  7554. $item_title = stripslashes($extra_info['title']);
  7555. $item_description = stripslashes($extra_info['description']);
  7556. $item_terms = stripslashes($extra_info['terms']);
  7557. if (empty ($item_title)) {
  7558. $path_parts = pathinfo($extra_info['path']);
  7559. $item_title = stripslashes($path_parts['filename']);
  7560. }
  7561. } elseif (is_numeric($extra_info)) {
  7562. $sql = "SELECT path, title FROM $tbl_doc
  7563. WHERE
  7564. c_id = ".$course_id." AND
  7565. id = " . intval($extra_info);
  7566. $result = Database::query($sql);
  7567. $row = Database::fetch_array($result);
  7568. $item_title = $row['title'];
  7569. $item_title = str_replace('_', ' ', $item_title);
  7570. if (empty ($item_title)) {
  7571. $path_parts = pathinfo($row['path']);
  7572. $item_title = stripslashes($path_parts['filename']);
  7573. }
  7574. } else {
  7575. $item_title = '';
  7576. $item_description = '';
  7577. }
  7578. $return = '<legend>';
  7579. if ($id != 0 && is_array($extra_info)) {
  7580. $parent = $extra_info['parent_item_id'];
  7581. } else {
  7582. $parent = 0;
  7583. }
  7584. $sql = "SELECT * FROM $tbl_lp_item
  7585. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7586. $result = Database::query($sql);
  7587. $arrLP = array();
  7588. while ($row = Database::fetch_array($result)) {
  7589. $arrLP[] = array(
  7590. 'id' => $row['id'],
  7591. 'item_type' => $row['item_type'],
  7592. 'title' => $row['title'],
  7593. 'path' => $row['path'],
  7594. 'description' => $row['description'],
  7595. 'parent_item_id' => $row['parent_item_id'],
  7596. 'previous_item_id' => $row['previous_item_id'],
  7597. 'next_item_id' => $row['next_item_id'],
  7598. 'display_order' => $row['display_order'],
  7599. 'max_score' => $row['max_score'],
  7600. 'min_score' => $row['min_score'],
  7601. 'mastery_score' => $row['mastery_score'],
  7602. 'prerequisite' => $row['prerequisite']
  7603. );
  7604. }
  7605. $this->tree_array($arrLP);
  7606. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7607. unset($this->arrMenu);
  7608. if ($action == 'add') {
  7609. $return .= get_lang('CreateTheDocument');
  7610. } elseif ($action == 'move') {
  7611. $return .= get_lang('MoveTheCurrentDocument');
  7612. } else {
  7613. $return .= get_lang('EditTheCurrentDocument');
  7614. }
  7615. $return .= '</legend>';
  7616. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7617. $return .= Display::return_message(
  7618. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7619. false
  7620. );
  7621. }
  7622. $form = new FormValidator(
  7623. 'form',
  7624. 'POST',
  7625. $this->getCurrentBuildingModeURL(),
  7626. '',
  7627. array('enctype' => 'multipart/form-data')
  7628. );
  7629. $defaults['title'] = Security::remove_XSS($item_title);
  7630. if (empty($item_title)) {
  7631. $defaults['title'] = Security::remove_XSS($item_title);
  7632. }
  7633. $defaults['description'] = $item_description;
  7634. $form->addElement('html', $return);
  7635. if ($action != 'move') {
  7636. $data = $this->generate_lp_folder($_course);
  7637. if ($action != 'edit') {
  7638. $folders = DocumentManager::get_all_document_folders(
  7639. $_course,
  7640. 0,
  7641. true
  7642. );
  7643. DocumentManager::build_directory_selector(
  7644. $folders,
  7645. '',
  7646. array(),
  7647. true,
  7648. $form,
  7649. 'directory_parent_id'
  7650. );
  7651. }
  7652. if (isset($data['id'])) {
  7653. $defaults['directory_parent_id'] = $data['id'];
  7654. }
  7655. $form->addElement(
  7656. 'text',
  7657. 'title',
  7658. get_lang('Title'),
  7659. array('id' => 'idTitle', 'class' => 'col-md-4')
  7660. );
  7661. $form->applyFilter('title', 'html_filter');
  7662. }
  7663. $arrHide[0]['value'] = $this->name;
  7664. $arrHide[0]['padding'] = 20;
  7665. for ($i = 0; $i < count($arrLP); $i++) {
  7666. if ($action != 'add') {
  7667. if ($arrLP[$i]['item_type'] == 'dir' &&
  7668. !in_array($arrLP[$i]['id'], $arrHide) &&
  7669. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7670. ) {
  7671. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7672. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7673. if ($parent == $arrLP[$i]['id']) {
  7674. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7675. }
  7676. }
  7677. } else {
  7678. if ($arrLP[$i]['item_type'] == 'dir') {
  7679. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7680. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7681. if ($parent == $arrLP[$i]['id']) {
  7682. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7683. }
  7684. }
  7685. }
  7686. }
  7687. $parent_select = $form->addSelect(
  7688. 'parent',
  7689. get_lang('Parent'),
  7690. [],
  7691. [
  7692. 'id' => 'idParent',
  7693. 'onchange' => 'javascript: load_cbo(this.value);',
  7694. ]
  7695. );
  7696. $my_count = 0;
  7697. foreach ($arrHide as $key => $value) {
  7698. if ($my_count != 0) {
  7699. // The LP name is also the first section and is not in the same charset like the other sections.
  7700. $value['value'] = Security::remove_XSS($value['value']);
  7701. $parent_select->addOption(
  7702. $value['value'],
  7703. $key,
  7704. 'style="padding-left:'.$value['padding'].'px;"'
  7705. );
  7706. } else {
  7707. $value['value'] = Security::remove_XSS($value['value']);
  7708. $parent_select->addOption(
  7709. $value['value'],
  7710. $key,
  7711. 'style="padding-left:'.$value['padding'].'px;"'
  7712. );
  7713. }
  7714. $my_count++;
  7715. }
  7716. if (!empty($id)) {
  7717. $parent_select->setSelected($parent);
  7718. } else {
  7719. $parent_item_id = Session::read('parent_item_id', 0);
  7720. $parent_select->setSelected($parent_item_id);
  7721. }
  7722. if (is_array($arrLP)) {
  7723. reset($arrLP);
  7724. }
  7725. $arrHide = array();
  7726. $s_selected_position = null;
  7727. // POSITION
  7728. $lastPosition = null;
  7729. for ($i = 0; $i < count($arrLP); $i++) {
  7730. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7731. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7732. ) {
  7733. if ((isset($extra_info['previous_item_id']) &&
  7734. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  7735. ) {
  7736. $s_selected_position = $arrLP[$i]['id'];
  7737. }
  7738. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7739. }
  7740. $lastPosition = $arrLP[$i]['id'];
  7741. }
  7742. if (empty($s_selected_position)) {
  7743. $s_selected_position = $lastPosition;
  7744. }
  7745. $position = $form->addSelect(
  7746. 'previous',
  7747. get_lang('Position'),
  7748. [],
  7749. ['id' => 'previous']
  7750. );
  7751. $position->addOption(get_lang('FirstPosition'), 0);
  7752. foreach ($arrHide as $key => $value) {
  7753. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7754. $position->addOption(
  7755. $value['value'],
  7756. $key,
  7757. 'style="padding-left:'.$padding.'px;"'
  7758. );
  7759. }
  7760. $position->setSelected($s_selected_position);
  7761. if (is_array($arrLP)) {
  7762. reset($arrLP);
  7763. }
  7764. if ($action != 'move') {
  7765. $id_prerequisite = 0;
  7766. if (is_array($arrLP)) {
  7767. foreach ($arrLP as $key => $value) {
  7768. if ($value['id'] == $id) {
  7769. $id_prerequisite = $value['prerequisite'];
  7770. break;
  7771. }
  7772. }
  7773. }
  7774. $arrHide = array();
  7775. for ($i = 0; $i < count($arrLP); $i++) {
  7776. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7777. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7778. ) {
  7779. if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7780. $s_selected_position = $arrLP[$i]['id'];
  7781. } elseif ($action == 'add') {
  7782. $s_selected_position = $arrLP[$i]['id'];
  7783. }
  7784. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7785. }
  7786. }
  7787. if (!$no_display_add) {
  7788. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7789. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7790. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true') {
  7791. if (isset ($_POST['content'])) {
  7792. $content = stripslashes($_POST['content']);
  7793. } elseif (is_array($extra_info)) {
  7794. //If it's an html document or a text file
  7795. if (!$no_display_edit_textarea) {
  7796. $content = $this->display_document(
  7797. $extra_info['path'],
  7798. false,
  7799. false
  7800. );
  7801. }
  7802. } elseif (is_numeric($extra_info)) {
  7803. $content = $this->display_document(
  7804. $extra_info,
  7805. false,
  7806. false
  7807. );
  7808. } else {
  7809. $content = '';
  7810. }
  7811. if (!$no_display_edit_textarea) {
  7812. // We need to calculate here some specific settings for the online editor.
  7813. // The calculated settings work for documents in the Documents tool
  7814. // (on the root or in subfolders).
  7815. // For documents in native scorm packages it is unclear whether the
  7816. // online editor should be activated or not.
  7817. // A new document, it is in the root of the repository.
  7818. $relative_path = '';
  7819. $relative_prefix = '';
  7820. if (is_array($extra_info) && $extra_info != 'new') {
  7821. // The document already exists. Whe have to determine its relative path towards the repository root.
  7822. $relative_path = explode('/', $extra_info['dir']);
  7823. $cnt = count($relative_path) - 2;
  7824. if ($cnt < 0) {
  7825. $cnt = 0;
  7826. }
  7827. $relative_prefix = str_repeat('../', $cnt);
  7828. $relative_path = array_slice($relative_path, 1, $cnt);
  7829. $relative_path = implode('/', $relative_path);
  7830. if (strlen($relative_path) > 0) {
  7831. $relative_path = $relative_path.'/';
  7832. }
  7833. } else {
  7834. $result = $this->generate_lp_folder($_course);
  7835. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7836. $relative_prefix = '../../';
  7837. }
  7838. $editor_config = array(
  7839. 'ToolbarSet' => 'LearningPathDocuments',
  7840. 'Width' => '100%',
  7841. 'Height' => '500',
  7842. 'FullPage' => true,
  7843. 'CreateDocumentDir' => $relative_prefix,
  7844. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7845. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path
  7846. );
  7847. if ($_GET['action'] == 'add_item') {
  7848. $class = 'add';
  7849. $text = get_lang('LPCreateDocument');
  7850. } else {
  7851. if ($_GET['action'] == 'edit_item') {
  7852. $class = 'save';
  7853. $text = get_lang('SaveDocument');
  7854. }
  7855. }
  7856. $form->addButtonSave($text, 'submit_button');
  7857. $renderer = $form->defaultRenderer();
  7858. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7859. $form->addElement('html', '<div class="editor-lp">');
  7860. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7861. $form->addElement('html', '</div>');
  7862. $defaults['content_lp'] = $content;
  7863. }
  7864. } elseif (is_numeric($extra_info)) {
  7865. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7866. $return = $this->display_document($extra_info, true, true, true);
  7867. $form->addElement('html', $return);
  7868. }
  7869. }
  7870. }
  7871. if (isset($extra_info['item_type']) &&
  7872. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7873. ) {
  7874. $parent_select->freeze();
  7875. $position->freeze();
  7876. }
  7877. if ($action == 'move') {
  7878. $form->addElement('hidden', 'title', $item_title);
  7879. $form->addElement('hidden', 'description', $item_description);
  7880. }
  7881. if (is_numeric($extra_info)) {
  7882. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7883. $form->addElement('hidden', 'path', $extra_info);
  7884. } elseif (is_array($extra_info)) {
  7885. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7886. $form->addElement('hidden', 'path', $extra_info['path']);
  7887. }
  7888. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7889. $form->addElement('hidden', 'post_time', time());
  7890. $form->setDefaults($defaults);
  7891. return $form->returnForm();
  7892. }
  7893. /**
  7894. * Return HTML form to add/edit a link item
  7895. * @param string $action (add/edit)
  7896. * @param integer $id Item ID if exists
  7897. * @param mixed $extra_info
  7898. * @return string HTML form
  7899. */
  7900. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  7901. {
  7902. $course_id = api_get_course_int_id();
  7903. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7904. $tbl_link = Database::get_course_table(TABLE_LINK);
  7905. if ($id != 0 && is_array($extra_info)) {
  7906. $item_title = stripslashes($extra_info['title']);
  7907. $item_description = stripslashes($extra_info['description']);
  7908. $item_url = stripslashes($extra_info['url']);
  7909. } elseif (is_numeric($extra_info)) {
  7910. $extra_info = intval($extra_info);
  7911. $sql = "SELECT title, description, url FROM ".$tbl_link."
  7912. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  7913. $result = Database::query($sql);
  7914. $row = Database::fetch_array($result);
  7915. $item_title = $row['title'];
  7916. $item_description = $row['description'];
  7917. $item_url = $row['url'];
  7918. } else {
  7919. $item_title = '';
  7920. $item_description = '';
  7921. $item_url = '';
  7922. }
  7923. $form = new FormValidator(
  7924. 'edit_link',
  7925. 'POST',
  7926. $this->getCurrentBuildingModeURL()
  7927. );
  7928. $defaults = [];
  7929. if ($id != 0 && is_array($extra_info)) {
  7930. $parent = $extra_info['parent_item_id'];
  7931. } else {
  7932. $parent = 0;
  7933. }
  7934. $sql = "SELECT * FROM ".$tbl_lp_item."
  7935. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  7936. $result = Database::query($sql);
  7937. $arrLP = array();
  7938. while ($row = Database::fetch_array($result)) {
  7939. $arrLP[] = array(
  7940. 'id' => $row['id'],
  7941. 'item_type' => $row['item_type'],
  7942. 'title' => $row['title'],
  7943. 'path' => $row['path'],
  7944. 'description' => $row['description'],
  7945. 'parent_item_id' => $row['parent_item_id'],
  7946. 'previous_item_id' => $row['previous_item_id'],
  7947. 'next_item_id' => $row['next_item_id'],
  7948. 'display_order' => $row['display_order'],
  7949. 'max_score' => $row['max_score'],
  7950. 'min_score' => $row['min_score'],
  7951. 'mastery_score' => $row['mastery_score'],
  7952. 'prerequisite' => $row['prerequisite']
  7953. );
  7954. }
  7955. $this->tree_array($arrLP);
  7956. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7957. unset($this->arrMenu);
  7958. if ($action == 'add') {
  7959. $legend = get_lang('CreateTheLink');
  7960. } elseif ($action == 'move') {
  7961. $legend = get_lang('MoveCurrentLink');
  7962. } else {
  7963. $legend = get_lang('EditCurrentLink');
  7964. }
  7965. $form->addHeader($legend);
  7966. if ($action != 'move') {
  7967. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  7968. $defaults['title'] = $item_title;
  7969. }
  7970. $selectParent = $form->addSelect(
  7971. 'parent',
  7972. get_lang('Parent'),
  7973. [],
  7974. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7975. );
  7976. $selectParent->addOption($this->name, 0);
  7977. $arrHide = array(
  7978. $id
  7979. );
  7980. $parent_item_id = Session::read('parent_item_id', 0);
  7981. for ($i = 0; $i < count($arrLP); $i++) {
  7982. if ($action != 'add') {
  7983. if (
  7984. ($arrLP[$i]['item_type'] == 'dir') &&
  7985. !in_array($arrLP[$i]['id'], $arrHide) &&
  7986. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7987. ) {
  7988. $selectParent->addOption(
  7989. $arrLP[$i]['title'],
  7990. $arrLP[$i]['id'],
  7991. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  7992. );
  7993. if ($parent == $arrLP[$i]['id']) {
  7994. $selectParent->setSelected($arrLP[$i]['id']);
  7995. }
  7996. } else {
  7997. $arrHide[] = $arrLP[$i]['id'];
  7998. }
  7999. } else {
  8000. if ($arrLP[$i]['item_type'] == 'dir') {
  8001. $selectParent->addOption(
  8002. $arrLP[$i]['title'],
  8003. $arrLP[$i]['id'],
  8004. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8005. );
  8006. if ($parent_item_id == $arrLP[$i]['id']) {
  8007. $selectParent->setSelected($arrLP[$i]['id']);
  8008. }
  8009. }
  8010. }
  8011. }
  8012. if (is_array($arrLP)) {
  8013. reset($arrLP);
  8014. }
  8015. $selectPrevious = $form->addSelect(
  8016. 'previous',
  8017. get_lang('Position'),
  8018. [],
  8019. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8020. );
  8021. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8022. for ($i = 0; $i < count($arrLP); $i++) {
  8023. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8024. $selectPrevious->addOption(
  8025. $arrLP[$i]['title'],
  8026. $arrLP[$i]['id']
  8027. );
  8028. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8029. $selectPrevious->setSelected($arrLP[$i]['id']);
  8030. } elseif ($action == 'add') {
  8031. $selectPrevious->setSelected($arrLP[$i]['id']);
  8032. }
  8033. }
  8034. }
  8035. if ($action != 'move') {
  8036. $urlAttributes = ['class' => 'learnpath_item_form'];
  8037. if (is_numeric($extra_info)) {
  8038. $urlAttributes['disabled'] = 'disabled';
  8039. }
  8040. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8041. $defaults['url'] = $item_url;
  8042. $id_prerequisite = 0;
  8043. if (is_array($arrLP)) {
  8044. foreach ($arrLP as $key => $value) {
  8045. if ($value['id'] == $id) {
  8046. $id_prerequisite = $value['prerequisite'];
  8047. break;
  8048. }
  8049. }
  8050. }
  8051. $arrHide = array();
  8052. for ($i = 0; $i < count($arrLP); $i++) {
  8053. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8054. if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
  8055. $s_selected_position = $arrLP[$i]['id'];
  8056. elseif ($action == 'add') $s_selected_position = 0;
  8057. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8058. }
  8059. }
  8060. }
  8061. if ($action == 'add') {
  8062. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8063. } else {
  8064. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8065. }
  8066. if ($action == 'move') {
  8067. $form->addHidden('title', $item_title);
  8068. $form->addHidden('description', $item_description);
  8069. }
  8070. if (is_numeric($extra_info)) {
  8071. $form->addHidden('path', $extra_info);
  8072. } elseif (is_array($extra_info)) {
  8073. $form->addHidden('path', $extra_info['path']);
  8074. }
  8075. $form->addHidden('type', TOOL_LINK);
  8076. $form->addHidden('post_time', time());
  8077. $form->setDefaults($defaults);
  8078. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8079. }
  8080. /**
  8081. * Return HTML form to add/edit a student publication (work)
  8082. * @param string Action (add/edit)
  8083. * @param integer Item ID if already exists
  8084. * @param mixed Extra info (work ID if integer)
  8085. * @return string HTML form
  8086. */
  8087. public function display_student_publication_form(
  8088. $action = 'add',
  8089. $id = 0,
  8090. $extra_info = ''
  8091. ) {
  8092. $course_id = api_get_course_int_id();
  8093. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8094. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8095. if ($id != 0 && is_array($extra_info)) {
  8096. $item_title = stripslashes($extra_info['title']);
  8097. $item_description = stripslashes($extra_info['description']);
  8098. } elseif (is_numeric($extra_info)) {
  8099. $extra_info = intval($extra_info);
  8100. $sql = "SELECT title, description
  8101. FROM $tbl_publication
  8102. WHERE c_id = $course_id AND id = ".$extra_info;
  8103. $result = Database::query($sql);
  8104. $row = Database::fetch_array($result);
  8105. $item_title = $row['title'];
  8106. } else {
  8107. $item_title = get_lang('Student_publication');
  8108. }
  8109. if ($id != 0 && is_array($extra_info)) {
  8110. $parent = $extra_info['parent_item_id'];
  8111. } else {
  8112. $parent = 0;
  8113. }
  8114. $sql = "SELECT * FROM $tbl_lp_item
  8115. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8116. $result = Database::query($sql);
  8117. $arrLP = array();
  8118. while ($row = Database::fetch_array($result)) {
  8119. $arrLP[] = array(
  8120. 'id' => $row['id'],
  8121. 'item_type' => $row['item_type'],
  8122. 'title' => $row['title'],
  8123. 'path' => $row['path'],
  8124. 'description' => $row['description'],
  8125. 'parent_item_id' => $row['parent_item_id'],
  8126. 'previous_item_id' => $row['previous_item_id'],
  8127. 'next_item_id' => $row['next_item_id'],
  8128. 'display_order' => $row['display_order'],
  8129. 'max_score' => $row['max_score'],
  8130. 'min_score' => $row['min_score'],
  8131. 'mastery_score' => $row['mastery_score'],
  8132. 'prerequisite' => $row['prerequisite']
  8133. );
  8134. }
  8135. $this->tree_array($arrLP);
  8136. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8137. unset($this->arrMenu);
  8138. $form = new FormValidator('frm_student_publication', 'post', '#');
  8139. if ($action == 'add') {
  8140. $form->addHeader(get_lang('Student_publication'));
  8141. } elseif ($action == 'move') {
  8142. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8143. } else {
  8144. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8145. }
  8146. if ($action != 'move') {
  8147. $form->addText(
  8148. 'title',
  8149. get_lang('Title'),
  8150. true,
  8151. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8152. );
  8153. }
  8154. $parentSelect = $form->addSelect(
  8155. 'parent',
  8156. get_lang('Parent'),
  8157. ['0' => $this->name],
  8158. [
  8159. 'onchange' => 'javascript: load_cbo(this.value);',
  8160. 'class' => 'learnpath_item_form',
  8161. 'id' => 'idParent'
  8162. ]
  8163. );
  8164. $arrHide = array($id);
  8165. for ($i = 0; $i < count($arrLP); $i++) {
  8166. if ($action != 'add') {
  8167. if (
  8168. ($arrLP[$i]['item_type'] == 'dir') &&
  8169. !in_array($arrLP[$i]['id'], $arrHide) &&
  8170. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8171. ) {
  8172. $parentSelect->addOption(
  8173. $arrLP[$i]['title'],
  8174. $arrLP[$i]['id'],
  8175. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8176. );
  8177. if ($parent == $arrLP[$i]['id']) {
  8178. $parentSelect->setSelected($arrLP[$i]['id']);
  8179. }
  8180. } else {
  8181. $arrHide[] = $arrLP[$i]['id'];
  8182. }
  8183. } else {
  8184. if ($arrLP[$i]['item_type'] == 'dir') {
  8185. $parentSelect->addOption(
  8186. $arrLP[$i]['title'],
  8187. $arrLP[$i]['id'],
  8188. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8189. );
  8190. if ($parent == $arrLP[$i]['id']) {
  8191. $parentSelect->setSelected($arrLP[$i]['id']);
  8192. }
  8193. }
  8194. }
  8195. }
  8196. if (is_array($arrLP)) {
  8197. reset($arrLP);
  8198. }
  8199. $previousSelect = $form->addSelect(
  8200. 'previous',
  8201. get_lang('Position'),
  8202. ['0' => get_lang('FirstPosition')],
  8203. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8204. );
  8205. for ($i = 0; $i < count($arrLP); $i++) {
  8206. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8207. $previousSelect->addOption(
  8208. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8209. $arrLP[$i]['id']
  8210. );
  8211. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8212. $previousSelect->setSelected($arrLP[$i]['id']);
  8213. } elseif ($action == 'add') {
  8214. $previousSelect->setSelected($arrLP[$i]['id']);
  8215. }
  8216. }
  8217. }
  8218. if ($action != 'move') {
  8219. $id_prerequisite = 0;
  8220. if (is_array($arrLP)) {
  8221. foreach ($arrLP as $key => $value) {
  8222. if ($value['id'] == $id) {
  8223. $id_prerequisite = $value['prerequisite'];
  8224. break;
  8225. }
  8226. }
  8227. }
  8228. $arrHide = array();
  8229. for ($i = 0; $i < count($arrLP); $i++) {
  8230. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8231. if ($extra_info['previous_item_id'] == $arrLP[$i]['id'])
  8232. $s_selected_position = $arrLP[$i]['id'];
  8233. elseif ($action == 'add') $s_selected_position = 0;
  8234. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8235. }
  8236. }
  8237. }
  8238. if ($action == 'add') {
  8239. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8240. } else {
  8241. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8242. }
  8243. if ($action == 'move') {
  8244. $form->addHidden('title', $item_title);
  8245. $form->addHidden('description', $item_description);
  8246. }
  8247. if (is_numeric($extra_info)) {
  8248. $form->addHidden('path', $extra_info);
  8249. } elseif (is_array($extra_info)) {
  8250. $form->addHidden('path', $extra_info['path']);
  8251. }
  8252. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8253. $form->addHidden('post_time', time());
  8254. $form->setDefaults(['title' => $item_title]);
  8255. $return = '<div class="sectioncomment">';
  8256. $return .= $form->returnForm();
  8257. $return .= '</div>';
  8258. return $return;
  8259. }
  8260. /**
  8261. * Displays the menu for manipulating a step
  8262. *
  8263. * @param $item_id
  8264. * @param string $item_type
  8265. * @return string
  8266. */
  8267. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8268. {
  8269. $_course = api_get_course_info();
  8270. $course_id = api_get_course_int_id();
  8271. $course_code = api_get_course_id();
  8272. $return = '<div class="actions">';
  8273. switch ($item_type) {
  8274. case 'dir':
  8275. // Commented the message cause should not show it.
  8276. //$lang = get_lang('TitleManipulateChapter');
  8277. break;
  8278. case TOOL_LP_FINAL_ITEM:
  8279. case TOOL_DOCUMENT:
  8280. // Commented the message cause should not show it.
  8281. //$lang = get_lang('TitleManipulateDocument');
  8282. break;
  8283. case TOOL_LINK:
  8284. case 'link' :
  8285. // Commented the message cause should not show it.
  8286. //$lang = get_lang('TitleManipulateLink');
  8287. break;
  8288. case TOOL_QUIZ:
  8289. // Commented the message cause should not show it.
  8290. //$lang = get_lang('TitleManipulateQuiz');
  8291. break;
  8292. case TOOL_STUDENTPUBLICATION:
  8293. // Commented the message cause should not show it.
  8294. //$lang = get_lang('TitleManipulateStudentPublication');
  8295. break;
  8296. }
  8297. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8298. $item_id = intval($item_id);
  8299. $sql = "SELECT * FROM ".$tbl_lp_item." as lp
  8300. WHERE lp.c_id = ".$course_id." AND lp.id = ".$item_id;
  8301. $result = Database::query($sql);
  8302. $row = Database::fetch_assoc($result);
  8303. $audio_player = null;
  8304. // We display an audio player if needed.
  8305. if (!empty($row['audio'])) {
  8306. $audio_player .= '<div class="lp_mediaplayer" id="container">
  8307. <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
  8308. </div>';
  8309. $audio_player .= api_get_js('js/mediaplayer/swfobject.js');
  8310. $audio_player .= '<script>
  8311. var s1 = new SWFObject("'.api_get_path(WEB_LIBRARY_JS_PATH).'mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
  8312. s1.addParam("allowscriptaccess","always");
  8313. s1.addParam("flashvars","file=../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'].'&autostart=true");
  8314. s1.write("container");
  8315. </script>';
  8316. }
  8317. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8318. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8319. $return .= Display::url(
  8320. Display::return_icon(
  8321. 'edit.png',
  8322. get_lang('Edit'),
  8323. array(),
  8324. ICON_SIZE_SMALL
  8325. ),
  8326. $url.'&action=edit_item&path_item='.$row['path']
  8327. );
  8328. $return .= Display::url(
  8329. Display::return_icon(
  8330. 'move.png',
  8331. get_lang('Move'),
  8332. array(),
  8333. ICON_SIZE_SMALL
  8334. ),
  8335. $url.'&action=move_item'
  8336. );
  8337. }
  8338. // Commented for now as prerequisites cannot be added to chapters.
  8339. if ($item_type != 'dir') {
  8340. $return .= Display::url(
  8341. Display::return_icon(
  8342. 'accept.png',
  8343. get_lang('LearnpathPrerequisites'),
  8344. array(),
  8345. ICON_SIZE_SMALL
  8346. ),
  8347. $url.'&action=edit_item_prereq'
  8348. );
  8349. }
  8350. $return .= Display::url(
  8351. Display::return_icon(
  8352. 'delete.png',
  8353. get_lang('Delete'),
  8354. array(),
  8355. ICON_SIZE_SMALL
  8356. ),
  8357. $url.'&action=delete_item'
  8358. );
  8359. if ($item_type == TOOL_HOTPOTATOES) {
  8360. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8361. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8362. }
  8363. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  8364. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8365. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8366. }
  8367. $return .= '</div>';
  8368. if (!empty($audio_player)) {
  8369. $return .= '<br />'.$audio_player;
  8370. }
  8371. return $return;
  8372. }
  8373. /**
  8374. * Creates the javascript needed for filling up the checkboxes without page reload
  8375. * @return string
  8376. */
  8377. public function get_js_dropdown_array()
  8378. {
  8379. $course_id = api_get_course_int_id();
  8380. $return = 'var child_name = new Array();'."\n";
  8381. $return .= 'var child_value = new Array();'."\n\n";
  8382. $return .= 'child_name[0] = new Array();'."\n";
  8383. $return .= 'child_value[0] = new Array();'."\n\n";
  8384. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8385. $sql = "SELECT * FROM ".$tbl_lp_item."
  8386. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id." AND parent_item_id = 0
  8387. ORDER BY display_order ASC";
  8388. $res_zero = Database::query($sql);
  8389. $i = 0;
  8390. while ($row_zero = Database::fetch_array($res_zero)) {
  8391. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8392. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8393. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8394. }
  8395. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8396. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8397. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['id'].'";'."\n";
  8398. }
  8399. }
  8400. $return .= "\n";
  8401. $sql = "SELECT * FROM ".$tbl_lp_item."
  8402. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  8403. $res = Database::query($sql);
  8404. while ($row = Database::fetch_array($res)) {
  8405. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8406. WHERE
  8407. c_id = ".$course_id." AND
  8408. parent_item_id = " . $row['id']."
  8409. ORDER BY display_order ASC";
  8410. $res_parent = Database::query($sql_parent);
  8411. $i = 0;
  8412. $return .= 'child_name['.$row['id'].'] = new Array();'."\n";
  8413. $return .= 'child_value['.$row['id'].'] = new Array();'."\n\n";
  8414. while ($row_parent = Database::fetch_array($res_parent)) {
  8415. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  8416. $return .= 'child_name['.$row['id'].']['.$i.'] = '.$js_var.' ;'."\n";
  8417. $return .= 'child_value['.$row['id'].']['.$i++.'] = "'.$row_parent['id'].'";'."\n";
  8418. }
  8419. $return .= "\n";
  8420. }
  8421. return $return;
  8422. }
  8423. /**
  8424. * Display the form to allow moving an item
  8425. * @param integer $item_id Item ID
  8426. * @return string HTML form
  8427. */
  8428. public function display_move_item($item_id)
  8429. {
  8430. $course_id = api_get_course_int_id();
  8431. $return = '';
  8432. if (is_numeric($item_id)) {
  8433. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8434. $sql = "SELECT * FROM ".$tbl_lp_item."
  8435. WHERE c_id = ".$course_id." AND id = ".$item_id;
  8436. $res = Database::query($sql);
  8437. $row = Database::fetch_array($res);
  8438. switch ($row['item_type']) {
  8439. case 'dir':
  8440. case 'asset':
  8441. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8442. $return .= $this->display_item_form(
  8443. $row['item_type'],
  8444. get_lang('MoveCurrentChapter'),
  8445. 'move',
  8446. $item_id,
  8447. $row
  8448. );
  8449. break;
  8450. case TOOL_DOCUMENT:
  8451. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8452. $return .= $this->display_document_form('move', $item_id, $row);
  8453. break;
  8454. case TOOL_LINK:
  8455. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8456. $return .= $this->display_link_form('move', $item_id, $row);
  8457. break;
  8458. case TOOL_HOTPOTATOES:
  8459. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8460. $return .= $this->display_link_form('move', $item_id, $row);
  8461. break;
  8462. case TOOL_QUIZ:
  8463. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8464. $return .= $this->display_quiz_form('move', $item_id, $row);
  8465. break;
  8466. case TOOL_STUDENTPUBLICATION:
  8467. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8468. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8469. break;
  8470. case TOOL_FORUM:
  8471. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8472. $return .= $this->display_forum_form('move', $item_id, $row);
  8473. break;
  8474. case TOOL_THREAD:
  8475. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8476. $return .= $this->display_forum_form('move', $item_id, $row);
  8477. break;
  8478. }
  8479. }
  8480. return $return;
  8481. }
  8482. /**
  8483. * Displays a basic form on the overview page for changing the item title and the item description.
  8484. * @param string $item_type
  8485. * @param string $title
  8486. * @param array $data
  8487. * @return string
  8488. */
  8489. public function display_item_small_form($item_type, $title = '', $data = array())
  8490. {
  8491. $url = api_get_self().'?'.api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
  8492. $form = new FormValidator('small_form', 'post', $url);
  8493. $form->addElement('header', $title);
  8494. $form->addElement('text', 'title', get_lang('Title'));
  8495. $form->addButtonSave(get_lang('Save'), 'submit_button');
  8496. $form->addElement('hidden', 'id', $data['id']);
  8497. $form->addElement('hidden', 'parent', $data['parent_item_id']);
  8498. $form->addElement('hidden', 'previous', $data['previous_item_id']);
  8499. $form->setDefaults(array('title' => $data['title']));
  8500. return $form->toHtml();
  8501. }
  8502. /**
  8503. * Return HTML form to allow prerequisites selection
  8504. * @todo use FormValidator
  8505. * @param integer Item ID
  8506. * @return string HTML form
  8507. */
  8508. public function display_item_prerequisites_form($item_id)
  8509. {
  8510. $course_id = api_get_course_int_id();
  8511. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8512. $item_id = intval($item_id);
  8513. /* Current prerequisite */
  8514. $sql = "SELECT * FROM $tbl_lp_item
  8515. WHERE c_id = $course_id AND id = ".$item_id;
  8516. $result = Database::query($sql);
  8517. $row = Database::fetch_array($result);
  8518. $prerequisiteId = $row['prerequisite'];
  8519. $return = '<legend>';
  8520. $return .= get_lang('AddEditPrerequisites');
  8521. $return .= '</legend>';
  8522. $return .= '<form method="POST">';
  8523. $return .= '<div class="table-responsive">';
  8524. $return .= '<table class="table table-hover">';
  8525. $return .= '<thead>';
  8526. $return .= '<tr>';
  8527. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8528. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8529. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8530. $return .= '</tr>';
  8531. $return .= '</thead>';
  8532. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8533. $return .= '<tbody>';
  8534. $return .= '<tr>';
  8535. $return .= '<td colspan="3">';
  8536. $return .= '<div class="radio learnpath"><label for="idNone">';
  8537. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8538. $return .= get_lang('None').'</label>';
  8539. $return .= '</div>';
  8540. $return .= '</tr>';
  8541. $sql = "SELECT * FROM $tbl_lp_item
  8542. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8543. $result = Database::query($sql);
  8544. $arrLP = array();
  8545. $selectedMinScore = array();
  8546. $selectedMaxScore = array();
  8547. while ($row = Database::fetch_array($result)) {
  8548. if ($row['id'] == $item_id) {
  8549. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8550. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8551. }
  8552. $arrLP[] = array(
  8553. 'id' => $row['id'],
  8554. 'item_type' => $row['item_type'],
  8555. 'title' => $row['title'],
  8556. 'ref' => $row['ref'],
  8557. 'description' => $row['description'],
  8558. 'parent_item_id' => $row['parent_item_id'],
  8559. 'previous_item_id' => $row['previous_item_id'],
  8560. 'next_item_id' => $row['next_item_id'],
  8561. 'max_score' => $row['max_score'],
  8562. 'min_score' => $row['min_score'],
  8563. 'mastery_score' => $row['mastery_score'],
  8564. 'prerequisite' => $row['prerequisite'],
  8565. 'next_item_id' => $row['next_item_id'],
  8566. 'display_order' => $row['display_order'],
  8567. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  8568. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  8569. );
  8570. }
  8571. $this->tree_array($arrLP);
  8572. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8573. unset($this->arrMenu);
  8574. for ($i = 0; $i < count($arrLP); $i++) {
  8575. $item = $arrLP[$i];
  8576. if ($item['id'] == $item_id) {
  8577. break;
  8578. }
  8579. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8580. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8581. $return .= '<tr>';
  8582. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8583. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8584. $return .= '<label for="id'.$item['id'].'">';
  8585. $return .= '<input'.(in_array($prerequisiteId, array($item['id'], $item['ref'])) ? ' checked="checked" ' : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id'].'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  8586. $icon_name = str_replace(' ', '', $item['item_type']);
  8587. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8588. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8589. } else {
  8590. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8591. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8592. } else {
  8593. $return .= Display::return_icon('folder_document.png');
  8594. }
  8595. }
  8596. $return .= $item['title'].'</label>';
  8597. $return .= '</div>';
  8598. $return .= '</td>';
  8599. if ($item['item_type'] == TOOL_QUIZ) {
  8600. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8601. $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
  8602. $tmp_obj_exercice = new Exercise();
  8603. $tmp_obj_exercice->read($tmp_obj_lp_item->path);
  8604. $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
  8605. $tmp_obj_lp_item->update_in_bdd();
  8606. $item['max_score'] = $tmp_obj_lp_item->max_score;
  8607. $return .= '<td>';
  8608. $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.'" />';
  8609. $return .= '</td>';
  8610. $return .= '<td>';
  8611. $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.'" />';
  8612. $return .= '</td>';
  8613. }
  8614. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8615. $return .= '<td>';
  8616. $return .= '<input size="4" maxlength="3" name="min_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue.'" />';
  8617. $return .= '</td>';
  8618. $return .= '<td>';
  8619. $return .= '<input size="4" maxlength="3" name="max_'.$item['id'].'" readonly type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue.'" />';
  8620. $return .= '</td>';
  8621. }
  8622. $return .= '</tr>';
  8623. }
  8624. $return .= '<tr>';
  8625. $return .= '</tr>';
  8626. $return .= '</tbody>';
  8627. $return .= '</table>';
  8628. $return .= '</div>';
  8629. $return .= '<div class="form-group">';
  8630. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.get_lang('ModifyPrerequisites').'</button>';
  8631. $return .= '</form>';
  8632. return $return;
  8633. }
  8634. /**
  8635. * Return HTML list to allow prerequisites selection for lp
  8636. * @param integer Item ID
  8637. * @return string HTML form
  8638. */
  8639. public function display_lp_prerequisites_list()
  8640. {
  8641. $course_id = api_get_course_int_id();
  8642. $lp_id = $this->lp_id;
  8643. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  8644. // get current prerequisite
  8645. $sql = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $lp_id ";
  8646. $result = Database::query($sql);
  8647. $row = Database::fetch_array($result);
  8648. $prerequisiteId = $row['prerequisite'];
  8649. $session_id = api_get_session_id();
  8650. $session_condition = api_get_session_condition($session_id, true, true);
  8651. $sql = "SELECT * FROM $tbl_lp
  8652. WHERE c_id = $course_id $session_condition
  8653. ORDER BY display_order ";
  8654. $rs = Database::query($sql);
  8655. $return = '';
  8656. $return .= '<select name="prerequisites" class="form-control">';
  8657. $return .= '<option value="0">'.get_lang('None').'</option>';
  8658. if (Database::num_rows($rs) > 0) {
  8659. while ($row = Database::fetch_array($rs)) {
  8660. if ($row['id'] == $lp_id) {
  8661. continue;
  8662. }
  8663. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  8664. }
  8665. }
  8666. $return .= '</select>';
  8667. return $return;
  8668. }
  8669. /**
  8670. * Creates a list with all the documents in it
  8671. * @param bool $showInvisibleFiles
  8672. * @return string
  8673. */
  8674. public function get_documents($showInvisibleFiles = false)
  8675. {
  8676. $course_info = api_get_course_info();
  8677. $sessionId = api_get_session_id();
  8678. $documentTree = DocumentManager::get_document_preview(
  8679. $course_info,
  8680. $this->lp_id,
  8681. null,
  8682. $sessionId,
  8683. true,
  8684. null,
  8685. null,
  8686. $showInvisibleFiles,
  8687. true
  8688. );
  8689. $headers = array(
  8690. get_lang('Files'),
  8691. get_lang('CreateTheDocument'),
  8692. get_lang('Upload')
  8693. );
  8694. $form = new FormValidator(
  8695. 'form_upload',
  8696. 'POST',
  8697. $this->getCurrentBuildingModeURL(),
  8698. '',
  8699. array('enctype' => 'multipart/form-data')
  8700. );
  8701. $folders = DocumentManager::get_all_document_folders(
  8702. api_get_course_info(),
  8703. 0,
  8704. true
  8705. );
  8706. DocumentManager::build_directory_selector(
  8707. $folders,
  8708. '',
  8709. array(),
  8710. true,
  8711. $form,
  8712. 'directory_parent_id'
  8713. );
  8714. $group = array(
  8715. $form->createElement(
  8716. 'radio',
  8717. 'if_exists',
  8718. get_lang("UplWhatIfFileExists"),
  8719. get_lang('UplDoNothing'),
  8720. 'nothing'
  8721. ),
  8722. $form->createElement(
  8723. 'radio',
  8724. 'if_exists',
  8725. null,
  8726. get_lang('UplOverwriteLong'),
  8727. 'overwrite'
  8728. ),
  8729. $form->createElement(
  8730. 'radio',
  8731. 'if_exists',
  8732. null,
  8733. get_lang('UplRenameLong'),
  8734. 'rename'
  8735. )
  8736. );
  8737. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  8738. $form->setDefaults(['if_exists' => 'rename']);
  8739. // Check box options
  8740. $form->addElement(
  8741. 'checkbox',
  8742. 'unzip',
  8743. get_lang('Options'),
  8744. get_lang('Uncompress')
  8745. );
  8746. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  8747. $form->addMultipleUpload($url);
  8748. $new = $this->display_document_form('add', 0);
  8749. $tabs = Display::tabs(
  8750. $headers,
  8751. array($documentTree, $new, $form->returnForm()),
  8752. 'subtab'
  8753. );
  8754. return $tabs;
  8755. }
  8756. /**
  8757. * Creates a list with all the exercises (quiz) in it
  8758. * @return string
  8759. */
  8760. public function get_exercises()
  8761. {
  8762. $course_id = api_get_course_int_id();
  8763. $session_id = api_get_session_id();
  8764. $userInfo = api_get_user_info();
  8765. // New for hotpotatoes.
  8766. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  8767. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8768. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  8769. $condition_session = api_get_session_condition($session_id, true, true);
  8770. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  8771. $activeCondition = ' active <> -1 ';
  8772. if ($setting) {
  8773. $activeCondition = ' active = 1 ';
  8774. }
  8775. $sql_quiz = "SELECT * FROM $tbl_quiz
  8776. WHERE c_id = $course_id AND $activeCondition $condition_session
  8777. ORDER BY title ASC";
  8778. $sql_hot = "SELECT * FROM $tbl_doc
  8779. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  8780. ORDER BY id ASC";
  8781. $res_quiz = Database::query($sql_quiz);
  8782. $res_hot = Database::query($sql_hot);
  8783. $return = '<ul class="lp_resource">';
  8784. $return .= '<li class="lp_resource_element">';
  8785. $return .= Display::return_icon('new_exercice.png');
  8786. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  8787. get_lang('NewExercise').'</a>';
  8788. $return .= '</li>';
  8789. $previewIcon = Display::return_icon(
  8790. 'preview_view.png',
  8791. get_lang('Preview')
  8792. );
  8793. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  8794. // Display hotpotatoes
  8795. while ($row_hot = Database::fetch_array($res_hot)) {
  8796. $link = Display::url(
  8797. $previewIcon,
  8798. $exerciseUrl.'&file='.$row_hot['path'],
  8799. ['target' => '_blank']
  8800. );
  8801. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  8802. $return .= '<a class="moved" href="#">';
  8803. $return .= Display::return_icon(
  8804. 'move_everywhere.png',
  8805. get_lang('Move'),
  8806. array(),
  8807. ICON_SIZE_TINY
  8808. );
  8809. $return .= '</a> ';
  8810. $return .= Display::return_icon('hotpotatoes_s.png');
  8811. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  8812. ((!empty ($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  8813. $return .= '</li>';
  8814. }
  8815. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  8816. while ($row_quiz = Database::fetch_array($res_quiz)) {
  8817. $title = strip_tags(
  8818. api_html_entity_decode($row_quiz['title'])
  8819. );
  8820. $link = Display::url(
  8821. $previewIcon,
  8822. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  8823. ['target' => '_blank']
  8824. );
  8825. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  8826. $return .= '<a class="moved" href="#">';
  8827. $return .= Display::return_icon(
  8828. 'move_everywhere.png',
  8829. get_lang('Move'),
  8830. array(),
  8831. ICON_SIZE_TINY
  8832. );
  8833. $return .= '</a> ';
  8834. $return .= Display::return_icon(
  8835. 'quizz_small.gif',
  8836. '',
  8837. array(),
  8838. ICON_SIZE_TINY
  8839. );
  8840. $sessionStar = api_get_session_image(
  8841. $row_quiz['session_id'],
  8842. $userInfo['status']
  8843. );
  8844. $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.'">'.
  8845. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  8846. '</a>';
  8847. $return .= '</li>';
  8848. }
  8849. $return .= '</ul>';
  8850. return $return;
  8851. }
  8852. /**
  8853. * Creates a list with all the links in it
  8854. * @return string
  8855. */
  8856. public function get_links()
  8857. {
  8858. $selfUrl = api_get_self();
  8859. $courseIdReq = api_get_cidreq();
  8860. $course = api_get_course_info();
  8861. $userInfo = api_get_user_info();
  8862. $course_id = $course['real_id'];
  8863. $tbl_link = Database::get_course_table(TABLE_LINK);
  8864. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  8865. $moveEverywhereIcon = Display::return_icon(
  8866. 'move_everywhere.png',
  8867. get_lang('Move'),
  8868. array(),
  8869. ICON_SIZE_TINY
  8870. );
  8871. $session_id = api_get_session_id();
  8872. $condition_session = api_get_session_condition(
  8873. $session_id,
  8874. true,
  8875. true,
  8876. "link.session_id"
  8877. );
  8878. $sql = "SELECT
  8879. link.id as link_id,
  8880. link.title as link_title,
  8881. link.session_id as link_session_id,
  8882. link.category_id as category_id,
  8883. link_category.category_title as category_title
  8884. FROM $tbl_link as link
  8885. LEFT JOIN $linkCategoryTable as link_category
  8886. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  8887. WHERE link.c_id = ".$course_id." $condition_session
  8888. ORDER BY link_category.category_title ASC, link.title ASC";
  8889. $result = Database::query($sql);
  8890. $categorizedLinks = array();
  8891. $categories = array();
  8892. while ($link = Database::fetch_array($result)) {
  8893. if (!$link['category_id']) {
  8894. $link['category_title'] = get_lang('Uncategorized');
  8895. }
  8896. $categories[$link['category_id']] = $link['category_title'];
  8897. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  8898. }
  8899. $linksHtmlCode =
  8900. '<script>
  8901. function toggle_tool(tool, id){
  8902. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  8903. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  8904. document.getElementById(tool+"_"+id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
  8905. } else {
  8906. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  8907. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  8908. }
  8909. }
  8910. </script>
  8911. <ul class="lp_resource">
  8912. <li class="lp_resource_element">
  8913. '.Display::return_icon('linksnew.gif').'
  8914. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  8915. get_lang('LinkAdd').'
  8916. </a>
  8917. </li>';
  8918. foreach ($categorizedLinks as $categoryId => $links) {
  8919. $linkNodes = null;
  8920. foreach ($links as $key => $linkInfo) {
  8921. $title = $linkInfo['link_title'];
  8922. $linkSessionId = $linkInfo['link_session_id'];
  8923. $link = Display::url(
  8924. Display::return_icon('preview_view.png', get_lang('Preview')),
  8925. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  8926. ['target' => '_blank']
  8927. );
  8928. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  8929. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  8930. $linkNodes .=
  8931. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  8932. <a class="moved" href="#">'.
  8933. $moveEverywhereIcon.
  8934. '</a>
  8935. '.Display::return_icon('lp_link.png').'
  8936. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  8937. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  8938. Security::remove_XSS($title).$sessionStar.$link.
  8939. '</a>
  8940. </li>';
  8941. }
  8942. }
  8943. $linksHtmlCode .=
  8944. '<li>
  8945. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  8946. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  8947. align="absbottom" />
  8948. </a>
  8949. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  8950. </li>
  8951. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  8952. }
  8953. $linksHtmlCode .= '</ul>';
  8954. return $linksHtmlCode;
  8955. }
  8956. /**
  8957. * Creates a list with all the student publications in it
  8958. * @return string
  8959. */
  8960. public function get_student_publications()
  8961. {
  8962. $return = '<ul class="lp_resource">';
  8963. $return .= '<li class="lp_resource_element">';
  8964. $return .= Display::return_icon('works_new.gif');
  8965. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  8966. get_lang('AddAssignmentPage').'</a>';
  8967. $return .= '</li>';
  8968. $sessionId = api_get_session_id();
  8969. if (empty($sessionId)) {
  8970. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  8971. $works = getWorkListTeacher(0, 100, null, null, null);
  8972. if (!empty($works)) {
  8973. foreach ($works as $work) {
  8974. $link = Display::url(
  8975. Display::return_icon('preview_view.png', get_lang('Preview')),
  8976. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  8977. ['target' => '_blank']
  8978. );
  8979. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  8980. $return .= '<a class="moved" href="#">';
  8981. $return .= Display::return_icon(
  8982. 'move_everywhere.png',
  8983. get_lang('Move'),
  8984. array(),
  8985. ICON_SIZE_TINY
  8986. );
  8987. $return .= '</a> ';
  8988. $return .= Display::return_icon('works.gif');
  8989. $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.'">'.
  8990. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  8991. </a>';
  8992. $return .= '</li>';
  8993. }
  8994. }
  8995. }
  8996. $return .= '</ul>';
  8997. return $return;
  8998. }
  8999. /**
  9000. * Creates a list with all the forums in it
  9001. * @return string
  9002. */
  9003. public function get_forums()
  9004. {
  9005. require_once '../forum/forumfunction.inc.php';
  9006. require_once '../forum/forumconfig.inc.php';
  9007. $forumCategories = get_forum_categories();
  9008. $forumsInNoCategory = get_forums_in_category(0);
  9009. if (!empty($forumsInNoCategory)) {
  9010. $forumCategories = array_merge(
  9011. $forumCategories,
  9012. array(
  9013. array(
  9014. 'cat_id' => 0,
  9015. 'session_id' => 0,
  9016. 'visibility' => 1,
  9017. 'cat_comment' => null,
  9018. ),
  9019. )
  9020. );
  9021. }
  9022. $forumList = get_forums();
  9023. $a_forums = [];
  9024. foreach ($forumCategories as $forumCategory) {
  9025. // The forums in this category.
  9026. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9027. if (!empty($forumsInCategory)) {
  9028. foreach ($forumList as $forum) {
  9029. if (isset($forum['forum_category']) &&
  9030. $forum['forum_category'] == $forumCategory['cat_id']
  9031. ) {
  9032. $a_forums[] = $forum;
  9033. }
  9034. }
  9035. }
  9036. }
  9037. $return = '<ul class="lp_resource">';
  9038. // First add link
  9039. $return .= '<li class="lp_resource_element">';
  9040. $return .= Display::return_icon('new_forum.png');
  9041. $return .= Display::url(
  9042. get_lang('CreateANewForum'),
  9043. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9044. 'action' => 'add',
  9045. 'content' => 'forum',
  9046. 'lp_id' => $this->lp_id
  9047. ]),
  9048. ['title' => get_lang('CreateANewForum')]
  9049. );
  9050. $return .= '</li>';
  9051. $return .= '<script>
  9052. function toggle_forum(forum_id) {
  9053. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9054. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9055. document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
  9056. } else {
  9057. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9058. document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('add.gif').'";
  9059. }
  9060. }
  9061. </script>';
  9062. foreach ($a_forums as $forum) {
  9063. if (!empty($forum['forum_id'])) {
  9064. $link = Display::url(
  9065. Display::return_icon('preview_view.png', get_lang('Preview')),
  9066. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9067. ['target' => '_blank']
  9068. );
  9069. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9070. $return .= '<a class="moved" href="#">';
  9071. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  9072. $return .= ' </a>';
  9073. $return .= Display::return_icon('lp_forum.png', '', array(), ICON_SIZE_TINY);
  9074. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9075. <img src="' . Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9076. </a>
  9077. <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">'.
  9078. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9079. $return .= '</li>';
  9080. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9081. $a_threads = get_threads($forum['forum_id']);
  9082. if (is_array($a_threads)) {
  9083. foreach ($a_threads as $thread) {
  9084. $link = Display::url(
  9085. Display::return_icon('preview_view.png', get_lang('Preview')),
  9086. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9087. ['target' => '_blank']
  9088. );
  9089. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9090. $return .= '&nbsp;<a class="moved" href="#">';
  9091. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  9092. $return .= ' </a>';
  9093. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), array(), ICON_SIZE_TINY);
  9094. $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.'">'.
  9095. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9096. $return .= '</li>';
  9097. }
  9098. }
  9099. $return .= '</div>';
  9100. }
  9101. }
  9102. $return .= '</ul>';
  9103. return $return;
  9104. }
  9105. /**
  9106. * // TODO: The output encoding should be equal to the system encoding.
  9107. *
  9108. * Exports the learning path as a SCORM package. This is the main function that
  9109. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9110. * whole thing and returns the zip.
  9111. *
  9112. * This method needs to be called in PHP5, as it will fail with non-adequate
  9113. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9114. * you need to call it on a learnpath object.
  9115. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9116. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9117. * path has been modified, it should use the generic method here below.
  9118. * @TODO link this function with the export_lp() function in the same class
  9119. * @param string Optional name of zip file. If none, title of learnpath is
  9120. * domesticated and trailed with ".zip"
  9121. * @return string Returns the zip package string, or null if error
  9122. */
  9123. public function scorm_export()
  9124. {
  9125. $_course = api_get_course_info();
  9126. $course_id = $_course['real_id'];
  9127. // Remove memory and time limits as much as possible as this might be a long process...
  9128. if (function_exists('ini_set')) {
  9129. api_set_memory_limit('256M');
  9130. ini_set('max_execution_time', 600);
  9131. }
  9132. // Create the zip handler (this will remain available throughout the method).
  9133. $archive_path = api_get_path(SYS_ARCHIVE_PATH);
  9134. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9135. $temp_dir_short = uniqid();
  9136. $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
  9137. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9138. $zip_folder = new PclZip($temp_zip_file);
  9139. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9140. $root_path = $main_path = api_get_path(SYS_PATH);
  9141. $files_cleanup = array();
  9142. // Place to temporarily stash the zip file.
  9143. // create the temp dir if it doesn't exist
  9144. // or do a cleanup before creating the zip file.
  9145. if (!is_dir($temp_zip_dir)) {
  9146. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9147. } else {
  9148. // Cleanup: Check the temp dir for old files and delete them.
  9149. $handle = opendir($temp_zip_dir);
  9150. while (false !== ($file = readdir($handle))) {
  9151. if ($file != '.' && $file != '..') {
  9152. unlink("$temp_zip_dir/$file");
  9153. }
  9154. }
  9155. closedir($handle);
  9156. }
  9157. $zip_files = $zip_files_abs = $zip_files_dist = array();
  9158. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9159. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9160. ) {
  9161. // Remove the possible . at the end of the path.
  9162. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9163. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9164. mkdir(
  9165. $dest_path_to_scorm_folder,
  9166. api_get_permissions_for_new_directories(),
  9167. true
  9168. );
  9169. copyr(
  9170. $current_course_path.'/scorm/'.$this->path,
  9171. $dest_path_to_scorm_folder,
  9172. array('imsmanifest'),
  9173. $zip_files
  9174. );
  9175. }
  9176. // Build a dummy imsmanifest structure.
  9177. // Do not add to the zip yet (we still need it).
  9178. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9179. // Aggregation Model official document, section "2.3 Content Packaging".
  9180. // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
  9181. $xmldoc = new DOMDocument('1.0');
  9182. $root = $xmldoc->createElement('manifest');
  9183. $root->setAttribute('identifier', 'SingleCourseManifest');
  9184. $root->setAttribute('version', '1.1');
  9185. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9186. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9187. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9188. $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');
  9189. // Build mandatory sub-root container elements.
  9190. $metadata = $xmldoc->createElement('metadata');
  9191. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9192. $metadata->appendChild($md_schema);
  9193. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9194. $metadata->appendChild($md_schemaversion);
  9195. $root->appendChild($metadata);
  9196. $organizations = $xmldoc->createElement('organizations');
  9197. $resources = $xmldoc->createElement('resources');
  9198. // Build the only organization we will use in building our learnpaths.
  9199. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9200. $organization = $xmldoc->createElement('organization');
  9201. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9202. // To set the title of the SCORM entity (=organization), we take the name given
  9203. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9204. // learning path charset) as it is the encoding that defines how it is stored
  9205. // in the database. Then we convert it to HTML entities again as the "&" character
  9206. // alone is not authorized in XML (must be &amp;).
  9207. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9208. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9209. $organization->appendChild($org_title);
  9210. $folder_name = 'document';
  9211. // Removes the learning_path/scorm_folder path when exporting see #4841
  9212. $path_to_remove = null;
  9213. $result = $this->generate_lp_folder($_course);
  9214. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9215. $path_to_remove = 'document'.$result['dir'];
  9216. $path_to_replace = $folder_name.'/';
  9217. }
  9218. // Fixes chamilo scorm exports
  9219. if ($this->ref === 'chamilo_scorm_export') {
  9220. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9221. }
  9222. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9223. // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
  9224. $link_updates = array();
  9225. $links_to_create = array();
  9226. //foreach ($this->items as $index => $item) {
  9227. foreach ($this->ordered_items as $index => $itemId) {
  9228. $item = $this->items[$itemId];
  9229. if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) {
  9230. // Get included documents from this item.
  9231. if ($item->type === 'sco') {
  9232. $inc_docs = $item->get_resources_from_source(
  9233. null,
  9234. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.'scorm/'.$this->path.'/'.$item->get_path()
  9235. );
  9236. } else {
  9237. $inc_docs = $item->get_resources_from_source();
  9238. }
  9239. // Give a child element <item> to the <organization> element.
  9240. $my_item_id = $item->get_id();
  9241. $my_item = $xmldoc->createElement('item');
  9242. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9243. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9244. $my_item->setAttribute('isvisible', 'true');
  9245. // Give a child element <title> to the <item> element.
  9246. $my_title = $xmldoc->createElement(
  9247. 'title',
  9248. htmlspecialchars(
  9249. api_utf8_encode($item->get_title()),
  9250. ENT_QUOTES,
  9251. 'UTF-8'
  9252. )
  9253. );
  9254. $my_item->appendChild($my_title);
  9255. // Give a child element <adlcp:prerequisites> to the <item> element.
  9256. $my_prereqs = $xmldoc->createElement(
  9257. 'adlcp:prerequisites',
  9258. $this->get_scorm_prereq_string($my_item_id)
  9259. );
  9260. $my_prereqs->setAttribute('type', 'aicc_script');
  9261. $my_item->appendChild($my_prereqs);
  9262. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9263. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9264. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9265. //$xmldoc->createElement('adlcp:timelimitaction','');
  9266. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9267. //$xmldoc->createElement('adlcp:datafromlms','');
  9268. // Give a child element <adlcp:masteryscore> to the <item> element.
  9269. $my_masteryscore = $xmldoc->createElement(
  9270. 'adlcp:masteryscore',
  9271. $item->get_mastery_score()
  9272. );
  9273. $my_item->appendChild($my_masteryscore);
  9274. // Attach this item to the organization element or hits parent if there is one.
  9275. if (!empty($item->parent) && $item->parent != 0) {
  9276. $children = $organization->childNodes;
  9277. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9278. if (is_object($possible_parent)) {
  9279. $possible_parent->appendChild($my_item);
  9280. } else {
  9281. if ($this->debug > 0) { error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found'); }
  9282. }
  9283. } else {
  9284. if ($this->debug > 0) { error_log('No parent'); }
  9285. $organization->appendChild($my_item);
  9286. }
  9287. // Get the path of the file(s) from the course directory root.
  9288. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9289. if (!empty($path_to_remove)) {
  9290. //From docs
  9291. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9292. //From quiz
  9293. if ($this->ref === 'chamilo_scorm_export') {
  9294. $path_to_remove = 'scorm/'.$this->path.'/';
  9295. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9296. }
  9297. } else {
  9298. $my_xml_file_path = $my_file_path;
  9299. }
  9300. $my_sub_dir = dirname($my_file_path);
  9301. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9302. $my_xml_sub_dir = $my_sub_dir;
  9303. // Give a <resource> child to the <resources> element
  9304. $my_resource = $xmldoc->createElement('resource');
  9305. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9306. $my_resource->setAttribute('type', 'webcontent');
  9307. $my_resource->setAttribute('href', $my_xml_file_path);
  9308. // adlcp:scormtype can be either 'sco' or 'asset'.
  9309. if ($item->type === 'sco') {
  9310. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9311. } else {
  9312. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9313. }
  9314. // xml:base is the base directory to find the files declared in this resource.
  9315. $my_resource->setAttribute('xml:base', '');
  9316. // Give a <file> child to the <resource> element.
  9317. $my_file = $xmldoc->createElement('file');
  9318. $my_file->setAttribute('href', $my_xml_file_path);
  9319. $my_resource->appendChild($my_file);
  9320. // Dependency to other files - not yet supported.
  9321. $i = 1;
  9322. if ($inc_docs)
  9323. foreach ($inc_docs as $doc_info) {
  9324. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9325. continue;
  9326. }
  9327. $my_dep = $xmldoc->createElement('resource');
  9328. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9329. $my_dep->setAttribute('identifier', $res_id);
  9330. $my_dep->setAttribute('type', 'webcontent');
  9331. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9332. $my_dep_file = $xmldoc->createElement('file');
  9333. // Check type of URL.
  9334. if ($doc_info[1] == 'remote') {
  9335. // Remote file. Save url as is.
  9336. $my_dep_file->setAttribute('href', $doc_info[0]);
  9337. $my_dep->setAttribute('xml:base', '');
  9338. } elseif ($doc_info[1] === 'local') {
  9339. switch ($doc_info[2]) {
  9340. case 'url': // Local URL - save path as url for now, don't zip file.
  9341. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9342. $current_dir = dirname($abs_path);
  9343. $current_dir = str_replace('\\', '/', $current_dir);
  9344. $file_path = realpath($abs_path);
  9345. $file_path = str_replace('\\', '/', $file_path);
  9346. $my_dep_file->setAttribute('href', $file_path);
  9347. $my_dep->setAttribute('xml:base', '');
  9348. if (strstr($file_path, $main_path) !== false) {
  9349. // The calculated real path is really inside Chamilo's root path.
  9350. // Reduce file path to what's under the DocumentRoot.
  9351. $file_path = substr($file_path, strlen($root_path) - 1);
  9352. //echo $file_path;echo '<br /><br />';
  9353. //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
  9354. $zip_files_abs[] = $file_path;
  9355. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9356. $my_dep_file->setAttribute('href', $file_path);
  9357. $my_dep->setAttribute('xml:base', '');
  9358. } elseif (empty($file_path)) {
  9359. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9360. if (strpos($document_root, -1) == '/') {
  9361. $document_root = substr(0, -1, $document_root);
  9362. }*/
  9363. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9364. $file_path = str_replace('//', '/', $file_path);
  9365. if (file_exists($file_path)) {
  9366. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9367. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9368. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9369. $my_dep_file->setAttribute('href', $file_path);
  9370. $my_dep->setAttribute('xml:base', '');
  9371. }
  9372. }
  9373. break;
  9374. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9375. $my_dep_file->setAttribute('href', $doc_info[0]);
  9376. $my_dep->setAttribute('xml:base', '');
  9377. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9378. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9379. $abs_img_path_without_subdir = $doc_info[0];
  9380. $relp = api_get_path(REL_PATH); // The url-append config param.
  9381. $pos = strpos($abs_img_path_without_subdir, $relp);
  9382. if ($pos === 0) {
  9383. $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir, strlen($relp));
  9384. }
  9385. //$file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
  9386. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9387. $file_path = str_replace('\\', '/', $file_path);
  9388. $file_path = str_replace('//', '/', $file_path);
  9389. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9390. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9391. // Check if the current document is in that path.
  9392. if (strstr($file_path, $cur_path) !== false) {
  9393. // The document is in that path, now get the relative path
  9394. // to the containing document.
  9395. $orig_file_path = dirname($cur_path.$my_file_path).'/';
  9396. $orig_file_path = str_replace('\\', '/', $orig_file_path);
  9397. $relative_path = '';
  9398. if (strstr($file_path, $cur_path) !== false) {
  9399. //$relative_path = substr($file_path, strlen($orig_file_path));
  9400. $relative_path = str_replace($cur_path, '', $file_path);
  9401. $file_path = substr($file_path, strlen($cur_path));
  9402. } else {
  9403. // This case is still a problem as it's difficult to calculate a relative path easily
  9404. // might still generate wrong links.
  9405. //$file_path = substr($file_path,strlen($cur_path));
  9406. // Calculate the directory path to the current file (without trailing slash).
  9407. $my_relative_path = dirname($file_path);
  9408. $my_relative_path = str_replace('\\', '/', $my_relative_path);
  9409. $my_relative_file = basename($file_path);
  9410. // Calculate the directory path to the containing file (without trailing slash).
  9411. $my_orig_file_path = substr($orig_file_path, 0, -1);
  9412. $dotdot = '';
  9413. $subdir = '';
  9414. while (strstr($my_relative_path, $my_orig_file_path) === false && (strlen($my_orig_file_path) > 1) && (strlen($my_relative_path) > 1)) {
  9415. $my_relative_path2 = dirname($my_relative_path);
  9416. $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
  9417. $my_orig_file_path = dirname($my_orig_file_path);
  9418. $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
  9419. $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'.$subdir;
  9420. $dotdot += '../';
  9421. $my_relative_path = $my_relative_path2;
  9422. }
  9423. $relative_path = $dotdot.$subdir.$my_relative_file;
  9424. }
  9425. // Put the current document in the zip (this array is the array
  9426. // that will manage documents already in the course folder - relative).
  9427. $zip_files[] = $file_path;
  9428. // Update the links to the current document in the containing document (make them relative).
  9429. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $relative_path);
  9430. $my_dep_file->setAttribute('href', $file_path);
  9431. $my_dep->setAttribute('xml:base', '');
  9432. } elseif (strstr($file_path, $main_path) !== false) {
  9433. // The calculated real path is really inside Chamilo's root path.
  9434. // Reduce file path to what's under the DocumentRoot.
  9435. $file_path = substr($file_path, strlen($root_path));
  9436. //echo $file_path;echo '<br /><br />';
  9437. //error_log('Reduced path: '.$file_path, 0);
  9438. $zip_files_abs[] = $file_path;
  9439. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9440. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9441. $my_dep->setAttribute('xml:base', '');
  9442. } elseif (empty($file_path)) {
  9443. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9444. if(strpos($document_root,-1) == '/') {
  9445. $document_root = substr(0, -1, $document_root);
  9446. }*/
  9447. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9448. $file_path = str_replace('//', '/', $file_path);
  9449. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9450. $current_dir = dirname($abs_path);
  9451. $current_dir = str_replace('\\', '/', $current_dir);
  9452. if (file_exists($file_path)) {
  9453. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9454. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9455. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9456. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9457. $my_dep->setAttribute('xml:base', '');
  9458. }
  9459. }
  9460. break;
  9461. case 'rel':
  9462. // Path relative to the current document.
  9463. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9464. if (substr($doc_info[0], 0, 2) == '..') {
  9465. // Relative path going up.
  9466. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9467. $current_dir = str_replace('\\', '/', $current_dir);
  9468. $file_path = realpath($current_dir.$doc_info[0]);
  9469. $file_path = str_replace('\\', '/', $file_path);
  9470. //error_log($file_path.' <-> '.$main_path,0);
  9471. if (strstr($file_path, $main_path) !== false) {
  9472. // The calculated real path is really inside Chamilo's root path.
  9473. // Reduce file path to what's under the DocumentRoot.
  9474. $file_path = substr($file_path, strlen($root_path));
  9475. //error_log('Reduced path: '.$file_path, 0);
  9476. $zip_files_abs[] = $file_path;
  9477. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9478. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9479. $my_dep->setAttribute('xml:base', '');
  9480. }
  9481. } else {
  9482. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9483. $my_dep_file->setAttribute('href', $doc_info[0]);
  9484. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9485. }
  9486. break;
  9487. default:
  9488. $my_dep_file->setAttribute('href', $doc_info[0]);
  9489. $my_dep->setAttribute('xml:base', '');
  9490. break;
  9491. }
  9492. }
  9493. $my_dep->appendChild($my_dep_file);
  9494. $resources->appendChild($my_dep);
  9495. $dependency = $xmldoc->createElement('dependency');
  9496. $dependency->setAttribute('identifierref', $res_id);
  9497. $my_resource->appendChild($dependency);
  9498. $i++;
  9499. }
  9500. $resources->appendChild($my_resource);
  9501. $zip_files[] = $my_file_path;
  9502. } else {
  9503. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9504. switch ($item->type) {
  9505. case TOOL_LINK:
  9506. $my_item = $xmldoc->createElement('item');
  9507. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9508. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9509. $my_item->setAttribute('isvisible', 'true');
  9510. // Give a child element <title> to the <item> element.
  9511. $my_title = $xmldoc->createElement(
  9512. 'title',
  9513. htmlspecialchars(
  9514. api_utf8_encode($item->get_title()),
  9515. ENT_QUOTES,
  9516. 'UTF-8'
  9517. )
  9518. );
  9519. $my_item->appendChild($my_title);
  9520. // Give a child element <adlcp:prerequisites> to the <item> element.
  9521. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9522. $my_prereqs->setAttribute('type', 'aicc_script');
  9523. $my_item->appendChild($my_prereqs);
  9524. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9525. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9526. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9527. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9528. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9529. //$xmldoc->createElement('adlcp:datafromlms', '');
  9530. // Give a child element <adlcp:masteryscore> to the <item> element.
  9531. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9532. $my_item->appendChild($my_masteryscore);
  9533. // Attach this item to the organization element or its parent if there is one.
  9534. if (!empty($item->parent) && $item->parent != 0) {
  9535. $children = $organization->childNodes;
  9536. for ($i = 0; $i < $children->length; $i++) {
  9537. $item_temp = $children->item($i);
  9538. if ($item_temp -> nodeName == 'item') {
  9539. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9540. $item_temp -> appendChild($my_item);
  9541. }
  9542. }
  9543. }
  9544. } else {
  9545. $organization->appendChild($my_item);
  9546. }
  9547. $my_file_path = 'link_'.$item->get_id().'.html';
  9548. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9549. WHERE c_id = '.$course_id.' AND id='.$item->path;
  9550. $rs = Database::query($sql);
  9551. if ($link = Database::fetch_array($rs)) {
  9552. $url = $link['url'];
  9553. $title = stripslashes($link['title']);
  9554. $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url);
  9555. $my_xml_file_path = $my_file_path;
  9556. $my_sub_dir = dirname($my_file_path);
  9557. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9558. $my_xml_sub_dir = $my_sub_dir;
  9559. // Give a <resource> child to the <resources> element.
  9560. $my_resource = $xmldoc->createElement('resource');
  9561. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9562. $my_resource->setAttribute('type', 'webcontent');
  9563. $my_resource->setAttribute('href', $my_xml_file_path);
  9564. // adlcp:scormtype can be either 'sco' or 'asset'.
  9565. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9566. // xml:base is the base directory to find the files declared in this resource.
  9567. $my_resource->setAttribute('xml:base', '');
  9568. // give a <file> child to the <resource> element.
  9569. $my_file = $xmldoc->createElement('file');
  9570. $my_file->setAttribute('href', $my_xml_file_path);
  9571. $my_resource->appendChild($my_file);
  9572. $resources->appendChild($my_resource);
  9573. }
  9574. break;
  9575. case TOOL_QUIZ:
  9576. $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
  9577. $exe = new Exercise();
  9578. $exe->read($exe_id);
  9579. $my_item = $xmldoc->createElement('item');
  9580. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9581. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9582. $my_item->setAttribute('isvisible', 'true');
  9583. // Give a child element <title> to the <item> element.
  9584. $my_title = $xmldoc->createElement(
  9585. 'title',
  9586. htmlspecialchars(
  9587. api_utf8_encode($item->get_title()),
  9588. ENT_QUOTES,
  9589. 'UTF-8'
  9590. )
  9591. );
  9592. $my_item->appendChild($my_title);
  9593. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  9594. //$my_item->appendChild($my_max_score);
  9595. // Give a child element <adlcp:prerequisites> to the <item> element.
  9596. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9597. $my_prereqs->setAttribute('type', 'aicc_script');
  9598. $my_item->appendChild($my_prereqs);
  9599. // Give a child element <adlcp:masteryscore> to the <item> element.
  9600. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9601. $my_item->appendChild($my_masteryscore);
  9602. // Attach this item to the organization element or hits parent if there is one.
  9603. if (!empty($item->parent) && $item->parent != 0) {
  9604. $children = $organization->childNodes;
  9605. /*for ($i = 0; $i < $children->length; $i++) {
  9606. $item_temp = $children->item($i);
  9607. if ($exe_id == 81) {
  9608. error_log($item_temp->nodeName );
  9609. error_log($item_temp->getAttribute('identifier'));
  9610. }
  9611. if ($item_temp->nodeName == 'item') {
  9612. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9613. $item_temp->appendChild($my_item);
  9614. }
  9615. }
  9616. }*/
  9617. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9618. if ($possible_parent) {
  9619. if ($possible_parent->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9620. $possible_parent->appendChild($my_item);
  9621. }
  9622. }
  9623. } else {
  9624. $organization->appendChild($my_item);
  9625. }
  9626. // Get the path of the file(s) from the course directory root
  9627. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9628. $my_file_path = 'quiz_'.$item->get_id().'.html';
  9629. // Write the contents of the exported exercise into a (big) html file
  9630. // to later pack it into the exported SCORM. The file will be removed afterwards.
  9631. $contents = ScormSection::export_exercise_to_scorm(
  9632. $exe,
  9633. true
  9634. );
  9635. $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
  9636. $res = file_put_contents($tmp_file_path, $contents);
  9637. if ($res === false) {
  9638. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  9639. }
  9640. $files_cleanup[] = $tmp_file_path;
  9641. $my_xml_file_path = $my_file_path;
  9642. $my_sub_dir = dirname($my_file_path);
  9643. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9644. $my_xml_sub_dir = $my_sub_dir;
  9645. // Give a <resource> child to the <resources> element.
  9646. $my_resource = $xmldoc->createElement('resource');
  9647. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9648. $my_resource->setAttribute('type', 'webcontent');
  9649. $my_resource->setAttribute('href', $my_xml_file_path);
  9650. // adlcp:scormtype can be either 'sco' or 'asset'.
  9651. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9652. // xml:base is the base directory to find the files declared in this resource.
  9653. $my_resource->setAttribute('xml:base', '');
  9654. // Give a <file> child to the <resource> element.
  9655. $my_file = $xmldoc->createElement('file');
  9656. $my_file->setAttribute('href', $my_xml_file_path);
  9657. $my_resource->appendChild($my_file);
  9658. // Get included docs.
  9659. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  9660. // Dependency to other files - not yet supported.
  9661. $i = 1;
  9662. foreach ($inc_docs as $doc_info) {
  9663. if (count($doc_info) < 1 || empty($doc_info[0])) { continue; }
  9664. $my_dep = $xmldoc->createElement('resource');
  9665. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9666. $my_dep->setAttribute('identifier', $res_id);
  9667. $my_dep->setAttribute('type', 'webcontent');
  9668. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9669. $my_dep_file = $xmldoc->createElement('file');
  9670. // Check type of URL.
  9671. if ($doc_info[1] == 'remote') {
  9672. // Remote file. Save url as is.
  9673. $my_dep_file->setAttribute('href', $doc_info[0]);
  9674. $my_dep->setAttribute('xml:base', '');
  9675. } elseif ($doc_info[1] == 'local') {
  9676. switch ($doc_info[2]) {
  9677. case 'url': // Local URL - save path as url for now, don't zip file.
  9678. // Save file but as local file (retrieve from URL).
  9679. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9680. $current_dir = dirname($abs_path);
  9681. $current_dir = str_replace('\\', '/', $current_dir);
  9682. $file_path = realpath($abs_path);
  9683. $file_path = str_replace('\\', '/', $file_path);
  9684. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9685. $my_dep->setAttribute('xml:base', '');
  9686. if (strstr($file_path, $main_path) !== false) {
  9687. // The calculated real path is really inside the chamilo root path.
  9688. // Reduce file path to what's under the DocumentRoot.
  9689. $file_path = substr($file_path, strlen($root_path));
  9690. $zip_files_abs[] = $file_path;
  9691. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
  9692. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9693. $my_dep->setAttribute('xml:base', '');
  9694. } elseif (empty($file_path)) {
  9695. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
  9696. if (strpos($document_root,-1) == '/') {
  9697. $document_root = substr(0, -1, $document_root);
  9698. }*/
  9699. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9700. $file_path = str_replace('//', '/', $file_path);
  9701. if (file_exists($file_path)) {
  9702. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9703. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9704. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => 'document/'.$file_path);
  9705. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9706. $my_dep->setAttribute('xml:base', '');
  9707. }
  9708. }
  9709. break;
  9710. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9711. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9712. $current_dir = str_replace('\\', '/', $current_dir);
  9713. $file_path = realpath($doc_info[0]);
  9714. $file_path = str_replace('\\', '/', $file_path);
  9715. $my_dep_file->setAttribute('href', $file_path);
  9716. $my_dep->setAttribute('xml:base', '');
  9717. if (strstr($file_path, $main_path) !== false) {
  9718. // The calculated real path is really inside the chamilo root path.
  9719. // Reduce file path to what's under the DocumentRoot.
  9720. $file_path = substr($file_path, strlen($root_path));
  9721. //echo $file_path;echo '<br /><br />';
  9722. //error_log('Reduced path: '.$file_path, 0);
  9723. $zip_files_abs[] = $file_path;
  9724. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9725. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9726. $my_dep->setAttribute('xml:base', '');
  9727. } elseif (empty($file_path)) {
  9728. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9729. if (strpos($document_root,-1) == '/') {
  9730. $document_root = substr(0, -1, $document_root);
  9731. }*/
  9732. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9733. $file_path = str_replace('//', '/', $file_path);
  9734. if (file_exists($file_path)) {
  9735. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9736. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9737. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path);
  9738. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9739. $my_dep->setAttribute('xml:base', '');
  9740. }
  9741. }
  9742. break;
  9743. case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
  9744. if (substr($doc_info[0], 0, 2) == '..') {
  9745. // Relative path going up.
  9746. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9747. $current_dir = str_replace('\\', '/', $current_dir);
  9748. $file_path = realpath($current_dir.$doc_info[0]);
  9749. $file_path = str_replace('\\', '/', $file_path);
  9750. //error_log($file_path.' <-> '.$main_path, 0);
  9751. if (strstr($file_path, $main_path) !== false) {
  9752. // The calculated real path is really inside Chamilo's root path.
  9753. // Reduce file path to what's under the DocumentRoot.
  9754. $file_path = substr($file_path, strlen($root_path));
  9755. $file_path_dest = $file_path;
  9756. // File path is courses/CHAMILO/document/....
  9757. $info_file_path = explode('/', $file_path);
  9758. if ($info_file_path[0] == 'courses') { // Add character "/" in file path.
  9759. $file_path_dest = 'document/'.$file_path;
  9760. }
  9761. //error_log('Reduced path: '.$file_path, 0);
  9762. $zip_files_abs[] = $file_path;
  9763. $link_updates[$my_file_path][] = array('orig' => $doc_info[0], 'dest' => $file_path_dest);
  9764. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9765. $my_dep->setAttribute('xml:base', '');
  9766. }
  9767. } else {
  9768. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9769. $my_dep_file->setAttribute('href', $doc_info[0]);
  9770. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9771. }
  9772. break;
  9773. default:
  9774. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  9775. $my_dep->setAttribute('xml:base', '');
  9776. break;
  9777. }
  9778. }
  9779. $my_dep->appendChild($my_dep_file);
  9780. $resources->appendChild($my_dep);
  9781. $dependency = $xmldoc->createElement('dependency');
  9782. $dependency->setAttribute('identifierref', $res_id);
  9783. $my_resource->appendChild($dependency);
  9784. $i++;
  9785. }
  9786. $resources->appendChild($my_resource);
  9787. $zip_files[] = $my_file_path;
  9788. break;
  9789. default:
  9790. // Get the path of the file(s) from the course directory root
  9791. $my_file_path = 'non_exportable.html';
  9792. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  9793. $my_xml_file_path = $my_file_path;
  9794. $my_sub_dir = dirname($my_file_path);
  9795. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9796. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  9797. $my_xml_sub_dir = $my_sub_dir;
  9798. // Give a <resource> child to the <resources> element.
  9799. $my_resource = $xmldoc->createElement('resource');
  9800. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9801. $my_resource->setAttribute('type', 'webcontent');
  9802. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  9803. // adlcp:scormtype can be either 'sco' or 'asset'.
  9804. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9805. // xml:base is the base directory to find the files declared in this resource.
  9806. $my_resource->setAttribute('xml:base', '');
  9807. // Give a <file> child to the <resource> element.
  9808. $my_file = $xmldoc->createElement('file');
  9809. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  9810. $my_resource->appendChild($my_file);
  9811. $resources->appendChild($my_resource);
  9812. break;
  9813. }
  9814. }
  9815. }
  9816. $organizations->appendChild($organization);
  9817. $root->appendChild($organizations);
  9818. $root->appendChild($resources);
  9819. $xmldoc->appendChild($root);
  9820. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  9821. // TODO: Add a readme file here, with a short description and a link to the Reload player
  9822. // then add the file to the zip, then destroy the file (this is done automatically).
  9823. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  9824. foreach ($zip_files as $file_path) {
  9825. if (empty($file_path)) {
  9826. continue;
  9827. }
  9828. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  9829. $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
  9830. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  9831. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  9832. }
  9833. $this->create_path($dest_file);
  9834. @copy($filePath, $dest_file);
  9835. // Check if the file needs a link update.
  9836. if (in_array($file_path, array_keys($link_updates))) {
  9837. $string = file_get_contents($dest_file);
  9838. unlink($dest_file);
  9839. foreach ($link_updates[$file_path] as $old_new) {
  9840. // This is an ugly hack that allows .flv files to be found by the flv player that
  9841. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  9842. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  9843. // ../../.. to return from inc/lib/flv_player to the document/main path.
  9844. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  9845. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  9846. } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
  9847. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  9848. }
  9849. //Fix to avoid problems with default_course_document
  9850. if (strpos("main/default_course_document", $old_new['dest'] === false)) {
  9851. //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
  9852. $newDestination = $old_new['dest'];
  9853. } else {
  9854. $newDestination = str_replace('document/', '', $old_new['dest']);
  9855. }
  9856. $string = str_replace($old_new['orig'], $newDestination, $string);
  9857. // Add files inside the HTMLs
  9858. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  9859. $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
  9860. if (file_exists($sys_course_path.$new_path)) {
  9861. copy($sys_course_path.$new_path, $destinationFile);
  9862. }
  9863. }
  9864. file_put_contents($dest_file, $string);
  9865. }
  9866. if (file_exists($filePath) && $copyAll) {
  9867. $extension = $this->get_extension($filePath);
  9868. if (in_array($extension, ['html', 'html'])) {
  9869. $containerOrigin = dirname($filePath);
  9870. $containerDestination = dirname($dest_file);
  9871. $finder = new Finder();
  9872. $finder->files()->in($containerOrigin)
  9873. ->notName('*_DELETED_*')
  9874. ->exclude('share_folder')
  9875. ->exclude('chat_files')
  9876. ->exclude('certificates')
  9877. ;
  9878. if (is_dir($containerOrigin) &&
  9879. is_dir($containerDestination)
  9880. ) {
  9881. $fs = new Filesystem();
  9882. $fs->mirror(
  9883. $containerOrigin,
  9884. $containerDestination,
  9885. $finder
  9886. );
  9887. }
  9888. }
  9889. }
  9890. }
  9891. foreach ($zip_files_abs as $file_path) {
  9892. if (empty($file_path)) {
  9893. continue;
  9894. }
  9895. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  9896. continue;
  9897. }
  9898. $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
  9899. $this->create_path($dest_file);
  9900. copy($main_path.$file_path, $dest_file);
  9901. // Check if the file needs a link update.
  9902. if (in_array($file_path, array_keys($link_updates))) {
  9903. $string = file_get_contents($dest_file);
  9904. unlink($dest_file);
  9905. foreach ($link_updates[$file_path] as $old_new) {
  9906. // This is an ugly hack that allows .flv files to be found by the flv player that
  9907. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  9908. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  9909. // ../../.. to return from inc/lib/flv_player to the document/main path.
  9910. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  9911. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  9912. }
  9913. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  9914. }
  9915. file_put_contents($dest_file, $string);
  9916. }
  9917. }
  9918. if (is_array($links_to_create)) {
  9919. foreach ($links_to_create as $file => $link) {
  9920. $file_content = '<!DOCTYPE html><head>
  9921. <meta charset="'.api_get_language_isocode().'" />
  9922. <title>'.$link['title'].'</title>
  9923. </head>
  9924. <body dir="'.api_get_text_direction().'">
  9925. <div style="text-align:center">
  9926. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  9927. </body>
  9928. </html>';
  9929. file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
  9930. }
  9931. }
  9932. // Add non exportable message explanation.
  9933. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  9934. $file_content = '<!DOCTYPE html><head>
  9935. <meta charset="'.api_get_language_isocode().'" />
  9936. <title>'.$lang_not_exportable.'</title>
  9937. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  9938. </head>
  9939. <body dir="'.api_get_text_direction().'">';
  9940. $file_content .=
  9941. <<<EOD
  9942. <style>
  9943. .error-message {
  9944. font-family: arial, verdana, helvetica, sans-serif;
  9945. border-width: 1px;
  9946. border-style: solid;
  9947. left: 50%;
  9948. margin: 10px auto;
  9949. min-height: 30px;
  9950. padding: 5px;
  9951. right: 50%;
  9952. width: 500px;
  9953. background-color: #FFD1D1;
  9954. border-color: #FF0000;
  9955. color: #000;
  9956. }
  9957. </style>
  9958. <body>
  9959. <div class="error-message">
  9960. $lang_not_exportable
  9961. </div>
  9962. </body>
  9963. </html>
  9964. EOD;
  9965. if (!is_dir($archive_path.$temp_dir_short.'/document')) {
  9966. @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  9967. }
  9968. file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
  9969. // Add the extra files that go along with a SCORM package.
  9970. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  9971. $fs = new Filesystem();
  9972. $fs->mirror($main_code_path, $archive_path.$temp_dir_short);
  9973. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  9974. $manifest = @$xmldoc->saveXML();
  9975. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  9976. file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  9977. $zip_folder->add(
  9978. $archive_path.'/'.$temp_dir_short,
  9979. PCLZIP_OPT_REMOVE_PATH,
  9980. $archive_path.'/'.$temp_dir_short.'/'
  9981. );
  9982. // Clean possible temporary files.
  9983. foreach ($files_cleanup as $file) {
  9984. $res = unlink($file);
  9985. if ($res === false) {
  9986. error_log(
  9987. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  9988. 0
  9989. );
  9990. }
  9991. }
  9992. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  9993. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  9994. }
  9995. /**
  9996. * @param int $lp_id
  9997. * @return bool
  9998. */
  9999. public function scorm_export_to_pdf($lp_id)
  10000. {
  10001. $lp_id = intval($lp_id);
  10002. $files_to_export = array();
  10003. $course_data = api_get_course_info($this->cc);
  10004. if (!empty($course_data)) {
  10005. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10006. $list = self::get_flat_ordered_items_list($lp_id);
  10007. if (!empty($list)) {
  10008. foreach ($list as $item_id) {
  10009. $item = $this->items[$item_id];
  10010. switch ($item->type) {
  10011. case 'document':
  10012. //Getting documents from a LP with chamilo documents
  10013. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10014. // Try loading document from the base course.
  10015. if (empty($file_data) && !empty($sessionId)) {
  10016. $file_data = DocumentManager::get_document_data_by_id(
  10017. $item->path,
  10018. $this->cc,
  10019. false,
  10020. 0
  10021. );
  10022. }
  10023. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10024. if (file_exists($file_path)) {
  10025. $files_to_export[] = array(
  10026. 'title' => $item->get_title(),
  10027. 'path' => $file_path
  10028. );
  10029. }
  10030. break;
  10031. case 'asset': //commes from a scorm package generated by chamilo
  10032. case 'sco':
  10033. $file_path = $scorm_path.'/'.$item->path;
  10034. if (file_exists($file_path)) {
  10035. $files_to_export[] = array(
  10036. 'title' => $item->get_title(),
  10037. 'path' => $file_path
  10038. );
  10039. }
  10040. break;
  10041. case 'dir':
  10042. $files_to_export[] = array(
  10043. 'title' => $item->get_title(),
  10044. 'path' => null
  10045. );
  10046. break;
  10047. }
  10048. }
  10049. }
  10050. $pdf = new PDF();
  10051. $result = $pdf->html_to_pdf(
  10052. $files_to_export,
  10053. $this->name,
  10054. $this->cc,
  10055. true
  10056. );
  10057. return $result;
  10058. }
  10059. return false;
  10060. }
  10061. /**
  10062. * Temp function to be moved in main_api or the best place around for this.
  10063. * Creates a file path if it doesn't exist
  10064. * @param string $path
  10065. */
  10066. public function create_path($path)
  10067. {
  10068. $path_bits = explode('/', dirname($path));
  10069. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10070. $path_built = IS_WINDOWS_OS ? '' : '/';
  10071. foreach ($path_bits as $bit) {
  10072. if (!empty ($bit)) {
  10073. $new_path = $path_built.$bit;
  10074. if (is_dir($new_path)) {
  10075. $path_built = $new_path.'/';
  10076. } else {
  10077. mkdir($new_path, api_get_permissions_for_new_directories());
  10078. $path_built = $new_path.'/';
  10079. }
  10080. }
  10081. }
  10082. }
  10083. /**
  10084. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10085. * @return boolean The results of the unlink function, or false if there was no image to start with
  10086. */
  10087. public function delete_lp_image()
  10088. {
  10089. $img = $this->get_preview_image();
  10090. if ($img != '') {
  10091. $del_file = $this->get_preview_image_path(null, 'sys');
  10092. if (isset($del_file) && file_exists($del_file)) {
  10093. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10094. if (file_exists($del_file_2)) {
  10095. unlink($del_file_2);
  10096. }
  10097. $this->set_preview_image('');
  10098. return @unlink($del_file);
  10099. }
  10100. }
  10101. return false;
  10102. }
  10103. /**
  10104. * Uploads an author image to the upload/learning_path/images directory
  10105. * @param array The image array, coming from the $_FILES superglobal
  10106. * @return boolean True on success, false on error
  10107. */
  10108. public function upload_image($image_array)
  10109. {
  10110. if (!empty ($image_array['name'])) {
  10111. $upload_ok = process_uploaded_file($image_array);
  10112. $has_attachment = true;
  10113. }
  10114. if ($upload_ok) {
  10115. if ($has_attachment) {
  10116. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10117. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10118. $updir = $sys_course_path.$courseDir;
  10119. // Try to add an extension to the file if it hasn't one.
  10120. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10121. if (filter_extension($new_file_name)) {
  10122. $file_extension = explode('.', $image_array['name']);
  10123. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10124. $filename = uniqid('');
  10125. $new_file_name = $filename.'.'.$file_extension;
  10126. $new_path = $updir.'/'.$new_file_name;
  10127. // Resize the image.
  10128. $temp = new Image($image_array['tmp_name']);
  10129. $temp->resize(104);
  10130. $result = $temp->send_image($new_path);
  10131. // Storing the image filename.
  10132. if ($result) {
  10133. $this->set_preview_image($new_file_name);
  10134. //Resize to 64px to use on course homepage
  10135. $temp->resize(64);
  10136. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10137. return true;
  10138. }
  10139. }
  10140. }
  10141. }
  10142. return false;
  10143. }
  10144. /**
  10145. * @param int $lp_id
  10146. * @param string $status
  10147. */
  10148. public function set_autolaunch($lp_id, $status)
  10149. {
  10150. $course_id = api_get_course_int_id();
  10151. $lp_id = intval($lp_id);
  10152. $status = intval($status);
  10153. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10154. // Setting everything to autolaunch = 0
  10155. $attributes['autolaunch'] = 0;
  10156. $where = array(
  10157. 'session_id = ? AND c_id = ? ' => array(
  10158. api_get_session_id(),
  10159. $course_id
  10160. )
  10161. );
  10162. Database::update($lp_table, $attributes, $where);
  10163. if ($status == 1) {
  10164. //Setting my lp_id to autolaunch = 1
  10165. $attributes['autolaunch'] = 1;
  10166. $where = array(
  10167. 'id = ? AND session_id = ? AND c_id = ?' => array(
  10168. $lp_id,
  10169. api_get_session_id(),
  10170. $course_id
  10171. )
  10172. );
  10173. Database::update($lp_table, $attributes, $where);
  10174. }
  10175. }
  10176. /**
  10177. * Gets previous_item_id for the next element of the lp_item table
  10178. * @author Isaac flores paz
  10179. * @return integer Previous item ID
  10180. */
  10181. public function select_previous_item_id()
  10182. {
  10183. $course_id = api_get_course_int_id();
  10184. if ($this->debug > 0) {
  10185. error_log('New LP - In learnpath::select_previous_item_id()', 0);
  10186. }
  10187. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10188. // Get the max order of the items
  10189. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10190. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'";
  10191. $rs_max_order = Database::query($sql);
  10192. $row_max_order = Database::fetch_object($rs_max_order);
  10193. $max_order = $row_max_order->display_order;
  10194. // Get the previous item ID
  10195. $sql = "SELECT id as previous FROM $table_lp_item
  10196. WHERE
  10197. c_id = $course_id AND
  10198. lp_id = '".$this->lp_id."' AND
  10199. display_order = '".$max_order."' ";
  10200. $rs_max = Database::query($sql);
  10201. $row_max = Database::fetch_object($rs_max);
  10202. // Return the previous item ID
  10203. return $row_max->previous;
  10204. }
  10205. /**
  10206. * Copies an LP
  10207. */
  10208. public function copy()
  10209. {
  10210. // Course builder
  10211. $cb = new CourseBuilder();
  10212. //Setting tools that will be copied
  10213. $cb->set_tools_to_build(array('learnpaths'));
  10214. //Setting elements that will be copied
  10215. $cb->set_tools_specific_id_list(
  10216. array('learnpaths' => array($this->lp_id))
  10217. );
  10218. $course = $cb->build();
  10219. //Course restorer
  10220. $course_restorer = new CourseRestorer($course);
  10221. $course_restorer->set_add_text_in_items(true);
  10222. $course_restorer->set_tool_copy_settings(
  10223. array('learnpaths' => array('reset_dates' => true))
  10224. );
  10225. $course_restorer->restore(
  10226. api_get_course_id(),
  10227. api_get_session_id(),
  10228. false,
  10229. false
  10230. );
  10231. }
  10232. /**
  10233. * Verify document size
  10234. * @param string $s
  10235. * @return bool
  10236. */
  10237. public static function verify_document_size($s)
  10238. {
  10239. $post_max = ini_get('post_max_size');
  10240. if (substr($post_max, -1, 1) == 'M') {
  10241. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10242. } elseif (substr($post_max, -1, 1) == 'G') {
  10243. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10244. }
  10245. $upl_max = ini_get('upload_max_filesize');
  10246. if (substr($upl_max, -1, 1) == 'M') {
  10247. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10248. } elseif (substr($upl_max, -1, 1) == 'G') {
  10249. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10250. }
  10251. $documents_total_space = DocumentManager::documents_total_space();
  10252. $course_max_space = DocumentManager::get_course_quota();
  10253. $total_size = filesize($s) + $documents_total_space;
  10254. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10255. return true;
  10256. } else {
  10257. return false;
  10258. }
  10259. }
  10260. /**
  10261. * Clear LP prerequisites
  10262. */
  10263. public function clear_prerequisites()
  10264. {
  10265. $course_id = $this->get_course_int_id();
  10266. if ($this->debug > 0) {
  10267. error_log('New LP - In learnpath::clear_prerequisites()', 0);
  10268. }
  10269. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10270. $lp_id = $this->get_id();
  10271. //Cleaning prerequisites
  10272. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10273. WHERE c_id = ".$course_id." AND lp_id = '$lp_id'";
  10274. Database::query($sql);
  10275. //Cleaning mastery score for exercises
  10276. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10277. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND item_type = 'quiz'";
  10278. Database::query($sql);
  10279. }
  10280. public function set_previous_step_as_prerequisite_for_all_items()
  10281. {
  10282. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10283. $course_id = $this->get_course_int_id();
  10284. $lp_id = $this->get_id();
  10285. if (!empty($this->items)) {
  10286. $previous_item_id = null;
  10287. $previous_item_max = 0;
  10288. $previous_item_type = null;
  10289. $last_item_not_dir = null;
  10290. $last_item_not_dir_type = null;
  10291. $last_item_not_dir_max = null;
  10292. foreach ($this->ordered_items as $itemId) {
  10293. $item = $this->getItem($itemId);
  10294. // if there was a previous item... (otherwise jump to set it)
  10295. if (!empty($previous_item_id)) {
  10296. $current_item_id = $item->get_id(); //save current id
  10297. if ($item->get_type() != 'dir') {
  10298. // Current item is not a folder, so it qualifies to get a prerequisites
  10299. if ($last_item_not_dir_type == 'quiz') {
  10300. // if previous is quiz, mark its max score as default score to be achieved
  10301. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10302. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$last_item_not_dir'";
  10303. Database::query($sql);
  10304. }
  10305. // now simply update the prerequisite to set it to the last non-chapter item
  10306. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10307. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$current_item_id'";
  10308. Database::query($sql);
  10309. // record item as 'non-chapter' reference
  10310. $last_item_not_dir = $item->get_id();
  10311. $last_item_not_dir_type = $item->get_type();
  10312. $last_item_not_dir_max = $item->get_max();
  10313. }
  10314. } else {
  10315. if ($item->get_type() != 'dir') {
  10316. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10317. $last_item_not_dir = $item->get_id();
  10318. $last_item_not_dir_type = $item->get_type();
  10319. $last_item_not_dir_max = $item->get_max();
  10320. }
  10321. }
  10322. // Saving the item as "previous item" for the next loop
  10323. $previous_item_id = $item->get_id();
  10324. $previous_item_max = $item->get_max();
  10325. $previous_item_type = $item->get_type();
  10326. }
  10327. }
  10328. }
  10329. /**
  10330. * @param array $params
  10331. */
  10332. public static function createCategory($params)
  10333. {
  10334. $em = Database::getManager();
  10335. $item = new CLpCategory();
  10336. $item->setName($params['name']);
  10337. $item->setCId($params['c_id']);
  10338. $em->persist($item);
  10339. $em->flush();
  10340. }
  10341. /**
  10342. * @param array $params
  10343. */
  10344. public static function updateCategory($params)
  10345. {
  10346. $em = Database::getManager();
  10347. /** @var CLpCategory $item */
  10348. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10349. if ($item) {
  10350. $item->setName($params['name']);
  10351. $em->merge($item);
  10352. $em->flush();
  10353. }
  10354. }
  10355. /**
  10356. * @param int $id
  10357. */
  10358. public static function moveUpCategory($id)
  10359. {
  10360. $em = Database::getManager();
  10361. /** @var CLpCategory $item */
  10362. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10363. if ($item) {
  10364. $position = $item->getPosition() - 1;
  10365. $item->setPosition($position);
  10366. $em->persist($item);
  10367. $em->flush();
  10368. }
  10369. }
  10370. /**
  10371. * @param int $id
  10372. */
  10373. public static function moveDownCategory($id)
  10374. {
  10375. $em = Database::getManager();
  10376. /** @var CLpCategory $item */
  10377. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10378. if ($item) {
  10379. $position = $item->getPosition() + 1;
  10380. $item->setPosition($position);
  10381. $em->persist($item);
  10382. $em->flush();
  10383. }
  10384. }
  10385. /**
  10386. * @param int $courseId
  10387. * @return int|mixed
  10388. */
  10389. public static function getCountCategories($courseId)
  10390. {
  10391. if (empty($course_id)) {
  10392. return 0;
  10393. }
  10394. $em = Database::getManager();
  10395. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10396. $query->setParameter('id', $courseId);
  10397. return $query->getSingleScalarResult();
  10398. }
  10399. /**
  10400. * @param int $courseId
  10401. *
  10402. * @return mixed
  10403. */
  10404. public static function getCategories($courseId)
  10405. {
  10406. $em = Database::getManager();
  10407. //Default behaviour
  10408. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10409. array('cId' => $course_id),
  10410. array('name' => 'ASC')
  10411. );*/
  10412. // Using doctrine extensions
  10413. /** @var SortableRepository $repo */
  10414. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10415. $items = $repo
  10416. ->getBySortableGroupsQuery(['cId' => $courseId])
  10417. ->getResult();
  10418. return $items;
  10419. }
  10420. /**
  10421. * @param int $id
  10422. *
  10423. * @return CLpCategory
  10424. */
  10425. public static function getCategory($id)
  10426. {
  10427. $em = Database::getManager();
  10428. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10429. return $item;
  10430. }
  10431. /**
  10432. * @param int $courseId
  10433. * @return array
  10434. */
  10435. public static function getCategoryByCourse($courseId)
  10436. {
  10437. $em = Database::getManager();
  10438. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10439. array('cId' => $courseId)
  10440. );
  10441. return $items;
  10442. }
  10443. /**
  10444. * @param int $id
  10445. *
  10446. * @return mixed
  10447. */
  10448. public static function deleteCategory($id)
  10449. {
  10450. $em = Database::getManager();
  10451. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10452. if ($item) {
  10453. $courseId = $item->getCId();
  10454. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10455. $query->setParameter('id', $courseId);
  10456. $query->setParameter('catId', $item->getId());
  10457. $lps = $query->getResult();
  10458. // Setting category = 0.
  10459. if ($lps) {
  10460. foreach ($lps as $lpItem) {
  10461. $lpItem->setCategoryId(0);
  10462. }
  10463. }
  10464. // Removing category.
  10465. $em->remove($item);
  10466. $em->flush();
  10467. }
  10468. }
  10469. /**
  10470. * @param int $courseId
  10471. * @param bool $addSelectOption
  10472. *
  10473. * @return mixed
  10474. */
  10475. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10476. {
  10477. $items = self::getCategoryByCourse($courseId);
  10478. $cats = array();
  10479. if ($addSelectOption) {
  10480. $cats = array(get_lang('SelectACategory'));
  10481. }
  10482. if (!empty($items)) {
  10483. foreach ($items as $cat) {
  10484. $cats[$cat->getId()] = $cat->getName();
  10485. }
  10486. }
  10487. return $cats;
  10488. }
  10489. /**
  10490. * Return the scorm item type object with spaces replaced with _
  10491. * The return result is use to build a css classname like scorm_type_$return
  10492. * @param $in_type
  10493. * @return mixed
  10494. */
  10495. private static function format_scorm_type_item($in_type)
  10496. {
  10497. return str_replace(' ', '_', $in_type);
  10498. }
  10499. /**
  10500. * @param string $courseCode
  10501. * @param int $lp_id
  10502. * @param int $user_id
  10503. *
  10504. * @return learnpath
  10505. */
  10506. public static function getLpFromSession($courseCode, $lp_id, $user_id)
  10507. {
  10508. $learnPath = null;
  10509. $lpObject = Session::read('lpobject');
  10510. if ($lpObject !== null) {
  10511. $learnPath = unserialize($lpObject);
  10512. }
  10513. if (!is_object($learnPath)) {
  10514. $learnPath = new learnpath($courseCode, $lp_id, $user_id);
  10515. }
  10516. return $learnPath;
  10517. }
  10518. /**
  10519. * @param int $itemId
  10520. * @return learnpathItem|false
  10521. */
  10522. public function getItem($itemId)
  10523. {
  10524. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  10525. return $this->items[$itemId];
  10526. }
  10527. return false;
  10528. }
  10529. /**
  10530. * @return int
  10531. */
  10532. public function getCategoryId()
  10533. {
  10534. return $this->categoryId;
  10535. }
  10536. /**
  10537. * @param int $categoryId
  10538. * @return bool
  10539. */
  10540. public function setCategoryId($categoryId)
  10541. {
  10542. $this->categoryId = intval($categoryId);
  10543. $courseId = api_get_course_int_id();
  10544. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10545. $lp_id = $this->get_id();
  10546. $sql = "UPDATE $lp_table SET category_id = ".$this->categoryId."
  10547. WHERE c_id = $courseId AND id = $lp_id";
  10548. Database::query($sql);
  10549. return true;
  10550. }
  10551. /**
  10552. * Get whether this is a learning path with the possibility to subscribe
  10553. * users or not
  10554. * @return int
  10555. */
  10556. public function getSubscribeUsers()
  10557. {
  10558. return $this->subscribeUsers;
  10559. }
  10560. /**
  10561. * Set whether this is a learning path with the possibility to subscribe
  10562. * users or not
  10563. * @param int $value (0 = false, 1 = true)
  10564. * @return bool
  10565. */
  10566. public function setSubscribeUsers($value)
  10567. {
  10568. if ($this->debug > 0) {
  10569. error_log('New LP - In learnpath::set_subscribe_users()', 0);
  10570. }
  10571. $this->subscribeUsers = (int) $value;
  10572. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10573. $lp_id = $this->get_id();
  10574. $sql = "UPDATE $lp_table SET subscribe_users = ".$this->subscribeUsers."
  10575. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  10576. Database::query($sql);
  10577. return true;
  10578. }
  10579. /**
  10580. * Calculate the count of stars for a user in this LP
  10581. * This calculation is based on the following rules:
  10582. * - the student gets one star when he gets to 50% of the learning path
  10583. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  10584. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  10585. * - the student gets the final star when the score for the *last* test is >= 80%
  10586. * @param int $sessionId Optional. The session ID
  10587. * @return int The count of stars
  10588. */
  10589. public function getCalculateStars($sessionId = 0)
  10590. {
  10591. $stars = 0;
  10592. $progress = self::getProgress(
  10593. $this->lp_id,
  10594. $this->user_id,
  10595. $this->course_int_id,
  10596. $sessionId
  10597. );
  10598. if ($progress >= 50) {
  10599. $stars++;
  10600. }
  10601. // Calculate stars chapters evaluation
  10602. $exercisesItems = $this->getExercisesItems();
  10603. if (!empty($exercisesItems)) {
  10604. $totalResult = 0;
  10605. foreach ($exercisesItems as $exerciseItem) {
  10606. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10607. $this->user_id,
  10608. $exerciseItem->path,
  10609. $this->course_int_id,
  10610. $sessionId,
  10611. $this->lp_id,
  10612. $exerciseItem->db_id
  10613. );
  10614. $exerciseResultInfo = end($exerciseResultInfo);
  10615. if (!$exerciseResultInfo) {
  10616. continue;
  10617. }
  10618. if (!empty($exerciseResultInfo['exe_weighting'])) {
  10619. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  10620. } else {
  10621. $exerciseResult = 0;
  10622. }
  10623. $totalResult += $exerciseResult;
  10624. }
  10625. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  10626. if ($totalExerciseAverage >= 50) {
  10627. $stars++;
  10628. }
  10629. if ($totalExerciseAverage >= 80) {
  10630. $stars++;
  10631. }
  10632. }
  10633. // Calculate star for final evaluation
  10634. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10635. if (!empty($finalEvaluationItem)) {
  10636. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10637. $this->user_id,
  10638. $finalEvaluationItem->path,
  10639. $this->course_int_id,
  10640. $sessionId,
  10641. $this->lp_id,
  10642. $finalEvaluationItem->db_id
  10643. );
  10644. $evaluationResultInfo = end($evaluationResultInfo);
  10645. if ($evaluationResultInfo) {
  10646. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  10647. if ($evaluationResult >= 80) {
  10648. $stars++;
  10649. }
  10650. }
  10651. }
  10652. return $stars;
  10653. }
  10654. /**
  10655. * Get the items of exercise type
  10656. * @return array The items. Otherwise return false
  10657. */
  10658. public function getExercisesItems()
  10659. {
  10660. $exercises = [];
  10661. foreach ($this->items as $item) {
  10662. if ($item->type != 'quiz') {
  10663. continue;
  10664. }
  10665. $exercises[] = $item;
  10666. }
  10667. array_pop($exercises);
  10668. return $exercises;
  10669. }
  10670. /**
  10671. * Get the item of exercise type (evaluation type)
  10672. * @return array The final evaluation. Otherwise return false
  10673. */
  10674. public function getFinalEvaluationItem()
  10675. {
  10676. $exercises = [];
  10677. foreach ($this->items as $item) {
  10678. if ($item->type != 'quiz') {
  10679. continue;
  10680. }
  10681. $exercises[] = $item;
  10682. }
  10683. return array_pop($exercises);
  10684. }
  10685. /**
  10686. * Calculate the total points achieved for the current user in this learning path
  10687. * @param int $sessionId Optional. The session Id
  10688. * @return int
  10689. */
  10690. public function getCalculateScore($sessionId = 0)
  10691. {
  10692. // Calculate stars chapters evaluation
  10693. $exercisesItems = $this->getExercisesItems();
  10694. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10695. $totalExercisesResult = 0;
  10696. $totalEvaluationResult = 0;
  10697. if ($exercisesItems !== false) {
  10698. foreach ($exercisesItems as $exerciseItem) {
  10699. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10700. $this->user_id,
  10701. $exerciseItem->path,
  10702. $this->course_int_id,
  10703. $sessionId,
  10704. $this->lp_id,
  10705. $exerciseItem->db_id
  10706. );
  10707. $exerciseResultInfo = end($exerciseResultInfo);
  10708. if (!$exerciseResultInfo) {
  10709. continue;
  10710. }
  10711. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  10712. }
  10713. }
  10714. if (!empty($finalEvaluationItem)) {
  10715. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10716. $this->user_id,
  10717. $finalEvaluationItem->path,
  10718. $this->course_int_id,
  10719. $sessionId,
  10720. $this->lp_id,
  10721. $finalEvaluationItem->db_id
  10722. );
  10723. $evaluationResultInfo = end($evaluationResultInfo);
  10724. if ($evaluationResultInfo) {
  10725. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  10726. }
  10727. }
  10728. return $totalExercisesResult + $totalEvaluationResult;
  10729. }
  10730. /**
  10731. * Check if URL is not allowed to be show in a iframe
  10732. * @param string $src
  10733. *
  10734. * @return string
  10735. */
  10736. public function fixBlockedLinks($src)
  10737. {
  10738. $urlInfo = parse_url($src);
  10739. $platformProtocol = 'https';
  10740. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  10741. $platformProtocol = 'http';
  10742. }
  10743. $protocolFixApplied = false;
  10744. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  10745. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  10746. if ($platformProtocol != $scheme) {
  10747. Session::write('x_frame_source', $src);
  10748. $src = 'blank.php?error=x_frames_options';
  10749. $protocolFixApplied = true;
  10750. }
  10751. if ($protocolFixApplied == false) {
  10752. if (strpos($src, api_get_path(WEB_CODE_PATH)) === false) {
  10753. // Check X-Frame-Options
  10754. $ch = curl_init();
  10755. $options = array(
  10756. CURLOPT_URL => $src,
  10757. CURLOPT_RETURNTRANSFER => true,
  10758. CURLOPT_HEADER => true,
  10759. CURLOPT_FOLLOWLOCATION => true,
  10760. CURLOPT_ENCODING => "",
  10761. CURLOPT_AUTOREFERER => true,
  10762. CURLOPT_CONNECTTIMEOUT => 120,
  10763. CURLOPT_TIMEOUT => 120,
  10764. CURLOPT_MAXREDIRS => 10,
  10765. );
  10766. curl_setopt_array($ch, $options);
  10767. $response = curl_exec($ch);
  10768. $httpCode = curl_getinfo($ch);
  10769. $headers = substr($response, 0, $httpCode['header_size']);
  10770. $error = false;
  10771. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  10772. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  10773. ) {
  10774. $error = true;
  10775. }
  10776. if ($error) {
  10777. Session::write('x_frame_source', $src);
  10778. $src = 'blank.php?error=x_frames_options';
  10779. }
  10780. }
  10781. }
  10782. return $src;
  10783. }
  10784. /**
  10785. * Check if this LP has a created forum in the basis course
  10786. * @return boolean
  10787. */
  10788. public function lpHasForum()
  10789. {
  10790. $forumTable = Database::get_course_table(TABLE_FORUM);
  10791. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10792. $fakeFrom = "
  10793. $forumTable f
  10794. INNER JOIN $itemProperty ip
  10795. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  10796. ";
  10797. $resultData = Database::select(
  10798. 'COUNT(f.iid) AS qty',
  10799. $fakeFrom,
  10800. [
  10801. 'where' => [
  10802. 'ip.visibility != ? AND ' => 2,
  10803. 'ip.tool = ? AND ' => TOOL_FORUM,
  10804. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10805. 'f.lp_id = ?' => intval($this->lp_id)
  10806. ]
  10807. ],
  10808. 'first'
  10809. );
  10810. return $resultData['qty'] > 0;
  10811. }
  10812. /**
  10813. * Get the forum for this learning path
  10814. * @param int $sessionId
  10815. * @return boolean
  10816. */
  10817. public function getForum($sessionId = 0)
  10818. {
  10819. $forumTable = Database::get_course_table(TABLE_FORUM);
  10820. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10821. $fakeFrom = "$forumTable f
  10822. INNER JOIN $itemProperty ip ";
  10823. if ($this->lp_session_id == 0) {
  10824. $fakeFrom .= "
  10825. ON (
  10826. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  10827. f.session_id = ip.session_id OR ip.session_id IS NULL
  10828. )
  10829. )
  10830. ";
  10831. } else {
  10832. $fakeFrom .= "
  10833. ON (
  10834. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  10835. )
  10836. ";
  10837. }
  10838. $resultData = Database::select(
  10839. 'f.*',
  10840. $fakeFrom,
  10841. [
  10842. 'where' => [
  10843. 'ip.visibility != ? AND ' => 2,
  10844. 'ip.tool = ? AND ' => TOOL_FORUM,
  10845. 'f.session_id = ? AND ' => $sessionId,
  10846. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10847. 'f.lp_id = ?' => intval($this->lp_id)
  10848. ]
  10849. ],
  10850. 'first'
  10851. );
  10852. if (empty($resultData)) {
  10853. return false;
  10854. }
  10855. return $resultData;
  10856. }
  10857. /**
  10858. * Create a forum for this learning path
  10859. * @param type $forumCategoryId
  10860. * @return int The forum ID if was created. Otherwise return false
  10861. */
  10862. public function createForum($forumCategoryId)
  10863. {
  10864. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  10865. $forumId = store_forum(
  10866. [
  10867. 'lp_id' => $this->lp_id,
  10868. 'forum_title' => $this->name,
  10869. 'forum_comment' => null,
  10870. 'forum_category' => intval($forumCategoryId),
  10871. 'students_can_edit_group' => ['students_can_edit' => 0],
  10872. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  10873. 'default_view_type_group' => ['default_view_type' => 'flat'],
  10874. 'group_forum' => 0,
  10875. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public']
  10876. ],
  10877. [],
  10878. true
  10879. );
  10880. return $forumId;
  10881. }
  10882. /**
  10883. * Check and obtain the lp final item if exist
  10884. *
  10885. * @return learnpathItem
  10886. */
  10887. private function getFinalItem()
  10888. {
  10889. if (empty($this->items)) {
  10890. return null;
  10891. }
  10892. foreach ($this->items as $item) {
  10893. if ($item->type !== 'final_item') {
  10894. continue;
  10895. }
  10896. return $item;
  10897. }
  10898. }
  10899. /**
  10900. * Get the LP Final Item Template
  10901. *
  10902. * @return string
  10903. */
  10904. private function getFinalItemTemplate()
  10905. {
  10906. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  10907. }
  10908. /**
  10909. * Get the LP Final Item Url
  10910. *
  10911. * @return string
  10912. */
  10913. private function getSavedFinalItem()
  10914. {
  10915. $finalItem = $this->getFinalItem();
  10916. $doc = DocumentManager::get_document_data_by_id(
  10917. $finalItem->path,
  10918. $this->cc
  10919. );
  10920. if ($doc && file_exists($doc['absolute_path'])) {
  10921. return file_get_contents($doc['absolute_path']);
  10922. }
  10923. return '';
  10924. }
  10925. /**
  10926. * Get the LP Final Item form
  10927. *
  10928. * @return string
  10929. */
  10930. public function getFinalItemForm()
  10931. {
  10932. $finalItem = $this->getFinalItem();
  10933. $title = '';
  10934. if ($finalItem) {
  10935. $title = $finalItem->get_title();
  10936. $buttonText = get_lang('Save');
  10937. $content = $this->getSavedFinalItem();
  10938. } else {
  10939. $buttonText = get_lang('LPCreateDocument');
  10940. $content = $this->getFinalItemTemplate();
  10941. }
  10942. $courseInfo = api_get_course_info();
  10943. $result = $this->generate_lp_folder($courseInfo);
  10944. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  10945. $relative_prefix = '../../';
  10946. $editorConfig = [
  10947. 'ToolbarSet' => 'LearningPathDocuments',
  10948. 'Width' => '100%',
  10949. 'Height' => '500',
  10950. 'FullPage' => true,
  10951. 'CreateDocumentDir' => $relative_prefix,
  10952. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  10953. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path
  10954. ];
  10955. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  10956. 'type' => 'document',
  10957. 'lp_id' => $this->lp_id
  10958. ]);
  10959. $form = new FormValidator('final_item', 'POST', $url);
  10960. $form->addText('title', get_lang('Title'));
  10961. $form->addButtonSave($buttonText);
  10962. $form->addHtml(
  10963. Display::return_message(
  10964. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  10965. 'normal',
  10966. false
  10967. )
  10968. );
  10969. $renderer = $form->defaultRenderer();
  10970. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  10971. $form->addHtmlEditor(
  10972. 'content_lp_certificate',
  10973. null,
  10974. true,
  10975. false,
  10976. $editorConfig,
  10977. true
  10978. );
  10979. $form->addHidden('action', 'add_final_item');
  10980. $form->addHidden('path', Session::read('pathItem'));
  10981. $form->addHidden('previous', $this->get_last());
  10982. $form->setDefaults(
  10983. ['title' => $title, 'content_lp_certificate' => $content]
  10984. );
  10985. if ($form->validate()) {
  10986. $values = $form->exportValues();
  10987. $lastItemId = $this->get_last();
  10988. if (!$finalItem) {
  10989. $documentId = $this->create_document(
  10990. $this->course_info,
  10991. $values['content_lp_certificate'],
  10992. $values['title']
  10993. );
  10994. $this->add_item(
  10995. 0,
  10996. $lastItemId,
  10997. 'final_item',
  10998. $documentId,
  10999. $values['title'],
  11000. ''
  11001. );
  11002. Display::addFlash(
  11003. Display::return_message(get_lang('Added'))
  11004. );
  11005. } else {
  11006. $this->edit_document($this->course_info);
  11007. }
  11008. }
  11009. return $form->returnForm();
  11010. }
  11011. /**
  11012. * Check if the current lp item is first, both, last or none from lp list
  11013. *
  11014. * @param int $currentItemId
  11015. * @return string
  11016. */
  11017. public function isFirstOrLastItem($currentItemId)
  11018. {
  11019. if ($this->debug > 0) {
  11020. error_log('New LP - In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11021. }
  11022. $lpItemId = [];
  11023. $typeListNotToVerify = self::getChapterTypes();
  11024. // Using get_toc() function instead $this->items because returns the correct order of the items
  11025. foreach ($this->get_toc() as $item) {
  11026. if (!in_array($item['type'], $typeListNotToVerify)) {
  11027. $lpItemId[] = $item['id'];
  11028. }
  11029. }
  11030. $lastLpItemIndex = count($lpItemId) - 1;
  11031. $position = array_search($currentItemId, $lpItemId);
  11032. switch ($position) {
  11033. case 0:
  11034. if (!$lastLpItemIndex) {
  11035. $answer = 'both';
  11036. break;
  11037. }
  11038. $answer = 'first';
  11039. break;
  11040. case $lastLpItemIndex:
  11041. $answer = 'last';
  11042. break;
  11043. default:
  11044. $answer = 'none';
  11045. }
  11046. return $answer;
  11047. }
  11048. /**
  11049. * Get whether this is a learning path with the accumulated SCORM time or not
  11050. * @return int
  11051. */
  11052. public function getAccumulateScormTime()
  11053. {
  11054. return $this->accumulateScormTime;
  11055. }
  11056. /**
  11057. * Set whether this is a learning path with the accumulated SCORM time or not
  11058. * @param int $value (0 = false, 1 = true)
  11059. * @return bool Always returns true
  11060. */
  11061. public function setAccumulateScormTime($value)
  11062. {
  11063. if ($this->debug > 0) {
  11064. error_log('New LP - In learnpath::setAccumulateScormTime()', 0);
  11065. }
  11066. $this->accumulateScormTime = intval($value);
  11067. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11068. $lp_id = $this->get_id();
  11069. $sql = "UPDATE $lp_table
  11070. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11071. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  11072. Database::query($sql);
  11073. return true;
  11074. }
  11075. /**
  11076. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11077. * the new learning path tool.
  11078. *
  11079. * The function is a big switch on tool type.
  11080. * In each case, we query the corresponding table for information and build the link
  11081. * with that information.
  11082. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11083. * previous work (display_addedresource_link_in_learnpath())
  11084. * @param int $course_id Course code
  11085. * @param int $learningPathId The learning path ID (in lp table)
  11086. * @param int $id_in_path the unique index in the items table
  11087. * @param int $lpViewId
  11088. * @param string $origin
  11089. * @return string
  11090. */
  11091. public static function rl_get_resource_link_for_learnpath(
  11092. $course_id,
  11093. $learningPathId,
  11094. $id_in_path,
  11095. $lpViewId,
  11096. $origin = 'learnpath'
  11097. ) {
  11098. $session_id = api_get_session_id();
  11099. $learningPathId = intval($learningPathId);
  11100. $id_in_path = intval($id_in_path);
  11101. $lpViewId = intval($lpViewId);
  11102. $em = Database::getManager();
  11103. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11104. /** @var CLpItem $rowItem */
  11105. $rowItem = $lpItemRepo->findOneBy([
  11106. 'cId' => $course_id,
  11107. 'lpId' => $learningPathId,
  11108. 'id' => $id_in_path
  11109. ]);
  11110. if (!$rowItem) {
  11111. return -1;
  11112. }
  11113. $course_info = api_get_course_info_by_id($course_id);
  11114. $course_code = $course_info['code'];
  11115. $type = $rowItem->getItemType();
  11116. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11117. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11118. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11119. $link = '';
  11120. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11121. switch ($type) {
  11122. case 'dir':
  11123. return $main_dir_path.'lp/blank.php';
  11124. case TOOL_CALENDAR_EVENT:
  11125. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11126. case TOOL_ANNOUNCEMENT:
  11127. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11128. case TOOL_LINK:
  11129. $linkInfo = Link::get_link_info($id);
  11130. return $linkInfo['url'];
  11131. case TOOL_QUIZ:
  11132. if (empty($id)) {
  11133. return '';
  11134. }
  11135. // Get the lp_item_view with the highest view_count.
  11136. $learnpathItemViewResult = $em
  11137. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11138. ->findBy(
  11139. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11140. ['viewCount' => 'DESC'],
  11141. 1
  11142. );
  11143. /** @var CLpItemView $learnpathItemViewData */
  11144. $learnpathItemViewData = current($learnpathItemViewResult);
  11145. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11146. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11147. .http_build_query([
  11148. 'lp_init' => 1,
  11149. 'learnpath_item_view_id' => $learnpathItemViewId,
  11150. 'learnpath_id' => $learningPathId,
  11151. 'learnpath_item_id' => $id_in_path,
  11152. 'exerciseId' => $id
  11153. ]);
  11154. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11155. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11156. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND id=$id");
  11157. $myrow = Database::fetch_array($result);
  11158. $path = $myrow['path'];
  11159. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11160. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11161. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11162. case TOOL_FORUM:
  11163. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11164. case TOOL_THREAD: //forum post
  11165. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11166. if (empty($id)) {
  11167. return '';
  11168. }
  11169. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11170. $result = Database::query($sql);
  11171. $myrow = Database::fetch_array($result);
  11172. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11173. .$extraParams;
  11174. case TOOL_POST:
  11175. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11176. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11177. $myrow = Database::fetch_array($result);
  11178. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11179. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11180. case TOOL_DOCUMENT:
  11181. $document = $em
  11182. ->getRepository('ChamiloCourseBundle:CDocument')
  11183. ->findOneBy(['cId' => $course_id, 'id' => $id]);
  11184. if (!$document) {
  11185. return '';
  11186. }
  11187. $documentPathInfo = pathinfo($document->getPath());
  11188. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  11189. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11190. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  11191. $openmethod = 2;
  11192. $officedoc = false;
  11193. Session::write('openmethod', $openmethod);
  11194. Session::write('officedoc', $officedoc);
  11195. if ($showDirectUrl) {
  11196. return $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11197. }
  11198. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11199. case TOOL_LP_FINAL_ITEM:
  11200. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11201. .$extraParams;
  11202. case 'assignments':
  11203. return $main_dir_path.'work/work.php?'.$extraParams;
  11204. case TOOL_DROPBOX:
  11205. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11206. case 'introduction_text': //DEPRECATED
  11207. return '';
  11208. case TOOL_COURSE_DESCRIPTION:
  11209. return $main_dir_path.'course_description?'.$extraParams;
  11210. case TOOL_GROUP:
  11211. return $main_dir_path.'group/group.php?'.$extraParams;
  11212. case TOOL_USER:
  11213. return $main_dir_path.'user/user.php?'.$extraParams;
  11214. case TOOL_STUDENTPUBLICATION:
  11215. if (!empty($rowItem->getPath())) {
  11216. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11217. }
  11218. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11219. } //end switch
  11220. return $link;
  11221. }
  11222. /**
  11223. * Gets the name of a resource (generally used in learnpath when no name is provided)
  11224. *
  11225. * @author Yannick Warnier <ywarnier@beeznest.org>
  11226. * @param string Course code
  11227. * @param string The tool type (using constants declared in main_api.lib.php)
  11228. * @param integer The resource ID
  11229. * @return string
  11230. */
  11231. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11232. {
  11233. $_course = api_get_course_info($course_code);
  11234. $course_id = $_course['real_id'];
  11235. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11236. $learningPathId = intval($learningPathId);
  11237. $id_in_path = intval($id_in_path);
  11238. $sql_item = "SELECT item_type, title, ref FROM $tbl_lp_item
  11239. WHERE c_id = $course_id AND lp_id = $learningPathId AND id = $id_in_path";
  11240. $res_item = Database::query($sql_item);
  11241. if (Database::num_rows($res_item) < 1) {
  11242. return '';
  11243. }
  11244. $row_item = Database::fetch_array($res_item);
  11245. $type = strtolower($row_item['item_type']);
  11246. $id = $row_item['ref'];
  11247. $output = '';
  11248. switch ($type) {
  11249. case TOOL_CALENDAR_EVENT:
  11250. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11251. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11252. $myrow = Database::fetch_array($result);
  11253. $output = $myrow['title'];
  11254. break;
  11255. case TOOL_ANNOUNCEMENT:
  11256. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11257. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11258. $myrow = Database::fetch_array($result);
  11259. $output = $myrow['title'];
  11260. break;
  11261. case TOOL_LINK:
  11262. // Doesn't take $target into account.
  11263. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11264. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11265. $myrow = Database::fetch_array($result);
  11266. $output = $myrow['title'];
  11267. break;
  11268. case TOOL_QUIZ:
  11269. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11270. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
  11271. $myrow = Database::fetch_array($result);
  11272. $output = $myrow['title'];
  11273. break;
  11274. case TOOL_FORUM:
  11275. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11276. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
  11277. $myrow = Database::fetch_array($result);
  11278. $output = $myrow['forum_name'];
  11279. break;
  11280. case TOOL_THREAD: //=topics
  11281. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11282. // Grabbing the title of the post.
  11283. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11284. $result_title = Database::query($sql_title);
  11285. $myrow_title = Database::fetch_array($result_title);
  11286. $output = $myrow_title['post_title'];
  11287. break;
  11288. case TOOL_POST:
  11289. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11290. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  11291. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11292. $result = Database::query($sql);
  11293. $post = Database::fetch_array($result);
  11294. $output = $post['post_title'];
  11295. break;
  11296. case 'dir':
  11297. $title = $row_item['title'];
  11298. if (!empty($title)) {
  11299. $output = $title;
  11300. } else {
  11301. $output = '-';
  11302. }
  11303. break;
  11304. case TOOL_DOCUMENT:
  11305. $title = $row_item['title'];
  11306. if (!empty($title)) {
  11307. $output = $title;
  11308. } else {
  11309. $output = '-';
  11310. }
  11311. break;
  11312. case 'hotpotatoes':
  11313. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11314. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND id = $id");
  11315. $myrow = Database::fetch_array($result);
  11316. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11317. $last = count($pathname) - 1; // Making a correct name for the link.
  11318. $filename = $pathname[$last]; // Making a correct name for the link.
  11319. $ext = explode('.', $filename);
  11320. $ext = strtolower($ext[sizeof($ext) - 1]);
  11321. $myrow['path'] = rawurlencode($myrow['path']);
  11322. $output = $filename;
  11323. break;
  11324. }
  11325. return stripslashes($output);
  11326. }
  11327. /**
  11328. * Get the parent names for the current item
  11329. * @param int $newItemId Optional. The item ID
  11330. * @return array
  11331. */
  11332. public function getCurrentItemParentNames($newItemId = 0)
  11333. {
  11334. $newItemId = $newItemId ?: $this->get_current_item_id();
  11335. $return = [];
  11336. $item = $this->getItem($newItemId);
  11337. $parent = $this->getItem($item->get_parent());
  11338. while ($parent) {
  11339. $return[] = $parent->get_title();
  11340. $parent = $this->getItem($parent->get_parent());
  11341. }
  11342. return array_reverse($return);
  11343. }
  11344. /**
  11345. * Reads and process "lp_subscription_settings" setting
  11346. * @return array
  11347. */
  11348. public static function getSubscriptionSettings()
  11349. {
  11350. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11351. if (empty($subscriptionSettings)) {
  11352. // By default allow both settings
  11353. $subscriptionSettings = [
  11354. 'allow_add_users_to_lp' => true,
  11355. 'allow_add_users_to_lp_category' => true,
  11356. ];
  11357. } else {
  11358. $subscriptionSettings = $subscriptionSettings['options'];
  11359. }
  11360. return $subscriptionSettings;
  11361. }
  11362. }