learnpath.class.php 533 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. if ($debug) {
  241. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  242. error_log('-- Start while--');
  243. }
  244. $lp_item_id_list = [];
  245. while ($row = Database::fetch_array($res)) {
  246. $lp_item_id_list[] = $row['iid'];
  247. switch ($this->type) {
  248. case 3: //aicc
  249. $oItem = new aiccItem('db', $row['iid'], $course_id);
  250. if (is_object($oItem)) {
  251. $my_item_id = $oItem->get_id();
  252. $oItem->set_lp_view($this->lp_view_id, $course_id);
  253. $oItem->set_prevent_reinit($this->prevent_reinit);
  254. // Don't use reference here as the next loop will make the pointed object change.
  255. $this->items[$my_item_id] = $oItem;
  256. $this->refs_list[$oItem->ref] = $my_item_id;
  257. if ($debug) {
  258. error_log(
  259. 'learnpath::__construct() - '.
  260. 'aicc object with id '.$my_item_id.
  261. ' set in items[]',
  262. 0
  263. );
  264. }
  265. }
  266. break;
  267. case 2:
  268. $oItem = new scormItem('db', $row['iid'], $course_id);
  269. if (is_object($oItem)) {
  270. $my_item_id = $oItem->get_id();
  271. $oItem->set_lp_view($this->lp_view_id, $course_id);
  272. $oItem->set_prevent_reinit($this->prevent_reinit);
  273. // Don't use reference here as the next loop will make the pointed object change.
  274. $this->items[$my_item_id] = $oItem;
  275. $this->refs_list[$oItem->ref] = $my_item_id;
  276. if ($debug) {
  277. error_log('object with id '.$my_item_id.' set in items[]');
  278. }
  279. }
  280. break;
  281. case 1:
  282. default:
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  285. }
  286. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  287. if ($debug) {
  288. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  289. }
  290. if (is_object($oItem)) {
  291. $my_item_id = $oItem->get_id();
  292. // Moved down to when we are sure the item_view exists.
  293. //$oItem->set_lp_view($this->lp_view_id);
  294. $oItem->set_prevent_reinit($this->prevent_reinit);
  295. // Don't use reference here as the next loop will make the pointed object change.
  296. $this->items[$my_item_id] = $oItem;
  297. $this->refs_list[$my_item_id] = $my_item_id;
  298. if ($debug) {
  299. error_log(
  300. 'learnpath::__construct() '.__LINE__.
  301. ' - object with id '.$my_item_id.' set in items[]'
  302. );
  303. }
  304. }
  305. break;
  306. }
  307. // Setting the object level with variable $this->items[$i][parent]
  308. foreach ($this->items as $itemLPObject) {
  309. $level = self::get_level_for_item(
  310. $this->items,
  311. $itemLPObject->db_id
  312. );
  313. $itemLPObject->level = $level;
  314. }
  315. // Setting the view in the item object.
  316. if (is_object($this->items[$row['iid']])) {
  317. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  318. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  319. $this->items[$row['iid']]->current_start_time = 0;
  320. $this->items[$row['iid']]->current_stop_time = 0;
  321. }
  322. }
  323. }
  324. if ($debug) {
  325. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  326. }
  327. if (!empty($lp_item_id_list)) {
  328. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  329. if (!empty($lp_item_id_list_to_string)) {
  330. // Get last viewing vars.
  331. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  332. // This query should only return one or zero result.
  333. $sql = "SELECT lp_item_id, status
  334. FROM $itemViewTable
  335. WHERE
  336. c_id = $course_id AND
  337. lp_view_id = ".$this->lp_view_id." AND
  338. lp_item_id IN ('".$lp_item_id_list_to_string."')
  339. ORDER BY view_count DESC ";
  340. if ($debug) {
  341. error_log(
  342. 'learnpath::__construct() - Selecting item_views: '.$sql,
  343. 0
  344. );
  345. }
  346. $status_list = [];
  347. $res = Database::query($sql);
  348. while ($row = Database:: fetch_array($res)) {
  349. $status_list[$row['lp_item_id']] = $row['status'];
  350. }
  351. foreach ($lp_item_id_list as $item_id) {
  352. if (isset($status_list[$item_id])) {
  353. $status = $status_list[$item_id];
  354. if (is_object($this->items[$item_id])) {
  355. $this->items[$item_id]->set_status($status);
  356. if (empty($status)) {
  357. $this->items[$item_id]->set_status(
  358. $this->default_status
  359. );
  360. }
  361. }
  362. } else {
  363. if (!api_is_invitee()) {
  364. if (is_object($this->items[$item_id])) {
  365. $this->items[$item_id]->set_status(
  366. $this->default_status
  367. );
  368. }
  369. if (!empty($this->lp_view_id)) {
  370. // Add that row to the lp_item_view table so that
  371. // we have something to show in the stats page.
  372. $params = [
  373. 'c_id' => $course_id,
  374. 'lp_item_id' => $item_id,
  375. 'lp_view_id' => $this->lp_view_id,
  376. 'view_count' => 1,
  377. 'status' => 'not attempted',
  378. 'start_time' => time(),
  379. 'total_time' => 0,
  380. 'score' => 0,
  381. ];
  382. $insertId = Database::insert($itemViewTable, $params);
  383. if ($insertId) {
  384. $sql = "UPDATE $itemViewTable SET id = iid
  385. WHERE iid = $insertId";
  386. Database::query($sql);
  387. }
  388. $this->items[$item_id]->set_lp_view(
  389. $this->lp_view_id,
  390. $course_id
  391. );
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. $this->ordered_items = self::get_flat_ordered_items_list(
  399. $this->get_id(),
  400. 0,
  401. $course_id
  402. );
  403. $this->max_ordered_items = 0;
  404. foreach ($this->ordered_items as $index => $dummy) {
  405. if ($index > $this->max_ordered_items && !empty($dummy)) {
  406. $this->max_ordered_items = $index;
  407. }
  408. }
  409. // TODO: Define the current item better.
  410. $this->first();
  411. if ($debug) {
  412. error_log('lp_view_session_id '.$this->lp_view_session_id);
  413. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  414. }
  415. } else {
  416. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  417. }
  418. }
  419. }
  420. /**
  421. * @return string
  422. */
  423. public function getCourseCode()
  424. {
  425. return $this->cc;
  426. }
  427. /**
  428. * @return int
  429. */
  430. public function get_course_int_id()
  431. {
  432. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  433. }
  434. /**
  435. * @param $course_id
  436. *
  437. * @return int
  438. */
  439. public function set_course_int_id($course_id)
  440. {
  441. return $this->course_int_id = (int) $course_id;
  442. }
  443. /**
  444. * Function rewritten based on old_add_item() from Yannick Warnier.
  445. * Due the fact that users can decide where the item should come, I had to overlook this function and
  446. * I found it better to rewrite it. Old function is still available.
  447. * Added also the possibility to add a description.
  448. *
  449. * @param int $parent
  450. * @param int $previous
  451. * @param string $type
  452. * @param int $id resource ID (ref)
  453. * @param string $title
  454. * @param string $description
  455. * @param int $prerequisites
  456. * @param int $max_time_allowed
  457. * @param int $userId
  458. *
  459. * @return int
  460. */
  461. public function add_item(
  462. $parent,
  463. $previous,
  464. $type = 'dir',
  465. $id,
  466. $title,
  467. $description,
  468. $prerequisites = 0,
  469. $max_time_allowed = 0,
  470. $userId = 0
  471. ) {
  472. $course_id = $this->course_info['real_id'];
  473. if ($this->debug > 0) {
  474. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  475. }
  476. if (empty($course_id)) {
  477. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  478. $this->course_info = api_get_course_info($this->cc);
  479. $course_id = $this->course_info['real_id'];
  480. }
  481. $userId = empty($userId) ? api_get_user_id() : $userId;
  482. $sessionId = api_get_session_id();
  483. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  484. $_course = $this->course_info;
  485. $parent = (int) $parent;
  486. $previous = (int) $previous;
  487. $id = (int) $id;
  488. $max_time_allowed = htmlentities($max_time_allowed);
  489. if (empty($max_time_allowed)) {
  490. $max_time_allowed = 0;
  491. }
  492. $sql = "SELECT COUNT(iid) AS num
  493. FROM $tbl_lp_item
  494. WHERE
  495. c_id = $course_id AND
  496. lp_id = ".$this->get_id()." AND
  497. parent_item_id = ".$parent;
  498. $res_count = Database::query($sql);
  499. $row = Database::fetch_array($res_count);
  500. $num = $row['num'];
  501. $tmp_previous = 0;
  502. $display_order = 0;
  503. $next = 0;
  504. if ($num > 0) {
  505. if (empty($previous)) {
  506. $sql = "SELECT iid, next_item_id, display_order
  507. FROM $tbl_lp_item
  508. WHERE
  509. c_id = $course_id AND
  510. lp_id = ".$this->get_id()." AND
  511. parent_item_id = $parent AND
  512. previous_item_id = 0 OR
  513. previous_item_id = $parent";
  514. $result = Database::query($sql);
  515. $row = Database::fetch_array($result);
  516. if ($row) {
  517. $next = $row['iid'];
  518. }
  519. } else {
  520. $previous = (int) $previous;
  521. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  522. FROM $tbl_lp_item
  523. WHERE
  524. c_id = $course_id AND
  525. lp_id = ".$this->get_id()." AND
  526. id = $previous";
  527. $result = Database::query($sql);
  528. $row = Database::fetch_array($result);
  529. if ($row) {
  530. $tmp_previous = $row['iid'];
  531. $next = $row['next_item_id'];
  532. $display_order = $row['display_order'];
  533. }
  534. }
  535. }
  536. $id = (int) $id;
  537. $typeCleaned = Database::escape_string($type);
  538. $max_score = 100;
  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. }
  558. $params = [
  559. 'c_id' => $course_id,
  560. 'lp_id' => $this->get_id(),
  561. 'item_type' => $typeCleaned,
  562. 'ref' => '',
  563. 'title' => $title,
  564. 'description' => $description,
  565. 'path' => $id,
  566. 'max_score' => $max_score,
  567. 'parent_item_id' => $parent,
  568. 'previous_item_id' => $previous,
  569. 'next_item_id' => (int) $next,
  570. 'display_order' => $display_order + 1,
  571. 'prerequisite' => $prerequisites,
  572. 'max_time_allowed' => $max_time_allowed,
  573. 'min_score' => 0,
  574. 'launch_data' => '',
  575. ];
  576. if ($prerequisites != 0) {
  577. $params['prerequisite'] = $prerequisites;
  578. }
  579. $new_item_id = Database::insert($tbl_lp_item, $params);
  580. if ($new_item_id) {
  581. if ($this->debug > 2) {
  582. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  583. }
  584. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  585. Database::query($sql);
  586. if (!empty($next)) {
  587. $sql = "UPDATE $tbl_lp_item
  588. SET previous_item_id = $new_item_id
  589. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  590. Database::query($sql);
  591. }
  592. // Update the item that should be before the new item.
  593. if (!empty($tmp_previous)) {
  594. $sql = "UPDATE $tbl_lp_item
  595. SET next_item_id = $new_item_id
  596. WHERE c_id = $course_id AND id = $tmp_previous";
  597. Database::query($sql);
  598. }
  599. // Update all the items after the new item.
  600. $sql = "UPDATE $tbl_lp_item
  601. SET display_order = display_order + 1
  602. WHERE
  603. c_id = $course_id AND
  604. lp_id = ".$this->get_id()." AND
  605. iid <> $new_item_id AND
  606. parent_item_id = $parent AND
  607. display_order > $display_order";
  608. Database::query($sql);
  609. // Update the item that should come after the new item.
  610. $sql = "UPDATE $tbl_lp_item
  611. SET ref = $new_item_id
  612. WHERE c_id = $course_id AND iid = $new_item_id";
  613. Database::query($sql);
  614. $sql = "UPDATE $tbl_lp_item
  615. SET previous_item_id = ".$this->getLastInFirstLevel()."
  616. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  617. Database::query($sql);
  618. // Upload audio.
  619. if (!empty($_FILES['mp3']['name'])) {
  620. // Create the audio folder if it does not exist yet.
  621. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  622. if (!is_dir($filepath.'audio')) {
  623. mkdir(
  624. $filepath.'audio',
  625. api_get_permissions_for_new_directories()
  626. );
  627. $audio_id = add_document(
  628. $_course,
  629. '/audio',
  630. 'folder',
  631. 0,
  632. 'audio',
  633. '',
  634. 0,
  635. true,
  636. null,
  637. $sessionId,
  638. $userId
  639. );
  640. api_item_property_update(
  641. $_course,
  642. TOOL_DOCUMENT,
  643. $audio_id,
  644. 'FolderCreated',
  645. $userId,
  646. null,
  647. null,
  648. null,
  649. null,
  650. $sessionId
  651. );
  652. api_item_property_update(
  653. $_course,
  654. TOOL_DOCUMENT,
  655. $audio_id,
  656. 'invisible',
  657. $userId,
  658. null,
  659. null,
  660. null,
  661. null,
  662. $sessionId
  663. );
  664. }
  665. $file_path = handle_uploaded_document(
  666. $_course,
  667. $_FILES['mp3'],
  668. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  669. '/audio',
  670. $userId,
  671. '',
  672. '',
  673. '',
  674. '',
  675. false
  676. );
  677. // Getting the filename only.
  678. $file_components = explode('/', $file_path);
  679. $file = $file_components[count($file_components) - 1];
  680. // Store the mp3 file in the lp_item table.
  681. $sql = "UPDATE $tbl_lp_item SET
  682. audio = '".Database::escape_string($file)."'
  683. WHERE iid = '".intval($new_item_id)."'";
  684. Database::query($sql);
  685. }
  686. }
  687. return $new_item_id;
  688. }
  689. /**
  690. * Static admin function allowing addition of a learnpath to a course.
  691. *
  692. * @param string $courseCode
  693. * @param string $name
  694. * @param string $description
  695. * @param string $learnpath
  696. * @param string $origin
  697. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  698. * @param string $publicated_on
  699. * @param string $expired_on
  700. * @param int $categoryId
  701. * @param int $userId
  702. *
  703. * @return int The new learnpath ID on success, 0 on failure
  704. */
  705. public static function add_lp(
  706. $courseCode,
  707. $name,
  708. $description = '',
  709. $learnpath = 'guess',
  710. $origin = 'zip',
  711. $zipname = '',
  712. $publicated_on = '',
  713. $expired_on = '',
  714. $categoryId = 0,
  715. $userId = 0
  716. ) {
  717. global $charset;
  718. if (!empty($courseCode)) {
  719. $courseInfo = api_get_course_info($courseCode);
  720. $course_id = $courseInfo['real_id'];
  721. } else {
  722. $course_id = api_get_course_int_id();
  723. $courseInfo = api_get_course_info();
  724. }
  725. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  726. // Check course code exists.
  727. // Check lp_name doesn't exist, otherwise append something.
  728. $i = 0;
  729. $name = Database::escape_string($name);
  730. $categoryId = (int) $categoryId;
  731. // Session id.
  732. $session_id = api_get_session_id();
  733. $userId = empty($userId) ? api_get_user_id() : $userId;
  734. $check_name = "SELECT * FROM $tbl_lp
  735. WHERE c_id = $course_id AND name = '$name'";
  736. $res_name = Database::query($check_name);
  737. if (empty($publicated_on)) {
  738. $publicated_on = null;
  739. } else {
  740. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  741. }
  742. if (empty($expired_on)) {
  743. $expired_on = null;
  744. } else {
  745. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  746. }
  747. while (Database::num_rows($res_name)) {
  748. // There is already one such name, update the current one a bit.
  749. $i++;
  750. $name = $name.' - '.$i;
  751. $check_name = "SELECT * FROM $tbl_lp
  752. WHERE c_id = $course_id AND name = '$name'";
  753. $res_name = Database::query($check_name);
  754. }
  755. // New name does not exist yet; keep it.
  756. // Escape description.
  757. // Kevin: added htmlentities().
  758. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  759. $type = 1;
  760. switch ($learnpath) {
  761. case 'guess':
  762. break;
  763. case 'dokeos':
  764. case 'chamilo':
  765. $type = 1;
  766. break;
  767. case 'aicc':
  768. break;
  769. }
  770. switch ($origin) {
  771. case 'zip':
  772. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  773. break;
  774. case 'manual':
  775. default:
  776. $get_max = "SELECT MAX(display_order)
  777. FROM $tbl_lp WHERE c_id = $course_id";
  778. $res_max = Database::query($get_max);
  779. if (Database::num_rows($res_max) < 1) {
  780. $dsp = 1;
  781. } else {
  782. $row = Database::fetch_array($res_max);
  783. $dsp = $row[0] + 1;
  784. }
  785. $params = [
  786. 'c_id' => $course_id,
  787. 'lp_type' => $type,
  788. 'name' => $name,
  789. 'description' => $description,
  790. 'path' => '',
  791. 'default_view_mod' => 'embedded',
  792. 'default_encoding' => 'UTF-8',
  793. 'display_order' => $dsp,
  794. 'content_maker' => 'Chamilo',
  795. 'content_local' => 'local',
  796. 'js_lib' => '',
  797. 'session_id' => $session_id,
  798. 'created_on' => api_get_utc_datetime(),
  799. 'modified_on' => api_get_utc_datetime(),
  800. 'publicated_on' => $publicated_on,
  801. 'expired_on' => $expired_on,
  802. 'category_id' => $categoryId,
  803. 'force_commit' => 0,
  804. 'content_license' => '',
  805. 'debug' => 0,
  806. 'theme' => '',
  807. 'preview_image' => '',
  808. 'author' => '',
  809. 'prerequisite' => 0,
  810. 'hide_toc_frame' => 0,
  811. 'seriousgame_mode' => 0,
  812. 'autolaunch' => 0,
  813. 'max_attempts' => 0,
  814. 'subscribe_users' => 0,
  815. 'accumulate_scorm_time' => 1,
  816. ];
  817. $id = Database::insert($tbl_lp, $params);
  818. if ($id > 0) {
  819. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  820. Database::query($sql);
  821. // Insert into item_property.
  822. api_item_property_update(
  823. $courseInfo,
  824. TOOL_LEARNPATH,
  825. $id,
  826. 'LearnpathAdded',
  827. $userId
  828. );
  829. api_set_default_visibility(
  830. $id,
  831. TOOL_LEARNPATH,
  832. 0,
  833. $courseInfo,
  834. $session_id,
  835. $userId
  836. );
  837. return $id;
  838. }
  839. break;
  840. }
  841. }
  842. /**
  843. * Auto completes the parents of an item in case it's been completed or passed.
  844. *
  845. * @param int $item Optional ID of the item from which to look for parents
  846. */
  847. public function autocomplete_parents($item)
  848. {
  849. $debug = $this->debug;
  850. if ($debug) {
  851. error_log('Learnpath::autocomplete_parents()');
  852. }
  853. if (empty($item)) {
  854. $item = $this->current;
  855. }
  856. $currentItem = $this->getItem($item);
  857. if ($currentItem) {
  858. $parent_id = $currentItem->get_parent();
  859. $parent = $this->getItem($parent_id);
  860. if ($parent) {
  861. // if $item points to an object and there is a parent.
  862. if ($debug) {
  863. error_log(
  864. 'Autocompleting parent of item '.$item.' '.
  865. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  866. 0
  867. );
  868. }
  869. // New experiment including failed and browsed in completed status.
  870. //$current_status = $currentItem->get_status();
  871. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  872. // Fixes chapter auto complete
  873. if (true) {
  874. // If the current item is completed or passes or succeeded.
  875. $updateParentStatus = true;
  876. if ($debug) {
  877. error_log('Status of current item is alright');
  878. }
  879. foreach ($parent->get_children() as $childItemId) {
  880. $childItem = $this->getItem($childItemId);
  881. // If children was not set try to get the info
  882. if (empty($childItem->db_item_view_id)) {
  883. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  884. }
  885. // Check all his brothers (parent's children) for completion status.
  886. if ($childItemId != $item) {
  887. if ($debug) {
  888. error_log(
  889. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  890. 0
  891. );
  892. }
  893. // Trying completing parents of failed and browsed items as well.
  894. if ($childItem->status_is(
  895. [
  896. 'completed',
  897. 'passed',
  898. 'succeeded',
  899. 'browsed',
  900. 'failed',
  901. ]
  902. )
  903. ) {
  904. // Keep completion status to true.
  905. continue;
  906. } else {
  907. if ($debug > 2) {
  908. error_log(
  909. '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,
  910. 0
  911. );
  912. }
  913. $updateParentStatus = false;
  914. break;
  915. }
  916. }
  917. }
  918. if ($updateParentStatus) {
  919. // If all the children were completed:
  920. $parent->set_status('completed');
  921. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  922. // Force the status to "completed"
  923. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  924. $this->update_queue[$parent->get_id()] = 'completed';
  925. if ($debug) {
  926. error_log(
  927. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  928. print_r($this->update_queue, 1),
  929. 0
  930. );
  931. }
  932. // Recursive call.
  933. $this->autocomplete_parents($parent->get_id());
  934. }
  935. }
  936. } else {
  937. if ($debug) {
  938. error_log("Parent #$parent_id does not exists");
  939. }
  940. }
  941. } else {
  942. if ($debug) {
  943. error_log("#$item is an item that doesn't have parents");
  944. }
  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. *
  954. * @return bool True on success, false on failure
  955. */
  956. public function close()
  957. {
  958. if ($this->debug > 0) {
  959. error_log('In learnpath::close()', 0);
  960. }
  961. if (empty($this->lp_id)) {
  962. $this->error = 'Trying to close this learnpath but no ID is set';
  963. return false;
  964. }
  965. $this->current_time_stop = time();
  966. $this->ordered_items = [];
  967. $this->index = 0;
  968. unset($this->lp_id);
  969. //unset other stuff
  970. return true;
  971. }
  972. /**
  973. * Static admin function allowing removal of a learnpath.
  974. *
  975. * @param array $courseInfo
  976. * @param int $id Learnpath ID
  977. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  978. *
  979. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  980. */
  981. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  982. {
  983. $course_id = api_get_course_int_id();
  984. if (!empty($courseInfo)) {
  985. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  986. }
  987. // TODO: Implement a way of getting this to work when the current object is not set.
  988. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  989. // If an ID is specifically given and the current LP is not the same, prevent delete.
  990. if (!empty($id) && ($id != $this->lp_id)) {
  991. return false;
  992. }
  993. $lp = Database::get_course_table(TABLE_LP_MAIN);
  994. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  995. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  996. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  997. // Delete lp item id.
  998. foreach ($this->items as $lpItemId => $dummy) {
  999. $sql = "DELETE FROM $lp_item_view
  1000. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  1001. Database::query($sql);
  1002. }
  1003. // Proposed by Christophe (nickname: clefevre)
  1004. $sql = "DELETE FROM $lp_item
  1005. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1006. Database::query($sql);
  1007. $sql = "DELETE FROM $lp_view
  1008. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1009. Database::query($sql);
  1010. self::toggle_publish($this->lp_id, 'i');
  1011. if ($this->type == 2 || $this->type == 3) {
  1012. // This is a scorm learning path, delete the files as well.
  1013. $sql = "SELECT path FROM $lp
  1014. WHERE iid = ".$this->lp_id;
  1015. $res = Database::query($sql);
  1016. if (Database::num_rows($res) > 0) {
  1017. $row = Database::fetch_array($res);
  1018. $path = $row['path'];
  1019. $sql = "SELECT id FROM $lp
  1020. WHERE
  1021. c_id = $course_id AND
  1022. path = '$path' AND
  1023. iid != ".$this->lp_id;
  1024. $res = Database::query($sql);
  1025. if (Database::num_rows($res) > 0) {
  1026. // Another learning path uses this directory, so don't delete it.
  1027. if ($this->debug > 2) {
  1028. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1029. }
  1030. } else {
  1031. // No other LP uses that directory, delete it.
  1032. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1033. // The absolute system path for this course.
  1034. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1035. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1036. if ($this->debug > 2) {
  1037. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1038. }
  1039. // Proposed by Christophe (clefevre).
  1040. if (strcmp(substr($path, -2), "/.") == 0) {
  1041. $path = substr($path, 0, -1); // Remove "." at the end.
  1042. }
  1043. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1044. rmdirr($course_scorm_dir.$path);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1050. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1051. // Delete tools
  1052. $sql = "DELETE FROM $tbl_tool
  1053. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1054. Database::query($sql);
  1055. $sql = "DELETE FROM $lp
  1056. WHERE iid = ".$this->lp_id;
  1057. Database::query($sql);
  1058. // Updates the display order of all lps.
  1059. $this->update_display_order();
  1060. api_item_property_update(
  1061. api_get_course_info(),
  1062. TOOL_LEARNPATH,
  1063. $this->lp_id,
  1064. 'delete',
  1065. api_get_user_id()
  1066. );
  1067. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1068. api_get_course_id(),
  1069. 4,
  1070. $id,
  1071. api_get_session_id()
  1072. );
  1073. if ($link_info !== false) {
  1074. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1075. }
  1076. if (api_get_setting('search_enabled') == 'true') {
  1077. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1078. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1079. }
  1080. }
  1081. /**
  1082. * Removes all the children of one item - dangerous!
  1083. *
  1084. * @param int $id Element ID of which children have to be removed
  1085. *
  1086. * @return int Total number of children removed
  1087. */
  1088. public function delete_children_items($id)
  1089. {
  1090. $course_id = $this->course_info['real_id'];
  1091. if ($this->debug > 0) {
  1092. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1093. }
  1094. $num = 0;
  1095. if (empty($id) || $id != strval(intval($id))) {
  1096. return false;
  1097. }
  1098. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1099. $sql = "SELECT * FROM $lp_item
  1100. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1101. $res = Database::query($sql);
  1102. while ($row = Database::fetch_array($res)) {
  1103. $num += $this->delete_children_items($row['iid']);
  1104. $sql = "DELETE FROM $lp_item
  1105. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1106. Database::query($sql);
  1107. $num++;
  1108. }
  1109. return $num;
  1110. }
  1111. /**
  1112. * Removes an item from the current learnpath.
  1113. *
  1114. * @param int $id Elem ID (0 if first)
  1115. *
  1116. * @return int Number of elements moved
  1117. *
  1118. * @todo implement resource removal
  1119. */
  1120. public function delete_item($id)
  1121. {
  1122. $course_id = api_get_course_int_id();
  1123. if ($this->debug > 0) {
  1124. error_log('In learnpath::delete_item()', 0);
  1125. }
  1126. // TODO: Implement the resource removal.
  1127. if (empty($id) || $id != strval(intval($id))) {
  1128. return false;
  1129. }
  1130. // First select item to get previous, next, and display order.
  1131. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1132. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1133. $res_sel = Database::query($sql_sel);
  1134. if (Database::num_rows($res_sel) < 1) {
  1135. return false;
  1136. }
  1137. $row = Database::fetch_array($res_sel);
  1138. $previous = $row['previous_item_id'];
  1139. $next = $row['next_item_id'];
  1140. $display = $row['display_order'];
  1141. $parent = $row['parent_item_id'];
  1142. $lp = $row['lp_id'];
  1143. // Delete children items.
  1144. $num = $this->delete_children_items($id);
  1145. if ($this->debug > 2) {
  1146. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1147. }
  1148. // Now delete the item.
  1149. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1150. if ($this->debug > 2) {
  1151. error_log('Deleting item: '.$sql_del, 0);
  1152. }
  1153. Database::query($sql_del);
  1154. // Now update surrounding items.
  1155. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1156. WHERE iid = $previous";
  1157. Database::query($sql_upd);
  1158. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1159. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1160. Database::query($sql_upd);
  1161. // Now update all following items with new display order.
  1162. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1163. WHERE
  1164. c_id = $course_id AND
  1165. lp_id = $lp AND
  1166. parent_item_id = $parent AND
  1167. display_order > $display";
  1168. Database::query($sql_all);
  1169. //Removing prerequisites since the item will not longer exist
  1170. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1171. WHERE c_id = $course_id AND prerequisite = $id";
  1172. Database::query($sql_all);
  1173. $sql = "UPDATE $lp_item
  1174. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1175. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1176. Database::query($sql);
  1177. // Remove from search engine if enabled.
  1178. if (api_get_setting('search_enabled') === 'true') {
  1179. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1180. $sql = 'SELECT * FROM %s
  1181. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1182. LIMIT 1';
  1183. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1184. $res = Database::query($sql);
  1185. if (Database::num_rows($res) > 0) {
  1186. $row2 = Database::fetch_array($res);
  1187. $di = new ChamiloIndexer();
  1188. $di->remove_document($row2['search_did']);
  1189. }
  1190. $sql = 'DELETE FROM %s
  1191. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1192. LIMIT 1';
  1193. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1194. Database::query($sql);
  1195. }
  1196. }
  1197. /**
  1198. * Updates an item's content in place.
  1199. *
  1200. * @param int $id Element ID
  1201. * @param int $parent Parent item ID
  1202. * @param int $previous Previous item ID
  1203. * @param string $title Item title
  1204. * @param string $description Item description
  1205. * @param string $prerequisites Prerequisites (optional)
  1206. * @param array $audio The array resulting of the $_FILES[mp3] element
  1207. * @param int $max_time_allowed
  1208. * @param string $url
  1209. *
  1210. * @return bool True on success, false on error
  1211. */
  1212. public function edit_item(
  1213. $id,
  1214. $parent,
  1215. $previous,
  1216. $title,
  1217. $description,
  1218. $prerequisites = '0',
  1219. $audio = [],
  1220. $max_time_allowed = 0,
  1221. $url = ''
  1222. ) {
  1223. $course_id = api_get_course_int_id();
  1224. $_course = api_get_course_info();
  1225. if ($this->debug > 0) {
  1226. error_log('In learnpath::edit_item()', 0);
  1227. }
  1228. if (empty($max_time_allowed)) {
  1229. $max_time_allowed = 0;
  1230. }
  1231. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1232. return false;
  1233. }
  1234. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1235. $sql = "SELECT * FROM $tbl_lp_item
  1236. WHERE iid = $id";
  1237. $res_select = Database::query($sql);
  1238. $row_select = Database::fetch_array($res_select);
  1239. $audio_update_sql = '';
  1240. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1241. // Create the audio folder if it does not exist yet.
  1242. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1243. if (!is_dir($filepath.'audio')) {
  1244. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1245. $audio_id = add_document(
  1246. $_course,
  1247. '/audio',
  1248. 'folder',
  1249. 0,
  1250. 'audio'
  1251. );
  1252. api_item_property_update(
  1253. $_course,
  1254. TOOL_DOCUMENT,
  1255. $audio_id,
  1256. 'FolderCreated',
  1257. api_get_user_id(),
  1258. null,
  1259. null,
  1260. null,
  1261. null,
  1262. api_get_session_id()
  1263. );
  1264. api_item_property_update(
  1265. $_course,
  1266. TOOL_DOCUMENT,
  1267. $audio_id,
  1268. 'invisible',
  1269. api_get_user_id(),
  1270. null,
  1271. null,
  1272. null,
  1273. null,
  1274. api_get_session_id()
  1275. );
  1276. }
  1277. // Upload file in documents.
  1278. $pi = pathinfo($audio['name']);
  1279. if ($pi['extension'] == 'mp3') {
  1280. $c_det = api_get_course_info($this->cc);
  1281. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1282. $path = handle_uploaded_document(
  1283. $c_det,
  1284. $audio,
  1285. $bp,
  1286. '/audio',
  1287. api_get_user_id(),
  1288. 0,
  1289. null,
  1290. 0,
  1291. 'rename',
  1292. false,
  1293. 0
  1294. );
  1295. $path = substr($path, 7);
  1296. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1297. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1298. }
  1299. }
  1300. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1301. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1302. // TODO: htmlspecialchars to be checked for encoding related problems.
  1303. if ($same_parent && $same_previous) {
  1304. // Only update title and description.
  1305. $sql = "UPDATE $tbl_lp_item
  1306. SET title = '".Database::escape_string($title)."',
  1307. prerequisite = '".$prerequisites."',
  1308. description = '".Database::escape_string($description)."'
  1309. ".$audio_update_sql.",
  1310. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1311. WHERE iid = $id";
  1312. Database::query($sql);
  1313. } else {
  1314. $old_parent = $row_select['parent_item_id'];
  1315. $old_previous = $row_select['previous_item_id'];
  1316. $old_next = $row_select['next_item_id'];
  1317. $old_order = $row_select['display_order'];
  1318. $old_prerequisite = $row_select['prerequisite'];
  1319. $old_max_time_allowed = $row_select['max_time_allowed'];
  1320. /* BEGIN -- virtually remove the current item id */
  1321. /* for the next and previous item it is like the current item doesn't exist anymore */
  1322. if ($old_previous != 0) {
  1323. // Next
  1324. $sql = "UPDATE $tbl_lp_item
  1325. SET next_item_id = $old_next
  1326. WHERE iid = $old_previous";
  1327. Database::query($sql);
  1328. }
  1329. if (!empty($old_next)) {
  1330. // Previous
  1331. $sql = "UPDATE $tbl_lp_item
  1332. SET previous_item_id = $old_previous
  1333. WHERE iid = $old_next";
  1334. Database::query($sql);
  1335. }
  1336. // display_order - 1 for every item with a display_order
  1337. // bigger then the display_order of the current item.
  1338. $sql = "UPDATE $tbl_lp_item
  1339. SET display_order = display_order - 1
  1340. WHERE
  1341. c_id = $course_id AND
  1342. display_order > $old_order AND
  1343. lp_id = ".$this->lp_id." AND
  1344. parent_item_id = $old_parent";
  1345. Database::query($sql);
  1346. /* END -- virtually remove the current item id */
  1347. /* BEGIN -- update the current item id to his new location */
  1348. if ($previous == 0) {
  1349. // Select the data of the item that should come after the current item.
  1350. $sql = "SELECT id, display_order
  1351. FROM $tbl_lp_item
  1352. WHERE
  1353. c_id = $course_id AND
  1354. lp_id = ".$this->lp_id." AND
  1355. parent_item_id = $parent AND
  1356. previous_item_id = $previous";
  1357. $res_select_old = Database::query($sql);
  1358. $row_select_old = Database::fetch_array($res_select_old);
  1359. // If the new parent didn't have children before.
  1360. if (Database::num_rows($res_select_old) == 0) {
  1361. $new_next = 0;
  1362. $new_order = 1;
  1363. } else {
  1364. $new_next = $row_select_old['id'];
  1365. $new_order = $row_select_old['display_order'];
  1366. }
  1367. } else {
  1368. // Select the data of the item that should come before the current item.
  1369. $sql = "SELECT next_item_id, display_order
  1370. FROM $tbl_lp_item
  1371. WHERE iid = $previous";
  1372. $res_select_old = Database::query($sql);
  1373. $row_select_old = Database::fetch_array($res_select_old);
  1374. $new_next = $row_select_old['next_item_id'];
  1375. $new_order = $row_select_old['display_order'] + 1;
  1376. }
  1377. // TODO: htmlspecialchars to be checked for encoding related problems.
  1378. // Update the current item with the new data.
  1379. $sql = "UPDATE $tbl_lp_item
  1380. SET
  1381. title = '".Database::escape_string($title)."',
  1382. description = '".Database::escape_string($description)."',
  1383. parent_item_id = $parent,
  1384. previous_item_id = $previous,
  1385. next_item_id = $new_next,
  1386. display_order = $new_order
  1387. $audio_update_sql
  1388. WHERE iid = $id";
  1389. Database::query($sql);
  1390. if ($previous != 0) {
  1391. // Update the previous item's next_item_id.
  1392. $sql = "UPDATE $tbl_lp_item
  1393. SET next_item_id = $id
  1394. WHERE iid = $previous";
  1395. Database::query($sql);
  1396. }
  1397. if (!empty($new_next)) {
  1398. // Update the next item's previous_item_id.
  1399. $sql = "UPDATE $tbl_lp_item
  1400. SET previous_item_id = $id
  1401. WHERE iid = $new_next";
  1402. Database::query($sql);
  1403. }
  1404. if ($old_prerequisite != $prerequisites) {
  1405. $sql = "UPDATE $tbl_lp_item
  1406. SET prerequisite = '$prerequisites'
  1407. WHERE iid = $id";
  1408. Database::query($sql);
  1409. }
  1410. if ($old_max_time_allowed != $max_time_allowed) {
  1411. // update max time allowed
  1412. $sql = "UPDATE $tbl_lp_item
  1413. SET max_time_allowed = $max_time_allowed
  1414. WHERE iid = $id";
  1415. Database::query($sql);
  1416. }
  1417. // Update all the items with the same or a bigger display_order than the current item.
  1418. $sql = "UPDATE $tbl_lp_item
  1419. SET display_order = display_order + 1
  1420. WHERE
  1421. c_id = $course_id AND
  1422. lp_id = ".$this->get_id()." AND
  1423. iid <> $id AND
  1424. parent_item_id = $parent AND
  1425. display_order >= $new_order";
  1426. Database::query($sql);
  1427. }
  1428. if ($row_select['item_type'] == 'link') {
  1429. $link = new Link();
  1430. $linkId = $row_select['path'];
  1431. $link->updateLink($linkId, $url);
  1432. }
  1433. }
  1434. /**
  1435. * Updates an item's prereq in place.
  1436. *
  1437. * @param int $id Element ID
  1438. * @param string $prerequisite_id Prerequisite Element ID
  1439. * @param int $minScore Prerequisite min score
  1440. * @param int $maxScore Prerequisite max score
  1441. *
  1442. * @return bool True on success, false on error
  1443. */
  1444. public function edit_item_prereq(
  1445. $id,
  1446. $prerequisite_id,
  1447. $minScore = 0,
  1448. $maxScore = 100
  1449. ) {
  1450. if ($this->debug > 0) {
  1451. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$minScore.','.$maxScore.')', 0);
  1452. }
  1453. $id = (int) $id;
  1454. $prerequisite_id = (int) $prerequisite_id;
  1455. if (empty($id)) {
  1456. return false;
  1457. }
  1458. if (empty($minScore) || $minScore < 0) {
  1459. $minScore = 0;
  1460. }
  1461. if (empty($maxScore) || $maxScore < 0) {
  1462. $maxScore = 100;
  1463. }
  1464. $minScore = floatval($minScore);
  1465. $maxScore = floatval($maxScore);
  1466. if (empty($prerequisite_id)) {
  1467. $prerequisite_id = 'NULL';
  1468. $minScore = 0;
  1469. $maxScore = 100;
  1470. }
  1471. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1472. $sql = " UPDATE $tbl_lp_item
  1473. SET
  1474. prerequisite = $prerequisite_id ,
  1475. prerequisite_min_score = $minScore ,
  1476. prerequisite_max_score = $maxScore
  1477. WHERE iid = $id";
  1478. Database::query($sql);
  1479. return true;
  1480. }
  1481. /**
  1482. * Gets all the chapters belonging to the same parent as the item/chapter given
  1483. * Can also be called as abstract method.
  1484. *
  1485. * @param int $id Item ID
  1486. *
  1487. * @return array A list of all the "brother items" (or an empty array on failure)
  1488. */
  1489. public function getSiblingDirectories($id)
  1490. {
  1491. $course_id = api_get_course_int_id();
  1492. if ($this->debug > 0) {
  1493. error_log('In learnpath::getSiblingDirectories()', 0);
  1494. }
  1495. if (empty($id) || $id != strval(intval($id))) {
  1496. return [];
  1497. }
  1498. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1499. $sql_parent = "SELECT * FROM $lp_item
  1500. WHERE iid = $id AND item_type='dir'";
  1501. $res_parent = Database::query($sql_parent);
  1502. if (Database::num_rows($res_parent) > 0) {
  1503. $row_parent = Database::fetch_array($res_parent);
  1504. $parent = $row_parent['parent_item_id'];
  1505. $sql = "SELECT * FROM $lp_item
  1506. WHERE
  1507. parent_item_id = $parent AND
  1508. iid = $id AND
  1509. item_type='dir'
  1510. ORDER BY display_order";
  1511. $res_bros = Database::query($sql);
  1512. $list = [];
  1513. while ($row_bro = Database::fetch_array($res_bros)) {
  1514. $list[] = $row_bro;
  1515. }
  1516. return $list;
  1517. }
  1518. return [];
  1519. }
  1520. /**
  1521. * Gets all the items belonging to the same parent as the item given
  1522. * Can also be called as abstract method.
  1523. *
  1524. * @param int $id Item ID
  1525. *
  1526. * @return array A list of all the "brother items" (or an empty array on failure)
  1527. */
  1528. public function get_brother_items($id)
  1529. {
  1530. $course_id = api_get_course_int_id();
  1531. if ($this->debug > 0) {
  1532. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1533. }
  1534. if (empty($id) || $id != strval(intval($id))) {
  1535. return [];
  1536. }
  1537. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1538. $sql_parent = "SELECT * FROM $lp_item
  1539. WHERE iid = $id";
  1540. $res_parent = Database::query($sql_parent);
  1541. if (Database::num_rows($res_parent) > 0) {
  1542. $row_parent = Database::fetch_array($res_parent);
  1543. $parent = $row_parent['parent_item_id'];
  1544. $sql = "SELECT * FROM $lp_item
  1545. WHERE c_id = $course_id AND parent_item_id = $parent
  1546. ORDER BY display_order";
  1547. $res_bros = Database::query($sql);
  1548. $list = [];
  1549. while ($row_bro = Database::fetch_array($res_bros)) {
  1550. $list[] = $row_bro;
  1551. }
  1552. return $list;
  1553. }
  1554. return [];
  1555. }
  1556. /**
  1557. * Get the specific prefix index terms of this learning path.
  1558. *
  1559. * @param string $prefix
  1560. *
  1561. * @return array Array of terms
  1562. */
  1563. public function get_common_index_terms_by_prefix($prefix)
  1564. {
  1565. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1566. $terms = get_specific_field_values_list_by_prefix(
  1567. $prefix,
  1568. $this->cc,
  1569. TOOL_LEARNPATH,
  1570. $this->lp_id
  1571. );
  1572. $prefix_terms = [];
  1573. if (!empty($terms)) {
  1574. foreach ($terms as $term) {
  1575. $prefix_terms[] = $term['value'];
  1576. }
  1577. }
  1578. return $prefix_terms;
  1579. }
  1580. /**
  1581. * Gets the number of items currently completed.
  1582. *
  1583. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1584. *
  1585. * @return int The number of items currently completed
  1586. */
  1587. public function get_complete_items_count($failedStatusException = false)
  1588. {
  1589. if ($this->debug > 0) {
  1590. error_log('In learnpath::get_complete_items_count()', 0);
  1591. }
  1592. $i = 0;
  1593. $completedStatusList = [
  1594. 'completed',
  1595. 'passed',
  1596. 'succeeded',
  1597. 'browsed',
  1598. ];
  1599. if (!$failedStatusException) {
  1600. $completedStatusList[] = 'failed';
  1601. }
  1602. foreach ($this->items as $id => $dummy) {
  1603. // Trying failed and browsed considered "progressed" as well.
  1604. if ($this->items[$id]->status_is($completedStatusList) &&
  1605. $this->items[$id]->get_type() != 'dir'
  1606. ) {
  1607. $i++;
  1608. }
  1609. }
  1610. return $i;
  1611. }
  1612. /**
  1613. * Gets the current item ID.
  1614. *
  1615. * @return int The current learnpath item id
  1616. */
  1617. public function get_current_item_id()
  1618. {
  1619. $current = 0;
  1620. if ($this->debug > 0) {
  1621. error_log('In learnpath::get_current_item_id()', 0);
  1622. }
  1623. if (!empty($this->current)) {
  1624. $current = $this->current;
  1625. }
  1626. if ($this->debug > 2) {
  1627. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1628. }
  1629. return $current;
  1630. }
  1631. /**
  1632. * Force to get the first learnpath item id.
  1633. *
  1634. * @return int The current learnpath item id
  1635. */
  1636. public function get_first_item_id()
  1637. {
  1638. $current = 0;
  1639. if (is_array($this->ordered_items)) {
  1640. $current = $this->ordered_items[0];
  1641. }
  1642. return $current;
  1643. }
  1644. /**
  1645. * Gets the total number of items available for viewing in this SCORM.
  1646. *
  1647. * @return int The total number of items
  1648. */
  1649. public function get_total_items_count()
  1650. {
  1651. if ($this->debug > 0) {
  1652. error_log('In learnpath::get_total_items_count()', 0);
  1653. }
  1654. return count($this->items);
  1655. }
  1656. /**
  1657. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1658. *
  1659. * @return int The total no-chapters number of items
  1660. */
  1661. public function getTotalItemsCountWithoutDirs()
  1662. {
  1663. if ($this->debug > 0) {
  1664. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1665. }
  1666. $total = 0;
  1667. $typeListNotToCount = self::getChapterTypes();
  1668. foreach ($this->items as $temp2) {
  1669. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1670. $total++;
  1671. }
  1672. }
  1673. return $total;
  1674. }
  1675. /**
  1676. * Sets the first element URL.
  1677. */
  1678. public function first()
  1679. {
  1680. if ($this->debug > 0) {
  1681. error_log('In learnpath::first()', 0);
  1682. error_log('$this->last_item_seen '.$this->last_item_seen);
  1683. }
  1684. // Test if the last_item_seen exists and is not a dir.
  1685. if (count($this->ordered_items) == 0) {
  1686. $this->index = 0;
  1687. }
  1688. if (!empty($this->last_item_seen) &&
  1689. !empty($this->items[$this->last_item_seen]) &&
  1690. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1691. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1692. //&& !$this->items[$this->last_item_seen]->is_done()
  1693. ) {
  1694. if ($this->debug > 2) {
  1695. error_log(
  1696. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1697. $this->items[$this->last_item_seen]->get_type()
  1698. );
  1699. }
  1700. $index = -1;
  1701. foreach ($this->ordered_items as $myindex => $item_id) {
  1702. if ($item_id == $this->last_item_seen) {
  1703. $index = $myindex;
  1704. break;
  1705. }
  1706. }
  1707. if ($index == -1) {
  1708. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1709. if ($this->debug > 2) {
  1710. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1711. }
  1712. return false;
  1713. } else {
  1714. $this->last = $this->last_item_seen;
  1715. $this->current = $this->last_item_seen;
  1716. $this->index = $index;
  1717. }
  1718. } else {
  1719. if ($this->debug > 2) {
  1720. error_log('In learnpath::first() - No last item seen', 0);
  1721. }
  1722. $index = 0;
  1723. // Loop through all ordered items and stop at the first item that is
  1724. // not a directory *and* that has not been completed yet.
  1725. while (!empty($this->ordered_items[$index]) &&
  1726. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1727. (
  1728. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1729. $this->items[$this->ordered_items[$index]]->is_done() === true
  1730. ) && $index < $this->max_ordered_items) {
  1731. $index++;
  1732. }
  1733. $this->last = $this->current;
  1734. // current is
  1735. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1736. $this->index = $index;
  1737. if ($this->debug > 2) {
  1738. error_log('$index '.$index);
  1739. error_log('In learnpath::first() - No last item seen');
  1740. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1741. }
  1742. }
  1743. if ($this->debug > 2) {
  1744. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1745. }
  1746. }
  1747. /**
  1748. * Gets the information about an item in a format usable as JavaScript to update
  1749. * the JS API by just printing this content into the <head> section of the message frame.
  1750. *
  1751. * @param int $item_id
  1752. *
  1753. * @return string
  1754. */
  1755. public function get_js_info($item_id = 0)
  1756. {
  1757. if ($this->debug > 0) {
  1758. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1759. }
  1760. $info = '';
  1761. $item_id = intval($item_id);
  1762. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1763. //if item is defined, return values from DB
  1764. $oItem = $this->items[$item_id];
  1765. $info .= '<script language="javascript">';
  1766. $info .= "top.set_score(".$oItem->get_score().");\n";
  1767. $info .= "top.set_max(".$oItem->get_max().");\n";
  1768. $info .= "top.set_min(".$oItem->get_min().");\n";
  1769. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1770. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1771. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1772. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1773. $info .= "top.set_flag_synchronized();";
  1774. $info .= '</script>';
  1775. if ($this->debug > 2) {
  1776. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1777. }
  1778. return $info;
  1779. } else {
  1780. // If item_id is empty, just update to default SCORM data.
  1781. $info .= '<script language="javascript">';
  1782. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1783. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1784. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1785. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1786. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1787. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1788. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1789. $info .= "top.set_flag_synchronized();";
  1790. $info .= '</script>';
  1791. if ($this->debug > 2) {
  1792. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1793. }
  1794. return $info;
  1795. }
  1796. }
  1797. /**
  1798. * Gets the js library from the database.
  1799. *
  1800. * @return string The name of the javascript library to be used
  1801. */
  1802. public function get_js_lib()
  1803. {
  1804. $lib = '';
  1805. if (!empty($this->js_lib)) {
  1806. $lib = $this->js_lib;
  1807. }
  1808. return $lib;
  1809. }
  1810. /**
  1811. * Gets the learnpath database ID.
  1812. *
  1813. * @return int Learnpath ID in the lp table
  1814. */
  1815. public function get_id()
  1816. {
  1817. if (!empty($this->lp_id)) {
  1818. return $this->lp_id;
  1819. } else {
  1820. return 0;
  1821. }
  1822. }
  1823. /**
  1824. * Gets the last element URL.
  1825. *
  1826. * @return string URL to load into the viewer
  1827. */
  1828. public function get_last()
  1829. {
  1830. if ($this->debug > 0) {
  1831. error_log('In learnpath::get_last()', 0);
  1832. }
  1833. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1834. if (count($this->ordered_items) > 0) {
  1835. $this->index = count($this->ordered_items) - 1;
  1836. return $this->ordered_items[$this->index];
  1837. }
  1838. return false;
  1839. }
  1840. /**
  1841. * Get the last element in the first level.
  1842. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1843. *
  1844. * @return mixed
  1845. */
  1846. public function getLastInFirstLevel()
  1847. {
  1848. try {
  1849. $lastId = Database::getManager()
  1850. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1851. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1852. ->setMaxResults(1)
  1853. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1854. ->getSingleScalarResult();
  1855. return $lastId;
  1856. } catch (Exception $exception) {
  1857. return 0;
  1858. }
  1859. }
  1860. /**
  1861. * Gets the navigation bar for the learnpath display screen.
  1862. *
  1863. * @return string The HTML string to use as a navigation bar
  1864. */
  1865. public function get_navigation_bar($idBar = null, $display = null)
  1866. {
  1867. if ($this->debug > 0) {
  1868. error_log('In learnpath::get_navigation_bar()', 0);
  1869. }
  1870. if (empty($idBar)) {
  1871. $idBar = 'control-top';
  1872. }
  1873. $lpId = $this->lp_id;
  1874. $mycurrentitemid = $this->get_current_item_id();
  1875. $reportingText = get_lang('Reporting');
  1876. $previousText = get_lang('ScormPrevious');
  1877. $nextText = get_lang('ScormNext');
  1878. $fullScreenText = get_lang('ScormExitFullScreen');
  1879. $settings = api_get_configuration_value('lp_view_settings');
  1880. $display = isset($settings['display']) ? $settings['display'] : false;
  1881. $reportingIcon = '
  1882. <a class="icon-toolbar"
  1883. id="stats_link"
  1884. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1885. onclick="window.parent.API.save_asset(); return true;"
  1886. target="content_name" title="'.$reportingText.'">
  1887. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1888. </a>';
  1889. if (!empty($display)) {
  1890. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1891. if ($showReporting == false) {
  1892. $reportingIcon = '';
  1893. }
  1894. }
  1895. $hideArrows = false;
  1896. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1897. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1898. }
  1899. $previousIcon = '';
  1900. $nextIcon = '';
  1901. if ($hideArrows === false) {
  1902. $previousIcon = '
  1903. <a class="icon-toolbar" id="scorm-previous" href="#"
  1904. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1905. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1906. </a>';
  1907. $nextIcon = '
  1908. <a class="icon-toolbar" id="scorm-next" href="#"
  1909. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1910. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1911. </a>';
  1912. }
  1913. if ($this->mode === 'fullscreen') {
  1914. $navbar = '
  1915. <span id="'.$idBar.'" class="buttons">
  1916. '.$reportingIcon.'
  1917. '.$previousIcon.'
  1918. '.$nextIcon.'
  1919. <a class="icon-toolbar" id="view-embedded"
  1920. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1921. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1922. </a>
  1923. </span>';
  1924. } else {
  1925. $navbar = '
  1926. <span id="'.$idBar.'" class="buttons text-right">
  1927. '.$reportingIcon.'
  1928. '.$previousIcon.'
  1929. '.$nextIcon.'
  1930. </span>';
  1931. }
  1932. return $navbar;
  1933. }
  1934. /**
  1935. * Gets the next resource in queue (url).
  1936. *
  1937. * @return string URL to load into the viewer
  1938. */
  1939. public function get_next_index()
  1940. {
  1941. if ($this->debug > 0) {
  1942. error_log('In learnpath::get_next_index()', 0);
  1943. }
  1944. // TODO
  1945. $index = $this->index;
  1946. $index++;
  1947. if ($this->debug > 2) {
  1948. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1949. }
  1950. while (
  1951. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1952. $index < $this->max_ordered_items
  1953. ) {
  1954. $index++;
  1955. if ($index == $this->max_ordered_items) {
  1956. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1957. return $this->index;
  1958. } else {
  1959. return $index;
  1960. }
  1961. }
  1962. }
  1963. if (empty($this->ordered_items[$index])) {
  1964. return $this->index;
  1965. }
  1966. if ($this->debug > 2) {
  1967. error_log('index is now '.$index, 0);
  1968. }
  1969. return $index;
  1970. }
  1971. /**
  1972. * Gets item_id for the next element.
  1973. *
  1974. * @return int Next item (DB) ID
  1975. */
  1976. public function get_next_item_id()
  1977. {
  1978. if ($this->debug > 0) {
  1979. error_log('In learnpath::get_next_item_id()', 0);
  1980. }
  1981. $new_index = $this->get_next_index();
  1982. if (!empty($new_index)) {
  1983. if (isset($this->ordered_items[$new_index])) {
  1984. if ($this->debug > 2) {
  1985. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1986. }
  1987. return $this->ordered_items[$new_index];
  1988. }
  1989. }
  1990. if ($this->debug > 2) {
  1991. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1992. }
  1993. return 0;
  1994. }
  1995. /**
  1996. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1997. *
  1998. * Generally, the package provided is in the form of a zip file, so the function
  1999. * has been written to test a zip file. If not a zip, the function will return the
  2000. * default return value: ''
  2001. *
  2002. * @param string $file_path the path to the file
  2003. * @param string $file_name the original name of the file
  2004. *
  2005. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  2006. */
  2007. public static function get_package_type($file_path, $file_name)
  2008. {
  2009. // Get name of the zip file without the extension.
  2010. $file_info = pathinfo($file_name);
  2011. $extension = $file_info['extension']; // Extension only.
  2012. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  2013. 'dll',
  2014. 'exe',
  2015. ])) {
  2016. return 'oogie';
  2017. }
  2018. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  2019. 'dll',
  2020. 'exe',
  2021. ])) {
  2022. return 'woogie';
  2023. }
  2024. $zipFile = new PclZip($file_path);
  2025. // Check the zip content (real size and file extension).
  2026. $zipContentArray = $zipFile->listContent();
  2027. $package_type = '';
  2028. $manifest = '';
  2029. $aicc_match_crs = 0;
  2030. $aicc_match_au = 0;
  2031. $aicc_match_des = 0;
  2032. $aicc_match_cst = 0;
  2033. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2034. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2035. foreach ($zipContentArray as $thisContent) {
  2036. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2037. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2038. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2039. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2040. $package_type = 'scorm';
  2041. break; // Exit the foreach loop.
  2042. } elseif (
  2043. preg_match('/aicc\//i', $thisContent['filename']) ||
  2044. in_array(
  2045. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2046. ['crs', 'au', 'des', 'cst']
  2047. )
  2048. ) {
  2049. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2050. switch ($ext) {
  2051. case 'crs':
  2052. $aicc_match_crs = 1;
  2053. break;
  2054. case 'au':
  2055. $aicc_match_au = 1;
  2056. break;
  2057. case 'des':
  2058. $aicc_match_des = 1;
  2059. break;
  2060. case 'cst':
  2061. $aicc_match_cst = 1;
  2062. break;
  2063. default:
  2064. break;
  2065. }
  2066. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2067. } else {
  2068. $package_type = '';
  2069. }
  2070. }
  2071. }
  2072. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2073. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2074. $package_type = 'aicc';
  2075. }
  2076. // Try with chamilo course builder
  2077. if (empty($package_type)) {
  2078. $package_type = 'chamilo';
  2079. }
  2080. return $package_type;
  2081. }
  2082. /**
  2083. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2084. *
  2085. * @return string URL to load into the viewer
  2086. */
  2087. public function get_previous_index()
  2088. {
  2089. if ($this->debug > 0) {
  2090. error_log('In learnpath::get_previous_index()', 0);
  2091. }
  2092. $index = $this->index;
  2093. if (isset($this->ordered_items[$index - 1])) {
  2094. $index--;
  2095. while (isset($this->ordered_items[$index]) &&
  2096. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2097. ) {
  2098. $index--;
  2099. if ($index < 0) {
  2100. return $this->index;
  2101. }
  2102. }
  2103. } else {
  2104. if ($this->debug > 2) {
  2105. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2106. }
  2107. // There is no previous item.
  2108. }
  2109. return $index;
  2110. }
  2111. /**
  2112. * Gets item_id for the next element.
  2113. *
  2114. * @return int Previous item (DB) ID
  2115. */
  2116. public function get_previous_item_id()
  2117. {
  2118. if ($this->debug > 0) {
  2119. error_log('In learnpath::get_previous_item_id()', 0);
  2120. }
  2121. $new_index = $this->get_previous_index();
  2122. return $this->ordered_items[$new_index];
  2123. }
  2124. /**
  2125. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2126. *
  2127. * @param int $lpItemId
  2128. * @param string $autostart
  2129. *
  2130. * @return string The mediaplayer HTML
  2131. */
  2132. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2133. {
  2134. $course_id = api_get_course_int_id();
  2135. $_course = api_get_course_info();
  2136. if (empty($_course)) {
  2137. return '';
  2138. }
  2139. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2140. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2141. $lpItemId = (int) $lpItemId;
  2142. /** @var learnpathItem $item */
  2143. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2144. $itemViewId = 0;
  2145. if ($item) {
  2146. $itemViewId = (int) $item->db_item_view_id;
  2147. }
  2148. // Getting all the information about the item.
  2149. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2150. FROM $tbl_lp_item as lpi
  2151. INNER JOIN $tbl_lp_item_view as lp_view
  2152. ON (lpi.iid = lp_view.lp_item_id)
  2153. WHERE
  2154. lp_view.iid = $itemViewId AND
  2155. lpi.iid = $lpItemId AND
  2156. lp_view.c_id = $course_id";
  2157. $result = Database::query($sql);
  2158. $row = Database::fetch_assoc($result);
  2159. $output = '';
  2160. if (!empty($row['audio'])) {
  2161. $list = $_SESSION['oLP']->get_toc();
  2162. switch ($row['item_type']) {
  2163. case 'quiz':
  2164. $type_quiz = false;
  2165. foreach ($list as $toc) {
  2166. if ($toc['id'] == $_SESSION['oLP']->current) {
  2167. $type_quiz = true;
  2168. }
  2169. }
  2170. if ($type_quiz) {
  2171. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2172. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2173. } else {
  2174. $autostart_audio = $autostart;
  2175. }
  2176. }
  2177. break;
  2178. case TOOL_READOUT_TEXT:;
  2179. $autostart_audio = 'false';
  2180. break;
  2181. default:
  2182. $autostart_audio = 'true';
  2183. }
  2184. $courseInfo = api_get_course_info();
  2185. $audio = $row['audio'];
  2186. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2187. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2188. if (!file_exists($file)) {
  2189. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2190. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2191. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2192. }
  2193. $player = Display::getMediaPlayer(
  2194. $file,
  2195. [
  2196. 'id' => 'lp_audio_media_player',
  2197. 'url' => $url,
  2198. 'autoplay' => $autostart_audio,
  2199. 'width' => '100%',
  2200. ]
  2201. );
  2202. // The mp3 player.
  2203. $output = '<div id="container">';
  2204. $output .= $player;
  2205. $output .= '</div>';
  2206. }
  2207. return $output;
  2208. }
  2209. /**
  2210. * @param int $studentId
  2211. * @param int $prerequisite
  2212. * @param array $courseInfo
  2213. * @param int $sessionId
  2214. *
  2215. * @return bool
  2216. */
  2217. public static function isBlockedByPrerequisite(
  2218. $studentId,
  2219. $prerequisite,
  2220. $courseInfo,
  2221. $sessionId
  2222. ) {
  2223. if (empty($courseInfo)) {
  2224. return false;
  2225. }
  2226. $courseId = $courseInfo['real_id'];
  2227. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2228. if ($allow) {
  2229. if (api_is_allowed_to_edit() ||
  2230. api_is_platform_admin(true) ||
  2231. api_is_drh() ||
  2232. api_is_coach($sessionId, $courseId, false)
  2233. ) {
  2234. return false;
  2235. }
  2236. }
  2237. $isBlocked = false;
  2238. if (!empty($prerequisite)) {
  2239. $progress = self::getProgress(
  2240. $prerequisite,
  2241. $studentId,
  2242. $courseId,
  2243. $sessionId
  2244. );
  2245. if ($progress < 100) {
  2246. $isBlocked = true;
  2247. }
  2248. if (Tracking::minimunTimeAvailable($sessionId, $courseId)) {
  2249. // Block if it does not exceed minimum time
  2250. // Minimum time (in minutes) to pass the learning path
  2251. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2252. if ($accumulateWorkTime > 0) {
  2253. // Total time in course (sum of times in learning paths from course)
  2254. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2255. // Connect with the plugin_licences_course_session table
  2256. // which indicates what percentage of the time applies
  2257. // Minimum connection percentage
  2258. $perc = 100;
  2259. // Time from the course
  2260. $tc = $accumulateWorkTimeTotal;
  2261. // Percentage of the learning paths
  2262. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2263. // Minimum time for each learning path
  2264. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2265. // Spent time (in seconds) so far in the learning path
  2266. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2267. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2268. if ($lpTime < ($accumulateWorkTime * 60)) {
  2269. $isBlocked = true;
  2270. }
  2271. }
  2272. }
  2273. }
  2274. return $isBlocked;
  2275. }
  2276. /**
  2277. * Checks if the learning path is visible for student after the progress
  2278. * of its prerequisite is completed, considering the time availability and
  2279. * the LP visibility.
  2280. *
  2281. * @param int $lp_id
  2282. * @param int $student_id
  2283. * @param null $courseCode
  2284. * @param int $sessionId
  2285. *
  2286. * @return bool
  2287. */
  2288. public static function is_lp_visible_for_student(
  2289. $lp_id,
  2290. $student_id,
  2291. $courseCode = null,
  2292. $sessionId = 0
  2293. ) {
  2294. $courseInfo = api_get_course_info($courseCode);
  2295. $lp_id = (int) $lp_id;
  2296. $sessionId = (int) $sessionId;
  2297. if (empty($courseInfo)) {
  2298. return false;
  2299. }
  2300. if (empty($sessionId)) {
  2301. $sessionId = api_get_session_id();
  2302. }
  2303. $itemInfo = api_get_item_property_info(
  2304. $courseInfo['real_id'],
  2305. TOOL_LEARNPATH,
  2306. $lp_id,
  2307. $sessionId
  2308. );
  2309. // If the item was deleted.
  2310. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2311. return false;
  2312. }
  2313. // @todo remove this query and load the row info as a parameter
  2314. $table = Database::get_course_table(TABLE_LP_MAIN);
  2315. // Get current prerequisite
  2316. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2317. FROM $table
  2318. WHERE iid = $lp_id";
  2319. $rs = Database::query($sql);
  2320. $now = time();
  2321. if (Database::num_rows($rs) > 0) {
  2322. $row = Database::fetch_array($rs, 'ASSOC');
  2323. $prerequisite = $row['prerequisite'];
  2324. $is_visible = true;
  2325. $isBlocked = self::isBlockedByPrerequisite(
  2326. $student_id,
  2327. $prerequisite,
  2328. $courseInfo,
  2329. $sessionId
  2330. );
  2331. if ($isBlocked) {
  2332. $is_visible = false;
  2333. }
  2334. // Also check the time availability of the LP
  2335. if ($is_visible) {
  2336. // Adding visibility restrictions
  2337. if (!empty($row['publicated_on'])) {
  2338. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2339. $is_visible = false;
  2340. }
  2341. }
  2342. // Blocking empty start times see BT#2800
  2343. global $_custom;
  2344. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2345. $_custom['lps_hidden_when_no_start_date']
  2346. ) {
  2347. if (empty($row['publicated_on'])) {
  2348. $is_visible = false;
  2349. }
  2350. }
  2351. if (!empty($row['expired_on'])) {
  2352. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2353. $is_visible = false;
  2354. }
  2355. }
  2356. }
  2357. if ($is_visible) {
  2358. $subscriptionSettings = self::getSubscriptionSettings();
  2359. // Check if the subscription users/group to a LP is ON
  2360. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2361. $subscriptionSettings['allow_add_users_to_lp'] === true
  2362. ) {
  2363. // Try group
  2364. $is_visible = false;
  2365. // Checking only the user visibility
  2366. $userVisibility = api_get_item_visibility(
  2367. $courseInfo,
  2368. 'learnpath',
  2369. $row['id'],
  2370. $sessionId,
  2371. $student_id,
  2372. 'LearnpathSubscription'
  2373. );
  2374. if ($userVisibility == 1) {
  2375. $is_visible = true;
  2376. } else {
  2377. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2378. if (!empty($userGroups)) {
  2379. foreach ($userGroups as $groupInfo) {
  2380. $groupId = $groupInfo['iid'];
  2381. $userVisibility = api_get_item_visibility(
  2382. $courseInfo,
  2383. 'learnpath',
  2384. $row['id'],
  2385. $sessionId,
  2386. null,
  2387. 'LearnpathSubscription',
  2388. $groupId
  2389. );
  2390. if ($userVisibility == 1) {
  2391. $is_visible = true;
  2392. break;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. }
  2398. }
  2399. return $is_visible;
  2400. }
  2401. return false;
  2402. }
  2403. /**
  2404. * @param int $lpId
  2405. * @param int $userId
  2406. * @param int $courseId
  2407. * @param int $sessionId
  2408. *
  2409. * @return int
  2410. */
  2411. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2412. {
  2413. $lpId = (int) $lpId;
  2414. $userId = (int) $userId;
  2415. $courseId = (int) $courseId;
  2416. $sessionId = (int) $sessionId;
  2417. $sessionCondition = api_get_session_condition($sessionId);
  2418. $table = Database::get_course_table(TABLE_LP_VIEW);
  2419. $sql = "SELECT * FROM $table
  2420. WHERE
  2421. c_id = $courseId AND
  2422. lp_id = $lpId AND
  2423. user_id = $userId $sessionCondition ";
  2424. $res = Database::query($sql);
  2425. $progress = 0;
  2426. if (Database::num_rows($res) > 0) {
  2427. $row = Database:: fetch_array($res);
  2428. $progress = (int) $row['progress'];
  2429. }
  2430. return $progress;
  2431. }
  2432. /**
  2433. * Displays a progress bar
  2434. * completed so far.
  2435. *
  2436. * @param int $percentage Progress value to display
  2437. * @param string $text_add Text to display near the progress value
  2438. *
  2439. * @return string HTML string containing the progress bar
  2440. */
  2441. public static function get_progress_bar($percentage = -1, $text_add = '')
  2442. {
  2443. $text = $percentage.$text_add;
  2444. $output = '<div class="progress">
  2445. <div id="progress_bar_value"
  2446. class="progress-bar progress-bar-success" role="progressbar"
  2447. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2448. '.$text.'
  2449. </div>
  2450. </div>';
  2451. return $output;
  2452. }
  2453. /**
  2454. * @param string $mode can be '%' or 'abs'
  2455. * otherwise this value will be used $this->progress_bar_mode
  2456. *
  2457. * @return string
  2458. */
  2459. public function getProgressBar($mode = null)
  2460. {
  2461. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2462. return self::get_progress_bar($percentage, $text_add);
  2463. }
  2464. /**
  2465. * Gets the progress bar info to display inside the progress bar.
  2466. * Also used by scorm_api.php.
  2467. *
  2468. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2469. * we display a number of completed elements per total elements
  2470. * @param int $add Additional steps to fake as completed
  2471. *
  2472. * @return array Percentage or number and symbol (% or /xx)
  2473. */
  2474. public function get_progress_bar_text($mode = '', $add = 0)
  2475. {
  2476. if ($this->debug > 0) {
  2477. error_log('In learnpath::get_progress_bar_text()', 0);
  2478. }
  2479. if (empty($mode)) {
  2480. $mode = $this->progress_bar_mode;
  2481. }
  2482. $total_items = $this->getTotalItemsCountWithoutDirs();
  2483. if ($this->debug > 2) {
  2484. error_log('Total items available in this learnpath: '.$total_items, 0);
  2485. }
  2486. $completeItems = $this->get_complete_items_count();
  2487. if ($this->debug > 2) {
  2488. error_log('Items completed so far: '.$completeItems, 0);
  2489. }
  2490. if ($add != 0) {
  2491. $completeItems += $add;
  2492. if ($this->debug > 2) {
  2493. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2494. }
  2495. }
  2496. $text = '';
  2497. if ($completeItems > $total_items) {
  2498. $completeItems = $total_items;
  2499. }
  2500. $percentage = 0;
  2501. if ($mode == '%') {
  2502. if ($total_items > 0) {
  2503. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2504. } else {
  2505. $percentage = 0;
  2506. }
  2507. $percentage = number_format($percentage, 0);
  2508. $text = '%';
  2509. } elseif ($mode == 'abs') {
  2510. $percentage = $completeItems;
  2511. $text = '/'.$total_items;
  2512. }
  2513. return [
  2514. $percentage,
  2515. $text,
  2516. ];
  2517. }
  2518. /**
  2519. * Gets the progress bar mode.
  2520. *
  2521. * @return string The progress bar mode attribute
  2522. */
  2523. public function get_progress_bar_mode()
  2524. {
  2525. if ($this->debug > 0) {
  2526. error_log('In learnpath::get_progress_bar_mode()', 0);
  2527. }
  2528. if (!empty($this->progress_bar_mode)) {
  2529. return $this->progress_bar_mode;
  2530. } else {
  2531. return '%';
  2532. }
  2533. }
  2534. /**
  2535. * Gets the learnpath theme (remote or local).
  2536. *
  2537. * @return string Learnpath theme
  2538. */
  2539. public function get_theme()
  2540. {
  2541. if ($this->debug > 0) {
  2542. error_log('In learnpath::get_theme()', 0);
  2543. }
  2544. if (!empty($this->theme)) {
  2545. return $this->theme;
  2546. } else {
  2547. return '';
  2548. }
  2549. }
  2550. /**
  2551. * Gets the learnpath session id.
  2552. *
  2553. * @return int
  2554. */
  2555. public function get_lp_session_id()
  2556. {
  2557. if ($this->debug > 0) {
  2558. error_log('In learnpath::get_lp_session_id()', 0);
  2559. }
  2560. if (!empty($this->lp_session_id)) {
  2561. return (int) $this->lp_session_id;
  2562. } else {
  2563. return 0;
  2564. }
  2565. }
  2566. /**
  2567. * Gets the learnpath image.
  2568. *
  2569. * @return string Web URL of the LP image
  2570. */
  2571. public function get_preview_image()
  2572. {
  2573. if ($this->debug > 0) {
  2574. error_log('In learnpath::get_preview_image()', 0);
  2575. }
  2576. if (!empty($this->preview_image)) {
  2577. return $this->preview_image;
  2578. } else {
  2579. return '';
  2580. }
  2581. }
  2582. /**
  2583. * @param string $size
  2584. * @param string $path_type
  2585. *
  2586. * @return bool|string
  2587. */
  2588. public function get_preview_image_path($size = null, $path_type = 'web')
  2589. {
  2590. $preview_image = $this->get_preview_image();
  2591. if (isset($preview_image) && !empty($preview_image)) {
  2592. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2593. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2594. if (isset($size)) {
  2595. $info = pathinfo($preview_image);
  2596. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2597. if (file_exists($image_sys_path.$image_custom_size)) {
  2598. if ($path_type == 'web') {
  2599. return $image_path.$image_custom_size;
  2600. } else {
  2601. return $image_sys_path.$image_custom_size;
  2602. }
  2603. }
  2604. } else {
  2605. if ($path_type == 'web') {
  2606. return $image_path.$preview_image;
  2607. } else {
  2608. return $image_sys_path.$preview_image;
  2609. }
  2610. }
  2611. }
  2612. return false;
  2613. }
  2614. /**
  2615. * Gets the learnpath author.
  2616. *
  2617. * @return string LP's author
  2618. */
  2619. public function get_author()
  2620. {
  2621. if ($this->debug > 0) {
  2622. error_log('In learnpath::get_author()', 0);
  2623. }
  2624. if (!empty($this->author)) {
  2625. return $this->author;
  2626. } else {
  2627. return '';
  2628. }
  2629. }
  2630. /**
  2631. * Gets hide table of contents.
  2632. *
  2633. * @return int
  2634. */
  2635. public function getHideTableOfContents()
  2636. {
  2637. return (int) $this->hide_toc_frame;
  2638. }
  2639. /**
  2640. * Generate a new prerequisites string for a given item. If this item was a sco and
  2641. * its prerequisites were strings (instead of IDs), then transform those strings into
  2642. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2643. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2644. * same rule as the scormExport() method.
  2645. *
  2646. * @param int $item_id Item ID
  2647. *
  2648. * @return string Prerequisites string ready for the export as SCORM
  2649. */
  2650. public function get_scorm_prereq_string($item_id)
  2651. {
  2652. if ($this->debug > 0) {
  2653. error_log('In learnpath::get_scorm_prereq_string()');
  2654. }
  2655. if (!is_object($this->items[$item_id])) {
  2656. return false;
  2657. }
  2658. /** @var learnpathItem $oItem */
  2659. $oItem = $this->items[$item_id];
  2660. $prereq = $oItem->get_prereq_string();
  2661. if (empty($prereq)) {
  2662. return '';
  2663. }
  2664. if (preg_match('/^\d+$/', $prereq) &&
  2665. isset($this->items[$prereq]) &&
  2666. is_object($this->items[$prereq])
  2667. ) {
  2668. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2669. // then simply return it (with the ITEM_ prefix).
  2670. //return 'ITEM_' . $prereq;
  2671. return $this->items[$prereq]->ref;
  2672. } else {
  2673. if (isset($this->refs_list[$prereq])) {
  2674. // It's a simple string item from which the ID can be found in the refs list,
  2675. // so we can transform it directly to an ID for export.
  2676. return $this->items[$this->refs_list[$prereq]]->ref;
  2677. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2678. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2679. } else {
  2680. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2681. // and replace them, one by one, by the internal IDs (chamilo db)
  2682. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2683. // by a space as well.
  2684. $find = [
  2685. '&',
  2686. '|',
  2687. '~',
  2688. '=',
  2689. '<>',
  2690. '{',
  2691. '}',
  2692. '*',
  2693. '(',
  2694. ')',
  2695. ];
  2696. $replace = [
  2697. ' ',
  2698. ' ',
  2699. ' ',
  2700. ' ',
  2701. ' ',
  2702. ' ',
  2703. ' ',
  2704. ' ',
  2705. ' ',
  2706. ' ',
  2707. ];
  2708. $prereq_mod = str_replace($find, $replace, $prereq);
  2709. $ids = explode(' ', $prereq_mod);
  2710. foreach ($ids as $id) {
  2711. $id = trim($id);
  2712. if (isset($this->refs_list[$id])) {
  2713. $prereq = preg_replace(
  2714. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2715. 'ITEM_'.$this->refs_list[$id],
  2716. $prereq
  2717. );
  2718. }
  2719. }
  2720. return $prereq;
  2721. }
  2722. }
  2723. }
  2724. /**
  2725. * Returns the XML DOM document's node.
  2726. *
  2727. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2728. * @param string $id The identifier to look for
  2729. *
  2730. * @return mixed The reference to the element found with that identifier. False if not found
  2731. */
  2732. public function get_scorm_xml_node(&$children, $id)
  2733. {
  2734. for ($i = 0; $i < $children->length; $i++) {
  2735. $item_temp = $children->item($i);
  2736. if ($item_temp->nodeName == 'item') {
  2737. if ($item_temp->getAttribute('identifier') == $id) {
  2738. return $item_temp;
  2739. }
  2740. }
  2741. $subchildren = $item_temp->childNodes;
  2742. if ($subchildren && $subchildren->length > 0) {
  2743. $val = $this->get_scorm_xml_node($subchildren, $id);
  2744. if (is_object($val)) {
  2745. return $val;
  2746. }
  2747. }
  2748. }
  2749. return false;
  2750. }
  2751. /**
  2752. * Gets the status list for all LP's items.
  2753. *
  2754. * @return array Array of [index] => [item ID => current status]
  2755. */
  2756. public function get_items_status_list()
  2757. {
  2758. if ($this->debug > 0) {
  2759. error_log('In learnpath::get_items_status_list()', 0);
  2760. }
  2761. $list = [];
  2762. foreach ($this->ordered_items as $item_id) {
  2763. $list[] = [
  2764. $item_id => $this->items[$item_id]->get_status(),
  2765. ];
  2766. }
  2767. return $list;
  2768. }
  2769. /**
  2770. * Return the number of interactions for the given learnpath Item View ID.
  2771. * This method can be used as static.
  2772. *
  2773. * @param int $lp_iv_id Item View ID
  2774. * @param int $course_id course id
  2775. *
  2776. * @return int
  2777. */
  2778. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2779. {
  2780. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2781. $lp_iv_id = (int) $lp_iv_id;
  2782. $course_id = (int) $course_id;
  2783. $sql = "SELECT count(*) FROM $table
  2784. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2785. $res = Database::query($sql);
  2786. $num = 0;
  2787. if (Database::num_rows($res)) {
  2788. $row = Database::fetch_array($res);
  2789. $num = $row[0];
  2790. }
  2791. return $num;
  2792. }
  2793. /**
  2794. * Return the interactions as an array for the given lp_iv_id.
  2795. * This method can be used as static.
  2796. *
  2797. * @param int $lp_iv_id Learnpath Item View ID
  2798. *
  2799. * @return array
  2800. *
  2801. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2802. */
  2803. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2804. {
  2805. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2806. $list = [];
  2807. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2808. $lp_iv_id = (int) $lp_iv_id;
  2809. if (empty($lp_iv_id) || empty($course_id)) {
  2810. return [];
  2811. }
  2812. $sql = "SELECT * FROM $table
  2813. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2814. ORDER BY order_id ASC";
  2815. $res = Database::query($sql);
  2816. $num = Database::num_rows($res);
  2817. if ($num > 0) {
  2818. $list[] = [
  2819. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2820. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2821. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2822. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2823. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2824. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2825. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2826. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2827. 'student_response_formatted' => '',
  2828. ];
  2829. while ($row = Database::fetch_array($res)) {
  2830. $studentResponseFormatted = urldecode($row['student_response']);
  2831. $content_student_response = explode('__|', $studentResponseFormatted);
  2832. if (count($content_student_response) > 0) {
  2833. if (count($content_student_response) >= 3) {
  2834. // Pop the element off the end of array.
  2835. array_pop($content_student_response);
  2836. }
  2837. $studentResponseFormatted = implode(',', $content_student_response);
  2838. }
  2839. $list[] = [
  2840. 'order_id' => $row['order_id'] + 1,
  2841. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2842. 'type' => $row['interaction_type'],
  2843. 'time' => $row['completion_time'],
  2844. 'correct_responses' => '', // Hide correct responses from students.
  2845. 'student_response' => $row['student_response'],
  2846. 'result' => $row['result'],
  2847. 'latency' => $row['latency'],
  2848. 'student_response_formatted' => $studentResponseFormatted,
  2849. ];
  2850. }
  2851. }
  2852. return $list;
  2853. }
  2854. /**
  2855. * Return the number of objectives for the given learnpath Item View ID.
  2856. * This method can be used as static.
  2857. *
  2858. * @param int $lp_iv_id Item View ID
  2859. * @param int $course_id Course ID
  2860. *
  2861. * @return int Number of objectives
  2862. */
  2863. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2864. {
  2865. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2866. $course_id = (int) $course_id;
  2867. $lp_iv_id = (int) $lp_iv_id;
  2868. $sql = "SELECT count(*) FROM $table
  2869. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2870. //@todo seems that this always returns 0
  2871. $res = Database::query($sql);
  2872. $num = 0;
  2873. if (Database::num_rows($res)) {
  2874. $row = Database::fetch_array($res);
  2875. $num = $row[0];
  2876. }
  2877. return $num;
  2878. }
  2879. /**
  2880. * Return the objectives as an array for the given lp_iv_id.
  2881. * This method can be used as static.
  2882. *
  2883. * @param int $lpItemViewId Learnpath Item View ID
  2884. * @param int $course_id
  2885. *
  2886. * @return array
  2887. *
  2888. * @todo Translate labels
  2889. */
  2890. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2891. {
  2892. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2893. $lpItemViewId = (int) $lpItemViewId;
  2894. if (empty($course_id) || empty($lpItemViewId)) {
  2895. return [];
  2896. }
  2897. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2898. $sql = "SELECT * FROM $table
  2899. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2900. ORDER BY order_id ASC";
  2901. $res = Database::query($sql);
  2902. $num = Database::num_rows($res);
  2903. $list = [];
  2904. if ($num > 0) {
  2905. $list[] = [
  2906. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2907. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2908. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2909. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2910. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2911. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2912. ];
  2913. while ($row = Database::fetch_array($res)) {
  2914. $list[] = [
  2915. 'order_id' => $row['order_id'] + 1,
  2916. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2917. 'score_raw' => $row['score_raw'],
  2918. 'score_max' => $row['score_max'],
  2919. 'score_min' => $row['score_min'],
  2920. 'status' => $row['status'],
  2921. ];
  2922. }
  2923. }
  2924. return $list;
  2925. }
  2926. /**
  2927. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2928. * used by get_html_toc() to be ready to display.
  2929. *
  2930. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2931. */
  2932. public function get_toc()
  2933. {
  2934. if ($this->debug > 0) {
  2935. error_log('learnpath::get_toc()', 0);
  2936. }
  2937. $toc = [];
  2938. foreach ($this->ordered_items as $item_id) {
  2939. if ($this->debug > 2) {
  2940. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2941. }
  2942. // TODO: Change this link generation and use new function instead.
  2943. $toc[] = [
  2944. 'id' => $item_id,
  2945. 'title' => $this->items[$item_id]->get_title(),
  2946. 'status' => $this->items[$item_id]->get_status(),
  2947. 'level' => $this->items[$item_id]->get_level(),
  2948. 'type' => $this->items[$item_id]->get_type(),
  2949. 'description' => $this->items[$item_id]->get_description(),
  2950. 'path' => $this->items[$item_id]->get_path(),
  2951. 'parent' => $this->items[$item_id]->get_parent(),
  2952. ];
  2953. }
  2954. if ($this->debug > 2) {
  2955. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2956. }
  2957. return $toc;
  2958. }
  2959. /**
  2960. * Generate and return the table of contents for this learnpath. The JS
  2961. * table returned is used inside of scorm_api.php.
  2962. *
  2963. * @param string $varname
  2964. *
  2965. * @return string A JS array variable construction
  2966. */
  2967. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2968. {
  2969. if ($this->debug > 0) {
  2970. error_log('In learnpath::get_items_details_as_js()', 0);
  2971. }
  2972. $toc = $varname.' = new Array();';
  2973. foreach ($this->ordered_items as $item_id) {
  2974. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2975. }
  2976. if ($this->debug > 2) {
  2977. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2978. }
  2979. return $toc;
  2980. }
  2981. /**
  2982. * Gets the learning path type.
  2983. *
  2984. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2985. *
  2986. * @return mixed Type ID or name, depending on the parameter
  2987. */
  2988. public function get_type($get_name = false)
  2989. {
  2990. $res = false;
  2991. if ($this->debug > 0) {
  2992. error_log('In learnpath::get_type()', 0);
  2993. }
  2994. if (!empty($this->type) && (!$get_name)) {
  2995. $res = $this->type;
  2996. }
  2997. if ($this->debug > 2) {
  2998. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2999. }
  3000. return $res;
  3001. }
  3002. /**
  3003. * Gets the learning path type as static method.
  3004. *
  3005. * @param int $lp_id
  3006. *
  3007. * @return mixed Type ID or name, depending on the parameter
  3008. */
  3009. public static function get_type_static($lp_id = 0)
  3010. {
  3011. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  3012. $lp_id = (int) $lp_id;
  3013. $sql = "SELECT lp_type FROM $tbl_lp
  3014. WHERE iid = $lp_id";
  3015. $res = Database::query($sql);
  3016. if ($res === false) {
  3017. return null;
  3018. }
  3019. if (Database::num_rows($res) <= 0) {
  3020. return null;
  3021. }
  3022. $row = Database::fetch_array($res);
  3023. return $row['lp_type'];
  3024. }
  3025. /**
  3026. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  3027. * This method can be used as abstract and is recursive.
  3028. *
  3029. * @param int $lp Learnpath ID
  3030. * @param int $parent Parent ID of the items to look for
  3031. * @param int $course_id
  3032. *
  3033. * @return array Ordered list of item IDs (empty array on error)
  3034. */
  3035. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  3036. {
  3037. if (empty($course_id)) {
  3038. $course_id = api_get_course_int_id();
  3039. } else {
  3040. $course_id = (int) $course_id;
  3041. }
  3042. $list = [];
  3043. if (empty($lp)) {
  3044. return $list;
  3045. }
  3046. $lp = (int) $lp;
  3047. $parent = (int) $parent;
  3048. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3049. $sql = "SELECT iid FROM $tbl_lp_item
  3050. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  3051. ORDER BY display_order";
  3052. $res = Database::query($sql);
  3053. while ($row = Database::fetch_array($res)) {
  3054. $sublist = self::get_flat_ordered_items_list(
  3055. $lp,
  3056. $row['iid'],
  3057. $course_id
  3058. );
  3059. $list[] = $row['iid'];
  3060. foreach ($sublist as $item) {
  3061. $list[] = $item;
  3062. }
  3063. }
  3064. return $list;
  3065. }
  3066. /**
  3067. * @return array
  3068. */
  3069. public static function getChapterTypes()
  3070. {
  3071. return [
  3072. 'dir',
  3073. ];
  3074. }
  3075. /**
  3076. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3077. *
  3078. * @param $tree
  3079. *
  3080. * @return array HTML TOC ready to display
  3081. */
  3082. public function getParentToc($tree)
  3083. {
  3084. if ($this->debug > 0) {
  3085. error_log('In learnpath::get_html_toc()', 0);
  3086. }
  3087. if (empty($tree)) {
  3088. $tree = $this->get_toc();
  3089. }
  3090. $dirTypes = self::getChapterTypes();
  3091. $myCurrentId = $this->get_current_item_id();
  3092. $listParent = [];
  3093. $listChildren = [];
  3094. $listNotParent = [];
  3095. $list = [];
  3096. foreach ($tree as $subtree) {
  3097. if (in_array($subtree['type'], $dirTypes)) {
  3098. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3099. $subtree['children'] = $listChildren;
  3100. if (!empty($subtree['children'])) {
  3101. foreach ($subtree['children'] as $subItem) {
  3102. if ($subItem['id'] == $this->current) {
  3103. $subtree['parent_current'] = 'in';
  3104. $subtree['current'] = 'on';
  3105. }
  3106. }
  3107. }
  3108. $listParent[] = $subtree;
  3109. }
  3110. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3111. $classStatus = [
  3112. 'not attempted' => 'scorm_not_attempted',
  3113. 'incomplete' => 'scorm_not_attempted',
  3114. 'failed' => 'scorm_failed',
  3115. 'completed' => 'scorm_completed',
  3116. 'passed' => 'scorm_completed',
  3117. 'succeeded' => 'scorm_completed',
  3118. 'browsed' => 'scorm_completed',
  3119. ];
  3120. if (isset($classStatus[$subtree['status']])) {
  3121. $cssStatus = $classStatus[$subtree['status']];
  3122. }
  3123. $title = Security::remove_XSS($subtree['title']);
  3124. unset($subtree['title']);
  3125. if (empty($title)) {
  3126. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3127. }
  3128. $classStyle = null;
  3129. if ($subtree['id'] == $this->current) {
  3130. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3131. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3132. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3133. }
  3134. $subtree['title'] = $title;
  3135. $subtree['class'] = $classStyle.' '.$cssStatus;
  3136. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3137. $subtree['current_id'] = $myCurrentId;
  3138. $listNotParent[] = $subtree;
  3139. }
  3140. }
  3141. $list['are_parents'] = $listParent;
  3142. $list['not_parents'] = $listNotParent;
  3143. return $list;
  3144. }
  3145. /**
  3146. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3147. *
  3148. * @param array $tree
  3149. * @param int $id
  3150. * @param bool $parent
  3151. *
  3152. * @return array HTML TOC ready to display
  3153. */
  3154. public function getChildrenToc($tree, $id, $parent = true)
  3155. {
  3156. if ($this->debug > 0) {
  3157. error_log('In learnpath::get_html_toc()', 0);
  3158. }
  3159. if (empty($tree)) {
  3160. $tree = $this->get_toc();
  3161. }
  3162. $dirTypes = self::getChapterTypes();
  3163. $mycurrentitemid = $this->get_current_item_id();
  3164. $list = [];
  3165. $classStatus = [
  3166. 'not attempted' => 'scorm_not_attempted',
  3167. 'incomplete' => 'scorm_not_attempted',
  3168. 'failed' => 'scorm_failed',
  3169. 'completed' => 'scorm_completed',
  3170. 'passed' => 'scorm_completed',
  3171. 'succeeded' => 'scorm_completed',
  3172. 'browsed' => 'scorm_completed',
  3173. ];
  3174. foreach ($tree as $subtree) {
  3175. $subtree['tree'] = null;
  3176. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3177. if ($subtree['id'] == $this->current) {
  3178. $subtree['current'] = 'active';
  3179. } else {
  3180. $subtree['current'] = null;
  3181. }
  3182. if (isset($classStatus[$subtree['status']])) {
  3183. $cssStatus = $classStatus[$subtree['status']];
  3184. }
  3185. $title = Security::remove_XSS($subtree['title']);
  3186. unset($subtree['title']);
  3187. if (empty($title)) {
  3188. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3189. }
  3190. $classStyle = null;
  3191. if ($subtree['id'] == $this->current) {
  3192. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3193. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3194. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3195. }
  3196. if (in_array($subtree['type'], $dirTypes)) {
  3197. $subtree['title'] = stripslashes($title);
  3198. } else {
  3199. $subtree['title'] = $title;
  3200. $subtree['class'] = $classStyle.' '.$cssStatus;
  3201. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3202. $subtree['current_id'] = $mycurrentitemid;
  3203. }
  3204. $list[] = $subtree;
  3205. }
  3206. }
  3207. return $list;
  3208. }
  3209. /**
  3210. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3211. *
  3212. * @param array $toc_list
  3213. *
  3214. * @return array HTML TOC ready to display
  3215. */
  3216. public function getListArrayToc($toc_list = [])
  3217. {
  3218. if ($this->debug > 0) {
  3219. error_log('In learnpath::get_html_toc()', 0);
  3220. }
  3221. if (empty($toc_list)) {
  3222. $toc_list = $this->get_toc();
  3223. }
  3224. // Temporary variables.
  3225. $mycurrentitemid = $this->get_current_item_id();
  3226. $list = [];
  3227. $arrayList = [];
  3228. $classStatus = [
  3229. 'not attempted' => 'scorm_not_attempted',
  3230. 'incomplete' => 'scorm_not_attempted',
  3231. 'failed' => 'scorm_failed',
  3232. 'completed' => 'scorm_completed',
  3233. 'passed' => 'scorm_completed',
  3234. 'succeeded' => 'scorm_completed',
  3235. 'browsed' => 'scorm_completed',
  3236. ];
  3237. foreach ($toc_list as $item) {
  3238. $list['id'] = $item['id'];
  3239. $list['status'] = $item['status'];
  3240. $cssStatus = null;
  3241. if (isset($classStatus[$item['status']])) {
  3242. $cssStatus = $classStatus[$item['status']];
  3243. }
  3244. $classStyle = ' ';
  3245. $dirTypes = self::getChapterTypes();
  3246. if (in_array($item['type'], $dirTypes)) {
  3247. $classStyle = 'scorm_item_section ';
  3248. }
  3249. if ($item['id'] == $this->current) {
  3250. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3251. } elseif (!in_array($item['type'], $dirTypes)) {
  3252. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3253. }
  3254. $title = $item['title'];
  3255. if (empty($title)) {
  3256. $title = self::rl_get_resource_name(
  3257. api_get_course_id(),
  3258. $this->get_id(),
  3259. $item['id']
  3260. );
  3261. }
  3262. $title = Security::remove_XSS($item['title']);
  3263. if (empty($item['description'])) {
  3264. $list['description'] = $title;
  3265. } else {
  3266. $list['description'] = $item['description'];
  3267. }
  3268. $list['class'] = $classStyle.' '.$cssStatus;
  3269. $list['level'] = $item['level'];
  3270. $list['type'] = $item['type'];
  3271. if (in_array($item['type'], $dirTypes)) {
  3272. $list['css_level'] = 'level_'.$item['level'];
  3273. } else {
  3274. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3275. }
  3276. if (in_array($item['type'], $dirTypes)) {
  3277. $list['title'] = stripslashes($title);
  3278. } else {
  3279. $list['title'] = stripslashes($title);
  3280. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3281. $list['current_id'] = $mycurrentitemid;
  3282. }
  3283. $arrayList[] = $list;
  3284. }
  3285. return $arrayList;
  3286. }
  3287. /**
  3288. * Returns an HTML-formatted string ready to display with teacher buttons
  3289. * in LP view menu.
  3290. *
  3291. * @return string HTML TOC ready to display
  3292. */
  3293. public function get_teacher_toc_buttons()
  3294. {
  3295. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3296. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3297. $html = '';
  3298. if ($isAllow && $hideIcons == false) {
  3299. if ($this->get_lp_session_id() == api_get_session_id()) {
  3300. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3301. $html .= '<div class="btn-group">';
  3302. $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'>".
  3303. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3304. $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'>".
  3305. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3306. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3307. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3308. $html .= '</div>';
  3309. $html .= '</div>';
  3310. }
  3311. }
  3312. return $html;
  3313. }
  3314. /**
  3315. * Gets the learnpath maker name - generally the editor's name.
  3316. *
  3317. * @return string Learnpath maker name
  3318. */
  3319. public function get_maker()
  3320. {
  3321. if ($this->debug > 0) {
  3322. error_log('In learnpath::get_maker()', 0);
  3323. }
  3324. if (!empty($this->maker)) {
  3325. return $this->maker;
  3326. } else {
  3327. return '';
  3328. }
  3329. }
  3330. /**
  3331. * Gets the learnpath name/title.
  3332. *
  3333. * @return string Learnpath name/title
  3334. */
  3335. public function get_name()
  3336. {
  3337. if ($this->debug > 0) {
  3338. error_log('In learnpath::get_name()', 0);
  3339. }
  3340. if (!empty($this->name)) {
  3341. return $this->name;
  3342. } else {
  3343. return 'N/A';
  3344. }
  3345. }
  3346. /**
  3347. * Gets a link to the resource from the present location, depending on item ID.
  3348. *
  3349. * @param string $type Type of link expected
  3350. * @param int $item_id Learnpath item ID
  3351. * @param bool $provided_toc
  3352. *
  3353. * @return string $provided_toc Link to the lp_item resource
  3354. */
  3355. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3356. {
  3357. $course_id = $this->get_course_int_id();
  3358. if ($this->debug > 0) {
  3359. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3360. }
  3361. if (empty($item_id)) {
  3362. if ($this->debug > 2) {
  3363. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3364. error_log('using current: '.$this->get_current_item_id(), 0);
  3365. }
  3366. $item_id = $this->get_current_item_id();
  3367. if (empty($item_id)) {
  3368. if ($this->debug > 2) {
  3369. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3370. }
  3371. //still empty, this means there was no item_id given and we are not in an object context or
  3372. //the object property is empty, return empty link
  3373. $this->first();
  3374. return '';
  3375. }
  3376. }
  3377. $file = '';
  3378. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3379. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3380. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3381. $item_id = (int) $item_id;
  3382. $sql = "SELECT
  3383. l.lp_type as ltype,
  3384. l.path as lpath,
  3385. li.item_type as litype,
  3386. li.path as lipath,
  3387. li.parameters as liparams
  3388. FROM $lp_table l
  3389. INNER JOIN $lp_item_table li
  3390. ON (li.lp_id = l.iid)
  3391. WHERE
  3392. li.iid = $item_id
  3393. ";
  3394. if ($this->debug > 2) {
  3395. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3396. }
  3397. $res = Database::query($sql);
  3398. if (Database::num_rows($res) > 0) {
  3399. $row = Database::fetch_array($res);
  3400. $lp_type = $row['ltype'];
  3401. $lp_path = $row['lpath'];
  3402. $lp_item_type = $row['litype'];
  3403. $lp_item_path = $row['lipath'];
  3404. $lp_item_params = $row['liparams'];
  3405. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3406. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3407. }
  3408. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3409. if ($type === 'http') {
  3410. //web path
  3411. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3412. } else {
  3413. $course_path = $sys_course_path; //system path
  3414. }
  3415. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3416. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3417. if (in_array(
  3418. $lp_item_type,
  3419. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3420. )
  3421. ) {
  3422. $lp_type = 1;
  3423. }
  3424. if ($this->debug > 2) {
  3425. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3426. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3427. }
  3428. // Now go through the specific cases to get the end of the path
  3429. // @todo Use constants instead of int values.
  3430. switch ($lp_type) {
  3431. case 1:
  3432. $file = self::rl_get_resource_link_for_learnpath(
  3433. $course_id,
  3434. $this->get_id(),
  3435. $item_id,
  3436. $this->get_view_id()
  3437. );
  3438. if ($this->debug > 0) {
  3439. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3440. }
  3441. switch ($lp_item_type) {
  3442. case 'document':
  3443. // Shows a button to download the file instead of just downloading the file directly.
  3444. $documentPathInfo = pathinfo($file);
  3445. if (isset($documentPathInfo['extension'])) {
  3446. $parsed = parse_url($documentPathInfo['extension']);
  3447. if (isset($parsed['path'])) {
  3448. $extension = $parsed['path'];
  3449. $extensionsToDownload = [
  3450. 'zip',
  3451. 'ppt',
  3452. 'pptx',
  3453. 'ods',
  3454. 'xlsx',
  3455. 'xls',
  3456. 'csv',
  3457. 'doc',
  3458. 'docx',
  3459. 'dot',
  3460. ];
  3461. if (in_array($extension, $extensionsToDownload)) {
  3462. $file = api_get_path(WEB_CODE_PATH).
  3463. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3464. }
  3465. }
  3466. }
  3467. break;
  3468. case 'dir':
  3469. $file = 'lp_content.php?type=dir';
  3470. break;
  3471. case 'link':
  3472. if (Link::is_youtube_link($file)) {
  3473. $src = Link::get_youtube_video_id($file);
  3474. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3475. } elseif (Link::isVimeoLink($file)) {
  3476. $src = Link::getVimeoLinkId($file);
  3477. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3478. } else {
  3479. // If the current site is HTTPS and the link is
  3480. // HTTP, browsers will refuse opening the link
  3481. $urlId = api_get_current_access_url_id();
  3482. $url = api_get_access_url($urlId, false);
  3483. $protocol = substr($url['url'], 0, 5);
  3484. if ($protocol === 'https') {
  3485. $linkProtocol = substr($file, 0, 5);
  3486. if ($linkProtocol === 'http:') {
  3487. //this is the special intervention case
  3488. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3489. }
  3490. }
  3491. }
  3492. break;
  3493. case 'quiz':
  3494. // Check how much attempts of a exercise exits in lp
  3495. $lp_item_id = $this->get_current_item_id();
  3496. $lp_view_id = $this->get_view_id();
  3497. $prevent_reinit = null;
  3498. if (isset($this->items[$this->current])) {
  3499. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3500. }
  3501. if (empty($provided_toc)) {
  3502. if ($this->debug > 0) {
  3503. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3504. }
  3505. $list = $this->get_toc();
  3506. } else {
  3507. if ($this->debug > 0) {
  3508. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3509. }
  3510. $list = $provided_toc;
  3511. }
  3512. $type_quiz = false;
  3513. foreach ($list as $toc) {
  3514. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3515. $type_quiz = true;
  3516. }
  3517. }
  3518. if ($type_quiz) {
  3519. $lp_item_id = (int) $lp_item_id;
  3520. $lp_view_id = (int) $lp_view_id;
  3521. $sql = "SELECT count(*) FROM $lp_item_view_table
  3522. WHERE
  3523. c_id = $course_id AND
  3524. lp_item_id='".$lp_item_id."' AND
  3525. lp_view_id ='".$lp_view_id."' AND
  3526. status='completed'";
  3527. $result = Database::query($sql);
  3528. $row_count = Database:: fetch_row($result);
  3529. $count_item_view = (int) $row_count[0];
  3530. $not_multiple_attempt = 0;
  3531. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3532. $not_multiple_attempt = 1;
  3533. }
  3534. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3535. }
  3536. break;
  3537. }
  3538. $tmp_array = explode('/', $file);
  3539. $document_name = $tmp_array[count($tmp_array) - 1];
  3540. if (strpos($document_name, '_DELETED_')) {
  3541. $file = 'blank.php?error=document_deleted';
  3542. }
  3543. break;
  3544. case 2:
  3545. if ($this->debug > 2) {
  3546. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3547. }
  3548. if ($lp_item_type != 'dir') {
  3549. // Quite complex here:
  3550. // We want to make sure 'http://' (and similar) links can
  3551. // be loaded as is (withouth the Chamilo path in front) but
  3552. // some contents use this form: resource.htm?resource=http://blablabla
  3553. // which means we have to find a protocol at the path's start, otherwise
  3554. // it should not be considered as an external URL.
  3555. // if ($this->prerequisites_match($item_id)) {
  3556. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3557. if ($this->debug > 2) {
  3558. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3559. }
  3560. // Distant url, return as is.
  3561. $file = $lp_item_path;
  3562. } else {
  3563. if ($this->debug > 2) {
  3564. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3565. }
  3566. // Prevent getting untranslatable urls.
  3567. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3568. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3569. // Prepare the path.
  3570. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3571. // TODO: Fix this for urls with protocol header.
  3572. $file = str_replace('//', '/', $file);
  3573. $file = str_replace(':/', '://', $file);
  3574. if (substr($lp_path, -1) == '/') {
  3575. $lp_path = substr($lp_path, 0, -1);
  3576. }
  3577. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3578. // if file not found.
  3579. $decoded = html_entity_decode($lp_item_path);
  3580. list($decoded) = explode('?', $decoded);
  3581. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3582. $file = self::rl_get_resource_link_for_learnpath(
  3583. $course_id,
  3584. $this->get_id(),
  3585. $item_id,
  3586. $this->get_view_id()
  3587. );
  3588. if (empty($file)) {
  3589. $file = 'blank.php?error=document_not_found';
  3590. } else {
  3591. $tmp_array = explode('/', $file);
  3592. $document_name = $tmp_array[count($tmp_array) - 1];
  3593. if (strpos($document_name, '_DELETED_')) {
  3594. $file = 'blank.php?error=document_deleted';
  3595. } else {
  3596. $file = 'blank.php?error=document_not_found';
  3597. }
  3598. }
  3599. } else {
  3600. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3601. }
  3602. }
  3603. }
  3604. // We want to use parameters if they were defined in the imsmanifest
  3605. if (strpos($file, 'blank.php') === false) {
  3606. $lp_item_params = ltrim($lp_item_params, '?');
  3607. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3608. }
  3609. } else {
  3610. $file = 'lp_content.php?type=dir';
  3611. }
  3612. break;
  3613. case 3:
  3614. if ($this->debug > 2) {
  3615. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3616. }
  3617. // Formatting AICC HACP append URL.
  3618. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3619. if (!empty($lp_item_params)) {
  3620. $aicc_append .= $lp_item_params.'&';
  3621. }
  3622. if ($lp_item_type != 'dir') {
  3623. // Quite complex here:
  3624. // We want to make sure 'http://' (and similar) links can
  3625. // be loaded as is (withouth the Chamilo path in front) but
  3626. // some contents use this form: resource.htm?resource=http://blablabla
  3627. // which means we have to find a protocol at the path's start, otherwise
  3628. // it should not be considered as an external URL.
  3629. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3630. if ($this->debug > 2) {
  3631. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3632. }
  3633. // Distant url, return as is.
  3634. $file = $lp_item_path;
  3635. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3636. /*
  3637. if (stristr($file,'<servername>') !== false) {
  3638. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3639. }
  3640. */
  3641. if (stripos($file, '<servername>') !== false) {
  3642. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3643. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3644. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3645. }
  3646. $file .= $aicc_append;
  3647. } else {
  3648. if ($this->debug > 2) {
  3649. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3650. }
  3651. // Prevent getting untranslatable urls.
  3652. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3653. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3654. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3655. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3656. // TODO: Fix this for urls with protocol header.
  3657. $file = str_replace('//', '/', $file);
  3658. $file = str_replace(':/', '://', $file);
  3659. $file .= $aicc_append;
  3660. }
  3661. } else {
  3662. $file = 'lp_content.php?type=dir';
  3663. }
  3664. break;
  3665. case 4:
  3666. break;
  3667. default:
  3668. break;
  3669. }
  3670. // Replace &amp; by & because &amp; will break URL with params
  3671. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3672. }
  3673. if ($this->debug > 2) {
  3674. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3675. }
  3676. return $file;
  3677. }
  3678. /**
  3679. * Gets the latest usable view or generate a new one.
  3680. *
  3681. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3682. *
  3683. * @return int DB lp_view id
  3684. */
  3685. public function get_view($attempt_num = 0)
  3686. {
  3687. if ($this->debug > 0) {
  3688. error_log('In learnpath::get_view()', 0);
  3689. }
  3690. $search = '';
  3691. // Use $attempt_num to enable multi-views management (disabled so far).
  3692. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3693. $search = 'AND view_count = '.$attempt_num;
  3694. }
  3695. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3696. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3697. $course_id = api_get_course_int_id();
  3698. $sessionId = api_get_session_id();
  3699. $sql = "SELECT iid, view_count FROM $lp_view_table
  3700. WHERE
  3701. c_id = $course_id AND
  3702. lp_id = ".$this->get_id()." AND
  3703. user_id = ".$this->get_user_id()." AND
  3704. session_id = $sessionId
  3705. $search
  3706. ORDER BY view_count DESC";
  3707. $res = Database::query($sql);
  3708. if (Database::num_rows($res) > 0) {
  3709. $row = Database::fetch_array($res);
  3710. $this->lp_view_id = $row['iid'];
  3711. } elseif (!api_is_invitee()) {
  3712. // There is no database record, create one.
  3713. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3714. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3715. Database::query($sql);
  3716. $id = Database::insert_id();
  3717. $this->lp_view_id = $id;
  3718. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3719. Database::query($sql);
  3720. }
  3721. return $this->lp_view_id;
  3722. }
  3723. /**
  3724. * Gets the current view id.
  3725. *
  3726. * @return int View ID (from lp_view)
  3727. */
  3728. public function get_view_id()
  3729. {
  3730. if ($this->debug > 0) {
  3731. error_log('In learnpath::get_view_id()', 0);
  3732. }
  3733. if (!empty($this->lp_view_id)) {
  3734. return $this->lp_view_id;
  3735. } else {
  3736. return 0;
  3737. }
  3738. }
  3739. /**
  3740. * Gets the update queue.
  3741. *
  3742. * @return array Array containing IDs of items to be updated by JavaScript
  3743. */
  3744. public function get_update_queue()
  3745. {
  3746. if ($this->debug > 0) {
  3747. error_log('In learnpath::get_update_queue()', 0);
  3748. }
  3749. return $this->update_queue;
  3750. }
  3751. /**
  3752. * Gets the user ID.
  3753. *
  3754. * @return int User ID
  3755. */
  3756. public function get_user_id()
  3757. {
  3758. if ($this->debug > 0) {
  3759. error_log('In learnpath::get_user_id()', 0);
  3760. }
  3761. if (!empty($this->user_id)) {
  3762. return $this->user_id;
  3763. } else {
  3764. return false;
  3765. }
  3766. }
  3767. /**
  3768. * Checks if any of the items has an audio element attached.
  3769. *
  3770. * @return bool True or false
  3771. */
  3772. public function has_audio()
  3773. {
  3774. if ($this->debug > 1) {
  3775. error_log('In learnpath::has_audio()', 0);
  3776. }
  3777. $has = false;
  3778. foreach ($this->items as $i => $item) {
  3779. if (!empty($this->items[$i]->audio)) {
  3780. $has = true;
  3781. break;
  3782. }
  3783. }
  3784. return $has;
  3785. }
  3786. /**
  3787. * Moves an item up and down at its level.
  3788. *
  3789. * @param int $id Item to move up and down
  3790. * @param string $direction Direction 'up' or 'down'
  3791. *
  3792. * @return bool|int
  3793. */
  3794. public function move_item($id, $direction)
  3795. {
  3796. $course_id = api_get_course_int_id();
  3797. if ($this->debug > 0) {
  3798. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3799. }
  3800. if (empty($id) || empty($direction)) {
  3801. return false;
  3802. }
  3803. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3804. $sql_sel = "SELECT *
  3805. FROM $tbl_lp_item
  3806. WHERE
  3807. iid = $id
  3808. ";
  3809. $res_sel = Database::query($sql_sel);
  3810. // Check if elem exists.
  3811. if (Database::num_rows($res_sel) < 1) {
  3812. return false;
  3813. }
  3814. // Gather data.
  3815. $row = Database::fetch_array($res_sel);
  3816. $previous = $row['previous_item_id'];
  3817. $next = $row['next_item_id'];
  3818. $display = $row['display_order'];
  3819. $parent = $row['parent_item_id'];
  3820. $lp = $row['lp_id'];
  3821. // Update the item (switch with previous/next one).
  3822. switch ($direction) {
  3823. case 'up':
  3824. if ($this->debug > 2) {
  3825. error_log('Movement up detected', 0);
  3826. }
  3827. if ($display > 1) {
  3828. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3829. WHERE iid = $previous";
  3830. if ($this->debug > 2) {
  3831. error_log('Selecting previous: '.$sql_sel2, 0);
  3832. }
  3833. $res_sel2 = Database::query($sql_sel2);
  3834. if (Database::num_rows($res_sel2) < 1) {
  3835. $previous_previous = 0;
  3836. }
  3837. // Gather data.
  3838. $row2 = Database::fetch_array($res_sel2);
  3839. $previous_previous = $row2['previous_item_id'];
  3840. // Update previous_previous item (switch "next" with current).
  3841. if ($previous_previous != 0) {
  3842. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3843. next_item_id = $id
  3844. WHERE iid = $previous_previous";
  3845. if ($this->debug > 2) {
  3846. error_log($sql_upd2, 0);
  3847. }
  3848. Database::query($sql_upd2);
  3849. }
  3850. // Update previous item (switch with current).
  3851. if ($previous != 0) {
  3852. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3853. next_item_id = $next,
  3854. previous_item_id = $id,
  3855. display_order = display_order +1
  3856. WHERE iid = $previous";
  3857. if ($this->debug > 2) {
  3858. error_log($sql_upd2, 0);
  3859. }
  3860. Database::query($sql_upd2);
  3861. }
  3862. // Update current item (switch with previous).
  3863. if ($id != 0) {
  3864. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3865. next_item_id = $previous,
  3866. previous_item_id = $previous_previous,
  3867. display_order = display_order-1
  3868. WHERE c_id = ".$course_id." AND id = $id";
  3869. if ($this->debug > 2) {
  3870. error_log($sql_upd2, 0);
  3871. }
  3872. Database::query($sql_upd2);
  3873. }
  3874. // Update next item (new previous item).
  3875. if (!empty($next)) {
  3876. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3877. WHERE iid = $next";
  3878. if ($this->debug > 2) {
  3879. error_log($sql_upd2, 0);
  3880. }
  3881. Database::query($sql_upd2);
  3882. }
  3883. $display = $display - 1;
  3884. }
  3885. break;
  3886. case 'down':
  3887. if ($this->debug > 2) {
  3888. error_log('Movement down detected', 0);
  3889. }
  3890. if ($next != 0) {
  3891. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3892. WHERE iid = $next";
  3893. if ($this->debug > 2) {
  3894. error_log('Selecting next: '.$sql_sel2, 0);
  3895. }
  3896. $res_sel2 = Database::query($sql_sel2);
  3897. if (Database::num_rows($res_sel2) < 1) {
  3898. $next_next = 0;
  3899. }
  3900. // Gather data.
  3901. $row2 = Database::fetch_array($res_sel2);
  3902. $next_next = $row2['next_item_id'];
  3903. // Update previous item (switch with current).
  3904. if ($previous != 0) {
  3905. $sql_upd2 = "UPDATE $tbl_lp_item
  3906. SET next_item_id = $next
  3907. WHERE iid = $previous";
  3908. Database::query($sql_upd2);
  3909. }
  3910. // Update current item (switch with previous).
  3911. if ($id != 0) {
  3912. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3913. previous_item_id = $next,
  3914. next_item_id = $next_next,
  3915. display_order = display_order + 1
  3916. WHERE iid = $id";
  3917. Database::query($sql_upd2);
  3918. }
  3919. // Update next item (new previous item).
  3920. if ($next != 0) {
  3921. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3922. previous_item_id = $previous,
  3923. next_item_id = $id,
  3924. display_order = display_order-1
  3925. WHERE iid = $next";
  3926. Database::query($sql_upd2);
  3927. }
  3928. // Update next_next item (switch "previous" with current).
  3929. if ($next_next != 0) {
  3930. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3931. previous_item_id = $id
  3932. WHERE iid = $next_next";
  3933. Database::query($sql_upd2);
  3934. }
  3935. $display = $display + 1;
  3936. }
  3937. break;
  3938. default:
  3939. return false;
  3940. }
  3941. return $display;
  3942. }
  3943. /**
  3944. * Move a LP up (display_order).
  3945. *
  3946. * @param int $lp_id Learnpath ID
  3947. * @param int $categoryId Category ID
  3948. *
  3949. * @return bool
  3950. */
  3951. public static function move_up($lp_id, $categoryId = 0)
  3952. {
  3953. $courseId = api_get_course_int_id();
  3954. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3955. $categoryCondition = '';
  3956. if (!empty($categoryId)) {
  3957. $categoryId = (int) $categoryId;
  3958. $categoryCondition = " AND category_id = $categoryId";
  3959. }
  3960. $sql = "SELECT * FROM $lp_table
  3961. WHERE c_id = $courseId
  3962. $categoryCondition
  3963. ORDER BY display_order";
  3964. $res = Database::query($sql);
  3965. if ($res === false) {
  3966. return false;
  3967. }
  3968. $lps = [];
  3969. $lp_order = [];
  3970. $num = Database::num_rows($res);
  3971. // First check the order is correct, globally (might be wrong because
  3972. // of versions < 1.8.4)
  3973. if ($num > 0) {
  3974. $i = 1;
  3975. while ($row = Database::fetch_array($res)) {
  3976. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3977. $sql = "UPDATE $lp_table SET display_order = $i
  3978. WHERE iid = ".$row['iid'];
  3979. Database::query($sql);
  3980. }
  3981. $row['display_order'] = $i;
  3982. $lps[$row['iid']] = $row;
  3983. $lp_order[$i] = $row['iid'];
  3984. $i++;
  3985. }
  3986. }
  3987. if ($num > 1) { // If there's only one element, no need to sort.
  3988. $order = $lps[$lp_id]['display_order'];
  3989. if ($order > 1) { // If it's the first element, no need to move up.
  3990. $sql = "UPDATE $lp_table SET display_order = $order
  3991. WHERE iid = ".$lp_order[$order - 1];
  3992. Database::query($sql);
  3993. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3994. WHERE iid = $lp_id";
  3995. Database::query($sql);
  3996. }
  3997. }
  3998. return true;
  3999. }
  4000. /**
  4001. * Move a learnpath down (display_order).
  4002. *
  4003. * @param int $lp_id Learnpath ID
  4004. * @param int $categoryId Category ID
  4005. *
  4006. * @return bool
  4007. */
  4008. public static function move_down($lp_id, $categoryId = 0)
  4009. {
  4010. $courseId = api_get_course_int_id();
  4011. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4012. $categoryCondition = '';
  4013. if (!empty($categoryId)) {
  4014. $categoryId = (int) $categoryId;
  4015. $categoryCondition = " AND category_id = $categoryId";
  4016. }
  4017. $sql = "SELECT * FROM $lp_table
  4018. WHERE c_id = $courseId
  4019. $categoryCondition
  4020. ORDER BY display_order";
  4021. $res = Database::query($sql);
  4022. if ($res === false) {
  4023. return false;
  4024. }
  4025. $lps = [];
  4026. $lp_order = [];
  4027. $num = Database::num_rows($res);
  4028. $max = 0;
  4029. // First check the order is correct, globally (might be wrong because
  4030. // of versions < 1.8.4).
  4031. if ($num > 0) {
  4032. $i = 1;
  4033. while ($row = Database::fetch_array($res)) {
  4034. $max = $i;
  4035. if ($row['display_order'] != $i) {
  4036. // If we find a gap in the order, we need to fix it.
  4037. $sql = "UPDATE $lp_table SET display_order = $i
  4038. WHERE iid = ".$row['iid'];
  4039. Database::query($sql);
  4040. }
  4041. $row['display_order'] = $i;
  4042. $lps[$row['iid']] = $row;
  4043. $lp_order[$i] = $row['iid'];
  4044. $i++;
  4045. }
  4046. }
  4047. if ($num > 1) { // If there's only one element, no need to sort.
  4048. $order = $lps[$lp_id]['display_order'];
  4049. if ($order < $max) { // If it's the first element, no need to move up.
  4050. $sql = "UPDATE $lp_table SET display_order = $order
  4051. WHERE iid = ".$lp_order[$order + 1];
  4052. Database::query($sql);
  4053. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  4054. WHERE iid = $lp_id";
  4055. Database::query($sql);
  4056. }
  4057. }
  4058. return true;
  4059. }
  4060. /**
  4061. * Updates learnpath attributes to point to the next element
  4062. * The last part is similar to set_current_item but processing the other way around.
  4063. */
  4064. public function next()
  4065. {
  4066. if ($this->debug > 0) {
  4067. error_log('In learnpath::next()', 0);
  4068. }
  4069. $this->last = $this->get_current_item_id();
  4070. $this->items[$this->last]->save(
  4071. false,
  4072. $this->prerequisites_match($this->last)
  4073. );
  4074. $this->autocomplete_parents($this->last);
  4075. $new_index = $this->get_next_index();
  4076. if ($this->debug > 2) {
  4077. error_log('New index: '.$new_index, 0);
  4078. }
  4079. $this->index = $new_index;
  4080. if ($this->debug > 2) {
  4081. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  4082. }
  4083. $this->current = $this->ordered_items[$new_index];
  4084. if ($this->debug > 2) {
  4085. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  4086. }
  4087. }
  4088. /**
  4089. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  4090. * class, this might be redefined to allow several behaviours depending on the document type.
  4091. *
  4092. * @param int $id Resource ID
  4093. */
  4094. public function open($id)
  4095. {
  4096. if ($this->debug > 0) {
  4097. error_log('In learnpath::open()', 0);
  4098. }
  4099. // TODO:
  4100. // set the current resource attribute to this resource
  4101. // switch on element type (redefine in child class?)
  4102. // set status for this item to "opened"
  4103. // start timer
  4104. // initialise score
  4105. $this->index = 0; //or = the last item seen (see $this->last)
  4106. }
  4107. /**
  4108. * Check that all prerequisites are fulfilled. Returns true and an
  4109. * empty string on success, returns false
  4110. * and the prerequisite string on error.
  4111. * This function is based on the rules for aicc_script language as
  4112. * described in the SCORM 1.2 CAM documentation page 108.
  4113. *
  4114. * @param int $itemId Optional item ID. If none given, uses the current open item.
  4115. *
  4116. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  4117. * string otherwise
  4118. */
  4119. public function prerequisites_match($itemId = null)
  4120. {
  4121. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  4122. if ($allow) {
  4123. if (api_is_allowed_to_edit() ||
  4124. api_is_platform_admin(true) ||
  4125. api_is_drh() ||
  4126. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4127. ) {
  4128. return true;
  4129. }
  4130. }
  4131. $debug = $this->debug;
  4132. if ($debug > 0) {
  4133. error_log('In learnpath::prerequisites_match()', 0);
  4134. }
  4135. if (empty($itemId)) {
  4136. $itemId = $this->current;
  4137. }
  4138. $currentItem = $this->getItem($itemId);
  4139. if ($currentItem) {
  4140. if ($this->type == 2) {
  4141. // Getting prereq from scorm
  4142. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4143. } else {
  4144. $prereq_string = $currentItem->get_prereq_string();
  4145. }
  4146. if (empty($prereq_string)) {
  4147. if ($debug > 0) {
  4148. error_log('Found prereq_string is empty return true');
  4149. }
  4150. return true;
  4151. }
  4152. // Clean spaces.
  4153. $prereq_string = str_replace(' ', '', $prereq_string);
  4154. if ($debug > 0) {
  4155. error_log('Found prereq_string: '.$prereq_string, 0);
  4156. }
  4157. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4158. $result = $currentItem->parse_prereq(
  4159. $prereq_string,
  4160. $this->items,
  4161. $this->refs_list,
  4162. $this->get_user_id()
  4163. );
  4164. if ($result === false) {
  4165. $this->set_error_msg($currentItem->prereq_alert);
  4166. }
  4167. } else {
  4168. $result = true;
  4169. if ($debug > 1) {
  4170. error_log('$this->items['.$itemId.'] was not an object', 0);
  4171. }
  4172. }
  4173. if ($debug > 1) {
  4174. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4175. }
  4176. return $result;
  4177. }
  4178. /**
  4179. * Updates learnpath attributes to point to the previous element
  4180. * The last part is similar to set_current_item but processing the other way around.
  4181. */
  4182. public function previous()
  4183. {
  4184. if ($this->debug > 0) {
  4185. error_log('In learnpath::previous()', 0);
  4186. }
  4187. $this->last = $this->get_current_item_id();
  4188. $this->items[$this->last]->save(
  4189. false,
  4190. $this->prerequisites_match($this->last)
  4191. );
  4192. $this->autocomplete_parents($this->last);
  4193. $new_index = $this->get_previous_index();
  4194. $this->index = $new_index;
  4195. $this->current = $this->ordered_items[$new_index];
  4196. }
  4197. /**
  4198. * Publishes a learnpath. This basically means show or hide the learnpath
  4199. * to normal users.
  4200. * Can be used as abstract.
  4201. *
  4202. * @param int $lp_id Learnpath ID
  4203. * @param int $set_visibility New visibility
  4204. *
  4205. * @return bool
  4206. */
  4207. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4208. {
  4209. $action = 'visible';
  4210. if ($set_visibility != 1) {
  4211. $action = 'invisible';
  4212. self::toggle_publish($lp_id, 'i');
  4213. }
  4214. return api_item_property_update(
  4215. api_get_course_info(),
  4216. TOOL_LEARNPATH,
  4217. $lp_id,
  4218. $action,
  4219. api_get_user_id()
  4220. );
  4221. }
  4222. /**
  4223. * Publishes a learnpath category.
  4224. * This basically means show or hide the learnpath category to normal users.
  4225. *
  4226. * @param int $id
  4227. * @param int $visibility
  4228. *
  4229. * @throws \Doctrine\ORM\NonUniqueResultException
  4230. * @throws \Doctrine\ORM\ORMException
  4231. * @throws \Doctrine\ORM\OptimisticLockException
  4232. * @throws \Doctrine\ORM\TransactionRequiredException
  4233. *
  4234. * @return bool
  4235. */
  4236. public static function toggleCategoryVisibility($id, $visibility = 1)
  4237. {
  4238. $action = 'visible';
  4239. if ($visibility != 1) {
  4240. $action = 'invisible';
  4241. $list = new LearnpathList(
  4242. api_get_user_id(),
  4243. null,
  4244. null,
  4245. null,
  4246. false,
  4247. $id
  4248. );
  4249. $lpList = $list->get_flat_list();
  4250. foreach ($lpList as $lp) {
  4251. self::toggle_visibility($lp['iid'], 0);
  4252. }
  4253. self::toggleCategoryPublish($id, 0);
  4254. }
  4255. return api_item_property_update(
  4256. api_get_course_info(),
  4257. TOOL_LEARNPATH_CATEGORY,
  4258. $id,
  4259. $action,
  4260. api_get_user_id()
  4261. );
  4262. }
  4263. /**
  4264. * Publishes a learnpath. This basically means show or hide the learnpath
  4265. * on the course homepage
  4266. * Can be used as abstract.
  4267. *
  4268. * @param int $lp_id Learnpath id
  4269. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4270. *
  4271. * @return bool
  4272. */
  4273. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4274. {
  4275. $course_id = api_get_course_int_id();
  4276. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4277. $lp_id = (int) $lp_id;
  4278. $sql = "SELECT * FROM $tbl_lp
  4279. WHERE iid = $lp_id";
  4280. $result = Database::query($sql);
  4281. if (Database::num_rows($result)) {
  4282. $row = Database::fetch_array($result);
  4283. $name = Database::escape_string($row['name']);
  4284. if ($set_visibility == 'i') {
  4285. $v = 0;
  4286. }
  4287. if ($set_visibility == 'v') {
  4288. $v = 1;
  4289. }
  4290. $session_id = api_get_session_id();
  4291. $session_condition = api_get_session_condition($session_id);
  4292. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4293. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4294. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4295. $sql = "SELECT * FROM $tbl_tool
  4296. WHERE
  4297. c_id = $course_id AND
  4298. (link = '$link' OR link = '$oldLink') AND
  4299. image = 'scormbuilder.gif' AND
  4300. (
  4301. link LIKE '$link%' OR
  4302. link LIKE '$oldLink%'
  4303. )
  4304. $session_condition
  4305. ";
  4306. $result = Database::query($sql);
  4307. $num = Database::num_rows($result);
  4308. if ($set_visibility == 'i' && $num > 0) {
  4309. $sql = "DELETE FROM $tbl_tool
  4310. WHERE
  4311. c_id = $course_id AND
  4312. (link = '$link' OR link = '$oldLink') AND
  4313. image='scormbuilder.gif'
  4314. $session_condition";
  4315. Database::query($sql);
  4316. } elseif ($set_visibility == 'v' && $num == 0) {
  4317. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4318. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4319. Database::query($sql);
  4320. $insertId = Database::insert_id();
  4321. if ($insertId) {
  4322. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4323. Database::query($sql);
  4324. }
  4325. } elseif ($set_visibility == 'v' && $num > 0) {
  4326. $sql = "UPDATE $tbl_tool SET
  4327. c_id = $course_id,
  4328. name = '$name',
  4329. link = '$link',
  4330. image = 'scormbuilder.gif',
  4331. visibility = '$v',
  4332. admin = '0',
  4333. address = 'pastillegris.gif',
  4334. added_tool = 0,
  4335. session_id = $session_id
  4336. WHERE
  4337. c_id = ".$course_id." AND
  4338. (link = '$link' OR link = '$oldLink') AND
  4339. image='scormbuilder.gif'
  4340. $session_condition
  4341. ";
  4342. Database::query($sql);
  4343. } else {
  4344. // Parameter and database incompatible, do nothing, exit.
  4345. return false;
  4346. }
  4347. } else {
  4348. return false;
  4349. }
  4350. }
  4351. /**
  4352. * Publishes a learnpath.
  4353. * Show or hide the learnpath category on the course homepage.
  4354. *
  4355. * @param int $id
  4356. * @param int $setVisibility
  4357. *
  4358. * @throws \Doctrine\ORM\NonUniqueResultException
  4359. * @throws \Doctrine\ORM\ORMException
  4360. * @throws \Doctrine\ORM\OptimisticLockException
  4361. * @throws \Doctrine\ORM\TransactionRequiredException
  4362. *
  4363. * @return bool
  4364. */
  4365. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4366. {
  4367. $courseId = api_get_course_int_id();
  4368. $sessionId = api_get_session_id();
  4369. $sessionCondition = api_get_session_condition(
  4370. $sessionId,
  4371. true,
  4372. false,
  4373. 't.sessionId'
  4374. );
  4375. $em = Database::getManager();
  4376. /** @var CLpCategory $category */
  4377. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4378. if (!$category) {
  4379. return false;
  4380. }
  4381. if (empty($courseId)) {
  4382. return false;
  4383. }
  4384. $link = self::getCategoryLinkForTool($id);
  4385. /** @var CTool $tool */
  4386. $tool = $em->createQuery("
  4387. SELECT t FROM ChamiloCourseBundle:CTool t
  4388. WHERE
  4389. t.cId = :course AND
  4390. t.link = :link1 AND
  4391. t.image = 'lp_category.gif' AND
  4392. t.link LIKE :link2
  4393. $sessionCondition
  4394. ")
  4395. ->setParameters([
  4396. 'course' => (int) $courseId,
  4397. 'link1' => $link,
  4398. 'link2' => "$link%",
  4399. ])
  4400. ->getOneOrNullResult();
  4401. if ($setVisibility == 0 && $tool) {
  4402. $em->remove($tool);
  4403. $em->flush();
  4404. return true;
  4405. }
  4406. if ($setVisibility == 1 && !$tool) {
  4407. $tool = new CTool();
  4408. $tool
  4409. ->setCategory('authoring')
  4410. ->setCId($courseId)
  4411. ->setName(strip_tags($category->getName()))
  4412. ->setLink($link)
  4413. ->setImage('lp_category.gif')
  4414. ->setVisibility(1)
  4415. ->setAdmin(0)
  4416. ->setAddress('pastillegris.gif')
  4417. ->setAddedTool(0)
  4418. ->setSessionId($sessionId)
  4419. ->setTarget('_self');
  4420. $em->persist($tool);
  4421. $em->flush();
  4422. $tool->setId($tool->getIid());
  4423. $em->persist($tool);
  4424. $em->flush();
  4425. return true;
  4426. }
  4427. if ($setVisibility == 1 && $tool) {
  4428. $tool
  4429. ->setName(strip_tags($category->getName()))
  4430. ->setVisibility(1);
  4431. $em->persist($tool);
  4432. $em->flush();
  4433. return true;
  4434. }
  4435. return false;
  4436. }
  4437. /**
  4438. * Check if the learnpath category is visible for a user.
  4439. *
  4440. * @param CLpCategory $category
  4441. * @param User $user
  4442. * @param int
  4443. * @param int
  4444. *
  4445. * @return bool
  4446. */
  4447. public static function categoryIsVisibleForStudent(
  4448. CLpCategory $category,
  4449. User $user,
  4450. $courseId = 0,
  4451. $sessionId = 0
  4452. ) {
  4453. $subscriptionSettings = self::getSubscriptionSettings();
  4454. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4455. return true;
  4456. }
  4457. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4458. if ($isAllowedToEdit) {
  4459. return true;
  4460. }
  4461. if (empty($category)) {
  4462. return false;
  4463. }
  4464. $users = $category->getUsers();
  4465. if (empty($users) || !$users->count()) {
  4466. return true;
  4467. }
  4468. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4469. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4470. if ($category->hasUserAdded($user)) {
  4471. return true;
  4472. }
  4473. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4474. if (!empty($groups)) {
  4475. $em = Database::getManager();
  4476. /** @var ItemPropertyRepository $itemRepo */
  4477. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4478. /** @var CourseRepository $courseRepo */
  4479. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4480. $session = null;
  4481. if (!empty($sessionId)) {
  4482. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4483. }
  4484. $course = $courseRepo->find($courseId);
  4485. // Subscribed groups to a LP
  4486. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4487. TOOL_LEARNPATH_CATEGORY,
  4488. $category->getId(),
  4489. $course,
  4490. $session
  4491. );
  4492. if (!empty($subscribedGroupsInLp)) {
  4493. $groups = array_column($groups, 'iid');
  4494. /** @var CItemProperty $item */
  4495. foreach ($subscribedGroupsInLp as $item) {
  4496. if ($item->getGroup() &&
  4497. in_array($item->getGroup()->getId(), $groups)
  4498. ) {
  4499. return true;
  4500. }
  4501. }
  4502. }
  4503. }
  4504. return false;
  4505. }
  4506. /**
  4507. * Check if a learnpath category is published as course tool.
  4508. *
  4509. * @param CLpCategory $category
  4510. * @param int $courseId
  4511. *
  4512. * @return bool
  4513. */
  4514. public static function categoryIsPublished(
  4515. CLpCategory $category,
  4516. $courseId
  4517. ) {
  4518. $link = self::getCategoryLinkForTool($category->getId());
  4519. $em = Database::getManager();
  4520. $tools = $em
  4521. ->createQuery("
  4522. SELECT t FROM ChamiloCourseBundle:CTool t
  4523. WHERE t.cId = :course AND
  4524. t.name = :name AND
  4525. t.image = 'lp_category.gif' AND
  4526. t.link LIKE :link
  4527. ")
  4528. ->setParameters([
  4529. 'course' => $courseId,
  4530. 'name' => strip_tags($category->getName()),
  4531. 'link' => "$link%",
  4532. ])
  4533. ->getResult();
  4534. /** @var CTool $tool */
  4535. $tool = current($tools);
  4536. return $tool ? $tool->getVisibility() : false;
  4537. }
  4538. /**
  4539. * Restart the whole learnpath. Return the URL of the first element.
  4540. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4541. * To use a similar method statically, use the create_new_attempt() method.
  4542. *
  4543. * @return bool
  4544. */
  4545. public function restart()
  4546. {
  4547. if ($this->debug > 0) {
  4548. error_log('In learnpath::restart()', 0);
  4549. }
  4550. // TODO
  4551. // Call autosave method to save the current progress.
  4552. //$this->index = 0;
  4553. if (api_is_invitee()) {
  4554. return false;
  4555. }
  4556. $session_id = api_get_session_id();
  4557. $course_id = api_get_course_int_id();
  4558. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4559. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4560. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4561. if ($this->debug > 2) {
  4562. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4563. }
  4564. Database::query($sql);
  4565. $view_id = Database::insert_id();
  4566. if ($view_id) {
  4567. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4568. Database::query($sql);
  4569. $this->lp_view_id = $view_id;
  4570. $this->attempt = $this->attempt + 1;
  4571. } else {
  4572. $this->error = 'Could not insert into item_view table...';
  4573. return false;
  4574. }
  4575. $this->autocomplete_parents($this->current);
  4576. foreach ($this->items as $index => $dummy) {
  4577. $this->items[$index]->restart();
  4578. $this->items[$index]->set_lp_view($this->lp_view_id);
  4579. }
  4580. $this->first();
  4581. return true;
  4582. }
  4583. /**
  4584. * Saves the current item.
  4585. *
  4586. * @return bool
  4587. */
  4588. public function save_current()
  4589. {
  4590. $debug = $this->debug;
  4591. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4592. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4593. if ($debug) {
  4594. error_log('save_current() saving item '.$this->current, 0);
  4595. error_log(''.print_r($this->items, true), 0);
  4596. }
  4597. if (isset($this->items[$this->current]) &&
  4598. is_object($this->items[$this->current])
  4599. ) {
  4600. if ($debug) {
  4601. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4602. }
  4603. $res = $this->items[$this->current]->save(
  4604. false,
  4605. $this->prerequisites_match($this->current)
  4606. );
  4607. $this->autocomplete_parents($this->current);
  4608. $status = $this->items[$this->current]->get_status();
  4609. $this->update_queue[$this->current] = $status;
  4610. if ($debug) {
  4611. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4612. }
  4613. return $res;
  4614. }
  4615. return false;
  4616. }
  4617. /**
  4618. * Saves the given item.
  4619. *
  4620. * @param int $item_id Optional (will take from $_REQUEST if null)
  4621. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4622. *
  4623. * @return bool
  4624. */
  4625. public function save_item($item_id = null, $from_outside = true)
  4626. {
  4627. $debug = $this->debug;
  4628. if ($debug) {
  4629. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4630. }
  4631. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4632. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4633. if (empty($item_id)) {
  4634. $item_id = (int) $_REQUEST['id'];
  4635. }
  4636. if (empty($item_id)) {
  4637. $item_id = $this->get_current_item_id();
  4638. }
  4639. if (isset($this->items[$item_id]) &&
  4640. is_object($this->items[$item_id])
  4641. ) {
  4642. if ($debug) {
  4643. error_log('Object exists');
  4644. }
  4645. // Saving the item.
  4646. $res = $this->items[$item_id]->save(
  4647. $from_outside,
  4648. $this->prerequisites_match($item_id)
  4649. );
  4650. if ($debug) {
  4651. error_log('update_queue before:');
  4652. error_log(print_r($this->update_queue, 1));
  4653. }
  4654. $this->autocomplete_parents($item_id);
  4655. $status = $this->items[$item_id]->get_status();
  4656. $this->update_queue[$item_id] = $status;
  4657. if ($debug) {
  4658. error_log('get_status(): '.$status);
  4659. error_log('update_queue after:');
  4660. error_log(print_r($this->update_queue, 1));
  4661. }
  4662. return $res;
  4663. }
  4664. return false;
  4665. }
  4666. /**
  4667. * Saves the last item seen's ID only in case.
  4668. */
  4669. public function save_last()
  4670. {
  4671. $course_id = api_get_course_int_id();
  4672. $debug = $this->debug;
  4673. if ($debug) {
  4674. error_log('In learnpath::save_last()', 0);
  4675. }
  4676. $session_condition = api_get_session_condition(
  4677. api_get_session_id(),
  4678. true,
  4679. false
  4680. );
  4681. $table = Database::get_course_table(TABLE_LP_VIEW);
  4682. if (isset($this->current) && !api_is_invitee()) {
  4683. if ($debug) {
  4684. error_log('Saving current item ('.$this->current.') for later review', 0);
  4685. }
  4686. $sql = "UPDATE $table SET
  4687. last_item = ".intval($this->get_current_item_id())."
  4688. WHERE
  4689. c_id = $course_id AND
  4690. lp_id = ".$this->get_id()." AND
  4691. user_id = ".$this->get_user_id()." ".$session_condition;
  4692. if ($debug) {
  4693. error_log('Saving last item seen : '.$sql, 0);
  4694. }
  4695. Database::query($sql);
  4696. }
  4697. if (!api_is_invitee()) {
  4698. // Save progress.
  4699. list($progress) = $this->get_progress_bar_text('%');
  4700. if ($progress >= 0 && $progress <= 100) {
  4701. $progress = (int) $progress;
  4702. $sql = "UPDATE $table SET
  4703. progress = $progress
  4704. WHERE
  4705. c_id = $course_id AND
  4706. lp_id = ".$this->get_id()." AND
  4707. user_id = ".$this->get_user_id()." ".$session_condition;
  4708. // Ignore errors as some tables might not have the progress field just yet.
  4709. Database::query($sql);
  4710. if ($debug) {
  4711. error_log($sql);
  4712. }
  4713. $this->progress_db = $progress;
  4714. }
  4715. }
  4716. }
  4717. /**
  4718. * Sets the current item ID (checks if valid and authorized first).
  4719. *
  4720. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4721. */
  4722. public function set_current_item($item_id = null)
  4723. {
  4724. $debug = $this->debug;
  4725. if ($debug) {
  4726. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4727. }
  4728. if (empty($item_id)) {
  4729. if ($debug) {
  4730. error_log('No new current item given, ignore...', 0);
  4731. }
  4732. // Do nothing.
  4733. } else {
  4734. if ($debug) {
  4735. error_log('New current item given is '.$item_id.'...', 0);
  4736. }
  4737. if (is_numeric($item_id)) {
  4738. $item_id = (int) $item_id;
  4739. // TODO: Check in database here.
  4740. $this->last = $this->current;
  4741. $this->current = $item_id;
  4742. // TODO: Update $this->index as well.
  4743. foreach ($this->ordered_items as $index => $item) {
  4744. if ($item == $this->current) {
  4745. $this->index = $index;
  4746. break;
  4747. }
  4748. }
  4749. if ($debug) {
  4750. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4751. }
  4752. } else {
  4753. if ($debug) {
  4754. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4755. }
  4756. }
  4757. }
  4758. }
  4759. /**
  4760. * Sets the encoding.
  4761. *
  4762. * @param string $enc New encoding
  4763. *
  4764. * @return bool
  4765. *
  4766. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4767. */
  4768. public function set_encoding($enc = 'UTF-8')
  4769. {
  4770. if ($this->debug > 0) {
  4771. error_log('In learnpath::set_encoding()', 0);
  4772. }
  4773. $enc = api_refine_encoding_id($enc);
  4774. if (empty($enc)) {
  4775. $enc = api_get_system_encoding();
  4776. }
  4777. if (api_is_encoding_supported($enc)) {
  4778. $lp = $this->get_id();
  4779. if ($lp != 0) {
  4780. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4781. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4782. WHERE iid = ".$lp;
  4783. $res = Database::query($sql);
  4784. return $res;
  4785. }
  4786. }
  4787. return false;
  4788. }
  4789. /**
  4790. * Sets the JS lib setting in the database directly.
  4791. * This is the JavaScript library file this lp needs to load on startup.
  4792. *
  4793. * @param string $lib Proximity setting
  4794. *
  4795. * @return bool True on update success. False otherwise.
  4796. */
  4797. public function set_jslib($lib = '')
  4798. {
  4799. if ($this->debug > 0) {
  4800. error_log('In learnpath::set_jslib()', 0);
  4801. }
  4802. $lp = $this->get_id();
  4803. if ($lp != 0) {
  4804. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4805. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4806. WHERE iid = $lp";
  4807. $res = Database::query($sql);
  4808. return $res;
  4809. } else {
  4810. return false;
  4811. }
  4812. }
  4813. /**
  4814. * Sets the name of the LP maker (publisher) (and save).
  4815. *
  4816. * @param string $name Optional string giving the new content_maker of this learnpath
  4817. *
  4818. * @return bool True
  4819. */
  4820. public function set_maker($name = '')
  4821. {
  4822. if ($this->debug > 0) {
  4823. error_log('In learnpath::set_maker()', 0);
  4824. }
  4825. if (empty($name)) {
  4826. return false;
  4827. }
  4828. $this->maker = $name;
  4829. $table = Database::get_course_table(TABLE_LP_MAIN);
  4830. $lp_id = $this->get_id();
  4831. $sql = "UPDATE $table SET
  4832. content_maker = '".Database::escape_string($this->maker)."'
  4833. WHERE iid = $lp_id";
  4834. if ($this->debug > 2) {
  4835. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4836. }
  4837. Database::query($sql);
  4838. return true;
  4839. }
  4840. /**
  4841. * Sets the name of the current learnpath (and save).
  4842. *
  4843. * @param string $name Optional string giving the new name of this learnpath
  4844. *
  4845. * @return bool True/False
  4846. */
  4847. public function set_name($name = null)
  4848. {
  4849. if ($this->debug > 0) {
  4850. error_log('In learnpath::set_name()', 0);
  4851. }
  4852. if (empty($name)) {
  4853. return false;
  4854. }
  4855. $this->name = Database::escape_string($name);
  4856. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4857. $lp_id = $this->get_id();
  4858. $course_id = $this->course_info['real_id'];
  4859. $sql = "UPDATE $lp_table SET
  4860. name = '".Database::escape_string($this->name)."'
  4861. WHERE iid = $lp_id";
  4862. if ($this->debug > 2) {
  4863. error_log('lp updated with new name : '.$this->name, 0);
  4864. }
  4865. $result = Database::query($sql);
  4866. // If the lp is visible on the homepage, change his name there.
  4867. if (Database::affected_rows($result)) {
  4868. $session_id = api_get_session_id();
  4869. $session_condition = api_get_session_condition($session_id);
  4870. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4871. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4872. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4873. WHERE
  4874. c_id = $course_id AND
  4875. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4876. Database::query($sql);
  4877. return true;
  4878. } else {
  4879. return false;
  4880. }
  4881. }
  4882. /**
  4883. * Set index specified prefix terms for all items in this path.
  4884. *
  4885. * @param string $terms_string Comma-separated list of terms
  4886. * @param string $prefix Xapian term prefix
  4887. *
  4888. * @return bool False on error, true otherwise
  4889. */
  4890. public function set_terms_by_prefix($terms_string, $prefix)
  4891. {
  4892. $course_id = api_get_course_int_id();
  4893. if (api_get_setting('search_enabled') !== 'true') {
  4894. return false;
  4895. }
  4896. if (!extension_loaded('xapian')) {
  4897. return false;
  4898. }
  4899. $terms_string = trim($terms_string);
  4900. $terms = explode(',', $terms_string);
  4901. array_walk($terms, 'trim_value');
  4902. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4903. // Don't do anything if no change, verify only at DB, not the search engine.
  4904. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4905. return false;
  4906. }
  4907. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4908. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4909. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4910. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4911. $lp_id = (int) $_POST['lp_id'];
  4912. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4913. $result = Database::query($sql);
  4914. $di = new ChamiloIndexer();
  4915. while ($lp_item = Database::fetch_array($result)) {
  4916. // Get search_did.
  4917. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4918. $sql = 'SELECT * FROM %s
  4919. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4920. LIMIT 1';
  4921. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4922. //echo $sql; echo '<br>';
  4923. $res = Database::query($sql);
  4924. if (Database::num_rows($res) > 0) {
  4925. $se_ref = Database::fetch_array($res);
  4926. // Compare terms.
  4927. $doc = $di->get_document($se_ref['search_did']);
  4928. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4929. $xterms = [];
  4930. foreach ($xapian_terms as $xapian_term) {
  4931. $xterms[] = substr($xapian_term['name'], 1);
  4932. }
  4933. $dterms = $terms;
  4934. $missing_terms = array_diff($dterms, $xterms);
  4935. $deprecated_terms = array_diff($xterms, $dterms);
  4936. // Save it to search engine.
  4937. foreach ($missing_terms as $term) {
  4938. $doc->add_term($prefix.$term, 1);
  4939. }
  4940. foreach ($deprecated_terms as $term) {
  4941. $doc->remove_term($prefix.$term);
  4942. }
  4943. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4944. $di->getDb()->flush();
  4945. }
  4946. }
  4947. return true;
  4948. }
  4949. /**
  4950. * Sets the theme of the LP (local/remote) (and save).
  4951. *
  4952. * @param string $name Optional string giving the new theme of this learnpath
  4953. *
  4954. * @return bool Returns true if theme name is not empty
  4955. */
  4956. public function set_theme($name = '')
  4957. {
  4958. if ($this->debug > 0) {
  4959. error_log('In learnpath::set_theme()', 0);
  4960. }
  4961. $this->theme = $name;
  4962. $table = Database::get_course_table(TABLE_LP_MAIN);
  4963. $lp_id = $this->get_id();
  4964. $sql = "UPDATE $table
  4965. SET theme = '".Database::escape_string($this->theme)."'
  4966. WHERE iid = $lp_id";
  4967. if ($this->debug > 2) {
  4968. error_log('lp updated with new theme : '.$this->theme, 0);
  4969. }
  4970. Database::query($sql);
  4971. return true;
  4972. }
  4973. /**
  4974. * Sets the image of an LP (and save).
  4975. *
  4976. * @param string $name Optional string giving the new image of this learnpath
  4977. *
  4978. * @return bool Returns true if theme name is not empty
  4979. */
  4980. public function set_preview_image($name = '')
  4981. {
  4982. if ($this->debug > 0) {
  4983. error_log('In learnpath::set_preview_image()', 0);
  4984. }
  4985. $this->preview_image = $name;
  4986. $table = Database::get_course_table(TABLE_LP_MAIN);
  4987. $lp_id = $this->get_id();
  4988. $sql = "UPDATE $table SET
  4989. preview_image = '".Database::escape_string($this->preview_image)."'
  4990. WHERE iid = $lp_id";
  4991. if ($this->debug > 2) {
  4992. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4993. }
  4994. Database::query($sql);
  4995. return true;
  4996. }
  4997. /**
  4998. * Sets the author of a LP (and save).
  4999. *
  5000. * @param string $name Optional string giving the new author of this learnpath
  5001. *
  5002. * @return bool Returns true if author's name is not empty
  5003. */
  5004. public function set_author($name = '')
  5005. {
  5006. if ($this->debug > 0) {
  5007. error_log('In learnpath::set_author()', 0);
  5008. }
  5009. $this->author = $name;
  5010. $table = Database::get_course_table(TABLE_LP_MAIN);
  5011. $lp_id = $this->get_id();
  5012. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  5013. WHERE iid = $lp_id";
  5014. if ($this->debug > 2) {
  5015. error_log('lp updated with new preview author : '.$this->author, 0);
  5016. }
  5017. Database::query($sql);
  5018. return true;
  5019. }
  5020. /**
  5021. * Sets the hide_toc_frame parameter of a LP (and save).
  5022. *
  5023. * @param int $hide 1 if frame is hidden 0 then else
  5024. *
  5025. * @return bool Returns true if author's name is not empty
  5026. */
  5027. public function set_hide_toc_frame($hide)
  5028. {
  5029. if ($this->debug > 0) {
  5030. error_log('In learnpath::set_hide_toc_frame()', 0);
  5031. }
  5032. if (intval($hide) == $hide) {
  5033. $this->hide_toc_frame = $hide;
  5034. $table = Database::get_course_table(TABLE_LP_MAIN);
  5035. $lp_id = $this->get_id();
  5036. $sql = "UPDATE $table SET
  5037. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  5038. WHERE iid = $lp_id";
  5039. if ($this->debug > 2) {
  5040. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  5041. }
  5042. Database::query($sql);
  5043. return true;
  5044. } else {
  5045. return false;
  5046. }
  5047. }
  5048. /**
  5049. * Sets the prerequisite of a LP (and save).
  5050. *
  5051. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  5052. *
  5053. * @return bool returns true if prerequisite is not empty
  5054. */
  5055. public function set_prerequisite($prerequisite)
  5056. {
  5057. if ($this->debug > 0) {
  5058. error_log('In learnpath::set_prerequisite()', 0);
  5059. }
  5060. $this->prerequisite = (int) $prerequisite;
  5061. $table = Database::get_course_table(TABLE_LP_MAIN);
  5062. $lp_id = $this->get_id();
  5063. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  5064. WHERE iid = $lp_id";
  5065. if ($this->debug > 2) {
  5066. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  5067. }
  5068. Database::query($sql);
  5069. return true;
  5070. }
  5071. /**
  5072. * Sets the location/proximity of the LP (local/remote) (and save).
  5073. *
  5074. * @param string $name Optional string giving the new location of this learnpath
  5075. *
  5076. * @return bool True on success / False on error
  5077. */
  5078. public function set_proximity($name = '')
  5079. {
  5080. if ($this->debug > 0) {
  5081. error_log('In learnpath::set_proximity()', 0);
  5082. }
  5083. if (empty($name)) {
  5084. return false;
  5085. }
  5086. $this->proximity = $name;
  5087. $table = Database::get_course_table(TABLE_LP_MAIN);
  5088. $lp_id = $this->get_id();
  5089. $sql = "UPDATE $table SET
  5090. content_local = '".Database::escape_string($name)."'
  5091. WHERE iid = $lp_id";
  5092. if ($this->debug > 2) {
  5093. error_log('lp updated with new proximity : '.$this->proximity, 0);
  5094. }
  5095. Database::query($sql);
  5096. return true;
  5097. }
  5098. /**
  5099. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  5100. *
  5101. * @param int $id DB ID of the item
  5102. */
  5103. public function set_previous_item($id)
  5104. {
  5105. if ($this->debug > 0) {
  5106. error_log('In learnpath::set_previous_item()', 0);
  5107. }
  5108. $this->last = $id;
  5109. }
  5110. /**
  5111. * Sets use_max_score.
  5112. *
  5113. * @param int $use_max_score Optional string giving the new location of this learnpath
  5114. *
  5115. * @return bool True on success / False on error
  5116. */
  5117. public function set_use_max_score($use_max_score = 1)
  5118. {
  5119. if ($this->debug > 0) {
  5120. error_log('In learnpath::set_use_max_score()', 0);
  5121. }
  5122. $use_max_score = (int) $use_max_score;
  5123. $this->use_max_score = $use_max_score;
  5124. $table = Database::get_course_table(TABLE_LP_MAIN);
  5125. $lp_id = $this->get_id();
  5126. $sql = "UPDATE $table SET
  5127. use_max_score = '".$this->use_max_score."'
  5128. WHERE iid = $lp_id";
  5129. if ($this->debug > 2) {
  5130. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  5131. }
  5132. Database::query($sql);
  5133. return true;
  5134. }
  5135. /**
  5136. * Sets and saves the expired_on date.
  5137. *
  5138. * @param string $expired_on Optional string giving the new author of this learnpath
  5139. *
  5140. * @throws \Doctrine\ORM\OptimisticLockException
  5141. *
  5142. * @return bool Returns true if author's name is not empty
  5143. */
  5144. public function set_expired_on($expired_on)
  5145. {
  5146. if ($this->debug > 0) {
  5147. error_log('In learnpath::set_expired_on()', 0);
  5148. }
  5149. $em = Database::getManager();
  5150. /** @var CLp $lp */
  5151. $lp = $em
  5152. ->getRepository('ChamiloCourseBundle:CLp')
  5153. ->findOneBy(
  5154. [
  5155. 'iid' => $this->get_id(),
  5156. ]
  5157. );
  5158. if (!$lp) {
  5159. return false;
  5160. }
  5161. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5162. $lp->setExpiredOn($this->expired_on);
  5163. $em->persist($lp);
  5164. $em->flush();
  5165. if ($this->debug > 2) {
  5166. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  5167. }
  5168. return true;
  5169. }
  5170. /**
  5171. * Sets and saves the publicated_on date.
  5172. *
  5173. * @param string $publicated_on Optional string giving the new author of this learnpath
  5174. *
  5175. * @throws \Doctrine\ORM\OptimisticLockException
  5176. *
  5177. * @return bool Returns true if author's name is not empty
  5178. */
  5179. public function set_publicated_on($publicated_on)
  5180. {
  5181. if ($this->debug > 0) {
  5182. error_log('In learnpath::set_expired_on()', 0);
  5183. }
  5184. $em = Database::getManager();
  5185. /** @var CLp $lp */
  5186. $lp = $em
  5187. ->getRepository('ChamiloCourseBundle:CLp')
  5188. ->findOneBy(
  5189. [
  5190. 'iid' => $this->get_id(),
  5191. ]
  5192. );
  5193. if (!$lp) {
  5194. return false;
  5195. }
  5196. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5197. $lp->setPublicatedOn($this->publicated_on);
  5198. $em->persist($lp);
  5199. $em->flush();
  5200. if ($this->debug > 2) {
  5201. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5202. }
  5203. return true;
  5204. }
  5205. /**
  5206. * Sets and saves the expired_on date.
  5207. *
  5208. * @return bool Returns true if author's name is not empty
  5209. */
  5210. public function set_modified_on()
  5211. {
  5212. if ($this->debug > 0) {
  5213. error_log('In learnpath::set_expired_on()', 0);
  5214. }
  5215. $this->modified_on = api_get_utc_datetime();
  5216. $table = Database::get_course_table(TABLE_LP_MAIN);
  5217. $lp_id = $this->get_id();
  5218. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5219. WHERE iid = $lp_id";
  5220. if ($this->debug > 2) {
  5221. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5222. }
  5223. Database::query($sql);
  5224. return true;
  5225. }
  5226. /**
  5227. * Sets the object's error message.
  5228. *
  5229. * @param string $error Error message. If empty, reinits the error string
  5230. */
  5231. public function set_error_msg($error = '')
  5232. {
  5233. if ($this->debug > 0) {
  5234. error_log('In learnpath::set_error_msg()', 0);
  5235. }
  5236. if (empty($error)) {
  5237. $this->error = '';
  5238. } else {
  5239. $this->error .= $error;
  5240. }
  5241. }
  5242. /**
  5243. * Launches the current item if not 'sco'
  5244. * (starts timer and make sure there is a record ready in the DB).
  5245. *
  5246. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5247. *
  5248. * @return bool
  5249. */
  5250. public function start_current_item($allow_new_attempt = false)
  5251. {
  5252. $debug = $this->debug;
  5253. if ($debug) {
  5254. error_log('In learnpath::start_current_item()');
  5255. error_log('current: '.$this->current);
  5256. }
  5257. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5258. $type = $this->get_type();
  5259. $item_type = $this->items[$this->current]->get_type();
  5260. if (($type == 2 && $item_type != 'sco') ||
  5261. ($type == 3 && $item_type != 'au') ||
  5262. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5263. ) {
  5264. if ($debug) {
  5265. error_log('item type: '.$item_type);
  5266. error_log('lp type: '.$type);
  5267. }
  5268. $this->items[$this->current]->open($allow_new_attempt);
  5269. $this->autocomplete_parents($this->current);
  5270. $prereq_check = $this->prerequisites_match($this->current);
  5271. if ($debug) {
  5272. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5273. }
  5274. $this->items[$this->current]->save(false, $prereq_check);
  5275. }
  5276. // If sco, then it is supposed to have been updated by some other call.
  5277. if ($item_type == 'sco') {
  5278. $this->items[$this->current]->restart();
  5279. }
  5280. }
  5281. if ($debug) {
  5282. error_log('lp_view_session_id');
  5283. error_log($this->lp_view_session_id);
  5284. error_log('api session id');
  5285. error_log(api_get_session_id());
  5286. error_log('End of learnpath::start_current_item()');
  5287. }
  5288. return true;
  5289. }
  5290. /**
  5291. * Stops the processing and counters for the old item (as held in $this->last).
  5292. *
  5293. * @return bool True/False
  5294. */
  5295. public function stop_previous_item()
  5296. {
  5297. $debug = $this->debug;
  5298. if ($debug) {
  5299. error_log('In learnpath::stop_previous_item()', 0);
  5300. }
  5301. if ($this->last != 0 && $this->last != $this->current &&
  5302. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5303. ) {
  5304. if ($debug) {
  5305. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5306. }
  5307. switch ($this->get_type()) {
  5308. case '3':
  5309. if ($this->items[$this->last]->get_type() != 'au') {
  5310. if ($debug) {
  5311. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5312. }
  5313. $this->items[$this->last]->close();
  5314. } else {
  5315. if ($debug) {
  5316. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5317. }
  5318. }
  5319. break;
  5320. case '2':
  5321. if ($this->items[$this->last]->get_type() != 'sco') {
  5322. if ($debug) {
  5323. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5324. }
  5325. $this->items[$this->last]->close();
  5326. } else {
  5327. if ($debug) {
  5328. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5329. }
  5330. }
  5331. break;
  5332. case '1':
  5333. default:
  5334. if ($debug) {
  5335. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5336. }
  5337. $this->items[$this->last]->close();
  5338. break;
  5339. }
  5340. } else {
  5341. if ($debug) {
  5342. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5343. }
  5344. return false;
  5345. }
  5346. return true;
  5347. }
  5348. /**
  5349. * Updates the default view mode from fullscreen to embedded and inversely.
  5350. *
  5351. * @return string The current default view mode ('fullscreen' or 'embedded')
  5352. */
  5353. public function update_default_view_mode()
  5354. {
  5355. if ($this->debug > 0) {
  5356. error_log('In learnpath::update_default_view_mode()', 0);
  5357. }
  5358. $table = Database::get_course_table(TABLE_LP_MAIN);
  5359. $sql = "SELECT * FROM $table
  5360. WHERE iid = ".$this->get_id();
  5361. $res = Database::query($sql);
  5362. if (Database::num_rows($res) > 0) {
  5363. $row = Database::fetch_array($res);
  5364. $default_view_mode = $row['default_view_mod'];
  5365. $view_mode = $default_view_mode;
  5366. switch ($default_view_mode) {
  5367. case 'fullscreen': // default with popup
  5368. $view_mode = 'embedded';
  5369. break;
  5370. case 'embedded': // default view with left menu
  5371. $view_mode = 'embedframe';
  5372. break;
  5373. case 'embedframe': //folded menu
  5374. $view_mode = 'impress';
  5375. break;
  5376. case 'impress':
  5377. $view_mode = 'fullscreen';
  5378. break;
  5379. }
  5380. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5381. WHERE iid = ".$this->get_id();
  5382. Database::query($sql);
  5383. $this->mode = $view_mode;
  5384. return $view_mode;
  5385. } else {
  5386. if ($this->debug > 2) {
  5387. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5388. }
  5389. }
  5390. return -1;
  5391. }
  5392. /**
  5393. * Updates the default behaviour about auto-commiting SCORM updates.
  5394. *
  5395. * @return bool True if auto-commit has been set to 'on', false otherwise
  5396. */
  5397. public function update_default_scorm_commit()
  5398. {
  5399. if ($this->debug > 0) {
  5400. error_log('In learnpath::update_default_scorm_commit()', 0);
  5401. }
  5402. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5403. $sql = "SELECT * FROM $lp_table
  5404. WHERE iid = ".$this->get_id();
  5405. $res = Database::query($sql);
  5406. if (Database::num_rows($res) > 0) {
  5407. $row = Database::fetch_array($res);
  5408. $force = $row['force_commit'];
  5409. if ($force == 1) {
  5410. $force = 0;
  5411. $force_return = false;
  5412. } elseif ($force == 0) {
  5413. $force = 1;
  5414. $force_return = true;
  5415. }
  5416. $sql = "UPDATE $lp_table SET force_commit = $force
  5417. WHERE iid = ".$this->get_id();
  5418. Database::query($sql);
  5419. $this->force_commit = $force_return;
  5420. return $force_return;
  5421. } else {
  5422. if ($this->debug > 2) {
  5423. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5424. }
  5425. }
  5426. return -1;
  5427. }
  5428. /**
  5429. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5430. *
  5431. * @return bool True on success, false on failure
  5432. */
  5433. public function update_display_order()
  5434. {
  5435. $course_id = api_get_course_int_id();
  5436. $table = Database::get_course_table(TABLE_LP_MAIN);
  5437. $sql = "SELECT * FROM $table
  5438. WHERE c_id = $course_id
  5439. ORDER BY display_order";
  5440. $res = Database::query($sql);
  5441. if ($res === false) {
  5442. return false;
  5443. }
  5444. $num = Database::num_rows($res);
  5445. // First check the order is correct, globally (might be wrong because
  5446. // of versions < 1.8.4).
  5447. if ($num > 0) {
  5448. $i = 1;
  5449. while ($row = Database::fetch_array($res)) {
  5450. if ($row['display_order'] != $i) {
  5451. // If we find a gap in the order, we need to fix it.
  5452. $sql = "UPDATE $table SET display_order = $i
  5453. WHERE iid = ".$row['iid'];
  5454. Database::query($sql);
  5455. }
  5456. $i++;
  5457. }
  5458. }
  5459. return true;
  5460. }
  5461. /**
  5462. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5463. *
  5464. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5465. */
  5466. public function update_reinit()
  5467. {
  5468. if ($this->debug > 0) {
  5469. error_log('In learnpath::update_reinit()', 0);
  5470. }
  5471. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5472. $sql = "SELECT * FROM $lp_table
  5473. WHERE iid = ".$this->get_id();
  5474. $res = Database::query($sql);
  5475. if (Database::num_rows($res) > 0) {
  5476. $row = Database::fetch_array($res);
  5477. $force = $row['prevent_reinit'];
  5478. if ($force == 1) {
  5479. $force = 0;
  5480. } elseif ($force == 0) {
  5481. $force = 1;
  5482. }
  5483. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5484. WHERE iid = ".$this->get_id();
  5485. Database::query($sql);
  5486. $this->prevent_reinit = $force;
  5487. return $force;
  5488. } else {
  5489. if ($this->debug > 2) {
  5490. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5491. }
  5492. }
  5493. return -1;
  5494. }
  5495. /**
  5496. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5497. *
  5498. * @return string 'single', 'multi' or 'seriousgame'
  5499. *
  5500. * @author ndiechburg <noel@cblue.be>
  5501. */
  5502. public function get_attempt_mode()
  5503. {
  5504. //Set default value for seriousgame_mode
  5505. if (!isset($this->seriousgame_mode)) {
  5506. $this->seriousgame_mode = 0;
  5507. }
  5508. // Set default value for prevent_reinit
  5509. if (!isset($this->prevent_reinit)) {
  5510. $this->prevent_reinit = 1;
  5511. }
  5512. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5513. return 'seriousgame';
  5514. }
  5515. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5516. return 'single';
  5517. }
  5518. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5519. return 'multiple';
  5520. }
  5521. return 'single';
  5522. }
  5523. /**
  5524. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5525. *
  5526. * @param string 'seriousgame', 'single' or 'multiple'
  5527. *
  5528. * @return bool
  5529. *
  5530. * @author ndiechburg <noel@cblue.be>
  5531. */
  5532. public function set_attempt_mode($mode)
  5533. {
  5534. switch ($mode) {
  5535. case 'seriousgame':
  5536. $sg_mode = 1;
  5537. $prevent_reinit = 1;
  5538. break;
  5539. case 'single':
  5540. $sg_mode = 0;
  5541. $prevent_reinit = 1;
  5542. break;
  5543. case 'multiple':
  5544. $sg_mode = 0;
  5545. $prevent_reinit = 0;
  5546. break;
  5547. default:
  5548. $sg_mode = 0;
  5549. $prevent_reinit = 0;
  5550. break;
  5551. }
  5552. $this->prevent_reinit = $prevent_reinit;
  5553. $this->seriousgame_mode = $sg_mode;
  5554. $table = Database::get_course_table(TABLE_LP_MAIN);
  5555. $sql = "UPDATE $table SET
  5556. prevent_reinit = $prevent_reinit ,
  5557. seriousgame_mode = $sg_mode
  5558. WHERE iid = ".$this->get_id();
  5559. $res = Database::query($sql);
  5560. if ($res) {
  5561. return true;
  5562. } else {
  5563. return false;
  5564. }
  5565. }
  5566. /**
  5567. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5568. *
  5569. * @author ndiechburg <noel@cblue.be>
  5570. */
  5571. public function switch_attempt_mode()
  5572. {
  5573. if ($this->debug > 0) {
  5574. error_log('In learnpath::switch_attempt_mode()', 0);
  5575. }
  5576. $mode = $this->get_attempt_mode();
  5577. switch ($mode) {
  5578. case 'single':
  5579. $next_mode = 'multiple';
  5580. break;
  5581. case 'multiple':
  5582. $next_mode = 'seriousgame';
  5583. break;
  5584. case 'seriousgame':
  5585. $next_mode = 'single';
  5586. break;
  5587. default:
  5588. $next_mode = 'single';
  5589. break;
  5590. }
  5591. $this->set_attempt_mode($next_mode);
  5592. }
  5593. /**
  5594. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5595. * but possibility to do again a completed item.
  5596. *
  5597. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5598. *
  5599. * @author ndiechburg <noel@cblue.be>
  5600. */
  5601. public function set_seriousgame_mode()
  5602. {
  5603. if ($this->debug > 0) {
  5604. error_log('In learnpath::set_seriousgame_mode()', 0);
  5605. }
  5606. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5607. $sql = "SELECT * FROM $lp_table
  5608. WHERE iid = ".$this->get_id();
  5609. $res = Database::query($sql);
  5610. if (Database::num_rows($res) > 0) {
  5611. $row = Database::fetch_array($res);
  5612. $force = $row['seriousgame_mode'];
  5613. if ($force == 1) {
  5614. $force = 0;
  5615. } elseif ($force == 0) {
  5616. $force = 1;
  5617. }
  5618. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5619. WHERE iid = ".$this->get_id();
  5620. Database::query($sql);
  5621. $this->seriousgame_mode = $force;
  5622. return $force;
  5623. } else {
  5624. if ($this->debug > 2) {
  5625. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5626. }
  5627. }
  5628. return -1;
  5629. }
  5630. /**
  5631. * Updates the "scorm_debug" value that shows or hide the debug window.
  5632. *
  5633. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5634. */
  5635. public function update_scorm_debug()
  5636. {
  5637. if ($this->debug > 0) {
  5638. error_log('In learnpath::update_scorm_debug()', 0);
  5639. }
  5640. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5641. $sql = "SELECT * FROM $lp_table
  5642. WHERE iid = ".$this->get_id();
  5643. $res = Database::query($sql);
  5644. if (Database::num_rows($res) > 0) {
  5645. $row = Database::fetch_array($res);
  5646. $force = $row['debug'];
  5647. if ($force == 1) {
  5648. $force = 0;
  5649. } elseif ($force == 0) {
  5650. $force = 1;
  5651. }
  5652. $sql = "UPDATE $lp_table SET debug = $force
  5653. WHERE iid = ".$this->get_id();
  5654. Database::query($sql);
  5655. $this->scorm_debug = $force;
  5656. return $force;
  5657. } else {
  5658. if ($this->debug > 2) {
  5659. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5660. }
  5661. }
  5662. return -1;
  5663. }
  5664. /**
  5665. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5666. *
  5667. * @author Kevin Van Den Haute
  5668. *
  5669. * @param array
  5670. */
  5671. public function tree_array($array)
  5672. {
  5673. if ($this->debug > 1) {
  5674. error_log('In learnpath::tree_array()', 0);
  5675. }
  5676. $array = $this->sort_tree_array($array);
  5677. $this->create_tree_array($array);
  5678. }
  5679. /**
  5680. * Creates an array with the elements of the learning path tree in it.
  5681. *
  5682. * @author Kevin Van Den Haute
  5683. *
  5684. * @param array $array
  5685. * @param int $parent
  5686. * @param int $depth
  5687. * @param array $tmp
  5688. */
  5689. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5690. {
  5691. if ($this->debug > 1) {
  5692. error_log('In learnpath::create_tree_array())', 0);
  5693. }
  5694. if (is_array($array)) {
  5695. for ($i = 0; $i < count($array); $i++) {
  5696. if ($array[$i]['parent_item_id'] == $parent) {
  5697. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5698. $tmp[] = $array[$i]['parent_item_id'];
  5699. $depth++;
  5700. }
  5701. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5702. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5703. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5704. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5705. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5706. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5707. $this->arrMenu[] = [
  5708. 'id' => $array[$i]['id'],
  5709. 'ref' => $ref,
  5710. 'item_type' => $array[$i]['item_type'],
  5711. 'title' => $array[$i]['title'],
  5712. 'path' => $path,
  5713. 'description' => $array[$i]['description'],
  5714. 'parent_item_id' => $array[$i]['parent_item_id'],
  5715. 'previous_item_id' => $array[$i]['previous_item_id'],
  5716. 'next_item_id' => $array[$i]['next_item_id'],
  5717. 'min_score' => $array[$i]['min_score'],
  5718. 'max_score' => $array[$i]['max_score'],
  5719. 'mastery_score' => $array[$i]['mastery_score'],
  5720. 'display_order' => $array[$i]['display_order'],
  5721. 'prerequisite' => $preq,
  5722. 'depth' => $depth,
  5723. 'audio' => $audio,
  5724. 'prerequisite_min_score' => $prerequisiteMinScore,
  5725. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5726. ];
  5727. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5728. }
  5729. }
  5730. }
  5731. }
  5732. /**
  5733. * Sorts a multi dimensional array by parent id and display order.
  5734. *
  5735. * @author Kevin Van Den Haute
  5736. *
  5737. * @param array $array (array with al the learning path items in it)
  5738. *
  5739. * @return array
  5740. */
  5741. public function sort_tree_array($array)
  5742. {
  5743. foreach ($array as $key => $row) {
  5744. $parent[$key] = $row['parent_item_id'];
  5745. $position[$key] = $row['display_order'];
  5746. }
  5747. if (count($array) > 0) {
  5748. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5749. }
  5750. return $array;
  5751. }
  5752. /**
  5753. * Function that creates a html list of learning path items so that we can add audio files to them.
  5754. *
  5755. * @author Kevin Van Den Haute
  5756. *
  5757. * @return string
  5758. */
  5759. public function overview()
  5760. {
  5761. if ($this->debug > 0) {
  5762. error_log('In learnpath::overview()', 0);
  5763. }
  5764. $return = '';
  5765. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5766. // we need to start a form when we want to update all the mp3 files
  5767. if ($update_audio == 'true') {
  5768. $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">';
  5769. }
  5770. $return .= '<div id="message"></div>';
  5771. if (count($this->items) == 0) {
  5772. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5773. } else {
  5774. $return_audio = '<table class="data_table">';
  5775. $return_audio .= '<tr>';
  5776. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5777. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5778. $return_audio .= '</tr>';
  5779. if ($update_audio != 'true') {
  5780. $return .= '<div class="col-md-12">';
  5781. $return .= self::return_new_tree($update_audio);
  5782. $return .= '</div>';
  5783. $return .= Display::div(
  5784. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5785. ['style' => 'float:left; margin-top:15px;width:100%']
  5786. );
  5787. } else {
  5788. $return_audio .= self::return_new_tree($update_audio);
  5789. $return .= $return_audio.'</table>';
  5790. }
  5791. // We need to close the form when we are updating the mp3 files.
  5792. if ($update_audio == 'true') {
  5793. $return .= '<div class="footer-audio">';
  5794. $return .= Display::button(
  5795. 'save_audio',
  5796. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5797. ['class' => 'btn btn-primary', 'type' => 'submit']
  5798. );
  5799. $return .= '</div>';
  5800. }
  5801. }
  5802. // We need to close the form when we are updating the mp3 files.
  5803. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5804. $return .= '</form>';
  5805. }
  5806. return $return;
  5807. }
  5808. /**
  5809. * @param string $update_audio
  5810. *
  5811. * @return array
  5812. */
  5813. public function processBuildMenuElements($update_audio = 'false')
  5814. {
  5815. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5816. $course_id = api_get_course_int_id();
  5817. $table = Database::get_course_table(TABLE_LP_ITEM);
  5818. $sql = "SELECT * FROM $table
  5819. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5820. $result = Database::query($sql);
  5821. $arrLP = [];
  5822. while ($row = Database::fetch_array($result)) {
  5823. $arrLP[] = [
  5824. 'id' => $row['iid'],
  5825. 'item_type' => $row['item_type'],
  5826. 'title' => Security::remove_XSS($row['title']),
  5827. 'path' => $row['path'],
  5828. 'description' => Security::remove_XSS($row['description']),
  5829. 'parent_item_id' => $row['parent_item_id'],
  5830. 'previous_item_id' => $row['previous_item_id'],
  5831. 'next_item_id' => $row['next_item_id'],
  5832. 'max_score' => $row['max_score'],
  5833. 'min_score' => $row['min_score'],
  5834. 'mastery_score' => $row['mastery_score'],
  5835. 'prerequisite' => $row['prerequisite'],
  5836. 'display_order' => $row['display_order'],
  5837. 'audio' => $row['audio'],
  5838. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5839. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5840. ];
  5841. }
  5842. $this->tree_array($arrLP);
  5843. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5844. unset($this->arrMenu);
  5845. $default_data = null;
  5846. $default_content = null;
  5847. $elements = [];
  5848. $return_audio = null;
  5849. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5850. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5851. for ($i = 0; $i < count($arrLP); $i++) {
  5852. $title = $arrLP[$i]['title'];
  5853. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5854. // Link for the documents
  5855. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5856. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5857. $title_cut = Display::url(
  5858. $title_cut,
  5859. $url,
  5860. [
  5861. 'class' => 'ajax moved',
  5862. 'data-title' => $title,
  5863. 'title' => $title,
  5864. ]
  5865. );
  5866. }
  5867. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5868. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5869. Session::write('pathItem', $arrLP[$i]['path']);
  5870. }
  5871. if (($i % 2) == 0) {
  5872. $oddClass = 'row_odd';
  5873. } else {
  5874. $oddClass = 'row_even';
  5875. }
  5876. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5877. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5878. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5879. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5880. } else {
  5881. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5882. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5883. } else {
  5884. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5885. $icon = Display::return_icon('certificate.png');
  5886. } else {
  5887. $icon = Display::return_icon('folder_document.gif');
  5888. }
  5889. }
  5890. }
  5891. // The audio column.
  5892. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5893. $audio = '';
  5894. if (!$update_audio || $update_audio != 'true') {
  5895. if (empty($arrLP[$i]['audio'])) {
  5896. $audio .= '';
  5897. }
  5898. } else {
  5899. $types = self::getChapterTypes();
  5900. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5901. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5902. if (!empty($arrLP[$i]['audio'])) {
  5903. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5904. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5905. }
  5906. }
  5907. }
  5908. $return_audio .= Display::span($icon.' '.$title).
  5909. Display::tag(
  5910. 'td',
  5911. $audio,
  5912. ['style' => '']
  5913. );
  5914. $return_audio .= '</td>';
  5915. $move_icon = '';
  5916. $move_item_icon = '';
  5917. $edit_icon = '';
  5918. $delete_icon = '';
  5919. $audio_icon = '';
  5920. $prerequisities_icon = '';
  5921. $forumIcon = '';
  5922. $previewIcon = '';
  5923. $pluginCalendarIcon = '';
  5924. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5925. $plugin = null;
  5926. if ($pluginCalendar) {
  5927. $plugin = LearningCalendarPlugin::create();
  5928. }
  5929. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5930. if ($is_allowed_to_edit) {
  5931. if (!$update_audio || $update_audio != 'true') {
  5932. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5933. $move_icon .= '<a class="moved" href="#">';
  5934. $move_icon .= Display::return_icon(
  5935. 'move_everywhere.png',
  5936. get_lang('Move'),
  5937. [],
  5938. ICON_SIZE_TINY
  5939. );
  5940. $move_icon .= '</a>';
  5941. }
  5942. }
  5943. // No edit for this item types
  5944. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5945. if ($arrLP[$i]['item_type'] != 'dir') {
  5946. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5947. $edit_icon .= Display::return_icon(
  5948. 'edit.png',
  5949. get_lang('LearnpathEditModule'),
  5950. [],
  5951. ICON_SIZE_TINY
  5952. );
  5953. $edit_icon .= '</a>';
  5954. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5955. $forumThread = null;
  5956. if (isset($this->items[$arrLP[$i]['id']])) {
  5957. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5958. $this->course_int_id,
  5959. $this->lp_session_id
  5960. );
  5961. }
  5962. if ($forumThread) {
  5963. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5964. 'action' => 'dissociate_forum',
  5965. 'id' => $arrLP[$i]['id'],
  5966. 'lp_id' => $this->lp_id,
  5967. ]);
  5968. $forumIcon = Display::url(
  5969. Display::return_icon(
  5970. 'forum.png',
  5971. get_lang('DissociateForumToLPItem'),
  5972. [],
  5973. ICON_SIZE_TINY
  5974. ),
  5975. $forumIconUrl,
  5976. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5977. );
  5978. } else {
  5979. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5980. 'action' => 'create_forum',
  5981. 'id' => $arrLP[$i]['id'],
  5982. 'lp_id' => $this->lp_id,
  5983. ]);
  5984. $forumIcon = Display::url(
  5985. Display::return_icon(
  5986. 'forum.png',
  5987. get_lang('AssociateForumToLPItem'),
  5988. [],
  5989. ICON_SIZE_TINY
  5990. ),
  5991. $forumIconUrl,
  5992. ['class' => 'btn btn-default lp-btn-associate-forum']
  5993. );
  5994. }
  5995. }
  5996. } else {
  5997. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5998. $edit_icon .= Display::return_icon(
  5999. 'edit.png',
  6000. get_lang('LearnpathEditModule'),
  6001. [],
  6002. ICON_SIZE_TINY
  6003. );
  6004. $edit_icon .= '</a>';
  6005. }
  6006. } else {
  6007. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  6008. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  6009. $edit_icon .= Display::return_icon(
  6010. 'edit.png',
  6011. get_lang('Edit'),
  6012. [],
  6013. ICON_SIZE_TINY
  6014. );
  6015. $edit_icon .= '</a>';
  6016. }
  6017. }
  6018. if ($pluginCalendar) {
  6019. $pluginLink = $pluginUrl.
  6020. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6021. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6022. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  6023. if ($itemInfo && $itemInfo['value'] == 1) {
  6024. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  6025. }
  6026. $pluginCalendarIcon = Display::url(
  6027. $iconCalendar,
  6028. $pluginLink,
  6029. ['class' => 'btn btn-default']
  6030. );
  6031. }
  6032. $delete_icon .= ' <a
  6033. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  6034. onclick="return confirmation(\''.addslashes($title).'\');"
  6035. class="btn btn-default">';
  6036. $delete_icon .= Display::return_icon(
  6037. 'delete.png',
  6038. get_lang('LearnpathDeleteModule'),
  6039. [],
  6040. ICON_SIZE_TINY
  6041. );
  6042. $delete_icon .= '</a>';
  6043. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6044. $previewImage = Display::return_icon(
  6045. 'preview_view.png',
  6046. get_lang('Preview'),
  6047. [],
  6048. ICON_SIZE_TINY
  6049. );
  6050. switch ($arrLP[$i]['item_type']) {
  6051. case TOOL_DOCUMENT:
  6052. case TOOL_LP_FINAL_ITEM:
  6053. case TOOL_READOUT_TEXT:
  6054. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6055. $previewIcon = Display::url(
  6056. $previewImage,
  6057. $urlPreviewLink,
  6058. [
  6059. 'target' => '_blank',
  6060. 'class' => 'btn btn-default',
  6061. 'data-title' => $arrLP[$i]['title'],
  6062. 'title' => $arrLP[$i]['title'],
  6063. ]
  6064. );
  6065. break;
  6066. case TOOL_THREAD:
  6067. case TOOL_FORUM:
  6068. case TOOL_QUIZ:
  6069. case TOOL_STUDENTPUBLICATION:
  6070. case TOOL_LP_FINAL_ITEM:
  6071. case TOOL_LINK:
  6072. //$target = '';
  6073. //$class = 'btn btn-default ajax';
  6074. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  6075. $class = 'btn btn-default';
  6076. $target = '_blank';
  6077. //}
  6078. $link = self::rl_get_resource_link_for_learnpath(
  6079. $this->course_int_id,
  6080. $this->lp_id,
  6081. $arrLP[$i]['id'],
  6082. 0
  6083. );
  6084. $previewIcon = Display::url(
  6085. $previewImage,
  6086. $link,
  6087. [
  6088. 'class' => $class,
  6089. 'data-title' => $arrLP[$i]['title'],
  6090. 'title' => $arrLP[$i]['title'],
  6091. 'target' => $target,
  6092. ]
  6093. );
  6094. break;
  6095. default:
  6096. $previewIcon = Display::url(
  6097. $previewImage,
  6098. $url.'&action=view_item',
  6099. ['class' => 'btn btn-default', 'target' => '_blank']
  6100. );
  6101. break;
  6102. }
  6103. if ($arrLP[$i]['item_type'] != 'dir') {
  6104. $prerequisities_icon = Display::url(
  6105. Display::return_icon(
  6106. 'accept.png',
  6107. get_lang('LearnpathPrerequisites'),
  6108. [],
  6109. ICON_SIZE_TINY
  6110. ),
  6111. $url.'&action=edit_item_prereq',
  6112. ['class' => 'btn btn-default']
  6113. );
  6114. if ($arrLP[$i]['item_type'] != 'final_item') {
  6115. $move_item_icon = Display::url(
  6116. Display::return_icon(
  6117. 'move.png',
  6118. get_lang('Move'),
  6119. [],
  6120. ICON_SIZE_TINY
  6121. ),
  6122. $url.'&action=move_item',
  6123. ['class' => 'btn btn-default']
  6124. );
  6125. }
  6126. $audio_icon = Display::url(
  6127. Display::return_icon(
  6128. 'audio.png',
  6129. get_lang('UplUpload'),
  6130. [],
  6131. ICON_SIZE_TINY
  6132. ),
  6133. $url.'&action=add_audio',
  6134. ['class' => 'btn btn-default']
  6135. );
  6136. }
  6137. }
  6138. if ($update_audio != 'true') {
  6139. $row = $move_icon.' '.$icon.
  6140. Display::span($title_cut).
  6141. Display::tag(
  6142. 'div',
  6143. "<div class=\"btn-group btn-group-xs\">
  6144. $previewIcon
  6145. $audio
  6146. $edit_icon
  6147. $pluginCalendarIcon
  6148. $forumIcon
  6149. $prerequisities_icon
  6150. $move_item_icon
  6151. $audio_icon
  6152. $delete_icon
  6153. </div>",
  6154. ['class' => 'btn-toolbar button_actions']
  6155. );
  6156. } else {
  6157. $row =
  6158. Display::span($title.$icon).
  6159. Display::span($audio, ['class' => 'button_actions']);
  6160. }
  6161. $parent_id = $arrLP[$i]['parent_item_id'];
  6162. $default_data[$arrLP[$i]['id']] = $row;
  6163. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6164. if (empty($parent_id)) {
  6165. $elements[$arrLP[$i]['id']]['data'] = $row;
  6166. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6167. } else {
  6168. $parent_arrays = [];
  6169. if ($arrLP[$i]['depth'] > 1) {
  6170. //Getting list of parents
  6171. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6172. foreach ($arrLP as $item) {
  6173. if ($item['id'] == $parent_id) {
  6174. if ($item['parent_item_id'] == 0) {
  6175. $parent_id = $item['id'];
  6176. break;
  6177. } else {
  6178. $parent_id = $item['parent_item_id'];
  6179. if (empty($parent_arrays)) {
  6180. $parent_arrays[] = intval($item['id']);
  6181. }
  6182. $parent_arrays[] = $parent_id;
  6183. break;
  6184. }
  6185. }
  6186. }
  6187. }
  6188. }
  6189. if (!empty($parent_arrays)) {
  6190. $parent_arrays = array_reverse($parent_arrays);
  6191. $val = '$elements';
  6192. $x = 0;
  6193. foreach ($parent_arrays as $item) {
  6194. if ($x != count($parent_arrays) - 1) {
  6195. $val .= '["'.$item.'"]["children"]';
  6196. } else {
  6197. $val .= '["'.$item.'"]["children"]';
  6198. }
  6199. $x++;
  6200. }
  6201. $val .= "";
  6202. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6203. eval($code_str);
  6204. } else {
  6205. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6206. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6207. }
  6208. }
  6209. }
  6210. return [
  6211. 'elements' => $elements,
  6212. 'default_data' => $default_data,
  6213. 'default_content' => $default_content,
  6214. 'return_audio' => $return_audio,
  6215. ];
  6216. }
  6217. /**
  6218. * @param string $updateAudio true/false strings
  6219. *
  6220. * @return string
  6221. */
  6222. public function returnLpItemList($updateAudio)
  6223. {
  6224. $result = $this->processBuildMenuElements($updateAudio);
  6225. $html = self::print_recursive(
  6226. $result['elements'],
  6227. $result['default_data'],
  6228. $result['default_content']
  6229. );
  6230. if (!empty($html)) {
  6231. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6232. }
  6233. return $html;
  6234. }
  6235. /**
  6236. * @param string $update_audio
  6237. * @param bool $drop_element_here
  6238. *
  6239. * @return string
  6240. */
  6241. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6242. {
  6243. $return = '';
  6244. $result = $this->processBuildMenuElements($update_audio);
  6245. $list = '<ul id="lp_item_list">';
  6246. $tree = $this->print_recursive(
  6247. $result['elements'],
  6248. $result['default_data'],
  6249. $result['default_content']
  6250. );
  6251. if (!empty($tree)) {
  6252. $list .= $tree;
  6253. } else {
  6254. if ($drop_element_here) {
  6255. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6256. }
  6257. }
  6258. $list .= '</ul>';
  6259. $return .= Display::panelCollapse(
  6260. $this->name,
  6261. $list,
  6262. 'scorm-list',
  6263. null,
  6264. 'scorm-list-accordion',
  6265. 'scorm-list-collapse'
  6266. );
  6267. if ($update_audio === 'true') {
  6268. $return = $result['return_audio'];
  6269. }
  6270. return $return;
  6271. }
  6272. /**
  6273. * @param array $elements
  6274. * @param array $default_data
  6275. * @param array $default_content
  6276. *
  6277. * @return string
  6278. */
  6279. public function print_recursive($elements, $default_data, $default_content)
  6280. {
  6281. $return = '';
  6282. foreach ($elements as $key => $item) {
  6283. if (isset($item['load_data']) || empty($item['data'])) {
  6284. $item['data'] = $default_data[$item['load_data']];
  6285. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6286. }
  6287. $sub_list = '';
  6288. if (isset($item['type']) && $item['type'] == 'dir') {
  6289. // empty value
  6290. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6291. }
  6292. if (empty($item['children'])) {
  6293. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6294. $active = null;
  6295. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6296. $active = 'active';
  6297. }
  6298. $return .= Display::tag(
  6299. 'li',
  6300. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6301. ['id' => $key, 'class' => 'record li_container']
  6302. );
  6303. } else {
  6304. // Sections
  6305. $data = '';
  6306. if (isset($item['children'])) {
  6307. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6308. }
  6309. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6310. $return .= Display::tag(
  6311. 'li',
  6312. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6313. ['id' => $key, 'class' => 'record li_container']
  6314. );
  6315. }
  6316. }
  6317. return $return;
  6318. }
  6319. /**
  6320. * This function builds the action menu.
  6321. *
  6322. * @param bool $returnContent Optional
  6323. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6324. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6325. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6326. *
  6327. * @return string
  6328. */
  6329. public function build_action_menu(
  6330. $returnContent = false,
  6331. $showRequirementButtons = true,
  6332. $isConfigPage = false,
  6333. $allowExpand = true
  6334. ) {
  6335. $actionsLeft = '';
  6336. $actionsRight = '';
  6337. $actionsLeft .= Display::url(
  6338. Display::return_icon(
  6339. 'back.png',
  6340. get_lang('ReturnToLearningPaths'),
  6341. '',
  6342. ICON_SIZE_MEDIUM
  6343. ),
  6344. 'lp_controller.php?'.api_get_cidreq()
  6345. );
  6346. $actionsLeft .= Display::url(
  6347. Display::return_icon(
  6348. 'preview_view.png',
  6349. get_lang('Preview'),
  6350. '',
  6351. ICON_SIZE_MEDIUM
  6352. ),
  6353. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6354. 'action' => 'view',
  6355. 'lp_id' => $this->lp_id,
  6356. 'isStudentView' => 'true',
  6357. ])
  6358. );
  6359. $actionsLeft .= Display::url(
  6360. Display::return_icon(
  6361. 'upload_audio.png',
  6362. get_lang('UpdateAllAudioFragments'),
  6363. '',
  6364. ICON_SIZE_MEDIUM
  6365. ),
  6366. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6367. 'action' => 'admin_view',
  6368. 'lp_id' => $this->lp_id,
  6369. 'updateaudio' => 'true',
  6370. ])
  6371. );
  6372. if (!$isConfigPage) {
  6373. $actionsLeft .= Display::url(
  6374. Display::return_icon(
  6375. 'settings.png',
  6376. get_lang('CourseSettings'),
  6377. '',
  6378. ICON_SIZE_MEDIUM
  6379. ),
  6380. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6381. 'action' => 'edit',
  6382. 'lp_id' => $this->lp_id,
  6383. ])
  6384. );
  6385. } else {
  6386. $actionsLeft .= Display::url(
  6387. Display::return_icon(
  6388. 'edit.png',
  6389. get_lang('Edit'),
  6390. '',
  6391. ICON_SIZE_MEDIUM
  6392. ),
  6393. 'lp_controller.php?'.http_build_query([
  6394. 'action' => 'build',
  6395. 'lp_id' => $this->lp_id,
  6396. ]).'&'.api_get_cidreq()
  6397. );
  6398. }
  6399. if ($allowExpand) {
  6400. $actionsLeft .= Display::url(
  6401. Display::return_icon(
  6402. 'expand.png',
  6403. get_lang('Expand'),
  6404. ['id' => 'expand'],
  6405. ICON_SIZE_MEDIUM
  6406. ).
  6407. Display::return_icon(
  6408. 'contract.png',
  6409. get_lang('Collapse'),
  6410. ['id' => 'contract', 'class' => 'hide'],
  6411. ICON_SIZE_MEDIUM
  6412. ),
  6413. '#',
  6414. ['role' => 'button', 'id' => 'hide_bar_template']
  6415. );
  6416. }
  6417. if ($showRequirementButtons) {
  6418. $buttons = [
  6419. [
  6420. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6421. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6422. 'action' => 'set_previous_step_as_prerequisite',
  6423. 'lp_id' => $this->lp_id,
  6424. ]),
  6425. ],
  6426. [
  6427. 'title' => get_lang('ClearAllPrerequisites'),
  6428. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6429. 'action' => 'clear_prerequisites',
  6430. 'lp_id' => $this->lp_id,
  6431. ]),
  6432. ],
  6433. ];
  6434. $actionsRight = Display::groupButtonWithDropDown(
  6435. get_lang('PrerequisitesOptions'),
  6436. $buttons,
  6437. true
  6438. );
  6439. }
  6440. $toolbar = Display::toolbarAction(
  6441. 'actions-lp-controller',
  6442. [$actionsLeft, $actionsRight]
  6443. );
  6444. if ($returnContent) {
  6445. return $toolbar;
  6446. }
  6447. echo $toolbar;
  6448. }
  6449. /**
  6450. * Creates the default learning path folder.
  6451. *
  6452. * @param array $course
  6453. * @param int $creatorId
  6454. *
  6455. * @return bool
  6456. */
  6457. public static function generate_learning_path_folder($course, $creatorId = 0)
  6458. {
  6459. // Creating learning_path folder
  6460. $dir = '/learning_path';
  6461. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6462. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6463. $folder = false;
  6464. if (!is_dir($filepath.'/'.$dir)) {
  6465. $folderData = create_unexisting_directory(
  6466. $course,
  6467. $creatorId,
  6468. 0,
  6469. null,
  6470. 0,
  6471. $filepath,
  6472. $dir,
  6473. get_lang('LearningPaths'),
  6474. 0
  6475. );
  6476. if (!empty($folderData)) {
  6477. $folder = true;
  6478. }
  6479. } else {
  6480. $folder = true;
  6481. }
  6482. return $folder;
  6483. }
  6484. /**
  6485. * @param array $course
  6486. * @param string $lp_name
  6487. * @param int $creatorId
  6488. *
  6489. * @return array
  6490. */
  6491. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6492. {
  6493. $filepath = '';
  6494. $dir = '/learning_path/';
  6495. if (empty($lp_name)) {
  6496. $lp_name = $this->name;
  6497. }
  6498. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6499. $folder = self::generate_learning_path_folder($course, $creatorId);
  6500. // Limits title size
  6501. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6502. $dir = $dir.$title;
  6503. // Creating LP folder
  6504. $documentId = null;
  6505. if ($folder) {
  6506. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6507. if (!is_dir($filepath.'/'.$dir)) {
  6508. $folderData = create_unexisting_directory(
  6509. $course,
  6510. $creatorId,
  6511. 0,
  6512. 0,
  6513. 0,
  6514. $filepath,
  6515. $dir,
  6516. $lp_name
  6517. );
  6518. if (!empty($folderData)) {
  6519. $folder = true;
  6520. }
  6521. $documentId = $folderData['id'];
  6522. } else {
  6523. $folder = true;
  6524. }
  6525. $dir = $dir.'/';
  6526. if ($folder) {
  6527. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6528. }
  6529. }
  6530. if (empty($documentId)) {
  6531. $dir = api_remove_trailing_slash($dir);
  6532. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6533. }
  6534. $array = [
  6535. 'dir' => $dir,
  6536. 'filepath' => $filepath,
  6537. 'folder' => $folder,
  6538. 'id' => $documentId,
  6539. ];
  6540. return $array;
  6541. }
  6542. /**
  6543. * Create a new document //still needs some finetuning.
  6544. *
  6545. * @param array $courseInfo
  6546. * @param string $content
  6547. * @param string $title
  6548. * @param string $extension
  6549. * @param int $parentId
  6550. * @param int $creatorId creator id
  6551. *
  6552. * @return int
  6553. */
  6554. public function create_document(
  6555. $courseInfo,
  6556. $content = '',
  6557. $title = '',
  6558. $extension = 'html',
  6559. $parentId = 0,
  6560. $creatorId = 0
  6561. ) {
  6562. if (!empty($courseInfo)) {
  6563. $course_id = $courseInfo['real_id'];
  6564. } else {
  6565. $course_id = api_get_course_int_id();
  6566. }
  6567. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6568. $sessionId = api_get_session_id();
  6569. // Generates folder
  6570. $result = $this->generate_lp_folder($courseInfo);
  6571. $dir = $result['dir'];
  6572. if (empty($parentId) || $parentId == '/') {
  6573. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6574. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6575. if ($parentId === '/') {
  6576. $dir = '/';
  6577. }
  6578. // Please, do not modify this dirname formatting.
  6579. if (strstr($dir, '..')) {
  6580. $dir = '/';
  6581. }
  6582. if (!empty($dir[0]) && $dir[0] == '.') {
  6583. $dir = substr($dir, 1);
  6584. }
  6585. if (!empty($dir[0]) && $dir[0] != '/') {
  6586. $dir = '/'.$dir;
  6587. }
  6588. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6589. $dir .= '/';
  6590. }
  6591. } else {
  6592. $parentInfo = DocumentManager::get_document_data_by_id(
  6593. $parentId,
  6594. $courseInfo['code']
  6595. );
  6596. if (!empty($parentInfo)) {
  6597. $dir = $parentInfo['path'].'/';
  6598. }
  6599. }
  6600. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6601. if (!is_dir($filepath)) {
  6602. $dir = '/';
  6603. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6604. }
  6605. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6606. // is already escaped twice when it gets here.
  6607. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6608. if (!empty($title)) {
  6609. $title = api_replace_dangerous_char(stripslashes($title));
  6610. } else {
  6611. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6612. }
  6613. $title = disable_dangerous_file($title);
  6614. $filename = $title;
  6615. $content = !empty($content) ? $content : $_POST['content_lp'];
  6616. $tmp_filename = $filename;
  6617. $i = 0;
  6618. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6619. $tmp_filename = $filename.'_'.++$i;
  6620. }
  6621. $filename = $tmp_filename.'.'.$extension;
  6622. if ($extension == 'html') {
  6623. $content = stripslashes($content);
  6624. $content = str_replace(
  6625. api_get_path(WEB_COURSE_PATH),
  6626. api_get_path(REL_PATH).'courses/',
  6627. $content
  6628. );
  6629. // Change the path of mp3 to absolute.
  6630. // The first regexp deals with :// urls.
  6631. $content = preg_replace(
  6632. "|(flashvars=\"file=)([^:/]+)/|",
  6633. "$1".api_get_path(
  6634. REL_COURSE_PATH
  6635. ).$courseInfo['path'].'/document/',
  6636. $content
  6637. );
  6638. // The second regexp deals with audio/ urls.
  6639. $content = preg_replace(
  6640. "|(flashvars=\"file=)([^/]+)/|",
  6641. "$1".api_get_path(
  6642. REL_COURSE_PATH
  6643. ).$courseInfo['path'].'/document/$2/',
  6644. $content
  6645. );
  6646. // For flv player: To prevent edition problem with firefox,
  6647. // we have to use a strange tip (don't blame me please).
  6648. $content = str_replace(
  6649. '</body>',
  6650. '<style type="text/css">body{}</style></body>',
  6651. $content
  6652. );
  6653. }
  6654. if (!file_exists($filepath.$filename)) {
  6655. if ($fp = @fopen($filepath.$filename, 'w')) {
  6656. fputs($fp, $content);
  6657. fclose($fp);
  6658. $file_size = filesize($filepath.$filename);
  6659. $save_file_path = $dir.$filename;
  6660. $document_id = add_document(
  6661. $courseInfo,
  6662. $save_file_path,
  6663. 'file',
  6664. $file_size,
  6665. $tmp_filename,
  6666. '',
  6667. 0, //readonly
  6668. true,
  6669. null,
  6670. $sessionId,
  6671. $creatorId
  6672. );
  6673. if ($document_id) {
  6674. api_item_property_update(
  6675. $courseInfo,
  6676. TOOL_DOCUMENT,
  6677. $document_id,
  6678. 'DocumentAdded',
  6679. $creatorId,
  6680. null,
  6681. null,
  6682. null,
  6683. null,
  6684. $sessionId
  6685. );
  6686. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6687. $new_title = $originalTitle;
  6688. if ($new_comment || $new_title) {
  6689. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6690. $ct = '';
  6691. if ($new_comment) {
  6692. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6693. }
  6694. if ($new_title) {
  6695. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6696. }
  6697. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6698. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6699. Database::query($sql);
  6700. }
  6701. }
  6702. return $document_id;
  6703. }
  6704. }
  6705. }
  6706. /**
  6707. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6708. *
  6709. * @param array $_course array
  6710. */
  6711. public function edit_document($_course)
  6712. {
  6713. $course_id = api_get_course_int_id();
  6714. $urlAppend = api_get_configuration_value('url_append');
  6715. // Please, do not modify this dirname formatting.
  6716. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6717. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6718. if (strstr($dir, '..')) {
  6719. $dir = '/';
  6720. }
  6721. if (isset($dir[0]) && $dir[0] == '.') {
  6722. $dir = substr($dir, 1);
  6723. }
  6724. if (isset($dir[0]) && $dir[0] != '/') {
  6725. $dir = '/'.$dir;
  6726. }
  6727. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6728. $dir .= '/';
  6729. }
  6730. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6731. if (!is_dir($filepath)) {
  6732. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6733. }
  6734. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6735. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6736. $document_id = (int) $_POST['path'];
  6737. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6738. if (empty($documentInfo)) {
  6739. // Try with iid
  6740. $table = Database::get_course_table(TABLE_DOCUMENT);
  6741. $sql = "SELECT id, path FROM $table
  6742. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6743. $res_doc = Database::query($sql);
  6744. $row = Database::fetch_array($res_doc);
  6745. if ($row) {
  6746. $document_id = $row['id'];
  6747. $documentPath = $row['path'];
  6748. }
  6749. } else {
  6750. $documentPath = $documentInfo['path'];
  6751. }
  6752. $content = stripslashes($_POST['content_lp']);
  6753. $file = $filepath.$documentPath;
  6754. if (!file_exists($file)) {
  6755. return false;
  6756. }
  6757. if ($fp = @fopen($file, 'w')) {
  6758. $content = str_replace(
  6759. api_get_path(WEB_COURSE_PATH),
  6760. $urlAppend.api_get_path(REL_COURSE_PATH),
  6761. $content
  6762. );
  6763. // Change the path of mp3 to absolute.
  6764. // The first regexp deals with :// urls.
  6765. $content = preg_replace(
  6766. "|(flashvars=\"file=)([^:/]+)/|",
  6767. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6768. $content
  6769. );
  6770. // The second regexp deals with audio/ urls.
  6771. $content = preg_replace(
  6772. "|(flashvars=\"file=)([^:/]+)/|",
  6773. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6774. $content
  6775. );
  6776. fputs($fp, $content);
  6777. fclose($fp);
  6778. $sql = "UPDATE $table_doc SET
  6779. title='".Database::escape_string($_POST['title'])."'
  6780. WHERE c_id = $course_id AND id = ".$document_id;
  6781. Database::query($sql);
  6782. }
  6783. }
  6784. }
  6785. /**
  6786. * Displays the selected item, with a panel for manipulating the item.
  6787. *
  6788. * @param int $item_id
  6789. * @param string $msg
  6790. * @param bool $show_actions
  6791. *
  6792. * @return string
  6793. */
  6794. public function display_item($item_id, $msg = null, $show_actions = true)
  6795. {
  6796. $course_id = api_get_course_int_id();
  6797. $return = '';
  6798. if (is_numeric($item_id)) {
  6799. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6800. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6801. WHERE lp.iid = ".intval($item_id);
  6802. $result = Database::query($sql);
  6803. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6804. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6805. // Prevents wrong parent selection for document, see Bug#1251.
  6806. if ($row['item_type'] != 'dir') {
  6807. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6808. }
  6809. if ($show_actions) {
  6810. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6811. }
  6812. $return .= '<div style="padding:10px;">';
  6813. if ($msg != '') {
  6814. $return .= $msg;
  6815. }
  6816. $return .= '<h3>'.$row['title'].'</h3>';
  6817. switch ($row['item_type']) {
  6818. case TOOL_THREAD:
  6819. $link = $this->rl_get_resource_link_for_learnpath(
  6820. $course_id,
  6821. $row['lp_id'],
  6822. $item_id,
  6823. 0
  6824. );
  6825. $return .= Display::url(
  6826. get_lang('GoToThread'),
  6827. $link,
  6828. ['class' => 'btn btn-primary']
  6829. );
  6830. break;
  6831. case TOOL_FORUM:
  6832. $return .= Display::url(
  6833. get_lang('GoToForum'),
  6834. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6835. ['class' => 'btn btn-primary']
  6836. );
  6837. break;
  6838. case TOOL_QUIZ:
  6839. if (!empty($row['path'])) {
  6840. $exercise = new Exercise();
  6841. $exercise->read($row['path']);
  6842. $return .= $exercise->description.'<br />';
  6843. $return .= Display::url(
  6844. get_lang('GoToExercise'),
  6845. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6846. ['class' => 'btn btn-primary']
  6847. );
  6848. }
  6849. break;
  6850. case TOOL_LP_FINAL_ITEM:
  6851. $return .= $this->getSavedFinalItem();
  6852. break;
  6853. case TOOL_DOCUMENT:
  6854. case TOOL_READOUT_TEXT:
  6855. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6856. $sql_doc = "SELECT path FROM $tbl_doc
  6857. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6858. $result = Database::query($sql_doc);
  6859. $path_file = Database::result($result, 0, 0);
  6860. $path_parts = pathinfo($path_file);
  6861. // TODO: Correct the following naive comparisons.
  6862. if (in_array($path_parts['extension'], [
  6863. 'html',
  6864. 'txt',
  6865. 'png',
  6866. 'jpg',
  6867. 'JPG',
  6868. 'jpeg',
  6869. 'JPEG',
  6870. 'gif',
  6871. 'swf',
  6872. 'pdf',
  6873. 'htm',
  6874. ])) {
  6875. $return .= $this->display_document($row['path'], true, true);
  6876. }
  6877. break;
  6878. case TOOL_HOTPOTATOES:
  6879. $return .= $this->display_document($row['path'], false, true);
  6880. break;
  6881. }
  6882. $return .= '</div>';
  6883. }
  6884. }
  6885. return $return;
  6886. }
  6887. /**
  6888. * Shows the needed forms for editing a specific item.
  6889. *
  6890. * @param int $item_id
  6891. *
  6892. * @throws Exception
  6893. * @throws HTML_QuickForm_Error
  6894. *
  6895. * @return string
  6896. */
  6897. public function display_edit_item($item_id)
  6898. {
  6899. $course_id = api_get_course_int_id();
  6900. $return = '';
  6901. $item_id = (int) $item_id;
  6902. if (empty($item_id)) {
  6903. return '';
  6904. }
  6905. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6906. $sql = "SELECT * FROM $tbl_lp_item
  6907. WHERE iid = ".$item_id;
  6908. $res = Database::query($sql);
  6909. $row = Database::fetch_array($res);
  6910. switch ($row['item_type']) {
  6911. case 'dir':
  6912. case 'asset':
  6913. case 'sco':
  6914. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6915. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6916. $return .= $this->display_item_form(
  6917. $row['item_type'],
  6918. get_lang('EditCurrentChapter').' :',
  6919. 'edit',
  6920. $item_id,
  6921. $row
  6922. );
  6923. } else {
  6924. $return .= $this->display_item_form(
  6925. $row['item_type'],
  6926. get_lang('EditCurrentChapter').' :',
  6927. 'edit_item',
  6928. $item_id,
  6929. $row
  6930. );
  6931. }
  6932. break;
  6933. case TOOL_DOCUMENT:
  6934. case TOOL_READOUT_TEXT:
  6935. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6936. $sql = "SELECT lp.*, doc.path as dir
  6937. FROM $tbl_lp_item as lp
  6938. LEFT JOIN $tbl_doc as doc
  6939. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6940. WHERE
  6941. doc.c_id = $course_id AND
  6942. lp.iid = ".$item_id;
  6943. $res_step = Database::query($sql);
  6944. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6945. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6946. if ($row['item_type'] === TOOL_DOCUMENT) {
  6947. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6948. }
  6949. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6950. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6951. }
  6952. break;
  6953. case TOOL_LINK:
  6954. $linkId = (int) $row['path'];
  6955. if (!empty($linkId)) {
  6956. $table = Database::get_course_table(TABLE_LINK);
  6957. $sql = 'SELECT url FROM '.$table.'
  6958. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6959. $res_link = Database::query($sql);
  6960. $row_link = Database::fetch_array($res_link);
  6961. if (empty($row_link)) {
  6962. // Try with id
  6963. $sql = 'SELECT url FROM '.$table.'
  6964. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6965. $res_link = Database::query($sql);
  6966. $row_link = Database::fetch_array($res_link);
  6967. }
  6968. if (is_array($row_link)) {
  6969. $row['url'] = $row_link['url'];
  6970. }
  6971. }
  6972. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6973. $return .= $this->display_link_form('edit', $item_id, $row);
  6974. break;
  6975. case TOOL_LP_FINAL_ITEM:
  6976. Session::write('finalItem', true);
  6977. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6978. $sql = "SELECT lp.*, doc.path as dir
  6979. FROM $tbl_lp_item as lp
  6980. LEFT JOIN $tbl_doc as doc
  6981. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6982. WHERE
  6983. doc.c_id = $course_id AND
  6984. lp.iid = ".$item_id;
  6985. $res_step = Database::query($sql);
  6986. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6987. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6988. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6989. break;
  6990. case TOOL_QUIZ:
  6991. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6992. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6993. break;
  6994. case TOOL_HOTPOTATOES:
  6995. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6996. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6997. break;
  6998. case TOOL_STUDENTPUBLICATION:
  6999. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7000. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  7001. break;
  7002. case TOOL_FORUM:
  7003. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7004. $return .= $this->display_forum_form('edit', $item_id, $row);
  7005. break;
  7006. case TOOL_THREAD:
  7007. $return .= $this->display_manipulate($item_id, $row['item_type']);
  7008. $return .= $this->display_thread_form('edit', $item_id, $row);
  7009. break;
  7010. }
  7011. return $return;
  7012. }
  7013. /**
  7014. * Function that displays a list with al the resources that
  7015. * could be added to the learning path.
  7016. *
  7017. * @throws Exception
  7018. * @throws HTML_QuickForm_Error
  7019. *
  7020. * @return bool
  7021. */
  7022. public function display_resources()
  7023. {
  7024. $course_code = api_get_course_id();
  7025. // Get all the docs.
  7026. $documents = $this->get_documents(true);
  7027. // Get all the exercises.
  7028. $exercises = $this->get_exercises();
  7029. // Get all the links.
  7030. $links = $this->get_links();
  7031. // Get all the student publications.
  7032. $works = $this->get_student_publications();
  7033. // Get all the forums.
  7034. $forums = $this->get_forums(null, $course_code);
  7035. // Get the final item form (see BT#11048) .
  7036. $finish = $this->getFinalItemForm();
  7037. $headers = [
  7038. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  7039. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  7040. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  7041. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  7042. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  7043. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  7044. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  7045. ];
  7046. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  7047. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  7048. echo Display::tabs(
  7049. $headers,
  7050. [
  7051. $documents,
  7052. $exercises,
  7053. $links,
  7054. $works,
  7055. $forums,
  7056. $dir,
  7057. $finish,
  7058. ],
  7059. 'resource_tab'
  7060. );
  7061. return true;
  7062. }
  7063. /**
  7064. * Returns the extension of a document.
  7065. *
  7066. * @param string $filename
  7067. *
  7068. * @return string Extension (part after the last dot)
  7069. */
  7070. public function get_extension($filename)
  7071. {
  7072. $explode = explode('.', $filename);
  7073. return $explode[count($explode) - 1];
  7074. }
  7075. /**
  7076. * Displays a document by id.
  7077. *
  7078. * @param int $id
  7079. * @param bool $show_title
  7080. * @param bool $iframe
  7081. * @param bool $edit_link
  7082. *
  7083. * @return string
  7084. */
  7085. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  7086. {
  7087. $_course = api_get_course_info();
  7088. $course_id = api_get_course_int_id();
  7089. $id = (int) $id;
  7090. $return = '';
  7091. $table = Database::get_course_table(TABLE_DOCUMENT);
  7092. $sql_doc = "SELECT * FROM $table
  7093. WHERE c_id = $course_id AND iid = $id";
  7094. $res_doc = Database::query($sql_doc);
  7095. $row_doc = Database::fetch_array($res_doc);
  7096. // TODO: Add a path filter.
  7097. if ($iframe) {
  7098. $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>';
  7099. } else {
  7100. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  7101. }
  7102. return $return;
  7103. }
  7104. /**
  7105. * Return HTML form to add/edit a quiz.
  7106. *
  7107. * @param string $action Action (add/edit)
  7108. * @param int $id Item ID if already exists
  7109. * @param mixed $extra_info Extra information (quiz ID if integer)
  7110. *
  7111. * @throws Exception
  7112. *
  7113. * @return string HTML form
  7114. */
  7115. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  7116. {
  7117. $course_id = api_get_course_int_id();
  7118. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7119. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7120. if ($id != 0 && is_array($extra_info)) {
  7121. $item_title = $extra_info['title'];
  7122. $item_description = $extra_info['description'];
  7123. } elseif (is_numeric($extra_info)) {
  7124. $sql = "SELECT title, description
  7125. FROM $tbl_quiz
  7126. WHERE c_id = $course_id AND iid = ".$extra_info;
  7127. $result = Database::query($sql);
  7128. $row = Database::fetch_array($result);
  7129. $item_title = $row['title'];
  7130. $item_description = $row['description'];
  7131. } else {
  7132. $item_title = '';
  7133. $item_description = '';
  7134. }
  7135. $item_title = Security::remove_XSS($item_title);
  7136. $item_description = Security::remove_XSS($item_description);
  7137. if ($id != 0 && is_array($extra_info)) {
  7138. $parent = $extra_info['parent_item_id'];
  7139. } else {
  7140. $parent = 0;
  7141. }
  7142. $sql = "SELECT * FROM $tbl_lp_item
  7143. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7144. $result = Database::query($sql);
  7145. $arrLP = [];
  7146. while ($row = Database::fetch_array($result)) {
  7147. $arrLP[] = [
  7148. 'id' => $row['iid'],
  7149. 'item_type' => $row['item_type'],
  7150. 'title' => $row['title'],
  7151. 'path' => $row['path'],
  7152. 'description' => $row['description'],
  7153. 'parent_item_id' => $row['parent_item_id'],
  7154. 'previous_item_id' => $row['previous_item_id'],
  7155. 'next_item_id' => $row['next_item_id'],
  7156. 'display_order' => $row['display_order'],
  7157. 'max_score' => $row['max_score'],
  7158. 'min_score' => $row['min_score'],
  7159. 'mastery_score' => $row['mastery_score'],
  7160. 'prerequisite' => $row['prerequisite'],
  7161. 'max_time_allowed' => $row['max_time_allowed'],
  7162. ];
  7163. }
  7164. $this->tree_array($arrLP);
  7165. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7166. unset($this->arrMenu);
  7167. $form = new FormValidator(
  7168. 'quiz_form',
  7169. 'POST',
  7170. $this->getCurrentBuildingModeURL()
  7171. );
  7172. $defaults = [];
  7173. if ($action == 'add') {
  7174. $legend = get_lang('CreateTheExercise');
  7175. } elseif ($action == 'move') {
  7176. $legend = get_lang('MoveTheCurrentExercise');
  7177. } else {
  7178. $legend = get_lang('EditCurrentExecice');
  7179. }
  7180. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7181. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7182. }
  7183. $form->addHeader($legend);
  7184. if ($action != 'move') {
  7185. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7186. $defaults['title'] = $item_title;
  7187. }
  7188. // Select for Parent item, root or chapter
  7189. $selectParent = $form->addSelect(
  7190. 'parent',
  7191. get_lang('Parent'),
  7192. [],
  7193. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7194. );
  7195. $selectParent->addOption($this->name, 0);
  7196. $arrHide = [
  7197. $id,
  7198. ];
  7199. for ($i = 0; $i < count($arrLP); $i++) {
  7200. if ($action != 'add') {
  7201. if (
  7202. ($arrLP[$i]['item_type'] == 'dir') &&
  7203. !in_array($arrLP[$i]['id'], $arrHide) &&
  7204. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7205. ) {
  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. } else {
  7215. $arrHide[] = $arrLP[$i]['id'];
  7216. }
  7217. } else {
  7218. if ($arrLP[$i]['item_type'] == 'dir') {
  7219. $selectParent->addOption(
  7220. $arrLP[$i]['title'],
  7221. $arrLP[$i]['id'],
  7222. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7223. );
  7224. if ($parent == $arrLP[$i]['id']) {
  7225. $selectParent->setSelected($arrLP[$i]['id']);
  7226. }
  7227. }
  7228. }
  7229. }
  7230. if (is_array($arrLP)) {
  7231. reset($arrLP);
  7232. }
  7233. $selectPrevious = $form->addSelect(
  7234. 'previous',
  7235. get_lang('Position'),
  7236. [],
  7237. ['id' => 'previous']
  7238. );
  7239. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7240. for ($i = 0; $i < count($arrLP); $i++) {
  7241. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7242. $arrLP[$i]['id'] != $id
  7243. ) {
  7244. $selectPrevious->addOption(
  7245. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7246. $arrLP[$i]['id']
  7247. );
  7248. if (is_array($extra_info)) {
  7249. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7250. $selectPrevious->setSelected($arrLP[$i]['id']);
  7251. }
  7252. } elseif ($action == 'add') {
  7253. $selectPrevious->setSelected($arrLP[$i]['id']);
  7254. }
  7255. }
  7256. }
  7257. if ($action != 'move') {
  7258. $arrHide = [];
  7259. for ($i = 0; $i < count($arrLP); $i++) {
  7260. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7261. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7262. }
  7263. }
  7264. }
  7265. if ($action == 'add') {
  7266. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7267. } else {
  7268. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7269. }
  7270. if ($action == 'move') {
  7271. $form->addHidden('title', $item_title);
  7272. $form->addHidden('description', $item_description);
  7273. }
  7274. if (is_numeric($extra_info)) {
  7275. $form->addHidden('path', $extra_info);
  7276. } elseif (is_array($extra_info)) {
  7277. $form->addHidden('path', $extra_info['path']);
  7278. }
  7279. $form->addHidden('type', TOOL_QUIZ);
  7280. $form->addHidden('post_time', time());
  7281. $form->setDefaults($defaults);
  7282. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7283. }
  7284. /**
  7285. * Addition of Hotpotatoes tests.
  7286. *
  7287. * @param string $action
  7288. * @param int $id Internal ID of the item
  7289. * @param string $extra_info
  7290. *
  7291. * @return string HTML structure to display the hotpotatoes addition formular
  7292. */
  7293. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7294. {
  7295. $course_id = api_get_course_int_id();
  7296. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7297. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7298. if ($id != 0 && is_array($extra_info)) {
  7299. $item_title = stripslashes($extra_info['title']);
  7300. $item_description = stripslashes($extra_info['description']);
  7301. } elseif (is_numeric($extra_info)) {
  7302. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7303. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7304. WHERE
  7305. c_id = ".$course_id." AND
  7306. path LIKE '".$uploadPath."/%/%htm%' AND
  7307. iid = ".(int) $extra_info."
  7308. ORDER BY iid ASC";
  7309. $res_hot = Database::query($sql);
  7310. $row = Database::fetch_array($res_hot);
  7311. $item_title = $row['title'];
  7312. $item_description = $row['description'];
  7313. if (!empty($row['comment'])) {
  7314. $item_title = $row['comment'];
  7315. }
  7316. } else {
  7317. $item_title = '';
  7318. $item_description = '';
  7319. }
  7320. if ($id != 0 && is_array($extra_info)) {
  7321. $parent = $extra_info['parent_item_id'];
  7322. } else {
  7323. $parent = 0;
  7324. }
  7325. $sql = "SELECT * FROM $tbl_lp_item
  7326. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7327. $result = Database::query($sql);
  7328. $arrLP = [];
  7329. while ($row = Database::fetch_array($result)) {
  7330. $arrLP[] = [
  7331. 'id' => $row['id'],
  7332. 'item_type' => $row['item_type'],
  7333. 'title' => $row['title'],
  7334. 'path' => $row['path'],
  7335. 'description' => $row['description'],
  7336. 'parent_item_id' => $row['parent_item_id'],
  7337. 'previous_item_id' => $row['previous_item_id'],
  7338. 'next_item_id' => $row['next_item_id'],
  7339. 'display_order' => $row['display_order'],
  7340. 'max_score' => $row['max_score'],
  7341. 'min_score' => $row['min_score'],
  7342. 'mastery_score' => $row['mastery_score'],
  7343. 'prerequisite' => $row['prerequisite'],
  7344. 'max_time_allowed' => $row['max_time_allowed'],
  7345. ];
  7346. }
  7347. $legend = '<legend>';
  7348. if ($action == 'add') {
  7349. $legend .= get_lang('CreateTheExercise');
  7350. } elseif ($action == 'move') {
  7351. $legend .= get_lang('MoveTheCurrentExercise');
  7352. } else {
  7353. $legend .= get_lang('EditCurrentExecice');
  7354. }
  7355. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7356. $legend .= Display:: return_message(
  7357. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7358. );
  7359. }
  7360. $legend .= '</legend>';
  7361. $return = '<form method="POST">';
  7362. $return .= $legend;
  7363. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7364. $return .= '<tr>';
  7365. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7366. $return .= '<td class="input">';
  7367. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7368. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7369. $arrHide = [
  7370. $id,
  7371. ];
  7372. if (count($arrLP) > 0) {
  7373. for ($i = 0; $i < count($arrLP); $i++) {
  7374. if ($action != 'add') {
  7375. if ($arrLP[$i]['item_type'] == 'dir' &&
  7376. !in_array($arrLP[$i]['id'], $arrHide) &&
  7377. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7378. ) {
  7379. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7380. } else {
  7381. $arrHide[] = $arrLP[$i]['id'];
  7382. }
  7383. } else {
  7384. if ($arrLP[$i]['item_type'] == 'dir') {
  7385. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7386. }
  7387. }
  7388. }
  7389. reset($arrLP);
  7390. }
  7391. $return .= '</select>';
  7392. $return .= '</td>';
  7393. $return .= '</tr>';
  7394. $return .= '<tr>';
  7395. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7396. $return .= '<td class="input">';
  7397. $return .= '<select id="previous" name="previous" size="1">';
  7398. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7399. for ($i = 0; $i < count($arrLP); $i++) {
  7400. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7401. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7402. $selected = 'selected="selected" ';
  7403. } elseif ($action == 'add') {
  7404. $selected = 'selected="selected" ';
  7405. } else {
  7406. $selected = '';
  7407. }
  7408. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7409. }
  7410. }
  7411. $return .= '</select>';
  7412. $return .= '</td>';
  7413. $return .= '</tr>';
  7414. if ($action != 'move') {
  7415. $return .= '<tr>';
  7416. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7417. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7418. $return .= '</tr>';
  7419. $id_prerequisite = 0;
  7420. if (is_array($arrLP) && count($arrLP) > 0) {
  7421. foreach ($arrLP as $key => $value) {
  7422. if ($value['id'] == $id) {
  7423. $id_prerequisite = $value['prerequisite'];
  7424. break;
  7425. }
  7426. }
  7427. $arrHide = [];
  7428. for ($i = 0; $i < count($arrLP); $i++) {
  7429. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7430. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7431. }
  7432. }
  7433. }
  7434. }
  7435. $return .= '<tr>';
  7436. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7437. get_lang('SaveHotpotatoes').'</button></td>';
  7438. $return .= '</tr>';
  7439. $return .= '</table>';
  7440. if ($action == 'move') {
  7441. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7442. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7443. }
  7444. if (is_numeric($extra_info)) {
  7445. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7446. } elseif (is_array($extra_info)) {
  7447. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7448. }
  7449. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7450. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7451. $return .= '</form>';
  7452. return $return;
  7453. }
  7454. /**
  7455. * Return the form to display the forum edit/add option.
  7456. *
  7457. * @param string $action
  7458. * @param int $id ID of the lp_item if already exists
  7459. * @param string $extra_info
  7460. *
  7461. * @throws Exception
  7462. *
  7463. * @return string HTML form
  7464. */
  7465. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7466. {
  7467. $course_id = api_get_course_int_id();
  7468. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7469. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7470. if ($id != 0 && is_array($extra_info)) {
  7471. $item_title = stripslashes($extra_info['title']);
  7472. } elseif (is_numeric($extra_info)) {
  7473. $sql = "SELECT forum_title as title, forum_comment as comment
  7474. FROM $tbl_forum
  7475. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7476. $result = Database::query($sql);
  7477. $row = Database::fetch_array($result);
  7478. $item_title = $row['title'];
  7479. $item_description = $row['comment'];
  7480. } else {
  7481. $item_title = '';
  7482. $item_description = '';
  7483. }
  7484. if ($id != 0 && is_array($extra_info)) {
  7485. $parent = $extra_info['parent_item_id'];
  7486. } else {
  7487. $parent = 0;
  7488. }
  7489. $sql = "SELECT * FROM $tbl_lp_item
  7490. WHERE
  7491. c_id = $course_id AND
  7492. lp_id = ".$this->lp_id;
  7493. $result = Database::query($sql);
  7494. $arrLP = [];
  7495. while ($row = Database::fetch_array($result)) {
  7496. $arrLP[] = [
  7497. 'id' => $row['iid'],
  7498. 'item_type' => $row['item_type'],
  7499. 'title' => $row['title'],
  7500. 'path' => $row['path'],
  7501. 'description' => $row['description'],
  7502. 'parent_item_id' => $row['parent_item_id'],
  7503. 'previous_item_id' => $row['previous_item_id'],
  7504. 'next_item_id' => $row['next_item_id'],
  7505. 'display_order' => $row['display_order'],
  7506. 'max_score' => $row['max_score'],
  7507. 'min_score' => $row['min_score'],
  7508. 'mastery_score' => $row['mastery_score'],
  7509. 'prerequisite' => $row['prerequisite'],
  7510. ];
  7511. }
  7512. $this->tree_array($arrLP);
  7513. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7514. unset($this->arrMenu);
  7515. if ($action == 'add') {
  7516. $legend = get_lang('CreateTheForum');
  7517. } elseif ($action == 'move') {
  7518. $legend = get_lang('MoveTheCurrentForum');
  7519. } else {
  7520. $legend = get_lang('EditCurrentForum');
  7521. }
  7522. $form = new FormValidator(
  7523. 'forum_form',
  7524. 'POST',
  7525. $this->getCurrentBuildingModeURL()
  7526. );
  7527. $defaults = [];
  7528. $form->addHeader($legend);
  7529. if ($action != 'move') {
  7530. $form->addText(
  7531. 'title',
  7532. get_lang('Title'),
  7533. true,
  7534. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7535. );
  7536. $defaults['title'] = $item_title;
  7537. }
  7538. $selectParent = $form->addSelect(
  7539. 'parent',
  7540. get_lang('Parent'),
  7541. [],
  7542. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7543. );
  7544. $selectParent->addOption($this->name, 0);
  7545. $arrHide = [
  7546. $id,
  7547. ];
  7548. for ($i = 0; $i < count($arrLP); $i++) {
  7549. if ($action != 'add') {
  7550. if ($arrLP[$i]['item_type'] == 'dir' &&
  7551. !in_array($arrLP[$i]['id'], $arrHide) &&
  7552. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7553. ) {
  7554. $selectParent->addOption(
  7555. $arrLP[$i]['title'],
  7556. $arrLP[$i]['id'],
  7557. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7558. );
  7559. if ($parent == $arrLP[$i]['id']) {
  7560. $selectParent->setSelected($arrLP[$i]['id']);
  7561. }
  7562. } else {
  7563. $arrHide[] = $arrLP[$i]['id'];
  7564. }
  7565. } else {
  7566. if ($arrLP[$i]['item_type'] == 'dir') {
  7567. $selectParent->addOption(
  7568. $arrLP[$i]['title'],
  7569. $arrLP[$i]['id'],
  7570. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7571. );
  7572. if ($parent == $arrLP[$i]['id']) {
  7573. $selectParent->setSelected($arrLP[$i]['id']);
  7574. }
  7575. }
  7576. }
  7577. }
  7578. if (is_array($arrLP)) {
  7579. reset($arrLP);
  7580. }
  7581. $selectPrevious = $form->addSelect(
  7582. 'previous',
  7583. get_lang('Position'),
  7584. [],
  7585. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7586. );
  7587. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7588. for ($i = 0; $i < count($arrLP); $i++) {
  7589. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7590. $arrLP[$i]['id'] != $id
  7591. ) {
  7592. $selectPrevious->addOption(
  7593. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7594. $arrLP[$i]['id']
  7595. );
  7596. if (isset($extra_info['previous_item_id']) &&
  7597. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7598. ) {
  7599. $selectPrevious->setSelected($arrLP[$i]['id']);
  7600. } elseif ($action == 'add') {
  7601. $selectPrevious->setSelected($arrLP[$i]['id']);
  7602. }
  7603. }
  7604. }
  7605. if ($action != 'move') {
  7606. $id_prerequisite = 0;
  7607. if (is_array($arrLP)) {
  7608. foreach ($arrLP as $key => $value) {
  7609. if ($value['id'] == $id) {
  7610. $id_prerequisite = $value['prerequisite'];
  7611. break;
  7612. }
  7613. }
  7614. }
  7615. $arrHide = [];
  7616. for ($i = 0; $i < count($arrLP); $i++) {
  7617. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7618. if (isset($extra_info['previous_item_id']) &&
  7619. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7620. ) {
  7621. $s_selected_position = $arrLP[$i]['id'];
  7622. } elseif ($action == 'add') {
  7623. $s_selected_position = 0;
  7624. }
  7625. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7626. }
  7627. }
  7628. }
  7629. if ($action == 'add') {
  7630. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7631. } else {
  7632. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7633. }
  7634. if ($action == 'move') {
  7635. $form->addHidden('title', $item_title);
  7636. $form->addHidden('description', $item_description);
  7637. }
  7638. if (is_numeric($extra_info)) {
  7639. $form->addHidden('path', $extra_info);
  7640. } elseif (is_array($extra_info)) {
  7641. $form->addHidden('path', $extra_info['path']);
  7642. }
  7643. $form->addHidden('type', TOOL_FORUM);
  7644. $form->addHidden('post_time', time());
  7645. $form->setDefaults($defaults);
  7646. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7647. }
  7648. /**
  7649. * Return HTML form to add/edit forum threads.
  7650. *
  7651. * @param string $action
  7652. * @param int $id Item ID if already exists in learning path
  7653. * @param string $extra_info
  7654. *
  7655. * @throws Exception
  7656. *
  7657. * @return string HTML form
  7658. */
  7659. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7660. {
  7661. $course_id = api_get_course_int_id();
  7662. if (empty($course_id)) {
  7663. return null;
  7664. }
  7665. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7666. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7667. if ($id != 0 && is_array($extra_info)) {
  7668. $item_title = stripslashes($extra_info['title']);
  7669. } elseif (is_numeric($extra_info)) {
  7670. $sql = "SELECT thread_title as title FROM $tbl_forum
  7671. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7672. $result = Database::query($sql);
  7673. $row = Database::fetch_array($result);
  7674. $item_title = $row['title'];
  7675. $item_description = '';
  7676. } else {
  7677. $item_title = '';
  7678. $item_description = '';
  7679. }
  7680. if ($id != 0 && is_array($extra_info)) {
  7681. $parent = $extra_info['parent_item_id'];
  7682. } else {
  7683. $parent = 0;
  7684. }
  7685. $sql = "SELECT * FROM $tbl_lp_item
  7686. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7687. $result = Database::query($sql);
  7688. $arrLP = [];
  7689. while ($row = Database::fetch_array($result)) {
  7690. $arrLP[] = [
  7691. 'id' => $row['iid'],
  7692. 'item_type' => $row['item_type'],
  7693. 'title' => $row['title'],
  7694. 'path' => $row['path'],
  7695. 'description' => $row['description'],
  7696. 'parent_item_id' => $row['parent_item_id'],
  7697. 'previous_item_id' => $row['previous_item_id'],
  7698. 'next_item_id' => $row['next_item_id'],
  7699. 'display_order' => $row['display_order'],
  7700. 'max_score' => $row['max_score'],
  7701. 'min_score' => $row['min_score'],
  7702. 'mastery_score' => $row['mastery_score'],
  7703. 'prerequisite' => $row['prerequisite'],
  7704. ];
  7705. }
  7706. $this->tree_array($arrLP);
  7707. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7708. unset($this->arrMenu);
  7709. $form = new FormValidator(
  7710. 'thread_form',
  7711. 'POST',
  7712. $this->getCurrentBuildingModeURL()
  7713. );
  7714. $defaults = [];
  7715. if ($action == 'add') {
  7716. $legend = get_lang('CreateTheForum');
  7717. } elseif ($action == 'move') {
  7718. $legend = get_lang('MoveTheCurrentForum');
  7719. } else {
  7720. $legend = get_lang('EditCurrentForum');
  7721. }
  7722. $form->addHeader($legend);
  7723. $selectParent = $form->addSelect(
  7724. 'parent',
  7725. get_lang('Parent'),
  7726. [],
  7727. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7728. );
  7729. $selectParent->addOption($this->name, 0);
  7730. $arrHide = [
  7731. $id,
  7732. ];
  7733. for ($i = 0; $i < count($arrLP); $i++) {
  7734. if ($action != 'add') {
  7735. if (
  7736. ($arrLP[$i]['item_type'] == 'dir') &&
  7737. !in_array($arrLP[$i]['id'], $arrHide) &&
  7738. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7739. ) {
  7740. $selectParent->addOption(
  7741. $arrLP[$i]['title'],
  7742. $arrLP[$i]['id'],
  7743. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7744. );
  7745. if ($parent == $arrLP[$i]['id']) {
  7746. $selectParent->setSelected($arrLP[$i]['id']);
  7747. }
  7748. } else {
  7749. $arrHide[] = $arrLP[$i]['id'];
  7750. }
  7751. } else {
  7752. if ($arrLP[$i]['item_type'] == 'dir') {
  7753. $selectParent->addOption(
  7754. $arrLP[$i]['title'],
  7755. $arrLP[$i]['id'],
  7756. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7757. );
  7758. if ($parent == $arrLP[$i]['id']) {
  7759. $selectParent->setSelected($arrLP[$i]['id']);
  7760. }
  7761. }
  7762. }
  7763. }
  7764. if ($arrLP != null) {
  7765. reset($arrLP);
  7766. }
  7767. $selectPrevious = $form->addSelect(
  7768. 'previous',
  7769. get_lang('Position'),
  7770. [],
  7771. ['id' => 'previous']
  7772. );
  7773. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7774. for ($i = 0; $i < count($arrLP); $i++) {
  7775. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7776. $selectPrevious->addOption(
  7777. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7778. $arrLP[$i]['id']
  7779. );
  7780. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7781. $selectPrevious->setSelected($arrLP[$i]['id']);
  7782. } elseif ($action == 'add') {
  7783. $selectPrevious->setSelected($arrLP[$i]['id']);
  7784. }
  7785. }
  7786. }
  7787. if ($action != 'move') {
  7788. $form->addText(
  7789. 'title',
  7790. get_lang('Title'),
  7791. true,
  7792. ['id' => 'idTitle']
  7793. );
  7794. $defaults['title'] = $item_title;
  7795. $id_prerequisite = 0;
  7796. if ($arrLP != null) {
  7797. foreach ($arrLP as $key => $value) {
  7798. if ($value['id'] == $id) {
  7799. $id_prerequisite = $value['prerequisite'];
  7800. break;
  7801. }
  7802. }
  7803. }
  7804. $arrHide = [];
  7805. $s_selected_position = 0;
  7806. for ($i = 0; $i < count($arrLP); $i++) {
  7807. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7808. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7809. $s_selected_position = $arrLP[$i]['id'];
  7810. } elseif ($action == 'add') {
  7811. $s_selected_position = 0;
  7812. }
  7813. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7814. }
  7815. }
  7816. $selectPrerequisites = $form->addSelect(
  7817. 'prerequisites',
  7818. get_lang('LearnpathPrerequisites'),
  7819. [],
  7820. ['id' => 'prerequisites']
  7821. );
  7822. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7823. foreach ($arrHide as $key => $value) {
  7824. $selectPrerequisites->addOption($value['value'], $key);
  7825. if ($key == $s_selected_position && $action == 'add') {
  7826. $selectPrerequisites->setSelected($key);
  7827. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7828. $selectPrerequisites->setSelected($key);
  7829. }
  7830. }
  7831. }
  7832. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7833. if ($action == 'move') {
  7834. $form->addHidden('title', $item_title);
  7835. $form->addHidden('description', $item_description);
  7836. }
  7837. if (is_numeric($extra_info)) {
  7838. $form->addHidden('path', $extra_info);
  7839. } elseif (is_array($extra_info)) {
  7840. $form->addHidden('path', $extra_info['path']);
  7841. }
  7842. $form->addHidden('type', TOOL_THREAD);
  7843. $form->addHidden('post_time', time());
  7844. $form->setDefaults($defaults);
  7845. return $form->returnForm();
  7846. }
  7847. /**
  7848. * Return the HTML form to display an item (generally a dir item).
  7849. *
  7850. * @param string $item_type
  7851. * @param string $title
  7852. * @param string $action
  7853. * @param int $id
  7854. * @param string $extra_info
  7855. *
  7856. * @throws Exception
  7857. * @throws HTML_QuickForm_Error
  7858. *
  7859. * @return string HTML form
  7860. */
  7861. public function display_item_form(
  7862. $item_type,
  7863. $title = '',
  7864. $action = 'add_item',
  7865. $id = 0,
  7866. $extra_info = 'new'
  7867. ) {
  7868. $_course = api_get_course_info();
  7869. global $charset;
  7870. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7871. $item_title = '';
  7872. $item_description = '';
  7873. $item_path_fck = '';
  7874. if ($id != 0 && is_array($extra_info)) {
  7875. $item_title = $extra_info['title'];
  7876. $item_description = $extra_info['description'];
  7877. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7878. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7879. }
  7880. $parent = 0;
  7881. if ($id != 0 && is_array($extra_info)) {
  7882. $parent = $extra_info['parent_item_id'];
  7883. }
  7884. $id = (int) $id;
  7885. $sql = "SELECT * FROM $tbl_lp_item
  7886. WHERE
  7887. lp_id = ".$this->lp_id." AND
  7888. iid != $id";
  7889. if ($item_type == 'dir') {
  7890. $sql .= " AND parent_item_id = 0";
  7891. }
  7892. $result = Database::query($sql);
  7893. $arrLP = [];
  7894. while ($row = Database::fetch_array($result)) {
  7895. $arrLP[] = [
  7896. 'id' => $row['iid'],
  7897. 'item_type' => $row['item_type'],
  7898. 'title' => $row['title'],
  7899. 'path' => $row['path'],
  7900. 'description' => $row['description'],
  7901. 'parent_item_id' => $row['parent_item_id'],
  7902. 'previous_item_id' => $row['previous_item_id'],
  7903. 'next_item_id' => $row['next_item_id'],
  7904. 'max_score' => $row['max_score'],
  7905. 'min_score' => $row['min_score'],
  7906. 'mastery_score' => $row['mastery_score'],
  7907. 'prerequisite' => $row['prerequisite'],
  7908. 'display_order' => $row['display_order'],
  7909. ];
  7910. }
  7911. $this->tree_array($arrLP);
  7912. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7913. unset($this->arrMenu);
  7914. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7915. $form = new FormValidator('form', 'POST', $url);
  7916. $defaults['title'] = api_html_entity_decode(
  7917. $item_title,
  7918. ENT_QUOTES,
  7919. $charset
  7920. );
  7921. $defaults['description'] = $item_description;
  7922. $form->addHeader($title);
  7923. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7924. $arrHide[0]['padding'] = 20;
  7925. $charset = api_get_system_encoding();
  7926. for ($i = 0; $i < count($arrLP); $i++) {
  7927. if ($action != 'add') {
  7928. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7929. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7930. ) {
  7931. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7932. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7933. if ($parent == $arrLP[$i]['id']) {
  7934. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7935. }
  7936. }
  7937. } else {
  7938. if ($arrLP[$i]['item_type'] == 'dir') {
  7939. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7940. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7941. if ($parent == $arrLP[$i]['id']) {
  7942. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7943. }
  7944. }
  7945. }
  7946. }
  7947. if ($action != 'move') {
  7948. $form->addElement('text', 'title', get_lang('Title'));
  7949. $form->applyFilter('title', 'html_filter');
  7950. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7951. } else {
  7952. $form->addElement('hidden', 'title');
  7953. }
  7954. $parentSelect = $form->addElement(
  7955. 'select',
  7956. 'parent',
  7957. get_lang('Parent'),
  7958. '',
  7959. [
  7960. 'id' => 'idParent',
  7961. 'onchange' => "javascript: load_cbo(this.value);",
  7962. ]
  7963. );
  7964. foreach ($arrHide as $key => $value) {
  7965. $parentSelect->addOption(
  7966. $value['value'],
  7967. $key,
  7968. 'style="padding-left:'.$value['padding'].'px;"'
  7969. );
  7970. $lastPosition = $key;
  7971. }
  7972. if (!empty($s_selected_parent)) {
  7973. $parentSelect->setSelected($s_selected_parent);
  7974. }
  7975. if (is_array($arrLP)) {
  7976. reset($arrLP);
  7977. }
  7978. $arrHide = [];
  7979. // POSITION
  7980. for ($i = 0; $i < count($arrLP); $i++) {
  7981. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7982. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7983. //this is the same!
  7984. if (isset($extra_info['previous_item_id']) &&
  7985. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7986. ) {
  7987. $s_selected_position = $arrLP[$i]['id'];
  7988. } elseif ($action == 'add') {
  7989. $s_selected_position = $arrLP[$i]['id'];
  7990. }
  7991. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7992. }
  7993. }
  7994. $position = $form->addElement(
  7995. 'select',
  7996. 'previous',
  7997. get_lang('Position'),
  7998. '',
  7999. ['id' => 'previous']
  8000. );
  8001. $padding = isset($value['padding']) ? $value['padding'] : 0;
  8002. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  8003. $lastPosition = null;
  8004. foreach ($arrHide as $key => $value) {
  8005. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  8006. $lastPosition = $key;
  8007. }
  8008. if (!empty($s_selected_position)) {
  8009. $position->setSelected($s_selected_position);
  8010. }
  8011. // When new chapter add at the end
  8012. if ($action == 'add_item') {
  8013. $position->setSelected($lastPosition);
  8014. }
  8015. if (is_array($arrLP)) {
  8016. reset($arrLP);
  8017. }
  8018. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  8019. //fix in order to use the tab
  8020. if ($item_type == 'dir') {
  8021. $form->addElement('hidden', 'type', 'dir');
  8022. }
  8023. $extension = null;
  8024. if (!empty($item_path)) {
  8025. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  8026. }
  8027. //assets can't be modified
  8028. //$item_type == 'asset' ||
  8029. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  8030. if ($item_type == 'sco') {
  8031. $form->addElement(
  8032. 'html',
  8033. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  8034. );
  8035. }
  8036. $renderer = $form->defaultRenderer();
  8037. $renderer->setElementTemplate(
  8038. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  8039. 'content_lp'
  8040. );
  8041. $relative_prefix = '';
  8042. $editor_config = [
  8043. 'ToolbarSet' => 'LearningPathDocuments',
  8044. 'Width' => '100%',
  8045. 'Height' => '500',
  8046. 'FullPage' => true,
  8047. 'CreateDocumentDir' => $relative_prefix,
  8048. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  8049. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  8050. ];
  8051. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  8052. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  8053. $defaults['content_lp'] = file_get_contents($content_path);
  8054. }
  8055. if (!empty($id)) {
  8056. $form->addHidden('id', $id);
  8057. }
  8058. $form->addElement('hidden', 'type', $item_type);
  8059. $form->addElement('hidden', 'post_time', time());
  8060. $form->setDefaults($defaults);
  8061. return $form->returnForm();
  8062. }
  8063. /**
  8064. * @return string
  8065. */
  8066. public function getCurrentBuildingModeURL()
  8067. {
  8068. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  8069. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  8070. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  8071. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  8072. $currentUrl = api_get_self().'?'.api_get_cidreq().
  8073. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  8074. return $currentUrl;
  8075. }
  8076. /**
  8077. * Returns the form to update or create a document.
  8078. *
  8079. * @param string $action (add/edit)
  8080. * @param int $id ID of the lp_item (if already exists)
  8081. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8082. *
  8083. * @throws Exception
  8084. * @throws HTML_QuickForm_Error
  8085. *
  8086. * @return string HTML form
  8087. */
  8088. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  8089. {
  8090. $course_id = api_get_course_int_id();
  8091. $_course = api_get_course_info();
  8092. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8093. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8094. $no_display_edit_textarea = false;
  8095. $item_description = '';
  8096. //If action==edit document
  8097. //We don't display the document form if it's not an editable document (html or txt file)
  8098. if ($action === 'edit') {
  8099. if (is_array($extra_info)) {
  8100. $path_parts = pathinfo($extra_info['dir']);
  8101. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8102. $no_display_edit_textarea = true;
  8103. }
  8104. }
  8105. }
  8106. $no_display_add = false;
  8107. // If action==add an existing document
  8108. // We don't display the document form if it's not an editable document (html or txt file).
  8109. if ($action === 'add') {
  8110. if (is_numeric($extra_info)) {
  8111. $extra_info = (int) $extra_info;
  8112. $sql_doc = "SELECT path FROM $tbl_doc
  8113. WHERE c_id = $course_id AND iid = ".$extra_info;
  8114. $result = Database::query($sql_doc);
  8115. $path_file = Database::result($result, 0, 0);
  8116. $path_parts = pathinfo($path_file);
  8117. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8118. $no_display_add = true;
  8119. }
  8120. }
  8121. }
  8122. if ($id != 0 && is_array($extra_info)) {
  8123. $item_title = stripslashes($extra_info['title']);
  8124. $item_description = stripslashes($extra_info['description']);
  8125. if (empty($item_title)) {
  8126. $path_parts = pathinfo($extra_info['path']);
  8127. $item_title = stripslashes($path_parts['filename']);
  8128. }
  8129. } elseif (is_numeric($extra_info)) {
  8130. $sql = "SELECT path, title FROM $tbl_doc
  8131. WHERE
  8132. c_id = ".$course_id." AND
  8133. iid = ".intval($extra_info);
  8134. $result = Database::query($sql);
  8135. $row = Database::fetch_array($result);
  8136. $item_title = $row['title'];
  8137. $item_title = str_replace('_', ' ', $item_title);
  8138. if (empty($item_title)) {
  8139. $path_parts = pathinfo($row['path']);
  8140. $item_title = stripslashes($path_parts['filename']);
  8141. }
  8142. } else {
  8143. $item_title = '';
  8144. $item_description = '';
  8145. }
  8146. $return = '<legend>';
  8147. $parent = 0;
  8148. if ($id != 0 && is_array($extra_info)) {
  8149. $parent = $extra_info['parent_item_id'];
  8150. }
  8151. $sql = "SELECT * FROM $tbl_lp_item
  8152. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8153. $result = Database::query($sql);
  8154. $arrLP = [];
  8155. while ($row = Database::fetch_array($result)) {
  8156. $arrLP[] = [
  8157. 'id' => $row['iid'],
  8158. 'item_type' => $row['item_type'],
  8159. 'title' => $row['title'],
  8160. 'path' => $row['path'],
  8161. 'description' => $row['description'],
  8162. 'parent_item_id' => $row['parent_item_id'],
  8163. 'previous_item_id' => $row['previous_item_id'],
  8164. 'next_item_id' => $row['next_item_id'],
  8165. 'display_order' => $row['display_order'],
  8166. 'max_score' => $row['max_score'],
  8167. 'min_score' => $row['min_score'],
  8168. 'mastery_score' => $row['mastery_score'],
  8169. 'prerequisite' => $row['prerequisite'],
  8170. ];
  8171. }
  8172. $this->tree_array($arrLP);
  8173. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8174. unset($this->arrMenu);
  8175. if ($action == 'add') {
  8176. $return .= get_lang('CreateTheDocument');
  8177. } elseif ($action == 'move') {
  8178. $return .= get_lang('MoveTheCurrentDocument');
  8179. } else {
  8180. $return .= get_lang('EditTheCurrentDocument');
  8181. }
  8182. $return .= '</legend>';
  8183. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8184. $return .= Display::return_message(
  8185. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8186. false
  8187. );
  8188. }
  8189. $form = new FormValidator(
  8190. 'form',
  8191. 'POST',
  8192. $this->getCurrentBuildingModeURL(),
  8193. '',
  8194. ['enctype' => 'multipart/form-data']
  8195. );
  8196. $defaults['title'] = Security::remove_XSS($item_title);
  8197. if (empty($item_title)) {
  8198. $defaults['title'] = Security::remove_XSS($item_title);
  8199. }
  8200. $defaults['description'] = $item_description;
  8201. $form->addElement('html', $return);
  8202. if ($action != 'move') {
  8203. $data = $this->generate_lp_folder($_course);
  8204. if ($action != 'edit') {
  8205. $folders = DocumentManager::get_all_document_folders(
  8206. $_course,
  8207. 0,
  8208. true
  8209. );
  8210. DocumentManager::build_directory_selector(
  8211. $folders,
  8212. '',
  8213. [],
  8214. true,
  8215. $form,
  8216. 'directory_parent_id'
  8217. );
  8218. }
  8219. if (isset($data['id'])) {
  8220. $defaults['directory_parent_id'] = $data['id'];
  8221. }
  8222. $form->addElement(
  8223. 'text',
  8224. 'title',
  8225. get_lang('Title'),
  8226. ['id' => 'idTitle', 'class' => 'col-md-4']
  8227. );
  8228. $form->applyFilter('title', 'html_filter');
  8229. }
  8230. $arrHide[0]['value'] = $this->name;
  8231. $arrHide[0]['padding'] = 20;
  8232. for ($i = 0; $i < count($arrLP); $i++) {
  8233. if ($action != 'add') {
  8234. if ($arrLP[$i]['item_type'] == 'dir' &&
  8235. !in_array($arrLP[$i]['id'], $arrHide) &&
  8236. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8237. ) {
  8238. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8239. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8240. }
  8241. } else {
  8242. if ($arrLP[$i]['item_type'] == 'dir') {
  8243. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8244. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8245. }
  8246. }
  8247. }
  8248. $parentSelect = $form->addSelect(
  8249. 'parent',
  8250. get_lang('Parent'),
  8251. [],
  8252. [
  8253. 'id' => 'idParent',
  8254. 'onchange' => 'javascript: load_cbo(this.value);',
  8255. ]
  8256. );
  8257. $my_count = 0;
  8258. foreach ($arrHide as $key => $value) {
  8259. if ($my_count != 0) {
  8260. // The LP name is also the first section and is not in the same charset like the other sections.
  8261. $value['value'] = Security::remove_XSS($value['value']);
  8262. $parentSelect->addOption(
  8263. $value['value'],
  8264. $key,
  8265. 'style="padding-left:'.$value['padding'].'px;"'
  8266. );
  8267. } else {
  8268. $value['value'] = Security::remove_XSS($value['value']);
  8269. $parentSelect->addOption(
  8270. $value['value'],
  8271. $key,
  8272. 'style="padding-left:'.$value['padding'].'px;"'
  8273. );
  8274. }
  8275. $my_count++;
  8276. }
  8277. if (!empty($id)) {
  8278. $parentSelect->setSelected($parent);
  8279. } else {
  8280. $parent_item_id = Session::read('parent_item_id', 0);
  8281. $parentSelect->setSelected($parent_item_id);
  8282. }
  8283. if (is_array($arrLP)) {
  8284. reset($arrLP);
  8285. }
  8286. $arrHide = [];
  8287. // POSITION
  8288. for ($i = 0; $i < count($arrLP); $i++) {
  8289. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8290. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8291. ) {
  8292. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8293. }
  8294. }
  8295. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8296. $position = $form->addSelect(
  8297. 'previous',
  8298. get_lang('Position'),
  8299. [],
  8300. ['id' => 'previous']
  8301. );
  8302. $position->addOption(get_lang('FirstPosition'), 0);
  8303. foreach ($arrHide as $key => $value) {
  8304. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8305. $position->addOption(
  8306. $value['value'],
  8307. $key,
  8308. 'style="padding-left:'.$padding.'px;"'
  8309. );
  8310. }
  8311. $position->setSelected($selectedPosition);
  8312. if (is_array($arrLP)) {
  8313. reset($arrLP);
  8314. }
  8315. if ($action != 'move') {
  8316. $arrHide = [];
  8317. for ($i = 0; $i < count($arrLP); $i++) {
  8318. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8319. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8320. ) {
  8321. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8322. }
  8323. }
  8324. if (!$no_display_add) {
  8325. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8326. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8327. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8328. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8329. ) {
  8330. if (isset($_POST['content'])) {
  8331. $content = stripslashes($_POST['content']);
  8332. } elseif (is_array($extra_info)) {
  8333. //If it's an html document or a text file
  8334. if (!$no_display_edit_textarea) {
  8335. $content = $this->display_document(
  8336. $extra_info['path'],
  8337. false,
  8338. false
  8339. );
  8340. }
  8341. } elseif (is_numeric($extra_info)) {
  8342. $content = $this->display_document(
  8343. $extra_info,
  8344. false,
  8345. false
  8346. );
  8347. } else {
  8348. $content = '';
  8349. }
  8350. if (!$no_display_edit_textarea) {
  8351. // We need to calculate here some specific settings for the online editor.
  8352. // The calculated settings work for documents in the Documents tool
  8353. // (on the root or in subfolders).
  8354. // For documents in native scorm packages it is unclear whether the
  8355. // online editor should be activated or not.
  8356. // A new document, it is in the root of the repository.
  8357. $relative_path = '';
  8358. $relative_prefix = '';
  8359. if (is_array($extra_info) && $extra_info != 'new') {
  8360. // The document already exists. Whe have to determine its relative path towards the repository root.
  8361. $relative_path = explode('/', $extra_info['dir']);
  8362. $cnt = count($relative_path) - 2;
  8363. if ($cnt < 0) {
  8364. $cnt = 0;
  8365. }
  8366. $relative_prefix = str_repeat('../', $cnt);
  8367. $relative_path = array_slice($relative_path, 1, $cnt);
  8368. $relative_path = implode('/', $relative_path);
  8369. if (strlen($relative_path) > 0) {
  8370. $relative_path = $relative_path.'/';
  8371. }
  8372. } else {
  8373. $result = $this->generate_lp_folder($_course);
  8374. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8375. $relative_prefix = '../../';
  8376. }
  8377. $editor_config = [
  8378. 'ToolbarSet' => 'LearningPathDocuments',
  8379. 'Width' => '100%',
  8380. 'Height' => '500',
  8381. 'FullPage' => true,
  8382. 'CreateDocumentDir' => $relative_prefix,
  8383. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8384. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8385. ];
  8386. if ($_GET['action'] == 'add_item') {
  8387. $class = 'add';
  8388. $text = get_lang('LPCreateDocument');
  8389. } else {
  8390. if ($_GET['action'] == 'edit_item') {
  8391. $class = 'save';
  8392. $text = get_lang('SaveDocument');
  8393. }
  8394. }
  8395. $form->addButtonSave($text, 'submit_button');
  8396. $renderer = $form->defaultRenderer();
  8397. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8398. $form->addElement('html', '<div class="editor-lp">');
  8399. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8400. $form->addElement('html', '</div>');
  8401. $defaults['content_lp'] = $content;
  8402. }
  8403. } elseif (is_numeric($extra_info)) {
  8404. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8405. $return = $this->display_document($extra_info, true, true, true);
  8406. $form->addElement('html', $return);
  8407. }
  8408. }
  8409. }
  8410. if (isset($extra_info['item_type']) &&
  8411. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8412. ) {
  8413. $parentSelect->freeze();
  8414. $position->freeze();
  8415. }
  8416. if ($action == 'move') {
  8417. $form->addElement('hidden', 'title', $item_title);
  8418. $form->addElement('hidden', 'description', $item_description);
  8419. }
  8420. if (is_numeric($extra_info)) {
  8421. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8422. $form->addElement('hidden', 'path', $extra_info);
  8423. } elseif (is_array($extra_info)) {
  8424. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8425. $form->addElement('hidden', 'path', $extra_info['path']);
  8426. }
  8427. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8428. $form->addElement('hidden', 'post_time', time());
  8429. $form->setDefaults($defaults);
  8430. return $form->returnForm();
  8431. }
  8432. /**
  8433. * Returns the form to update or create a read-out text.
  8434. *
  8435. * @param string $action "add" or "edit"
  8436. * @param int $id ID of the lp_item (if already exists)
  8437. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8438. *
  8439. * @throws Exception
  8440. * @throws HTML_QuickForm_Error
  8441. *
  8442. * @return string HTML form
  8443. */
  8444. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8445. {
  8446. $course_id = api_get_course_int_id();
  8447. $_course = api_get_course_info();
  8448. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8449. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8450. $no_display_edit_textarea = false;
  8451. $item_description = '';
  8452. //If action==edit document
  8453. //We don't display the document form if it's not an editable document (html or txt file)
  8454. if ($action == 'edit') {
  8455. if (is_array($extra_info)) {
  8456. $path_parts = pathinfo($extra_info['dir']);
  8457. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8458. $no_display_edit_textarea = true;
  8459. }
  8460. }
  8461. }
  8462. $no_display_add = false;
  8463. if ($id != 0 && is_array($extra_info)) {
  8464. $item_title = stripslashes($extra_info['title']);
  8465. $item_description = stripslashes($extra_info['description']);
  8466. $item_terms = stripslashes($extra_info['terms']);
  8467. if (empty($item_title)) {
  8468. $path_parts = pathinfo($extra_info['path']);
  8469. $item_title = stripslashes($path_parts['filename']);
  8470. }
  8471. } elseif (is_numeric($extra_info)) {
  8472. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8473. $result = Database::query($sql);
  8474. $row = Database::fetch_array($result);
  8475. $item_title = $row['title'];
  8476. $item_title = str_replace('_', ' ', $item_title);
  8477. if (empty($item_title)) {
  8478. $path_parts = pathinfo($row['path']);
  8479. $item_title = stripslashes($path_parts['filename']);
  8480. }
  8481. } else {
  8482. $item_title = '';
  8483. $item_description = '';
  8484. }
  8485. if ($id != 0 && is_array($extra_info)) {
  8486. $parent = $extra_info['parent_item_id'];
  8487. } else {
  8488. $parent = 0;
  8489. }
  8490. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8491. $result = Database::query($sql);
  8492. $arrLP = [];
  8493. while ($row = Database::fetch_array($result)) {
  8494. $arrLP[] = [
  8495. 'id' => $row['iid'],
  8496. 'item_type' => $row['item_type'],
  8497. 'title' => $row['title'],
  8498. 'path' => $row['path'],
  8499. 'description' => $row['description'],
  8500. 'parent_item_id' => $row['parent_item_id'],
  8501. 'previous_item_id' => $row['previous_item_id'],
  8502. 'next_item_id' => $row['next_item_id'],
  8503. 'display_order' => $row['display_order'],
  8504. 'max_score' => $row['max_score'],
  8505. 'min_score' => $row['min_score'],
  8506. 'mastery_score' => $row['mastery_score'],
  8507. 'prerequisite' => $row['prerequisite'],
  8508. ];
  8509. }
  8510. $this->tree_array($arrLP);
  8511. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8512. unset($this->arrMenu);
  8513. if ($action == 'add') {
  8514. $formHeader = get_lang('CreateTheDocument');
  8515. } else {
  8516. $formHeader = get_lang('EditTheCurrentDocument');
  8517. }
  8518. if ('edit' === $action) {
  8519. $urlAudioIcon = Display::url(
  8520. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8521. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8522. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8523. );
  8524. } else {
  8525. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8526. }
  8527. $form = new FormValidator(
  8528. 'frm_add_reading',
  8529. 'POST',
  8530. $this->getCurrentBuildingModeURL(),
  8531. '',
  8532. ['enctype' => 'multipart/form-data']
  8533. );
  8534. $form->addHeader($formHeader);
  8535. $form->addHtml(
  8536. Display::return_message(
  8537. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8538. 'normal',
  8539. false
  8540. )
  8541. );
  8542. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8543. $defaults['description'] = $item_description;
  8544. $data = $this->generate_lp_folder($_course);
  8545. if ($action != 'edit') {
  8546. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8547. DocumentManager::build_directory_selector(
  8548. $folders,
  8549. '',
  8550. [],
  8551. true,
  8552. $form,
  8553. 'directory_parent_id'
  8554. );
  8555. }
  8556. if (isset($data['id'])) {
  8557. $defaults['directory_parent_id'] = $data['id'];
  8558. }
  8559. $form->addElement(
  8560. 'text',
  8561. 'title',
  8562. get_lang('Title')
  8563. );
  8564. $form->applyFilter('title', 'trim');
  8565. $form->applyFilter('title', 'html_filter');
  8566. $arrHide[0]['value'] = $this->name;
  8567. $arrHide[0]['padding'] = 20;
  8568. for ($i = 0; $i < count($arrLP); $i++) {
  8569. if ($action != 'add') {
  8570. if ($arrLP[$i]['item_type'] == 'dir' &&
  8571. !in_array($arrLP[$i]['id'], $arrHide) &&
  8572. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8573. ) {
  8574. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8575. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8576. }
  8577. } else {
  8578. if ($arrLP[$i]['item_type'] == 'dir') {
  8579. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8580. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8581. }
  8582. }
  8583. }
  8584. $parent_select = $form->addSelect(
  8585. 'parent',
  8586. get_lang('Parent'),
  8587. [],
  8588. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8589. );
  8590. $my_count = 0;
  8591. foreach ($arrHide as $key => $value) {
  8592. if ($my_count != 0) {
  8593. // The LP name is also the first section and is not in the same charset like the other sections.
  8594. $value['value'] = Security::remove_XSS($value['value']);
  8595. $parent_select->addOption(
  8596. $value['value'],
  8597. $key,
  8598. 'style="padding-left:'.$value['padding'].'px;"'
  8599. );
  8600. } else {
  8601. $value['value'] = Security::remove_XSS($value['value']);
  8602. $parent_select->addOption(
  8603. $value['value'],
  8604. $key,
  8605. 'style="padding-left:'.$value['padding'].'px;"'
  8606. );
  8607. }
  8608. $my_count++;
  8609. }
  8610. if (!empty($id)) {
  8611. $parent_select->setSelected($parent);
  8612. } else {
  8613. $parent_item_id = Session::read('parent_item_id', 0);
  8614. $parent_select->setSelected($parent_item_id);
  8615. }
  8616. if (is_array($arrLP)) {
  8617. reset($arrLP);
  8618. }
  8619. $arrHide = [];
  8620. $s_selected_position = null;
  8621. // POSITION
  8622. $lastPosition = null;
  8623. for ($i = 0; $i < count($arrLP); $i++) {
  8624. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8625. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8626. ) {
  8627. if ((isset($extra_info['previous_item_id']) &&
  8628. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8629. ) {
  8630. $s_selected_position = $arrLP[$i]['id'];
  8631. }
  8632. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8633. }
  8634. $lastPosition = $arrLP[$i]['id'];
  8635. }
  8636. if (empty($s_selected_position)) {
  8637. $s_selected_position = $lastPosition;
  8638. }
  8639. $position = $form->addSelect(
  8640. 'previous',
  8641. get_lang('Position'),
  8642. []
  8643. );
  8644. $position->addOption(get_lang('FirstPosition'), 0);
  8645. foreach ($arrHide as $key => $value) {
  8646. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8647. $position->addOption(
  8648. $value['value'],
  8649. $key,
  8650. 'style="padding-left:'.$padding.'px;"'
  8651. );
  8652. }
  8653. $position->setSelected($s_selected_position);
  8654. if (is_array($arrLP)) {
  8655. reset($arrLP);
  8656. }
  8657. $arrHide = [];
  8658. for ($i = 0; $i < count($arrLP); $i++) {
  8659. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8660. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8661. ) {
  8662. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8663. }
  8664. }
  8665. if (!$no_display_add) {
  8666. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8667. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8668. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8669. if (!$no_display_edit_textarea) {
  8670. $content = '';
  8671. if (isset($_POST['content'])) {
  8672. $content = stripslashes($_POST['content']);
  8673. } elseif (is_array($extra_info)) {
  8674. $content = $this->display_document($extra_info['path'], false, false);
  8675. } elseif (is_numeric($extra_info)) {
  8676. $content = $this->display_document($extra_info, false, false);
  8677. }
  8678. // A new document, it is in the root of the repository.
  8679. if (is_array($extra_info) && $extra_info != 'new') {
  8680. } else {
  8681. $this->generate_lp_folder($_course);
  8682. }
  8683. if ($_GET['action'] == 'add_item') {
  8684. $text = get_lang('LPCreateDocument');
  8685. } else {
  8686. $text = get_lang('SaveDocument');
  8687. }
  8688. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8689. $form
  8690. ->defaultRenderer()
  8691. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8692. $form->addButtonSave($text, 'submit_button');
  8693. $defaults['content_lp'] = $content;
  8694. }
  8695. } elseif (is_numeric($extra_info)) {
  8696. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8697. $return = $this->display_document($extra_info, true, true, true);
  8698. $form->addElement('html', $return);
  8699. }
  8700. }
  8701. if (is_numeric($extra_info)) {
  8702. $form->addElement('hidden', 'path', $extra_info);
  8703. } elseif (is_array($extra_info)) {
  8704. $form->addElement('hidden', 'path', $extra_info['path']);
  8705. }
  8706. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8707. $form->addElement('hidden', 'post_time', time());
  8708. $form->setDefaults($defaults);
  8709. return $form->returnForm();
  8710. }
  8711. /**
  8712. * @param array $courseInfo
  8713. * @param string $content
  8714. * @param string $title
  8715. * @param int $parentId
  8716. *
  8717. * @throws \Doctrine\ORM\ORMException
  8718. * @throws \Doctrine\ORM\OptimisticLockException
  8719. * @throws \Doctrine\ORM\TransactionRequiredException
  8720. *
  8721. * @return int
  8722. */
  8723. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8724. {
  8725. $creatorId = api_get_user_id();
  8726. $sessionId = api_get_session_id();
  8727. // Generates folder
  8728. $result = $this->generate_lp_folder($courseInfo);
  8729. $dir = $result['dir'];
  8730. if (empty($parentId) || $parentId == '/') {
  8731. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8732. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8733. if ($parentId === '/') {
  8734. $dir = '/';
  8735. }
  8736. // Please, do not modify this dirname formatting.
  8737. if (strstr($dir, '..')) {
  8738. $dir = '/';
  8739. }
  8740. if (!empty($dir[0]) && $dir[0] == '.') {
  8741. $dir = substr($dir, 1);
  8742. }
  8743. if (!empty($dir[0]) && $dir[0] != '/') {
  8744. $dir = '/'.$dir;
  8745. }
  8746. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8747. $dir .= '/';
  8748. }
  8749. } else {
  8750. $parentInfo = DocumentManager::get_document_data_by_id(
  8751. $parentId,
  8752. $courseInfo['code']
  8753. );
  8754. if (!empty($parentInfo)) {
  8755. $dir = $parentInfo['path'].'/';
  8756. }
  8757. }
  8758. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8759. if (!is_dir($filepath)) {
  8760. $dir = '/';
  8761. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8762. }
  8763. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8764. if (!empty($title)) {
  8765. $title = api_replace_dangerous_char(stripslashes($title));
  8766. } else {
  8767. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8768. }
  8769. $title = disable_dangerous_file($title);
  8770. $filename = $title;
  8771. $content = !empty($content) ? $content : $_POST['content_lp'];
  8772. $tmpFileName = $filename;
  8773. $i = 0;
  8774. while (file_exists($filepath.$tmpFileName.'.html')) {
  8775. $tmpFileName = $filename.'_'.++$i;
  8776. }
  8777. $filename = $tmpFileName.'.html';
  8778. $content = stripslashes($content);
  8779. if (file_exists($filepath.$filename)) {
  8780. return 0;
  8781. }
  8782. $putContent = file_put_contents($filepath.$filename, $content);
  8783. if ($putContent === false) {
  8784. return 0;
  8785. }
  8786. $fileSize = filesize($filepath.$filename);
  8787. $saveFilePath = $dir.$filename;
  8788. $documentId = add_document(
  8789. $courseInfo,
  8790. $saveFilePath,
  8791. 'file',
  8792. $fileSize,
  8793. $tmpFileName,
  8794. '',
  8795. 0, //readonly
  8796. true,
  8797. null,
  8798. $sessionId,
  8799. $creatorId
  8800. );
  8801. if (!$documentId) {
  8802. return 0;
  8803. }
  8804. api_item_property_update(
  8805. $courseInfo,
  8806. TOOL_DOCUMENT,
  8807. $documentId,
  8808. 'DocumentAdded',
  8809. $creatorId,
  8810. null,
  8811. null,
  8812. null,
  8813. null,
  8814. $sessionId
  8815. );
  8816. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8817. $newTitle = $originalTitle;
  8818. if ($newComment || $newTitle) {
  8819. $em = Database::getManager();
  8820. /** @var CDocument $doc */
  8821. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8822. if ($newComment) {
  8823. $doc->setComment($newComment);
  8824. }
  8825. if ($newTitle) {
  8826. $doc->setTitle($newTitle);
  8827. }
  8828. $em->persist($doc);
  8829. $em->flush();
  8830. }
  8831. return $documentId;
  8832. }
  8833. /**
  8834. * Return HTML form to add/edit a link item.
  8835. *
  8836. * @param string $action (add/edit)
  8837. * @param int $id Item ID if exists
  8838. * @param mixed $extra_info
  8839. *
  8840. * @throws Exception
  8841. * @throws HTML_QuickForm_Error
  8842. *
  8843. * @return string HTML form
  8844. */
  8845. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8846. {
  8847. $course_id = api_get_course_int_id();
  8848. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8849. $tbl_link = Database::get_course_table(TABLE_LINK);
  8850. $item_title = '';
  8851. $item_description = '';
  8852. $item_url = '';
  8853. if ($id != 0 && is_array($extra_info)) {
  8854. $item_title = stripslashes($extra_info['title']);
  8855. $item_description = stripslashes($extra_info['description']);
  8856. $item_url = stripslashes($extra_info['url']);
  8857. } elseif (is_numeric($extra_info)) {
  8858. $extra_info = (int) $extra_info;
  8859. $sql = "SELECT title, description, url
  8860. FROM $tbl_link
  8861. WHERE c_id = $course_id AND iid = $extra_info";
  8862. $result = Database::query($sql);
  8863. $row = Database::fetch_array($result);
  8864. $item_title = $row['title'];
  8865. $item_description = $row['description'];
  8866. $item_url = $row['url'];
  8867. }
  8868. $form = new FormValidator(
  8869. 'edit_link',
  8870. 'POST',
  8871. $this->getCurrentBuildingModeURL()
  8872. );
  8873. $defaults = [];
  8874. $parent = 0;
  8875. if ($id != 0 && is_array($extra_info)) {
  8876. $parent = $extra_info['parent_item_id'];
  8877. }
  8878. $sql = "SELECT * FROM $tbl_lp_item
  8879. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8880. $result = Database::query($sql);
  8881. $arrLP = [];
  8882. while ($row = Database::fetch_array($result)) {
  8883. $arrLP[] = [
  8884. 'id' => $row['id'],
  8885. 'item_type' => $row['item_type'],
  8886. 'title' => $row['title'],
  8887. 'path' => $row['path'],
  8888. 'description' => $row['description'],
  8889. 'parent_item_id' => $row['parent_item_id'],
  8890. 'previous_item_id' => $row['previous_item_id'],
  8891. 'next_item_id' => $row['next_item_id'],
  8892. 'display_order' => $row['display_order'],
  8893. 'max_score' => $row['max_score'],
  8894. 'min_score' => $row['min_score'],
  8895. 'mastery_score' => $row['mastery_score'],
  8896. 'prerequisite' => $row['prerequisite'],
  8897. ];
  8898. }
  8899. $this->tree_array($arrLP);
  8900. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8901. unset($this->arrMenu);
  8902. if ($action == 'add') {
  8903. $legend = get_lang('CreateTheLink');
  8904. } elseif ($action == 'move') {
  8905. $legend = get_lang('MoveCurrentLink');
  8906. } else {
  8907. $legend = get_lang('EditCurrentLink');
  8908. }
  8909. $form->addHeader($legend);
  8910. if ($action != 'move') {
  8911. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8912. $defaults['title'] = $item_title;
  8913. }
  8914. $selectParent = $form->addSelect(
  8915. 'parent',
  8916. get_lang('Parent'),
  8917. [],
  8918. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8919. );
  8920. $selectParent->addOption($this->name, 0);
  8921. $arrHide = [
  8922. $id,
  8923. ];
  8924. $parent_item_id = Session::read('parent_item_id', 0);
  8925. for ($i = 0; $i < count($arrLP); $i++) {
  8926. if ($action != 'add') {
  8927. if (
  8928. ($arrLP[$i]['item_type'] == 'dir') &&
  8929. !in_array($arrLP[$i]['id'], $arrHide) &&
  8930. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8931. ) {
  8932. $selectParent->addOption(
  8933. $arrLP[$i]['title'],
  8934. $arrLP[$i]['id'],
  8935. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8936. );
  8937. if ($parent == $arrLP[$i]['id']) {
  8938. $selectParent->setSelected($arrLP[$i]['id']);
  8939. }
  8940. } else {
  8941. $arrHide[] = $arrLP[$i]['id'];
  8942. }
  8943. } else {
  8944. if ($arrLP[$i]['item_type'] == 'dir') {
  8945. $selectParent->addOption(
  8946. $arrLP[$i]['title'],
  8947. $arrLP[$i]['id'],
  8948. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8949. );
  8950. if ($parent_item_id == $arrLP[$i]['id']) {
  8951. $selectParent->setSelected($arrLP[$i]['id']);
  8952. }
  8953. }
  8954. }
  8955. }
  8956. if (is_array($arrLP)) {
  8957. reset($arrLP);
  8958. }
  8959. $selectPrevious = $form->addSelect(
  8960. 'previous',
  8961. get_lang('Position'),
  8962. [],
  8963. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8964. );
  8965. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8966. for ($i = 0; $i < count($arrLP); $i++) {
  8967. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8968. $selectPrevious->addOption(
  8969. $arrLP[$i]['title'],
  8970. $arrLP[$i]['id']
  8971. );
  8972. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8973. $selectPrevious->setSelected($arrLP[$i]['id']);
  8974. } elseif ($action == 'add') {
  8975. $selectPrevious->setSelected($arrLP[$i]['id']);
  8976. }
  8977. }
  8978. }
  8979. if ($action != 'move') {
  8980. $urlAttributes = ['class' => 'learnpath_item_form'];
  8981. if (is_numeric($extra_info)) {
  8982. $urlAttributes['disabled'] = 'disabled';
  8983. }
  8984. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8985. $defaults['url'] = $item_url;
  8986. $arrHide = [];
  8987. for ($i = 0; $i < count($arrLP); $i++) {
  8988. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8989. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8990. }
  8991. }
  8992. }
  8993. if ($action == 'add') {
  8994. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8995. } else {
  8996. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8997. }
  8998. if ($action == 'move') {
  8999. $form->addHidden('title', $item_title);
  9000. $form->addHidden('description', $item_description);
  9001. }
  9002. if (is_numeric($extra_info)) {
  9003. $form->addHidden('path', $extra_info);
  9004. } elseif (is_array($extra_info)) {
  9005. $form->addHidden('path', $extra_info['path']);
  9006. }
  9007. $form->addHidden('type', TOOL_LINK);
  9008. $form->addHidden('post_time', time());
  9009. $form->setDefaults($defaults);
  9010. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  9011. }
  9012. /**
  9013. * Return HTML form to add/edit a student publication (work).
  9014. *
  9015. * @param string $action
  9016. * @param int $id Item ID if already exists
  9017. * @param string $extra_info
  9018. *
  9019. * @throws Exception
  9020. *
  9021. * @return string HTML form
  9022. */
  9023. public function display_student_publication_form(
  9024. $action = 'add',
  9025. $id = 0,
  9026. $extra_info = ''
  9027. ) {
  9028. $course_id = api_get_course_int_id();
  9029. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9030. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  9031. $item_title = get_lang('Student_publication');
  9032. if ($id != 0 && is_array($extra_info)) {
  9033. $item_title = stripslashes($extra_info['title']);
  9034. $item_description = stripslashes($extra_info['description']);
  9035. } elseif (is_numeric($extra_info)) {
  9036. $extra_info = (int) $extra_info;
  9037. $sql = "SELECT title, description
  9038. FROM $tbl_publication
  9039. WHERE c_id = $course_id AND id = ".$extra_info;
  9040. $result = Database::query($sql);
  9041. $row = Database::fetch_array($result);
  9042. if ($row) {
  9043. $item_title = $row['title'];
  9044. }
  9045. }
  9046. $parent = 0;
  9047. if ($id != 0 && is_array($extra_info)) {
  9048. $parent = $extra_info['parent_item_id'];
  9049. }
  9050. $sql = "SELECT * FROM $tbl_lp_item
  9051. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9052. $result = Database::query($sql);
  9053. $arrLP = [];
  9054. while ($row = Database::fetch_array($result)) {
  9055. $arrLP[] = [
  9056. 'id' => $row['iid'],
  9057. 'item_type' => $row['item_type'],
  9058. 'title' => $row['title'],
  9059. 'path' => $row['path'],
  9060. 'description' => $row['description'],
  9061. 'parent_item_id' => $row['parent_item_id'],
  9062. 'previous_item_id' => $row['previous_item_id'],
  9063. 'next_item_id' => $row['next_item_id'],
  9064. 'display_order' => $row['display_order'],
  9065. 'max_score' => $row['max_score'],
  9066. 'min_score' => $row['min_score'],
  9067. 'mastery_score' => $row['mastery_score'],
  9068. 'prerequisite' => $row['prerequisite'],
  9069. ];
  9070. }
  9071. $this->tree_array($arrLP);
  9072. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9073. unset($this->arrMenu);
  9074. $form = new FormValidator('frm_student_publication', 'post', '#');
  9075. if ($action == 'add') {
  9076. $form->addHeader(get_lang('Student_publication'));
  9077. } elseif ($action == 'move') {
  9078. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  9079. } else {
  9080. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  9081. }
  9082. if ($action != 'move') {
  9083. $form->addText(
  9084. 'title',
  9085. get_lang('Title'),
  9086. true,
  9087. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  9088. );
  9089. }
  9090. $parentSelect = $form->addSelect(
  9091. 'parent',
  9092. get_lang('Parent'),
  9093. ['0' => $this->name],
  9094. [
  9095. 'onchange' => 'javascript: load_cbo(this.value);',
  9096. 'class' => 'learnpath_item_form',
  9097. 'id' => 'idParent',
  9098. ]
  9099. );
  9100. $arrHide = [$id];
  9101. for ($i = 0; $i < count($arrLP); $i++) {
  9102. if ($action != 'add') {
  9103. if (
  9104. ($arrLP[$i]['item_type'] == 'dir') &&
  9105. !in_array($arrLP[$i]['id'], $arrHide) &&
  9106. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  9107. ) {
  9108. $parentSelect->addOption(
  9109. $arrLP[$i]['title'],
  9110. $arrLP[$i]['id'],
  9111. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9112. );
  9113. if ($parent == $arrLP[$i]['id']) {
  9114. $parentSelect->setSelected($arrLP[$i]['id']);
  9115. }
  9116. } else {
  9117. $arrHide[] = $arrLP[$i]['id'];
  9118. }
  9119. } else {
  9120. if ($arrLP[$i]['item_type'] == 'dir') {
  9121. $parentSelect->addOption(
  9122. $arrLP[$i]['title'],
  9123. $arrLP[$i]['id'],
  9124. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9125. );
  9126. if ($parent == $arrLP[$i]['id']) {
  9127. $parentSelect->setSelected($arrLP[$i]['id']);
  9128. }
  9129. }
  9130. }
  9131. }
  9132. if (is_array($arrLP)) {
  9133. reset($arrLP);
  9134. }
  9135. $previousSelect = $form->addSelect(
  9136. 'previous',
  9137. get_lang('Position'),
  9138. ['0' => get_lang('FirstPosition')],
  9139. ['id' => 'previous', 'class' => 'learnpath_item_form']
  9140. );
  9141. for ($i = 0; $i < count($arrLP); $i++) {
  9142. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  9143. $previousSelect->addOption(
  9144. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  9145. $arrLP[$i]['id']
  9146. );
  9147. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9148. $previousSelect->setSelected($arrLP[$i]['id']);
  9149. } elseif ($action == 'add') {
  9150. $previousSelect->setSelected($arrLP[$i]['id']);
  9151. }
  9152. }
  9153. }
  9154. if ($action == 'add') {
  9155. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  9156. } else {
  9157. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  9158. }
  9159. if ($action == 'move') {
  9160. $form->addHidden('title', $item_title);
  9161. $form->addHidden('description', $item_description);
  9162. }
  9163. if (is_numeric($extra_info)) {
  9164. $form->addHidden('path', $extra_info);
  9165. } elseif (is_array($extra_info)) {
  9166. $form->addHidden('path', $extra_info['path']);
  9167. }
  9168. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  9169. $form->addHidden('post_time', time());
  9170. $form->setDefaults(['title' => $item_title]);
  9171. $return = '<div class="sectioncomment">';
  9172. $return .= $form->returnForm();
  9173. $return .= '</div>';
  9174. return $return;
  9175. }
  9176. /**
  9177. * Displays the menu for manipulating a step.
  9178. *
  9179. * @param id $item_id
  9180. * @param string $item_type
  9181. *
  9182. * @return string
  9183. */
  9184. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  9185. {
  9186. $_course = api_get_course_info();
  9187. $course_code = api_get_course_id();
  9188. $return = '<div class="actions">';
  9189. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9190. $item_id = (int) $item_id;
  9191. $sql = "SELECT * FROM $tbl_lp_item
  9192. WHERE iid = ".$item_id;
  9193. $result = Database::query($sql);
  9194. $row = Database::fetch_assoc($result);
  9195. $audio_player = null;
  9196. // We display an audio player if needed.
  9197. if (!empty($row['audio'])) {
  9198. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9199. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9200. .'<audio src="'.$webAudioPath.'" controls>'
  9201. .'</div><br>';
  9202. }
  9203. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9204. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9205. $return .= Display::url(
  9206. Display::return_icon(
  9207. 'edit.png',
  9208. get_lang('Edit'),
  9209. [],
  9210. ICON_SIZE_SMALL
  9211. ),
  9212. $url.'&action=edit_item&path_item='.$row['path']
  9213. );
  9214. $return .= Display::url(
  9215. Display::return_icon(
  9216. 'move.png',
  9217. get_lang('Move'),
  9218. [],
  9219. ICON_SIZE_SMALL
  9220. ),
  9221. $url.'&action=move_item'
  9222. );
  9223. }
  9224. // Commented for now as prerequisites cannot be added to chapters.
  9225. if ($item_type != 'dir') {
  9226. $return .= Display::url(
  9227. Display::return_icon(
  9228. 'accept.png',
  9229. get_lang('LearnpathPrerequisites'),
  9230. [],
  9231. ICON_SIZE_SMALL
  9232. ),
  9233. $url.'&action=edit_item_prereq'
  9234. );
  9235. }
  9236. $return .= Display::url(
  9237. Display::return_icon(
  9238. 'delete.png',
  9239. get_lang('Delete'),
  9240. [],
  9241. ICON_SIZE_SMALL
  9242. ),
  9243. $url.'&action=delete_item'
  9244. );
  9245. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  9246. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9247. if (empty($documentData)) {
  9248. // Try with iid
  9249. $table = Database::get_course_table(TABLE_DOCUMENT);
  9250. $sql = "SELECT path FROM $table
  9251. WHERE
  9252. c_id = ".api_get_course_int_id()." AND
  9253. iid = ".$row['path']." AND
  9254. path NOT LIKE '%_DELETED_%'";
  9255. $result = Database::query($sql);
  9256. $documentData = Database::fetch_array($result);
  9257. if ($documentData) {
  9258. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  9259. }
  9260. }
  9261. if (isset($documentData['absolute_path_from_document'])) {
  9262. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  9263. }
  9264. }
  9265. $return .= '</div>';
  9266. if (!empty($audio_player)) {
  9267. $return .= $audio_player;
  9268. }
  9269. return $return;
  9270. }
  9271. /**
  9272. * Creates the javascript needed for filling up the checkboxes without page reload.
  9273. *
  9274. * @return string
  9275. */
  9276. public function get_js_dropdown_array()
  9277. {
  9278. $course_id = api_get_course_int_id();
  9279. $return = 'var child_name = new Array();'."\n";
  9280. $return .= 'var child_value = new Array();'."\n\n";
  9281. $return .= 'child_name[0] = new Array();'."\n";
  9282. $return .= 'child_value[0] = new Array();'."\n\n";
  9283. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9284. $sql = "SELECT * FROM ".$tbl_lp_item."
  9285. WHERE
  9286. c_id = $course_id AND
  9287. lp_id = ".$this->lp_id." AND
  9288. parent_item_id = 0
  9289. ORDER BY display_order ASC";
  9290. $res_zero = Database::query($sql);
  9291. $i = 0;
  9292. while ($row_zero = Database::fetch_array($res_zero)) {
  9293. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9294. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9295. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9296. }
  9297. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9298. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9299. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9300. }
  9301. }
  9302. $return .= "\n";
  9303. $sql = "SELECT * FROM $tbl_lp_item
  9304. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9305. $res = Database::query($sql);
  9306. while ($row = Database::fetch_array($res)) {
  9307. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9308. WHERE
  9309. c_id = ".$course_id." AND
  9310. parent_item_id = ".$row['iid']."
  9311. ORDER BY display_order ASC";
  9312. $res_parent = Database::query($sql_parent);
  9313. $i = 0;
  9314. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9315. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9316. while ($row_parent = Database::fetch_array($res_parent)) {
  9317. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9318. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9319. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9320. }
  9321. $return .= "\n";
  9322. }
  9323. $return .= "
  9324. function load_cbo(id) {
  9325. if (!id) {
  9326. return false;
  9327. }
  9328. var cbo = document.getElementById('previous');
  9329. for(var i = cbo.length - 1; i > 0; i--) {
  9330. cbo.options[i] = null;
  9331. }
  9332. var k=0;
  9333. for(var i = 1; i <= child_name[id].length; i++){
  9334. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9335. option.style.paddingLeft = '40px';
  9336. cbo.options[i] = option;
  9337. k = i;
  9338. }
  9339. cbo.options[k].selected = true;
  9340. $('#previous').selectpicker('refresh');
  9341. }";
  9342. return $return;
  9343. }
  9344. /**
  9345. * Display the form to allow moving an item.
  9346. *
  9347. * @param int $item_id Item ID
  9348. *
  9349. * @throws Exception
  9350. * @throws HTML_QuickForm_Error
  9351. *
  9352. * @return string HTML form
  9353. */
  9354. public function display_move_item($item_id)
  9355. {
  9356. $return = '';
  9357. if (is_numeric($item_id)) {
  9358. $item_id = (int) $item_id;
  9359. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9360. $sql = "SELECT * FROM $tbl_lp_item
  9361. WHERE iid = $item_id";
  9362. $res = Database::query($sql);
  9363. $row = Database::fetch_array($res);
  9364. switch ($row['item_type']) {
  9365. case 'dir':
  9366. case 'asset':
  9367. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9368. $return .= $this->display_item_form(
  9369. $row['item_type'],
  9370. get_lang('MoveCurrentChapter'),
  9371. 'move',
  9372. $item_id,
  9373. $row
  9374. );
  9375. break;
  9376. case TOOL_DOCUMENT:
  9377. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9378. $return .= $this->display_document_form('move', $item_id, $row);
  9379. break;
  9380. case TOOL_LINK:
  9381. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9382. $return .= $this->display_link_form('move', $item_id, $row);
  9383. break;
  9384. case TOOL_HOTPOTATOES:
  9385. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9386. $return .= $this->display_link_form('move', $item_id, $row);
  9387. break;
  9388. case TOOL_QUIZ:
  9389. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9390. $return .= $this->display_quiz_form('move', $item_id, $row);
  9391. break;
  9392. case TOOL_STUDENTPUBLICATION:
  9393. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9394. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9395. break;
  9396. case TOOL_FORUM:
  9397. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9398. $return .= $this->display_forum_form('move', $item_id, $row);
  9399. break;
  9400. case TOOL_THREAD:
  9401. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9402. $return .= $this->display_forum_form('move', $item_id, $row);
  9403. break;
  9404. }
  9405. }
  9406. return $return;
  9407. }
  9408. /**
  9409. * Return HTML form to allow prerequisites selection.
  9410. *
  9411. * @todo use FormValidator
  9412. *
  9413. * @param int Item ID
  9414. *
  9415. * @return string HTML form
  9416. */
  9417. public function display_item_prerequisites_form($item_id = 0)
  9418. {
  9419. $course_id = api_get_course_int_id();
  9420. $item_id = (int) $item_id;
  9421. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9422. /* Current prerequisite */
  9423. $sql = "SELECT * FROM $tbl_lp_item
  9424. WHERE iid = $item_id";
  9425. $result = Database::query($sql);
  9426. $row = Database::fetch_array($result);
  9427. $prerequisiteId = $row['prerequisite'];
  9428. $return = '<legend>';
  9429. $return .= get_lang('AddEditPrerequisites');
  9430. $return .= '</legend>';
  9431. $return .= '<form method="POST">';
  9432. $return .= '<div class="table-responsive">';
  9433. $return .= '<table class="table table-hover">';
  9434. $return .= '<thead>';
  9435. $return .= '<tr>';
  9436. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9437. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9438. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9439. $return .= '</tr>';
  9440. $return .= '</thead>';
  9441. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9442. $return .= '<tbody>';
  9443. $return .= '<tr>';
  9444. $return .= '<td colspan="3">';
  9445. $return .= '<div class="radio learnpath"><label for="idNone">';
  9446. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9447. $return .= get_lang('None').'</label>';
  9448. $return .= '</div>';
  9449. $return .= '</tr>';
  9450. $sql = "SELECT * FROM $tbl_lp_item
  9451. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9452. $result = Database::query($sql);
  9453. $arrLP = [];
  9454. $selectedMinScore = [];
  9455. $selectedMaxScore = [];
  9456. $masteryScore = [];
  9457. while ($row = Database::fetch_array($result)) {
  9458. if ($row['iid'] == $item_id) {
  9459. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9460. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9461. }
  9462. $masteryScore[$row['iid']] = $row['mastery_score'];
  9463. $arrLP[] = [
  9464. 'id' => $row['iid'],
  9465. 'item_type' => $row['item_type'],
  9466. 'title' => $row['title'],
  9467. 'ref' => $row['ref'],
  9468. 'description' => $row['description'],
  9469. 'parent_item_id' => $row['parent_item_id'],
  9470. 'previous_item_id' => $row['previous_item_id'],
  9471. 'next_item_id' => $row['next_item_id'],
  9472. 'max_score' => $row['max_score'],
  9473. 'min_score' => $row['min_score'],
  9474. 'mastery_score' => $row['mastery_score'],
  9475. 'prerequisite' => $row['prerequisite'],
  9476. 'display_order' => $row['display_order'],
  9477. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9478. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9479. ];
  9480. }
  9481. $this->tree_array($arrLP);
  9482. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9483. unset($this->arrMenu);
  9484. for ($i = 0; $i < count($arrLP); $i++) {
  9485. $item = $arrLP[$i];
  9486. if ($item['id'] == $item_id) {
  9487. break;
  9488. }
  9489. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9490. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9491. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  9492. $return .= '<tr>';
  9493. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9494. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9495. $return .= '<label for="id'.$item['id'].'">';
  9496. $return .= '<input'.(in_array($prerequisiteId, [$item['id'], $item['ref']]) ? ' checked="checked" ' : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id'].'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  9497. $icon_name = str_replace(' ', '', $item['item_type']);
  9498. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9499. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9500. } else {
  9501. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9502. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9503. } else {
  9504. $return .= Display::return_icon('folder_document.png');
  9505. }
  9506. }
  9507. $return .= $item['title'].'</label>';
  9508. $return .= '</div>';
  9509. $return .= '</td>';
  9510. if ($item['item_type'] == TOOL_QUIZ) {
  9511. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9512. $lpItemObj = new LpItem($course_id, $item['id']);
  9513. $exercise = new Exercise($course_id);
  9514. $exercise->read($lpItemObj->path);
  9515. $lpItemObj->max_score = $exercise->get_max_score();
  9516. $lpItemObj->update();
  9517. $item['max_score'] = $lpItemObj->max_score;
  9518. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  9519. // Backwards compatibility with 1.9.x use mastery_score as min value
  9520. $selectedMinScoreValue = $masteryScoreAsMinValue;
  9521. }
  9522. $return .= '<td>';
  9523. $return .= '<input
  9524. class="form-control"
  9525. size="4" maxlength="3"
  9526. name="min_'.$item['id'].'"
  9527. type="number"
  9528. min="0"
  9529. step="1"
  9530. max="'.$item['max_score'].'"
  9531. value="'.$selectedMinScoreValue.'"
  9532. />';
  9533. $return .= '</td>';
  9534. $return .= '<td>';
  9535. $return .= '<input
  9536. class="form-control"
  9537. size="4"
  9538. maxlength="3"
  9539. name="max_'.$item['id'].'"
  9540. type="number"
  9541. min="0"
  9542. step="1"
  9543. max="'.$item['max_score'].'"
  9544. value="'.$selectedMaxScoreValue.'"
  9545. />';
  9546. $return .= '</td>';
  9547. }
  9548. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9549. $return .= '<td>';
  9550. $return .= '<input
  9551. size="4"
  9552. maxlength="3"
  9553. name="min_'.$item['id'].'"
  9554. type="number"
  9555. min="0"
  9556. step="1"
  9557. max="'.$item['max_score'].'"
  9558. value="'.$selectedMinScoreValue.'"
  9559. />';
  9560. $return .= '</td>';
  9561. $return .= '<td>';
  9562. $return .= '<input
  9563. size="4"
  9564. maxlength="3"
  9565. name="max_'.$item['id'].'"
  9566. type="number"
  9567. min="0"
  9568. step="1"
  9569. max="'.$item['max_score'].'"
  9570. value="'.$selectedMaxScoreValue.'"
  9571. />';
  9572. $return .= '</td>';
  9573. }
  9574. $return .= '</tr>';
  9575. }
  9576. $return .= '<tr>';
  9577. $return .= '</tr>';
  9578. $return .= '</tbody>';
  9579. $return .= '</table>';
  9580. $return .= '</div>';
  9581. $return .= '<div class="form-group">';
  9582. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9583. get_lang('ModifyPrerequisites').'</button>';
  9584. $return .= '</form>';
  9585. return $return;
  9586. }
  9587. /**
  9588. * Return HTML list to allow prerequisites selection for lp.
  9589. *
  9590. * @return string HTML form
  9591. */
  9592. public function display_lp_prerequisites_list()
  9593. {
  9594. $course_id = api_get_course_int_id();
  9595. $lp_id = $this->lp_id;
  9596. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9597. // get current prerequisite
  9598. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9599. $result = Database::query($sql);
  9600. $row = Database::fetch_array($result);
  9601. $prerequisiteId = $row['prerequisite'];
  9602. $session_id = api_get_session_id();
  9603. $session_condition = api_get_session_condition($session_id, true, true);
  9604. $sql = "SELECT * FROM $tbl_lp
  9605. WHERE c_id = $course_id $session_condition
  9606. ORDER BY display_order ";
  9607. $rs = Database::query($sql);
  9608. $return = '';
  9609. $return .= '<select name="prerequisites" class="form-control">';
  9610. $return .= '<option value="0">'.get_lang('None').'</option>';
  9611. if (Database::num_rows($rs) > 0) {
  9612. while ($row = Database::fetch_array($rs)) {
  9613. if ($row['id'] == $lp_id) {
  9614. continue;
  9615. }
  9616. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9617. }
  9618. }
  9619. $return .= '</select>';
  9620. return $return;
  9621. }
  9622. /**
  9623. * Creates a list with all the documents in it.
  9624. *
  9625. * @param bool $showInvisibleFiles
  9626. *
  9627. * @throws Exception
  9628. * @throws HTML_QuickForm_Error
  9629. *
  9630. * @return string
  9631. */
  9632. public function get_documents($showInvisibleFiles = false)
  9633. {
  9634. $course_info = api_get_course_info();
  9635. $sessionId = api_get_session_id();
  9636. $documentTree = DocumentManager::get_document_preview(
  9637. $course_info,
  9638. $this->lp_id,
  9639. null,
  9640. $sessionId,
  9641. true,
  9642. null,
  9643. null,
  9644. $showInvisibleFiles,
  9645. true
  9646. );
  9647. $headers = [
  9648. get_lang('Files'),
  9649. get_lang('CreateTheDocument'),
  9650. get_lang('CreateReadOutText'),
  9651. get_lang('Upload'),
  9652. ];
  9653. $form = new FormValidator(
  9654. 'form_upload',
  9655. 'POST',
  9656. $this->getCurrentBuildingModeURL(),
  9657. '',
  9658. ['enctype' => 'multipart/form-data']
  9659. );
  9660. $folders = DocumentManager::get_all_document_folders(
  9661. api_get_course_info(),
  9662. 0,
  9663. true
  9664. );
  9665. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9666. DocumentManager::build_directory_selector(
  9667. $folders,
  9668. $lpPathInfo['id'],
  9669. [],
  9670. true,
  9671. $form,
  9672. 'directory_parent_id'
  9673. );
  9674. $group = [
  9675. $form->createElement(
  9676. 'radio',
  9677. 'if_exists',
  9678. get_lang('UplWhatIfFileExists'),
  9679. get_lang('UplDoNothing'),
  9680. 'nothing'
  9681. ),
  9682. $form->createElement(
  9683. 'radio',
  9684. 'if_exists',
  9685. null,
  9686. get_lang('UplOverwriteLong'),
  9687. 'overwrite'
  9688. ),
  9689. $form->createElement(
  9690. 'radio',
  9691. 'if_exists',
  9692. null,
  9693. get_lang('UplRenameLong'),
  9694. 'rename'
  9695. ),
  9696. ];
  9697. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9698. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9699. $defaultFileExistsOption = 'rename';
  9700. if (!empty($fileExistsOption)) {
  9701. $defaultFileExistsOption = $fileExistsOption;
  9702. }
  9703. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9704. // Check box options
  9705. $form->addElement(
  9706. 'checkbox',
  9707. 'unzip',
  9708. get_lang('Options'),
  9709. get_lang('Uncompress')
  9710. );
  9711. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9712. $form->addMultipleUpload($url);
  9713. $new = $this->display_document_form('add', 0);
  9714. $frmReadOutText = $this->displayFrmReadOutText('add');
  9715. $tabs = Display::tabs(
  9716. $headers,
  9717. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9718. 'subtab'
  9719. );
  9720. return $tabs;
  9721. }
  9722. /**
  9723. * Creates a list with all the exercises (quiz) in it.
  9724. *
  9725. * @return string
  9726. */
  9727. public function get_exercises()
  9728. {
  9729. $course_id = api_get_course_int_id();
  9730. $session_id = api_get_session_id();
  9731. $userInfo = api_get_user_info();
  9732. // New for hotpotatoes.
  9733. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9734. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9735. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9736. $condition_session = api_get_session_condition($session_id, true, true);
  9737. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9738. $activeCondition = ' active <> -1 ';
  9739. if ($setting) {
  9740. $activeCondition = ' active = 1 ';
  9741. }
  9742. $sql_quiz = "SELECT * FROM $tbl_quiz
  9743. WHERE c_id = $course_id AND $activeCondition $condition_session
  9744. ORDER BY title ASC";
  9745. $sql_hot = "SELECT * FROM $tbl_doc
  9746. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9747. ORDER BY id ASC";
  9748. $res_quiz = Database::query($sql_quiz);
  9749. $res_hot = Database::query($sql_hot);
  9750. $return = '<ul class="lp_resource">';
  9751. $return .= '<li class="lp_resource_element">';
  9752. $return .= Display::return_icon('new_exercice.png');
  9753. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9754. get_lang('NewExercise').'</a>';
  9755. $return .= '</li>';
  9756. $previewIcon = Display::return_icon(
  9757. 'preview_view.png',
  9758. get_lang('Preview')
  9759. );
  9760. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9761. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9762. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9763. // Display hotpotatoes
  9764. while ($row_hot = Database::fetch_array($res_hot)) {
  9765. $link = Display::url(
  9766. $previewIcon,
  9767. $exerciseUrl.'&file='.$row_hot['path'],
  9768. ['target' => '_blank']
  9769. );
  9770. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9771. $return .= '<a class="moved" href="#">';
  9772. $return .= Display::return_icon(
  9773. 'move_everywhere.png',
  9774. get_lang('Move'),
  9775. [],
  9776. ICON_SIZE_TINY
  9777. );
  9778. $return .= '</a> ';
  9779. $return .= Display::return_icon('hotpotatoes_s.png');
  9780. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9781. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9782. $return .= '</li>';
  9783. }
  9784. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9785. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9786. $title = strip_tags(
  9787. api_html_entity_decode($row_quiz['title'])
  9788. );
  9789. $visibility = api_get_item_visibility(
  9790. ['real_id' => $course_id],
  9791. TOOL_QUIZ,
  9792. $row_quiz['iid'],
  9793. $session_id
  9794. );
  9795. $link = Display::url(
  9796. $previewIcon,
  9797. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9798. ['target' => '_blank']
  9799. );
  9800. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9801. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9802. $return .= $quizIcon;
  9803. $sessionStar = api_get_session_image(
  9804. $row_quiz['session_id'],
  9805. $userInfo['status']
  9806. );
  9807. $return .= Display::url(
  9808. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9809. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9810. [
  9811. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9812. ]
  9813. );
  9814. $return .= '</li>';
  9815. }
  9816. $return .= '</ul>';
  9817. return $return;
  9818. }
  9819. /**
  9820. * Creates a list with all the links in it.
  9821. *
  9822. * @return string
  9823. */
  9824. public function get_links()
  9825. {
  9826. $selfUrl = api_get_self();
  9827. $courseIdReq = api_get_cidreq();
  9828. $course = api_get_course_info();
  9829. $userInfo = api_get_user_info();
  9830. $course_id = $course['real_id'];
  9831. $tbl_link = Database::get_course_table(TABLE_LINK);
  9832. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9833. $moveEverywhereIcon = Display::return_icon(
  9834. 'move_everywhere.png',
  9835. get_lang('Move'),
  9836. [],
  9837. ICON_SIZE_TINY
  9838. );
  9839. $session_id = api_get_session_id();
  9840. $condition_session = api_get_session_condition(
  9841. $session_id,
  9842. true,
  9843. true,
  9844. 'link.session_id'
  9845. );
  9846. $sql = "SELECT
  9847. link.id as link_id,
  9848. link.title as link_title,
  9849. link.session_id as link_session_id,
  9850. link.category_id as category_id,
  9851. link_category.category_title as category_title
  9852. FROM $tbl_link as link
  9853. LEFT JOIN $linkCategoryTable as link_category
  9854. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9855. WHERE link.c_id = $course_id $condition_session
  9856. ORDER BY link_category.category_title ASC, link.title ASC";
  9857. $result = Database::query($sql);
  9858. $categorizedLinks = [];
  9859. $categories = [];
  9860. while ($link = Database::fetch_array($result)) {
  9861. if (!$link['category_id']) {
  9862. $link['category_title'] = get_lang('Uncategorized');
  9863. }
  9864. $categories[$link['category_id']] = $link['category_title'];
  9865. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9866. }
  9867. $linksHtmlCode =
  9868. '<script>
  9869. function toggle_tool(tool, id) {
  9870. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9871. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9872. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9873. } else {
  9874. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9875. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9876. }
  9877. }
  9878. </script>
  9879. <ul class="lp_resource">
  9880. <li class="lp_resource_element">
  9881. '.Display::return_icon('linksnew.gif').'
  9882. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9883. get_lang('LinkAdd').'
  9884. </a>
  9885. </li>';
  9886. foreach ($categorizedLinks as $categoryId => $links) {
  9887. $linkNodes = null;
  9888. foreach ($links as $key => $linkInfo) {
  9889. $title = $linkInfo['link_title'];
  9890. $linkSessionId = $linkInfo['link_session_id'];
  9891. $link = Display::url(
  9892. Display::return_icon('preview_view.png', get_lang('Preview')),
  9893. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9894. ['target' => '_blank']
  9895. );
  9896. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9897. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9898. $linkNodes .=
  9899. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9900. <a class="moved" href="#">'.
  9901. $moveEverywhereIcon.
  9902. '</a>
  9903. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9904. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9905. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9906. Security::remove_XSS($title).$sessionStar.$link.
  9907. '</a>
  9908. </li>';
  9909. }
  9910. }
  9911. $linksHtmlCode .=
  9912. '<li>
  9913. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9914. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9915. align="absbottom" />
  9916. </a>
  9917. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9918. </li>
  9919. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9920. }
  9921. $linksHtmlCode .= '</ul>';
  9922. return $linksHtmlCode;
  9923. }
  9924. /**
  9925. * Creates a list with all the student publications in it.
  9926. *
  9927. * @return string
  9928. */
  9929. public function get_student_publications()
  9930. {
  9931. $return = '<ul class="lp_resource">';
  9932. $return .= '<li class="lp_resource_element">';
  9933. $return .= Display::return_icon('works_new.gif');
  9934. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9935. get_lang('AddAssignmentPage').'</a>';
  9936. $return .= '</li>';
  9937. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9938. $works = getWorkListTeacher(0, 100, null, null, null);
  9939. if (!empty($works)) {
  9940. foreach ($works as $work) {
  9941. $link = Display::url(
  9942. Display::return_icon('preview_view.png', get_lang('Preview')),
  9943. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9944. ['target' => '_blank']
  9945. );
  9946. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9947. $return .= '<a class="moved" href="#">';
  9948. $return .= Display::return_icon(
  9949. 'move_everywhere.png',
  9950. get_lang('Move'),
  9951. [],
  9952. ICON_SIZE_TINY
  9953. );
  9954. $return .= '</a> ';
  9955. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9956. $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.'">'.
  9957. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9958. </a>';
  9959. $return .= '</li>';
  9960. }
  9961. }
  9962. $return .= '</ul>';
  9963. return $return;
  9964. }
  9965. /**
  9966. * Creates a list with all the forums in it.
  9967. *
  9968. * @return string
  9969. */
  9970. public function get_forums()
  9971. {
  9972. require_once '../forum/forumfunction.inc.php';
  9973. $forumCategories = get_forum_categories();
  9974. $forumsInNoCategory = get_forums_in_category(0);
  9975. if (!empty($forumsInNoCategory)) {
  9976. $forumCategories = array_merge(
  9977. $forumCategories,
  9978. [
  9979. [
  9980. 'cat_id' => 0,
  9981. 'session_id' => 0,
  9982. 'visibility' => 1,
  9983. 'cat_comment' => null,
  9984. ],
  9985. ]
  9986. );
  9987. }
  9988. $forumList = get_forums();
  9989. $a_forums = [];
  9990. foreach ($forumCategories as $forumCategory) {
  9991. // The forums in this category.
  9992. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9993. if (!empty($forumsInCategory)) {
  9994. foreach ($forumList as $forum) {
  9995. if (isset($forum['forum_category']) &&
  9996. $forum['forum_category'] == $forumCategory['cat_id']
  9997. ) {
  9998. $a_forums[] = $forum;
  9999. }
  10000. }
  10001. }
  10002. }
  10003. $return = '<ul class="lp_resource">';
  10004. // First add link
  10005. $return .= '<li class="lp_resource_element">';
  10006. $return .= Display::return_icon('new_forum.png');
  10007. $return .= Display::url(
  10008. get_lang('CreateANewForum'),
  10009. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  10010. 'action' => 'add',
  10011. 'content' => 'forum',
  10012. 'lp_id' => $this->lp_id,
  10013. ]),
  10014. ['title' => get_lang('CreateANewForum')]
  10015. );
  10016. $return .= '</li>';
  10017. $return .= '<script>
  10018. function toggle_forum(forum_id) {
  10019. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  10020. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  10021. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  10022. } else {
  10023. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  10024. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  10025. }
  10026. }
  10027. </script>';
  10028. foreach ($a_forums as $forum) {
  10029. if (!empty($forum['forum_id'])) {
  10030. $link = Display::url(
  10031. Display::return_icon('preview_view.png', get_lang('Preview')),
  10032. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  10033. ['target' => '_blank']
  10034. );
  10035. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  10036. $return .= '<a class="moved" href="#">';
  10037. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10038. $return .= ' </a>';
  10039. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  10040. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  10041. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  10042. </a>
  10043. <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">'.
  10044. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  10045. $return .= '</li>';
  10046. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  10047. $a_threads = get_threads($forum['forum_id']);
  10048. if (is_array($a_threads)) {
  10049. foreach ($a_threads as $thread) {
  10050. $link = Display::url(
  10051. Display::return_icon('preview_view.png', get_lang('Preview')),
  10052. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  10053. ['target' => '_blank']
  10054. );
  10055. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  10056. $return .= '&nbsp;<a class="moved" href="#">';
  10057. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10058. $return .= ' </a>';
  10059. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  10060. $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.'">'.
  10061. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  10062. $return .= '</li>';
  10063. }
  10064. }
  10065. $return .= '</div>';
  10066. }
  10067. }
  10068. $return .= '</ul>';
  10069. return $return;
  10070. }
  10071. /**
  10072. * // TODO: The output encoding should be equal to the system encoding.
  10073. *
  10074. * Exports the learning path as a SCORM package. This is the main function that
  10075. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  10076. * whole thing and returns the zip.
  10077. *
  10078. * This method needs to be called in PHP5, as it will fail with non-adequate
  10079. * XML package (like the ones for PHP4), and it is *not* a static method, so
  10080. * you need to call it on a learnpath object.
  10081. *
  10082. * @TODO The method might be redefined later on in the scorm class itself to avoid
  10083. * creating a SCORM structure if there is one already. However, if the initial SCORM
  10084. * path has been modified, it should use the generic method here below.
  10085. *
  10086. * @return string Returns the zip package string, or null if error
  10087. */
  10088. public function scormExport()
  10089. {
  10090. api_set_more_memory_and_time_limits();
  10091. $_course = api_get_course_info();
  10092. $course_id = $_course['real_id'];
  10093. // Create the zip handler (this will remain available throughout the method).
  10094. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  10095. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10096. $temp_dir_short = uniqid('scorm_export', true);
  10097. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  10098. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  10099. $zip_folder = new PclZip($temp_zip_file);
  10100. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  10101. $root_path = $main_path = api_get_path(SYS_PATH);
  10102. $files_cleanup = [];
  10103. // Place to temporarily stash the zip file.
  10104. // create the temp dir if it doesn't exist
  10105. // or do a cleanup before creating the zip file.
  10106. if (!is_dir($temp_zip_dir)) {
  10107. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  10108. } else {
  10109. // Cleanup: Check the temp dir for old files and delete them.
  10110. $handle = opendir($temp_zip_dir);
  10111. while (false !== ($file = readdir($handle))) {
  10112. if ($file != '.' && $file != '..') {
  10113. unlink("$temp_zip_dir/$file");
  10114. }
  10115. }
  10116. closedir($handle);
  10117. }
  10118. $zip_files = $zip_files_abs = $zip_files_dist = [];
  10119. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  10120. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  10121. ) {
  10122. // Remove the possible . at the end of the path.
  10123. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  10124. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  10125. mkdir(
  10126. $dest_path_to_scorm_folder,
  10127. api_get_permissions_for_new_directories(),
  10128. true
  10129. );
  10130. copyr(
  10131. $current_course_path.'/scorm/'.$this->path,
  10132. $dest_path_to_scorm_folder,
  10133. ['imsmanifest'],
  10134. $zip_files
  10135. );
  10136. }
  10137. // Build a dummy imsmanifest structure.
  10138. // Do not add to the zip yet (we still need it).
  10139. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  10140. // Aggregation Model official document, section "2.3 Content Packaging".
  10141. // We are going to build a UTF-8 encoded manifest.
  10142. // Later we will recode it to the desired (and supported) encoding.
  10143. $xmldoc = new DOMDocument('1.0');
  10144. $root = $xmldoc->createElement('manifest');
  10145. $root->setAttribute('identifier', 'SingleCourseManifest');
  10146. $root->setAttribute('version', '1.1');
  10147. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10148. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10149. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10150. $root->setAttribute(
  10151. 'xsi:schemaLocation',
  10152. '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'
  10153. );
  10154. // Build mandatory sub-root container elements.
  10155. $metadata = $xmldoc->createElement('metadata');
  10156. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10157. $metadata->appendChild($md_schema);
  10158. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10159. $metadata->appendChild($md_schemaversion);
  10160. $root->appendChild($metadata);
  10161. $organizations = $xmldoc->createElement('organizations');
  10162. $resources = $xmldoc->createElement('resources');
  10163. // Build the only organization we will use in building our learnpaths.
  10164. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10165. $organization = $xmldoc->createElement('organization');
  10166. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10167. // To set the title of the SCORM entity (=organization), we take the name given
  10168. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10169. // learning path charset) as it is the encoding that defines how it is stored
  10170. // in the database. Then we convert it to HTML entities again as the "&" character
  10171. // alone is not authorized in XML (must be &amp;).
  10172. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10173. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10174. $organization->appendChild($org_title);
  10175. $folder_name = 'document';
  10176. // Removes the learning_path/scorm_folder path when exporting see #4841
  10177. $path_to_remove = '';
  10178. $path_to_replace = '';
  10179. $result = $this->generate_lp_folder($_course);
  10180. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10181. $path_to_remove = 'document'.$result['dir'];
  10182. $path_to_replace = $folder_name.'/';
  10183. }
  10184. // Fixes chamilo scorm exports
  10185. if ($this->ref === 'chamilo_scorm_export') {
  10186. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10187. }
  10188. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10189. $link_updates = [];
  10190. $links_to_create = [];
  10191. foreach ($this->ordered_items as $index => $itemId) {
  10192. /** @var learnpathItem $item */
  10193. $item = $this->items[$itemId];
  10194. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10195. // Get included documents from this item.
  10196. if ($item->type === 'sco') {
  10197. $inc_docs = $item->get_resources_from_source(
  10198. null,
  10199. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10200. );
  10201. } else {
  10202. $inc_docs = $item->get_resources_from_source();
  10203. }
  10204. // Give a child element <item> to the <organization> element.
  10205. $my_item_id = $item->get_id();
  10206. $my_item = $xmldoc->createElement('item');
  10207. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10208. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10209. $my_item->setAttribute('isvisible', 'true');
  10210. // Give a child element <title> to the <item> element.
  10211. $my_title = $xmldoc->createElement(
  10212. 'title',
  10213. htmlspecialchars(
  10214. api_utf8_encode($item->get_title()),
  10215. ENT_QUOTES,
  10216. 'UTF-8'
  10217. )
  10218. );
  10219. $my_item->appendChild($my_title);
  10220. // Give a child element <adlcp:prerequisites> to the <item> element.
  10221. $my_prereqs = $xmldoc->createElement(
  10222. 'adlcp:prerequisites',
  10223. $this->get_scorm_prereq_string($my_item_id)
  10224. );
  10225. $my_prereqs->setAttribute('type', 'aicc_script');
  10226. $my_item->appendChild($my_prereqs);
  10227. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10228. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10229. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10230. //$xmldoc->createElement('adlcp:timelimitaction','');
  10231. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10232. //$xmldoc->createElement('adlcp:datafromlms','');
  10233. // Give a child element <adlcp:masteryscore> to the <item> element.
  10234. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10235. $my_item->appendChild($my_masteryscore);
  10236. // Attach this item to the organization element or hits parent if there is one.
  10237. if (!empty($item->parent) && $item->parent != 0) {
  10238. $children = $organization->childNodes;
  10239. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10240. if (is_object($possible_parent)) {
  10241. $possible_parent->appendChild($my_item);
  10242. } else {
  10243. if ($this->debug > 0) {
  10244. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10245. }
  10246. }
  10247. } else {
  10248. if ($this->debug > 0) {
  10249. error_log('No parent');
  10250. }
  10251. $organization->appendChild($my_item);
  10252. }
  10253. // Get the path of the file(s) from the course directory root.
  10254. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10255. $my_xml_file_path = $my_file_path;
  10256. if (!empty($path_to_remove)) {
  10257. // From docs
  10258. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10259. // From quiz
  10260. if ($this->ref === 'chamilo_scorm_export') {
  10261. $path_to_remove = 'scorm/'.$this->path.'/';
  10262. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10263. }
  10264. }
  10265. $my_sub_dir = dirname($my_file_path);
  10266. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10267. $my_xml_sub_dir = $my_sub_dir;
  10268. // Give a <resource> child to the <resources> element
  10269. $my_resource = $xmldoc->createElement('resource');
  10270. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10271. $my_resource->setAttribute('type', 'webcontent');
  10272. $my_resource->setAttribute('href', $my_xml_file_path);
  10273. // adlcp:scormtype can be either 'sco' or 'asset'.
  10274. if ($item->type === 'sco') {
  10275. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10276. } else {
  10277. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10278. }
  10279. // xml:base is the base directory to find the files declared in this resource.
  10280. $my_resource->setAttribute('xml:base', '');
  10281. // Give a <file> child to the <resource> element.
  10282. $my_file = $xmldoc->createElement('file');
  10283. $my_file->setAttribute('href', $my_xml_file_path);
  10284. $my_resource->appendChild($my_file);
  10285. // Dependency to other files - not yet supported.
  10286. $i = 1;
  10287. if ($inc_docs) {
  10288. foreach ($inc_docs as $doc_info) {
  10289. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10290. continue;
  10291. }
  10292. $my_dep = $xmldoc->createElement('resource');
  10293. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10294. $my_dep->setAttribute('identifier', $res_id);
  10295. $my_dep->setAttribute('type', 'webcontent');
  10296. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10297. $my_dep_file = $xmldoc->createElement('file');
  10298. // Check type of URL.
  10299. if ($doc_info[1] == 'remote') {
  10300. // Remote file. Save url as is.
  10301. $my_dep_file->setAttribute('href', $doc_info[0]);
  10302. $my_dep->setAttribute('xml:base', '');
  10303. } elseif ($doc_info[1] === 'local') {
  10304. switch ($doc_info[2]) {
  10305. case 'url':
  10306. // Local URL - save path as url for now, don't zip file.
  10307. $abs_path = api_get_path(SYS_PATH).
  10308. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10309. $current_dir = dirname($abs_path);
  10310. $current_dir = str_replace('\\', '/', $current_dir);
  10311. $file_path = realpath($abs_path);
  10312. $file_path = str_replace('\\', '/', $file_path);
  10313. $my_dep_file->setAttribute('href', $file_path);
  10314. $my_dep->setAttribute('xml:base', '');
  10315. if (strstr($file_path, $main_path) !== false) {
  10316. // The calculated real path is really inside Chamilo's root path.
  10317. // Reduce file path to what's under the DocumentRoot.
  10318. $replace = $file_path;
  10319. $file_path = substr($file_path, strlen($root_path) - 1);
  10320. $destinationFile = $file_path;
  10321. if (strstr($file_path, 'upload/users') !== false) {
  10322. $pos = strpos($file_path, 'my_files/');
  10323. if ($pos !== false) {
  10324. $onlyDirectory = str_replace(
  10325. 'upload/users/',
  10326. '',
  10327. substr($file_path, $pos, strlen($file_path))
  10328. );
  10329. }
  10330. $replace = $onlyDirectory;
  10331. $destinationFile = $replace;
  10332. }
  10333. $zip_files_abs[] = $file_path;
  10334. $link_updates[$my_file_path][] = [
  10335. 'orig' => $doc_info[0],
  10336. 'dest' => $destinationFile,
  10337. 'replace' => $replace,
  10338. ];
  10339. $my_dep_file->setAttribute('href', $file_path);
  10340. $my_dep->setAttribute('xml:base', '');
  10341. } elseif (empty($file_path)) {
  10342. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10343. $file_path = str_replace('//', '/', $file_path);
  10344. if (file_exists($file_path)) {
  10345. // We get the relative path.
  10346. $file_path = substr($file_path, strlen($current_dir));
  10347. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10348. $link_updates[$my_file_path][] = [
  10349. 'orig' => $doc_info[0],
  10350. 'dest' => $file_path,
  10351. ];
  10352. $my_dep_file->setAttribute('href', $file_path);
  10353. $my_dep->setAttribute('xml:base', '');
  10354. }
  10355. }
  10356. break;
  10357. case 'abs':
  10358. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10359. $my_dep_file->setAttribute('href', $doc_info[0]);
  10360. $my_dep->setAttribute('xml:base', '');
  10361. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10362. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10363. $abs_img_path_without_subdir = $doc_info[0];
  10364. $relp = api_get_path(REL_PATH); // The url-append config param.
  10365. $pos = strpos($abs_img_path_without_subdir, $relp);
  10366. if ($pos === 0) {
  10367. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10368. }
  10369. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10370. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10371. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10372. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10373. // Check if the current document is in that path.
  10374. if (strstr($file_path, $cur_path) !== false) {
  10375. $destinationFile = substr($file_path, strlen($cur_path));
  10376. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10377. $fileToTest = $cur_path.$my_file_path;
  10378. if (!empty($path_to_remove)) {
  10379. $fileToTest = str_replace(
  10380. $path_to_remove.'/',
  10381. $path_to_replace,
  10382. $cur_path.$my_file_path
  10383. );
  10384. }
  10385. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10386. // Put the current document in the zip (this array is the array
  10387. // that will manage documents already in the course folder - relative).
  10388. $zip_files[] = $filePathNoCoursePart;
  10389. // Update the links to the current document in the
  10390. // containing document (make them relative).
  10391. $link_updates[$my_file_path][] = [
  10392. 'orig' => $doc_info[0],
  10393. 'dest' => $destinationFile,
  10394. 'replace' => $relative_path,
  10395. ];
  10396. $my_dep_file->setAttribute('href', $file_path);
  10397. $my_dep->setAttribute('xml:base', '');
  10398. } elseif (strstr($file_path, $main_path) !== false) {
  10399. // The calculated real path is really inside Chamilo's root path.
  10400. // Reduce file path to what's under the DocumentRoot.
  10401. $file_path = substr($file_path, strlen($root_path));
  10402. $zip_files_abs[] = $file_path;
  10403. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10404. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10405. $my_dep->setAttribute('xml:base', '');
  10406. } elseif (empty($file_path)) {
  10407. // Probably this is an image inside "/main" directory
  10408. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10409. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10410. if (file_exists($file_path)) {
  10411. if (strstr($file_path, 'main/default_course_document') !== false) {
  10412. // We get the relative path.
  10413. $pos = strpos($file_path, 'main/default_course_document/');
  10414. if ($pos !== false) {
  10415. $onlyDirectory = str_replace(
  10416. 'main/default_course_document/',
  10417. '',
  10418. substr($file_path, $pos, strlen($file_path))
  10419. );
  10420. }
  10421. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10422. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10423. $zip_files_abs[] = $fileAbs;
  10424. $link_updates[$my_file_path][] = [
  10425. 'orig' => $doc_info[0],
  10426. 'dest' => $destinationFile,
  10427. ];
  10428. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10429. $my_dep->setAttribute('xml:base', '');
  10430. }
  10431. }
  10432. }
  10433. break;
  10434. case 'rel':
  10435. // Path relative to the current document.
  10436. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10437. if (substr($doc_info[0], 0, 2) === '..') {
  10438. // Relative path going up.
  10439. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10440. $current_dir = str_replace('\\', '/', $current_dir);
  10441. $file_path = realpath($current_dir.$doc_info[0]);
  10442. $file_path = str_replace('\\', '/', $file_path);
  10443. if (strstr($file_path, $main_path) !== false) {
  10444. // The calculated real path is really inside Chamilo's root path.
  10445. // Reduce file path to what's under the DocumentRoot.
  10446. $file_path = substr($file_path, strlen($root_path));
  10447. $zip_files_abs[] = $file_path;
  10448. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10449. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10450. $my_dep->setAttribute('xml:base', '');
  10451. }
  10452. } else {
  10453. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10454. $my_dep_file->setAttribute('href', $doc_info[0]);
  10455. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10456. }
  10457. break;
  10458. default:
  10459. $my_dep_file->setAttribute('href', $doc_info[0]);
  10460. $my_dep->setAttribute('xml:base', '');
  10461. break;
  10462. }
  10463. }
  10464. $my_dep->appendChild($my_dep_file);
  10465. $resources->appendChild($my_dep);
  10466. $dependency = $xmldoc->createElement('dependency');
  10467. $dependency->setAttribute('identifierref', $res_id);
  10468. $my_resource->appendChild($dependency);
  10469. $i++;
  10470. }
  10471. }
  10472. $resources->appendChild($my_resource);
  10473. $zip_files[] = $my_file_path;
  10474. } else {
  10475. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10476. switch ($item->type) {
  10477. case TOOL_LINK:
  10478. $my_item = $xmldoc->createElement('item');
  10479. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10480. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10481. $my_item->setAttribute('isvisible', 'true');
  10482. // Give a child element <title> to the <item> element.
  10483. $my_title = $xmldoc->createElement(
  10484. 'title',
  10485. htmlspecialchars(
  10486. api_utf8_encode($item->get_title()),
  10487. ENT_QUOTES,
  10488. 'UTF-8'
  10489. )
  10490. );
  10491. $my_item->appendChild($my_title);
  10492. // Give a child element <adlcp:prerequisites> to the <item> element.
  10493. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10494. $my_prereqs->setAttribute('type', 'aicc_script');
  10495. $my_item->appendChild($my_prereqs);
  10496. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10497. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10498. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10499. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10500. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10501. //$xmldoc->createElement('adlcp:datafromlms', '');
  10502. // Give a child element <adlcp:masteryscore> to the <item> element.
  10503. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10504. $my_item->appendChild($my_masteryscore);
  10505. // Attach this item to the organization element or its parent if there is one.
  10506. if (!empty($item->parent) && $item->parent != 0) {
  10507. $children = $organization->childNodes;
  10508. for ($i = 0; $i < $children->length; $i++) {
  10509. $item_temp = $children->item($i);
  10510. if ($item_temp->nodeName == 'item') {
  10511. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10512. $item_temp->appendChild($my_item);
  10513. }
  10514. }
  10515. }
  10516. } else {
  10517. $organization->appendChild($my_item);
  10518. }
  10519. $my_file_path = 'link_'.$item->get_id().'.html';
  10520. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10521. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10522. $rs = Database::query($sql);
  10523. if ($link = Database::fetch_array($rs)) {
  10524. $url = $link['url'];
  10525. $title = stripslashes($link['title']);
  10526. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10527. $my_xml_file_path = $my_file_path;
  10528. $my_sub_dir = dirname($my_file_path);
  10529. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10530. $my_xml_sub_dir = $my_sub_dir;
  10531. // Give a <resource> child to the <resources> element.
  10532. $my_resource = $xmldoc->createElement('resource');
  10533. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10534. $my_resource->setAttribute('type', 'webcontent');
  10535. $my_resource->setAttribute('href', $my_xml_file_path);
  10536. // adlcp:scormtype can be either 'sco' or 'asset'.
  10537. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10538. // xml:base is the base directory to find the files declared in this resource.
  10539. $my_resource->setAttribute('xml:base', '');
  10540. // give a <file> child to the <resource> element.
  10541. $my_file = $xmldoc->createElement('file');
  10542. $my_file->setAttribute('href', $my_xml_file_path);
  10543. $my_resource->appendChild($my_file);
  10544. $resources->appendChild($my_resource);
  10545. }
  10546. break;
  10547. case TOOL_QUIZ:
  10548. $exe_id = $item->path;
  10549. // Should be using ref when everything will be cleaned up in this regard.
  10550. $exe = new Exercise();
  10551. $exe->read($exe_id);
  10552. $my_item = $xmldoc->createElement('item');
  10553. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10554. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10555. $my_item->setAttribute('isvisible', 'true');
  10556. // Give a child element <title> to the <item> element.
  10557. $my_title = $xmldoc->createElement(
  10558. 'title',
  10559. htmlspecialchars(
  10560. api_utf8_encode($item->get_title()),
  10561. ENT_QUOTES,
  10562. 'UTF-8'
  10563. )
  10564. );
  10565. $my_item->appendChild($my_title);
  10566. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10567. $my_item->appendChild($my_max_score);
  10568. // Give a child element <adlcp:prerequisites> to the <item> element.
  10569. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10570. $my_prereqs->setAttribute('type', 'aicc_script');
  10571. $my_item->appendChild($my_prereqs);
  10572. // Give a child element <adlcp:masteryscore> to the <item> element.
  10573. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10574. $my_item->appendChild($my_masteryscore);
  10575. // Attach this item to the organization element or hits parent if there is one.
  10576. if (!empty($item->parent) && $item->parent != 0) {
  10577. $children = $organization->childNodes;
  10578. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10579. if ($possible_parent) {
  10580. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10581. $possible_parent->appendChild($my_item);
  10582. }
  10583. }
  10584. } else {
  10585. $organization->appendChild($my_item);
  10586. }
  10587. // Get the path of the file(s) from the course directory root
  10588. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10589. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10590. // Write the contents of the exported exercise into a (big) html file
  10591. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10592. $scormExercise = new ScormExercise($exe, true);
  10593. $contents = $scormExercise->export();
  10594. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10595. $res = file_put_contents($tmp_file_path, $contents);
  10596. if ($res === false) {
  10597. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10598. }
  10599. $files_cleanup[] = $tmp_file_path;
  10600. $my_xml_file_path = $my_file_path;
  10601. $my_sub_dir = dirname($my_file_path);
  10602. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10603. $my_xml_sub_dir = $my_sub_dir;
  10604. // Give a <resource> child to the <resources> element.
  10605. $my_resource = $xmldoc->createElement('resource');
  10606. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10607. $my_resource->setAttribute('type', 'webcontent');
  10608. $my_resource->setAttribute('href', $my_xml_file_path);
  10609. // adlcp:scormtype can be either 'sco' or 'asset'.
  10610. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10611. // xml:base is the base directory to find the files declared in this resource.
  10612. $my_resource->setAttribute('xml:base', '');
  10613. // Give a <file> child to the <resource> element.
  10614. $my_file = $xmldoc->createElement('file');
  10615. $my_file->setAttribute('href', $my_xml_file_path);
  10616. $my_resource->appendChild($my_file);
  10617. // Get included docs.
  10618. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10619. // Dependency to other files - not yet supported.
  10620. $i = 1;
  10621. foreach ($inc_docs as $doc_info) {
  10622. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10623. continue;
  10624. }
  10625. $my_dep = $xmldoc->createElement('resource');
  10626. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10627. $my_dep->setAttribute('identifier', $res_id);
  10628. $my_dep->setAttribute('type', 'webcontent');
  10629. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10630. $my_dep_file = $xmldoc->createElement('file');
  10631. // Check type of URL.
  10632. if ($doc_info[1] == 'remote') {
  10633. // Remote file. Save url as is.
  10634. $my_dep_file->setAttribute('href', $doc_info[0]);
  10635. $my_dep->setAttribute('xml:base', '');
  10636. } elseif ($doc_info[1] == 'local') {
  10637. switch ($doc_info[2]) {
  10638. case 'url': // Local URL - save path as url for now, don't zip file.
  10639. // Save file but as local file (retrieve from URL).
  10640. $abs_path = api_get_path(SYS_PATH).
  10641. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10642. $current_dir = dirname($abs_path);
  10643. $current_dir = str_replace('\\', '/', $current_dir);
  10644. $file_path = realpath($abs_path);
  10645. $file_path = str_replace('\\', '/', $file_path);
  10646. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10647. $my_dep->setAttribute('xml:base', '');
  10648. if (strstr($file_path, $main_path) !== false) {
  10649. // The calculated real path is really inside the chamilo root path.
  10650. // Reduce file path to what's under the DocumentRoot.
  10651. $file_path = substr($file_path, strlen($root_path));
  10652. $zip_files_abs[] = $file_path;
  10653. $link_updates[$my_file_path][] = [
  10654. 'orig' => $doc_info[0],
  10655. 'dest' => 'document/'.$file_path,
  10656. ];
  10657. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10658. $my_dep->setAttribute('xml:base', '');
  10659. } elseif (empty($file_path)) {
  10660. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10661. $file_path = str_replace('//', '/', $file_path);
  10662. if (file_exists($file_path)) {
  10663. $file_path = substr($file_path, strlen($current_dir));
  10664. // We get the relative path.
  10665. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10666. $link_updates[$my_file_path][] = [
  10667. 'orig' => $doc_info[0],
  10668. 'dest' => 'document/'.$file_path,
  10669. ];
  10670. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10671. $my_dep->setAttribute('xml:base', '');
  10672. }
  10673. }
  10674. break;
  10675. case 'abs':
  10676. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10677. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10678. $current_dir = str_replace('\\', '/', $current_dir);
  10679. $file_path = realpath($doc_info[0]);
  10680. $file_path = str_replace('\\', '/', $file_path);
  10681. $my_dep_file->setAttribute('href', $file_path);
  10682. $my_dep->setAttribute('xml:base', '');
  10683. if (strstr($file_path, $main_path) !== false) {
  10684. // The calculated real path is really inside the chamilo root path.
  10685. // Reduce file path to what's under the DocumentRoot.
  10686. $file_path = substr($file_path, strlen($root_path));
  10687. $zip_files_abs[] = $file_path;
  10688. $link_updates[$my_file_path][] = [
  10689. 'orig' => $doc_info[0],
  10690. 'dest' => $file_path,
  10691. ];
  10692. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10693. $my_dep->setAttribute('xml:base', '');
  10694. } elseif (empty($file_path)) {
  10695. $docSysPartPath = str_replace(
  10696. api_get_path(REL_COURSE_PATH),
  10697. '',
  10698. $doc_info[0]
  10699. );
  10700. $docSysPartPathNoCourseCode = str_replace(
  10701. $_course['directory'].'/',
  10702. '',
  10703. $docSysPartPath
  10704. );
  10705. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10706. if (file_exists($docSysPath)) {
  10707. $file_path = $docSysPartPathNoCourseCode;
  10708. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10709. $link_updates[$my_file_path][] = [
  10710. 'orig' => $doc_info[0],
  10711. 'dest' => $file_path,
  10712. ];
  10713. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10714. $my_dep->setAttribute('xml:base', '');
  10715. }
  10716. }
  10717. break;
  10718. case 'rel':
  10719. // Path relative to the current document. Save xml:base as current document's
  10720. // directory and save file in zip as subdir.file_path
  10721. if (substr($doc_info[0], 0, 2) === '..') {
  10722. // Relative path going up.
  10723. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10724. $current_dir = str_replace('\\', '/', $current_dir);
  10725. $file_path = realpath($current_dir.$doc_info[0]);
  10726. $file_path = str_replace('\\', '/', $file_path);
  10727. //error_log($file_path.' <-> '.$main_path, 0);
  10728. if (strstr($file_path, $main_path) !== false) {
  10729. // The calculated real path is really inside Chamilo's root path.
  10730. // Reduce file path to what's under the DocumentRoot.
  10731. $file_path = substr($file_path, strlen($root_path));
  10732. $file_path_dest = $file_path;
  10733. // File path is courses/CHAMILO/document/....
  10734. $info_file_path = explode('/', $file_path);
  10735. if ($info_file_path[0] == 'courses') {
  10736. // Add character "/" in file path.
  10737. $file_path_dest = 'document/'.$file_path;
  10738. }
  10739. $zip_files_abs[] = $file_path;
  10740. $link_updates[$my_file_path][] = [
  10741. 'orig' => $doc_info[0],
  10742. 'dest' => $file_path_dest,
  10743. ];
  10744. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10745. $my_dep->setAttribute('xml:base', '');
  10746. }
  10747. } else {
  10748. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10749. $my_dep_file->setAttribute('href', $doc_info[0]);
  10750. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10751. }
  10752. break;
  10753. default:
  10754. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10755. $my_dep->setAttribute('xml:base', '');
  10756. break;
  10757. }
  10758. }
  10759. $my_dep->appendChild($my_dep_file);
  10760. $resources->appendChild($my_dep);
  10761. $dependency = $xmldoc->createElement('dependency');
  10762. $dependency->setAttribute('identifierref', $res_id);
  10763. $my_resource->appendChild($dependency);
  10764. $i++;
  10765. }
  10766. $resources->appendChild($my_resource);
  10767. $zip_files[] = $my_file_path;
  10768. break;
  10769. default:
  10770. // Get the path of the file(s) from the course directory root
  10771. $my_file_path = 'non_exportable.html';
  10772. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10773. $my_xml_file_path = $my_file_path;
  10774. $my_sub_dir = dirname($my_file_path);
  10775. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10776. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10777. $my_xml_sub_dir = $my_sub_dir;
  10778. // Give a <resource> child to the <resources> element.
  10779. $my_resource = $xmldoc->createElement('resource');
  10780. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10781. $my_resource->setAttribute('type', 'webcontent');
  10782. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10783. // adlcp:scormtype can be either 'sco' or 'asset'.
  10784. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10785. // xml:base is the base directory to find the files declared in this resource.
  10786. $my_resource->setAttribute('xml:base', '');
  10787. // Give a <file> child to the <resource> element.
  10788. $my_file = $xmldoc->createElement('file');
  10789. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10790. $my_resource->appendChild($my_file);
  10791. $resources->appendChild($my_resource);
  10792. break;
  10793. }
  10794. }
  10795. }
  10796. $organizations->appendChild($organization);
  10797. $root->appendChild($organizations);
  10798. $root->appendChild($resources);
  10799. $xmldoc->appendChild($root);
  10800. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10801. // then add the file to the zip, then destroy the file (this is done automatically).
  10802. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10803. foreach ($zip_files as $file_path) {
  10804. if (empty($file_path)) {
  10805. continue;
  10806. }
  10807. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10808. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10809. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10810. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10811. }
  10812. $this->create_path($dest_file);
  10813. @copy($filePath, $dest_file);
  10814. // Check if the file needs a link update.
  10815. if (in_array($file_path, array_keys($link_updates))) {
  10816. $string = file_get_contents($dest_file);
  10817. unlink($dest_file);
  10818. foreach ($link_updates[$file_path] as $old_new) {
  10819. // This is an ugly hack that allows .flv files to be found by the flv player that
  10820. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10821. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10822. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10823. if (substr($old_new['dest'], -3) === 'flv' &&
  10824. substr($old_new['dest'], 0, 5) === 'main/'
  10825. ) {
  10826. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10827. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10828. substr($old_new['dest'], 0, 6) === 'video/'
  10829. ) {
  10830. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10831. }
  10832. // Fix to avoid problems with default_course_document
  10833. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10834. $newDestination = $old_new['dest'];
  10835. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10836. $newDestination = $old_new['replace'];
  10837. }
  10838. } else {
  10839. $newDestination = str_replace('document/', '', $old_new['dest']);
  10840. }
  10841. $string = str_replace($old_new['orig'], $newDestination, $string);
  10842. // Add files inside the HTMLs
  10843. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10844. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10845. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10846. copy(
  10847. $sys_course_path.$new_path,
  10848. $destinationFile
  10849. );
  10850. }
  10851. }
  10852. file_put_contents($dest_file, $string);
  10853. }
  10854. if (file_exists($filePath) && $copyAll) {
  10855. $extension = $this->get_extension($filePath);
  10856. if (in_array($extension, ['html', 'html'])) {
  10857. $containerOrigin = dirname($filePath);
  10858. $containerDestination = dirname($dest_file);
  10859. $finder = new Finder();
  10860. $finder->files()->in($containerOrigin)
  10861. ->notName('*_DELETED_*')
  10862. ->exclude('share_folder')
  10863. ->exclude('chat_files')
  10864. ->exclude('certificates')
  10865. ;
  10866. if (is_dir($containerOrigin) &&
  10867. is_dir($containerDestination)
  10868. ) {
  10869. $fs = new Filesystem();
  10870. $fs->mirror(
  10871. $containerOrigin,
  10872. $containerDestination,
  10873. $finder
  10874. );
  10875. }
  10876. }
  10877. }
  10878. }
  10879. foreach ($zip_files_abs as $file_path) {
  10880. if (empty($file_path)) {
  10881. continue;
  10882. }
  10883. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10884. continue;
  10885. }
  10886. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10887. if (strstr($file_path, 'upload/users') !== false) {
  10888. $pos = strpos($file_path, 'my_files/');
  10889. if ($pos !== false) {
  10890. $onlyDirectory = str_replace(
  10891. 'upload/users/',
  10892. '',
  10893. substr($file_path, $pos, strlen($file_path))
  10894. );
  10895. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10896. }
  10897. }
  10898. if (strstr($file_path, 'default_course_document/') !== false) {
  10899. $replace = str_replace('/main', '', $file_path);
  10900. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10901. }
  10902. if (empty($dest_file)) {
  10903. continue;
  10904. }
  10905. $this->create_path($dest_file);
  10906. copy($main_path.$file_path, $dest_file);
  10907. // Check if the file needs a link update.
  10908. if (in_array($file_path, array_keys($link_updates))) {
  10909. $string = file_get_contents($dest_file);
  10910. unlink($dest_file);
  10911. foreach ($link_updates[$file_path] as $old_new) {
  10912. // This is an ugly hack that allows .flv files to be found by the flv player that
  10913. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10914. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10915. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10916. if (substr($old_new['dest'], -3) == 'flv' &&
  10917. substr($old_new['dest'], 0, 5) == 'main/'
  10918. ) {
  10919. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10920. }
  10921. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10922. }
  10923. file_put_contents($dest_file, $string);
  10924. }
  10925. }
  10926. if (is_array($links_to_create)) {
  10927. foreach ($links_to_create as $file => $link) {
  10928. $content = '<!DOCTYPE html><head>
  10929. <meta charset="'.api_get_language_isocode().'" />
  10930. <title>'.$link['title'].'</title>
  10931. </head>
  10932. <body dir="'.api_get_text_direction().'">
  10933. <div style="text-align:center">
  10934. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10935. </body>
  10936. </html>';
  10937. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10938. }
  10939. }
  10940. // Add non exportable message explanation.
  10941. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10942. $file_content = '<!DOCTYPE html><head>
  10943. <meta charset="'.api_get_language_isocode().'" />
  10944. <title>'.$lang_not_exportable.'</title>
  10945. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10946. </head>
  10947. <body dir="'.api_get_text_direction().'">';
  10948. $file_content .=
  10949. <<<EOD
  10950. <style>
  10951. .error-message {
  10952. font-family: arial, verdana, helvetica, sans-serif;
  10953. border-width: 1px;
  10954. border-style: solid;
  10955. left: 50%;
  10956. margin: 10px auto;
  10957. min-height: 30px;
  10958. padding: 5px;
  10959. right: 50%;
  10960. width: 500px;
  10961. background-color: #FFD1D1;
  10962. border-color: #FF0000;
  10963. color: #000;
  10964. }
  10965. </style>
  10966. <body>
  10967. <div class="error-message">
  10968. $lang_not_exportable
  10969. </div>
  10970. </body>
  10971. </html>
  10972. EOD;
  10973. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10974. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10975. }
  10976. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10977. // Add the extra files that go along with a SCORM package.
  10978. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10979. $fs = new Filesystem();
  10980. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10981. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10982. $manifest = @$xmldoc->saveXML();
  10983. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10984. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10985. $zip_folder->add(
  10986. $archivePath.'/'.$temp_dir_short,
  10987. PCLZIP_OPT_REMOVE_PATH,
  10988. $archivePath.'/'.$temp_dir_short.'/'
  10989. );
  10990. // Clean possible temporary files.
  10991. foreach ($files_cleanup as $file) {
  10992. $res = unlink($file);
  10993. if ($res === false) {
  10994. error_log(
  10995. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10996. 0
  10997. );
  10998. }
  10999. }
  11000. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  11001. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  11002. }
  11003. /**
  11004. * @param int $lp_id
  11005. *
  11006. * @return bool
  11007. */
  11008. public function scorm_export_to_pdf($lp_id)
  11009. {
  11010. $lp_id = (int) $lp_id;
  11011. $files_to_export = [];
  11012. $sessionId = api_get_session_id();
  11013. $course_data = api_get_course_info($this->cc);
  11014. if (!empty($course_data)) {
  11015. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  11016. $list = self::get_flat_ordered_items_list($lp_id);
  11017. if (!empty($list)) {
  11018. foreach ($list as $item_id) {
  11019. $item = $this->items[$item_id];
  11020. switch ($item->type) {
  11021. case 'document':
  11022. // Getting documents from a LP with chamilo documents
  11023. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  11024. // Try loading document from the base course.
  11025. if (empty($file_data) && !empty($sessionId)) {
  11026. $file_data = DocumentManager::get_document_data_by_id(
  11027. $item->path,
  11028. $this->cc,
  11029. false,
  11030. 0
  11031. );
  11032. }
  11033. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  11034. if (file_exists($file_path)) {
  11035. $files_to_export[] = [
  11036. 'title' => $item->get_title(),
  11037. 'path' => $file_path,
  11038. ];
  11039. }
  11040. break;
  11041. case 'asset': //commes from a scorm package generated by chamilo
  11042. case 'sco':
  11043. $file_path = $scorm_path.'/'.$item->path;
  11044. if (file_exists($file_path)) {
  11045. $files_to_export[] = [
  11046. 'title' => $item->get_title(),
  11047. 'path' => $file_path,
  11048. ];
  11049. }
  11050. break;
  11051. case 'dir':
  11052. $files_to_export[] = [
  11053. 'title' => $item->get_title(),
  11054. 'path' => null,
  11055. ];
  11056. break;
  11057. }
  11058. }
  11059. }
  11060. $pdf = new PDF();
  11061. $result = $pdf->html_to_pdf(
  11062. $files_to_export,
  11063. $this->name,
  11064. $this->cc,
  11065. true,
  11066. true,
  11067. true,
  11068. $this->get_name()
  11069. );
  11070. return $result;
  11071. }
  11072. return false;
  11073. }
  11074. /**
  11075. * Temp function to be moved in main_api or the best place around for this.
  11076. * Creates a file path if it doesn't exist.
  11077. *
  11078. * @param string $path
  11079. */
  11080. public function create_path($path)
  11081. {
  11082. $path_bits = explode('/', dirname($path));
  11083. // IS_WINDOWS_OS has been defined in main_api.lib.php
  11084. $path_built = IS_WINDOWS_OS ? '' : '/';
  11085. foreach ($path_bits as $bit) {
  11086. if (!empty($bit)) {
  11087. $new_path = $path_built.$bit;
  11088. if (is_dir($new_path)) {
  11089. $path_built = $new_path.'/';
  11090. } else {
  11091. mkdir($new_path, api_get_permissions_for_new_directories());
  11092. $path_built = $new_path.'/';
  11093. }
  11094. }
  11095. }
  11096. }
  11097. /**
  11098. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  11099. *
  11100. * @return bool The results of the unlink function, or false if there was no image to start with
  11101. */
  11102. public function delete_lp_image()
  11103. {
  11104. $img = $this->get_preview_image();
  11105. if ($img != '') {
  11106. $del_file = $this->get_preview_image_path(null, 'sys');
  11107. if (isset($del_file) && file_exists($del_file)) {
  11108. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  11109. if (file_exists($del_file_2)) {
  11110. unlink($del_file_2);
  11111. }
  11112. $this->set_preview_image('');
  11113. return @unlink($del_file);
  11114. }
  11115. }
  11116. return false;
  11117. }
  11118. /**
  11119. * Uploads an author image to the upload/learning_path/images directory.
  11120. *
  11121. * @param array The image array, coming from the $_FILES superglobal
  11122. *
  11123. * @return bool True on success, false on error
  11124. */
  11125. public function upload_image($image_array)
  11126. {
  11127. if (!empty($image_array['name'])) {
  11128. $upload_ok = process_uploaded_file($image_array);
  11129. $has_attachment = true;
  11130. }
  11131. if ($upload_ok && $has_attachment) {
  11132. $courseDir = api_get_course_path().'/upload/learning_path/images';
  11133. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  11134. $updir = $sys_course_path.$courseDir;
  11135. // Try to add an extension to the file if it hasn't one.
  11136. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  11137. if (filter_extension($new_file_name)) {
  11138. $file_extension = explode('.', $image_array['name']);
  11139. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  11140. $filename = uniqid('');
  11141. $new_file_name = $filename.'.'.$file_extension;
  11142. $new_path = $updir.'/'.$new_file_name;
  11143. // Resize the image.
  11144. $temp = new Image($image_array['tmp_name']);
  11145. $temp->resize(104);
  11146. $result = $temp->send_image($new_path);
  11147. // Storing the image filename.
  11148. if ($result) {
  11149. $this->set_preview_image($new_file_name);
  11150. //Resize to 64px to use on course homepage
  11151. $temp->resize(64);
  11152. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11153. return true;
  11154. }
  11155. }
  11156. }
  11157. return false;
  11158. }
  11159. /**
  11160. * @param int $lp_id
  11161. * @param string $status
  11162. */
  11163. public function set_autolaunch($lp_id, $status)
  11164. {
  11165. $course_id = api_get_course_int_id();
  11166. $lp_id = (int) $lp_id;
  11167. $status = (int) $status;
  11168. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11169. // Setting everything to autolaunch = 0
  11170. $attributes['autolaunch'] = 0;
  11171. $where = [
  11172. 'session_id = ? AND c_id = ? ' => [
  11173. api_get_session_id(),
  11174. $course_id,
  11175. ],
  11176. ];
  11177. Database::update($lp_table, $attributes, $where);
  11178. if ($status == 1) {
  11179. //Setting my lp_id to autolaunch = 1
  11180. $attributes['autolaunch'] = 1;
  11181. $where = [
  11182. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11183. $lp_id,
  11184. api_get_session_id(),
  11185. $course_id,
  11186. ],
  11187. ];
  11188. Database::update($lp_table, $attributes, $where);
  11189. }
  11190. }
  11191. /**
  11192. * Gets previous_item_id for the next element of the lp_item table.
  11193. *
  11194. * @author Isaac flores paz
  11195. *
  11196. * @return int Previous item ID
  11197. */
  11198. public function select_previous_item_id()
  11199. {
  11200. $course_id = api_get_course_int_id();
  11201. if ($this->debug > 0) {
  11202. error_log('In learnpath::select_previous_item_id()', 0);
  11203. }
  11204. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11205. // Get the max order of the items
  11206. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11207. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11208. $rs_max_order = Database::query($sql);
  11209. $row_max_order = Database::fetch_object($rs_max_order);
  11210. $max_order = $row_max_order->display_order;
  11211. // Get the previous item ID
  11212. $sql = "SELECT iid as previous FROM $table_lp_item
  11213. WHERE
  11214. c_id = $course_id AND
  11215. lp_id = ".$this->lp_id." AND
  11216. display_order = '$max_order' ";
  11217. $rs_max = Database::query($sql);
  11218. $row_max = Database::fetch_object($rs_max);
  11219. // Return the previous item ID
  11220. return $row_max->previous;
  11221. }
  11222. /**
  11223. * Copies an LP.
  11224. */
  11225. public function copy()
  11226. {
  11227. // Course builder
  11228. $cb = new CourseBuilder();
  11229. //Setting tools that will be copied
  11230. $cb->set_tools_to_build(['learnpaths']);
  11231. //Setting elements that will be copied
  11232. $cb->set_tools_specific_id_list(
  11233. ['learnpaths' => [$this->lp_id]]
  11234. );
  11235. $course = $cb->build();
  11236. //Course restorer
  11237. $course_restorer = new CourseRestorer($course);
  11238. $course_restorer->set_add_text_in_items(true);
  11239. $course_restorer->set_tool_copy_settings(
  11240. ['learnpaths' => ['reset_dates' => true]]
  11241. );
  11242. $course_restorer->restore(
  11243. api_get_course_id(),
  11244. api_get_session_id(),
  11245. false,
  11246. false
  11247. );
  11248. }
  11249. /**
  11250. * Verify document size.
  11251. *
  11252. * @param string $s
  11253. *
  11254. * @return bool
  11255. */
  11256. public static function verify_document_size($s)
  11257. {
  11258. $post_max = ini_get('post_max_size');
  11259. if (substr($post_max, -1, 1) == 'M') {
  11260. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11261. } elseif (substr($post_max, -1, 1) == 'G') {
  11262. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11263. }
  11264. $upl_max = ini_get('upload_max_filesize');
  11265. if (substr($upl_max, -1, 1) == 'M') {
  11266. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11267. } elseif (substr($upl_max, -1, 1) == 'G') {
  11268. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11269. }
  11270. $documents_total_space = DocumentManager::documents_total_space();
  11271. $course_max_space = DocumentManager::get_course_quota();
  11272. $total_size = filesize($s) + $documents_total_space;
  11273. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11274. return true;
  11275. } else {
  11276. return false;
  11277. }
  11278. }
  11279. /**
  11280. * Clear LP prerequisites.
  11281. */
  11282. public function clear_prerequisites()
  11283. {
  11284. $course_id = $this->get_course_int_id();
  11285. if ($this->debug > 0) {
  11286. error_log('In learnpath::clear_prerequisites()', 0);
  11287. }
  11288. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11289. $lp_id = $this->get_id();
  11290. //Cleaning prerequisites
  11291. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11292. WHERE c_id = $course_id AND lp_id = $lp_id";
  11293. Database::query($sql);
  11294. //Cleaning mastery score for exercises
  11295. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11296. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11297. Database::query($sql);
  11298. }
  11299. public function set_previous_step_as_prerequisite_for_all_items()
  11300. {
  11301. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11302. $course_id = $this->get_course_int_id();
  11303. $lp_id = $this->get_id();
  11304. if (!empty($this->items)) {
  11305. $previous_item_id = null;
  11306. $previous_item_max = 0;
  11307. $previous_item_type = null;
  11308. $last_item_not_dir = null;
  11309. $last_item_not_dir_type = null;
  11310. $last_item_not_dir_max = null;
  11311. foreach ($this->ordered_items as $itemId) {
  11312. $item = $this->getItem($itemId);
  11313. // if there was a previous item... (otherwise jump to set it)
  11314. if (!empty($previous_item_id)) {
  11315. $current_item_id = $item->get_id(); //save current id
  11316. if ($item->get_type() != 'dir') {
  11317. // Current item is not a folder, so it qualifies to get a prerequisites
  11318. if ($last_item_not_dir_type == 'quiz') {
  11319. // if previous is quiz, mark its max score as default score to be achieved
  11320. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11321. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11322. Database::query($sql);
  11323. }
  11324. // now simply update the prerequisite to set it to the last non-chapter item
  11325. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11326. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11327. Database::query($sql);
  11328. // record item as 'non-chapter' reference
  11329. $last_item_not_dir = $item->get_id();
  11330. $last_item_not_dir_type = $item->get_type();
  11331. $last_item_not_dir_max = $item->get_max();
  11332. }
  11333. } else {
  11334. if ($item->get_type() != 'dir') {
  11335. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11336. $last_item_not_dir = $item->get_id();
  11337. $last_item_not_dir_type = $item->get_type();
  11338. $last_item_not_dir_max = $item->get_max();
  11339. }
  11340. }
  11341. // Saving the item as "previous item" for the next loop
  11342. $previous_item_id = $item->get_id();
  11343. $previous_item_max = $item->get_max();
  11344. $previous_item_type = $item->get_type();
  11345. }
  11346. }
  11347. }
  11348. /**
  11349. * @param array $params
  11350. *
  11351. * @throws \Doctrine\ORM\OptimisticLockException
  11352. *
  11353. * @return int
  11354. */
  11355. public static function createCategory($params)
  11356. {
  11357. $em = Database::getManager();
  11358. $item = new CLpCategory();
  11359. $item->setName($params['name']);
  11360. $item->setCId($params['c_id']);
  11361. $em->persist($item);
  11362. $em->flush();
  11363. api_item_property_update(
  11364. api_get_course_info(),
  11365. TOOL_LEARNPATH_CATEGORY,
  11366. $item->getId(),
  11367. 'visible',
  11368. api_get_user_id()
  11369. );
  11370. return $item->getId();
  11371. }
  11372. /**
  11373. * @param array $params
  11374. *
  11375. * @throws \Doctrine\ORM\ORMException
  11376. * @throws \Doctrine\ORM\OptimisticLockException
  11377. * @throws \Doctrine\ORM\TransactionRequiredException
  11378. */
  11379. public static function updateCategory($params)
  11380. {
  11381. $em = Database::getManager();
  11382. /** @var CLpCategory $item */
  11383. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11384. if ($item) {
  11385. $item->setName($params['name']);
  11386. $em->merge($item);
  11387. $em->flush();
  11388. }
  11389. }
  11390. /**
  11391. * @param int $id
  11392. *
  11393. * @throws \Doctrine\ORM\ORMException
  11394. * @throws \Doctrine\ORM\OptimisticLockException
  11395. * @throws \Doctrine\ORM\TransactionRequiredException
  11396. */
  11397. public static function moveUpCategory($id)
  11398. {
  11399. $id = (int) $id;
  11400. $em = Database::getManager();
  11401. /** @var CLpCategory $item */
  11402. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11403. if ($item) {
  11404. $position = $item->getPosition() - 1;
  11405. $item->setPosition($position);
  11406. $em->persist($item);
  11407. $em->flush();
  11408. }
  11409. }
  11410. /**
  11411. * @param int $id
  11412. *
  11413. * @throws \Doctrine\ORM\ORMException
  11414. * @throws \Doctrine\ORM\OptimisticLockException
  11415. * @throws \Doctrine\ORM\TransactionRequiredException
  11416. */
  11417. public static function moveDownCategory($id)
  11418. {
  11419. $id = (int) $id;
  11420. $em = Database::getManager();
  11421. /** @var CLpCategory $item */
  11422. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11423. if ($item) {
  11424. $position = $item->getPosition() + 1;
  11425. $item->setPosition($position);
  11426. $em->persist($item);
  11427. $em->flush();
  11428. }
  11429. }
  11430. /**
  11431. * @param int $courseId
  11432. *
  11433. * @throws \Doctrine\ORM\Query\QueryException
  11434. *
  11435. * @return int|mixed
  11436. */
  11437. public static function getCountCategories($courseId)
  11438. {
  11439. if (empty($courseId)) {
  11440. return 0;
  11441. }
  11442. $em = Database::getManager();
  11443. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11444. $query->setParameter('id', $courseId);
  11445. return $query->getSingleScalarResult();
  11446. }
  11447. /**
  11448. * @param int $courseId
  11449. *
  11450. * @return mixed
  11451. */
  11452. public static function getCategories($courseId)
  11453. {
  11454. $em = Database::getManager();
  11455. // Using doctrine extensions
  11456. /** @var SortableRepository $repo */
  11457. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11458. $items = $repo
  11459. ->getBySortableGroupsQuery(['cId' => $courseId])
  11460. ->getResult();
  11461. return $items;
  11462. }
  11463. /**
  11464. * @param int $id
  11465. *
  11466. * @throws \Doctrine\ORM\ORMException
  11467. * @throws \Doctrine\ORM\OptimisticLockException
  11468. * @throws \Doctrine\ORM\TransactionRequiredException
  11469. *
  11470. * @return CLpCategory
  11471. */
  11472. public static function getCategory($id)
  11473. {
  11474. $id = (int) $id;
  11475. $em = Database::getManager();
  11476. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11477. return $item;
  11478. }
  11479. /**
  11480. * @param int $courseId
  11481. *
  11482. * @return array
  11483. */
  11484. public static function getCategoryByCourse($courseId)
  11485. {
  11486. $em = Database::getManager();
  11487. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11488. ['cId' => $courseId]
  11489. );
  11490. return $items;
  11491. }
  11492. /**
  11493. * @param int $id
  11494. *
  11495. * @throws \Doctrine\ORM\ORMException
  11496. * @throws \Doctrine\ORM\OptimisticLockException
  11497. * @throws \Doctrine\ORM\TransactionRequiredException
  11498. *
  11499. * @return mixed
  11500. */
  11501. public static function deleteCategory($id)
  11502. {
  11503. $em = Database::getManager();
  11504. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11505. if ($item) {
  11506. $courseId = $item->getCId();
  11507. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11508. $query->setParameter('id', $courseId);
  11509. $query->setParameter('catId', $item->getId());
  11510. $lps = $query->getResult();
  11511. // Setting category = 0.
  11512. if ($lps) {
  11513. foreach ($lps as $lpItem) {
  11514. $lpItem->setCategoryId(0);
  11515. }
  11516. }
  11517. // Removing category.
  11518. $em->remove($item);
  11519. $em->flush();
  11520. $courseInfo = api_get_course_info_by_id($courseId);
  11521. $sessionId = api_get_session_id();
  11522. // Delete link tool
  11523. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11524. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11525. // Delete tools
  11526. $sql = "DELETE FROM $tbl_tool
  11527. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11528. Database::query($sql);
  11529. return true;
  11530. }
  11531. return false;
  11532. }
  11533. /**
  11534. * @param int $courseId
  11535. * @param bool $addSelectOption
  11536. *
  11537. * @return mixed
  11538. */
  11539. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11540. {
  11541. $items = self::getCategoryByCourse($courseId);
  11542. $cats = [];
  11543. if ($addSelectOption) {
  11544. $cats = [get_lang('SelectACategory')];
  11545. }
  11546. if (!empty($items)) {
  11547. foreach ($items as $cat) {
  11548. $cats[$cat->getId()] = $cat->getName();
  11549. }
  11550. }
  11551. return $cats;
  11552. }
  11553. /**
  11554. * @param string $courseCode
  11555. * @param int $lpId
  11556. * @param int $user_id
  11557. *
  11558. * @return learnpath
  11559. */
  11560. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11561. {
  11562. $debug = 0;
  11563. $learnPath = null;
  11564. $lpObject = Session::read('lpobject');
  11565. if ($lpObject !== null) {
  11566. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11567. if ($debug) {
  11568. error_log('getLpFromSession: unserialize');
  11569. error_log('------getLpFromSession------');
  11570. error_log('------unserialize------');
  11571. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11572. error_log("api_get_sessionid: ".api_get_session_id());
  11573. }
  11574. }
  11575. if (!is_object($learnPath)) {
  11576. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11577. if ($debug) {
  11578. error_log('------getLpFromSession------');
  11579. error_log('getLpFromSession: create new learnpath');
  11580. error_log("create new LP with $courseCode - $lpId - $user_id");
  11581. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11582. error_log("api_get_sessionid: ".api_get_session_id());
  11583. }
  11584. }
  11585. return $learnPath;
  11586. }
  11587. /**
  11588. * @param int $itemId
  11589. *
  11590. * @return learnpathItem|false
  11591. */
  11592. public function getItem($itemId)
  11593. {
  11594. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11595. return $this->items[$itemId];
  11596. }
  11597. return false;
  11598. }
  11599. /**
  11600. * @return int
  11601. */
  11602. public function getCategoryId()
  11603. {
  11604. return (int) $this->categoryId;
  11605. }
  11606. /**
  11607. * @param int $categoryId
  11608. *
  11609. * @return bool
  11610. */
  11611. public function setCategoryId($categoryId)
  11612. {
  11613. $this->categoryId = (int) $categoryId;
  11614. $table = Database::get_course_table(TABLE_LP_MAIN);
  11615. $lp_id = $this->get_id();
  11616. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11617. WHERE iid = $lp_id";
  11618. Database::query($sql);
  11619. return true;
  11620. }
  11621. /**
  11622. * Get whether this is a learning path with the possibility to subscribe
  11623. * users or not.
  11624. *
  11625. * @return int
  11626. */
  11627. public function getSubscribeUsers()
  11628. {
  11629. return $this->subscribeUsers;
  11630. }
  11631. /**
  11632. * Set whether this is a learning path with the possibility to subscribe
  11633. * users or not.
  11634. *
  11635. * @param int $value (0 = false, 1 = true)
  11636. *
  11637. * @return bool
  11638. */
  11639. public function setSubscribeUsers($value)
  11640. {
  11641. if ($this->debug > 0) {
  11642. error_log('In learnpath::set_subscribe_users()', 0);
  11643. }
  11644. $this->subscribeUsers = (int) $value;
  11645. $table = Database::get_course_table(TABLE_LP_MAIN);
  11646. $lp_id = $this->get_id();
  11647. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11648. WHERE iid = $lp_id";
  11649. Database::query($sql);
  11650. return true;
  11651. }
  11652. /**
  11653. * Calculate the count of stars for a user in this LP
  11654. * This calculation is based on the following rules:
  11655. * - the student gets one star when he gets to 50% of the learning path
  11656. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11657. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11658. * - the student gets the final star when the score for the *last* test is >= 80%.
  11659. *
  11660. * @param int $sessionId Optional. The session ID
  11661. *
  11662. * @return int The count of stars
  11663. */
  11664. public function getCalculateStars($sessionId = 0)
  11665. {
  11666. $stars = 0;
  11667. $progress = self::getProgress(
  11668. $this->lp_id,
  11669. $this->user_id,
  11670. $this->course_int_id,
  11671. $sessionId
  11672. );
  11673. if ($progress >= 50) {
  11674. $stars++;
  11675. }
  11676. // Calculate stars chapters evaluation
  11677. $exercisesItems = $this->getExercisesItems();
  11678. if (!empty($exercisesItems)) {
  11679. $totalResult = 0;
  11680. foreach ($exercisesItems as $exerciseItem) {
  11681. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11682. $this->user_id,
  11683. $exerciseItem->path,
  11684. $this->course_int_id,
  11685. $sessionId,
  11686. $this->lp_id,
  11687. $exerciseItem->db_id
  11688. );
  11689. $exerciseResultInfo = end($exerciseResultInfo);
  11690. if (!$exerciseResultInfo) {
  11691. continue;
  11692. }
  11693. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11694. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11695. } else {
  11696. $exerciseResult = 0;
  11697. }
  11698. $totalResult += $exerciseResult;
  11699. }
  11700. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11701. if ($totalExerciseAverage >= 50) {
  11702. $stars++;
  11703. }
  11704. if ($totalExerciseAverage >= 80) {
  11705. $stars++;
  11706. }
  11707. }
  11708. // Calculate star for final evaluation
  11709. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11710. if (!empty($finalEvaluationItem)) {
  11711. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11712. $this->user_id,
  11713. $finalEvaluationItem->path,
  11714. $this->course_int_id,
  11715. $sessionId,
  11716. $this->lp_id,
  11717. $finalEvaluationItem->db_id
  11718. );
  11719. $evaluationResultInfo = end($evaluationResultInfo);
  11720. if ($evaluationResultInfo) {
  11721. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11722. if ($evaluationResult >= 80) {
  11723. $stars++;
  11724. }
  11725. }
  11726. }
  11727. return $stars;
  11728. }
  11729. /**
  11730. * Get the items of exercise type.
  11731. *
  11732. * @return array The items. Otherwise return false
  11733. */
  11734. public function getExercisesItems()
  11735. {
  11736. $exercises = [];
  11737. foreach ($this->items as $item) {
  11738. if ($item->type != 'quiz') {
  11739. continue;
  11740. }
  11741. $exercises[] = $item;
  11742. }
  11743. array_pop($exercises);
  11744. return $exercises;
  11745. }
  11746. /**
  11747. * Get the item of exercise type (evaluation type).
  11748. *
  11749. * @return array The final evaluation. Otherwise return false
  11750. */
  11751. public function getFinalEvaluationItem()
  11752. {
  11753. $exercises = [];
  11754. foreach ($this->items as $item) {
  11755. if ($item->type != 'quiz') {
  11756. continue;
  11757. }
  11758. $exercises[] = $item;
  11759. }
  11760. return array_pop($exercises);
  11761. }
  11762. /**
  11763. * Calculate the total points achieved for the current user in this learning path.
  11764. *
  11765. * @param int $sessionId Optional. The session Id
  11766. *
  11767. * @return int
  11768. */
  11769. public function getCalculateScore($sessionId = 0)
  11770. {
  11771. // Calculate stars chapters evaluation
  11772. $exercisesItems = $this->getExercisesItems();
  11773. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11774. $totalExercisesResult = 0;
  11775. $totalEvaluationResult = 0;
  11776. if ($exercisesItems !== false) {
  11777. foreach ($exercisesItems as $exerciseItem) {
  11778. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11779. $this->user_id,
  11780. $exerciseItem->path,
  11781. $this->course_int_id,
  11782. $sessionId,
  11783. $this->lp_id,
  11784. $exerciseItem->db_id
  11785. );
  11786. $exerciseResultInfo = end($exerciseResultInfo);
  11787. if (!$exerciseResultInfo) {
  11788. continue;
  11789. }
  11790. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11791. }
  11792. }
  11793. if (!empty($finalEvaluationItem)) {
  11794. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11795. $this->user_id,
  11796. $finalEvaluationItem->path,
  11797. $this->course_int_id,
  11798. $sessionId,
  11799. $this->lp_id,
  11800. $finalEvaluationItem->db_id
  11801. );
  11802. $evaluationResultInfo = end($evaluationResultInfo);
  11803. if ($evaluationResultInfo) {
  11804. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11805. }
  11806. }
  11807. return $totalExercisesResult + $totalEvaluationResult;
  11808. }
  11809. /**
  11810. * Check if URL is not allowed to be show in a iframe.
  11811. *
  11812. * @param string $src
  11813. *
  11814. * @return string
  11815. */
  11816. public function fixBlockedLinks($src)
  11817. {
  11818. $urlInfo = parse_url($src);
  11819. $platformProtocol = 'https';
  11820. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11821. $platformProtocol = 'http';
  11822. }
  11823. $protocolFixApplied = false;
  11824. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11825. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11826. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11827. if ($platformProtocol != $scheme) {
  11828. Session::write('x_frame_source', $src);
  11829. $src = 'blank.php?error=x_frames_options';
  11830. $protocolFixApplied = true;
  11831. }
  11832. if ($protocolFixApplied == false) {
  11833. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11834. // Check X-Frame-Options
  11835. $ch = curl_init();
  11836. $options = [
  11837. CURLOPT_URL => $src,
  11838. CURLOPT_RETURNTRANSFER => true,
  11839. CURLOPT_HEADER => true,
  11840. CURLOPT_FOLLOWLOCATION => true,
  11841. CURLOPT_ENCODING => "",
  11842. CURLOPT_AUTOREFERER => true,
  11843. CURLOPT_CONNECTTIMEOUT => 120,
  11844. CURLOPT_TIMEOUT => 120,
  11845. CURLOPT_MAXREDIRS => 10,
  11846. ];
  11847. $proxySettings = api_get_configuration_value('proxy_settings');
  11848. if (!empty($proxySettings) &&
  11849. isset($proxySettings['curl_setopt_array'])
  11850. ) {
  11851. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11852. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11853. }
  11854. curl_setopt_array($ch, $options);
  11855. $response = curl_exec($ch);
  11856. $httpCode = curl_getinfo($ch);
  11857. $headers = substr($response, 0, $httpCode['header_size']);
  11858. $error = false;
  11859. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11860. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11861. ) {
  11862. $error = true;
  11863. }
  11864. if ($error) {
  11865. Session::write('x_frame_source', $src);
  11866. $src = 'blank.php?error=x_frames_options';
  11867. }
  11868. }
  11869. }
  11870. return $src;
  11871. }
  11872. /**
  11873. * Check if this LP has a created forum in the basis course.
  11874. *
  11875. * @return bool
  11876. */
  11877. public function lpHasForum()
  11878. {
  11879. $forumTable = Database::get_course_table(TABLE_FORUM);
  11880. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11881. $fakeFrom = "
  11882. $forumTable f
  11883. INNER JOIN $itemProperty ip
  11884. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11885. ";
  11886. $resultData = Database::select(
  11887. 'COUNT(f.iid) AS qty',
  11888. $fakeFrom,
  11889. [
  11890. 'where' => [
  11891. 'ip.visibility != ? AND ' => 2,
  11892. 'ip.tool = ? AND ' => TOOL_FORUM,
  11893. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11894. 'f.lp_id = ?' => intval($this->lp_id),
  11895. ],
  11896. ],
  11897. 'first'
  11898. );
  11899. return $resultData['qty'] > 0;
  11900. }
  11901. /**
  11902. * Get the forum for this learning path.
  11903. *
  11904. * @param int $sessionId
  11905. *
  11906. * @return bool
  11907. */
  11908. public function getForum($sessionId = 0)
  11909. {
  11910. $forumTable = Database::get_course_table(TABLE_FORUM);
  11911. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11912. $fakeFrom = "$forumTable f
  11913. INNER JOIN $itemProperty ip ";
  11914. if ($this->lp_session_id == 0) {
  11915. $fakeFrom .= "
  11916. ON (
  11917. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11918. f.session_id = ip.session_id OR ip.session_id IS NULL
  11919. )
  11920. )
  11921. ";
  11922. } else {
  11923. $fakeFrom .= "
  11924. ON (
  11925. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11926. )
  11927. ";
  11928. }
  11929. $resultData = Database::select(
  11930. 'f.*',
  11931. $fakeFrom,
  11932. [
  11933. 'where' => [
  11934. 'ip.visibility != ? AND ' => 2,
  11935. 'ip.tool = ? AND ' => TOOL_FORUM,
  11936. 'f.session_id = ? AND ' => $sessionId,
  11937. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11938. 'f.lp_id = ?' => intval($this->lp_id),
  11939. ],
  11940. ],
  11941. 'first'
  11942. );
  11943. if (empty($resultData)) {
  11944. return false;
  11945. }
  11946. return $resultData;
  11947. }
  11948. /**
  11949. * Create a forum for this learning path.
  11950. *
  11951. * @param int $forumCategoryId
  11952. *
  11953. * @return int The forum ID if was created. Otherwise return false
  11954. */
  11955. public function createForum($forumCategoryId)
  11956. {
  11957. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11958. $forumId = store_forum(
  11959. [
  11960. 'lp_id' => $this->lp_id,
  11961. 'forum_title' => $this->name,
  11962. 'forum_comment' => null,
  11963. 'forum_category' => (int) $forumCategoryId,
  11964. 'students_can_edit_group' => ['students_can_edit' => 0],
  11965. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11966. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11967. 'group_forum' => 0,
  11968. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11969. ],
  11970. [],
  11971. true
  11972. );
  11973. return $forumId;
  11974. }
  11975. /**
  11976. * Get the LP Final Item form.
  11977. *
  11978. * @throws Exception
  11979. * @throws HTML_QuickForm_Error
  11980. *
  11981. * @return string
  11982. */
  11983. public function getFinalItemForm()
  11984. {
  11985. $finalItem = $this->getFinalItem();
  11986. $title = '';
  11987. if ($finalItem) {
  11988. $title = $finalItem->get_title();
  11989. $buttonText = get_lang('Save');
  11990. $content = $this->getSavedFinalItem();
  11991. } else {
  11992. $buttonText = get_lang('LPCreateDocument');
  11993. $content = $this->getFinalItemTemplate();
  11994. }
  11995. $courseInfo = api_get_course_info();
  11996. $result = $this->generate_lp_folder($courseInfo);
  11997. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11998. $relative_prefix = '../../';
  11999. $editorConfig = [
  12000. 'ToolbarSet' => 'LearningPathDocuments',
  12001. 'Width' => '100%',
  12002. 'Height' => '500',
  12003. 'FullPage' => true,
  12004. 'CreateDocumentDir' => $relative_prefix,
  12005. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  12006. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  12007. ];
  12008. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  12009. 'type' => 'document',
  12010. 'lp_id' => $this->lp_id,
  12011. ]);
  12012. $form = new FormValidator('final_item', 'POST', $url);
  12013. $form->addText('title', get_lang('Title'));
  12014. $form->addButtonSave($buttonText);
  12015. $form->addHtml(
  12016. Display::return_message(
  12017. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  12018. 'normal',
  12019. false
  12020. )
  12021. );
  12022. $renderer = $form->defaultRenderer();
  12023. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  12024. $form->addHtmlEditor(
  12025. 'content_lp_certificate',
  12026. null,
  12027. true,
  12028. false,
  12029. $editorConfig,
  12030. true
  12031. );
  12032. $form->addHidden('action', 'add_final_item');
  12033. $form->addHidden('path', Session::read('pathItem'));
  12034. $form->addHidden('previous', $this->get_last());
  12035. $form->setDefaults(
  12036. ['title' => $title, 'content_lp_certificate' => $content]
  12037. );
  12038. if ($form->validate()) {
  12039. $values = $form->exportValues();
  12040. $lastItemId = $this->getLastInFirstLevel();
  12041. if (!$finalItem) {
  12042. $documentId = $this->create_document(
  12043. $this->course_info,
  12044. $values['content_lp_certificate'],
  12045. $values['title']
  12046. );
  12047. $this->add_item(
  12048. 0,
  12049. $lastItemId,
  12050. 'final_item',
  12051. $documentId,
  12052. $values['title'],
  12053. ''
  12054. );
  12055. Display::addFlash(
  12056. Display::return_message(get_lang('Added'))
  12057. );
  12058. } else {
  12059. $this->edit_document($this->course_info);
  12060. }
  12061. }
  12062. return $form->returnForm();
  12063. }
  12064. /**
  12065. * Check if the current lp item is first, both, last or none from lp list.
  12066. *
  12067. * @param int $currentItemId
  12068. *
  12069. * @return string
  12070. */
  12071. public function isFirstOrLastItem($currentItemId)
  12072. {
  12073. if ($this->debug > 0) {
  12074. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  12075. }
  12076. $lpItemId = [];
  12077. $typeListNotToVerify = self::getChapterTypes();
  12078. // Using get_toc() function instead $this->items because returns the correct order of the items
  12079. foreach ($this->get_toc() as $item) {
  12080. if (!in_array($item['type'], $typeListNotToVerify)) {
  12081. $lpItemId[] = $item['id'];
  12082. }
  12083. }
  12084. $lastLpItemIndex = count($lpItemId) - 1;
  12085. $position = array_search($currentItemId, $lpItemId);
  12086. switch ($position) {
  12087. case 0:
  12088. if (!$lastLpItemIndex) {
  12089. $answer = 'both';
  12090. break;
  12091. }
  12092. $answer = 'first';
  12093. break;
  12094. case $lastLpItemIndex:
  12095. $answer = 'last';
  12096. break;
  12097. default:
  12098. $answer = 'none';
  12099. }
  12100. return $answer;
  12101. }
  12102. /**
  12103. * Get whether this is a learning path with the accumulated SCORM time or not.
  12104. *
  12105. * @return int
  12106. */
  12107. public function getAccumulateScormTime()
  12108. {
  12109. return $this->accumulateScormTime;
  12110. }
  12111. /**
  12112. * Set whether this is a learning path with the accumulated SCORM time or not.
  12113. *
  12114. * @param int $value (0 = false, 1 = true)
  12115. *
  12116. * @return bool Always returns true
  12117. */
  12118. public function setAccumulateScormTime($value)
  12119. {
  12120. if ($this->debug > 0) {
  12121. error_log('In learnpath::setAccumulateScormTime()', 0);
  12122. }
  12123. $this->accumulateScormTime = (int) $value;
  12124. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  12125. $lp_id = $this->get_id();
  12126. $sql = "UPDATE $lp_table
  12127. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  12128. WHERE iid = $lp_id";
  12129. Database::query($sql);
  12130. return true;
  12131. }
  12132. /**
  12133. * Returns an HTML-formatted link to a resource, to incorporate directly into
  12134. * the new learning path tool.
  12135. *
  12136. * The function is a big switch on tool type.
  12137. * In each case, we query the corresponding table for information and build the link
  12138. * with that information.
  12139. *
  12140. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  12141. * previous work (display_addedresource_link_in_learnpath())
  12142. *
  12143. * @param int $course_id Course code
  12144. * @param int $learningPathId The learning path ID (in lp table)
  12145. * @param int $id_in_path the unique index in the items table
  12146. * @param int $lpViewId
  12147. *
  12148. * @return string
  12149. */
  12150. public static function rl_get_resource_link_for_learnpath(
  12151. $course_id,
  12152. $learningPathId,
  12153. $id_in_path,
  12154. $lpViewId
  12155. ) {
  12156. $session_id = api_get_session_id();
  12157. $course_info = api_get_course_info_by_id($course_id);
  12158. $learningPathId = (int) $learningPathId;
  12159. $id_in_path = (int) $id_in_path;
  12160. $lpViewId = (int) $lpViewId;
  12161. $em = Database::getManager();
  12162. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12163. /** @var CLpItem $rowItem */
  12164. $rowItem = $lpItemRepo->findOneBy([
  12165. 'cId' => $course_id,
  12166. 'lpId' => $learningPathId,
  12167. 'iid' => $id_in_path,
  12168. ]);
  12169. if (!$rowItem) {
  12170. // Try one more time with "id"
  12171. /** @var CLpItem $rowItem */
  12172. $rowItem = $lpItemRepo->findOneBy([
  12173. 'cId' => $course_id,
  12174. 'lpId' => $learningPathId,
  12175. 'id' => $id_in_path,
  12176. ]);
  12177. if (!$rowItem) {
  12178. return -1;
  12179. }
  12180. }
  12181. $course_code = $course_info['code'];
  12182. $type = $rowItem->getItemType();
  12183. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12184. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12185. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12186. $link = '';
  12187. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12188. switch ($type) {
  12189. case 'dir':
  12190. return $main_dir_path.'lp/blank.php';
  12191. case TOOL_CALENDAR_EVENT:
  12192. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12193. case TOOL_ANNOUNCEMENT:
  12194. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12195. case TOOL_LINK:
  12196. $linkInfo = Link::getLinkInfo($id);
  12197. if (isset($linkInfo['url'])) {
  12198. return $linkInfo['url'];
  12199. }
  12200. return '';
  12201. case TOOL_QUIZ:
  12202. if (empty($id)) {
  12203. return '';
  12204. }
  12205. // Get the lp_item_view with the highest view_count.
  12206. $learnpathItemViewResult = $em
  12207. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12208. ->findBy(
  12209. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12210. ['viewCount' => 'DESC'],
  12211. 1
  12212. );
  12213. /** @var CLpItemView $learnpathItemViewData */
  12214. $learnpathItemViewData = current($learnpathItemViewResult);
  12215. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12216. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12217. .http_build_query([
  12218. 'lp_init' => 1,
  12219. 'learnpath_item_view_id' => $learnpathItemViewId,
  12220. 'learnpath_id' => $learningPathId,
  12221. 'learnpath_item_id' => $id_in_path,
  12222. 'exerciseId' => $id,
  12223. ]);
  12224. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12225. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12226. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12227. $myrow = Database::fetch_array($result);
  12228. $path = $myrow['path'];
  12229. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12230. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12231. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12232. case TOOL_FORUM:
  12233. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12234. case TOOL_THREAD:
  12235. // forum post
  12236. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12237. if (empty($id)) {
  12238. return '';
  12239. }
  12240. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12241. $result = Database::query($sql);
  12242. $myrow = Database::fetch_array($result);
  12243. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12244. .$extraParams;
  12245. case TOOL_POST:
  12246. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12247. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12248. $myrow = Database::fetch_array($result);
  12249. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12250. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12251. case TOOL_READOUT_TEXT:
  12252. return api_get_path(WEB_CODE_PATH).
  12253. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  12254. case TOOL_DOCUMENT:
  12255. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  12256. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12257. if (empty($document)) {
  12258. // Try with normal id
  12259. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  12260. if (empty($document)) {
  12261. return '';
  12262. }
  12263. }
  12264. $documentPathInfo = pathinfo($document->getPath());
  12265. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  12266. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12267. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  12268. $openmethod = 2;
  12269. $officedoc = false;
  12270. Session::write('openmethod', $openmethod);
  12271. Session::write('officedoc', $officedoc);
  12272. if ($showDirectUrl) {
  12273. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12274. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  12275. if (Link::isPdfLink($file)) {
  12276. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  12277. return $pdfUrl;
  12278. }
  12279. }
  12280. return $file;
  12281. }
  12282. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12283. case TOOL_LP_FINAL_ITEM:
  12284. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12285. .$extraParams;
  12286. case 'assignments':
  12287. return $main_dir_path.'work/work.php?'.$extraParams;
  12288. case TOOL_DROPBOX:
  12289. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12290. case 'introduction_text': //DEPRECATED
  12291. return '';
  12292. case TOOL_COURSE_DESCRIPTION:
  12293. return $main_dir_path.'course_description?'.$extraParams;
  12294. case TOOL_GROUP:
  12295. return $main_dir_path.'group/group.php?'.$extraParams;
  12296. case TOOL_USER:
  12297. return $main_dir_path.'user/user.php?'.$extraParams;
  12298. case TOOL_STUDENTPUBLICATION:
  12299. if (!empty($rowItem->getPath())) {
  12300. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12301. }
  12302. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12303. }
  12304. return $link;
  12305. }
  12306. /**
  12307. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12308. *
  12309. * @author Yannick Warnier <ywarnier@beeznest.org>
  12310. *
  12311. * @param string $course_code Course code
  12312. * @param int $learningPathId
  12313. * @param int $id_in_path The resource ID
  12314. *
  12315. * @return string
  12316. */
  12317. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12318. {
  12319. $_course = api_get_course_info($course_code);
  12320. $course_id = $_course['real_id'];
  12321. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12322. $learningPathId = (int) $learningPathId;
  12323. $id_in_path = (int) $id_in_path;
  12324. $sql = "SELECT item_type, title, ref
  12325. FROM $tbl_lp_item
  12326. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12327. $res_item = Database::query($sql);
  12328. if (Database::num_rows($res_item) < 1) {
  12329. return '';
  12330. }
  12331. $row_item = Database::fetch_array($res_item);
  12332. $type = strtolower($row_item['item_type']);
  12333. $id = $row_item['ref'];
  12334. $output = '';
  12335. switch ($type) {
  12336. case TOOL_CALENDAR_EVENT:
  12337. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12338. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12339. $myrow = Database::fetch_array($result);
  12340. $output = $myrow['title'];
  12341. break;
  12342. case TOOL_ANNOUNCEMENT:
  12343. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12344. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12345. $myrow = Database::fetch_array($result);
  12346. $output = $myrow['title'];
  12347. break;
  12348. case TOOL_LINK:
  12349. // Doesn't take $target into account.
  12350. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12351. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12352. $myrow = Database::fetch_array($result);
  12353. $output = $myrow['title'];
  12354. break;
  12355. case TOOL_QUIZ:
  12356. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12357. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12358. $myrow = Database::fetch_array($result);
  12359. $output = $myrow['title'];
  12360. break;
  12361. case TOOL_FORUM:
  12362. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12363. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12364. $myrow = Database::fetch_array($result);
  12365. $output = $myrow['forum_name'];
  12366. break;
  12367. case TOOL_THREAD: //=topics
  12368. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12369. // Grabbing the title of the post.
  12370. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12371. $result_title = Database::query($sql_title);
  12372. $myrow_title = Database::fetch_array($result_title);
  12373. $output = $myrow_title['post_title'];
  12374. break;
  12375. case TOOL_POST:
  12376. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12377. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  12378. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12379. $result = Database::query($sql);
  12380. $post = Database::fetch_array($result);
  12381. $output = $post['post_title'];
  12382. break;
  12383. case 'dir':
  12384. $title = $row_item['title'];
  12385. if (!empty($title)) {
  12386. $output = $title;
  12387. } else {
  12388. $output = '-';
  12389. }
  12390. break;
  12391. case TOOL_DOCUMENT:
  12392. $title = $row_item['title'];
  12393. if (!empty($title)) {
  12394. $output = $title;
  12395. } else {
  12396. $output = '-';
  12397. }
  12398. break;
  12399. case 'hotpotatoes':
  12400. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12401. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12402. $myrow = Database::fetch_array($result);
  12403. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12404. $last = count($pathname) - 1; // Making a correct name for the link.
  12405. $filename = $pathname[$last]; // Making a correct name for the link.
  12406. $ext = explode('.', $filename);
  12407. $ext = strtolower($ext[sizeof($ext) - 1]);
  12408. $myrow['path'] = rawurlencode($myrow['path']);
  12409. $output = $filename;
  12410. break;
  12411. }
  12412. return stripslashes($output);
  12413. }
  12414. /**
  12415. * Get the parent names for the current item.
  12416. *
  12417. * @param int $newItemId Optional. The item ID
  12418. *
  12419. * @return array
  12420. */
  12421. public function getCurrentItemParentNames($newItemId = 0)
  12422. {
  12423. $newItemId = $newItemId ?: $this->get_current_item_id();
  12424. $return = [];
  12425. $item = $this->getItem($newItemId);
  12426. $parent = $this->getItem($item->get_parent());
  12427. while ($parent) {
  12428. $return[] = $parent->get_title();
  12429. $parent = $this->getItem($parent->get_parent());
  12430. }
  12431. return array_reverse($return);
  12432. }
  12433. /**
  12434. * Reads and process "lp_subscription_settings" setting.
  12435. *
  12436. * @return array
  12437. */
  12438. public static function getSubscriptionSettings()
  12439. {
  12440. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12441. if (empty($subscriptionSettings)) {
  12442. // By default allow both settings
  12443. $subscriptionSettings = [
  12444. 'allow_add_users_to_lp' => true,
  12445. 'allow_add_users_to_lp_category' => true,
  12446. ];
  12447. } else {
  12448. $subscriptionSettings = $subscriptionSettings['options'];
  12449. }
  12450. return $subscriptionSettings;
  12451. }
  12452. /**
  12453. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12454. */
  12455. public function exportToCourseBuildFormat()
  12456. {
  12457. if (!api_is_allowed_to_edit()) {
  12458. return false;
  12459. }
  12460. $courseBuilder = new CourseBuilder();
  12461. $itemList = [];
  12462. /** @var learnpathItem $item */
  12463. foreach ($this->items as $item) {
  12464. $itemList[$item->get_type()][] = $item->get_path();
  12465. }
  12466. if (empty($itemList)) {
  12467. return false;
  12468. }
  12469. if (isset($itemList['document'])) {
  12470. // Get parents
  12471. foreach ($itemList['document'] as $documentId) {
  12472. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12473. if (!empty($documentInfo['parents'])) {
  12474. foreach ($documentInfo['parents'] as $parentInfo) {
  12475. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12476. continue;
  12477. }
  12478. $itemList['document'][] = $parentInfo['iid'];
  12479. }
  12480. }
  12481. }
  12482. $courseInfo = api_get_course_info();
  12483. foreach ($itemList['document'] as $documentId) {
  12484. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12485. $items = DocumentManager::get_resources_from_source_html(
  12486. $documentInfo['absolute_path'],
  12487. true,
  12488. TOOL_DOCUMENT
  12489. );
  12490. if (!empty($items)) {
  12491. foreach ($items as $item) {
  12492. // Get information about source url
  12493. $url = $item[0]; // url
  12494. $scope = $item[1]; // scope (local, remote)
  12495. $type = $item[2]; // type (rel, abs, url)
  12496. $origParseUrl = parse_url($url);
  12497. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12498. if ($scope == 'local') {
  12499. if ($type == 'abs' || $type == 'rel') {
  12500. $documentFile = strstr($realOrigPath, 'document');
  12501. if (strpos($realOrigPath, $documentFile) !== false) {
  12502. $documentFile = str_replace('document', '', $documentFile);
  12503. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12504. // Document found! Add it to the list
  12505. if ($itemDocumentId) {
  12506. $itemList['document'][] = $itemDocumentId;
  12507. }
  12508. }
  12509. }
  12510. }
  12511. }
  12512. }
  12513. }
  12514. $courseBuilder->build_documents(
  12515. api_get_session_id(),
  12516. $this->get_course_int_id(),
  12517. true,
  12518. $itemList['document']
  12519. );
  12520. }
  12521. if (isset($itemList['quiz'])) {
  12522. $courseBuilder->build_quizzes(
  12523. api_get_session_id(),
  12524. $this->get_course_int_id(),
  12525. true,
  12526. $itemList['quiz']
  12527. );
  12528. }
  12529. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12530. /*if (!empty($itemList['thread'])) {
  12531. $postList = [];
  12532. foreach ($itemList['thread'] as $postId) {
  12533. $post = get_post_information($postId);
  12534. if ($post) {
  12535. if (!isset($itemList['forum'])) {
  12536. $itemList['forum'] = [];
  12537. }
  12538. $itemList['forum'][] = $post['forum_id'];
  12539. $postList[] = $postId;
  12540. }
  12541. }
  12542. if (!empty($postList)) {
  12543. $courseBuilder->build_forum_posts(
  12544. $this->get_course_int_id(),
  12545. null,
  12546. null,
  12547. $postList
  12548. );
  12549. }
  12550. }*/
  12551. if (!empty($itemList['thread'])) {
  12552. $threadList = [];
  12553. $em = Database::getManager();
  12554. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12555. foreach ($itemList['thread'] as $threadId) {
  12556. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12557. $thread = $repo->find($threadId);
  12558. if ($thread) {
  12559. $itemList['forum'][] = $thread->getForumId();
  12560. $threadList[] = $thread->getIid();
  12561. }
  12562. }
  12563. if (!empty($threadList)) {
  12564. $courseBuilder->build_forum_topics(
  12565. api_get_session_id(),
  12566. $this->get_course_int_id(),
  12567. null,
  12568. $threadList
  12569. );
  12570. }
  12571. }
  12572. $forumCategoryList = [];
  12573. if (isset($itemList['forum'])) {
  12574. foreach ($itemList['forum'] as $forumId) {
  12575. $forumInfo = get_forums($forumId);
  12576. $forumCategoryList[] = $forumInfo['forum_category'];
  12577. }
  12578. }
  12579. if (!empty($forumCategoryList)) {
  12580. $courseBuilder->build_forum_category(
  12581. api_get_session_id(),
  12582. $this->get_course_int_id(),
  12583. true,
  12584. $forumCategoryList
  12585. );
  12586. }
  12587. if (!empty($itemList['forum'])) {
  12588. $courseBuilder->build_forums(
  12589. api_get_session_id(),
  12590. $this->get_course_int_id(),
  12591. true,
  12592. $itemList['forum']
  12593. );
  12594. }
  12595. if (isset($itemList['link'])) {
  12596. $courseBuilder->build_links(
  12597. api_get_session_id(),
  12598. $this->get_course_int_id(),
  12599. true,
  12600. $itemList['link']
  12601. );
  12602. }
  12603. if (!empty($itemList['student_publication'])) {
  12604. $courseBuilder->build_works(
  12605. api_get_session_id(),
  12606. $this->get_course_int_id(),
  12607. true,
  12608. $itemList['student_publication']
  12609. );
  12610. }
  12611. $courseBuilder->build_learnpaths(
  12612. api_get_session_id(),
  12613. $this->get_course_int_id(),
  12614. true,
  12615. [$this->get_id()],
  12616. false
  12617. );
  12618. $courseBuilder->restoreDocumentsFromList();
  12619. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12620. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12621. $result = DocumentManager::file_send_for_download(
  12622. $zipPath,
  12623. true,
  12624. $this->get_name().'.zip'
  12625. );
  12626. if ($result) {
  12627. api_not_allowed();
  12628. }
  12629. return true;
  12630. }
  12631. /**
  12632. * Get whether this is a learning path with the accumulated work time or not.
  12633. *
  12634. * @return int
  12635. */
  12636. public function getAccumulateWorkTime()
  12637. {
  12638. return (int) $this->accumulateWorkTime;
  12639. }
  12640. /**
  12641. * Get whether this is a learning path with the accumulated work time or not.
  12642. *
  12643. * @return int
  12644. */
  12645. public function getAccumulateWorkTimeTotalCourse()
  12646. {
  12647. $table = Database::get_course_table(TABLE_LP_MAIN);
  12648. $sql = "SELECT SUM(accumulate_work_time) AS total
  12649. FROM $table
  12650. WHERE c_id = ".$this->course_int_id;
  12651. $result = Database::query($sql);
  12652. $row = Database::fetch_array($result);
  12653. return (int) $row['total'];
  12654. }
  12655. /**
  12656. * Set whether this is a learning path with the accumulated work time or not.
  12657. *
  12658. * @param int $value (0 = false, 1 = true)
  12659. *
  12660. * @return bool
  12661. */
  12662. public function setAccumulateWorkTime($value)
  12663. {
  12664. if (!api_get_configuration_value('lp_minimum_time')) {
  12665. return false;
  12666. }
  12667. $this->accumulateWorkTime = (int) $value;
  12668. $table = Database::get_course_table(TABLE_LP_MAIN);
  12669. $lp_id = $this->get_id();
  12670. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12671. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12672. Database::query($sql);
  12673. return true;
  12674. }
  12675. /**
  12676. * @param int $lpId
  12677. * @param int $courseId
  12678. *
  12679. * @return mixed
  12680. */
  12681. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12682. {
  12683. $lpId = (int) $lpId;
  12684. $courseId = (int) $courseId;
  12685. $table = Database::get_course_table(TABLE_LP_MAIN);
  12686. $sql = "SELECT accumulate_work_time
  12687. FROM $table
  12688. WHERE c_id = $courseId AND id = $lpId";
  12689. $result = Database::query($sql);
  12690. $row = Database::fetch_array($result);
  12691. return $row['accumulate_work_time'];
  12692. }
  12693. /**
  12694. * @param int $courseId
  12695. *
  12696. * @return int
  12697. */
  12698. public static function getAccumulateWorkTimeTotal($courseId)
  12699. {
  12700. $table = Database::get_course_table(TABLE_LP_MAIN);
  12701. $courseId = (int) $courseId;
  12702. $sql = "SELECT SUM(accumulate_work_time) AS total
  12703. FROM $table
  12704. WHERE c_id = $courseId";
  12705. $result = Database::query($sql);
  12706. $row = Database::fetch_array($result);
  12707. return (int) $row['total'];
  12708. }
  12709. /**
  12710. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12711. * and put the images in.
  12712. *
  12713. * @return array
  12714. */
  12715. public static function getIconSelect()
  12716. {
  12717. $theme = api_get_visual_theme();
  12718. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12719. $icons = ['' => get_lang('SelectAnOption')];
  12720. if (is_dir($path)) {
  12721. $finder = new Finder();
  12722. $finder->files()->in($path);
  12723. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12724. /** @var SplFileInfo $file */
  12725. foreach ($finder as $file) {
  12726. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12727. $icons[$file->getFilename()] = $file->getFilename();
  12728. }
  12729. }
  12730. }
  12731. return $icons;
  12732. }
  12733. /**
  12734. * @param int $lpId
  12735. *
  12736. * @return string
  12737. */
  12738. public static function getSelectedIcon($lpId)
  12739. {
  12740. $extraFieldValue = new ExtraFieldValue('lp');
  12741. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12742. $icon = '';
  12743. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12744. $icon = $lpIcon['value'];
  12745. }
  12746. return $icon;
  12747. }
  12748. /**
  12749. * @param int $lpId
  12750. *
  12751. * @return string
  12752. */
  12753. public static function getSelectedIconHtml($lpId)
  12754. {
  12755. $icon = self::getSelectedIcon($lpId);
  12756. if (empty($icon)) {
  12757. return '';
  12758. }
  12759. $theme = api_get_visual_theme();
  12760. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12761. return Display::img($path);
  12762. }
  12763. /**
  12764. * Get the depth level of LP item.
  12765. *
  12766. * @param array $items
  12767. * @param int $currentItemId
  12768. *
  12769. * @return int
  12770. */
  12771. private static function get_level_for_item($items, $currentItemId)
  12772. {
  12773. $parentItemId = 0;
  12774. if (isset($items[$currentItemId])) {
  12775. $parentItemId = $items[$currentItemId]->parent;
  12776. }
  12777. if ($parentItemId == 0) {
  12778. return 0;
  12779. } else {
  12780. return self::get_level_for_item($items, $parentItemId) + 1;
  12781. }
  12782. }
  12783. /**
  12784. * Generate the link for a learnpath category as course tool.
  12785. *
  12786. * @param int $categoryId
  12787. *
  12788. * @return string
  12789. */
  12790. private static function getCategoryLinkForTool($categoryId)
  12791. {
  12792. $categoryId = (int) $categoryId;
  12793. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12794. .http_build_query(
  12795. [
  12796. 'action' => 'view_category',
  12797. 'id' => $categoryId,
  12798. ]
  12799. );
  12800. return $link;
  12801. }
  12802. /**
  12803. * Return the scorm item type object with spaces replaced with _
  12804. * The return result is use to build a css classname like scorm_type_$return.
  12805. *
  12806. * @param $in_type
  12807. *
  12808. * @return mixed
  12809. */
  12810. private static function format_scorm_type_item($in_type)
  12811. {
  12812. return str_replace(' ', '_', $in_type);
  12813. }
  12814. /**
  12815. * Check and obtain the lp final item if exist.
  12816. *
  12817. * @return learnpathItem
  12818. */
  12819. private function getFinalItem()
  12820. {
  12821. if (empty($this->items)) {
  12822. return null;
  12823. }
  12824. foreach ($this->items as $item) {
  12825. if ($item->type !== 'final_item') {
  12826. continue;
  12827. }
  12828. return $item;
  12829. }
  12830. }
  12831. /**
  12832. * Get the LP Final Item Template.
  12833. *
  12834. * @return string
  12835. */
  12836. private function getFinalItemTemplate()
  12837. {
  12838. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12839. }
  12840. /**
  12841. * Get the LP Final Item Url.
  12842. *
  12843. * @return string
  12844. */
  12845. private function getSavedFinalItem()
  12846. {
  12847. $finalItem = $this->getFinalItem();
  12848. $doc = DocumentManager::get_document_data_by_id(
  12849. $finalItem->path,
  12850. $this->cc
  12851. );
  12852. if ($doc && file_exists($doc['absolute_path'])) {
  12853. return file_get_contents($doc['absolute_path']);
  12854. }
  12855. return '';
  12856. }
  12857. }