learnpath.class.php 524 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933
  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. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  62. public $prevent_reinit = 1;
  63. // Describes the mode of progress bar display.
  64. public $seriousgame_mode = 0;
  65. public $progress_bar_mode = '%';
  66. // Percentage progress as saved in the db.
  67. public $progress_db = 0;
  68. public $proximity; // Wether the content is distant or local or unknown.
  69. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  70. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  71. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  72. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  73. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  74. public $user_id; //ID of the user that is viewing/using the course
  75. public $update_queue = [];
  76. public $scorm_debug = 0;
  77. public $arrMenu = []; // Array for the menu items.
  78. public $debug = 0; // Logging level.
  79. public $lp_session_id = 0;
  80. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  81. public $prerequisite = 0;
  82. public $use_max_score = 1; // 1 or 0
  83. public $subscribeUsers = 0; // Subscribe users or not
  84. public $created_on = '';
  85. public $modified_on = '';
  86. public $publicated_on = '';
  87. public $expired_on = '';
  88. public $ref = null;
  89. public $course_int_id;
  90. public $course_info = [];
  91. public $categoryId;
  92. /**
  93. * Constructor.
  94. * Needs a database handler, a course code and a learnpath id from the database.
  95. * Also builds the list of items into $this->items.
  96. *
  97. * @param string $course Course code
  98. * @param int $lp_id c_lp.iid
  99. * @param int $user_id
  100. */
  101. public function __construct($course, $lp_id, $user_id)
  102. {
  103. $debug = $this->debug;
  104. $this->encoding = api_get_system_encoding();
  105. if ($debug) {
  106. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  107. }
  108. if (empty($course)) {
  109. $course = api_get_course_id();
  110. }
  111. $course_info = api_get_course_info($course);
  112. if (!empty($course_info)) {
  113. $this->cc = $course_info['code'];
  114. $this->course_info = $course_info;
  115. $course_id = $course_info['real_id'];
  116. } else {
  117. $this->error = 'Course code does not exist in database.';
  118. }
  119. $lp_id = (int) $lp_id;
  120. $course_id = (int) $course_id;
  121. $this->set_course_int_id($course_id);
  122. // Check learnpath ID.
  123. if (empty($lp_id) || empty($course_id)) {
  124. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  125. } else {
  126. // TODO: Make it flexible to use any course_code (still using env course code here).
  127. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  128. $sql = "SELECT * FROM $lp_table
  129. WHERE iid = $lp_id";
  130. if ($debug) {
  131. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  132. }
  133. $res = Database::query($sql);
  134. if (Database::num_rows($res) > 0) {
  135. $this->lp_id = $lp_id;
  136. $row = Database::fetch_array($res);
  137. $this->type = $row['lp_type'];
  138. $this->name = stripslashes($row['name']);
  139. $this->proximity = $row['content_local'];
  140. $this->theme = $row['theme'];
  141. $this->maker = $row['content_maker'];
  142. $this->prevent_reinit = $row['prevent_reinit'];
  143. $this->seriousgame_mode = $row['seriousgame_mode'];
  144. $this->license = $row['content_license'];
  145. $this->scorm_debug = $row['debug'];
  146. $this->js_lib = $row['js_lib'];
  147. $this->path = $row['path'];
  148. $this->preview_image = $row['preview_image'];
  149. $this->author = $row['author'];
  150. $this->hide_toc_frame = $row['hide_toc_frame'];
  151. $this->lp_session_id = $row['session_id'];
  152. $this->use_max_score = $row['use_max_score'];
  153. $this->subscribeUsers = $row['subscribe_users'];
  154. $this->created_on = $row['created_on'];
  155. $this->modified_on = $row['modified_on'];
  156. $this->ref = $row['ref'];
  157. $this->categoryId = $row['category_id'];
  158. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  159. if (!empty($row['publicated_on'])) {
  160. $this->publicated_on = $row['publicated_on'];
  161. }
  162. if (!empty($row['expired_on'])) {
  163. $this->expired_on = $row['expired_on'];
  164. }
  165. if ($this->type == 2) {
  166. if ($row['force_commit'] == 1) {
  167. $this->force_commit = true;
  168. }
  169. }
  170. $this->mode = $row['default_view_mod'];
  171. // Check user ID.
  172. if (empty($user_id)) {
  173. $this->error = 'User ID is empty';
  174. } else {
  175. $userInfo = api_get_user_info($user_id);
  176. if (!empty($userInfo)) {
  177. $this->user_id = $userInfo['user_id'];
  178. } else {
  179. $this->error = 'User ID does not exist in database #'.$user_id;
  180. }
  181. }
  182. // End of variables checking.
  183. $session_id = api_get_session_id();
  184. // Get the session condition for learning paths of the base + session.
  185. $session = api_get_session_condition($session_id);
  186. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  187. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  188. // Selecting by view_count descending allows to get the highest view_count first.
  189. $sql = "SELECT * FROM $lp_table
  190. WHERE
  191. c_id = $course_id AND
  192. lp_id = $lp_id AND
  193. user_id = $user_id
  194. $session
  195. ORDER BY view_count DESC";
  196. $res = Database::query($sql);
  197. if ($debug) {
  198. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  199. }
  200. if (Database::num_rows($res) > 0) {
  201. if ($debug) {
  202. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  203. }
  204. $row = Database::fetch_array($res);
  205. $this->attempt = $row['view_count'];
  206. $this->lp_view_id = $row['id'];
  207. $this->last_item_seen = $row['last_item'];
  208. $this->progress_db = $row['progress'];
  209. $this->lp_view_session_id = $row['session_id'];
  210. } elseif (!api_is_invitee()) {
  211. if ($debug) {
  212. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  213. }
  214. $this->attempt = 1;
  215. $params = [
  216. 'c_id' => $course_id,
  217. 'lp_id' => $lp_id,
  218. 'user_id' => $user_id,
  219. 'view_count' => 1,
  220. 'session_id' => $session_id,
  221. 'last_item' => 0,
  222. ];
  223. $this->last_item_seen = 0;
  224. $this->lp_view_session_id = $session_id;
  225. $this->lp_view_id = Database::insert($lp_table, $params);
  226. if (!empty($this->lp_view_id)) {
  227. $sql = "UPDATE $lp_table SET id = iid
  228. WHERE iid = ".$this->lp_view_id;
  229. Database::query($sql);
  230. }
  231. }
  232. // Initialise items.
  233. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  234. $sql = "SELECT * FROM $lp_item_table
  235. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  236. ORDER BY parent_item_id, display_order";
  237. $res = Database::query($sql);
  238. if ($debug) {
  239. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  240. error_log('-- Start while--');
  241. }
  242. $lp_item_id_list = [];
  243. while ($row = Database::fetch_array($res)) {
  244. $lp_item_id_list[] = $row['iid'];
  245. switch ($this->type) {
  246. case 3: //aicc
  247. $oItem = new aiccItem('db', $row['iid'], $course_id);
  248. if (is_object($oItem)) {
  249. $my_item_id = $oItem->get_id();
  250. $oItem->set_lp_view($this->lp_view_id, $course_id);
  251. $oItem->set_prevent_reinit($this->prevent_reinit);
  252. // Don't use reference here as the next loop will make the pointed object change.
  253. $this->items[$my_item_id] = $oItem;
  254. $this->refs_list[$oItem->ref] = $my_item_id;
  255. if ($debug) {
  256. error_log(
  257. 'learnpath::__construct() - '.
  258. 'aicc object with id '.$my_item_id.
  259. ' set in items[]',
  260. 0
  261. );
  262. }
  263. }
  264. break;
  265. case 2:
  266. $oItem = new scormItem('db', $row['iid'], $course_id);
  267. if (is_object($oItem)) {
  268. $my_item_id = $oItem->get_id();
  269. $oItem->set_lp_view($this->lp_view_id, $course_id);
  270. $oItem->set_prevent_reinit($this->prevent_reinit);
  271. // Don't use reference here as the next loop will make the pointed object change.
  272. $this->items[$my_item_id] = $oItem;
  273. $this->refs_list[$oItem->ref] = $my_item_id;
  274. if ($debug) {
  275. error_log('object with id '.$my_item_id.' set in items[]');
  276. }
  277. }
  278. break;
  279. case 1:
  280. default:
  281. if ($debug) {
  282. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  283. }
  284. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  285. if ($debug) {
  286. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  287. }
  288. if (is_object($oItem)) {
  289. $my_item_id = $oItem->get_id();
  290. // Moved down to when we are sure the item_view exists.
  291. //$oItem->set_lp_view($this->lp_view_id);
  292. $oItem->set_prevent_reinit($this->prevent_reinit);
  293. // Don't use reference here as the next loop will make the pointed object change.
  294. $this->items[$my_item_id] = $oItem;
  295. $this->refs_list[$my_item_id] = $my_item_id;
  296. if ($debug) {
  297. error_log(
  298. 'learnpath::__construct() '.__LINE__.
  299. ' - object with id '.$my_item_id.' set in items[]'
  300. );
  301. }
  302. }
  303. break;
  304. }
  305. // Setting the object level with variable $this->items[$i][parent]
  306. foreach ($this->items as $itemLPObject) {
  307. $level = self::get_level_for_item(
  308. $this->items,
  309. $itemLPObject->db_id
  310. );
  311. $itemLPObject->level = $level;
  312. }
  313. // Setting the view in the item object.
  314. if (is_object($this->items[$row['iid']])) {
  315. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  316. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  317. $this->items[$row['iid']]->current_start_time = 0;
  318. $this->items[$row['iid']]->current_stop_time = 0;
  319. }
  320. }
  321. }
  322. if ($debug) {
  323. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  324. }
  325. if (!empty($lp_item_id_list)) {
  326. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  327. if (!empty($lp_item_id_list_to_string)) {
  328. // Get last viewing vars.
  329. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  330. // This query should only return one or zero result.
  331. $sql = "SELECT lp_item_id, status
  332. FROM $itemViewTable
  333. WHERE
  334. c_id = $course_id AND
  335. lp_view_id = ".$this->lp_view_id." AND
  336. lp_item_id IN ('".$lp_item_id_list_to_string."')
  337. ORDER BY view_count DESC ";
  338. if ($debug) {
  339. error_log(
  340. 'learnpath::__construct() - Selecting item_views: '.$sql,
  341. 0
  342. );
  343. }
  344. $status_list = [];
  345. $res = Database::query($sql);
  346. while ($row = Database:: fetch_array($res)) {
  347. $status_list[$row['lp_item_id']] = $row['status'];
  348. }
  349. foreach ($lp_item_id_list as $item_id) {
  350. if (isset($status_list[$item_id])) {
  351. $status = $status_list[$item_id];
  352. if (is_object($this->items[$item_id])) {
  353. $this->items[$item_id]->set_status($status);
  354. if (empty($status)) {
  355. $this->items[$item_id]->set_status(
  356. $this->default_status
  357. );
  358. }
  359. }
  360. } else {
  361. if (!api_is_invitee()) {
  362. if (is_object($this->items[$item_id])) {
  363. $this->items[$item_id]->set_status(
  364. $this->default_status
  365. );
  366. }
  367. if (!empty($this->lp_view_id)) {
  368. // Add that row to the lp_item_view table so that
  369. // we have something to show in the stats page.
  370. $params = [
  371. 'c_id' => $course_id,
  372. 'lp_item_id' => $item_id,
  373. 'lp_view_id' => $this->lp_view_id,
  374. 'view_count' => 1,
  375. 'status' => 'not attempted',
  376. 'start_time' => time(),
  377. 'total_time' => 0,
  378. 'score' => 0,
  379. ];
  380. $insertId = Database::insert($itemViewTable, $params);
  381. if ($insertId) {
  382. $sql = "UPDATE $itemViewTable SET id = iid
  383. WHERE iid = $insertId";
  384. Database::query($sql);
  385. }
  386. $this->items[$item_id]->set_lp_view(
  387. $this->lp_view_id,
  388. $course_id
  389. );
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }
  396. $this->ordered_items = self::get_flat_ordered_items_list(
  397. $this->get_id(),
  398. 0,
  399. $course_id
  400. );
  401. $this->max_ordered_items = 0;
  402. foreach ($this->ordered_items as $index => $dummy) {
  403. if ($index > $this->max_ordered_items && !empty($dummy)) {
  404. $this->max_ordered_items = $index;
  405. }
  406. }
  407. // TODO: Define the current item better.
  408. $this->first();
  409. if ($debug) {
  410. error_log('lp_view_session_id '.$this->lp_view_session_id);
  411. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  412. }
  413. } else {
  414. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  415. }
  416. }
  417. }
  418. /**
  419. * @return string
  420. */
  421. public function getCourseCode()
  422. {
  423. return $this->cc;
  424. }
  425. /**
  426. * @return int
  427. */
  428. public function get_course_int_id()
  429. {
  430. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  431. }
  432. /**
  433. * @param $course_id
  434. *
  435. * @return int
  436. */
  437. public function set_course_int_id($course_id)
  438. {
  439. return $this->course_int_id = (int) $course_id;
  440. }
  441. /**
  442. * Function rewritten based on old_add_item() from Yannick Warnier.
  443. * Due the fact that users can decide where the item should come, I had to overlook this function and
  444. * I found it better to rewrite it. Old function is still available.
  445. * Added also the possibility to add a description.
  446. *
  447. * @param int $parent
  448. * @param int $previous
  449. * @param string $type
  450. * @param int $id resource ID (ref)
  451. * @param string $title
  452. * @param string $description
  453. * @param int $prerequisites
  454. * @param int $max_time_allowed
  455. * @param int $userId
  456. *
  457. * @return int
  458. */
  459. public function add_item(
  460. $parent,
  461. $previous,
  462. $type = 'dir',
  463. $id,
  464. $title,
  465. $description,
  466. $prerequisites = 0,
  467. $max_time_allowed = 0,
  468. $userId = 0
  469. ) {
  470. $course_id = $this->course_info['real_id'];
  471. if ($this->debug > 0) {
  472. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  473. }
  474. if (empty($course_id)) {
  475. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  476. $this->course_info = api_get_course_info($this->cc);
  477. $course_id = $this->course_info['real_id'];
  478. }
  479. $userId = empty($userId) ? api_get_user_id() : $userId;
  480. $sessionId = api_get_session_id();
  481. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  482. $_course = $this->course_info;
  483. $parent = (int) $parent;
  484. $previous = (int) $previous;
  485. $id = (int) $id;
  486. $max_time_allowed = htmlentities($max_time_allowed);
  487. if (empty($max_time_allowed)) {
  488. $max_time_allowed = 0;
  489. }
  490. $sql = "SELECT COUNT(iid) AS num
  491. FROM $tbl_lp_item
  492. WHERE
  493. c_id = $course_id AND
  494. lp_id = ".$this->get_id()." AND
  495. parent_item_id = ".$parent;
  496. $res_count = Database::query($sql);
  497. $row = Database::fetch_array($res_count);
  498. $num = $row['num'];
  499. $tmp_previous = 0;
  500. $display_order = 0;
  501. $next = 0;
  502. if ($num > 0) {
  503. if (empty($previous)) {
  504. $sql = "SELECT iid, next_item_id, display_order
  505. FROM $tbl_lp_item
  506. WHERE
  507. c_id = $course_id AND
  508. lp_id = ".$this->get_id()." AND
  509. parent_item_id = $parent AND
  510. previous_item_id = 0 OR
  511. previous_item_id = $parent";
  512. $result = Database::query($sql);
  513. $row = Database::fetch_array($result);
  514. if ($row) {
  515. $next = $row['iid'];
  516. }
  517. } else {
  518. $previous = (int) $previous;
  519. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  520. FROM $tbl_lp_item
  521. WHERE
  522. c_id = $course_id AND
  523. lp_id = ".$this->get_id()." AND
  524. id = $previous";
  525. $result = Database::query($sql);
  526. $row = Database::fetch_array($result);
  527. if ($row) {
  528. $tmp_previous = $row['iid'];
  529. $next = $row['next_item_id'];
  530. $display_order = $row['display_order'];
  531. }
  532. }
  533. }
  534. $id = (int) $id;
  535. $typeCleaned = Database::escape_string($type);
  536. $max_score = 100;
  537. if ($type === 'quiz') {
  538. $sql = 'SELECT SUM(ponderation)
  539. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  540. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  541. ON
  542. quiz_question.id = quiz_rel_question.question_id AND
  543. quiz_question.c_id = quiz_rel_question.c_id
  544. WHERE
  545. quiz_rel_question.exercice_id = '.$id." AND
  546. quiz_question.c_id = $course_id AND
  547. quiz_rel_question.c_id = $course_id ";
  548. $rsQuiz = Database::query($sql);
  549. $max_score = Database::result($rsQuiz, 0, 0);
  550. // Disabling the exercise if we add it inside a LP
  551. $exercise = new Exercise($course_id);
  552. $exercise->read($id);
  553. $exercise->disable();
  554. $exercise->save();
  555. }
  556. $params = [
  557. 'c_id' => $course_id,
  558. 'lp_id' => $this->get_id(),
  559. 'item_type' => $typeCleaned,
  560. 'ref' => '',
  561. 'title' => $title,
  562. 'description' => $description,
  563. 'path' => $id,
  564. 'max_score' => $max_score,
  565. 'parent_item_id' => $parent,
  566. 'previous_item_id' => $previous,
  567. 'next_item_id' => (int) $next,
  568. 'display_order' => $display_order + 1,
  569. 'prerequisite' => $prerequisites,
  570. 'max_time_allowed' => $max_time_allowed,
  571. 'min_score' => 0,
  572. 'launch_data' => '',
  573. ];
  574. if ($prerequisites != 0) {
  575. $params['prerequisite'] = $prerequisites;
  576. }
  577. $new_item_id = Database::insert($tbl_lp_item, $params);
  578. if ($new_item_id) {
  579. if ($this->debug > 2) {
  580. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  581. }
  582. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  583. Database::query($sql);
  584. if (!empty($next)) {
  585. $sql = "UPDATE $tbl_lp_item
  586. SET previous_item_id = $new_item_id
  587. WHERE c_id = $course_id AND id = $next";
  588. Database::query($sql);
  589. }
  590. // Update the item that should be before the new item.
  591. if (!empty($tmp_previous)) {
  592. $sql = "UPDATE $tbl_lp_item
  593. SET next_item_id = $new_item_id
  594. WHERE c_id = $course_id AND id = $tmp_previous";
  595. Database::query($sql);
  596. }
  597. // Update all the items after the new item.
  598. $sql = "UPDATE $tbl_lp_item
  599. SET display_order = display_order + 1
  600. WHERE
  601. c_id = $course_id AND
  602. lp_id = ".$this->get_id()." AND
  603. iid <> $new_item_id AND
  604. parent_item_id = $parent AND
  605. display_order > $display_order";
  606. Database::query($sql);
  607. // Update the item that should come after the new item.
  608. $sql = "UPDATE $tbl_lp_item
  609. SET ref = $new_item_id
  610. WHERE c_id = $course_id AND iid = $new_item_id";
  611. Database::query($sql);
  612. // Upload audio.
  613. if (!empty($_FILES['mp3']['name'])) {
  614. // Create the audio folder if it does not exist yet.
  615. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  616. if (!is_dir($filepath.'audio')) {
  617. mkdir(
  618. $filepath.'audio',
  619. api_get_permissions_for_new_directories()
  620. );
  621. $audio_id = add_document(
  622. $_course,
  623. '/audio',
  624. 'folder',
  625. 0,
  626. 'audio',
  627. '',
  628. 0,
  629. true,
  630. null,
  631. $sessionId,
  632. $userId
  633. );
  634. api_item_property_update(
  635. $_course,
  636. TOOL_DOCUMENT,
  637. $audio_id,
  638. 'FolderCreated',
  639. $userId,
  640. null,
  641. null,
  642. null,
  643. null,
  644. $sessionId
  645. );
  646. api_item_property_update(
  647. $_course,
  648. TOOL_DOCUMENT,
  649. $audio_id,
  650. 'invisible',
  651. $userId,
  652. null,
  653. null,
  654. null,
  655. null,
  656. $sessionId
  657. );
  658. }
  659. $file_path = handle_uploaded_document(
  660. $_course,
  661. $_FILES['mp3'],
  662. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  663. '/audio',
  664. $userId,
  665. '',
  666. '',
  667. '',
  668. '',
  669. false
  670. );
  671. // Getting the filename only.
  672. $file_components = explode('/', $file_path);
  673. $file = $file_components[count($file_components) - 1];
  674. // Store the mp3 file in the lp_item table.
  675. $sql = "UPDATE $tbl_lp_item SET
  676. audio = '".Database::escape_string($file)."'
  677. WHERE iid = '".intval($new_item_id)."'";
  678. Database::query($sql);
  679. }
  680. }
  681. return $new_item_id;
  682. }
  683. /**
  684. * Static admin function allowing addition of a learnpath to a course.
  685. *
  686. * @param string $courseCode
  687. * @param string $name
  688. * @param string $description
  689. * @param string $learnpath
  690. * @param string $origin
  691. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  692. * @param string $publicated_on
  693. * @param string $expired_on
  694. * @param int $categoryId
  695. * @param int $userId
  696. *
  697. * @return int The new learnpath ID on success, 0 on failure
  698. */
  699. public static function add_lp(
  700. $courseCode,
  701. $name,
  702. $description = '',
  703. $learnpath = 'guess',
  704. $origin = 'zip',
  705. $zipname = '',
  706. $publicated_on = '',
  707. $expired_on = '',
  708. $categoryId = 0,
  709. $userId = 0
  710. ) {
  711. global $charset;
  712. if (!empty($courseCode)) {
  713. $courseInfo = api_get_course_info($courseCode);
  714. $course_id = $courseInfo['real_id'];
  715. } else {
  716. $course_id = api_get_course_int_id();
  717. $courseInfo = api_get_course_info();
  718. }
  719. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  720. // Check course code exists.
  721. // Check lp_name doesn't exist, otherwise append something.
  722. $i = 0;
  723. $name = Database::escape_string($name);
  724. $categoryId = (int) $categoryId;
  725. // Session id.
  726. $session_id = api_get_session_id();
  727. $userId = empty($userId) ? api_get_user_id() : $userId;
  728. $check_name = "SELECT * FROM $tbl_lp
  729. WHERE c_id = $course_id AND name = '$name'";
  730. $res_name = Database::query($check_name);
  731. if (empty($publicated_on)) {
  732. $publicated_on = null;
  733. } else {
  734. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  735. }
  736. if (empty($expired_on)) {
  737. $expired_on = null;
  738. } else {
  739. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  740. }
  741. while (Database::num_rows($res_name)) {
  742. // There is already one such name, update the current one a bit.
  743. $i++;
  744. $name = $name.' - '.$i;
  745. $check_name = "SELECT * FROM $tbl_lp
  746. WHERE c_id = $course_id AND name = '$name'";
  747. $res_name = Database::query($check_name);
  748. }
  749. // New name does not exist yet; keep it.
  750. // Escape description.
  751. // Kevin: added htmlentities().
  752. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  753. $type = 1;
  754. switch ($learnpath) {
  755. case 'guess':
  756. break;
  757. case 'dokeos':
  758. case 'chamilo':
  759. $type = 1;
  760. break;
  761. case 'aicc':
  762. break;
  763. }
  764. switch ($origin) {
  765. case 'zip':
  766. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  767. break;
  768. case 'manual':
  769. default:
  770. $get_max = "SELECT MAX(display_order)
  771. FROM $tbl_lp WHERE c_id = $course_id";
  772. $res_max = Database::query($get_max);
  773. if (Database::num_rows($res_max) < 1) {
  774. $dsp = 1;
  775. } else {
  776. $row = Database::fetch_array($res_max);
  777. $dsp = $row[0] + 1;
  778. }
  779. $params = [
  780. 'c_id' => $course_id,
  781. 'lp_type' => $type,
  782. 'name' => $name,
  783. 'description' => $description,
  784. 'path' => '',
  785. 'default_view_mod' => 'embedded',
  786. 'default_encoding' => 'UTF-8',
  787. 'display_order' => $dsp,
  788. 'content_maker' => 'Chamilo',
  789. 'content_local' => 'local',
  790. 'js_lib' => '',
  791. 'session_id' => $session_id,
  792. 'created_on' => api_get_utc_datetime(),
  793. 'modified_on' => api_get_utc_datetime(),
  794. 'publicated_on' => $publicated_on,
  795. 'expired_on' => $expired_on,
  796. 'category_id' => $categoryId,
  797. 'force_commit' => 0,
  798. 'content_license' => '',
  799. 'debug' => 0,
  800. 'theme' => '',
  801. 'preview_image' => '',
  802. 'author' => '',
  803. 'prerequisite' => 0,
  804. 'hide_toc_frame' => 0,
  805. 'seriousgame_mode' => 0,
  806. 'autolaunch' => 0,
  807. 'max_attempts' => 0,
  808. 'subscribe_users' => 0,
  809. 'accumulate_scorm_time' => 1,
  810. ];
  811. $id = Database::insert($tbl_lp, $params);
  812. if ($id > 0) {
  813. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  814. Database::query($sql);
  815. // Insert into item_property.
  816. api_item_property_update(
  817. $courseInfo,
  818. TOOL_LEARNPATH,
  819. $id,
  820. 'LearnpathAdded',
  821. $userId
  822. );
  823. api_set_default_visibility(
  824. $id,
  825. TOOL_LEARNPATH,
  826. 0,
  827. $courseInfo,
  828. $session_id,
  829. $userId
  830. );
  831. return $id;
  832. }
  833. break;
  834. }
  835. }
  836. /**
  837. * Auto completes the parents of an item in case it's been completed or passed.
  838. *
  839. * @param int $item Optional ID of the item from which to look for parents
  840. */
  841. public function autocomplete_parents($item)
  842. {
  843. $debug = $this->debug;
  844. if ($debug) {
  845. error_log('Learnpath::autocomplete_parents()');
  846. }
  847. if (empty($item)) {
  848. $item = $this->current;
  849. }
  850. $currentItem = $this->getItem($item);
  851. if ($currentItem) {
  852. $parent_id = $currentItem->get_parent();
  853. $parent = $this->getItem($parent_id);
  854. if ($parent) {
  855. // if $item points to an object and there is a parent.
  856. if ($debug) {
  857. error_log(
  858. 'Autocompleting parent of item '.$item.' '.
  859. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  860. 0
  861. );
  862. }
  863. // New experiment including failed and browsed in completed status.
  864. //$current_status = $currentItem->get_status();
  865. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  866. // Fixes chapter auto complete
  867. if (true) {
  868. // If the current item is completed or passes or succeeded.
  869. $updateParentStatus = true;
  870. if ($debug) {
  871. error_log('Status of current item is alright');
  872. }
  873. foreach ($parent->get_children() as $childItemId) {
  874. $childItem = $this->getItem($childItemId);
  875. // If children was not set try to get the info
  876. if (empty($childItem->db_item_view_id)) {
  877. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  878. }
  879. // Check all his brothers (parent's children) for completion status.
  880. if ($childItemId != $item) {
  881. if ($debug) {
  882. error_log(
  883. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  884. 0
  885. );
  886. }
  887. // Trying completing parents of failed and browsed items as well.
  888. if ($childItem->status_is(
  889. [
  890. 'completed',
  891. 'passed',
  892. 'succeeded',
  893. 'browsed',
  894. 'failed',
  895. ]
  896. )
  897. ) {
  898. // Keep completion status to true.
  899. continue;
  900. } else {
  901. if ($debug > 2) {
  902. error_log(
  903. '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,
  904. 0
  905. );
  906. }
  907. $updateParentStatus = false;
  908. break;
  909. }
  910. }
  911. }
  912. if ($updateParentStatus) {
  913. // If all the children were completed:
  914. $parent->set_status('completed');
  915. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  916. // Force the status to "completed"
  917. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  918. $this->update_queue[$parent->get_id()] = 'completed';
  919. if ($debug) {
  920. error_log(
  921. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  922. print_r($this->update_queue, 1),
  923. 0
  924. );
  925. }
  926. // Recursive call.
  927. $this->autocomplete_parents($parent->get_id());
  928. }
  929. }
  930. } else {
  931. if ($debug) {
  932. error_log("Parent #$parent_id does not exists");
  933. }
  934. }
  935. } else {
  936. if ($debug) {
  937. error_log("#$item is an item that doesn't have parents");
  938. }
  939. }
  940. }
  941. /**
  942. * Closes the current resource.
  943. *
  944. * Stops the timer
  945. * Saves into the database if required
  946. * Clears the current resource data from this object
  947. *
  948. * @return bool True on success, false on failure
  949. */
  950. public function close()
  951. {
  952. if ($this->debug > 0) {
  953. error_log('In learnpath::close()', 0);
  954. }
  955. if (empty($this->lp_id)) {
  956. $this->error = 'Trying to close this learnpath but no ID is set';
  957. return false;
  958. }
  959. $this->current_time_stop = time();
  960. $this->ordered_items = [];
  961. $this->index = 0;
  962. unset($this->lp_id);
  963. //unset other stuff
  964. return true;
  965. }
  966. /**
  967. * Static admin function allowing removal of a learnpath.
  968. *
  969. * @param array $courseInfo
  970. * @param int $id Learnpath ID
  971. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  972. *
  973. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  974. */
  975. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  976. {
  977. $course_id = api_get_course_int_id();
  978. if (!empty($courseInfo)) {
  979. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  980. }
  981. // TODO: Implement a way of getting this to work when the current object is not set.
  982. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  983. // If an ID is specifically given and the current LP is not the same, prevent delete.
  984. if (!empty($id) && ($id != $this->lp_id)) {
  985. return false;
  986. }
  987. $lp = Database::get_course_table(TABLE_LP_MAIN);
  988. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  989. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  990. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  991. // Delete lp item id.
  992. foreach ($this->items as $lpItemId => $dummy) {
  993. $sql = "DELETE FROM $lp_item_view
  994. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  995. Database::query($sql);
  996. }
  997. // Proposed by Christophe (nickname: clefevre)
  998. $sql = "DELETE FROM $lp_item
  999. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1000. Database::query($sql);
  1001. $sql = "DELETE FROM $lp_view
  1002. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1003. Database::query($sql);
  1004. self::toggle_publish($this->lp_id, 'i');
  1005. if ($this->type == 2 || $this->type == 3) {
  1006. // This is a scorm learning path, delete the files as well.
  1007. $sql = "SELECT path FROM $lp
  1008. WHERE iid = ".$this->lp_id;
  1009. $res = Database::query($sql);
  1010. if (Database::num_rows($res) > 0) {
  1011. $row = Database::fetch_array($res);
  1012. $path = $row['path'];
  1013. $sql = "SELECT id FROM $lp
  1014. WHERE
  1015. c_id = $course_id AND
  1016. path = '$path' AND
  1017. iid != ".$this->lp_id;
  1018. $res = Database::query($sql);
  1019. if (Database::num_rows($res) > 0) {
  1020. // Another learning path uses this directory, so don't delete it.
  1021. if ($this->debug > 2) {
  1022. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1023. }
  1024. } else {
  1025. // No other LP uses that directory, delete it.
  1026. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1027. // The absolute system path for this course.
  1028. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1029. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1030. if ($this->debug > 2) {
  1031. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1032. }
  1033. // Proposed by Christophe (clefevre).
  1034. if (strcmp(substr($path, -2), "/.") == 0) {
  1035. $path = substr($path, 0, -1); // Remove "." at the end.
  1036. }
  1037. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1038. rmdirr($course_scorm_dir.$path);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1044. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1045. // Delete tools
  1046. $sql = "DELETE FROM $tbl_tool
  1047. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1048. Database::query($sql);
  1049. $sql = "DELETE FROM $lp
  1050. WHERE iid = ".$this->lp_id;
  1051. Database::query($sql);
  1052. // Updates the display order of all lps.
  1053. $this->update_display_order();
  1054. api_item_property_update(
  1055. api_get_course_info(),
  1056. TOOL_LEARNPATH,
  1057. $this->lp_id,
  1058. 'delete',
  1059. api_get_user_id()
  1060. );
  1061. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1062. api_get_course_id(),
  1063. 4,
  1064. $id,
  1065. api_get_session_id()
  1066. );
  1067. if ($link_info !== false) {
  1068. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1069. }
  1070. if (api_get_setting('search_enabled') == 'true') {
  1071. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1072. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1073. }
  1074. }
  1075. /**
  1076. * Removes all the children of one item - dangerous!
  1077. *
  1078. * @param int $id Element ID of which children have to be removed
  1079. *
  1080. * @return int Total number of children removed
  1081. */
  1082. public function delete_children_items($id)
  1083. {
  1084. $course_id = $this->course_info['real_id'];
  1085. if ($this->debug > 0) {
  1086. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1087. }
  1088. $num = 0;
  1089. if (empty($id) || $id != strval(intval($id))) {
  1090. return false;
  1091. }
  1092. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1093. $sql = "SELECT * FROM $lp_item
  1094. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1095. $res = Database::query($sql);
  1096. while ($row = Database::fetch_array($res)) {
  1097. $num += $this->delete_children_items($row['iid']);
  1098. $sql = "DELETE FROM $lp_item
  1099. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1100. Database::query($sql);
  1101. $num++;
  1102. }
  1103. return $num;
  1104. }
  1105. /**
  1106. * Removes an item from the current learnpath.
  1107. *
  1108. * @param int $id Elem ID (0 if first)
  1109. *
  1110. * @return int Number of elements moved
  1111. *
  1112. * @todo implement resource removal
  1113. */
  1114. public function delete_item($id)
  1115. {
  1116. $course_id = api_get_course_int_id();
  1117. if ($this->debug > 0) {
  1118. error_log('In learnpath::delete_item()', 0);
  1119. }
  1120. // TODO: Implement the resource removal.
  1121. if (empty($id) || $id != strval(intval($id))) {
  1122. return false;
  1123. }
  1124. // First select item to get previous, next, and display order.
  1125. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1126. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1127. $res_sel = Database::query($sql_sel);
  1128. if (Database::num_rows($res_sel) < 1) {
  1129. return false;
  1130. }
  1131. $row = Database::fetch_array($res_sel);
  1132. $previous = $row['previous_item_id'];
  1133. $next = $row['next_item_id'];
  1134. $display = $row['display_order'];
  1135. $parent = $row['parent_item_id'];
  1136. $lp = $row['lp_id'];
  1137. // Delete children items.
  1138. $num = $this->delete_children_items($id);
  1139. if ($this->debug > 2) {
  1140. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1141. }
  1142. // Now delete the item.
  1143. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1144. if ($this->debug > 2) {
  1145. error_log('Deleting item: '.$sql_del, 0);
  1146. }
  1147. Database::query($sql_del);
  1148. // Now update surrounding items.
  1149. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1150. WHERE iid = $previous";
  1151. Database::query($sql_upd);
  1152. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1153. WHERE iid = $next";
  1154. Database::query($sql_upd);
  1155. // Now update all following items with new display order.
  1156. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1157. WHERE
  1158. c_id = $course_id AND
  1159. lp_id = $lp AND
  1160. parent_item_id = $parent AND
  1161. display_order > $display";
  1162. Database::query($sql_all);
  1163. //Removing prerequisites since the item will not longer exist
  1164. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1165. WHERE c_id = $course_id AND prerequisite = $id";
  1166. Database::query($sql_all);
  1167. // Remove from search engine if enabled.
  1168. if (api_get_setting('search_enabled') === 'true') {
  1169. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1170. $sql = 'SELECT * FROM %s
  1171. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1172. LIMIT 1';
  1173. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1174. $res = Database::query($sql);
  1175. if (Database::num_rows($res) > 0) {
  1176. $row2 = Database::fetch_array($res);
  1177. $di = new ChamiloIndexer();
  1178. $di->remove_document($row2['search_did']);
  1179. }
  1180. $sql = 'DELETE 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. Database::query($sql);
  1185. }
  1186. }
  1187. /**
  1188. * Updates an item's content in place.
  1189. *
  1190. * @param int $id Element ID
  1191. * @param int $parent Parent item ID
  1192. * @param int $previous Previous item ID
  1193. * @param string $title Item title
  1194. * @param string $description Item description
  1195. * @param string $prerequisites Prerequisites (optional)
  1196. * @param array $audio The array resulting of the $_FILES[mp3] element
  1197. * @param int $max_time_allowed
  1198. * @param string $url
  1199. *
  1200. * @return bool True on success, false on error
  1201. */
  1202. public function edit_item(
  1203. $id,
  1204. $parent,
  1205. $previous,
  1206. $title,
  1207. $description,
  1208. $prerequisites = '0',
  1209. $audio = [],
  1210. $max_time_allowed = 0,
  1211. $url = ''
  1212. ) {
  1213. $course_id = api_get_course_int_id();
  1214. $_course = api_get_course_info();
  1215. if ($this->debug > 0) {
  1216. error_log('In learnpath::edit_item()', 0);
  1217. }
  1218. if (empty($max_time_allowed)) {
  1219. $max_time_allowed = 0;
  1220. }
  1221. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1222. return false;
  1223. }
  1224. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1225. $sql = "SELECT * FROM $tbl_lp_item
  1226. WHERE iid = $id";
  1227. $res_select = Database::query($sql);
  1228. $row_select = Database::fetch_array($res_select);
  1229. $audio_update_sql = '';
  1230. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1231. // Create the audio folder if it does not exist yet.
  1232. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1233. if (!is_dir($filepath.'audio')) {
  1234. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1235. $audio_id = add_document(
  1236. $_course,
  1237. '/audio',
  1238. 'folder',
  1239. 0,
  1240. 'audio'
  1241. );
  1242. api_item_property_update(
  1243. $_course,
  1244. TOOL_DOCUMENT,
  1245. $audio_id,
  1246. 'FolderCreated',
  1247. api_get_user_id(),
  1248. null,
  1249. null,
  1250. null,
  1251. null,
  1252. api_get_session_id()
  1253. );
  1254. api_item_property_update(
  1255. $_course,
  1256. TOOL_DOCUMENT,
  1257. $audio_id,
  1258. 'invisible',
  1259. api_get_user_id(),
  1260. null,
  1261. null,
  1262. null,
  1263. null,
  1264. api_get_session_id()
  1265. );
  1266. }
  1267. // Upload file in documents.
  1268. $pi = pathinfo($audio['name']);
  1269. if ($pi['extension'] == 'mp3') {
  1270. $c_det = api_get_course_info($this->cc);
  1271. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1272. $path = handle_uploaded_document(
  1273. $c_det,
  1274. $audio,
  1275. $bp,
  1276. '/audio',
  1277. api_get_user_id(),
  1278. 0,
  1279. null,
  1280. 0,
  1281. 'rename',
  1282. false,
  1283. 0
  1284. );
  1285. $path = substr($path, 7);
  1286. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1287. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1288. }
  1289. }
  1290. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1291. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1292. // TODO: htmlspecialchars to be checked for encoding related problems.
  1293. if ($same_parent && $same_previous) {
  1294. // Only update title and description.
  1295. $sql = "UPDATE $tbl_lp_item
  1296. SET title = '".Database::escape_string($title)."',
  1297. prerequisite = '".$prerequisites."',
  1298. description = '".Database::escape_string($description)."'
  1299. ".$audio_update_sql.",
  1300. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1301. WHERE iid = $id";
  1302. Database::query($sql);
  1303. } else {
  1304. $old_parent = $row_select['parent_item_id'];
  1305. $old_previous = $row_select['previous_item_id'];
  1306. $old_next = $row_select['next_item_id'];
  1307. $old_order = $row_select['display_order'];
  1308. $old_prerequisite = $row_select['prerequisite'];
  1309. $old_max_time_allowed = $row_select['max_time_allowed'];
  1310. /* BEGIN -- virtually remove the current item id */
  1311. /* for the next and previous item it is like the current item doesn't exist anymore */
  1312. if ($old_previous != 0) {
  1313. // Next
  1314. $sql = "UPDATE $tbl_lp_item
  1315. SET next_item_id = $old_next
  1316. WHERE iid = $old_previous";
  1317. Database::query($sql);
  1318. }
  1319. if (!empty($old_next)) {
  1320. // Previous
  1321. $sql = "UPDATE $tbl_lp_item
  1322. SET previous_item_id = $old_previous
  1323. WHERE iid = $old_next";
  1324. Database::query($sql);
  1325. }
  1326. // display_order - 1 for every item with a display_order
  1327. // bigger then the display_order of the current item.
  1328. $sql = "UPDATE $tbl_lp_item
  1329. SET display_order = display_order - 1
  1330. WHERE
  1331. c_id = $course_id AND
  1332. display_order > $old_order AND
  1333. lp_id = ".$this->lp_id." AND
  1334. parent_item_id = $old_parent";
  1335. Database::query($sql);
  1336. /* END -- virtually remove the current item id */
  1337. /* BEGIN -- update the current item id to his new location */
  1338. if ($previous == 0) {
  1339. // Select the data of the item that should come after the current item.
  1340. $sql = "SELECT id, display_order
  1341. FROM $tbl_lp_item
  1342. WHERE
  1343. c_id = $course_id AND
  1344. lp_id = ".$this->lp_id." AND
  1345. parent_item_id = $parent AND
  1346. previous_item_id = $previous";
  1347. $res_select_old = Database::query($sql);
  1348. $row_select_old = Database::fetch_array($res_select_old);
  1349. // If the new parent didn't have children before.
  1350. if (Database::num_rows($res_select_old) == 0) {
  1351. $new_next = 0;
  1352. $new_order = 1;
  1353. } else {
  1354. $new_next = $row_select_old['id'];
  1355. $new_order = $row_select_old['display_order'];
  1356. }
  1357. } else {
  1358. // Select the data of the item that should come before the current item.
  1359. $sql = "SELECT next_item_id, display_order
  1360. FROM $tbl_lp_item
  1361. WHERE iid = $previous";
  1362. $res_select_old = Database::query($sql);
  1363. $row_select_old = Database::fetch_array($res_select_old);
  1364. $new_next = $row_select_old['next_item_id'];
  1365. $new_order = $row_select_old['display_order'] + 1;
  1366. }
  1367. // TODO: htmlspecialchars to be checked for encoding related problems.
  1368. // Update the current item with the new data.
  1369. $sql = "UPDATE $tbl_lp_item
  1370. SET
  1371. title = '".Database::escape_string($title)."',
  1372. description = '".Database::escape_string($description)."',
  1373. parent_item_id = $parent,
  1374. previous_item_id = $previous,
  1375. next_item_id = $new_next,
  1376. display_order = $new_order
  1377. $audio_update_sql
  1378. WHERE iid = $id";
  1379. Database::query($sql);
  1380. if ($previous != 0) {
  1381. // Update the previous item's next_item_id.
  1382. $sql = "UPDATE $tbl_lp_item
  1383. SET next_item_id = $id
  1384. WHERE iid = $previous";
  1385. Database::query($sql);
  1386. }
  1387. if (!empty($new_next)) {
  1388. // Update the next item's previous_item_id.
  1389. $sql = "UPDATE $tbl_lp_item
  1390. SET previous_item_id = $id
  1391. WHERE iid = $new_next";
  1392. Database::query($sql);
  1393. }
  1394. if ($old_prerequisite != $prerequisites) {
  1395. $sql = "UPDATE $tbl_lp_item
  1396. SET prerequisite = '$prerequisites'
  1397. WHERE iid = $id";
  1398. Database::query($sql);
  1399. }
  1400. if ($old_max_time_allowed != $max_time_allowed) {
  1401. // update max time allowed
  1402. $sql = "UPDATE $tbl_lp_item
  1403. SET max_time_allowed = $max_time_allowed
  1404. WHERE iid = $id";
  1405. Database::query($sql);
  1406. }
  1407. // Update all the items with the same or a bigger display_order than the current item.
  1408. $sql = "UPDATE $tbl_lp_item
  1409. SET display_order = display_order + 1
  1410. WHERE
  1411. c_id = $course_id AND
  1412. lp_id = ".$this->get_id()." AND
  1413. iid <> $id AND
  1414. parent_item_id = $parent AND
  1415. display_order >= $new_order";
  1416. Database::query($sql);
  1417. }
  1418. if ($row_select['item_type'] == 'link') {
  1419. $link = new Link();
  1420. $linkId = $row_select['path'];
  1421. $link->updateLink($linkId, $url);
  1422. }
  1423. }
  1424. /**
  1425. * Updates an item's prereq in place.
  1426. *
  1427. * @param int $id Element ID
  1428. * @param string $prerequisite_id Prerequisite Element ID
  1429. * @param int $mastery_score Prerequisite min score
  1430. * @param int $max_score Prerequisite max score
  1431. *
  1432. * @return bool True on success, false on error
  1433. */
  1434. public function edit_item_prereq(
  1435. $id,
  1436. $prerequisite_id,
  1437. $mastery_score = 0,
  1438. $max_score = 100
  1439. ) {
  1440. $course_id = api_get_course_int_id();
  1441. if ($this->debug > 0) {
  1442. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','.$max_score.')', 0);
  1443. }
  1444. if (empty($id) || ($id != strval(intval($id))) || empty($prerequisite_id)) {
  1445. return false;
  1446. }
  1447. $prerequisite_id = (int) $prerequisite_id;
  1448. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1449. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1450. $mastery_score = 0;
  1451. }
  1452. if (!is_numeric($max_score) || $max_score < 0) {
  1453. $max_score = 100;
  1454. }
  1455. /*if ($mastery_score > $max_score) {
  1456. $max_score = $mastery_score;
  1457. }*/
  1458. if (!is_numeric($prerequisite_id)) {
  1459. $prerequisite_id = 'NULL';
  1460. }
  1461. $mastery_score = floatval($mastery_score);
  1462. $max_score = floatval($max_score);
  1463. $sql = " UPDATE $tbl_lp_item
  1464. SET
  1465. prerequisite = $prerequisite_id ,
  1466. prerequisite_min_score = $mastery_score ,
  1467. prerequisite_max_score = $max_score
  1468. WHERE iid = $id";
  1469. Database::query($sql);
  1470. // TODO: Update the item object (can be ignored for now because refreshed).
  1471. return true;
  1472. }
  1473. /**
  1474. * Gets all the chapters belonging to the same parent as the item/chapter given
  1475. * Can also be called as abstract method.
  1476. *
  1477. * @param int $id Item ID
  1478. *
  1479. * @return array A list of all the "brother items" (or an empty array on failure)
  1480. */
  1481. public function getSiblingDirectories($id)
  1482. {
  1483. $course_id = api_get_course_int_id();
  1484. if ($this->debug > 0) {
  1485. error_log('In learnpath::getSiblingDirectories()', 0);
  1486. }
  1487. if (empty($id) || $id != strval(intval($id))) {
  1488. return [];
  1489. }
  1490. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1491. $sql_parent = "SELECT * FROM $lp_item
  1492. WHERE iid = $id AND item_type='dir'";
  1493. $res_parent = Database::query($sql_parent);
  1494. if (Database::num_rows($res_parent) > 0) {
  1495. $row_parent = Database::fetch_array($res_parent);
  1496. $parent = $row_parent['parent_item_id'];
  1497. $sql = "SELECT * FROM $lp_item
  1498. WHERE
  1499. parent_item_id = $parent AND
  1500. iid = $id AND
  1501. item_type='dir'
  1502. ORDER BY display_order";
  1503. $res_bros = Database::query($sql);
  1504. $list = [];
  1505. while ($row_bro = Database::fetch_array($res_bros)) {
  1506. $list[] = $row_bro;
  1507. }
  1508. return $list;
  1509. }
  1510. return [];
  1511. }
  1512. /**
  1513. * Gets all the items belonging to the same parent as the item given
  1514. * Can also be called as abstract method.
  1515. *
  1516. * @param int $id Item ID
  1517. *
  1518. * @return array A list of all the "brother items" (or an empty array on failure)
  1519. */
  1520. public function get_brother_items($id)
  1521. {
  1522. $course_id = api_get_course_int_id();
  1523. if ($this->debug > 0) {
  1524. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1525. }
  1526. if (empty($id) || $id != strval(intval($id))) {
  1527. return [];
  1528. }
  1529. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1530. $sql_parent = "SELECT * FROM $lp_item
  1531. WHERE iid = $id";
  1532. $res_parent = Database::query($sql_parent);
  1533. if (Database::num_rows($res_parent) > 0) {
  1534. $row_parent = Database::fetch_array($res_parent);
  1535. $parent = $row_parent['parent_item_id'];
  1536. $sql = "SELECT * FROM $lp_item
  1537. WHERE c_id = $course_id AND parent_item_id = $parent
  1538. ORDER BY display_order";
  1539. $res_bros = Database::query($sql);
  1540. $list = [];
  1541. while ($row_bro = Database::fetch_array($res_bros)) {
  1542. $list[] = $row_bro;
  1543. }
  1544. return $list;
  1545. }
  1546. return [];
  1547. }
  1548. /**
  1549. * Get the specific prefix index terms of this learning path.
  1550. *
  1551. * @param string $prefix
  1552. *
  1553. * @return array Array of terms
  1554. */
  1555. public function get_common_index_terms_by_prefix($prefix)
  1556. {
  1557. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1558. $terms = get_specific_field_values_list_by_prefix(
  1559. $prefix,
  1560. $this->cc,
  1561. TOOL_LEARNPATH,
  1562. $this->lp_id
  1563. );
  1564. $prefix_terms = [];
  1565. if (!empty($terms)) {
  1566. foreach ($terms as $term) {
  1567. $prefix_terms[] = $term['value'];
  1568. }
  1569. }
  1570. return $prefix_terms;
  1571. }
  1572. /**
  1573. * Gets the number of items currently completed.
  1574. *
  1575. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1576. *
  1577. * @return int The number of items currently completed
  1578. */
  1579. public function get_complete_items_count($failedStatusException = false)
  1580. {
  1581. if ($this->debug > 0) {
  1582. error_log('In learnpath::get_complete_items_count()', 0);
  1583. }
  1584. $i = 0;
  1585. $completedStatusList = [
  1586. 'completed',
  1587. 'passed',
  1588. 'succeeded',
  1589. 'browsed',
  1590. ];
  1591. if (!$failedStatusException) {
  1592. $completedStatusList[] = 'failed';
  1593. }
  1594. foreach ($this->items as $id => $dummy) {
  1595. // Trying failed and browsed considered "progressed" as well.
  1596. if ($this->items[$id]->status_is($completedStatusList) &&
  1597. $this->items[$id]->get_type() != 'dir'
  1598. ) {
  1599. $i++;
  1600. }
  1601. }
  1602. return $i;
  1603. }
  1604. /**
  1605. * Gets the current item ID.
  1606. *
  1607. * @return int The current learnpath item id
  1608. */
  1609. public function get_current_item_id()
  1610. {
  1611. $current = 0;
  1612. if ($this->debug > 0) {
  1613. error_log('In learnpath::get_current_item_id()', 0);
  1614. }
  1615. if (!empty($this->current)) {
  1616. $current = $this->current;
  1617. }
  1618. if ($this->debug > 2) {
  1619. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1620. }
  1621. return $current;
  1622. }
  1623. /**
  1624. * Force to get the first learnpath item id.
  1625. *
  1626. * @return int The current learnpath item id
  1627. */
  1628. public function get_first_item_id()
  1629. {
  1630. $current = 0;
  1631. if (is_array($this->ordered_items)) {
  1632. $current = $this->ordered_items[0];
  1633. }
  1634. return $current;
  1635. }
  1636. /**
  1637. * Gets the total number of items available for viewing in this SCORM.
  1638. *
  1639. * @return int The total number of items
  1640. */
  1641. public function get_total_items_count()
  1642. {
  1643. if ($this->debug > 0) {
  1644. error_log('In learnpath::get_total_items_count()', 0);
  1645. }
  1646. return count($this->items);
  1647. }
  1648. /**
  1649. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1650. *
  1651. * @return int The total no-chapters number of items
  1652. */
  1653. public function getTotalItemsCountWithoutDirs()
  1654. {
  1655. if ($this->debug > 0) {
  1656. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1657. }
  1658. $total = 0;
  1659. $typeListNotToCount = self::getChapterTypes();
  1660. foreach ($this->items as $temp2) {
  1661. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1662. $total++;
  1663. }
  1664. }
  1665. return $total;
  1666. }
  1667. /**
  1668. * Sets the first element URL.
  1669. */
  1670. public function first()
  1671. {
  1672. if ($this->debug > 0) {
  1673. error_log('In learnpath::first()', 0);
  1674. error_log('$this->last_item_seen '.$this->last_item_seen);
  1675. }
  1676. // Test if the last_item_seen exists and is not a dir.
  1677. if (count($this->ordered_items) == 0) {
  1678. $this->index = 0;
  1679. }
  1680. if (!empty($this->last_item_seen) &&
  1681. !empty($this->items[$this->last_item_seen]) &&
  1682. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1683. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1684. //&& !$this->items[$this->last_item_seen]->is_done()
  1685. ) {
  1686. if ($this->debug > 2) {
  1687. error_log(
  1688. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1689. $this->items[$this->last_item_seen]->get_type()
  1690. );
  1691. }
  1692. $index = -1;
  1693. foreach ($this->ordered_items as $myindex => $item_id) {
  1694. if ($item_id == $this->last_item_seen) {
  1695. $index = $myindex;
  1696. break;
  1697. }
  1698. }
  1699. if ($index == -1) {
  1700. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1701. if ($this->debug > 2) {
  1702. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1703. }
  1704. return false;
  1705. } else {
  1706. $this->last = $this->last_item_seen;
  1707. $this->current = $this->last_item_seen;
  1708. $this->index = $index;
  1709. }
  1710. } else {
  1711. if ($this->debug > 2) {
  1712. error_log('In learnpath::first() - No last item seen', 0);
  1713. }
  1714. $index = 0;
  1715. // Loop through all ordered items and stop at the first item that is
  1716. // not a directory *and* that has not been completed yet.
  1717. while (!empty($this->ordered_items[$index]) &&
  1718. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1719. (
  1720. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1721. $this->items[$this->ordered_items[$index]]->is_done() === true
  1722. ) && $index < $this->max_ordered_items) {
  1723. $index++;
  1724. }
  1725. $this->last = $this->current;
  1726. // current is
  1727. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1728. $this->index = $index;
  1729. if ($this->debug > 2) {
  1730. error_log('$index '.$index);
  1731. error_log('In learnpath::first() - No last item seen');
  1732. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1733. }
  1734. }
  1735. if ($this->debug > 2) {
  1736. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1737. }
  1738. }
  1739. /**
  1740. * Gets the information about an item in a format usable as JavaScript to update
  1741. * the JS API by just printing this content into the <head> section of the message frame.
  1742. *
  1743. * @param int $item_id
  1744. *
  1745. * @return string
  1746. */
  1747. public function get_js_info($item_id = 0)
  1748. {
  1749. if ($this->debug > 0) {
  1750. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1751. }
  1752. $info = '';
  1753. $item_id = intval($item_id);
  1754. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1755. //if item is defined, return values from DB
  1756. $oItem = $this->items[$item_id];
  1757. $info .= '<script language="javascript">';
  1758. $info .= "top.set_score(".$oItem->get_score().");\n";
  1759. $info .= "top.set_max(".$oItem->get_max().");\n";
  1760. $info .= "top.set_min(".$oItem->get_min().");\n";
  1761. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1762. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1763. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1764. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1765. $info .= "top.set_flag_synchronized();";
  1766. $info .= '</script>';
  1767. if ($this->debug > 2) {
  1768. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1769. }
  1770. return $info;
  1771. } else {
  1772. // If item_id is empty, just update to default SCORM data.
  1773. $info .= '<script language="javascript">';
  1774. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1775. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1776. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1777. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1778. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1779. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1780. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1781. $info .= "top.set_flag_synchronized();";
  1782. $info .= '</script>';
  1783. if ($this->debug > 2) {
  1784. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1785. }
  1786. return $info;
  1787. }
  1788. }
  1789. /**
  1790. * Gets the js library from the database.
  1791. *
  1792. * @return string The name of the javascript library to be used
  1793. */
  1794. public function get_js_lib()
  1795. {
  1796. $lib = '';
  1797. if (!empty($this->js_lib)) {
  1798. $lib = $this->js_lib;
  1799. }
  1800. return $lib;
  1801. }
  1802. /**
  1803. * Gets the learnpath database ID.
  1804. *
  1805. * @return int Learnpath ID in the lp table
  1806. */
  1807. public function get_id()
  1808. {
  1809. if (!empty($this->lp_id)) {
  1810. return $this->lp_id;
  1811. } else {
  1812. return 0;
  1813. }
  1814. }
  1815. /**
  1816. * Gets the last element URL.
  1817. *
  1818. * @return string URL to load into the viewer
  1819. */
  1820. public function get_last()
  1821. {
  1822. if ($this->debug > 0) {
  1823. error_log('In learnpath::get_last()', 0);
  1824. }
  1825. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1826. if (count($this->ordered_items) > 0) {
  1827. $this->index = count($this->ordered_items) - 1;
  1828. return $this->ordered_items[$this->index];
  1829. }
  1830. return false;
  1831. }
  1832. /**
  1833. * Gets the navigation bar for the learnpath display screen.
  1834. *
  1835. * @return string The HTML string to use as a navigation bar
  1836. */
  1837. public function get_navigation_bar($idBar = null, $display = null)
  1838. {
  1839. if ($this->debug > 0) {
  1840. error_log('In learnpath::get_navigation_bar()', 0);
  1841. }
  1842. if (empty($idBar)) {
  1843. $idBar = 'control-top';
  1844. }
  1845. $lpId = $this->lp_id;
  1846. $mycurrentitemid = $this->get_current_item_id();
  1847. $reportingText = get_lang('Reporting');
  1848. $previousText = get_lang('ScormPrevious');
  1849. $nextText = get_lang('ScormNext');
  1850. $fullScreenText = get_lang('ScormExitFullScreen');
  1851. $settings = api_get_configuration_value('lp_view_settings');
  1852. $display = isset($settings['display']) ? $settings['display'] : false;
  1853. $reportingIcon = '
  1854. <a class="icon-toolbar"
  1855. id="stats_link"
  1856. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1857. onclick="window.parent.API.save_asset(); return true;"
  1858. target="content_name" title="'.$reportingText.'">
  1859. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1860. </a>';
  1861. if (!empty($display)) {
  1862. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1863. if ($showReporting == false) {
  1864. $reportingIcon = '';
  1865. }
  1866. }
  1867. $hideArrows = false;
  1868. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1869. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1870. }
  1871. $previousIcon = '';
  1872. $nextIcon = '';
  1873. if ($hideArrows === false) {
  1874. $previousIcon = '
  1875. <a class="icon-toolbar" id="scorm-previous" href="#"
  1876. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1877. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1878. </a>';
  1879. $nextIcon = '
  1880. <a class="icon-toolbar" id="scorm-next" href="#"
  1881. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1882. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1883. </a>';
  1884. }
  1885. if ($this->mode === 'fullscreen') {
  1886. $navbar = '
  1887. <span id="'.$idBar.'" class="buttons">
  1888. '.$reportingIcon.'
  1889. '.$previousIcon.'
  1890. '.$nextIcon.'
  1891. <a class="icon-toolbar" id="view-embedded"
  1892. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1893. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1894. </a>
  1895. </span>';
  1896. } else {
  1897. $navbar = '
  1898. <span id="'.$idBar.'" class="buttons text-right">
  1899. '.$reportingIcon.'
  1900. '.$previousIcon.'
  1901. '.$nextIcon.'
  1902. </span>';
  1903. }
  1904. return $navbar;
  1905. }
  1906. /**
  1907. * Gets the next resource in queue (url).
  1908. *
  1909. * @return string URL to load into the viewer
  1910. */
  1911. public function get_next_index()
  1912. {
  1913. if ($this->debug > 0) {
  1914. error_log('In learnpath::get_next_index()', 0);
  1915. }
  1916. // TODO
  1917. $index = $this->index;
  1918. $index++;
  1919. if ($this->debug > 2) {
  1920. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1921. }
  1922. while (
  1923. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1924. $index < $this->max_ordered_items
  1925. ) {
  1926. $index++;
  1927. if ($index == $this->max_ordered_items) {
  1928. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1929. return $this->index;
  1930. } else {
  1931. return $index;
  1932. }
  1933. }
  1934. }
  1935. if (empty($this->ordered_items[$index])) {
  1936. return $this->index;
  1937. }
  1938. if ($this->debug > 2) {
  1939. error_log('index is now '.$index, 0);
  1940. }
  1941. return $index;
  1942. }
  1943. /**
  1944. * Gets item_id for the next element.
  1945. *
  1946. * @return int Next item (DB) ID
  1947. */
  1948. public function get_next_item_id()
  1949. {
  1950. if ($this->debug > 0) {
  1951. error_log('In learnpath::get_next_item_id()', 0);
  1952. }
  1953. $new_index = $this->get_next_index();
  1954. if (!empty($new_index)) {
  1955. if (isset($this->ordered_items[$new_index])) {
  1956. if ($this->debug > 2) {
  1957. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1958. }
  1959. return $this->ordered_items[$new_index];
  1960. }
  1961. }
  1962. if ($this->debug > 2) {
  1963. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1964. }
  1965. return 0;
  1966. }
  1967. /**
  1968. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1969. *
  1970. * Generally, the package provided is in the form of a zip file, so the function
  1971. * has been written to test a zip file. If not a zip, the function will return the
  1972. * default return value: ''
  1973. *
  1974. * @param string $file_path the path to the file
  1975. * @param string $file_name the original name of the file
  1976. *
  1977. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1978. */
  1979. public static function get_package_type($file_path, $file_name)
  1980. {
  1981. // Get name of the zip file without the extension.
  1982. $file_info = pathinfo($file_name);
  1983. $extension = $file_info['extension']; // Extension only.
  1984. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1985. 'dll',
  1986. 'exe',
  1987. ])) {
  1988. return 'oogie';
  1989. }
  1990. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1991. 'dll',
  1992. 'exe',
  1993. ])) {
  1994. return 'woogie';
  1995. }
  1996. $zipFile = new PclZip($file_path);
  1997. // Check the zip content (real size and file extension).
  1998. $zipContentArray = $zipFile->listContent();
  1999. $package_type = '';
  2000. $manifest = '';
  2001. $aicc_match_crs = 0;
  2002. $aicc_match_au = 0;
  2003. $aicc_match_des = 0;
  2004. $aicc_match_cst = 0;
  2005. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2006. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2007. foreach ($zipContentArray as $thisContent) {
  2008. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2009. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2010. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2011. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2012. $package_type = 'scorm';
  2013. break; // Exit the foreach loop.
  2014. } elseif (
  2015. preg_match('/aicc\//i', $thisContent['filename']) ||
  2016. in_array(
  2017. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2018. ['crs', 'au', 'des', 'cst']
  2019. )
  2020. ) {
  2021. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2022. switch ($ext) {
  2023. case 'crs':
  2024. $aicc_match_crs = 1;
  2025. break;
  2026. case 'au':
  2027. $aicc_match_au = 1;
  2028. break;
  2029. case 'des':
  2030. $aicc_match_des = 1;
  2031. break;
  2032. case 'cst':
  2033. $aicc_match_cst = 1;
  2034. break;
  2035. default:
  2036. break;
  2037. }
  2038. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2039. } else {
  2040. $package_type = '';
  2041. }
  2042. }
  2043. }
  2044. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2045. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2046. $package_type = 'aicc';
  2047. }
  2048. // Try with chamilo course builder
  2049. if (empty($package_type)) {
  2050. $package_type = 'chamilo';
  2051. }
  2052. return $package_type;
  2053. }
  2054. /**
  2055. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2056. *
  2057. * @return string URL to load into the viewer
  2058. */
  2059. public function get_previous_index()
  2060. {
  2061. if ($this->debug > 0) {
  2062. error_log('In learnpath::get_previous_index()', 0);
  2063. }
  2064. $index = $this->index;
  2065. if (isset($this->ordered_items[$index - 1])) {
  2066. $index--;
  2067. while (isset($this->ordered_items[$index]) &&
  2068. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2069. ) {
  2070. $index--;
  2071. if ($index < 0) {
  2072. return $this->index;
  2073. }
  2074. }
  2075. } else {
  2076. if ($this->debug > 2) {
  2077. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2078. }
  2079. // There is no previous item.
  2080. }
  2081. return $index;
  2082. }
  2083. /**
  2084. * Gets item_id for the next element.
  2085. *
  2086. * @return int Previous item (DB) ID
  2087. */
  2088. public function get_previous_item_id()
  2089. {
  2090. if ($this->debug > 0) {
  2091. error_log('In learnpath::get_previous_item_id()', 0);
  2092. }
  2093. $new_index = $this->get_previous_index();
  2094. return $this->ordered_items[$new_index];
  2095. }
  2096. /**
  2097. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2098. *
  2099. * @param int $lpItemId
  2100. * @param string $autostart
  2101. *
  2102. * @return string The mediaplayer HTML
  2103. */
  2104. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2105. {
  2106. $course_id = api_get_course_int_id();
  2107. $_course = api_get_course_info();
  2108. if (empty($_course)) {
  2109. return '';
  2110. }
  2111. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2112. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2113. $lpItemId = (int) $lpItemId;
  2114. // Getting all the information about the item.
  2115. $sql = "SELECT * FROM $tbl_lp_item as lpi
  2116. INNER JOIN $tbl_lp_item_view as lp_view
  2117. ON (lpi.iid = lp_view.lp_item_id)
  2118. WHERE
  2119. lpi.iid = $lpItemId AND
  2120. lp_view.c_id = $course_id";
  2121. $result = Database::query($sql);
  2122. $row = Database::fetch_assoc($result);
  2123. $output = '';
  2124. if (!empty($row['audio'])) {
  2125. $list = $_SESSION['oLP']->get_toc();
  2126. switch ($row['item_type']) {
  2127. case 'quiz':
  2128. $type_quiz = false;
  2129. foreach ($list as $toc) {
  2130. if ($toc['id'] == $_SESSION['oLP']->current) {
  2131. $type_quiz = true;
  2132. }
  2133. }
  2134. if ($type_quiz) {
  2135. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2136. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2137. } else {
  2138. $autostart_audio = $autostart;
  2139. }
  2140. }
  2141. break;
  2142. case TOOL_READOUT_TEXT:;
  2143. $autostart_audio = 'false';
  2144. break;
  2145. default:
  2146. $autostart_audio = 'true';
  2147. }
  2148. $courseInfo = api_get_course_info();
  2149. $audio = $row['audio'];
  2150. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2151. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2152. if (!file_exists($file)) {
  2153. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2154. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2155. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2156. }
  2157. $player = Display::getMediaPlayer(
  2158. $file,
  2159. [
  2160. 'id' => 'lp_audio_media_player',
  2161. 'url' => $url,
  2162. 'autoplay' => $autostart_audio,
  2163. 'width' => '100%',
  2164. ]
  2165. );
  2166. // The mp3 player.
  2167. $output = '<div id="container">';
  2168. $output .= $player;
  2169. $output .= '</div>';
  2170. }
  2171. return $output;
  2172. }
  2173. /**
  2174. * @param int $studentId
  2175. * @param int $prerequisite
  2176. * @param array $courseInfo
  2177. * @param int $sessionId
  2178. *
  2179. * @return bool
  2180. */
  2181. public static function isBlockedByPrerequisite(
  2182. $studentId,
  2183. $prerequisite,
  2184. $courseInfo,
  2185. $sessionId
  2186. ) {
  2187. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2188. if ($allow) {
  2189. if (api_is_allowed_to_edit() ||
  2190. api_is_platform_admin(true) ||
  2191. api_is_drh() ||
  2192. api_is_coach($sessionId, $courseInfo['real_id'], false)
  2193. ) {
  2194. return false;
  2195. }
  2196. }
  2197. $isBlocked = false;
  2198. if (!empty($prerequisite)) {
  2199. $progress = self::getProgress(
  2200. $prerequisite,
  2201. $studentId,
  2202. $courseInfo['real_id'],
  2203. $sessionId
  2204. );
  2205. if ($progress < 100) {
  2206. $isBlocked = true;
  2207. }
  2208. }
  2209. return $isBlocked;
  2210. }
  2211. /**
  2212. * Checks if the learning path is visible for student after the progress
  2213. * of its prerequisite is completed, considering the time availability and
  2214. * the LP visibility.
  2215. *
  2216. * @param int $lp_id
  2217. * @param int $student_id
  2218. * @param null $courseCode
  2219. * @param int $sessionId
  2220. *
  2221. * @return bool
  2222. */
  2223. public static function is_lp_visible_for_student(
  2224. $lp_id,
  2225. $student_id,
  2226. $courseCode = null,
  2227. $sessionId = 0
  2228. ) {
  2229. $courseInfo = api_get_course_info($courseCode);
  2230. $lp_id = (int) $lp_id;
  2231. $sessionId = (int) $sessionId;
  2232. if (empty($courseInfo)) {
  2233. return false;
  2234. }
  2235. if (empty($sessionId)) {
  2236. $sessionId = api_get_session_id();
  2237. }
  2238. $itemInfo = api_get_item_property_info(
  2239. $courseInfo['real_id'],
  2240. TOOL_LEARNPATH,
  2241. $lp_id,
  2242. $sessionId
  2243. );
  2244. // If the item was deleted.
  2245. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2246. return false;
  2247. }
  2248. // @todo remove this query and load the row info as a parameter
  2249. $table = Database::get_course_table(TABLE_LP_MAIN);
  2250. // Get current prerequisite
  2251. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2252. FROM $table
  2253. WHERE iid = $lp_id";
  2254. $rs = Database::query($sql);
  2255. $now = time();
  2256. if (Database::num_rows($rs) > 0) {
  2257. $row = Database::fetch_array($rs, 'ASSOC');
  2258. $prerequisite = $row['prerequisite'];
  2259. $is_visible = true;
  2260. $isBlocked = self::isBlockedByPrerequisite(
  2261. $student_id,
  2262. $prerequisite,
  2263. $courseInfo,
  2264. $sessionId
  2265. );
  2266. if ($isBlocked) {
  2267. $is_visible = false;
  2268. }
  2269. // Also check the time availability of the LP
  2270. if ($is_visible) {
  2271. // Adding visibility restrictions
  2272. if (!empty($row['publicated_on'])) {
  2273. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2274. $is_visible = false;
  2275. }
  2276. }
  2277. // Blocking empty start times see BT#2800
  2278. global $_custom;
  2279. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2280. $_custom['lps_hidden_when_no_start_date']
  2281. ) {
  2282. if (empty($row['publicated_on'])) {
  2283. $is_visible = false;
  2284. }
  2285. }
  2286. if (!empty($row['expired_on'])) {
  2287. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2288. $is_visible = false;
  2289. }
  2290. }
  2291. }
  2292. $subscriptionSettings = self::getSubscriptionSettings();
  2293. // Check if the subscription users/group to a LP is ON
  2294. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2295. $subscriptionSettings['allow_add_users_to_lp'] === true
  2296. ) {
  2297. // Try group
  2298. $is_visible = false;
  2299. // Checking only the user visibility
  2300. $userVisibility = api_get_item_visibility(
  2301. $courseInfo,
  2302. 'learnpath',
  2303. $row['id'],
  2304. $sessionId,
  2305. $student_id,
  2306. 'LearnpathSubscription'
  2307. );
  2308. if ($userVisibility == 1) {
  2309. $is_visible = true;
  2310. } else {
  2311. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2312. if (!empty($userGroups)) {
  2313. foreach ($userGroups as $groupInfo) {
  2314. $groupId = $groupInfo['iid'];
  2315. $userVisibility = api_get_item_visibility(
  2316. $courseInfo,
  2317. 'learnpath',
  2318. $row['id'],
  2319. $sessionId,
  2320. null,
  2321. 'LearnpathSubscription',
  2322. $groupId
  2323. );
  2324. if ($userVisibility == 1) {
  2325. $is_visible = true;
  2326. break;
  2327. }
  2328. }
  2329. }
  2330. }
  2331. }
  2332. return $is_visible;
  2333. }
  2334. return false;
  2335. }
  2336. /**
  2337. * @param int $lpId
  2338. * @param int $userId
  2339. * @param int $courseId
  2340. * @param int $sessionId
  2341. *
  2342. * @return int
  2343. */
  2344. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2345. {
  2346. $lpId = (int) $lpId;
  2347. $userId = (int) $userId;
  2348. $courseId = (int) $courseId;
  2349. $sessionId = (int) $sessionId;
  2350. $progress = 0;
  2351. $sessionCondition = api_get_session_condition($sessionId);
  2352. $table = Database::get_course_table(TABLE_LP_VIEW);
  2353. $sql = "SELECT * FROM $table
  2354. WHERE
  2355. c_id = $courseId AND
  2356. lp_id = $lpId AND
  2357. user_id = $userId $sessionCondition ";
  2358. $res = Database::query($sql);
  2359. if (Database::num_rows($res) > 0) {
  2360. $row = Database:: fetch_array($res);
  2361. $progress = $row['progress'];
  2362. }
  2363. return (int) $progress;
  2364. }
  2365. /**
  2366. * Displays a progress bar
  2367. * completed so far.
  2368. *
  2369. * @param int $percentage Progress value to display
  2370. * @param string $text_add Text to display near the progress value
  2371. *
  2372. * @return string HTML string containing the progress bar
  2373. */
  2374. public static function get_progress_bar($percentage = -1, $text_add = '')
  2375. {
  2376. $text = $percentage.$text_add;
  2377. $output = '<div class="progress">
  2378. <div id="progress_bar_value"
  2379. class="progress-bar progress-bar-success" role="progressbar"
  2380. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2381. '.$text.'
  2382. </div>
  2383. </div>';
  2384. return $output;
  2385. }
  2386. /**
  2387. * @param string $mode can be '%' or 'abs'
  2388. * otherwise this value will be used $this->progress_bar_mode
  2389. *
  2390. * @return string
  2391. */
  2392. public function getProgressBar($mode = null)
  2393. {
  2394. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2395. return self::get_progress_bar($percentage, $text_add);
  2396. }
  2397. /**
  2398. * Gets the progress bar info to display inside the progress bar.
  2399. * Also used by scorm_api.php.
  2400. *
  2401. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2402. * we display a number of completed elements per total elements
  2403. * @param int $add Additional steps to fake as completed
  2404. *
  2405. * @return array Percentage or number and symbol (% or /xx)
  2406. */
  2407. public function get_progress_bar_text($mode = '', $add = 0)
  2408. {
  2409. if ($this->debug > 0) {
  2410. error_log('In learnpath::get_progress_bar_text()', 0);
  2411. }
  2412. if (empty($mode)) {
  2413. $mode = $this->progress_bar_mode;
  2414. }
  2415. $total_items = $this->getTotalItemsCountWithoutDirs();
  2416. if ($this->debug > 2) {
  2417. error_log('Total items available in this learnpath: '.$total_items, 0);
  2418. }
  2419. $completeItems = $this->get_complete_items_count();
  2420. if ($this->debug > 2) {
  2421. error_log('Items completed so far: '.$completeItems, 0);
  2422. }
  2423. if ($add != 0) {
  2424. $completeItems += $add;
  2425. if ($this->debug > 2) {
  2426. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2427. }
  2428. }
  2429. $text = '';
  2430. if ($completeItems > $total_items) {
  2431. $completeItems = $total_items;
  2432. }
  2433. $percentage = 0;
  2434. if ($mode == '%') {
  2435. if ($total_items > 0) {
  2436. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2437. } else {
  2438. $percentage = 0;
  2439. }
  2440. $percentage = number_format($percentage, 0);
  2441. $text = '%';
  2442. } elseif ($mode == 'abs') {
  2443. $percentage = $completeItems;
  2444. $text = '/'.$total_items;
  2445. }
  2446. return [
  2447. $percentage,
  2448. $text,
  2449. ];
  2450. }
  2451. /**
  2452. * Gets the progress bar mode.
  2453. *
  2454. * @return string The progress bar mode attribute
  2455. */
  2456. public function get_progress_bar_mode()
  2457. {
  2458. if ($this->debug > 0) {
  2459. error_log('In learnpath::get_progress_bar_mode()', 0);
  2460. }
  2461. if (!empty($this->progress_bar_mode)) {
  2462. return $this->progress_bar_mode;
  2463. } else {
  2464. return '%';
  2465. }
  2466. }
  2467. /**
  2468. * Gets the learnpath theme (remote or local).
  2469. *
  2470. * @return string Learnpath theme
  2471. */
  2472. public function get_theme()
  2473. {
  2474. if ($this->debug > 0) {
  2475. error_log('In learnpath::get_theme()', 0);
  2476. }
  2477. if (!empty($this->theme)) {
  2478. return $this->theme;
  2479. } else {
  2480. return '';
  2481. }
  2482. }
  2483. /**
  2484. * Gets the learnpath session id.
  2485. *
  2486. * @return int
  2487. */
  2488. public function get_lp_session_id()
  2489. {
  2490. if ($this->debug > 0) {
  2491. error_log('In learnpath::get_lp_session_id()', 0);
  2492. }
  2493. if (!empty($this->lp_session_id)) {
  2494. return (int) $this->lp_session_id;
  2495. } else {
  2496. return 0;
  2497. }
  2498. }
  2499. /**
  2500. * Gets the learnpath image.
  2501. *
  2502. * @return string Web URL of the LP image
  2503. */
  2504. public function get_preview_image()
  2505. {
  2506. if ($this->debug > 0) {
  2507. error_log('In learnpath::get_preview_image()', 0);
  2508. }
  2509. if (!empty($this->preview_image)) {
  2510. return $this->preview_image;
  2511. } else {
  2512. return '';
  2513. }
  2514. }
  2515. /**
  2516. * @param string $size
  2517. * @param string $path_type
  2518. *
  2519. * @return bool|string
  2520. */
  2521. public function get_preview_image_path($size = null, $path_type = 'web')
  2522. {
  2523. $preview_image = $this->get_preview_image();
  2524. if (isset($preview_image) && !empty($preview_image)) {
  2525. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2526. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2527. if (isset($size)) {
  2528. $info = pathinfo($preview_image);
  2529. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2530. if (file_exists($image_sys_path.$image_custom_size)) {
  2531. if ($path_type == 'web') {
  2532. return $image_path.$image_custom_size;
  2533. } else {
  2534. return $image_sys_path.$image_custom_size;
  2535. }
  2536. }
  2537. } else {
  2538. if ($path_type == 'web') {
  2539. return $image_path.$preview_image;
  2540. } else {
  2541. return $image_sys_path.$preview_image;
  2542. }
  2543. }
  2544. }
  2545. return false;
  2546. }
  2547. /**
  2548. * Gets the learnpath author.
  2549. *
  2550. * @return string LP's author
  2551. */
  2552. public function get_author()
  2553. {
  2554. if ($this->debug > 0) {
  2555. error_log('In learnpath::get_author()', 0);
  2556. }
  2557. if (!empty($this->author)) {
  2558. return $this->author;
  2559. } else {
  2560. return '';
  2561. }
  2562. }
  2563. /**
  2564. * Gets hide table of contents.
  2565. *
  2566. * @return int
  2567. */
  2568. public function getHideTableOfContents()
  2569. {
  2570. return (int) $this->hide_toc_frame;
  2571. }
  2572. /**
  2573. * Generate a new prerequisites string for a given item. If this item was a sco and
  2574. * its prerequisites were strings (instead of IDs), then transform those strings into
  2575. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2576. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2577. * same rule as the scormExport() method.
  2578. *
  2579. * @param int $item_id Item ID
  2580. *
  2581. * @return string Prerequisites string ready for the export as SCORM
  2582. */
  2583. public function get_scorm_prereq_string($item_id)
  2584. {
  2585. if ($this->debug > 0) {
  2586. error_log('In learnpath::get_scorm_prereq_string()');
  2587. }
  2588. if (!is_object($this->items[$item_id])) {
  2589. return false;
  2590. }
  2591. /** @var learnpathItem $oItem */
  2592. $oItem = $this->items[$item_id];
  2593. $prereq = $oItem->get_prereq_string();
  2594. if (empty($prereq)) {
  2595. return '';
  2596. }
  2597. if (preg_match('/^\d+$/', $prereq) &&
  2598. isset($this->items[$prereq]) &&
  2599. is_object($this->items[$prereq])
  2600. ) {
  2601. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2602. // then simply return it (with the ITEM_ prefix).
  2603. //return 'ITEM_' . $prereq;
  2604. return $this->items[$prereq]->ref;
  2605. } else {
  2606. if (isset($this->refs_list[$prereq])) {
  2607. // It's a simple string item from which the ID can be found in the refs list,
  2608. // so we can transform it directly to an ID for export.
  2609. return $this->items[$this->refs_list[$prereq]]->ref;
  2610. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2611. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2612. } else {
  2613. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2614. // and replace them, one by one, by the internal IDs (chamilo db)
  2615. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2616. // by a space as well.
  2617. $find = [
  2618. '&',
  2619. '|',
  2620. '~',
  2621. '=',
  2622. '<>',
  2623. '{',
  2624. '}',
  2625. '*',
  2626. '(',
  2627. ')',
  2628. ];
  2629. $replace = [
  2630. ' ',
  2631. ' ',
  2632. ' ',
  2633. ' ',
  2634. ' ',
  2635. ' ',
  2636. ' ',
  2637. ' ',
  2638. ' ',
  2639. ' ',
  2640. ];
  2641. $prereq_mod = str_replace($find, $replace, $prereq);
  2642. $ids = explode(' ', $prereq_mod);
  2643. foreach ($ids as $id) {
  2644. $id = trim($id);
  2645. if (isset($this->refs_list[$id])) {
  2646. $prereq = preg_replace(
  2647. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2648. 'ITEM_'.$this->refs_list[$id],
  2649. $prereq
  2650. );
  2651. }
  2652. }
  2653. return $prereq;
  2654. }
  2655. }
  2656. }
  2657. /**
  2658. * Returns the XML DOM document's node.
  2659. *
  2660. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2661. * @param string $id The identifier to look for
  2662. *
  2663. * @return mixed The reference to the element found with that identifier. False if not found
  2664. */
  2665. public function get_scorm_xml_node(&$children, $id)
  2666. {
  2667. for ($i = 0; $i < $children->length; $i++) {
  2668. $item_temp = $children->item($i);
  2669. if ($item_temp->nodeName == 'item') {
  2670. if ($item_temp->getAttribute('identifier') == $id) {
  2671. return $item_temp;
  2672. }
  2673. }
  2674. $subchildren = $item_temp->childNodes;
  2675. if ($subchildren && $subchildren->length > 0) {
  2676. $val = $this->get_scorm_xml_node($subchildren, $id);
  2677. if (is_object($val)) {
  2678. return $val;
  2679. }
  2680. }
  2681. }
  2682. return false;
  2683. }
  2684. /**
  2685. * Gets the status list for all LP's items.
  2686. *
  2687. * @return array Array of [index] => [item ID => current status]
  2688. */
  2689. public function get_items_status_list()
  2690. {
  2691. if ($this->debug > 0) {
  2692. error_log('In learnpath::get_items_status_list()', 0);
  2693. }
  2694. $list = [];
  2695. foreach ($this->ordered_items as $item_id) {
  2696. $list[] = [
  2697. $item_id => $this->items[$item_id]->get_status(),
  2698. ];
  2699. }
  2700. return $list;
  2701. }
  2702. /**
  2703. * Return the number of interactions for the given learnpath Item View ID.
  2704. * This method can be used as static.
  2705. *
  2706. * @param int $lp_iv_id Item View ID
  2707. * @param int $course_id course id
  2708. *
  2709. * @return int
  2710. */
  2711. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2712. {
  2713. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2714. $lp_iv_id = (int) $lp_iv_id;
  2715. $course_id = (int) $course_id;
  2716. $sql = "SELECT count(*) FROM $table
  2717. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2718. $res = Database::query($sql);
  2719. $num = 0;
  2720. if (Database::num_rows($res)) {
  2721. $row = Database::fetch_array($res);
  2722. $num = $row[0];
  2723. }
  2724. return $num;
  2725. }
  2726. /**
  2727. * Return the interactions as an array for the given lp_iv_id.
  2728. * This method can be used as static.
  2729. *
  2730. * @param int $lp_iv_id Learnpath Item View ID
  2731. *
  2732. * @return array
  2733. *
  2734. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2735. */
  2736. public static function get_iv_interactions_array($lp_iv_id)
  2737. {
  2738. $course_id = api_get_course_int_id();
  2739. $list = [];
  2740. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2741. if (empty($lp_iv_id)) {
  2742. return [];
  2743. }
  2744. $sql = "SELECT * FROM $table
  2745. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2746. ORDER BY order_id ASC";
  2747. $res = Database::query($sql);
  2748. $num = Database::num_rows($res);
  2749. if ($num > 0) {
  2750. $list[] = [
  2751. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2752. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2753. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2754. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2755. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2756. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2757. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2758. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2759. ];
  2760. while ($row = Database::fetch_array($res)) {
  2761. $list[] = [
  2762. 'order_id' => ($row['order_id'] + 1),
  2763. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2764. 'type' => $row['interaction_type'],
  2765. 'time' => $row['completion_time'],
  2766. //'correct_responses' => $row['correct_responses'],
  2767. 'correct_responses' => '', // Hide correct responses from students.
  2768. 'student_response' => $row['student_response'],
  2769. 'result' => $row['result'],
  2770. 'latency' => $row['latency'],
  2771. ];
  2772. }
  2773. }
  2774. return $list;
  2775. }
  2776. /**
  2777. * Return the number of objectives for the given learnpath Item View ID.
  2778. * This method can be used as static.
  2779. *
  2780. * @param int $lp_iv_id Item View ID
  2781. * @param int $course_id Course ID
  2782. *
  2783. * @return int Number of objectives
  2784. */
  2785. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2786. {
  2787. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2788. $course_id = (int) $course_id;
  2789. $lp_iv_id = (int) $lp_iv_id;
  2790. $sql = "SELECT count(*) FROM $table
  2791. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2792. //@todo seems that this always returns 0
  2793. $res = Database::query($sql);
  2794. $num = 0;
  2795. if (Database::num_rows($res)) {
  2796. $row = Database::fetch_array($res);
  2797. $num = $row[0];
  2798. }
  2799. return $num;
  2800. }
  2801. /**
  2802. * Return the objectives as an array for the given lp_iv_id.
  2803. * This method can be used as static.
  2804. *
  2805. * @param int $lpItemViewId Learnpath Item View ID
  2806. *
  2807. * @return array
  2808. *
  2809. * @todo Translate labels
  2810. */
  2811. public static function get_iv_objectives_array($lpItemViewId = 0)
  2812. {
  2813. $course_id = api_get_course_int_id();
  2814. $lpItemViewId = (int) $lpItemViewId;
  2815. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2816. $sql = "SELECT * FROM $table
  2817. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2818. ORDER BY order_id ASC";
  2819. $res = Database::query($sql);
  2820. $num = Database::num_rows($res);
  2821. $list = [];
  2822. if ($num > 0) {
  2823. $list[] = [
  2824. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2825. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2826. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2827. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2828. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2829. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2830. ];
  2831. while ($row = Database::fetch_array($res)) {
  2832. $list[] = [
  2833. 'order_id' => ($row['order_id'] + 1),
  2834. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2835. 'score_raw' => $row['score_raw'],
  2836. 'score_max' => $row['score_max'],
  2837. 'score_min' => $row['score_min'],
  2838. 'status' => $row['status'],
  2839. ];
  2840. }
  2841. }
  2842. return $list;
  2843. }
  2844. /**
  2845. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2846. * used by get_html_toc() to be ready to display.
  2847. *
  2848. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2849. */
  2850. public function get_toc()
  2851. {
  2852. if ($this->debug > 0) {
  2853. error_log('learnpath::get_toc()', 0);
  2854. }
  2855. $toc = [];
  2856. foreach ($this->ordered_items as $item_id) {
  2857. if ($this->debug > 2) {
  2858. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2859. }
  2860. // TODO: Change this link generation and use new function instead.
  2861. $toc[] = [
  2862. 'id' => $item_id,
  2863. 'title' => $this->items[$item_id]->get_title(),
  2864. 'status' => $this->items[$item_id]->get_status(),
  2865. 'level' => $this->items[$item_id]->get_level(),
  2866. 'type' => $this->items[$item_id]->get_type(),
  2867. 'description' => $this->items[$item_id]->get_description(),
  2868. 'path' => $this->items[$item_id]->get_path(),
  2869. 'parent' => $this->items[$item_id]->get_parent(),
  2870. ];
  2871. }
  2872. if ($this->debug > 2) {
  2873. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2874. }
  2875. return $toc;
  2876. }
  2877. /**
  2878. * Generate and return the table of contents for this learnpath. The JS
  2879. * table returned is used inside of scorm_api.php.
  2880. *
  2881. * @param string $varname
  2882. *
  2883. * @return string A JS array variable construction
  2884. */
  2885. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2886. {
  2887. if ($this->debug > 0) {
  2888. error_log('In learnpath::get_items_details_as_js()', 0);
  2889. }
  2890. $toc = $varname.' = new Array();';
  2891. foreach ($this->ordered_items as $item_id) {
  2892. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2893. }
  2894. if ($this->debug > 2) {
  2895. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2896. }
  2897. return $toc;
  2898. }
  2899. /**
  2900. * Gets the learning path type.
  2901. *
  2902. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2903. *
  2904. * @return mixed Type ID or name, depending on the parameter
  2905. */
  2906. public function get_type($get_name = false)
  2907. {
  2908. $res = false;
  2909. if ($this->debug > 0) {
  2910. error_log('In learnpath::get_type()', 0);
  2911. }
  2912. if (!empty($this->type) && (!$get_name)) {
  2913. $res = $this->type;
  2914. }
  2915. if ($this->debug > 2) {
  2916. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2917. }
  2918. return $res;
  2919. }
  2920. /**
  2921. * Gets the learning path type as static method.
  2922. *
  2923. * @param int $lp_id
  2924. *
  2925. * @return mixed Type ID or name, depending on the parameter
  2926. */
  2927. public static function get_type_static($lp_id = 0)
  2928. {
  2929. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2930. $lp_id = (int) $lp_id;
  2931. $sql = "SELECT lp_type FROM $tbl_lp
  2932. WHERE iid = $lp_id";
  2933. $res = Database::query($sql);
  2934. if ($res === false) {
  2935. return null;
  2936. }
  2937. if (Database::num_rows($res) <= 0) {
  2938. return null;
  2939. }
  2940. $row = Database::fetch_array($res);
  2941. return $row['lp_type'];
  2942. }
  2943. /**
  2944. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2945. * This method can be used as abstract and is recursive.
  2946. *
  2947. * @param int $lp Learnpath ID
  2948. * @param int $parent Parent ID of the items to look for
  2949. * @param int $course_id
  2950. *
  2951. * @return array Ordered list of item IDs (empty array on error)
  2952. */
  2953. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2954. {
  2955. if (empty($course_id)) {
  2956. $course_id = api_get_course_int_id();
  2957. } else {
  2958. $course_id = (int) $course_id;
  2959. }
  2960. $list = [];
  2961. if (empty($lp)) {
  2962. return $list;
  2963. }
  2964. $lp = (int) $lp;
  2965. $parent = (int) $parent;
  2966. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2967. $sql = "SELECT iid FROM $tbl_lp_item
  2968. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2969. ORDER BY display_order";
  2970. $res = Database::query($sql);
  2971. while ($row = Database::fetch_array($res)) {
  2972. $sublist = self::get_flat_ordered_items_list(
  2973. $lp,
  2974. $row['iid'],
  2975. $course_id
  2976. );
  2977. $list[] = $row['iid'];
  2978. foreach ($sublist as $item) {
  2979. $list[] = $item;
  2980. }
  2981. }
  2982. return $list;
  2983. }
  2984. /**
  2985. * @return array
  2986. */
  2987. public static function getChapterTypes()
  2988. {
  2989. return [
  2990. 'dir',
  2991. ];
  2992. }
  2993. /**
  2994. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2995. *
  2996. * @param $tree
  2997. *
  2998. * @return array HTML TOC ready to display
  2999. */
  3000. public function getParentToc($tree)
  3001. {
  3002. if ($this->debug > 0) {
  3003. error_log('In learnpath::get_html_toc()', 0);
  3004. }
  3005. if (empty($tree)) {
  3006. $tree = $this->get_toc();
  3007. }
  3008. $dirTypes = self::getChapterTypes();
  3009. $myCurrentId = $this->get_current_item_id();
  3010. $listParent = [];
  3011. $listChildren = [];
  3012. $listNotParent = [];
  3013. $list = [];
  3014. foreach ($tree as $subtree) {
  3015. if (in_array($subtree['type'], $dirTypes)) {
  3016. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3017. $subtree['children'] = $listChildren;
  3018. if (!empty($subtree['children'])) {
  3019. foreach ($subtree['children'] as $subItem) {
  3020. if ($subItem['id'] == $this->current) {
  3021. $subtree['parent_current'] = 'in';
  3022. $subtree['current'] = 'on';
  3023. }
  3024. }
  3025. }
  3026. $listParent[] = $subtree;
  3027. }
  3028. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3029. $classStatus = [
  3030. 'not attempted' => 'scorm_not_attempted',
  3031. 'incomplete' => 'scorm_not_attempted',
  3032. 'failed' => 'scorm_failed',
  3033. 'completed' => 'scorm_completed',
  3034. 'passed' => 'scorm_completed',
  3035. 'succeeded' => 'scorm_completed',
  3036. 'browsed' => 'scorm_completed',
  3037. ];
  3038. if (isset($classStatus[$subtree['status']])) {
  3039. $cssStatus = $classStatus[$subtree['status']];
  3040. }
  3041. $title = Security::remove_XSS($subtree['title']);
  3042. unset($subtree['title']);
  3043. if (empty($title)) {
  3044. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3045. }
  3046. $classStyle = null;
  3047. if ($subtree['id'] == $this->current) {
  3048. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3049. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3050. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3051. }
  3052. $subtree['title'] = $title;
  3053. $subtree['class'] = $classStyle.' '.$cssStatus;
  3054. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3055. $subtree['current_id'] = $myCurrentId;
  3056. $listNotParent[] = $subtree;
  3057. }
  3058. }
  3059. $list['are_parents'] = $listParent;
  3060. $list['not_parents'] = $listNotParent;
  3061. return $list;
  3062. }
  3063. /**
  3064. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3065. *
  3066. * @param array $tree
  3067. * @param int $id
  3068. * @param bool $parent
  3069. *
  3070. * @return array HTML TOC ready to display
  3071. */
  3072. public function getChildrenToc($tree, $id, $parent = true)
  3073. {
  3074. if ($this->debug > 0) {
  3075. error_log('In learnpath::get_html_toc()', 0);
  3076. }
  3077. if (empty($tree)) {
  3078. $tree = $this->get_toc();
  3079. }
  3080. $dirTypes = self::getChapterTypes();
  3081. $mycurrentitemid = $this->get_current_item_id();
  3082. $list = [];
  3083. $classStatus = [
  3084. 'not attempted' => 'scorm_not_attempted',
  3085. 'incomplete' => 'scorm_not_attempted',
  3086. 'failed' => 'scorm_failed',
  3087. 'completed' => 'scorm_completed',
  3088. 'passed' => 'scorm_completed',
  3089. 'succeeded' => 'scorm_completed',
  3090. 'browsed' => 'scorm_completed',
  3091. ];
  3092. foreach ($tree as $subtree) {
  3093. $subtree['tree'] = null;
  3094. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3095. if ($subtree['id'] == $this->current) {
  3096. $subtree['current'] = 'active';
  3097. } else {
  3098. $subtree['current'] = null;
  3099. }
  3100. if (isset($classStatus[$subtree['status']])) {
  3101. $cssStatus = $classStatus[$subtree['status']];
  3102. }
  3103. $title = Security::remove_XSS($subtree['title']);
  3104. unset($subtree['title']);
  3105. if (empty($title)) {
  3106. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3107. }
  3108. $classStyle = null;
  3109. if ($subtree['id'] == $this->current) {
  3110. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3111. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3112. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3113. }
  3114. if (in_array($subtree['type'], $dirTypes)) {
  3115. $subtree['title'] = stripslashes($title);
  3116. } else {
  3117. $subtree['title'] = $title;
  3118. $subtree['class'] = $classStyle.' '.$cssStatus;
  3119. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3120. $subtree['current_id'] = $mycurrentitemid;
  3121. }
  3122. $list[] = $subtree;
  3123. }
  3124. }
  3125. return $list;
  3126. }
  3127. /**
  3128. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3129. *
  3130. * @param array $toc_list
  3131. *
  3132. * @return array HTML TOC ready to display
  3133. */
  3134. public function getListArrayToc($toc_list = [])
  3135. {
  3136. if ($this->debug > 0) {
  3137. error_log('In learnpath::get_html_toc()', 0);
  3138. }
  3139. if (empty($toc_list)) {
  3140. $toc_list = $this->get_toc();
  3141. }
  3142. // Temporary variables.
  3143. $mycurrentitemid = $this->get_current_item_id();
  3144. $list = [];
  3145. $arrayList = [];
  3146. $classStatus = [
  3147. 'not attempted' => 'scorm_not_attempted',
  3148. 'incomplete' => 'scorm_not_attempted',
  3149. 'failed' => 'scorm_failed',
  3150. 'completed' => 'scorm_completed',
  3151. 'passed' => 'scorm_completed',
  3152. 'succeeded' => 'scorm_completed',
  3153. 'browsed' => 'scorm_completed',
  3154. ];
  3155. foreach ($toc_list as $item) {
  3156. $list['id'] = $item['id'];
  3157. $list['status'] = $item['status'];
  3158. $cssStatus = null;
  3159. if (isset($classStatus[$item['status']])) {
  3160. $cssStatus = $classStatus[$item['status']];
  3161. }
  3162. $classStyle = ' ';
  3163. $dirTypes = self::getChapterTypes();
  3164. if (in_array($item['type'], $dirTypes)) {
  3165. $classStyle = 'scorm_item_section ';
  3166. }
  3167. if ($item['id'] == $this->current) {
  3168. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3169. } elseif (!in_array($item['type'], $dirTypes)) {
  3170. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3171. }
  3172. $title = $item['title'];
  3173. if (empty($title)) {
  3174. $title = self::rl_get_resource_name(
  3175. api_get_course_id(),
  3176. $this->get_id(),
  3177. $item['id']
  3178. );
  3179. }
  3180. $title = Security::remove_XSS($item['title']);
  3181. if (empty($item['description'])) {
  3182. $list['description'] = $title;
  3183. } else {
  3184. $list['description'] = $item['description'];
  3185. }
  3186. $list['class'] = $classStyle.' '.$cssStatus;
  3187. $list['level'] = $item['level'];
  3188. $list['type'] = $item['type'];
  3189. if (in_array($item['type'], $dirTypes)) {
  3190. $list['css_level'] = 'level_'.$item['level'];
  3191. } else {
  3192. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3193. }
  3194. if (in_array($item['type'], $dirTypes)) {
  3195. $list['title'] = stripslashes($title);
  3196. } else {
  3197. $list['title'] = stripslashes($title);
  3198. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3199. $list['current_id'] = $mycurrentitemid;
  3200. }
  3201. $arrayList[] = $list;
  3202. }
  3203. return $arrayList;
  3204. }
  3205. /**
  3206. * Returns an HTML-formatted string ready to display with teacher buttons
  3207. * in LP view menu.
  3208. *
  3209. * @return string HTML TOC ready to display
  3210. */
  3211. public function get_teacher_toc_buttons()
  3212. {
  3213. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3214. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3215. $html = '';
  3216. if ($isAllow && $hideIcons == false) {
  3217. if ($this->get_lp_session_id() == api_get_session_id()) {
  3218. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3219. $html .= '<div class="btn-group">';
  3220. $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'>".
  3221. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3222. $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'>".
  3223. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3224. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3225. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3226. $html .= '</div>';
  3227. $html .= '</div>';
  3228. }
  3229. }
  3230. return $html;
  3231. }
  3232. /**
  3233. * Gets the learnpath maker name - generally the editor's name.
  3234. *
  3235. * @return string Learnpath maker name
  3236. */
  3237. public function get_maker()
  3238. {
  3239. if ($this->debug > 0) {
  3240. error_log('In learnpath::get_maker()', 0);
  3241. }
  3242. if (!empty($this->maker)) {
  3243. return $this->maker;
  3244. } else {
  3245. return '';
  3246. }
  3247. }
  3248. /**
  3249. * Gets the learnpath name/title.
  3250. *
  3251. * @return string Learnpath name/title
  3252. */
  3253. public function get_name()
  3254. {
  3255. if ($this->debug > 0) {
  3256. error_log('In learnpath::get_name()', 0);
  3257. }
  3258. if (!empty($this->name)) {
  3259. return $this->name;
  3260. } else {
  3261. return 'N/A';
  3262. }
  3263. }
  3264. /**
  3265. * Gets a link to the resource from the present location, depending on item ID.
  3266. *
  3267. * @param string $type Type of link expected
  3268. * @param int $item_id Learnpath item ID
  3269. * @param bool $provided_toc
  3270. *
  3271. * @return string $provided_toc Link to the lp_item resource
  3272. */
  3273. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3274. {
  3275. $course_id = $this->get_course_int_id();
  3276. if ($this->debug > 0) {
  3277. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3278. }
  3279. if (empty($item_id)) {
  3280. if ($this->debug > 2) {
  3281. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3282. error_log('using current: '.$this->get_current_item_id(), 0);
  3283. }
  3284. $item_id = $this->get_current_item_id();
  3285. if (empty($item_id)) {
  3286. if ($this->debug > 2) {
  3287. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3288. }
  3289. //still empty, this means there was no item_id given and we are not in an object context or
  3290. //the object property is empty, return empty link
  3291. $this->first();
  3292. return '';
  3293. }
  3294. }
  3295. $file = '';
  3296. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3297. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3298. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3299. $item_id = (int) $item_id;
  3300. $sql = "SELECT
  3301. l.lp_type as ltype,
  3302. l.path as lpath,
  3303. li.item_type as litype,
  3304. li.path as lipath,
  3305. li.parameters as liparams
  3306. FROM $lp_table l
  3307. INNER JOIN $lp_item_table li
  3308. ON (li.lp_id = l.iid)
  3309. WHERE
  3310. li.iid = $item_id
  3311. ";
  3312. if ($this->debug > 2) {
  3313. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3314. }
  3315. $res = Database::query($sql);
  3316. if (Database::num_rows($res) > 0) {
  3317. $row = Database::fetch_array($res);
  3318. $lp_type = $row['ltype'];
  3319. $lp_path = $row['lpath'];
  3320. $lp_item_type = $row['litype'];
  3321. $lp_item_path = $row['lipath'];
  3322. $lp_item_params = $row['liparams'];
  3323. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3324. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3325. }
  3326. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3327. if ($type === 'http') {
  3328. //web path
  3329. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3330. } else {
  3331. $course_path = $sys_course_path; //system path
  3332. }
  3333. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3334. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3335. if (in_array(
  3336. $lp_item_type,
  3337. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3338. )
  3339. ) {
  3340. $lp_type = 1;
  3341. }
  3342. if ($this->debug > 2) {
  3343. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3344. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3345. }
  3346. // Now go through the specific cases to get the end of the path
  3347. // @todo Use constants instead of int values.
  3348. switch ($lp_type) {
  3349. case 1:
  3350. $file = self::rl_get_resource_link_for_learnpath(
  3351. $course_id,
  3352. $this->get_id(),
  3353. $item_id,
  3354. $this->get_view_id()
  3355. );
  3356. if ($this->debug > 0) {
  3357. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3358. }
  3359. switch ($lp_item_type) {
  3360. case 'document':
  3361. if(api_get_configuration_value('allow_pdf_viewerjs_in_lp')){
  3362. if(Link::is_pdf_link($file)){
  3363. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  3364. $file = $pdfUrl;
  3365. }
  3366. }
  3367. break;
  3368. case 'dir':
  3369. $file = 'lp_content.php?type=dir';
  3370. break;
  3371. case 'link':
  3372. if (Link::is_youtube_link($file)) {
  3373. $src = Link::get_youtube_video_id($file);
  3374. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3375. } elseif (Link::isVimeoLink($file)) {
  3376. $src = Link::getVimeoLinkId($file);
  3377. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3378. } else {
  3379. // If the current site is HTTPS and the link is
  3380. // HTTP, browsers will refuse opening the link
  3381. $urlId = api_get_current_access_url_id();
  3382. $url = api_get_access_url($urlId, false);
  3383. $protocol = substr($url['url'], 0, 5);
  3384. if ($protocol === 'https') {
  3385. $linkProtocol = substr($file, 0, 5);
  3386. if ($linkProtocol === 'http:') {
  3387. //this is the special intervention case
  3388. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3389. }
  3390. }
  3391. }
  3392. break;
  3393. case 'quiz':
  3394. // Check how much attempts of a exercise exits in lp
  3395. $lp_item_id = $this->get_current_item_id();
  3396. $lp_view_id = $this->get_view_id();
  3397. $prevent_reinit = null;
  3398. if (isset($this->items[$this->current])) {
  3399. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3400. }
  3401. if (empty($provided_toc)) {
  3402. if ($this->debug > 0) {
  3403. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3404. }
  3405. $list = $this->get_toc();
  3406. } else {
  3407. if ($this->debug > 0) {
  3408. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3409. }
  3410. $list = $provided_toc;
  3411. }
  3412. $type_quiz = false;
  3413. foreach ($list as $toc) {
  3414. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3415. $type_quiz = true;
  3416. }
  3417. }
  3418. if ($type_quiz) {
  3419. $lp_item_id = intval($lp_item_id);
  3420. $lp_view_id = intval($lp_view_id);
  3421. $sql = "SELECT count(*) FROM $lp_item_view_table
  3422. WHERE
  3423. c_id = $course_id AND
  3424. lp_item_id='".$lp_item_id."' AND
  3425. lp_view_id ='".$lp_view_id."' AND
  3426. status='completed'";
  3427. $result = Database::query($sql);
  3428. $row_count = Database:: fetch_row($result);
  3429. $count_item_view = (int) $row_count[0];
  3430. $not_multiple_attempt = 0;
  3431. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3432. $not_multiple_attempt = 1;
  3433. }
  3434. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3435. }
  3436. break;
  3437. }
  3438. $tmp_array = explode('/', $file);
  3439. $document_name = $tmp_array[count($tmp_array) - 1];
  3440. if (strpos($document_name, '_DELETED_')) {
  3441. $file = 'blank.php?error=document_deleted';
  3442. }
  3443. break;
  3444. case 2:
  3445. if ($this->debug > 2) {
  3446. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3447. }
  3448. if ($lp_item_type != 'dir') {
  3449. // Quite complex here:
  3450. // We want to make sure 'http://' (and similar) links can
  3451. // be loaded as is (withouth the Chamilo path in front) but
  3452. // some contents use this form: resource.htm?resource=http://blablabla
  3453. // which means we have to find a protocol at the path's start, otherwise
  3454. // it should not be considered as an external URL.
  3455. // if ($this->prerequisites_match($item_id)) {
  3456. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3457. if ($this->debug > 2) {
  3458. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3459. }
  3460. // Distant url, return as is.
  3461. $file = $lp_item_path;
  3462. } else {
  3463. if ($this->debug > 2) {
  3464. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3465. }
  3466. // Prevent getting untranslatable urls.
  3467. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3468. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3469. // Prepare the path.
  3470. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3471. // TODO: Fix this for urls with protocol header.
  3472. $file = str_replace('//', '/', $file);
  3473. $file = str_replace(':/', '://', $file);
  3474. if (substr($lp_path, -1) == '/') {
  3475. $lp_path = substr($lp_path, 0, -1);
  3476. }
  3477. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3478. // if file not found.
  3479. $decoded = html_entity_decode($lp_item_path);
  3480. list($decoded) = explode('?', $decoded);
  3481. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3482. $file = self::rl_get_resource_link_for_learnpath(
  3483. $course_id,
  3484. $this->get_id(),
  3485. $item_id,
  3486. $this->get_view_id()
  3487. );
  3488. if (empty($file)) {
  3489. $file = 'blank.php?error=document_not_found';
  3490. } else {
  3491. $tmp_array = explode('/', $file);
  3492. $document_name = $tmp_array[count($tmp_array) - 1];
  3493. if (strpos($document_name, '_DELETED_')) {
  3494. $file = 'blank.php?error=document_deleted';
  3495. } else {
  3496. $file = 'blank.php?error=document_not_found';
  3497. }
  3498. }
  3499. } else {
  3500. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3501. }
  3502. }
  3503. }
  3504. // We want to use parameters if they were defined in the imsmanifest
  3505. if (strpos($file, 'blank.php') === false) {
  3506. $lp_item_params = ltrim($lp_item_params, '?');
  3507. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3508. }
  3509. } else {
  3510. $file = 'lp_content.php?type=dir';
  3511. }
  3512. break;
  3513. case 3:
  3514. if ($this->debug > 2) {
  3515. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3516. }
  3517. // Formatting AICC HACP append URL.
  3518. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3519. if (!empty($lp_item_params)) {
  3520. $aicc_append .= $lp_item_params.'&';
  3521. }
  3522. if ($lp_item_type != 'dir') {
  3523. // Quite complex here:
  3524. // We want to make sure 'http://' (and similar) links can
  3525. // be loaded as is (withouth the Chamilo path in front) but
  3526. // some contents use this form: resource.htm?resource=http://blablabla
  3527. // which means we have to find a protocol at the path's start, otherwise
  3528. // it should not be considered as an external URL.
  3529. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3530. if ($this->debug > 2) {
  3531. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3532. }
  3533. // Distant url, return as is.
  3534. $file = $lp_item_path;
  3535. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3536. /*
  3537. if (stristr($file,'<servername>') !== false) {
  3538. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3539. }
  3540. */
  3541. if (stripos($file, '<servername>') !== false) {
  3542. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3543. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3544. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3545. }
  3546. $file .= $aicc_append;
  3547. } else {
  3548. if ($this->debug > 2) {
  3549. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3550. }
  3551. // Prevent getting untranslatable urls.
  3552. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3553. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3554. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3555. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3556. // TODO: Fix this for urls with protocol header.
  3557. $file = str_replace('//', '/', $file);
  3558. $file = str_replace(':/', '://', $file);
  3559. $file .= $aicc_append;
  3560. }
  3561. } else {
  3562. $file = 'lp_content.php?type=dir';
  3563. }
  3564. break;
  3565. case 4:
  3566. break;
  3567. default:
  3568. break;
  3569. }
  3570. // Replace &amp; by & because &amp; will break URL with params
  3571. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3572. }
  3573. if ($this->debug > 2) {
  3574. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3575. }
  3576. return $file;
  3577. }
  3578. /**
  3579. * Gets the latest usable view or generate a new one.
  3580. *
  3581. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3582. *
  3583. * @return int DB lp_view id
  3584. */
  3585. public function get_view($attempt_num = 0)
  3586. {
  3587. if ($this->debug > 0) {
  3588. error_log('In learnpath::get_view()', 0);
  3589. }
  3590. $search = '';
  3591. // Use $attempt_num to enable multi-views management (disabled so far).
  3592. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3593. $search = 'AND view_count = '.$attempt_num;
  3594. }
  3595. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3596. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3597. $course_id = api_get_course_int_id();
  3598. $sessionId = api_get_session_id();
  3599. $sql = "SELECT iid, view_count FROM $lp_view_table
  3600. WHERE
  3601. c_id = $course_id AND
  3602. lp_id = ".$this->get_id()." AND
  3603. user_id = ".$this->get_user_id()." AND
  3604. session_id = $sessionId
  3605. $search
  3606. ORDER BY view_count DESC";
  3607. $res = Database::query($sql);
  3608. if (Database::num_rows($res) > 0) {
  3609. $row = Database::fetch_array($res);
  3610. $this->lp_view_id = $row['iid'];
  3611. } elseif (!api_is_invitee()) {
  3612. // There is no database record, create one.
  3613. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3614. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3615. Database::query($sql);
  3616. $id = Database::insert_id();
  3617. $this->lp_view_id = $id;
  3618. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3619. Database::query($sql);
  3620. }
  3621. return $this->lp_view_id;
  3622. }
  3623. /**
  3624. * Gets the current view id.
  3625. *
  3626. * @return int View ID (from lp_view)
  3627. */
  3628. public function get_view_id()
  3629. {
  3630. if ($this->debug > 0) {
  3631. error_log('In learnpath::get_view_id()', 0);
  3632. }
  3633. if (!empty($this->lp_view_id)) {
  3634. return $this->lp_view_id;
  3635. } else {
  3636. return 0;
  3637. }
  3638. }
  3639. /**
  3640. * Gets the update queue.
  3641. *
  3642. * @return array Array containing IDs of items to be updated by JavaScript
  3643. */
  3644. public function get_update_queue()
  3645. {
  3646. if ($this->debug > 0) {
  3647. error_log('In learnpath::get_update_queue()', 0);
  3648. }
  3649. return $this->update_queue;
  3650. }
  3651. /**
  3652. * Gets the user ID.
  3653. *
  3654. * @return int User ID
  3655. */
  3656. public function get_user_id()
  3657. {
  3658. if ($this->debug > 0) {
  3659. error_log('In learnpath::get_user_id()', 0);
  3660. }
  3661. if (!empty($this->user_id)) {
  3662. return $this->user_id;
  3663. } else {
  3664. return false;
  3665. }
  3666. }
  3667. /**
  3668. * Checks if any of the items has an audio element attached.
  3669. *
  3670. * @return bool True or false
  3671. */
  3672. public function has_audio()
  3673. {
  3674. if ($this->debug > 1) {
  3675. error_log('In learnpath::has_audio()', 0);
  3676. }
  3677. $has = false;
  3678. foreach ($this->items as $i => $item) {
  3679. if (!empty($this->items[$i]->audio)) {
  3680. $has = true;
  3681. break;
  3682. }
  3683. }
  3684. return $has;
  3685. }
  3686. /**
  3687. * Moves an item up and down at its level.
  3688. *
  3689. * @param int $id Item to move up and down
  3690. * @param string $direction Direction 'up' or 'down'
  3691. *
  3692. * @return bool|int
  3693. */
  3694. public function move_item($id, $direction)
  3695. {
  3696. $course_id = api_get_course_int_id();
  3697. if ($this->debug > 0) {
  3698. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3699. }
  3700. if (empty($id) || empty($direction)) {
  3701. return false;
  3702. }
  3703. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3704. $sql_sel = "SELECT *
  3705. FROM $tbl_lp_item
  3706. WHERE
  3707. iid = $id
  3708. ";
  3709. $res_sel = Database::query($sql_sel);
  3710. // Check if elem exists.
  3711. if (Database::num_rows($res_sel) < 1) {
  3712. return false;
  3713. }
  3714. // Gather data.
  3715. $row = Database::fetch_array($res_sel);
  3716. $previous = $row['previous_item_id'];
  3717. $next = $row['next_item_id'];
  3718. $display = $row['display_order'];
  3719. $parent = $row['parent_item_id'];
  3720. $lp = $row['lp_id'];
  3721. // Update the item (switch with previous/next one).
  3722. switch ($direction) {
  3723. case 'up':
  3724. if ($this->debug > 2) {
  3725. error_log('Movement up detected', 0);
  3726. }
  3727. if ($display > 1) {
  3728. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3729. WHERE iid = $previous";
  3730. if ($this->debug > 2) {
  3731. error_log('Selecting previous: '.$sql_sel2, 0);
  3732. }
  3733. $res_sel2 = Database::query($sql_sel2);
  3734. if (Database::num_rows($res_sel2) < 1) {
  3735. $previous_previous = 0;
  3736. }
  3737. // Gather data.
  3738. $row2 = Database::fetch_array($res_sel2);
  3739. $previous_previous = $row2['previous_item_id'];
  3740. // Update previous_previous item (switch "next" with current).
  3741. if ($previous_previous != 0) {
  3742. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3743. next_item_id = $id
  3744. WHERE iid = $previous_previous";
  3745. if ($this->debug > 2) {
  3746. error_log($sql_upd2, 0);
  3747. }
  3748. Database::query($sql_upd2);
  3749. }
  3750. // Update previous item (switch with current).
  3751. if ($previous != 0) {
  3752. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3753. next_item_id = $next,
  3754. previous_item_id = $id,
  3755. display_order = display_order +1
  3756. WHERE iid = $previous";
  3757. if ($this->debug > 2) {
  3758. error_log($sql_upd2, 0);
  3759. }
  3760. Database::query($sql_upd2);
  3761. }
  3762. // Update current item (switch with previous).
  3763. if ($id != 0) {
  3764. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3765. next_item_id = $previous,
  3766. previous_item_id = $previous_previous,
  3767. display_order = display_order-1
  3768. WHERE c_id = ".$course_id." AND id = $id";
  3769. if ($this->debug > 2) {
  3770. error_log($sql_upd2, 0);
  3771. }
  3772. Database::query($sql_upd2);
  3773. }
  3774. // Update next item (new previous item).
  3775. if (!empty($next)) {
  3776. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3777. WHERE iid = $next";
  3778. if ($this->debug > 2) {
  3779. error_log($sql_upd2, 0);
  3780. }
  3781. Database::query($sql_upd2);
  3782. }
  3783. $display = $display - 1;
  3784. }
  3785. break;
  3786. case 'down':
  3787. if ($this->debug > 2) {
  3788. error_log('Movement down detected', 0);
  3789. }
  3790. if ($next != 0) {
  3791. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3792. WHERE iid = $next";
  3793. if ($this->debug > 2) {
  3794. error_log('Selecting next: '.$sql_sel2, 0);
  3795. }
  3796. $res_sel2 = Database::query($sql_sel2);
  3797. if (Database::num_rows($res_sel2) < 1) {
  3798. $next_next = 0;
  3799. }
  3800. // Gather data.
  3801. $row2 = Database::fetch_array($res_sel2);
  3802. $next_next = $row2['next_item_id'];
  3803. // Update previous item (switch with current).
  3804. if ($previous != 0) {
  3805. $sql_upd2 = "UPDATE $tbl_lp_item
  3806. SET next_item_id = $next
  3807. WHERE iid = $previous";
  3808. Database::query($sql_upd2);
  3809. }
  3810. // Update current item (switch with previous).
  3811. if ($id != 0) {
  3812. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3813. previous_item_id = $next,
  3814. next_item_id = $next_next,
  3815. display_order = display_order + 1
  3816. WHERE iid = $id";
  3817. Database::query($sql_upd2);
  3818. }
  3819. // Update next item (new previous item).
  3820. if ($next != 0) {
  3821. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3822. previous_item_id = $previous,
  3823. next_item_id = $id,
  3824. display_order = display_order-1
  3825. WHERE iid = $next";
  3826. Database::query($sql_upd2);
  3827. }
  3828. // Update next_next item (switch "previous" with current).
  3829. if ($next_next != 0) {
  3830. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3831. previous_item_id = $id
  3832. WHERE iid = $next_next";
  3833. Database::query($sql_upd2);
  3834. }
  3835. $display = $display + 1;
  3836. }
  3837. break;
  3838. default:
  3839. return false;
  3840. }
  3841. return $display;
  3842. }
  3843. /**
  3844. * Move a LP up (display_order).
  3845. *
  3846. * @param int $lp_id Learnpath ID
  3847. * @param int $categoryId Category ID
  3848. *
  3849. * @return bool
  3850. */
  3851. public static function move_up($lp_id, $categoryId = 0)
  3852. {
  3853. $courseId = api_get_course_int_id();
  3854. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3855. $categoryCondition = '';
  3856. if (!empty($categoryId)) {
  3857. $categoryId = (int) $categoryId;
  3858. $categoryCondition = " AND category_id = $categoryId";
  3859. }
  3860. $sql = "SELECT * FROM $lp_table
  3861. WHERE c_id = $courseId
  3862. $categoryCondition
  3863. ORDER BY display_order";
  3864. $res = Database::query($sql);
  3865. if ($res === false) {
  3866. return false;
  3867. }
  3868. $lps = [];
  3869. $lp_order = [];
  3870. $num = Database::num_rows($res);
  3871. // First check the order is correct, globally (might be wrong because
  3872. // of versions < 1.8.4)
  3873. if ($num > 0) {
  3874. $i = 1;
  3875. while ($row = Database::fetch_array($res)) {
  3876. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3877. $sql = "UPDATE $lp_table SET display_order = $i
  3878. WHERE iid = ".$row['iid'];
  3879. Database::query($sql);
  3880. }
  3881. $row['display_order'] = $i;
  3882. $lps[$row['iid']] = $row;
  3883. $lp_order[$i] = $row['iid'];
  3884. $i++;
  3885. }
  3886. }
  3887. if ($num > 1) { // If there's only one element, no need to sort.
  3888. $order = $lps[$lp_id]['display_order'];
  3889. if ($order > 1) { // If it's the first element, no need to move up.
  3890. $sql = "UPDATE $lp_table SET display_order = $order
  3891. WHERE iid = ".$lp_order[$order - 1];
  3892. Database::query($sql);
  3893. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3894. WHERE iid = $lp_id";
  3895. Database::query($sql);
  3896. }
  3897. }
  3898. return true;
  3899. }
  3900. /**
  3901. * Move a learnpath down (display_order).
  3902. *
  3903. * @param int $lp_id Learnpath ID
  3904. * @param int $categoryId Category ID
  3905. *
  3906. * @return bool
  3907. */
  3908. public static function move_down($lp_id, $categoryId = 0)
  3909. {
  3910. $courseId = api_get_course_int_id();
  3911. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3912. $categoryCondition = '';
  3913. if (!empty($categoryId)) {
  3914. $categoryId = (int) $categoryId;
  3915. $categoryCondition = " AND category_id = $categoryId";
  3916. }
  3917. $sql = "SELECT * FROM $lp_table
  3918. WHERE c_id = $courseId
  3919. $categoryCondition
  3920. ORDER BY display_order";
  3921. $res = Database::query($sql);
  3922. if ($res === false) {
  3923. return false;
  3924. }
  3925. $lps = [];
  3926. $lp_order = [];
  3927. $num = Database::num_rows($res);
  3928. $max = 0;
  3929. // First check the order is correct, globally (might be wrong because
  3930. // of versions < 1.8.4).
  3931. if ($num > 0) {
  3932. $i = 1;
  3933. while ($row = Database::fetch_array($res)) {
  3934. $max = $i;
  3935. if ($row['display_order'] != $i) {
  3936. // If we find a gap in the order, we need to fix it.
  3937. $sql = "UPDATE $lp_table SET display_order = $i
  3938. WHERE iid = ".$row['iid'];
  3939. Database::query($sql);
  3940. }
  3941. $row['display_order'] = $i;
  3942. $lps[$row['iid']] = $row;
  3943. $lp_order[$i] = $row['iid'];
  3944. $i++;
  3945. }
  3946. }
  3947. if ($num > 1) { // If there's only one element, no need to sort.
  3948. $order = $lps[$lp_id]['display_order'];
  3949. if ($order < $max) { // If it's the first element, no need to move up.
  3950. $sql = "UPDATE $lp_table SET display_order = $order
  3951. WHERE iid = ".$lp_order[$order + 1];
  3952. Database::query($sql);
  3953. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3954. WHERE iid = $lp_id";
  3955. Database::query($sql);
  3956. }
  3957. }
  3958. return true;
  3959. }
  3960. /**
  3961. * Updates learnpath attributes to point to the next element
  3962. * The last part is similar to set_current_item but processing the other way around.
  3963. */
  3964. public function next()
  3965. {
  3966. if ($this->debug > 0) {
  3967. error_log('In learnpath::next()', 0);
  3968. }
  3969. $this->last = $this->get_current_item_id();
  3970. $this->items[$this->last]->save(
  3971. false,
  3972. $this->prerequisites_match($this->last)
  3973. );
  3974. $this->autocomplete_parents($this->last);
  3975. $new_index = $this->get_next_index();
  3976. if ($this->debug > 2) {
  3977. error_log('New index: '.$new_index, 0);
  3978. }
  3979. $this->index = $new_index;
  3980. if ($this->debug > 2) {
  3981. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3982. }
  3983. $this->current = $this->ordered_items[$new_index];
  3984. if ($this->debug > 2) {
  3985. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3986. }
  3987. }
  3988. /**
  3989. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3990. * class, this might be redefined to allow several behaviours depending on the document type.
  3991. *
  3992. * @param int $id Resource ID
  3993. */
  3994. public function open($id)
  3995. {
  3996. if ($this->debug > 0) {
  3997. error_log('In learnpath::open()', 0);
  3998. }
  3999. // TODO:
  4000. // set the current resource attribute to this resource
  4001. // switch on element type (redefine in child class?)
  4002. // set status for this item to "opened"
  4003. // start timer
  4004. // initialise score
  4005. $this->index = 0; //or = the last item seen (see $this->last)
  4006. }
  4007. /**
  4008. * Check that all prerequisites are fulfilled. Returns true and an
  4009. * empty string on success, returns false
  4010. * and the prerequisite string on error.
  4011. * This function is based on the rules for aicc_script language as
  4012. * described in the SCORM 1.2 CAM documentation page 108.
  4013. *
  4014. * @param int $itemId Optional item ID. If none given, uses the current open item.
  4015. *
  4016. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  4017. * string otherwise
  4018. */
  4019. public function prerequisites_match($itemId = null)
  4020. {
  4021. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  4022. if ($allow) {
  4023. if (api_is_allowed_to_edit() ||
  4024. api_is_platform_admin(true) ||
  4025. api_is_drh() ||
  4026. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4027. ) {
  4028. return true;
  4029. }
  4030. }
  4031. $debug = $this->debug;
  4032. if ($debug > 0) {
  4033. error_log('In learnpath::prerequisites_match()', 0);
  4034. }
  4035. if (empty($itemId)) {
  4036. $itemId = $this->current;
  4037. }
  4038. $currentItem = $this->getItem($itemId);
  4039. if ($currentItem) {
  4040. if ($this->type == 2) {
  4041. // Getting prereq from scorm
  4042. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4043. } else {
  4044. $prereq_string = $currentItem->get_prereq_string();
  4045. }
  4046. if (empty($prereq_string)) {
  4047. if ($debug > 0) {
  4048. error_log('Found prereq_string is empty return true');
  4049. }
  4050. return true;
  4051. }
  4052. // Clean spaces.
  4053. $prereq_string = str_replace(' ', '', $prereq_string);
  4054. if ($debug > 0) {
  4055. error_log('Found prereq_string: '.$prereq_string, 0);
  4056. }
  4057. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4058. $result = $currentItem->parse_prereq(
  4059. $prereq_string,
  4060. $this->items,
  4061. $this->refs_list,
  4062. $this->get_user_id()
  4063. );
  4064. if ($result === false) {
  4065. $this->set_error_msg($currentItem->prereq_alert);
  4066. }
  4067. } else {
  4068. $result = true;
  4069. if ($debug > 1) {
  4070. error_log('$this->items['.$itemId.'] was not an object', 0);
  4071. }
  4072. }
  4073. if ($debug > 1) {
  4074. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4075. }
  4076. return $result;
  4077. }
  4078. /**
  4079. * Updates learnpath attributes to point to the previous element
  4080. * The last part is similar to set_current_item but processing the other way around.
  4081. */
  4082. public function previous()
  4083. {
  4084. if ($this->debug > 0) {
  4085. error_log('In learnpath::previous()', 0);
  4086. }
  4087. $this->last = $this->get_current_item_id();
  4088. $this->items[$this->last]->save(
  4089. false,
  4090. $this->prerequisites_match($this->last)
  4091. );
  4092. $this->autocomplete_parents($this->last);
  4093. $new_index = $this->get_previous_index();
  4094. $this->index = $new_index;
  4095. $this->current = $this->ordered_items[$new_index];
  4096. }
  4097. /**
  4098. * Publishes a learnpath. This basically means show or hide the learnpath
  4099. * to normal users.
  4100. * Can be used as abstract.
  4101. *
  4102. * @param int $lp_id Learnpath ID
  4103. * @param int $set_visibility New visibility
  4104. *
  4105. * @return bool
  4106. */
  4107. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4108. {
  4109. $action = 'visible';
  4110. if ($set_visibility != 1) {
  4111. $action = 'invisible';
  4112. self::toggle_publish($lp_id, 'i');
  4113. }
  4114. return api_item_property_update(
  4115. api_get_course_info(),
  4116. TOOL_LEARNPATH,
  4117. $lp_id,
  4118. $action,
  4119. api_get_user_id()
  4120. );
  4121. }
  4122. /**
  4123. * Publishes a learnpath category.
  4124. * This basically means show or hide the learnpath category to normal users.
  4125. *
  4126. * @param int $id
  4127. * @param int $visibility
  4128. *
  4129. * @throws \Doctrine\ORM\NonUniqueResultException
  4130. * @throws \Doctrine\ORM\ORMException
  4131. * @throws \Doctrine\ORM\OptimisticLockException
  4132. * @throws \Doctrine\ORM\TransactionRequiredException
  4133. *
  4134. * @return bool
  4135. */
  4136. public static function toggleCategoryVisibility($id, $visibility = 1)
  4137. {
  4138. $action = 'visible';
  4139. if ($visibility != 1) {
  4140. $action = 'invisible';
  4141. $list = new LearnpathList(
  4142. api_get_user_id(),
  4143. null,
  4144. null,
  4145. null,
  4146. false,
  4147. $id
  4148. );
  4149. $lpList = $list->get_flat_list();
  4150. foreach ($lpList as $lp) {
  4151. self::toggle_visibility($lp['iid'], 0);
  4152. }
  4153. self::toggleCategoryPublish($id, 0);
  4154. }
  4155. return api_item_property_update(
  4156. api_get_course_info(),
  4157. TOOL_LEARNPATH_CATEGORY,
  4158. $id,
  4159. $action,
  4160. api_get_user_id()
  4161. );
  4162. }
  4163. /**
  4164. * Publishes a learnpath. This basically means show or hide the learnpath
  4165. * on the course homepage
  4166. * Can be used as abstract.
  4167. *
  4168. * @param int $lp_id Learnpath id
  4169. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4170. *
  4171. * @return bool
  4172. */
  4173. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4174. {
  4175. $course_id = api_get_course_int_id();
  4176. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4177. $lp_id = (int) $lp_id;
  4178. $sql = "SELECT * FROM $tbl_lp
  4179. WHERE iid = $lp_id";
  4180. $result = Database::query($sql);
  4181. if (Database::num_rows($result)) {
  4182. $row = Database::fetch_array($result);
  4183. $name = Database::escape_string($row['name']);
  4184. if ($set_visibility == 'i') {
  4185. $v = 0;
  4186. }
  4187. if ($set_visibility == 'v') {
  4188. $v = 1;
  4189. }
  4190. $session_id = api_get_session_id();
  4191. $session_condition = api_get_session_condition($session_id);
  4192. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4193. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4194. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4195. $sql = "SELECT * FROM $tbl_tool
  4196. WHERE
  4197. c_id = $course_id AND
  4198. (link = '$link' OR link = '$oldLink') AND
  4199. image = 'scormbuilder.gif' AND
  4200. (
  4201. link LIKE '$link%' OR
  4202. link LIKE '$oldLink%'
  4203. )
  4204. $session_condition
  4205. ";
  4206. $result = Database::query($sql);
  4207. $num = Database::num_rows($result);
  4208. if ($set_visibility == 'i' && $num > 0) {
  4209. $sql = "DELETE FROM $tbl_tool
  4210. WHERE
  4211. c_id = $course_id AND
  4212. (link = '$link' OR link = '$oldLink') AND
  4213. image='scormbuilder.gif'
  4214. $session_condition";
  4215. Database::query($sql);
  4216. } elseif ($set_visibility == 'v' && $num == 0) {
  4217. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4218. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4219. Database::query($sql);
  4220. $insertId = Database::insert_id();
  4221. if ($insertId) {
  4222. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4223. Database::query($sql);
  4224. }
  4225. } elseif ($set_visibility == 'v' && $num > 0) {
  4226. $sql = "UPDATE $tbl_tool SET
  4227. c_id = $course_id,
  4228. name = '$name',
  4229. link = '$link',
  4230. image = 'scormbuilder.gif',
  4231. visibility = '$v',
  4232. admin = '0',
  4233. address = 'pastillegris.gif',
  4234. added_tool = 0,
  4235. session_id = $session_id
  4236. WHERE
  4237. c_id = ".$course_id." AND
  4238. (link = '$link' OR link = '$oldLink') AND
  4239. image='scormbuilder.gif'
  4240. $session_condition
  4241. ";
  4242. Database::query($sql);
  4243. } else {
  4244. // Parameter and database incompatible, do nothing, exit.
  4245. return false;
  4246. }
  4247. } else {
  4248. return false;
  4249. }
  4250. }
  4251. /**
  4252. * Publishes a learnpath.
  4253. * Show or hide the learnpath category on the course homepage.
  4254. *
  4255. * @param int $id
  4256. * @param int $setVisibility
  4257. *
  4258. * @throws \Doctrine\ORM\NonUniqueResultException
  4259. * @throws \Doctrine\ORM\ORMException
  4260. * @throws \Doctrine\ORM\OptimisticLockException
  4261. * @throws \Doctrine\ORM\TransactionRequiredException
  4262. *
  4263. * @return bool
  4264. */
  4265. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4266. {
  4267. $courseId = api_get_course_int_id();
  4268. $sessionId = api_get_session_id();
  4269. $sessionCondition = api_get_session_condition(
  4270. $sessionId,
  4271. true,
  4272. false,
  4273. 't.sessionId'
  4274. );
  4275. $em = Database::getManager();
  4276. /** @var CLpCategory $category */
  4277. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4278. if (!$category) {
  4279. return false;
  4280. }
  4281. $link = self::getCategoryLinkForTool($id);
  4282. /** @var CTool $tool */
  4283. $tool = $em->createQuery("
  4284. SELECT t FROM ChamiloCourseBundle:CTool t
  4285. WHERE
  4286. t.cId = :course AND
  4287. t.link = :link1 AND
  4288. t.image = 'lp_category.gif' AND
  4289. t.link LIKE :link2
  4290. $sessionCondition
  4291. ")
  4292. ->setParameters([
  4293. 'course' => (int) $courseId,
  4294. 'link1' => $link,
  4295. 'link2' => "$link%",
  4296. ])
  4297. ->getOneOrNullResult();
  4298. if ($setVisibility == 0 && $tool) {
  4299. $em->remove($tool);
  4300. $em->flush();
  4301. return true;
  4302. }
  4303. if ($setVisibility == 1 && !$tool) {
  4304. $tool = new CTool();
  4305. $tool
  4306. ->setCategory('authoring')
  4307. ->setCId($courseId)
  4308. ->setName(strip_tags($category->getName()))
  4309. ->setLink($link)
  4310. ->setImage('lp_category.gif')
  4311. ->setVisibility(1)
  4312. ->setAdmin(0)
  4313. ->setAddress('pastillegris.gif')
  4314. ->setAddedTool(0)
  4315. ->setSessionId($sessionId)
  4316. ->setTarget('_self');
  4317. $em->persist($tool);
  4318. $em->flush();
  4319. $tool->setId($tool->getIid());
  4320. $em->persist($tool);
  4321. $em->flush();
  4322. return true;
  4323. }
  4324. if ($setVisibility == 1 && $tool) {
  4325. $tool
  4326. ->setName(strip_tags($category->getName()))
  4327. ->setVisibility(1);
  4328. $em->persist($tool);
  4329. $em->flush();
  4330. return true;
  4331. }
  4332. return false;
  4333. }
  4334. /**
  4335. * Check if the learnpath category is visible for a user.
  4336. *
  4337. * @param CLpCategory $category
  4338. * @param User $user
  4339. *
  4340. * @return bool
  4341. */
  4342. public static function categoryIsVisibleForStudent(
  4343. CLpCategory $category,
  4344. User $user
  4345. ) {
  4346. $subscriptionSettings = self::getSubscriptionSettings();
  4347. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4348. return true;
  4349. }
  4350. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4351. if ($isAllowedToEdit) {
  4352. return true;
  4353. }
  4354. if (empty($category)) {
  4355. return false;
  4356. }
  4357. $users = $category->getUsers();
  4358. if (empty($users) || !$users->count()) {
  4359. return true;
  4360. }
  4361. if ($category->hasUserAdded($user)) {
  4362. return true;
  4363. }
  4364. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4365. if (!empty($groups)) {
  4366. $em = Database::getManager();
  4367. /** @var ItemPropertyRepository $itemRepo */
  4368. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4369. /** @var CourseRepository $courseRepo */
  4370. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4371. $sessionId = api_get_session_id();
  4372. $session = null;
  4373. if (!empty($sessionId)) {
  4374. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4375. }
  4376. $course = $courseRepo->find(api_get_course_int_id());
  4377. // Subscribed groups to a LP
  4378. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4379. TOOL_LEARNPATH_CATEGORY,
  4380. $category->getId(),
  4381. $course,
  4382. $session
  4383. );
  4384. if (!empty($subscribedGroupsInLp)) {
  4385. $groups = array_column($groups, 'iid');
  4386. /** @var CItemProperty $item */
  4387. foreach ($subscribedGroupsInLp as $item) {
  4388. if ($item->getGroup() &&
  4389. in_array($item->getGroup()->getId(), $groups)
  4390. ) {
  4391. return true;
  4392. }
  4393. }
  4394. }
  4395. }
  4396. return false;
  4397. }
  4398. /**
  4399. * Check if a learnpath category is published as course tool.
  4400. *
  4401. * @param CLpCategory $category
  4402. * @param int $courseId
  4403. *
  4404. * @return bool
  4405. */
  4406. public static function categoryIsPublished(
  4407. CLpCategory $category,
  4408. $courseId
  4409. ) {
  4410. $link = self::getCategoryLinkForTool($category->getId());
  4411. $em = Database::getManager();
  4412. $tools = $em
  4413. ->createQuery("
  4414. SELECT t FROM ChamiloCourseBundle:CTool t
  4415. WHERE t.cId = :course AND
  4416. t.name = :name AND
  4417. t.image = 'lp_category.gif' AND
  4418. t.link LIKE :link
  4419. ")
  4420. ->setParameters([
  4421. 'course' => $courseId,
  4422. 'name' => strip_tags($category->getName()),
  4423. 'link' => "$link%",
  4424. ])
  4425. ->getResult();
  4426. /** @var CTool $tool */
  4427. $tool = current($tools);
  4428. return $tool ? $tool->getVisibility() : false;
  4429. }
  4430. /**
  4431. * Restart the whole learnpath. Return the URL of the first element.
  4432. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4433. * To use a similar method statically, use the create_new_attempt() method.
  4434. *
  4435. * @return bool
  4436. */
  4437. public function restart()
  4438. {
  4439. if ($this->debug > 0) {
  4440. error_log('In learnpath::restart()', 0);
  4441. }
  4442. // TODO
  4443. // Call autosave method to save the current progress.
  4444. //$this->index = 0;
  4445. if (api_is_invitee()) {
  4446. return false;
  4447. }
  4448. $session_id = api_get_session_id();
  4449. $course_id = api_get_course_int_id();
  4450. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4451. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4452. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4453. if ($this->debug > 2) {
  4454. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4455. }
  4456. Database::query($sql);
  4457. $view_id = Database::insert_id();
  4458. if ($view_id) {
  4459. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4460. Database::query($sql);
  4461. $this->lp_view_id = $view_id;
  4462. $this->attempt = $this->attempt + 1;
  4463. } else {
  4464. $this->error = 'Could not insert into item_view table...';
  4465. return false;
  4466. }
  4467. $this->autocomplete_parents($this->current);
  4468. foreach ($this->items as $index => $dummy) {
  4469. $this->items[$index]->restart();
  4470. $this->items[$index]->set_lp_view($this->lp_view_id);
  4471. }
  4472. $this->first();
  4473. return true;
  4474. }
  4475. /**
  4476. * Saves the current item.
  4477. *
  4478. * @return bool
  4479. */
  4480. public function save_current()
  4481. {
  4482. $debug = $this->debug;
  4483. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4484. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4485. if ($debug) {
  4486. error_log('save_current() saving item '.$this->current, 0);
  4487. error_log(''.print_r($this->items, true), 0);
  4488. }
  4489. if (isset($this->items[$this->current]) &&
  4490. is_object($this->items[$this->current])
  4491. ) {
  4492. if ($debug) {
  4493. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4494. }
  4495. $res = $this->items[$this->current]->save(
  4496. false,
  4497. $this->prerequisites_match($this->current)
  4498. );
  4499. $this->autocomplete_parents($this->current);
  4500. $status = $this->items[$this->current]->get_status();
  4501. $this->update_queue[$this->current] = $status;
  4502. if ($debug) {
  4503. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4504. }
  4505. return $res;
  4506. }
  4507. return false;
  4508. }
  4509. /**
  4510. * Saves the given item.
  4511. *
  4512. * @param int $item_id Optional (will take from $_REQUEST if null)
  4513. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4514. *
  4515. * @return bool
  4516. */
  4517. public function save_item($item_id = null, $from_outside = true)
  4518. {
  4519. $debug = $this->debug;
  4520. if ($debug) {
  4521. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4522. }
  4523. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4524. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4525. if (empty($item_id)) {
  4526. $item_id = (int) $_REQUEST['id'];
  4527. }
  4528. if (empty($item_id)) {
  4529. $item_id = $this->get_current_item_id();
  4530. }
  4531. if (isset($this->items[$item_id]) &&
  4532. is_object($this->items[$item_id])
  4533. ) {
  4534. if ($debug) {
  4535. error_log('Object exists');
  4536. }
  4537. // Saving the item.
  4538. $res = $this->items[$item_id]->save(
  4539. $from_outside,
  4540. $this->prerequisites_match($item_id)
  4541. );
  4542. if ($debug) {
  4543. error_log('update_queue before:');
  4544. error_log(print_r($this->update_queue, 1));
  4545. }
  4546. $this->autocomplete_parents($item_id);
  4547. $status = $this->items[$item_id]->get_status();
  4548. $this->update_queue[$item_id] = $status;
  4549. if ($debug) {
  4550. error_log('get_status(): '.$status);
  4551. error_log('update_queue after:');
  4552. error_log(print_r($this->update_queue, 1));
  4553. }
  4554. return $res;
  4555. }
  4556. return false;
  4557. }
  4558. /**
  4559. * Saves the last item seen's ID only in case.
  4560. */
  4561. public function save_last()
  4562. {
  4563. $course_id = api_get_course_int_id();
  4564. $debug = $this->debug;
  4565. if ($debug) {
  4566. error_log('In learnpath::save_last()', 0);
  4567. }
  4568. $session_condition = api_get_session_condition(
  4569. api_get_session_id(),
  4570. true,
  4571. false
  4572. );
  4573. $table = Database::get_course_table(TABLE_LP_VIEW);
  4574. if (isset($this->current) && !api_is_invitee()) {
  4575. if ($debug) {
  4576. error_log('Saving current item ('.$this->current.') for later review', 0);
  4577. }
  4578. $sql = "UPDATE $table SET
  4579. last_item = ".intval($this->get_current_item_id())."
  4580. WHERE
  4581. c_id = $course_id AND
  4582. lp_id = ".$this->get_id()." AND
  4583. user_id = ".$this->get_user_id()." ".$session_condition;
  4584. if ($debug) {
  4585. error_log('Saving last item seen : '.$sql, 0);
  4586. }
  4587. Database::query($sql);
  4588. }
  4589. if (!api_is_invitee()) {
  4590. // Save progress.
  4591. list($progress) = $this->get_progress_bar_text('%');
  4592. if ($progress >= 0 && $progress <= 100) {
  4593. $progress = (int) $progress;
  4594. $sql = "UPDATE $table SET
  4595. progress = $progress
  4596. WHERE
  4597. c_id = $course_id AND
  4598. lp_id = ".$this->get_id()." AND
  4599. user_id = ".$this->get_user_id()." ".$session_condition;
  4600. // Ignore errors as some tables might not have the progress field just yet.
  4601. Database::query($sql);
  4602. if ($debug) {
  4603. error_log($sql);
  4604. }
  4605. $this->progress_db = $progress;
  4606. }
  4607. }
  4608. }
  4609. /**
  4610. * Sets the current item ID (checks if valid and authorized first).
  4611. *
  4612. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4613. */
  4614. public function set_current_item($item_id = null)
  4615. {
  4616. $debug = $this->debug;
  4617. if ($debug) {
  4618. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4619. }
  4620. if (empty($item_id)) {
  4621. if ($debug) {
  4622. error_log('No new current item given, ignore...', 0);
  4623. }
  4624. // Do nothing.
  4625. } else {
  4626. if ($debug) {
  4627. error_log('New current item given is '.$item_id.'...', 0);
  4628. }
  4629. if (is_numeric($item_id)) {
  4630. $item_id = (int) $item_id;
  4631. // TODO: Check in database here.
  4632. $this->last = $this->current;
  4633. $this->current = $item_id;
  4634. // TODO: Update $this->index as well.
  4635. foreach ($this->ordered_items as $index => $item) {
  4636. if ($item == $this->current) {
  4637. $this->index = $index;
  4638. break;
  4639. }
  4640. }
  4641. if ($debug) {
  4642. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4643. }
  4644. } else {
  4645. if ($debug) {
  4646. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4647. }
  4648. }
  4649. }
  4650. }
  4651. /**
  4652. * Sets the encoding.
  4653. *
  4654. * @param string $enc New encoding
  4655. *
  4656. * @return bool
  4657. *
  4658. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4659. */
  4660. public function set_encoding($enc = 'UTF-8')
  4661. {
  4662. if ($this->debug > 0) {
  4663. error_log('In learnpath::set_encoding()', 0);
  4664. }
  4665. $enc = api_refine_encoding_id($enc);
  4666. if (empty($enc)) {
  4667. $enc = api_get_system_encoding();
  4668. }
  4669. if (api_is_encoding_supported($enc)) {
  4670. $lp = $this->get_id();
  4671. if ($lp != 0) {
  4672. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4673. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4674. WHERE iid = ".$lp;
  4675. $res = Database::query($sql);
  4676. return $res;
  4677. }
  4678. }
  4679. return false;
  4680. }
  4681. /**
  4682. * Sets the JS lib setting in the database directly.
  4683. * This is the JavaScript library file this lp needs to load on startup.
  4684. *
  4685. * @param string $lib Proximity setting
  4686. *
  4687. * @return bool True on update success. False otherwise.
  4688. */
  4689. public function set_jslib($lib = '')
  4690. {
  4691. if ($this->debug > 0) {
  4692. error_log('In learnpath::set_jslib()', 0);
  4693. }
  4694. $lp = $this->get_id();
  4695. if ($lp != 0) {
  4696. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4697. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4698. WHERE iid = $lp";
  4699. $res = Database::query($sql);
  4700. return $res;
  4701. } else {
  4702. return false;
  4703. }
  4704. }
  4705. /**
  4706. * Sets the name of the LP maker (publisher) (and save).
  4707. *
  4708. * @param string $name Optional string giving the new content_maker of this learnpath
  4709. *
  4710. * @return bool True
  4711. */
  4712. public function set_maker($name = '')
  4713. {
  4714. if ($this->debug > 0) {
  4715. error_log('In learnpath::set_maker()', 0);
  4716. }
  4717. if (empty($name)) {
  4718. return false;
  4719. }
  4720. $this->maker = $name;
  4721. $table = Database::get_course_table(TABLE_LP_MAIN);
  4722. $lp_id = $this->get_id();
  4723. $sql = "UPDATE $table SET
  4724. content_maker = '".Database::escape_string($this->maker)."'
  4725. WHERE iid = $lp_id";
  4726. if ($this->debug > 2) {
  4727. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4728. }
  4729. Database::query($sql);
  4730. return true;
  4731. }
  4732. /**
  4733. * Sets the name of the current learnpath (and save).
  4734. *
  4735. * @param string $name Optional string giving the new name of this learnpath
  4736. *
  4737. * @return bool True/False
  4738. */
  4739. public function set_name($name = null)
  4740. {
  4741. if ($this->debug > 0) {
  4742. error_log('In learnpath::set_name()', 0);
  4743. }
  4744. if (empty($name)) {
  4745. return false;
  4746. }
  4747. $this->name = Database::escape_string($name);
  4748. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4749. $lp_id = $this->get_id();
  4750. $course_id = $this->course_info['real_id'];
  4751. $sql = "UPDATE $lp_table SET
  4752. name = '".Database::escape_string($this->name)."'
  4753. WHERE iid = $lp_id";
  4754. if ($this->debug > 2) {
  4755. error_log('lp updated with new name : '.$this->name, 0);
  4756. }
  4757. $result = Database::query($sql);
  4758. // If the lp is visible on the homepage, change his name there.
  4759. if (Database::affected_rows($result)) {
  4760. $session_id = api_get_session_id();
  4761. $session_condition = api_get_session_condition($session_id);
  4762. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4763. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4764. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4765. WHERE
  4766. c_id = $course_id AND
  4767. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4768. Database::query($sql);
  4769. return true;
  4770. } else {
  4771. return false;
  4772. }
  4773. }
  4774. /**
  4775. * Set index specified prefix terms for all items in this path.
  4776. *
  4777. * @param string $terms_string Comma-separated list of terms
  4778. * @param string $prefix Xapian term prefix
  4779. *
  4780. * @return bool False on error, true otherwise
  4781. */
  4782. public function set_terms_by_prefix($terms_string, $prefix)
  4783. {
  4784. $course_id = api_get_course_int_id();
  4785. if (api_get_setting('search_enabled') !== 'true') {
  4786. return false;
  4787. }
  4788. if (!extension_loaded('xapian')) {
  4789. return false;
  4790. }
  4791. $terms_string = trim($terms_string);
  4792. $terms = explode(',', $terms_string);
  4793. array_walk($terms, 'trim_value');
  4794. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4795. // Don't do anything if no change, verify only at DB, not the search engine.
  4796. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4797. return false;
  4798. }
  4799. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4800. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4801. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4802. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4803. $lp_id = (int) $_POST['lp_id'];
  4804. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4805. $result = Database::query($sql);
  4806. $di = new ChamiloIndexer();
  4807. while ($lp_item = Database::fetch_array($result)) {
  4808. // Get search_did.
  4809. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4810. $sql = 'SELECT * FROM %s
  4811. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4812. LIMIT 1';
  4813. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4814. //echo $sql; echo '<br>';
  4815. $res = Database::query($sql);
  4816. if (Database::num_rows($res) > 0) {
  4817. $se_ref = Database::fetch_array($res);
  4818. // Compare terms.
  4819. $doc = $di->get_document($se_ref['search_did']);
  4820. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4821. $xterms = [];
  4822. foreach ($xapian_terms as $xapian_term) {
  4823. $xterms[] = substr($xapian_term['name'], 1);
  4824. }
  4825. $dterms = $terms;
  4826. $missing_terms = array_diff($dterms, $xterms);
  4827. $deprecated_terms = array_diff($xterms, $dterms);
  4828. // Save it to search engine.
  4829. foreach ($missing_terms as $term) {
  4830. $doc->add_term($prefix.$term, 1);
  4831. }
  4832. foreach ($deprecated_terms as $term) {
  4833. $doc->remove_term($prefix.$term);
  4834. }
  4835. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4836. $di->getDb()->flush();
  4837. }
  4838. }
  4839. return true;
  4840. }
  4841. /**
  4842. * Sets the theme of the LP (local/remote) (and save).
  4843. *
  4844. * @param string $name Optional string giving the new theme of this learnpath
  4845. *
  4846. * @return bool Returns true if theme name is not empty
  4847. */
  4848. public function set_theme($name = '')
  4849. {
  4850. if ($this->debug > 0) {
  4851. error_log('In learnpath::set_theme()', 0);
  4852. }
  4853. $this->theme = $name;
  4854. $table = Database::get_course_table(TABLE_LP_MAIN);
  4855. $lp_id = $this->get_id();
  4856. $sql = "UPDATE $table
  4857. SET theme = '".Database::escape_string($this->theme)."'
  4858. WHERE iid = $lp_id";
  4859. if ($this->debug > 2) {
  4860. error_log('lp updated with new theme : '.$this->theme, 0);
  4861. }
  4862. Database::query($sql);
  4863. return true;
  4864. }
  4865. /**
  4866. * Sets the image of an LP (and save).
  4867. *
  4868. * @param string $name Optional string giving the new image of this learnpath
  4869. *
  4870. * @return bool Returns true if theme name is not empty
  4871. */
  4872. public function set_preview_image($name = '')
  4873. {
  4874. if ($this->debug > 0) {
  4875. error_log('In learnpath::set_preview_image()', 0);
  4876. }
  4877. $this->preview_image = $name;
  4878. $table = Database::get_course_table(TABLE_LP_MAIN);
  4879. $lp_id = $this->get_id();
  4880. $sql = "UPDATE $table SET
  4881. preview_image = '".Database::escape_string($this->preview_image)."'
  4882. WHERE iid = $lp_id";
  4883. if ($this->debug > 2) {
  4884. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4885. }
  4886. Database::query($sql);
  4887. return true;
  4888. }
  4889. /**
  4890. * Sets the author of a LP (and save).
  4891. *
  4892. * @param string $name Optional string giving the new author of this learnpath
  4893. *
  4894. * @return bool Returns true if author's name is not empty
  4895. */
  4896. public function set_author($name = '')
  4897. {
  4898. if ($this->debug > 0) {
  4899. error_log('In learnpath::set_author()', 0);
  4900. }
  4901. $this->author = $name;
  4902. $table = Database::get_course_table(TABLE_LP_MAIN);
  4903. $lp_id = $this->get_id();
  4904. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4905. WHERE iid = $lp_id";
  4906. if ($this->debug > 2) {
  4907. error_log('lp updated with new preview author : '.$this->author, 0);
  4908. }
  4909. Database::query($sql);
  4910. return true;
  4911. }
  4912. /**
  4913. * Sets the hide_toc_frame parameter of a LP (and save).
  4914. *
  4915. * @param int $hide 1 if frame is hidden 0 then else
  4916. *
  4917. * @return bool Returns true if author's name is not empty
  4918. */
  4919. public function set_hide_toc_frame($hide)
  4920. {
  4921. if ($this->debug > 0) {
  4922. error_log('In learnpath::set_hide_toc_frame()', 0);
  4923. }
  4924. if (intval($hide) == $hide) {
  4925. $this->hide_toc_frame = $hide;
  4926. $table = Database::get_course_table(TABLE_LP_MAIN);
  4927. $lp_id = $this->get_id();
  4928. $sql = "UPDATE $table SET
  4929. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4930. WHERE iid = $lp_id";
  4931. if ($this->debug > 2) {
  4932. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4933. }
  4934. Database::query($sql);
  4935. return true;
  4936. } else {
  4937. return false;
  4938. }
  4939. }
  4940. /**
  4941. * Sets the prerequisite of a LP (and save).
  4942. *
  4943. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4944. *
  4945. * @return bool returns true if prerequisite is not empty
  4946. */
  4947. public function set_prerequisite($prerequisite)
  4948. {
  4949. if ($this->debug > 0) {
  4950. error_log('In learnpath::set_prerequisite()', 0);
  4951. }
  4952. $this->prerequisite = (int) $prerequisite;
  4953. $table = Database::get_course_table(TABLE_LP_MAIN);
  4954. $lp_id = $this->get_id();
  4955. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4956. WHERE iid = $lp_id";
  4957. if ($this->debug > 2) {
  4958. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  4959. }
  4960. Database::query($sql);
  4961. return true;
  4962. }
  4963. /**
  4964. * Sets the location/proximity of the LP (local/remote) (and save).
  4965. *
  4966. * @param string $name Optional string giving the new location of this learnpath
  4967. *
  4968. * @return bool True on success / False on error
  4969. */
  4970. public function set_proximity($name = '')
  4971. {
  4972. if ($this->debug > 0) {
  4973. error_log('In learnpath::set_proximity()', 0);
  4974. }
  4975. if (empty($name)) {
  4976. return false;
  4977. }
  4978. $this->proximity = $name;
  4979. $table = Database::get_course_table(TABLE_LP_MAIN);
  4980. $lp_id = $this->get_id();
  4981. $sql = "UPDATE $table SET
  4982. content_local = '".Database::escape_string($name)."'
  4983. WHERE iid = $lp_id";
  4984. if ($this->debug > 2) {
  4985. error_log('lp updated with new proximity : '.$this->proximity, 0);
  4986. }
  4987. Database::query($sql);
  4988. return true;
  4989. }
  4990. /**
  4991. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4992. *
  4993. * @param int $id DB ID of the item
  4994. */
  4995. public function set_previous_item($id)
  4996. {
  4997. if ($this->debug > 0) {
  4998. error_log('In learnpath::set_previous_item()', 0);
  4999. }
  5000. $this->last = $id;
  5001. }
  5002. /**
  5003. * Sets use_max_score.
  5004. *
  5005. * @param int $use_max_score Optional string giving the new location of this learnpath
  5006. *
  5007. * @return bool True on success / False on error
  5008. */
  5009. public function set_use_max_score($use_max_score = 1)
  5010. {
  5011. if ($this->debug > 0) {
  5012. error_log('In learnpath::set_use_max_score()', 0);
  5013. }
  5014. $use_max_score = (int) $use_max_score;
  5015. $this->use_max_score = $use_max_score;
  5016. $table = Database::get_course_table(TABLE_LP_MAIN);
  5017. $lp_id = $this->get_id();
  5018. $sql = "UPDATE $table SET
  5019. use_max_score = '".$this->use_max_score."'
  5020. WHERE iid = $lp_id";
  5021. if ($this->debug > 2) {
  5022. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  5023. }
  5024. Database::query($sql);
  5025. return true;
  5026. }
  5027. /**
  5028. * Sets and saves the expired_on date.
  5029. *
  5030. * @param string $expired_on Optional string giving the new author of this learnpath
  5031. *
  5032. * @throws \Doctrine\ORM\OptimisticLockException
  5033. *
  5034. * @return bool Returns true if author's name is not empty
  5035. */
  5036. public function set_expired_on($expired_on)
  5037. {
  5038. if ($this->debug > 0) {
  5039. error_log('In learnpath::set_expired_on()', 0);
  5040. }
  5041. $em = Database::getManager();
  5042. /** @var CLp $lp */
  5043. $lp = $em
  5044. ->getRepository('ChamiloCourseBundle:CLp')
  5045. ->findOneBy(
  5046. [
  5047. 'iid' => $this->get_id(),
  5048. ]
  5049. );
  5050. if (!$lp) {
  5051. return false;
  5052. }
  5053. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5054. $lp->setExpiredOn($this->expired_on);
  5055. $em->persist($lp);
  5056. $em->flush();
  5057. if ($this->debug > 2) {
  5058. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  5059. }
  5060. return true;
  5061. }
  5062. /**
  5063. * Sets and saves the publicated_on date.
  5064. *
  5065. * @param string $publicated_on Optional string giving the new author of this learnpath
  5066. *
  5067. * @throws \Doctrine\ORM\OptimisticLockException
  5068. *
  5069. * @return bool Returns true if author's name is not empty
  5070. */
  5071. public function set_publicated_on($publicated_on)
  5072. {
  5073. if ($this->debug > 0) {
  5074. error_log('In learnpath::set_expired_on()', 0);
  5075. }
  5076. $em = Database::getManager();
  5077. /** @var CLp $lp */
  5078. $lp = $em
  5079. ->getRepository('ChamiloCourseBundle:CLp')
  5080. ->findOneBy(
  5081. [
  5082. 'iid' => $this->get_id(),
  5083. ]
  5084. );
  5085. if (!$lp) {
  5086. return false;
  5087. }
  5088. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5089. $lp->setPublicatedOn($this->publicated_on);
  5090. $em->persist($lp);
  5091. $em->flush();
  5092. if ($this->debug > 2) {
  5093. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5094. }
  5095. return true;
  5096. }
  5097. /**
  5098. * Sets and saves the expired_on date.
  5099. *
  5100. * @return bool Returns true if author's name is not empty
  5101. */
  5102. public function set_modified_on()
  5103. {
  5104. if ($this->debug > 0) {
  5105. error_log('In learnpath::set_expired_on()', 0);
  5106. }
  5107. $this->modified_on = api_get_utc_datetime();
  5108. $table = Database::get_course_table(TABLE_LP_MAIN);
  5109. $lp_id = $this->get_id();
  5110. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5111. WHERE iid = $lp_id";
  5112. if ($this->debug > 2) {
  5113. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5114. }
  5115. Database::query($sql);
  5116. return true;
  5117. }
  5118. /**
  5119. * Sets the object's error message.
  5120. *
  5121. * @param string $error Error message. If empty, reinits the error string
  5122. */
  5123. public function set_error_msg($error = '')
  5124. {
  5125. if ($this->debug > 0) {
  5126. error_log('In learnpath::set_error_msg()', 0);
  5127. }
  5128. if (empty($error)) {
  5129. $this->error = '';
  5130. } else {
  5131. $this->error .= $error;
  5132. }
  5133. }
  5134. /**
  5135. * Launches the current item if not 'sco'
  5136. * (starts timer and make sure there is a record ready in the DB).
  5137. *
  5138. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5139. *
  5140. * @return bool
  5141. */
  5142. public function start_current_item($allow_new_attempt = false)
  5143. {
  5144. $debug = $this->debug;
  5145. if ($debug) {
  5146. error_log('In learnpath::start_current_item()');
  5147. error_log('current: '.$this->current);
  5148. }
  5149. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5150. $type = $this->get_type();
  5151. $item_type = $this->items[$this->current]->get_type();
  5152. if (($type == 2 && $item_type != 'sco') ||
  5153. ($type == 3 && $item_type != 'au') ||
  5154. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5155. ) {
  5156. if ($debug) {
  5157. error_log('item type: '.$item_type);
  5158. error_log('lp type: '.$type);
  5159. }
  5160. $this->items[$this->current]->open($allow_new_attempt);
  5161. $this->autocomplete_parents($this->current);
  5162. $prereq_check = $this->prerequisites_match($this->current);
  5163. if ($debug) {
  5164. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5165. }
  5166. $this->items[$this->current]->save(false, $prereq_check);
  5167. }
  5168. // If sco, then it is supposed to have been updated by some other call.
  5169. if ($item_type == 'sco') {
  5170. $this->items[$this->current]->restart();
  5171. }
  5172. }
  5173. if ($debug) {
  5174. error_log('lp_view_session_id');
  5175. error_log($this->lp_view_session_id);
  5176. error_log('api session id');
  5177. error_log(api_get_session_id());
  5178. error_log('End of learnpath::start_current_item()');
  5179. }
  5180. return true;
  5181. }
  5182. /**
  5183. * Stops the processing and counters for the old item (as held in $this->last).
  5184. *
  5185. * @return bool True/False
  5186. */
  5187. public function stop_previous_item()
  5188. {
  5189. $debug = $this->debug;
  5190. if ($debug) {
  5191. error_log('In learnpath::stop_previous_item()', 0);
  5192. }
  5193. if ($this->last != 0 && $this->last != $this->current &&
  5194. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5195. ) {
  5196. if ($debug) {
  5197. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5198. }
  5199. switch ($this->get_type()) {
  5200. case '3':
  5201. if ($this->items[$this->last]->get_type() != 'au') {
  5202. if ($debug) {
  5203. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5204. }
  5205. $this->items[$this->last]->close();
  5206. } else {
  5207. if ($debug) {
  5208. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5209. }
  5210. }
  5211. break;
  5212. case '2':
  5213. if ($this->items[$this->last]->get_type() != 'sco') {
  5214. if ($debug) {
  5215. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5216. }
  5217. $this->items[$this->last]->close();
  5218. } else {
  5219. if ($debug) {
  5220. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5221. }
  5222. }
  5223. break;
  5224. case '1':
  5225. default:
  5226. if ($debug) {
  5227. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5228. }
  5229. $this->items[$this->last]->close();
  5230. break;
  5231. }
  5232. } else {
  5233. if ($debug) {
  5234. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5235. }
  5236. return false;
  5237. }
  5238. return true;
  5239. }
  5240. /**
  5241. * Updates the default view mode from fullscreen to embedded and inversely.
  5242. *
  5243. * @return string The current default view mode ('fullscreen' or 'embedded')
  5244. */
  5245. public function update_default_view_mode()
  5246. {
  5247. if ($this->debug > 0) {
  5248. error_log('In learnpath::update_default_view_mode()', 0);
  5249. }
  5250. $table = Database::get_course_table(TABLE_LP_MAIN);
  5251. $sql = "SELECT * FROM $table
  5252. WHERE iid = ".$this->get_id();
  5253. $res = Database::query($sql);
  5254. if (Database::num_rows($res) > 0) {
  5255. $row = Database::fetch_array($res);
  5256. $default_view_mode = $row['default_view_mod'];
  5257. $view_mode = $default_view_mode;
  5258. switch ($default_view_mode) {
  5259. case 'fullscreen': // default with popup
  5260. $view_mode = 'embedded';
  5261. break;
  5262. case 'embedded': // default view with left menu
  5263. $view_mode = 'embedframe';
  5264. break;
  5265. case 'embedframe': //folded menu
  5266. $view_mode = 'impress';
  5267. break;
  5268. case 'impress':
  5269. $view_mode = 'fullscreen';
  5270. break;
  5271. }
  5272. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5273. WHERE iid = ".$this->get_id();
  5274. Database::query($sql);
  5275. $this->mode = $view_mode;
  5276. return $view_mode;
  5277. } else {
  5278. if ($this->debug > 2) {
  5279. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5280. }
  5281. }
  5282. return -1;
  5283. }
  5284. /**
  5285. * Updates the default behaviour about auto-commiting SCORM updates.
  5286. *
  5287. * @return bool True if auto-commit has been set to 'on', false otherwise
  5288. */
  5289. public function update_default_scorm_commit()
  5290. {
  5291. if ($this->debug > 0) {
  5292. error_log('In learnpath::update_default_scorm_commit()', 0);
  5293. }
  5294. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5295. $sql = "SELECT * FROM $lp_table
  5296. WHERE iid = ".$this->get_id();
  5297. $res = Database::query($sql);
  5298. if (Database::num_rows($res) > 0) {
  5299. $row = Database::fetch_array($res);
  5300. $force = $row['force_commit'];
  5301. if ($force == 1) {
  5302. $force = 0;
  5303. $force_return = false;
  5304. } elseif ($force == 0) {
  5305. $force = 1;
  5306. $force_return = true;
  5307. }
  5308. $sql = "UPDATE $lp_table SET force_commit = $force
  5309. WHERE iid = ".$this->get_id();
  5310. Database::query($sql);
  5311. $this->force_commit = $force_return;
  5312. return $force_return;
  5313. } else {
  5314. if ($this->debug > 2) {
  5315. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5316. }
  5317. }
  5318. return -1;
  5319. }
  5320. /**
  5321. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5322. *
  5323. * @return bool True on success, false on failure
  5324. */
  5325. public function update_display_order()
  5326. {
  5327. $course_id = api_get_course_int_id();
  5328. $table = Database::get_course_table(TABLE_LP_MAIN);
  5329. $sql = "SELECT * FROM $table
  5330. WHERE c_id = $course_id
  5331. ORDER BY display_order";
  5332. $res = Database::query($sql);
  5333. if ($res === false) {
  5334. return false;
  5335. }
  5336. $num = Database::num_rows($res);
  5337. // First check the order is correct, globally (might be wrong because
  5338. // of versions < 1.8.4).
  5339. if ($num > 0) {
  5340. $i = 1;
  5341. while ($row = Database::fetch_array($res)) {
  5342. if ($row['display_order'] != $i) {
  5343. // If we find a gap in the order, we need to fix it.
  5344. $sql = "UPDATE $table SET display_order = $i
  5345. WHERE iid = ".$row['iid'];
  5346. Database::query($sql);
  5347. }
  5348. $i++;
  5349. }
  5350. }
  5351. return true;
  5352. }
  5353. /**
  5354. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5355. *
  5356. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5357. */
  5358. public function update_reinit()
  5359. {
  5360. if ($this->debug > 0) {
  5361. error_log('In learnpath::update_reinit()', 0);
  5362. }
  5363. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5364. $sql = "SELECT * FROM $lp_table
  5365. WHERE iid = ".$this->get_id();
  5366. $res = Database::query($sql);
  5367. if (Database::num_rows($res) > 0) {
  5368. $row = Database::fetch_array($res);
  5369. $force = $row['prevent_reinit'];
  5370. if ($force == 1) {
  5371. $force = 0;
  5372. } elseif ($force == 0) {
  5373. $force = 1;
  5374. }
  5375. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5376. WHERE iid = ".$this->get_id();
  5377. Database::query($sql);
  5378. $this->prevent_reinit = $force;
  5379. return $force;
  5380. } else {
  5381. if ($this->debug > 2) {
  5382. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5383. }
  5384. }
  5385. return -1;
  5386. }
  5387. /**
  5388. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5389. *
  5390. * @return string 'single', 'multi' or 'seriousgame'
  5391. *
  5392. * @author ndiechburg <noel@cblue.be>
  5393. */
  5394. public function get_attempt_mode()
  5395. {
  5396. //Set default value for seriousgame_mode
  5397. if (!isset($this->seriousgame_mode)) {
  5398. $this->seriousgame_mode = 0;
  5399. }
  5400. // Set default value for prevent_reinit
  5401. if (!isset($this->prevent_reinit)) {
  5402. $this->prevent_reinit = 1;
  5403. }
  5404. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5405. return 'seriousgame';
  5406. }
  5407. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5408. return 'single';
  5409. }
  5410. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5411. return 'multiple';
  5412. }
  5413. return 'single';
  5414. }
  5415. /**
  5416. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5417. *
  5418. * @param string 'seriousgame', 'single' or 'multiple'
  5419. *
  5420. * @return bool
  5421. *
  5422. * @author ndiechburg <noel@cblue.be>
  5423. */
  5424. public function set_attempt_mode($mode)
  5425. {
  5426. switch ($mode) {
  5427. case 'seriousgame':
  5428. $sg_mode = 1;
  5429. $prevent_reinit = 1;
  5430. break;
  5431. case 'single':
  5432. $sg_mode = 0;
  5433. $prevent_reinit = 1;
  5434. break;
  5435. case 'multiple':
  5436. $sg_mode = 0;
  5437. $prevent_reinit = 0;
  5438. break;
  5439. default:
  5440. $sg_mode = 0;
  5441. $prevent_reinit = 0;
  5442. break;
  5443. }
  5444. $this->prevent_reinit = $prevent_reinit;
  5445. $this->seriousgame_mode = $sg_mode;
  5446. $table = Database::get_course_table(TABLE_LP_MAIN);
  5447. $sql = "UPDATE $table SET
  5448. prevent_reinit = $prevent_reinit ,
  5449. seriousgame_mode = $sg_mode
  5450. WHERE iid = ".$this->get_id();
  5451. $res = Database::query($sql);
  5452. if ($res) {
  5453. return true;
  5454. } else {
  5455. return false;
  5456. }
  5457. }
  5458. /**
  5459. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5460. *
  5461. * @author ndiechburg <noel@cblue.be>
  5462. */
  5463. public function switch_attempt_mode()
  5464. {
  5465. if ($this->debug > 0) {
  5466. error_log('In learnpath::switch_attempt_mode()', 0);
  5467. }
  5468. $mode = $this->get_attempt_mode();
  5469. switch ($mode) {
  5470. case 'single':
  5471. $next_mode = 'multiple';
  5472. break;
  5473. case 'multiple':
  5474. $next_mode = 'seriousgame';
  5475. break;
  5476. case 'seriousgame':
  5477. $next_mode = 'single';
  5478. break;
  5479. default:
  5480. $next_mode = 'single';
  5481. break;
  5482. }
  5483. $this->set_attempt_mode($next_mode);
  5484. }
  5485. /**
  5486. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5487. * but possibility to do again a completed item.
  5488. *
  5489. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5490. *
  5491. * @author ndiechburg <noel@cblue.be>
  5492. */
  5493. public function set_seriousgame_mode()
  5494. {
  5495. if ($this->debug > 0) {
  5496. error_log('In learnpath::set_seriousgame_mode()', 0);
  5497. }
  5498. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5499. $sql = "SELECT * FROM $lp_table
  5500. WHERE iid = ".$this->get_id();
  5501. $res = Database::query($sql);
  5502. if (Database::num_rows($res) > 0) {
  5503. $row = Database::fetch_array($res);
  5504. $force = $row['seriousgame_mode'];
  5505. if ($force == 1) {
  5506. $force = 0;
  5507. } elseif ($force == 0) {
  5508. $force = 1;
  5509. }
  5510. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5511. WHERE iid = ".$this->get_id();
  5512. Database::query($sql);
  5513. $this->seriousgame_mode = $force;
  5514. return $force;
  5515. } else {
  5516. if ($this->debug > 2) {
  5517. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5518. }
  5519. }
  5520. return -1;
  5521. }
  5522. /**
  5523. * Updates the "scorm_debug" value that shows or hide the debug window.
  5524. *
  5525. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5526. */
  5527. public function update_scorm_debug()
  5528. {
  5529. if ($this->debug > 0) {
  5530. error_log('In learnpath::update_scorm_debug()', 0);
  5531. }
  5532. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5533. $sql = "SELECT * FROM $lp_table
  5534. WHERE iid = ".$this->get_id();
  5535. $res = Database::query($sql);
  5536. if (Database::num_rows($res) > 0) {
  5537. $row = Database::fetch_array($res);
  5538. $force = $row['debug'];
  5539. if ($force == 1) {
  5540. $force = 0;
  5541. } elseif ($force == 0) {
  5542. $force = 1;
  5543. }
  5544. $sql = "UPDATE $lp_table SET debug = $force
  5545. WHERE iid = ".$this->get_id();
  5546. Database::query($sql);
  5547. $this->scorm_debug = $force;
  5548. return $force;
  5549. } else {
  5550. if ($this->debug > 2) {
  5551. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5552. }
  5553. }
  5554. return -1;
  5555. }
  5556. /**
  5557. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5558. *
  5559. * @author Kevin Van Den Haute
  5560. *
  5561. * @param array
  5562. */
  5563. public function tree_array($array)
  5564. {
  5565. if ($this->debug > 1) {
  5566. error_log('In learnpath::tree_array()', 0);
  5567. }
  5568. $array = $this->sort_tree_array($array);
  5569. $this->create_tree_array($array);
  5570. }
  5571. /**
  5572. * Creates an array with the elements of the learning path tree in it.
  5573. *
  5574. * @author Kevin Van Den Haute
  5575. *
  5576. * @param array $array
  5577. * @param int $parent
  5578. * @param int $depth
  5579. * @param array $tmp
  5580. */
  5581. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5582. {
  5583. if ($this->debug > 1) {
  5584. error_log('In learnpath::create_tree_array())', 0);
  5585. }
  5586. if (is_array($array)) {
  5587. for ($i = 0; $i < count($array); $i++) {
  5588. if ($array[$i]['parent_item_id'] == $parent) {
  5589. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5590. $tmp[] = $array[$i]['parent_item_id'];
  5591. $depth++;
  5592. }
  5593. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5594. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5595. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5596. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5597. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5598. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5599. $this->arrMenu[] = [
  5600. 'id' => $array[$i]['id'],
  5601. 'ref' => $ref,
  5602. 'item_type' => $array[$i]['item_type'],
  5603. 'title' => $array[$i]['title'],
  5604. 'path' => $path,
  5605. 'description' => $array[$i]['description'],
  5606. 'parent_item_id' => $array[$i]['parent_item_id'],
  5607. 'previous_item_id' => $array[$i]['previous_item_id'],
  5608. 'next_item_id' => $array[$i]['next_item_id'],
  5609. 'min_score' => $array[$i]['min_score'],
  5610. 'max_score' => $array[$i]['max_score'],
  5611. 'mastery_score' => $array[$i]['mastery_score'],
  5612. 'display_order' => $array[$i]['display_order'],
  5613. 'prerequisite' => $preq,
  5614. 'depth' => $depth,
  5615. 'audio' => $audio,
  5616. 'prerequisite_min_score' => $prerequisiteMinScore,
  5617. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5618. ];
  5619. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5620. }
  5621. }
  5622. }
  5623. }
  5624. /**
  5625. * Sorts a multi dimensional array by parent id and display order.
  5626. *
  5627. * @author Kevin Van Den Haute
  5628. *
  5629. * @param array $array (array with al the learning path items in it)
  5630. *
  5631. * @return array
  5632. */
  5633. public function sort_tree_array($array)
  5634. {
  5635. foreach ($array as $key => $row) {
  5636. $parent[$key] = $row['parent_item_id'];
  5637. $position[$key] = $row['display_order'];
  5638. }
  5639. if (count($array) > 0) {
  5640. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5641. }
  5642. return $array;
  5643. }
  5644. /**
  5645. * Function that creates a html list of learning path items so that we can add audio files to them.
  5646. *
  5647. * @author Kevin Van Den Haute
  5648. *
  5649. * @return string
  5650. */
  5651. public function overview()
  5652. {
  5653. if ($this->debug > 0) {
  5654. error_log('In learnpath::overview()', 0);
  5655. }
  5656. $return = '';
  5657. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5658. // we need to start a form when we want to update all the mp3 files
  5659. if ($update_audio == 'true') {
  5660. $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">';
  5661. }
  5662. $return .= '<div id="message"></div>';
  5663. if (count($this->items) == 0) {
  5664. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5665. } else {
  5666. $return_audio = '<table class="data_table">';
  5667. $return_audio .= '<tr>';
  5668. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5669. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5670. $return_audio .= '</tr>';
  5671. if ($update_audio != 'true') {
  5672. $return .= '<div class="col-md-12">';
  5673. $return .= self::return_new_tree($update_audio);
  5674. $return .= '</div>';
  5675. $return .= Display::div(
  5676. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5677. ['style' => 'float:left; margin-top:15px;width:100%']
  5678. );
  5679. } else {
  5680. $return_audio .= self::return_new_tree($update_audio);
  5681. $return .= $return_audio.'</table>';
  5682. }
  5683. // We need to close the form when we are updating the mp3 files.
  5684. if ($update_audio == 'true') {
  5685. $return .= '<div class="footer-audio">';
  5686. $return .= Display::button(
  5687. 'save_audio',
  5688. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5689. ['class' => 'btn btn-primary', 'type' => 'submit']
  5690. );
  5691. $return .= '</div>';
  5692. }
  5693. }
  5694. // We need to close the form when we are updating the mp3 files.
  5695. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5696. $return .= '</form>';
  5697. }
  5698. return $return;
  5699. }
  5700. /**
  5701. * @param string $update_audio
  5702. *
  5703. * @return array
  5704. */
  5705. public function processBuildMenuElements($update_audio = 'false')
  5706. {
  5707. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5708. $course_id = api_get_course_int_id();
  5709. $table = Database::get_course_table(TABLE_LP_ITEM);
  5710. $sql = "SELECT * FROM $table
  5711. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5712. $result = Database::query($sql);
  5713. $arrLP = [];
  5714. while ($row = Database::fetch_array($result)) {
  5715. $arrLP[] = [
  5716. 'id' => $row['iid'],
  5717. 'item_type' => $row['item_type'],
  5718. 'title' => Security::remove_XSS($row['title']),
  5719. 'path' => $row['path'],
  5720. 'description' => Security::remove_XSS($row['description']),
  5721. 'parent_item_id' => $row['parent_item_id'],
  5722. 'previous_item_id' => $row['previous_item_id'],
  5723. 'next_item_id' => $row['next_item_id'],
  5724. 'max_score' => $row['max_score'],
  5725. 'min_score' => $row['min_score'],
  5726. 'mastery_score' => $row['mastery_score'],
  5727. 'prerequisite' => $row['prerequisite'],
  5728. 'display_order' => $row['display_order'],
  5729. 'audio' => $row['audio'],
  5730. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5731. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5732. ];
  5733. }
  5734. $this->tree_array($arrLP);
  5735. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5736. unset($this->arrMenu);
  5737. $default_data = null;
  5738. $default_content = null;
  5739. $elements = [];
  5740. $return_audio = null;
  5741. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5742. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5743. for ($i = 0; $i < count($arrLP); $i++) {
  5744. $title = $arrLP[$i]['title'];
  5745. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5746. // Link for the documents
  5747. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5748. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5749. $title_cut = Display::url(
  5750. $title_cut,
  5751. $url,
  5752. [
  5753. 'class' => 'ajax moved',
  5754. 'data-title' => $title,
  5755. 'title' => $title,
  5756. ]
  5757. );
  5758. }
  5759. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5760. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5761. Session::write('pathItem', $arrLP[$i]['path']);
  5762. }
  5763. if (($i % 2) == 0) {
  5764. $oddClass = 'row_odd';
  5765. } else {
  5766. $oddClass = 'row_even';
  5767. }
  5768. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5769. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5770. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5771. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5772. } else {
  5773. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5774. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5775. } else {
  5776. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5777. $icon = Display::return_icon('certificate.png');
  5778. } else {
  5779. $icon = Display::return_icon('folder_document.gif');
  5780. }
  5781. }
  5782. }
  5783. // The audio column.
  5784. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5785. $audio = '';
  5786. if (!$update_audio || $update_audio != 'true') {
  5787. if (empty($arrLP[$i]['audio'])) {
  5788. $audio .= '';
  5789. }
  5790. } else {
  5791. $types = self::getChapterTypes();
  5792. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5793. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5794. if (!empty($arrLP[$i]['audio'])) {
  5795. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5796. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5797. }
  5798. }
  5799. }
  5800. $return_audio .= Display::span($icon.' '.$title).
  5801. Display::tag(
  5802. 'td',
  5803. $audio,
  5804. ['style' => '']
  5805. );
  5806. $return_audio .= '</td>';
  5807. $move_icon = '';
  5808. $move_item_icon = '';
  5809. $edit_icon = '';
  5810. $delete_icon = '';
  5811. $audio_icon = '';
  5812. $prerequisities_icon = '';
  5813. $forumIcon = '';
  5814. $previewIcon = '';
  5815. $pluginCalendarIcon = '';
  5816. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5817. $plugin = null;
  5818. if ($pluginCalendar) {
  5819. $plugin = LearningCalendarPlugin::create();
  5820. }
  5821. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5822. if ($is_allowed_to_edit) {
  5823. if (!$update_audio || $update_audio != 'true') {
  5824. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5825. $move_icon .= '<a class="moved" href="#">';
  5826. $move_icon .= Display::return_icon(
  5827. 'move_everywhere.png',
  5828. get_lang('Move'),
  5829. [],
  5830. ICON_SIZE_TINY
  5831. );
  5832. $move_icon .= '</a>';
  5833. }
  5834. }
  5835. // No edit for this item types
  5836. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5837. if ($arrLP[$i]['item_type'] != 'dir') {
  5838. $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">';
  5839. $edit_icon .= Display::return_icon(
  5840. 'edit.png',
  5841. get_lang('LearnpathEditModule'),
  5842. [],
  5843. ICON_SIZE_TINY
  5844. );
  5845. $edit_icon .= '</a>';
  5846. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5847. $forumThread = null;
  5848. if (isset($this->items[$arrLP[$i]['id']])) {
  5849. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5850. $this->course_int_id,
  5851. $this->lp_session_id
  5852. );
  5853. }
  5854. if ($forumThread) {
  5855. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5856. 'action' => 'dissociate_forum',
  5857. 'id' => $arrLP[$i]['id'],
  5858. 'lp_id' => $this->lp_id,
  5859. ]);
  5860. $forumIcon = Display::url(
  5861. Display::return_icon(
  5862. 'forum.png',
  5863. get_lang('DissociateForumToLPItem'),
  5864. [],
  5865. ICON_SIZE_TINY
  5866. ),
  5867. $forumIconUrl,
  5868. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5869. );
  5870. } else {
  5871. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5872. 'action' => 'create_forum',
  5873. 'id' => $arrLP[$i]['id'],
  5874. 'lp_id' => $this->lp_id,
  5875. ]);
  5876. $forumIcon = Display::url(
  5877. Display::return_icon(
  5878. 'forum.png',
  5879. get_lang('AssociateForumToLPItem'),
  5880. [],
  5881. ICON_SIZE_TINY
  5882. ),
  5883. $forumIconUrl,
  5884. ['class' => 'btn btn-default lp-btn-associate-forum']
  5885. );
  5886. }
  5887. }
  5888. } else {
  5889. $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">';
  5890. $edit_icon .= Display::return_icon(
  5891. 'edit.png',
  5892. get_lang('LearnpathEditModule'),
  5893. [],
  5894. ICON_SIZE_TINY
  5895. );
  5896. $edit_icon .= '</a>';
  5897. }
  5898. } else {
  5899. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5900. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5901. $edit_icon .= Display::return_icon(
  5902. 'edit.png',
  5903. get_lang('Edit'),
  5904. [],
  5905. ICON_SIZE_TINY
  5906. );
  5907. $edit_icon .= '</a>';
  5908. }
  5909. }
  5910. if ($pluginCalendar) {
  5911. $pluginLink = $pluginUrl.
  5912. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5913. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5914. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5915. if ($itemInfo && $itemInfo['value'] == 1) {
  5916. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5917. }
  5918. $pluginCalendarIcon = Display::url(
  5919. $iconCalendar,
  5920. $pluginLink,
  5921. ['class' => 'btn btn-default']
  5922. );
  5923. }
  5924. $delete_icon .= ' <a
  5925. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5926. onclick="return confirmation(\''.addslashes($title).'\');"
  5927. class="btn btn-default">';
  5928. $delete_icon .= Display::return_icon(
  5929. 'delete.png',
  5930. get_lang('LearnpathDeleteModule'),
  5931. [],
  5932. ICON_SIZE_TINY
  5933. );
  5934. $delete_icon .= '</a>';
  5935. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5936. $previewImage = Display::return_icon(
  5937. 'preview_view.png',
  5938. get_lang('Preview'),
  5939. [],
  5940. ICON_SIZE_TINY
  5941. );
  5942. switch ($arrLP[$i]['item_type']) {
  5943. case TOOL_DOCUMENT:
  5944. case TOOL_LP_FINAL_ITEM:
  5945. case TOOL_READOUT_TEXT:
  5946. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5947. $previewIcon = Display::url(
  5948. $previewImage,
  5949. $urlPreviewLink,
  5950. [
  5951. 'target' => '_blank',
  5952. 'class' => 'btn btn-default',
  5953. 'data-title' => $arrLP[$i]['title'],
  5954. 'title' => $arrLP[$i]['title'],
  5955. ]
  5956. );
  5957. break;
  5958. case TOOL_THREAD:
  5959. case TOOL_FORUM:
  5960. case TOOL_QUIZ:
  5961. case TOOL_STUDENTPUBLICATION:
  5962. case TOOL_LP_FINAL_ITEM:
  5963. case TOOL_LINK:
  5964. //$target = '';
  5965. //$class = 'btn btn-default ajax';
  5966. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5967. $class = 'btn btn-default';
  5968. $target = '_blank';
  5969. //}
  5970. $link = self::rl_get_resource_link_for_learnpath(
  5971. $this->course_int_id,
  5972. $this->lp_id,
  5973. $arrLP[$i]['id'],
  5974. 0
  5975. );
  5976. $previewIcon = Display::url(
  5977. $previewImage,
  5978. $link,
  5979. [
  5980. 'class' => $class,
  5981. 'data-title' => $arrLP[$i]['title'],
  5982. 'title' => $arrLP[$i]['title'],
  5983. 'target' => $target,
  5984. ]
  5985. );
  5986. break;
  5987. default:
  5988. $previewIcon = Display::url(
  5989. $previewImage,
  5990. $url.'&action=view_item',
  5991. ['class' => 'btn btn-default', 'target' => '_blank']
  5992. );
  5993. break;
  5994. }
  5995. if ($arrLP[$i]['item_type'] != 'dir') {
  5996. $prerequisities_icon = Display::url(
  5997. Display::return_icon(
  5998. 'accept.png',
  5999. get_lang('LearnpathPrerequisites'),
  6000. [],
  6001. ICON_SIZE_TINY
  6002. ),
  6003. $url.'&action=edit_item_prereq',
  6004. ['class' => 'btn btn-default']
  6005. );
  6006. if ($arrLP[$i]['item_type'] != 'final_item') {
  6007. $move_item_icon = Display::url(
  6008. Display::return_icon(
  6009. 'move.png',
  6010. get_lang('Move'),
  6011. [],
  6012. ICON_SIZE_TINY
  6013. ),
  6014. $url.'&action=move_item',
  6015. ['class' => 'btn btn-default']
  6016. );
  6017. }
  6018. $audio_icon = Display::url(
  6019. Display::return_icon(
  6020. 'audio.png',
  6021. get_lang('UplUpload'),
  6022. [],
  6023. ICON_SIZE_TINY
  6024. ),
  6025. $url.'&action=add_audio',
  6026. ['class' => 'btn btn-default']
  6027. );
  6028. }
  6029. }
  6030. if ($update_audio != 'true') {
  6031. $row = $move_icon.' '.$icon.
  6032. Display::span($title_cut).
  6033. Display::tag(
  6034. 'div',
  6035. "<div class=\"btn-group btn-group-xs\">
  6036. $previewIcon
  6037. $audio
  6038. $edit_icon
  6039. $pluginCalendarIcon
  6040. $forumIcon
  6041. $prerequisities_icon
  6042. $move_item_icon
  6043. $audio_icon
  6044. $delete_icon
  6045. </div>",
  6046. ['class' => 'btn-toolbar button_actions']
  6047. );
  6048. } else {
  6049. $row =
  6050. Display::span($title.$icon).
  6051. Display::span($audio, ['class' => 'button_actions']);
  6052. }
  6053. $parent_id = $arrLP[$i]['parent_item_id'];
  6054. $default_data[$arrLP[$i]['id']] = $row;
  6055. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6056. if (empty($parent_id)) {
  6057. $elements[$arrLP[$i]['id']]['data'] = $row;
  6058. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6059. } else {
  6060. $parent_arrays = [];
  6061. if ($arrLP[$i]['depth'] > 1) {
  6062. //Getting list of parents
  6063. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6064. foreach ($arrLP as $item) {
  6065. if ($item['id'] == $parent_id) {
  6066. if ($item['parent_item_id'] == 0) {
  6067. $parent_id = $item['id'];
  6068. break;
  6069. } else {
  6070. $parent_id = $item['parent_item_id'];
  6071. if (empty($parent_arrays)) {
  6072. $parent_arrays[] = intval($item['id']);
  6073. }
  6074. $parent_arrays[] = $parent_id;
  6075. break;
  6076. }
  6077. }
  6078. }
  6079. }
  6080. }
  6081. if (!empty($parent_arrays)) {
  6082. $parent_arrays = array_reverse($parent_arrays);
  6083. $val = '$elements';
  6084. $x = 0;
  6085. foreach ($parent_arrays as $item) {
  6086. if ($x != count($parent_arrays) - 1) {
  6087. $val .= '["'.$item.'"]["children"]';
  6088. } else {
  6089. $val .= '["'.$item.'"]["children"]';
  6090. }
  6091. $x++;
  6092. }
  6093. $val .= "";
  6094. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6095. eval($code_str);
  6096. } else {
  6097. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6098. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6099. }
  6100. }
  6101. }
  6102. return [
  6103. 'elements' => $elements,
  6104. 'default_data' => $default_data,
  6105. 'default_content' => $default_content,
  6106. 'return_audio' => $return_audio,
  6107. ];
  6108. }
  6109. /**
  6110. * @param string $updateAudio true/false strings
  6111. *
  6112. * @return string
  6113. */
  6114. public function returnLpItemList($updateAudio)
  6115. {
  6116. $result = $this->processBuildMenuElements($updateAudio);
  6117. $html = self::print_recursive(
  6118. $result['elements'],
  6119. $result['default_data'],
  6120. $result['default_content']
  6121. );
  6122. if (!empty($html)) {
  6123. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6124. }
  6125. return $html;
  6126. }
  6127. /**
  6128. * @param string $update_audio
  6129. * @param bool $drop_element_here
  6130. *
  6131. * @return string
  6132. */
  6133. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6134. {
  6135. $return = '';
  6136. $result = $this->processBuildMenuElements($update_audio);
  6137. $list = '<ul id="lp_item_list">';
  6138. $tree = $this->print_recursive(
  6139. $result['elements'],
  6140. $result['default_data'],
  6141. $result['default_content']
  6142. );
  6143. if (!empty($tree)) {
  6144. $list .= $tree;
  6145. } else {
  6146. if ($drop_element_here) {
  6147. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6148. }
  6149. }
  6150. $list .= '</ul>';
  6151. $return .= Display::panelCollapse(
  6152. $this->name,
  6153. $list,
  6154. 'scorm-list',
  6155. null,
  6156. 'scorm-list-accordion',
  6157. 'scorm-list-collapse'
  6158. );
  6159. if ($update_audio === 'true') {
  6160. $return = $result['return_audio'];
  6161. }
  6162. return $return;
  6163. }
  6164. /**
  6165. * @param array $elements
  6166. * @param array $default_data
  6167. * @param array $default_content
  6168. *
  6169. * @return string
  6170. */
  6171. public function print_recursive($elements, $default_data, $default_content)
  6172. {
  6173. $return = '';
  6174. foreach ($elements as $key => $item) {
  6175. if (isset($item['load_data']) || empty($item['data'])) {
  6176. $item['data'] = $default_data[$item['load_data']];
  6177. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6178. }
  6179. $sub_list = '';
  6180. if (isset($item['type']) && $item['type'] == 'dir') {
  6181. // empty value
  6182. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6183. }
  6184. if (empty($item['children'])) {
  6185. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6186. $active = null;
  6187. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6188. $active = 'active';
  6189. }
  6190. $return .= Display::tag(
  6191. 'li',
  6192. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6193. ['id' => $key, 'class' => 'record li_container']
  6194. );
  6195. } else {
  6196. // Sections
  6197. $data = '';
  6198. if (isset($item['children'])) {
  6199. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6200. }
  6201. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6202. $return .= Display::tag(
  6203. 'li',
  6204. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6205. ['id' => $key, 'class' => 'record li_container']
  6206. );
  6207. }
  6208. }
  6209. return $return;
  6210. }
  6211. /**
  6212. * This function builds the action menu.
  6213. *
  6214. * @param bool $returnContent Optional
  6215. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6216. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6217. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6218. *
  6219. * @return string
  6220. */
  6221. public function build_action_menu(
  6222. $returnContent = false,
  6223. $showRequirementButtons = true,
  6224. $isConfigPage = false,
  6225. $allowExpand = true
  6226. ) {
  6227. $actionsLeft = '';
  6228. $actionsRight = '';
  6229. $actionsLeft .= Display::url(
  6230. Display::return_icon(
  6231. 'preview_view.png',
  6232. get_lang('Preview'),
  6233. '',
  6234. ICON_SIZE_MEDIUM
  6235. ),
  6236. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6237. 'action' => 'view',
  6238. 'lp_id' => $this->lp_id,
  6239. 'isStudentView' => 'true',
  6240. ])
  6241. );
  6242. $actionsLeft .= Display::url(
  6243. Display::return_icon(
  6244. 'upload_audio.png',
  6245. get_lang('UpdateAllAudioFragments'),
  6246. '',
  6247. ICON_SIZE_MEDIUM
  6248. ),
  6249. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6250. 'action' => 'admin_view',
  6251. 'lp_id' => $this->lp_id,
  6252. 'updateaudio' => 'true',
  6253. ])
  6254. );
  6255. if (!$isConfigPage) {
  6256. $actionsLeft .= Display::url(
  6257. Display::return_icon(
  6258. 'settings.png',
  6259. get_lang('CourseSettings'),
  6260. '',
  6261. ICON_SIZE_MEDIUM
  6262. ),
  6263. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6264. 'action' => 'edit',
  6265. 'lp_id' => $this->lp_id,
  6266. ])
  6267. );
  6268. } else {
  6269. $actionsLeft .= Display::url(
  6270. Display::return_icon(
  6271. 'edit.png',
  6272. get_lang('Edit'),
  6273. '',
  6274. ICON_SIZE_MEDIUM
  6275. ),
  6276. 'lp_controller.php?'.http_build_query([
  6277. 'action' => 'build',
  6278. 'lp_id' => $this->lp_id,
  6279. ]).'&'.api_get_cidreq()
  6280. );
  6281. }
  6282. if ($allowExpand) {
  6283. $actionsLeft .= Display::url(
  6284. Display::return_icon(
  6285. 'expand.png',
  6286. get_lang('Expand'),
  6287. ['id' => 'expand'],
  6288. ICON_SIZE_MEDIUM
  6289. ).
  6290. Display::return_icon(
  6291. 'contract.png',
  6292. get_lang('Collapse'),
  6293. ['id' => 'contract', 'class' => 'hide'],
  6294. ICON_SIZE_MEDIUM
  6295. ),
  6296. '#',
  6297. ['role' => 'button', 'id' => 'hide_bar_template']
  6298. );
  6299. }
  6300. if ($showRequirementButtons) {
  6301. $buttons = [
  6302. [
  6303. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6304. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6305. 'action' => 'set_previous_step_as_prerequisite',
  6306. 'lp_id' => $this->lp_id,
  6307. ]),
  6308. ],
  6309. [
  6310. 'title' => get_lang('ClearAllPrerequisites'),
  6311. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6312. 'action' => 'clear_prerequisites',
  6313. 'lp_id' => $this->lp_id,
  6314. ]),
  6315. ],
  6316. ];
  6317. $actionsRight = Display::groupButtonWithDropDown(
  6318. get_lang('PrerequisitesOptions'),
  6319. $buttons,
  6320. true
  6321. );
  6322. }
  6323. $toolbar = Display::toolbarAction(
  6324. 'actions-lp-controller',
  6325. [$actionsLeft, $actionsRight]
  6326. );
  6327. if ($returnContent) {
  6328. return $toolbar;
  6329. }
  6330. echo $toolbar;
  6331. }
  6332. /**
  6333. * Creates the default learning path folder.
  6334. *
  6335. * @param array $course
  6336. * @param int $creatorId
  6337. *
  6338. * @return bool
  6339. */
  6340. public static function generate_learning_path_folder($course, $creatorId = 0)
  6341. {
  6342. // Creating learning_path folder
  6343. $dir = '/learning_path';
  6344. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6345. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6346. $folder = false;
  6347. if (!is_dir($filepath.'/'.$dir)) {
  6348. $folderData = create_unexisting_directory(
  6349. $course,
  6350. $creatorId,
  6351. 0,
  6352. null,
  6353. 0,
  6354. $filepath,
  6355. $dir,
  6356. get_lang('LearningPaths'),
  6357. 0
  6358. );
  6359. if (!empty($folderData)) {
  6360. $folder = true;
  6361. }
  6362. } else {
  6363. $folder = true;
  6364. }
  6365. return $folder;
  6366. }
  6367. /**
  6368. * @param array $course
  6369. * @param string $lp_name
  6370. * @param int $creatorId
  6371. *
  6372. * @return array
  6373. */
  6374. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6375. {
  6376. $filepath = '';
  6377. $dir = '/learning_path/';
  6378. if (empty($lp_name)) {
  6379. $lp_name = $this->name;
  6380. }
  6381. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6382. $folder = self::generate_learning_path_folder($course, $creatorId);
  6383. // Limits title size
  6384. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6385. $dir = $dir.$title;
  6386. // Creating LP folder
  6387. $documentId = null;
  6388. if ($folder) {
  6389. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6390. if (!is_dir($filepath.'/'.$dir)) {
  6391. $folderData = create_unexisting_directory(
  6392. $course,
  6393. $creatorId,
  6394. 0,
  6395. 0,
  6396. 0,
  6397. $filepath,
  6398. $dir,
  6399. $lp_name
  6400. );
  6401. if (!empty($folderData)) {
  6402. $folder = true;
  6403. }
  6404. $documentId = $folderData['id'];
  6405. } else {
  6406. $folder = true;
  6407. }
  6408. $dir = $dir.'/';
  6409. if ($folder) {
  6410. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6411. }
  6412. }
  6413. if (empty($documentId)) {
  6414. $dir = api_remove_trailing_slash($dir);
  6415. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6416. }
  6417. $array = [
  6418. 'dir' => $dir,
  6419. 'filepath' => $filepath,
  6420. 'folder' => $folder,
  6421. 'id' => $documentId,
  6422. ];
  6423. return $array;
  6424. }
  6425. /**
  6426. * Create a new document //still needs some finetuning.
  6427. *
  6428. * @param array $courseInfo
  6429. * @param string $content
  6430. * @param string $title
  6431. * @param string $extension
  6432. * @param int $parentId
  6433. * @param int $creatorId creator id
  6434. *
  6435. * @return int
  6436. */
  6437. public function create_document(
  6438. $courseInfo,
  6439. $content = '',
  6440. $title = '',
  6441. $extension = 'html',
  6442. $parentId = 0,
  6443. $creatorId = 0
  6444. ) {
  6445. if (!empty($courseInfo)) {
  6446. $course_id = $courseInfo['real_id'];
  6447. } else {
  6448. $course_id = api_get_course_int_id();
  6449. }
  6450. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6451. $sessionId = api_get_session_id();
  6452. // Generates folder
  6453. $result = $this->generate_lp_folder($courseInfo);
  6454. $dir = $result['dir'];
  6455. if (empty($parentId) || $parentId == '/') {
  6456. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6457. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6458. if ($parentId === '/') {
  6459. $dir = '/';
  6460. }
  6461. // Please, do not modify this dirname formatting.
  6462. if (strstr($dir, '..')) {
  6463. $dir = '/';
  6464. }
  6465. if (!empty($dir[0]) && $dir[0] == '.') {
  6466. $dir = substr($dir, 1);
  6467. }
  6468. if (!empty($dir[0]) && $dir[0] != '/') {
  6469. $dir = '/'.$dir;
  6470. }
  6471. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6472. $dir .= '/';
  6473. }
  6474. } else {
  6475. $parentInfo = DocumentManager::get_document_data_by_id(
  6476. $parentId,
  6477. $courseInfo['code']
  6478. );
  6479. if (!empty($parentInfo)) {
  6480. $dir = $parentInfo['path'].'/';
  6481. }
  6482. }
  6483. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6484. if (!is_dir($filepath)) {
  6485. $dir = '/';
  6486. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6487. }
  6488. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6489. // is already escaped twice when it gets here.
  6490. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6491. if (!empty($title)) {
  6492. $title = api_replace_dangerous_char(stripslashes($title));
  6493. } else {
  6494. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6495. }
  6496. $title = disable_dangerous_file($title);
  6497. $filename = $title;
  6498. $content = !empty($content) ? $content : $_POST['content_lp'];
  6499. $tmp_filename = $filename;
  6500. $i = 0;
  6501. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6502. $tmp_filename = $filename.'_'.++$i;
  6503. }
  6504. $filename = $tmp_filename.'.'.$extension;
  6505. if ($extension == 'html') {
  6506. $content = stripslashes($content);
  6507. $content = str_replace(
  6508. api_get_path(WEB_COURSE_PATH),
  6509. api_get_path(REL_PATH).'courses/',
  6510. $content
  6511. );
  6512. // Change the path of mp3 to absolute.
  6513. // The first regexp deals with :// urls.
  6514. $content = preg_replace(
  6515. "|(flashvars=\"file=)([^:/]+)/|",
  6516. "$1".api_get_path(
  6517. REL_COURSE_PATH
  6518. ).$courseInfo['path'].'/document/',
  6519. $content
  6520. );
  6521. // The second regexp deals with audio/ urls.
  6522. $content = preg_replace(
  6523. "|(flashvars=\"file=)([^/]+)/|",
  6524. "$1".api_get_path(
  6525. REL_COURSE_PATH
  6526. ).$courseInfo['path'].'/document/$2/',
  6527. $content
  6528. );
  6529. // For flv player: To prevent edition problem with firefox,
  6530. // we have to use a strange tip (don't blame me please).
  6531. $content = str_replace(
  6532. '</body>',
  6533. '<style type="text/css">body{}</style></body>',
  6534. $content
  6535. );
  6536. }
  6537. if (!file_exists($filepath.$filename)) {
  6538. if ($fp = @fopen($filepath.$filename, 'w')) {
  6539. fputs($fp, $content);
  6540. fclose($fp);
  6541. $file_size = filesize($filepath.$filename);
  6542. $save_file_path = $dir.$filename;
  6543. $document_id = add_document(
  6544. $courseInfo,
  6545. $save_file_path,
  6546. 'file',
  6547. $file_size,
  6548. $tmp_filename,
  6549. '',
  6550. 0, //readonly
  6551. true,
  6552. null,
  6553. $sessionId,
  6554. $creatorId
  6555. );
  6556. if ($document_id) {
  6557. api_item_property_update(
  6558. $courseInfo,
  6559. TOOL_DOCUMENT,
  6560. $document_id,
  6561. 'DocumentAdded',
  6562. $creatorId,
  6563. null,
  6564. null,
  6565. null,
  6566. null,
  6567. $sessionId
  6568. );
  6569. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6570. $new_title = $originalTitle;
  6571. if ($new_comment || $new_title) {
  6572. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6573. $ct = '';
  6574. if ($new_comment) {
  6575. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6576. }
  6577. if ($new_title) {
  6578. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6579. }
  6580. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6581. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6582. Database::query($sql);
  6583. }
  6584. }
  6585. return $document_id;
  6586. }
  6587. }
  6588. }
  6589. /**
  6590. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6591. *
  6592. * @param array $_course array
  6593. */
  6594. public function edit_document($_course)
  6595. {
  6596. $course_id = api_get_course_int_id();
  6597. $urlAppend = api_get_configuration_value('url_append');
  6598. // Please, do not modify this dirname formatting.
  6599. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6600. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6601. if (strstr($dir, '..')) {
  6602. $dir = '/';
  6603. }
  6604. if (isset($dir[0]) && $dir[0] == '.') {
  6605. $dir = substr($dir, 1);
  6606. }
  6607. if (isset($dir[0]) && $dir[0] != '/') {
  6608. $dir = '/'.$dir;
  6609. }
  6610. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6611. $dir .= '/';
  6612. }
  6613. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6614. if (!is_dir($filepath)) {
  6615. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6616. }
  6617. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6618. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6619. $document_id = (int) $_POST['path'];
  6620. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6621. if (empty($documentInfo)) {
  6622. // Try with iid
  6623. $table = Database::get_course_table(TABLE_DOCUMENT);
  6624. $sql = "SELECT id, path FROM $table
  6625. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6626. $res_doc = Database::query($sql);
  6627. $row = Database::fetch_array($res_doc);
  6628. if ($row) {
  6629. $document_id = $row['id'];
  6630. $documentPath = $row['path'];
  6631. }
  6632. } else {
  6633. $documentPath = $documentInfo['path'];
  6634. }
  6635. $content = stripslashes($_POST['content_lp']);
  6636. $file = $filepath.$documentPath;
  6637. if (!file_exists($file)) {
  6638. return false;
  6639. }
  6640. if ($fp = @fopen($file, 'w')) {
  6641. $content = str_replace(
  6642. api_get_path(WEB_COURSE_PATH),
  6643. $urlAppend.api_get_path(REL_COURSE_PATH),
  6644. $content
  6645. );
  6646. // Change the path of mp3 to absolute.
  6647. // The first regexp deals with :// urls.
  6648. $content = preg_replace(
  6649. "|(flashvars=\"file=)([^:/]+)/|",
  6650. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6651. $content
  6652. );
  6653. // The second regexp deals with audio/ urls.
  6654. $content = preg_replace(
  6655. "|(flashvars=\"file=)([^:/]+)/|",
  6656. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6657. $content
  6658. );
  6659. fputs($fp, $content);
  6660. fclose($fp);
  6661. $sql = "UPDATE $table_doc SET
  6662. title='".Database::escape_string($_POST['title'])."'
  6663. WHERE c_id = $course_id AND id = ".$document_id;
  6664. Database::query($sql);
  6665. }
  6666. }
  6667. }
  6668. /**
  6669. * Displays the selected item, with a panel for manipulating the item.
  6670. *
  6671. * @param int $item_id
  6672. * @param string $msg
  6673. * @param bool $show_actions
  6674. *
  6675. * @return string
  6676. */
  6677. public function display_item($item_id, $msg = null, $show_actions = true)
  6678. {
  6679. $course_id = api_get_course_int_id();
  6680. $return = '';
  6681. if (is_numeric($item_id)) {
  6682. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6683. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6684. WHERE lp.iid = ".intval($item_id);
  6685. $result = Database::query($sql);
  6686. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6687. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6688. // Prevents wrong parent selection for document, see Bug#1251.
  6689. if ($row['item_type'] != 'dir') {
  6690. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6691. }
  6692. if ($show_actions) {
  6693. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6694. }
  6695. $return .= '<div style="padding:10px;">';
  6696. if ($msg != '') {
  6697. $return .= $msg;
  6698. }
  6699. $return .= '<h3>'.$row['title'].'</h3>';
  6700. switch ($row['item_type']) {
  6701. case TOOL_THREAD:
  6702. $link = $this->rl_get_resource_link_for_learnpath(
  6703. $course_id,
  6704. $row['lp_id'],
  6705. $item_id,
  6706. 0
  6707. );
  6708. $return .= Display::url(
  6709. get_lang('GoToThread'),
  6710. $link,
  6711. ['class' => 'btn btn-primary']
  6712. );
  6713. break;
  6714. case TOOL_FORUM:
  6715. $return .= Display::url(
  6716. get_lang('GoToForum'),
  6717. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6718. ['class' => 'btn btn-primary']
  6719. );
  6720. break;
  6721. case TOOL_QUIZ:
  6722. if (!empty($row['path'])) {
  6723. $exercise = new Exercise();
  6724. $exercise->read($row['path']);
  6725. $return .= $exercise->description.'<br />';
  6726. $return .= Display::url(
  6727. get_lang('GoToExercise'),
  6728. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6729. ['class' => 'btn btn-primary']
  6730. );
  6731. }
  6732. break;
  6733. case TOOL_LP_FINAL_ITEM:
  6734. $return .= $this->getSavedFinalItem();
  6735. break;
  6736. case TOOL_DOCUMENT:
  6737. case TOOL_READOUT_TEXT:
  6738. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6739. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6740. WHERE c_id = ".$course_id." AND iid = ".intval($row['path']);
  6741. $result = Database::query($sql_doc);
  6742. $path_file = Database::result($result, 0, 0);
  6743. $path_parts = pathinfo($path_file);
  6744. // TODO: Correct the following naive comparisons.
  6745. if (in_array($path_parts['extension'], [
  6746. 'html',
  6747. 'txt',
  6748. 'png',
  6749. 'jpg',
  6750. 'JPG',
  6751. 'jpeg',
  6752. 'JPEG',
  6753. 'gif',
  6754. 'swf',
  6755. 'pdf',
  6756. 'htm',
  6757. ])) {
  6758. $return .= $this->display_document($row['path'], true, true);
  6759. }
  6760. break;
  6761. case TOOL_HOTPOTATOES:
  6762. $return .= $this->display_document($row['path'], false, true);
  6763. break;
  6764. }
  6765. $return .= '</div>';
  6766. }
  6767. }
  6768. return $return;
  6769. }
  6770. /**
  6771. * Shows the needed forms for editing a specific item.
  6772. *
  6773. * @param int $item_id
  6774. *
  6775. * @throws Exception
  6776. * @throws HTML_QuickForm_Error
  6777. *
  6778. * @return string
  6779. */
  6780. public function display_edit_item($item_id)
  6781. {
  6782. $course_id = api_get_course_int_id();
  6783. $return = '';
  6784. $item_id = (int) $item_id;
  6785. if (empty($item_id)) {
  6786. return '';
  6787. }
  6788. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6789. $sql = "SELECT * FROM $tbl_lp_item
  6790. WHERE iid = ".$item_id;
  6791. $res = Database::query($sql);
  6792. $row = Database::fetch_array($res);
  6793. switch ($row['item_type']) {
  6794. case 'dir':
  6795. case 'asset':
  6796. case 'sco':
  6797. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6798. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6799. $return .= $this->display_item_form(
  6800. $row['item_type'],
  6801. get_lang('EditCurrentChapter').' :',
  6802. 'edit',
  6803. $item_id,
  6804. $row
  6805. );
  6806. } else {
  6807. $return .= $this->display_item_form(
  6808. $row['item_type'],
  6809. get_lang('EditCurrentChapter').' :',
  6810. 'edit_item',
  6811. $item_id,
  6812. $row
  6813. );
  6814. }
  6815. break;
  6816. case TOOL_DOCUMENT:
  6817. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6818. $sql = "SELECT lp.*, doc.path as dir
  6819. FROM $tbl_lp_item as lp
  6820. LEFT JOIN $tbl_doc as doc
  6821. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6822. WHERE
  6823. doc.c_id = $course_id AND
  6824. lp.iid = ".$item_id;
  6825. $res_step = Database::query($sql);
  6826. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6827. $return .= $this->display_manipulate(
  6828. $item_id,
  6829. $row['item_type']
  6830. );
  6831. $return .= $this->display_document_form(
  6832. 'edit',
  6833. $item_id,
  6834. $row_step
  6835. );
  6836. break;
  6837. case TOOL_READOUT_TEXT:
  6838. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6839. $sql = "SELECT lp.*, doc.path as dir
  6840. FROM $tbl_lp_item as lp
  6841. LEFT JOIN $tbl_doc as doc
  6842. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6843. WHERE
  6844. doc.c_id = $course_id AND
  6845. lp.iid = ".$item_id;
  6846. $res_step = Database::query($sql);
  6847. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6848. $return .= $this->display_manipulate(
  6849. $item_id,
  6850. $row['item_type']
  6851. );
  6852. $return .= $this->displayFrmReadOutText(
  6853. 'edit',
  6854. $item_id,
  6855. $row_step
  6856. );
  6857. break;
  6858. case TOOL_LINK:
  6859. $link_id = (string) $row['path'];
  6860. if (ctype_digit($link_id)) {
  6861. $tbl_link = Database::get_course_table(TABLE_LINK);
  6862. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6863. WHERE c_id = '.$course_id.' AND iid = '.intval($link_id);
  6864. $res_link = Database::query($sql_select);
  6865. $row_link = Database::fetch_array($res_link);
  6866. if (is_array($row_link)) {
  6867. $row['url'] = $row_link['url'];
  6868. }
  6869. }
  6870. $return .= $this->display_manipulate(
  6871. $item_id,
  6872. $row['item_type']
  6873. );
  6874. $return .= $this->display_link_form('edit', $item_id, $row);
  6875. break;
  6876. case TOOL_LP_FINAL_ITEM:
  6877. Session::write('finalItem', true);
  6878. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6879. $sql = "SELECT lp.*, doc.path as dir
  6880. FROM $tbl_lp_item as lp
  6881. LEFT JOIN $tbl_doc as doc
  6882. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6883. WHERE
  6884. doc.c_id = $course_id AND
  6885. lp.iid = ".$item_id;
  6886. $res_step = Database::query($sql);
  6887. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6888. $return .= $this->display_manipulate(
  6889. $item_id,
  6890. $row['item_type']
  6891. );
  6892. $return .= $this->display_document_form(
  6893. 'edit',
  6894. $item_id,
  6895. $row_step
  6896. );
  6897. break;
  6898. case TOOL_QUIZ:
  6899. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6900. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6901. break;
  6902. case TOOL_HOTPOTATOES:
  6903. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6904. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6905. break;
  6906. case TOOL_STUDENTPUBLICATION:
  6907. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6908. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6909. break;
  6910. case TOOL_FORUM:
  6911. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6912. $return .= $this->display_forum_form('edit', $item_id, $row);
  6913. break;
  6914. case TOOL_THREAD:
  6915. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6916. $return .= $this->display_thread_form('edit', $item_id, $row);
  6917. break;
  6918. }
  6919. return $return;
  6920. }
  6921. /**
  6922. * Function that displays a list with al the resources that
  6923. * could be added to the learning path.
  6924. *
  6925. * @throws Exception
  6926. * @throws HTML_QuickForm_Error
  6927. *
  6928. * @return bool
  6929. */
  6930. public function display_resources()
  6931. {
  6932. $course_code = api_get_course_id();
  6933. // Get all the docs.
  6934. $documents = $this->get_documents(true);
  6935. // Get all the exercises.
  6936. $exercises = $this->get_exercises();
  6937. // Get all the links.
  6938. $links = $this->get_links();
  6939. // Get all the student publications.
  6940. $works = $this->get_student_publications();
  6941. // Get all the forums.
  6942. $forums = $this->get_forums(null, $course_code);
  6943. // Get the final item form (see BT#11048) .
  6944. $finish = $this->getFinalItemForm();
  6945. $headers = [
  6946. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6947. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6948. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6949. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6950. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6951. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6952. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6953. ];
  6954. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6955. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6956. echo Display::tabs(
  6957. $headers,
  6958. [
  6959. $documents,
  6960. $exercises,
  6961. $links,
  6962. $works,
  6963. $forums,
  6964. $dir,
  6965. $finish,
  6966. ],
  6967. 'resource_tab'
  6968. );
  6969. return true;
  6970. }
  6971. /**
  6972. * Returns the extension of a document.
  6973. *
  6974. * @param string $filename
  6975. *
  6976. * @return string Extension (part after the last dot)
  6977. */
  6978. public function get_extension($filename)
  6979. {
  6980. $explode = explode('.', $filename);
  6981. return $explode[count($explode) - 1];
  6982. }
  6983. /**
  6984. * Displays a document by id.
  6985. *
  6986. * @param int $id
  6987. * @param bool $show_title
  6988. * @param bool $iframe
  6989. * @param bool $edit_link
  6990. *
  6991. * @return string
  6992. */
  6993. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6994. {
  6995. $_course = api_get_course_info();
  6996. $course_id = api_get_course_int_id();
  6997. $id = (int) $id;
  6998. $return = '';
  6999. $table = Database::get_course_table(TABLE_DOCUMENT);
  7000. $sql_doc = "SELECT * FROM $table
  7001. WHERE c_id = $course_id AND iid = $id";
  7002. $res_doc = Database::query($sql_doc);
  7003. $row_doc = Database::fetch_array($res_doc);
  7004. // TODO: Add a path filter.
  7005. if ($iframe) {
  7006. $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>';
  7007. } else {
  7008. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  7009. }
  7010. return $return;
  7011. }
  7012. /**
  7013. * Return HTML form to add/edit a quiz.
  7014. *
  7015. * @param string $action Action (add/edit)
  7016. * @param int $id Item ID if already exists
  7017. * @param mixed $extra_info Extra information (quiz ID if integer)
  7018. *
  7019. * @throws Exception
  7020. *
  7021. * @return string HTML form
  7022. */
  7023. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  7024. {
  7025. $course_id = api_get_course_int_id();
  7026. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7027. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7028. if ($id != 0 && is_array($extra_info)) {
  7029. $item_title = $extra_info['title'];
  7030. $item_description = $extra_info['description'];
  7031. } elseif (is_numeric($extra_info)) {
  7032. $sql = "SELECT title, description
  7033. FROM $tbl_quiz
  7034. WHERE c_id = $course_id AND iid = ".$extra_info;
  7035. $result = Database::query($sql);
  7036. $row = Database::fetch_array($result);
  7037. $item_title = $row['title'];
  7038. $item_description = $row['description'];
  7039. } else {
  7040. $item_title = '';
  7041. $item_description = '';
  7042. }
  7043. $item_title = Security::remove_XSS($item_title);
  7044. $item_description = Security::remove_XSS($item_description);
  7045. if ($id != 0 && is_array($extra_info)) {
  7046. $parent = $extra_info['parent_item_id'];
  7047. } else {
  7048. $parent = 0;
  7049. }
  7050. $sql = "SELECT * FROM $tbl_lp_item
  7051. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7052. $result = Database::query($sql);
  7053. $arrLP = [];
  7054. while ($row = Database::fetch_array($result)) {
  7055. $arrLP[] = [
  7056. 'id' => $row['iid'],
  7057. 'item_type' => $row['item_type'],
  7058. 'title' => $row['title'],
  7059. 'path' => $row['path'],
  7060. 'description' => $row['description'],
  7061. 'parent_item_id' => $row['parent_item_id'],
  7062. 'previous_item_id' => $row['previous_item_id'],
  7063. 'next_item_id' => $row['next_item_id'],
  7064. 'display_order' => $row['display_order'],
  7065. 'max_score' => $row['max_score'],
  7066. 'min_score' => $row['min_score'],
  7067. 'mastery_score' => $row['mastery_score'],
  7068. 'prerequisite' => $row['prerequisite'],
  7069. 'max_time_allowed' => $row['max_time_allowed'],
  7070. ];
  7071. }
  7072. $this->tree_array($arrLP);
  7073. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7074. unset($this->arrMenu);
  7075. $form = new FormValidator(
  7076. 'quiz_form',
  7077. 'POST',
  7078. $this->getCurrentBuildingModeURL()
  7079. );
  7080. $defaults = [];
  7081. if ($action == 'add') {
  7082. $legend = get_lang('CreateTheExercise');
  7083. } elseif ($action == 'move') {
  7084. $legend = get_lang('MoveTheCurrentExercise');
  7085. } else {
  7086. $legend = get_lang('EditCurrentExecice');
  7087. }
  7088. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7089. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7090. }
  7091. $form->addHeader($legend);
  7092. if ($action != 'move') {
  7093. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7094. $defaults['title'] = $item_title;
  7095. }
  7096. // Select for Parent item, root or chapter
  7097. $selectParent = $form->addSelect(
  7098. 'parent',
  7099. get_lang('Parent'),
  7100. [],
  7101. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7102. );
  7103. $selectParent->addOption($this->name, 0);
  7104. $arrHide = [
  7105. $id,
  7106. ];
  7107. for ($i = 0; $i < count($arrLP); $i++) {
  7108. if ($action != 'add') {
  7109. if (
  7110. ($arrLP[$i]['item_type'] == 'dir') &&
  7111. !in_array($arrLP[$i]['id'], $arrHide) &&
  7112. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7113. ) {
  7114. $selectParent->addOption(
  7115. $arrLP[$i]['title'],
  7116. $arrLP[$i]['id'],
  7117. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7118. );
  7119. if ($parent == $arrLP[$i]['id']) {
  7120. $selectParent->setSelected($arrLP[$i]['id']);
  7121. }
  7122. } else {
  7123. $arrHide[] = $arrLP[$i]['id'];
  7124. }
  7125. } else {
  7126. if ($arrLP[$i]['item_type'] == 'dir') {
  7127. $selectParent->addOption(
  7128. $arrLP[$i]['title'],
  7129. $arrLP[$i]['id'],
  7130. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7131. );
  7132. if ($parent == $arrLP[$i]['id']) {
  7133. $selectParent->setSelected($arrLP[$i]['id']);
  7134. }
  7135. }
  7136. }
  7137. }
  7138. if (is_array($arrLP)) {
  7139. reset($arrLP);
  7140. }
  7141. $selectPrevious = $form->addSelect(
  7142. 'previous',
  7143. get_lang('Position'),
  7144. [],
  7145. ['id' => 'previous']
  7146. );
  7147. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7148. for ($i = 0; $i < count($arrLP); $i++) {
  7149. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7150. $arrLP[$i]['id'] != $id
  7151. ) {
  7152. $selectPrevious->addOption(
  7153. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7154. $arrLP[$i]['id']
  7155. );
  7156. if (is_array($extra_info)) {
  7157. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7158. $selectPrevious->setSelected($arrLP[$i]['id']);
  7159. }
  7160. } elseif ($action == 'add') {
  7161. $selectPrevious->setSelected($arrLP[$i]['id']);
  7162. }
  7163. }
  7164. }
  7165. if ($action != 'move') {
  7166. $arrHide = [];
  7167. for ($i = 0; $i < count($arrLP); $i++) {
  7168. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7169. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7170. }
  7171. }
  7172. }
  7173. if ($action == 'add') {
  7174. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7175. } else {
  7176. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7177. }
  7178. if ($action == 'move') {
  7179. $form->addHidden('title', $item_title);
  7180. $form->addHidden('description', $item_description);
  7181. }
  7182. if (is_numeric($extra_info)) {
  7183. $form->addHidden('path', $extra_info);
  7184. } elseif (is_array($extra_info)) {
  7185. $form->addHidden('path', $extra_info['path']);
  7186. }
  7187. $form->addHidden('type', TOOL_QUIZ);
  7188. $form->addHidden('post_time', time());
  7189. $form->setDefaults($defaults);
  7190. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7191. }
  7192. /**
  7193. * Addition of Hotpotatoes tests.
  7194. *
  7195. * @param string $action
  7196. * @param int $id Internal ID of the item
  7197. * @param string $extra_info
  7198. *
  7199. * @return string HTML structure to display the hotpotatoes addition formular
  7200. */
  7201. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7202. {
  7203. $course_id = api_get_course_int_id();
  7204. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7205. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7206. if ($id != 0 && is_array($extra_info)) {
  7207. $item_title = stripslashes($extra_info['title']);
  7208. $item_description = stripslashes($extra_info['description']);
  7209. } elseif (is_numeric($extra_info)) {
  7210. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7211. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7212. WHERE
  7213. c_id = ".$course_id." AND
  7214. path LIKE '".$uploadPath."/%/%htm%' AND
  7215. iid = ".(int) $extra_info."
  7216. ORDER BY iid ASC";
  7217. $res_hot = Database::query($sql);
  7218. $row = Database::fetch_array($res_hot);
  7219. $item_title = $row['title'];
  7220. $item_description = $row['description'];
  7221. if (!empty($row['comment'])) {
  7222. $item_title = $row['comment'];
  7223. }
  7224. } else {
  7225. $item_title = '';
  7226. $item_description = '';
  7227. }
  7228. if ($id != 0 && is_array($extra_info)) {
  7229. $parent = $extra_info['parent_item_id'];
  7230. } else {
  7231. $parent = 0;
  7232. }
  7233. $sql = "SELECT * FROM $tbl_lp_item
  7234. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7235. $result = Database::query($sql);
  7236. $arrLP = [];
  7237. while ($row = Database::fetch_array($result)) {
  7238. $arrLP[] = [
  7239. 'id' => $row['id'],
  7240. 'item_type' => $row['item_type'],
  7241. 'title' => $row['title'],
  7242. 'path' => $row['path'],
  7243. 'description' => $row['description'],
  7244. 'parent_item_id' => $row['parent_item_id'],
  7245. 'previous_item_id' => $row['previous_item_id'],
  7246. 'next_item_id' => $row['next_item_id'],
  7247. 'display_order' => $row['display_order'],
  7248. 'max_score' => $row['max_score'],
  7249. 'min_score' => $row['min_score'],
  7250. 'mastery_score' => $row['mastery_score'],
  7251. 'prerequisite' => $row['prerequisite'],
  7252. 'max_time_allowed' => $row['max_time_allowed'],
  7253. ];
  7254. }
  7255. $legend = '<legend>';
  7256. if ($action == 'add') {
  7257. $legend .= get_lang('CreateTheExercise');
  7258. } elseif ($action == 'move') {
  7259. $legend .= get_lang('MoveTheCurrentExercise');
  7260. } else {
  7261. $legend .= get_lang('EditCurrentExecice');
  7262. }
  7263. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7264. $legend .= Display:: return_message(
  7265. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7266. );
  7267. }
  7268. $legend .= '</legend>';
  7269. $return = '<form method="POST">';
  7270. $return .= $legend;
  7271. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7272. $return .= '<tr>';
  7273. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7274. $return .= '<td class="input">';
  7275. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7276. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7277. $arrHide = [
  7278. $id,
  7279. ];
  7280. if (count($arrLP) > 0) {
  7281. for ($i = 0; $i < count($arrLP); $i++) {
  7282. if ($action != 'add') {
  7283. if ($arrLP[$i]['item_type'] == 'dir' &&
  7284. !in_array($arrLP[$i]['id'], $arrHide) &&
  7285. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7286. ) {
  7287. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7288. } else {
  7289. $arrHide[] = $arrLP[$i]['id'];
  7290. }
  7291. } else {
  7292. if ($arrLP[$i]['item_type'] == 'dir') {
  7293. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7294. }
  7295. }
  7296. }
  7297. reset($arrLP);
  7298. }
  7299. $return .= '</select>';
  7300. $return .= '</td>';
  7301. $return .= '</tr>';
  7302. $return .= '<tr>';
  7303. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7304. $return .= '<td class="input">';
  7305. $return .= '<select id="previous" name="previous" size="1">';
  7306. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7307. for ($i = 0; $i < count($arrLP); $i++) {
  7308. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7309. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7310. $selected = 'selected="selected" ';
  7311. } elseif ($action == 'add') {
  7312. $selected = 'selected="selected" ';
  7313. } else {
  7314. $selected = '';
  7315. }
  7316. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7317. }
  7318. }
  7319. $return .= '</select>';
  7320. $return .= '</td>';
  7321. $return .= '</tr>';
  7322. if ($action != 'move') {
  7323. $return .= '<tr>';
  7324. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7325. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7326. $return .= '</tr>';
  7327. $id_prerequisite = 0;
  7328. if (is_array($arrLP) && count($arrLP) > 0) {
  7329. foreach ($arrLP as $key => $value) {
  7330. if ($value['id'] == $id) {
  7331. $id_prerequisite = $value['prerequisite'];
  7332. break;
  7333. }
  7334. }
  7335. $arrHide = [];
  7336. for ($i = 0; $i < count($arrLP); $i++) {
  7337. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7338. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7339. }
  7340. }
  7341. }
  7342. }
  7343. $return .= '<tr>';
  7344. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7345. get_lang('SaveHotpotatoes').'</button></td>';
  7346. $return .= '</tr>';
  7347. $return .= '</table>';
  7348. if ($action == 'move') {
  7349. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7350. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7351. }
  7352. if (is_numeric($extra_info)) {
  7353. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7354. } elseif (is_array($extra_info)) {
  7355. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7356. }
  7357. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7358. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7359. $return .= '</form>';
  7360. return $return;
  7361. }
  7362. /**
  7363. * Return the form to display the forum edit/add option.
  7364. *
  7365. * @param string $action
  7366. * @param int $id ID of the lp_item if already exists
  7367. * @param string $extra_info
  7368. *
  7369. * @throws Exception
  7370. *
  7371. * @return string HTML form
  7372. */
  7373. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7374. {
  7375. $course_id = api_get_course_int_id();
  7376. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7377. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7378. if ($id != 0 && is_array($extra_info)) {
  7379. $item_title = stripslashes($extra_info['title']);
  7380. } elseif (is_numeric($extra_info)) {
  7381. $sql = "SELECT forum_title as title, forum_comment as comment
  7382. FROM ".$tbl_forum."
  7383. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7384. $result = Database::query($sql);
  7385. $row = Database::fetch_array($result);
  7386. $item_title = $row['title'];
  7387. $item_description = $row['comment'];
  7388. } else {
  7389. $item_title = '';
  7390. $item_description = '';
  7391. }
  7392. if ($id != 0 && is_array($extra_info)) {
  7393. $parent = $extra_info['parent_item_id'];
  7394. } else {
  7395. $parent = 0;
  7396. }
  7397. $sql = "SELECT * FROM $tbl_lp_item
  7398. WHERE
  7399. c_id = $course_id AND
  7400. lp_id = ".$this->lp_id;
  7401. $result = Database::query($sql);
  7402. $arrLP = [];
  7403. while ($row = Database::fetch_array($result)) {
  7404. $arrLP[] = [
  7405. 'id' => $row['iid'],
  7406. 'item_type' => $row['item_type'],
  7407. 'title' => $row['title'],
  7408. 'path' => $row['path'],
  7409. 'description' => $row['description'],
  7410. 'parent_item_id' => $row['parent_item_id'],
  7411. 'previous_item_id' => $row['previous_item_id'],
  7412. 'next_item_id' => $row['next_item_id'],
  7413. 'display_order' => $row['display_order'],
  7414. 'max_score' => $row['max_score'],
  7415. 'min_score' => $row['min_score'],
  7416. 'mastery_score' => $row['mastery_score'],
  7417. 'prerequisite' => $row['prerequisite'],
  7418. ];
  7419. }
  7420. $this->tree_array($arrLP);
  7421. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7422. unset($this->arrMenu);
  7423. if ($action == 'add') {
  7424. $legend = get_lang('CreateTheForum');
  7425. } elseif ($action == 'move') {
  7426. $legend = get_lang('MoveTheCurrentForum');
  7427. } else {
  7428. $legend = get_lang('EditCurrentForum');
  7429. }
  7430. $form = new FormValidator(
  7431. 'forum_form',
  7432. 'POST',
  7433. $this->getCurrentBuildingModeURL()
  7434. );
  7435. $defaults = [];
  7436. $form->addHeader($legend);
  7437. if ($action != 'move') {
  7438. $form->addText(
  7439. 'title',
  7440. get_lang('Title'),
  7441. true,
  7442. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7443. );
  7444. $defaults['title'] = $item_title;
  7445. }
  7446. $selectParent = $form->addSelect(
  7447. 'parent',
  7448. get_lang('Parent'),
  7449. [],
  7450. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7451. );
  7452. $selectParent->addOption($this->name, 0);
  7453. $arrHide = [
  7454. $id,
  7455. ];
  7456. for ($i = 0; $i < count($arrLP); $i++) {
  7457. if ($action != 'add') {
  7458. if ($arrLP[$i]['item_type'] == 'dir' &&
  7459. !in_array($arrLP[$i]['id'], $arrHide) &&
  7460. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7461. ) {
  7462. $selectParent->addOption(
  7463. $arrLP[$i]['title'],
  7464. $arrLP[$i]['id'],
  7465. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7466. );
  7467. if ($parent == $arrLP[$i]['id']) {
  7468. $selectParent->setSelected($arrLP[$i]['id']);
  7469. }
  7470. } else {
  7471. $arrHide[] = $arrLP[$i]['id'];
  7472. }
  7473. } else {
  7474. if ($arrLP[$i]['item_type'] == 'dir') {
  7475. $selectParent->addOption(
  7476. $arrLP[$i]['title'],
  7477. $arrLP[$i]['id'],
  7478. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7479. );
  7480. if ($parent == $arrLP[$i]['id']) {
  7481. $selectParent->setSelected($arrLP[$i]['id']);
  7482. }
  7483. }
  7484. }
  7485. }
  7486. if (is_array($arrLP)) {
  7487. reset($arrLP);
  7488. }
  7489. $selectPrevious = $form->addSelect(
  7490. 'previous',
  7491. get_lang('Position'),
  7492. [],
  7493. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7494. );
  7495. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7496. for ($i = 0; $i < count($arrLP); $i++) {
  7497. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7498. $arrLP[$i]['id'] != $id
  7499. ) {
  7500. $selectPrevious->addOption(
  7501. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7502. $arrLP[$i]['id']
  7503. );
  7504. if (isset($extra_info['previous_item_id']) &&
  7505. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7506. ) {
  7507. $selectPrevious->setSelected($arrLP[$i]['id']);
  7508. } elseif ($action == 'add') {
  7509. $selectPrevious->setSelected($arrLP[$i]['id']);
  7510. }
  7511. }
  7512. }
  7513. if ($action != 'move') {
  7514. $id_prerequisite = 0;
  7515. if (is_array($arrLP)) {
  7516. foreach ($arrLP as $key => $value) {
  7517. if ($value['id'] == $id) {
  7518. $id_prerequisite = $value['prerequisite'];
  7519. break;
  7520. }
  7521. }
  7522. }
  7523. $arrHide = [];
  7524. for ($i = 0; $i < count($arrLP); $i++) {
  7525. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7526. if (isset($extra_info['previous_item_id']) &&
  7527. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7528. ) {
  7529. $s_selected_position = $arrLP[$i]['id'];
  7530. } elseif ($action == 'add') {
  7531. $s_selected_position = 0;
  7532. }
  7533. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7534. }
  7535. }
  7536. }
  7537. if ($action == 'add') {
  7538. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7539. } else {
  7540. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7541. }
  7542. if ($action == 'move') {
  7543. $form->addHidden('title', $item_title);
  7544. $form->addHidden('description', $item_description);
  7545. }
  7546. if (is_numeric($extra_info)) {
  7547. $form->addHidden('path', $extra_info);
  7548. } elseif (is_array($extra_info)) {
  7549. $form->addHidden('path', $extra_info['path']);
  7550. }
  7551. $form->addHidden('type', TOOL_FORUM);
  7552. $form->addHidden('post_time', time());
  7553. $form->setDefaults($defaults);
  7554. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7555. }
  7556. /**
  7557. * Return HTML form to add/edit forum threads.
  7558. *
  7559. * @param string $action
  7560. * @param int $id Item ID if already exists in learning path
  7561. * @param string $extra_info
  7562. *
  7563. * @throws Exception
  7564. *
  7565. * @return string HTML form
  7566. */
  7567. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7568. {
  7569. $course_id = api_get_course_int_id();
  7570. if (empty($course_id)) {
  7571. return null;
  7572. }
  7573. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7574. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7575. if ($id != 0 && is_array($extra_info)) {
  7576. $item_title = stripslashes($extra_info['title']);
  7577. } elseif (is_numeric($extra_info)) {
  7578. $sql = "SELECT thread_title as title FROM $tbl_forum
  7579. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7580. $result = Database::query($sql);
  7581. $row = Database::fetch_array($result);
  7582. $item_title = $row['title'];
  7583. $item_description = '';
  7584. } else {
  7585. $item_title = '';
  7586. $item_description = '';
  7587. }
  7588. if ($id != 0 && is_array($extra_info)) {
  7589. $parent = $extra_info['parent_item_id'];
  7590. } else {
  7591. $parent = 0;
  7592. }
  7593. $sql = "SELECT * FROM $tbl_lp_item
  7594. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7595. $result = Database::query($sql);
  7596. $arrLP = [];
  7597. while ($row = Database::fetch_array($result)) {
  7598. $arrLP[] = [
  7599. 'id' => $row['iid'],
  7600. 'item_type' => $row['item_type'],
  7601. 'title' => $row['title'],
  7602. 'path' => $row['path'],
  7603. 'description' => $row['description'],
  7604. 'parent_item_id' => $row['parent_item_id'],
  7605. 'previous_item_id' => $row['previous_item_id'],
  7606. 'next_item_id' => $row['next_item_id'],
  7607. 'display_order' => $row['display_order'],
  7608. 'max_score' => $row['max_score'],
  7609. 'min_score' => $row['min_score'],
  7610. 'mastery_score' => $row['mastery_score'],
  7611. 'prerequisite' => $row['prerequisite'],
  7612. ];
  7613. }
  7614. $this->tree_array($arrLP);
  7615. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7616. unset($this->arrMenu);
  7617. $form = new FormValidator(
  7618. 'thread_form',
  7619. 'POST',
  7620. $this->getCurrentBuildingModeURL()
  7621. );
  7622. $defaults = [];
  7623. if ($action == 'add') {
  7624. $legend = get_lang('CreateTheForum');
  7625. } elseif ($action == 'move') {
  7626. $legend = get_lang('MoveTheCurrentForum');
  7627. } else {
  7628. $legend = get_lang('EditCurrentForum');
  7629. }
  7630. $form->addHeader($legend);
  7631. $selectParent = $form->addSelect(
  7632. 'parent',
  7633. get_lang('Parent'),
  7634. [],
  7635. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7636. );
  7637. $selectParent->addOption($this->name, 0);
  7638. $arrHide = [
  7639. $id,
  7640. ];
  7641. for ($i = 0; $i < count($arrLP); $i++) {
  7642. if ($action != 'add') {
  7643. if (
  7644. ($arrLP[$i]['item_type'] == 'dir') &&
  7645. !in_array($arrLP[$i]['id'], $arrHide) &&
  7646. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7647. ) {
  7648. $selectParent->addOption(
  7649. $arrLP[$i]['title'],
  7650. $arrLP[$i]['id'],
  7651. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7652. );
  7653. if ($parent == $arrLP[$i]['id']) {
  7654. $selectParent->setSelected($arrLP[$i]['id']);
  7655. }
  7656. } else {
  7657. $arrHide[] = $arrLP[$i]['id'];
  7658. }
  7659. } else {
  7660. if ($arrLP[$i]['item_type'] == 'dir') {
  7661. $selectParent->addOption(
  7662. $arrLP[$i]['title'],
  7663. $arrLP[$i]['id'],
  7664. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7665. );
  7666. if ($parent == $arrLP[$i]['id']) {
  7667. $selectParent->setSelected($arrLP[$i]['id']);
  7668. }
  7669. }
  7670. }
  7671. }
  7672. if ($arrLP != null) {
  7673. reset($arrLP);
  7674. }
  7675. $selectPrevious = $form->addSelect(
  7676. 'previous',
  7677. get_lang('Position'),
  7678. [],
  7679. ['id' => 'previous']
  7680. );
  7681. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7682. for ($i = 0; $i < count($arrLP); $i++) {
  7683. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7684. $selectPrevious->addOption(
  7685. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7686. $arrLP[$i]['id']
  7687. );
  7688. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7689. $selectPrevious->setSelected($arrLP[$i]['id']);
  7690. } elseif ($action == 'add') {
  7691. $selectPrevious->setSelected($arrLP[$i]['id']);
  7692. }
  7693. }
  7694. }
  7695. if ($action != 'move') {
  7696. $form->addText(
  7697. 'title',
  7698. get_lang('Title'),
  7699. true,
  7700. ['id' => 'idTitle']
  7701. );
  7702. $defaults['title'] = $item_title;
  7703. $id_prerequisite = 0;
  7704. if ($arrLP != null) {
  7705. foreach ($arrLP as $key => $value) {
  7706. if ($value['id'] == $id) {
  7707. $id_prerequisite = $value['prerequisite'];
  7708. break;
  7709. }
  7710. }
  7711. }
  7712. $arrHide = [];
  7713. $s_selected_position = 0;
  7714. for ($i = 0; $i < count($arrLP); $i++) {
  7715. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7716. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7717. $s_selected_position = $arrLP[$i]['id'];
  7718. } elseif ($action == 'add') {
  7719. $s_selected_position = 0;
  7720. }
  7721. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7722. }
  7723. }
  7724. $selectPrerequisites = $form->addSelect(
  7725. 'prerequisites',
  7726. get_lang('LearnpathPrerequisites'),
  7727. [],
  7728. ['id' => 'prerequisites']
  7729. );
  7730. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7731. foreach ($arrHide as $key => $value) {
  7732. $selectPrerequisites->addOption($value['value'], $key);
  7733. if ($key == $s_selected_position && $action == 'add') {
  7734. $selectPrerequisites->setSelected($key);
  7735. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7736. $selectPrerequisites->setSelected($key);
  7737. }
  7738. }
  7739. }
  7740. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7741. if ($action == 'move') {
  7742. $form->addHidden('title', $item_title);
  7743. $form->addHidden('description', $item_description);
  7744. }
  7745. if (is_numeric($extra_info)) {
  7746. $form->addHidden('path', $extra_info);
  7747. } elseif (is_array($extra_info)) {
  7748. $form->addHidden('path', $extra_info['path']);
  7749. }
  7750. $form->addHidden('type', TOOL_THREAD);
  7751. $form->addHidden('post_time', time());
  7752. $form->setDefaults($defaults);
  7753. return $form->returnForm();
  7754. }
  7755. /**
  7756. * Return the HTML form to display an item (generally a dir item).
  7757. *
  7758. * @param string $item_type
  7759. * @param string $title
  7760. * @param string $action
  7761. * @param int $id
  7762. * @param string $extra_info
  7763. *
  7764. * @throws Exception
  7765. * @throws HTML_QuickForm_Error
  7766. *
  7767. * @return string HTML form
  7768. */
  7769. public function display_item_form(
  7770. $item_type,
  7771. $title = '',
  7772. $action = 'add_item',
  7773. $id = 0,
  7774. $extra_info = 'new'
  7775. ) {
  7776. $_course = api_get_course_info();
  7777. global $charset;
  7778. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7779. $item_title = '';
  7780. $item_description = '';
  7781. $item_path_fck = '';
  7782. if ($id != 0 && is_array($extra_info)) {
  7783. $item_title = $extra_info['title'];
  7784. $item_description = $extra_info['description'];
  7785. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7786. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7787. }
  7788. $parent = 0;
  7789. if ($id != 0 && is_array($extra_info)) {
  7790. $parent = $extra_info['parent_item_id'];
  7791. }
  7792. $id = (int) $id;
  7793. $sql = "SELECT * FROM $tbl_lp_item
  7794. WHERE
  7795. lp_id = ".$this->lp_id." AND
  7796. iid != $id";
  7797. if ($item_type == 'dir') {
  7798. $sql .= " AND parent_item_id = 0";
  7799. }
  7800. $result = Database::query($sql);
  7801. $arrLP = [];
  7802. while ($row = Database::fetch_array($result)) {
  7803. $arrLP[] = [
  7804. 'id' => $row['iid'],
  7805. 'item_type' => $row['item_type'],
  7806. 'title' => $row['title'],
  7807. 'path' => $row['path'],
  7808. 'description' => $row['description'],
  7809. 'parent_item_id' => $row['parent_item_id'],
  7810. 'previous_item_id' => $row['previous_item_id'],
  7811. 'next_item_id' => $row['next_item_id'],
  7812. 'max_score' => $row['max_score'],
  7813. 'min_score' => $row['min_score'],
  7814. 'mastery_score' => $row['mastery_score'],
  7815. 'prerequisite' => $row['prerequisite'],
  7816. 'display_order' => $row['display_order'],
  7817. ];
  7818. }
  7819. $this->tree_array($arrLP);
  7820. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7821. unset($this->arrMenu);
  7822. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7823. $form = new FormValidator('form', 'POST', $url);
  7824. $defaults['title'] = api_html_entity_decode(
  7825. $item_title,
  7826. ENT_QUOTES,
  7827. $charset
  7828. );
  7829. $defaults['description'] = $item_description;
  7830. $form->addHeader($title);
  7831. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7832. $arrHide[0]['padding'] = 20;
  7833. $charset = api_get_system_encoding();
  7834. for ($i = 0; $i < count($arrLP); $i++) {
  7835. if ($action != 'add') {
  7836. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7837. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7838. ) {
  7839. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7840. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7841. if ($parent == $arrLP[$i]['id']) {
  7842. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7843. }
  7844. }
  7845. } else {
  7846. if ($arrLP[$i]['item_type'] == 'dir') {
  7847. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7848. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7849. if ($parent == $arrLP[$i]['id']) {
  7850. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7851. }
  7852. }
  7853. }
  7854. }
  7855. if ($action != 'move') {
  7856. $form->addElement('text', 'title', get_lang('Title'));
  7857. $form->applyFilter('title', 'html_filter');
  7858. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7859. } else {
  7860. $form->addElement('hidden', 'title');
  7861. }
  7862. $parentSelect = $form->addElement(
  7863. 'select',
  7864. 'parent',
  7865. get_lang('Parent'),
  7866. '',
  7867. [
  7868. 'id' => 'idParent',
  7869. 'onchange' => "javascript: load_cbo(this.value);",
  7870. ]
  7871. );
  7872. foreach ($arrHide as $key => $value) {
  7873. $parentSelect->addOption(
  7874. $value['value'],
  7875. $key,
  7876. 'style="padding-left:'.$value['padding'].'px;"'
  7877. );
  7878. $lastPosition = $key;
  7879. }
  7880. if (!empty($s_selected_parent)) {
  7881. $parentSelect->setSelected($s_selected_parent);
  7882. }
  7883. if (is_array($arrLP)) {
  7884. reset($arrLP);
  7885. }
  7886. $arrHide = [];
  7887. // POSITION
  7888. for ($i = 0; $i < count($arrLP); $i++) {
  7889. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7890. //this is the same!
  7891. if (isset($extra_info['previous_item_id']) &&
  7892. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7893. ) {
  7894. $s_selected_position = $arrLP[$i]['id'];
  7895. } elseif ($action == 'add') {
  7896. $s_selected_position = $arrLP[$i]['id'];
  7897. }
  7898. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7899. }
  7900. }
  7901. $position = $form->addElement(
  7902. 'select',
  7903. 'previous',
  7904. get_lang('Position'),
  7905. '',
  7906. ['id' => 'previous']
  7907. );
  7908. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7909. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7910. $lastPosition = null;
  7911. foreach ($arrHide as $key => $value) {
  7912. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7913. $lastPosition = $key;
  7914. }
  7915. if (!empty($s_selected_position)) {
  7916. $position->setSelected($s_selected_position);
  7917. }
  7918. // When new chapter add at the end
  7919. if ($action == 'add_item') {
  7920. $position->setSelected($lastPosition);
  7921. }
  7922. if (is_array($arrLP)) {
  7923. reset($arrLP);
  7924. }
  7925. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7926. //fix in order to use the tab
  7927. if ($item_type == 'dir') {
  7928. $form->addElement('hidden', 'type', 'dir');
  7929. }
  7930. $extension = null;
  7931. if (!empty($item_path)) {
  7932. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7933. }
  7934. //assets can't be modified
  7935. //$item_type == 'asset' ||
  7936. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7937. if ($item_type == 'sco') {
  7938. $form->addElement(
  7939. 'html',
  7940. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7941. );
  7942. }
  7943. $renderer = $form->defaultRenderer();
  7944. $renderer->setElementTemplate(
  7945. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7946. 'content_lp'
  7947. );
  7948. $relative_prefix = '';
  7949. $editor_config = [
  7950. 'ToolbarSet' => 'LearningPathDocuments',
  7951. 'Width' => '100%',
  7952. 'Height' => '500',
  7953. 'FullPage' => true,
  7954. 'CreateDocumentDir' => $relative_prefix,
  7955. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7956. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7957. ];
  7958. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7959. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7960. $defaults['content_lp'] = file_get_contents($content_path);
  7961. }
  7962. if (!empty($id)) {
  7963. $form->addHidden('id', $id);
  7964. }
  7965. $form->addElement('hidden', 'type', $item_type);
  7966. $form->addElement('hidden', 'post_time', time());
  7967. $form->setDefaults($defaults);
  7968. return $form->returnForm();
  7969. }
  7970. /**
  7971. * @return string
  7972. */
  7973. public function getCurrentBuildingModeURL()
  7974. {
  7975. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7976. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7977. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7978. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7979. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7980. return $currentUrl;
  7981. }
  7982. /**
  7983. * Returns the form to update or create a document.
  7984. *
  7985. * @param string $action (add/edit)
  7986. * @param int $id ID of the lp_item (if already exists)
  7987. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7988. *
  7989. * @throws Exception
  7990. * @throws HTML_QuickForm_Error
  7991. *
  7992. * @return string HTML form
  7993. */
  7994. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7995. {
  7996. $course_id = api_get_course_int_id();
  7997. $_course = api_get_course_info();
  7998. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7999. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8000. $no_display_edit_textarea = false;
  8001. $item_description = '';
  8002. //If action==edit document
  8003. //We don't display the document form if it's not an editable document (html or txt file)
  8004. if ($action == 'edit') {
  8005. if (is_array($extra_info)) {
  8006. $path_parts = pathinfo($extra_info['dir']);
  8007. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8008. $no_display_edit_textarea = true;
  8009. }
  8010. }
  8011. }
  8012. $no_display_add = false;
  8013. // If action==add an existing document
  8014. // We don't display the document form if it's not an editable document (html or txt file).
  8015. if ($action == 'add') {
  8016. if (is_numeric($extra_info)) {
  8017. $extra_info = (int) $extra_info;
  8018. $sql_doc = "SELECT path FROM $tbl_doc
  8019. WHERE c_id = $course_id AND iid = ".$extra_info;
  8020. $result = Database::query($sql_doc);
  8021. $path_file = Database::result($result, 0, 0);
  8022. $path_parts = pathinfo($path_file);
  8023. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8024. $no_display_add = true;
  8025. }
  8026. }
  8027. }
  8028. if ($id != 0 && is_array($extra_info)) {
  8029. $item_title = stripslashes($extra_info['title']);
  8030. $item_description = stripslashes($extra_info['description']);
  8031. if (empty($item_title)) {
  8032. $path_parts = pathinfo($extra_info['path']);
  8033. $item_title = stripslashes($path_parts['filename']);
  8034. }
  8035. } elseif (is_numeric($extra_info)) {
  8036. $sql = "SELECT path, title FROM $tbl_doc
  8037. WHERE
  8038. c_id = ".$course_id." AND
  8039. iid = ".intval($extra_info);
  8040. $result = Database::query($sql);
  8041. $row = Database::fetch_array($result);
  8042. $item_title = $row['title'];
  8043. $item_title = str_replace('_', ' ', $item_title);
  8044. if (empty($item_title)) {
  8045. $path_parts = pathinfo($row['path']);
  8046. $item_title = stripslashes($path_parts['filename']);
  8047. }
  8048. } else {
  8049. $item_title = '';
  8050. $item_description = '';
  8051. }
  8052. $return = '<legend>';
  8053. $parent = 0;
  8054. if ($id != 0 && is_array($extra_info)) {
  8055. $parent = $extra_info['parent_item_id'];
  8056. }
  8057. $sql = "SELECT * FROM $tbl_lp_item
  8058. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8059. $result = Database::query($sql);
  8060. $arrLP = [];
  8061. while ($row = Database::fetch_array($result)) {
  8062. $arrLP[] = [
  8063. 'id' => $row['iid'],
  8064. 'item_type' => $row['item_type'],
  8065. 'title' => $row['title'],
  8066. 'path' => $row['path'],
  8067. 'description' => $row['description'],
  8068. 'parent_item_id' => $row['parent_item_id'],
  8069. 'previous_item_id' => $row['previous_item_id'],
  8070. 'next_item_id' => $row['next_item_id'],
  8071. 'display_order' => $row['display_order'],
  8072. 'max_score' => $row['max_score'],
  8073. 'min_score' => $row['min_score'],
  8074. 'mastery_score' => $row['mastery_score'],
  8075. 'prerequisite' => $row['prerequisite'],
  8076. ];
  8077. }
  8078. $this->tree_array($arrLP);
  8079. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8080. unset($this->arrMenu);
  8081. if ($action == 'add') {
  8082. $return .= get_lang('CreateTheDocument');
  8083. } elseif ($action == 'move') {
  8084. $return .= get_lang('MoveTheCurrentDocument');
  8085. } else {
  8086. $return .= get_lang('EditTheCurrentDocument');
  8087. }
  8088. $return .= '</legend>';
  8089. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8090. $return .= Display::return_message(
  8091. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8092. false
  8093. );
  8094. }
  8095. $form = new FormValidator(
  8096. 'form',
  8097. 'POST',
  8098. $this->getCurrentBuildingModeURL(),
  8099. '',
  8100. ['enctype' => 'multipart/form-data']
  8101. );
  8102. $defaults['title'] = Security::remove_XSS($item_title);
  8103. if (empty($item_title)) {
  8104. $defaults['title'] = Security::remove_XSS($item_title);
  8105. }
  8106. $defaults['description'] = $item_description;
  8107. $form->addElement('html', $return);
  8108. if ($action != 'move') {
  8109. $data = $this->generate_lp_folder($_course);
  8110. if ($action != 'edit') {
  8111. $folders = DocumentManager::get_all_document_folders(
  8112. $_course,
  8113. 0,
  8114. true
  8115. );
  8116. DocumentManager::build_directory_selector(
  8117. $folders,
  8118. '',
  8119. [],
  8120. true,
  8121. $form,
  8122. 'directory_parent_id'
  8123. );
  8124. }
  8125. if (isset($data['id'])) {
  8126. $defaults['directory_parent_id'] = $data['id'];
  8127. }
  8128. $form->addElement(
  8129. 'text',
  8130. 'title',
  8131. get_lang('Title'),
  8132. ['id' => 'idTitle', 'class' => 'col-md-4']
  8133. );
  8134. $form->applyFilter('title', 'html_filter');
  8135. }
  8136. $arrHide[0]['value'] = $this->name;
  8137. $arrHide[0]['padding'] = 20;
  8138. for ($i = 0; $i < count($arrLP); $i++) {
  8139. if ($action != 'add') {
  8140. if ($arrLP[$i]['item_type'] == 'dir' &&
  8141. !in_array($arrLP[$i]['id'], $arrHide) &&
  8142. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8143. ) {
  8144. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8145. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8146. }
  8147. } else {
  8148. if ($arrLP[$i]['item_type'] == 'dir') {
  8149. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8150. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8151. }
  8152. }
  8153. }
  8154. $parentSelect = $form->addSelect(
  8155. 'parent',
  8156. get_lang('Parent'),
  8157. [],
  8158. [
  8159. 'id' => 'idParent',
  8160. 'onchange' => 'javascript: load_cbo(this.value);',
  8161. ]
  8162. );
  8163. $my_count = 0;
  8164. foreach ($arrHide as $key => $value) {
  8165. if ($my_count != 0) {
  8166. // The LP name is also the first section and is not in the same charset like the other sections.
  8167. $value['value'] = Security::remove_XSS($value['value']);
  8168. $parentSelect->addOption(
  8169. $value['value'],
  8170. $key,
  8171. 'style="padding-left:'.$value['padding'].'px;"'
  8172. );
  8173. } else {
  8174. $value['value'] = Security::remove_XSS($value['value']);
  8175. $parentSelect->addOption(
  8176. $value['value'],
  8177. $key,
  8178. 'style="padding-left:'.$value['padding'].'px;"'
  8179. );
  8180. }
  8181. $my_count++;
  8182. }
  8183. if (!empty($id)) {
  8184. $parentSelect->setSelected($parent);
  8185. } else {
  8186. $parent_item_id = Session::read('parent_item_id', 0);
  8187. $parentSelect->setSelected($parent_item_id);
  8188. }
  8189. if (is_array($arrLP)) {
  8190. reset($arrLP);
  8191. }
  8192. $arrHide = [];
  8193. // POSITION
  8194. for ($i = 0; $i < count($arrLP); $i++) {
  8195. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8196. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8197. ) {
  8198. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8199. }
  8200. }
  8201. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8202. $position = $form->addSelect(
  8203. 'previous',
  8204. get_lang('Position'),
  8205. [],
  8206. ['id' => 'previous']
  8207. );
  8208. $position->addOption(get_lang('FirstPosition'), 0);
  8209. foreach ($arrHide as $key => $value) {
  8210. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8211. $position->addOption(
  8212. $value['value'],
  8213. $key,
  8214. 'style="padding-left:'.$padding.'px;"'
  8215. );
  8216. }
  8217. $position->setSelected($selectedPosition);
  8218. if (is_array($arrLP)) {
  8219. reset($arrLP);
  8220. }
  8221. if ($action != 'move') {
  8222. $arrHide = [];
  8223. for ($i = 0; $i < count($arrLP); $i++) {
  8224. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8225. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8226. ) {
  8227. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8228. }
  8229. }
  8230. if (!$no_display_add) {
  8231. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8232. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8233. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8234. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8235. ) {
  8236. if (isset($_POST['content'])) {
  8237. $content = stripslashes($_POST['content']);
  8238. } elseif (is_array($extra_info)) {
  8239. //If it's an html document or a text file
  8240. if (!$no_display_edit_textarea) {
  8241. $content = $this->display_document(
  8242. $extra_info['path'],
  8243. false,
  8244. false
  8245. );
  8246. }
  8247. } elseif (is_numeric($extra_info)) {
  8248. $content = $this->display_document(
  8249. $extra_info,
  8250. false,
  8251. false
  8252. );
  8253. } else {
  8254. $content = '';
  8255. }
  8256. if (!$no_display_edit_textarea) {
  8257. // We need to calculate here some specific settings for the online editor.
  8258. // The calculated settings work for documents in the Documents tool
  8259. // (on the root or in subfolders).
  8260. // For documents in native scorm packages it is unclear whether the
  8261. // online editor should be activated or not.
  8262. // A new document, it is in the root of the repository.
  8263. $relative_path = '';
  8264. $relative_prefix = '';
  8265. if (is_array($extra_info) && $extra_info != 'new') {
  8266. // The document already exists. Whe have to determine its relative path towards the repository root.
  8267. $relative_path = explode('/', $extra_info['dir']);
  8268. $cnt = count($relative_path) - 2;
  8269. if ($cnt < 0) {
  8270. $cnt = 0;
  8271. }
  8272. $relative_prefix = str_repeat('../', $cnt);
  8273. $relative_path = array_slice($relative_path, 1, $cnt);
  8274. $relative_path = implode('/', $relative_path);
  8275. if (strlen($relative_path) > 0) {
  8276. $relative_path = $relative_path.'/';
  8277. }
  8278. } else {
  8279. $result = $this->generate_lp_folder($_course);
  8280. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8281. $relative_prefix = '../../';
  8282. }
  8283. $editor_config = [
  8284. 'ToolbarSet' => 'LearningPathDocuments',
  8285. 'Width' => '100%',
  8286. 'Height' => '500',
  8287. 'FullPage' => true,
  8288. 'CreateDocumentDir' => $relative_prefix,
  8289. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8290. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8291. ];
  8292. if ($_GET['action'] == 'add_item') {
  8293. $class = 'add';
  8294. $text = get_lang('LPCreateDocument');
  8295. } else {
  8296. if ($_GET['action'] == 'edit_item') {
  8297. $class = 'save';
  8298. $text = get_lang('SaveDocument');
  8299. }
  8300. }
  8301. $form->addButtonSave($text, 'submit_button');
  8302. $renderer = $form->defaultRenderer();
  8303. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8304. $form->addElement('html', '<div class="editor-lp">');
  8305. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8306. $form->addElement('html', '</div>');
  8307. $defaults['content_lp'] = $content;
  8308. }
  8309. } elseif (is_numeric($extra_info)) {
  8310. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8311. $return = $this->display_document($extra_info, true, true, true);
  8312. $form->addElement('html', $return);
  8313. }
  8314. }
  8315. }
  8316. if (isset($extra_info['item_type']) &&
  8317. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8318. ) {
  8319. $parentSelect->freeze();
  8320. $position->freeze();
  8321. }
  8322. if ($action == 'move') {
  8323. $form->addElement('hidden', 'title', $item_title);
  8324. $form->addElement('hidden', 'description', $item_description);
  8325. }
  8326. if (is_numeric($extra_info)) {
  8327. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8328. $form->addElement('hidden', 'path', $extra_info);
  8329. } elseif (is_array($extra_info)) {
  8330. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8331. $form->addElement('hidden', 'path', $extra_info['path']);
  8332. }
  8333. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8334. $form->addElement('hidden', 'post_time', time());
  8335. $form->setDefaults($defaults);
  8336. return $form->returnForm();
  8337. }
  8338. /**
  8339. * Returns the form to update or create a read-out text.
  8340. *
  8341. * @param string $action "add" or "edit"
  8342. * @param int $id ID of the lp_item (if already exists)
  8343. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8344. *
  8345. * @throws Exception
  8346. * @throws HTML_QuickForm_Error
  8347. *
  8348. * @return string HTML form
  8349. */
  8350. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8351. {
  8352. $course_id = api_get_course_int_id();
  8353. $_course = api_get_course_info();
  8354. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8355. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8356. $no_display_edit_textarea = false;
  8357. $item_description = '';
  8358. //If action==edit document
  8359. //We don't display the document form if it's not an editable document (html or txt file)
  8360. if ($action == 'edit') {
  8361. if (is_array($extra_info)) {
  8362. $path_parts = pathinfo($extra_info['dir']);
  8363. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8364. $no_display_edit_textarea = true;
  8365. }
  8366. }
  8367. }
  8368. $no_display_add = false;
  8369. if ($id != 0 && is_array($extra_info)) {
  8370. $item_title = stripslashes($extra_info['title']);
  8371. $item_description = stripslashes($extra_info['description']);
  8372. $item_terms = stripslashes($extra_info['terms']);
  8373. if (empty($item_title)) {
  8374. $path_parts = pathinfo($extra_info['path']);
  8375. $item_title = stripslashes($path_parts['filename']);
  8376. }
  8377. } elseif (is_numeric($extra_info)) {
  8378. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8379. $result = Database::query($sql);
  8380. $row = Database::fetch_array($result);
  8381. $item_title = $row['title'];
  8382. $item_title = str_replace('_', ' ', $item_title);
  8383. if (empty($item_title)) {
  8384. $path_parts = pathinfo($row['path']);
  8385. $item_title = stripslashes($path_parts['filename']);
  8386. }
  8387. } else {
  8388. $item_title = '';
  8389. $item_description = '';
  8390. }
  8391. if ($id != 0 && is_array($extra_info)) {
  8392. $parent = $extra_info['parent_item_id'];
  8393. } else {
  8394. $parent = 0;
  8395. }
  8396. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8397. $result = Database::query($sql);
  8398. $arrLP = [];
  8399. while ($row = Database::fetch_array($result)) {
  8400. $arrLP[] = [
  8401. 'id' => $row['iid'],
  8402. 'item_type' => $row['item_type'],
  8403. 'title' => $row['title'],
  8404. 'path' => $row['path'],
  8405. 'description' => $row['description'],
  8406. 'parent_item_id' => $row['parent_item_id'],
  8407. 'previous_item_id' => $row['previous_item_id'],
  8408. 'next_item_id' => $row['next_item_id'],
  8409. 'display_order' => $row['display_order'],
  8410. 'max_score' => $row['max_score'],
  8411. 'min_score' => $row['min_score'],
  8412. 'mastery_score' => $row['mastery_score'],
  8413. 'prerequisite' => $row['prerequisite'],
  8414. ];
  8415. }
  8416. $this->tree_array($arrLP);
  8417. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8418. unset($this->arrMenu);
  8419. if ($action == 'add') {
  8420. $formHeader = get_lang('CreateTheDocument');
  8421. } else {
  8422. $formHeader = get_lang('EditTheCurrentDocument');
  8423. }
  8424. if ('edit' === $action) {
  8425. $urlAudioIcon = Display::url(
  8426. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8427. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8428. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8429. );
  8430. } else {
  8431. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8432. }
  8433. $form = new FormValidator(
  8434. 'frm_add_reading',
  8435. 'POST',
  8436. $this->getCurrentBuildingModeURL(),
  8437. '',
  8438. ['enctype' => 'multipart/form-data']
  8439. );
  8440. $form->addHeader($formHeader);
  8441. $form->addHtml(
  8442. Display::return_message(
  8443. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8444. 'normal',
  8445. false
  8446. )
  8447. );
  8448. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8449. $defaults['description'] = $item_description;
  8450. $data = $this->generate_lp_folder($_course);
  8451. if ($action != 'edit') {
  8452. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8453. DocumentManager::build_directory_selector(
  8454. $folders,
  8455. '',
  8456. [],
  8457. true,
  8458. $form,
  8459. 'directory_parent_id'
  8460. );
  8461. }
  8462. if (isset($data['id'])) {
  8463. $defaults['directory_parent_id'] = $data['id'];
  8464. }
  8465. $form->addElement(
  8466. 'text',
  8467. 'title',
  8468. get_lang('Title')
  8469. );
  8470. $form->applyFilter('title', 'trim');
  8471. $form->applyFilter('title', 'html_filter');
  8472. $arrHide[0]['value'] = $this->name;
  8473. $arrHide[0]['padding'] = 20;
  8474. for ($i = 0; $i < count($arrLP); $i++) {
  8475. if ($action != 'add') {
  8476. if ($arrLP[$i]['item_type'] == 'dir' &&
  8477. !in_array($arrLP[$i]['id'], $arrHide) &&
  8478. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8479. ) {
  8480. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8481. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8482. }
  8483. } else {
  8484. if ($arrLP[$i]['item_type'] == 'dir') {
  8485. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8486. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8487. }
  8488. }
  8489. }
  8490. $parent_select = $form->addSelect(
  8491. 'parent',
  8492. get_lang('Parent'),
  8493. [],
  8494. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8495. );
  8496. $my_count = 0;
  8497. foreach ($arrHide as $key => $value) {
  8498. if ($my_count != 0) {
  8499. // The LP name is also the first section and is not in the same charset like the other sections.
  8500. $value['value'] = Security::remove_XSS($value['value']);
  8501. $parent_select->addOption(
  8502. $value['value'],
  8503. $key,
  8504. 'style="padding-left:'.$value['padding'].'px;"'
  8505. );
  8506. } else {
  8507. $value['value'] = Security::remove_XSS($value['value']);
  8508. $parent_select->addOption(
  8509. $value['value'],
  8510. $key,
  8511. 'style="padding-left:'.$value['padding'].'px;"'
  8512. );
  8513. }
  8514. $my_count++;
  8515. }
  8516. if (!empty($id)) {
  8517. $parent_select->setSelected($parent);
  8518. } else {
  8519. $parent_item_id = Session::read('parent_item_id', 0);
  8520. $parent_select->setSelected($parent_item_id);
  8521. }
  8522. if (is_array($arrLP)) {
  8523. reset($arrLP);
  8524. }
  8525. $arrHide = [];
  8526. $s_selected_position = null;
  8527. // POSITION
  8528. $lastPosition = null;
  8529. for ($i = 0; $i < count($arrLP); $i++) {
  8530. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8531. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8532. ) {
  8533. if ((isset($extra_info['previous_item_id']) &&
  8534. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8535. ) {
  8536. $s_selected_position = $arrLP[$i]['id'];
  8537. }
  8538. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8539. }
  8540. $lastPosition = $arrLP[$i]['id'];
  8541. }
  8542. if (empty($s_selected_position)) {
  8543. $s_selected_position = $lastPosition;
  8544. }
  8545. $position = $form->addSelect(
  8546. 'previous',
  8547. get_lang('Position'),
  8548. []
  8549. );
  8550. $position->addOption(get_lang('FirstPosition'), 0);
  8551. foreach ($arrHide as $key => $value) {
  8552. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8553. $position->addOption(
  8554. $value['value'],
  8555. $key,
  8556. 'style="padding-left:'.$padding.'px;"'
  8557. );
  8558. }
  8559. $position->setSelected($s_selected_position);
  8560. if (is_array($arrLP)) {
  8561. reset($arrLP);
  8562. }
  8563. $arrHide = [];
  8564. for ($i = 0; $i < count($arrLP); $i++) {
  8565. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8566. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8567. ) {
  8568. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8569. }
  8570. }
  8571. if (!$no_display_add) {
  8572. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8573. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8574. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8575. if (!$no_display_edit_textarea) {
  8576. $content = '';
  8577. if (isset($_POST['content'])) {
  8578. $content = stripslashes($_POST['content']);
  8579. } elseif (is_array($extra_info)) {
  8580. $content = $this->display_document($extra_info['path'], false, false);
  8581. } elseif (is_numeric($extra_info)) {
  8582. $content = $this->display_document($extra_info, false, false);
  8583. }
  8584. // A new document, it is in the root of the repository.
  8585. if (is_array($extra_info) && $extra_info != 'new') {
  8586. } else {
  8587. $this->generate_lp_folder($_course);
  8588. }
  8589. if ($_GET['action'] == 'add_item') {
  8590. $text = get_lang('LPCreateDocument');
  8591. } else {
  8592. $text = get_lang('SaveDocument');
  8593. }
  8594. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8595. $form
  8596. ->defaultRenderer()
  8597. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8598. $form->addButtonSave($text, 'submit_button');
  8599. $defaults['content_lp'] = $content;
  8600. }
  8601. } elseif (is_numeric($extra_info)) {
  8602. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8603. $return = $this->display_document($extra_info, true, true, true);
  8604. $form->addElement('html', $return);
  8605. }
  8606. }
  8607. if (is_numeric($extra_info)) {
  8608. $form->addElement('hidden', 'path', $extra_info);
  8609. } elseif (is_array($extra_info)) {
  8610. $form->addElement('hidden', 'path', $extra_info['path']);
  8611. }
  8612. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8613. $form->addElement('hidden', 'post_time', time());
  8614. $form->setDefaults($defaults);
  8615. return $form->returnForm();
  8616. }
  8617. /**
  8618. * @param array $courseInfo
  8619. * @param string $content
  8620. * @param string $title
  8621. * @param int $parentId
  8622. *
  8623. * @throws \Doctrine\ORM\ORMException
  8624. * @throws \Doctrine\ORM\OptimisticLockException
  8625. * @throws \Doctrine\ORM\TransactionRequiredException
  8626. *
  8627. * @return int
  8628. */
  8629. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8630. {
  8631. $creatorId = api_get_user_id();
  8632. $sessionId = api_get_session_id();
  8633. // Generates folder
  8634. $result = $this->generate_lp_folder($courseInfo);
  8635. $dir = $result['dir'];
  8636. if (empty($parentId) || $parentId == '/') {
  8637. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8638. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8639. if ($parentId === '/') {
  8640. $dir = '/';
  8641. }
  8642. // Please, do not modify this dirname formatting.
  8643. if (strstr($dir, '..')) {
  8644. $dir = '/';
  8645. }
  8646. if (!empty($dir[0]) && $dir[0] == '.') {
  8647. $dir = substr($dir, 1);
  8648. }
  8649. if (!empty($dir[0]) && $dir[0] != '/') {
  8650. $dir = '/'.$dir;
  8651. }
  8652. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8653. $dir .= '/';
  8654. }
  8655. } else {
  8656. $parentInfo = DocumentManager::get_document_data_by_id(
  8657. $parentId,
  8658. $courseInfo['code']
  8659. );
  8660. if (!empty($parentInfo)) {
  8661. $dir = $parentInfo['path'].'/';
  8662. }
  8663. }
  8664. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8665. if (!is_dir($filepath)) {
  8666. $dir = '/';
  8667. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8668. }
  8669. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8670. if (!empty($title)) {
  8671. $title = api_replace_dangerous_char(stripslashes($title));
  8672. } else {
  8673. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8674. }
  8675. $title = disable_dangerous_file($title);
  8676. $filename = $title;
  8677. $content = !empty($content) ? $content : $_POST['content_lp'];
  8678. $tmpFileName = $filename;
  8679. $i = 0;
  8680. while (file_exists($filepath.$tmpFileName.'.html')) {
  8681. $tmpFileName = $filename.'_'.++$i;
  8682. }
  8683. $filename = $tmpFileName.'.html';
  8684. $content = stripslashes($content);
  8685. if (file_exists($filepath.$filename)) {
  8686. return 0;
  8687. }
  8688. $putContent = file_put_contents($filepath.$filename, $content);
  8689. if ($putContent === false) {
  8690. return 0;
  8691. }
  8692. $fileSize = filesize($filepath.$filename);
  8693. $saveFilePath = $dir.$filename;
  8694. $documentId = add_document(
  8695. $courseInfo,
  8696. $saveFilePath,
  8697. 'file',
  8698. $fileSize,
  8699. $tmpFileName,
  8700. '',
  8701. 0, //readonly
  8702. true,
  8703. null,
  8704. $sessionId,
  8705. $creatorId
  8706. );
  8707. if (!$documentId) {
  8708. return 0;
  8709. }
  8710. api_item_property_update(
  8711. $courseInfo,
  8712. TOOL_DOCUMENT,
  8713. $documentId,
  8714. 'DocumentAdded',
  8715. $creatorId,
  8716. null,
  8717. null,
  8718. null,
  8719. null,
  8720. $sessionId
  8721. );
  8722. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8723. $newTitle = $originalTitle;
  8724. if ($newComment || $newTitle) {
  8725. $em = Database::getManager();
  8726. /** @var CDocument $doc */
  8727. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8728. if ($newComment) {
  8729. $doc->setComment($newComment);
  8730. }
  8731. if ($newTitle) {
  8732. $doc->setTitle($newTitle);
  8733. }
  8734. $em->persist($doc);
  8735. $em->flush();
  8736. }
  8737. return $documentId;
  8738. }
  8739. /**
  8740. * Return HTML form to add/edit a link item.
  8741. *
  8742. * @param string $action (add/edit)
  8743. * @param int $id Item ID if exists
  8744. * @param mixed $extra_info
  8745. *
  8746. * @throws Exception
  8747. * @throws HTML_QuickForm_Error
  8748. *
  8749. * @return string HTML form
  8750. */
  8751. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8752. {
  8753. $course_id = api_get_course_int_id();
  8754. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8755. $tbl_link = Database::get_course_table(TABLE_LINK);
  8756. if ($id != 0 && is_array($extra_info)) {
  8757. $item_title = stripslashes($extra_info['title']);
  8758. $item_description = stripslashes($extra_info['description']);
  8759. $item_url = stripslashes($extra_info['url']);
  8760. } elseif (is_numeric($extra_info)) {
  8761. $extra_info = intval($extra_info);
  8762. $sql = "SELECT title, description, url FROM ".$tbl_link."
  8763. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  8764. $result = Database::query($sql);
  8765. $row = Database::fetch_array($result);
  8766. $item_title = $row['title'];
  8767. $item_description = $row['description'];
  8768. $item_url = $row['url'];
  8769. } else {
  8770. $item_title = '';
  8771. $item_description = '';
  8772. $item_url = '';
  8773. }
  8774. $form = new FormValidator(
  8775. 'edit_link',
  8776. 'POST',
  8777. $this->getCurrentBuildingModeURL()
  8778. );
  8779. $defaults = [];
  8780. if ($id != 0 && is_array($extra_info)) {
  8781. $parent = $extra_info['parent_item_id'];
  8782. } else {
  8783. $parent = 0;
  8784. }
  8785. $sql = "SELECT * FROM $tbl_lp_item
  8786. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8787. $result = Database::query($sql);
  8788. $arrLP = [];
  8789. while ($row = Database::fetch_array($result)) {
  8790. $arrLP[] = [
  8791. 'id' => $row['id'],
  8792. 'item_type' => $row['item_type'],
  8793. 'title' => $row['title'],
  8794. 'path' => $row['path'],
  8795. 'description' => $row['description'],
  8796. 'parent_item_id' => $row['parent_item_id'],
  8797. 'previous_item_id' => $row['previous_item_id'],
  8798. 'next_item_id' => $row['next_item_id'],
  8799. 'display_order' => $row['display_order'],
  8800. 'max_score' => $row['max_score'],
  8801. 'min_score' => $row['min_score'],
  8802. 'mastery_score' => $row['mastery_score'],
  8803. 'prerequisite' => $row['prerequisite'],
  8804. ];
  8805. }
  8806. $this->tree_array($arrLP);
  8807. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8808. unset($this->arrMenu);
  8809. if ($action == 'add') {
  8810. $legend = get_lang('CreateTheLink');
  8811. } elseif ($action == 'move') {
  8812. $legend = get_lang('MoveCurrentLink');
  8813. } else {
  8814. $legend = get_lang('EditCurrentLink');
  8815. }
  8816. $form->addHeader($legend);
  8817. if ($action != 'move') {
  8818. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8819. $defaults['title'] = $item_title;
  8820. }
  8821. $selectParent = $form->addSelect(
  8822. 'parent',
  8823. get_lang('Parent'),
  8824. [],
  8825. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8826. );
  8827. $selectParent->addOption($this->name, 0);
  8828. $arrHide = [
  8829. $id,
  8830. ];
  8831. $parent_item_id = Session::read('parent_item_id', 0);
  8832. for ($i = 0; $i < count($arrLP); $i++) {
  8833. if ($action != 'add') {
  8834. if (
  8835. ($arrLP[$i]['item_type'] == 'dir') &&
  8836. !in_array($arrLP[$i]['id'], $arrHide) &&
  8837. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8838. ) {
  8839. $selectParent->addOption(
  8840. $arrLP[$i]['title'],
  8841. $arrLP[$i]['id'],
  8842. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8843. );
  8844. if ($parent == $arrLP[$i]['id']) {
  8845. $selectParent->setSelected($arrLP[$i]['id']);
  8846. }
  8847. } else {
  8848. $arrHide[] = $arrLP[$i]['id'];
  8849. }
  8850. } else {
  8851. if ($arrLP[$i]['item_type'] == 'dir') {
  8852. $selectParent->addOption(
  8853. $arrLP[$i]['title'],
  8854. $arrLP[$i]['id'],
  8855. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8856. );
  8857. if ($parent_item_id == $arrLP[$i]['id']) {
  8858. $selectParent->setSelected($arrLP[$i]['id']);
  8859. }
  8860. }
  8861. }
  8862. }
  8863. if (is_array($arrLP)) {
  8864. reset($arrLP);
  8865. }
  8866. $selectPrevious = $form->addSelect(
  8867. 'previous',
  8868. get_lang('Position'),
  8869. [],
  8870. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8871. );
  8872. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8873. for ($i = 0; $i < count($arrLP); $i++) {
  8874. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8875. $selectPrevious->addOption(
  8876. $arrLP[$i]['title'],
  8877. $arrLP[$i]['id']
  8878. );
  8879. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8880. $selectPrevious->setSelected($arrLP[$i]['id']);
  8881. } elseif ($action == 'add') {
  8882. $selectPrevious->setSelected($arrLP[$i]['id']);
  8883. }
  8884. }
  8885. }
  8886. if ($action != 'move') {
  8887. $urlAttributes = ['class' => 'learnpath_item_form'];
  8888. if (is_numeric($extra_info)) {
  8889. $urlAttributes['disabled'] = 'disabled';
  8890. }
  8891. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8892. $defaults['url'] = $item_url;
  8893. $arrHide = [];
  8894. for ($i = 0; $i < count($arrLP); $i++) {
  8895. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8896. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8897. }
  8898. }
  8899. }
  8900. if ($action == 'add') {
  8901. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8902. } else {
  8903. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8904. }
  8905. if ($action == 'move') {
  8906. $form->addHidden('title', $item_title);
  8907. $form->addHidden('description', $item_description);
  8908. }
  8909. if (is_numeric($extra_info)) {
  8910. $form->addHidden('path', $extra_info);
  8911. } elseif (is_array($extra_info)) {
  8912. $form->addHidden('path', $extra_info['path']);
  8913. }
  8914. $form->addHidden('type', TOOL_LINK);
  8915. $form->addHidden('post_time', time());
  8916. $form->setDefaults($defaults);
  8917. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8918. }
  8919. /**
  8920. * Return HTML form to add/edit a student publication (work).
  8921. *
  8922. * @param string $action
  8923. * @param int $id Item ID if already exists
  8924. * @param string $extra_info
  8925. *
  8926. * @throws Exception
  8927. *
  8928. * @return string HTML form
  8929. */
  8930. public function display_student_publication_form(
  8931. $action = 'add',
  8932. $id = 0,
  8933. $extra_info = ''
  8934. ) {
  8935. $course_id = api_get_course_int_id();
  8936. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8937. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8938. $item_title = get_lang('Student_publication');
  8939. if ($id != 0 && is_array($extra_info)) {
  8940. $item_title = stripslashes($extra_info['title']);
  8941. $item_description = stripslashes($extra_info['description']);
  8942. } elseif (is_numeric($extra_info)) {
  8943. $extra_info = (int) $extra_info;
  8944. $sql = "SELECT title, description
  8945. FROM $tbl_publication
  8946. WHERE c_id = $course_id AND id = ".$extra_info;
  8947. $result = Database::query($sql);
  8948. $row = Database::fetch_array($result);
  8949. if ($row) {
  8950. $item_title = $row['title'];
  8951. }
  8952. }
  8953. $parent = 0;
  8954. if ($id != 0 && is_array($extra_info)) {
  8955. $parent = $extra_info['parent_item_id'];
  8956. }
  8957. $sql = "SELECT * FROM $tbl_lp_item
  8958. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8959. $result = Database::query($sql);
  8960. $arrLP = [];
  8961. while ($row = Database::fetch_array($result)) {
  8962. $arrLP[] = [
  8963. 'id' => $row['iid'],
  8964. 'item_type' => $row['item_type'],
  8965. 'title' => $row['title'],
  8966. 'path' => $row['path'],
  8967. 'description' => $row['description'],
  8968. 'parent_item_id' => $row['parent_item_id'],
  8969. 'previous_item_id' => $row['previous_item_id'],
  8970. 'next_item_id' => $row['next_item_id'],
  8971. 'display_order' => $row['display_order'],
  8972. 'max_score' => $row['max_score'],
  8973. 'min_score' => $row['min_score'],
  8974. 'mastery_score' => $row['mastery_score'],
  8975. 'prerequisite' => $row['prerequisite'],
  8976. ];
  8977. }
  8978. $this->tree_array($arrLP);
  8979. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8980. unset($this->arrMenu);
  8981. $form = new FormValidator('frm_student_publication', 'post', '#');
  8982. if ($action == 'add') {
  8983. $form->addHeader(get_lang('Student_publication'));
  8984. } elseif ($action == 'move') {
  8985. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8986. } else {
  8987. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8988. }
  8989. if ($action != 'move') {
  8990. $form->addText(
  8991. 'title',
  8992. get_lang('Title'),
  8993. true,
  8994. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8995. );
  8996. }
  8997. $parentSelect = $form->addSelect(
  8998. 'parent',
  8999. get_lang('Parent'),
  9000. ['0' => $this->name],
  9001. [
  9002. 'onchange' => 'javascript: load_cbo(this.value);',
  9003. 'class' => 'learnpath_item_form',
  9004. 'id' => 'idParent',
  9005. ]
  9006. );
  9007. $arrHide = [$id];
  9008. for ($i = 0; $i < count($arrLP); $i++) {
  9009. if ($action != 'add') {
  9010. if (
  9011. ($arrLP[$i]['item_type'] == 'dir') &&
  9012. !in_array($arrLP[$i]['id'], $arrHide) &&
  9013. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  9014. ) {
  9015. $parentSelect->addOption(
  9016. $arrLP[$i]['title'],
  9017. $arrLP[$i]['id'],
  9018. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9019. );
  9020. if ($parent == $arrLP[$i]['id']) {
  9021. $parentSelect->setSelected($arrLP[$i]['id']);
  9022. }
  9023. } else {
  9024. $arrHide[] = $arrLP[$i]['id'];
  9025. }
  9026. } else {
  9027. if ($arrLP[$i]['item_type'] == 'dir') {
  9028. $parentSelect->addOption(
  9029. $arrLP[$i]['title'],
  9030. $arrLP[$i]['id'],
  9031. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9032. );
  9033. if ($parent == $arrLP[$i]['id']) {
  9034. $parentSelect->setSelected($arrLP[$i]['id']);
  9035. }
  9036. }
  9037. }
  9038. }
  9039. if (is_array($arrLP)) {
  9040. reset($arrLP);
  9041. }
  9042. $previousSelect = $form->addSelect(
  9043. 'previous',
  9044. get_lang('Position'),
  9045. ['0' => get_lang('FirstPosition')],
  9046. ['id' => 'previous', 'class' => 'learnpath_item_form']
  9047. );
  9048. for ($i = 0; $i < count($arrLP); $i++) {
  9049. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  9050. $previousSelect->addOption(
  9051. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  9052. $arrLP[$i]['id']
  9053. );
  9054. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9055. $previousSelect->setSelected($arrLP[$i]['id']);
  9056. } elseif ($action == 'add') {
  9057. $previousSelect->setSelected($arrLP[$i]['id']);
  9058. }
  9059. }
  9060. }
  9061. if ($action == 'add') {
  9062. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  9063. } else {
  9064. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  9065. }
  9066. if ($action == 'move') {
  9067. $form->addHidden('title', $item_title);
  9068. $form->addHidden('description', $item_description);
  9069. }
  9070. if (is_numeric($extra_info)) {
  9071. $form->addHidden('path', $extra_info);
  9072. } elseif (is_array($extra_info)) {
  9073. $form->addHidden('path', $extra_info['path']);
  9074. }
  9075. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  9076. $form->addHidden('post_time', time());
  9077. $form->setDefaults(['title' => $item_title]);
  9078. $return = '<div class="sectioncomment">';
  9079. $return .= $form->returnForm();
  9080. $return .= '</div>';
  9081. return $return;
  9082. }
  9083. /**
  9084. * Displays the menu for manipulating a step.
  9085. *
  9086. * @param id $item_id
  9087. * @param string $item_type
  9088. *
  9089. * @return string
  9090. */
  9091. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  9092. {
  9093. $_course = api_get_course_info();
  9094. $course_code = api_get_course_id();
  9095. $return = '<div class="actions">';
  9096. switch ($item_type) {
  9097. case 'dir':
  9098. // Commented the message cause should not show it.
  9099. //$lang = get_lang('TitleManipulateChapter');
  9100. break;
  9101. case TOOL_LP_FINAL_ITEM:
  9102. case TOOL_DOCUMENT:
  9103. // Commented the message cause should not show it.
  9104. //$lang = get_lang('TitleManipulateDocument');
  9105. break;
  9106. case TOOL_LINK:
  9107. case 'link':
  9108. // Commented the message cause should not show it.
  9109. //$lang = get_lang('TitleManipulateLink');
  9110. break;
  9111. case TOOL_QUIZ:
  9112. // Commented the message cause should not show it.
  9113. //$lang = get_lang('TitleManipulateQuiz');
  9114. break;
  9115. case TOOL_STUDENTPUBLICATION:
  9116. // Commented the message cause should not show it.
  9117. //$lang = get_lang('TitleManipulateStudentPublication');
  9118. break;
  9119. }
  9120. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9121. $item_id = (int) $item_id;
  9122. $sql = "SELECT * FROM $tbl_lp_item
  9123. WHERE iid = ".$item_id;
  9124. $result = Database::query($sql);
  9125. $row = Database::fetch_assoc($result);
  9126. $audio_player = null;
  9127. // We display an audio player if needed.
  9128. if (!empty($row['audio'])) {
  9129. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9130. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9131. .'<audio src="'.$webAudioPath.'" controls>'
  9132. .'</div><br>';
  9133. }
  9134. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9135. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9136. $return .= Display::url(
  9137. Display::return_icon(
  9138. 'edit.png',
  9139. get_lang('Edit'),
  9140. [],
  9141. ICON_SIZE_SMALL
  9142. ),
  9143. $url.'&action=edit_item&path_item='.$row['path']
  9144. );
  9145. $return .= Display::url(
  9146. Display::return_icon(
  9147. 'move.png',
  9148. get_lang('Move'),
  9149. [],
  9150. ICON_SIZE_SMALL
  9151. ),
  9152. $url.'&action=move_item'
  9153. );
  9154. }
  9155. // Commented for now as prerequisites cannot be added to chapters.
  9156. if ($item_type != 'dir') {
  9157. $return .= Display::url(
  9158. Display::return_icon(
  9159. 'accept.png',
  9160. get_lang('LearnpathPrerequisites'),
  9161. [],
  9162. ICON_SIZE_SMALL
  9163. ),
  9164. $url.'&action=edit_item_prereq'
  9165. );
  9166. }
  9167. $return .= Display::url(
  9168. Display::return_icon(
  9169. 'delete.png',
  9170. get_lang('Delete'),
  9171. [],
  9172. ICON_SIZE_SMALL
  9173. ),
  9174. $url.'&action=delete_item'
  9175. );
  9176. if ($item_type == TOOL_HOTPOTATOES) {
  9177. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9178. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  9179. }
  9180. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  9181. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9182. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  9183. }
  9184. $return .= '</div>';
  9185. if (!empty($audio_player)) {
  9186. $return .= $audio_player;
  9187. }
  9188. return $return;
  9189. }
  9190. /**
  9191. * Creates the javascript needed for filling up the checkboxes without page reload.
  9192. *
  9193. * @return string
  9194. */
  9195. public function get_js_dropdown_array()
  9196. {
  9197. $course_id = api_get_course_int_id();
  9198. $return = 'var child_name = new Array();'."\n";
  9199. $return .= 'var child_value = new Array();'."\n\n";
  9200. $return .= 'child_name[0] = new Array();'."\n";
  9201. $return .= 'child_value[0] = new Array();'."\n\n";
  9202. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9203. $sql = "SELECT * FROM ".$tbl_lp_item."
  9204. WHERE
  9205. c_id = $course_id AND
  9206. lp_id = ".$this->lp_id." AND
  9207. parent_item_id = 0
  9208. ORDER BY display_order ASC";
  9209. $res_zero = Database::query($sql);
  9210. $i = 0;
  9211. while ($row_zero = Database::fetch_array($res_zero)) {
  9212. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9213. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9214. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9215. }
  9216. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9217. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9218. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9219. }
  9220. }
  9221. $return .= "\n";
  9222. $sql = "SELECT * FROM $tbl_lp_item
  9223. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9224. $res = Database::query($sql);
  9225. while ($row = Database::fetch_array($res)) {
  9226. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9227. WHERE
  9228. c_id = ".$course_id." AND
  9229. parent_item_id = ".$row['iid']."
  9230. ORDER BY display_order ASC";
  9231. $res_parent = Database::query($sql_parent);
  9232. $i = 0;
  9233. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9234. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9235. while ($row_parent = Database::fetch_array($res_parent)) {
  9236. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9237. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9238. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9239. }
  9240. $return .= "\n";
  9241. }
  9242. $return .= "
  9243. function load_cbo(id) {
  9244. if (!id) {
  9245. return false;
  9246. }
  9247. var cbo = document.getElementById('previous');
  9248. for(var i = cbo.length - 1; i > 0; i--) {
  9249. cbo.options[i] = null;
  9250. }
  9251. var k=0;
  9252. for(var i = 1; i <= child_name[id].length; i++){
  9253. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9254. option.style.paddingLeft = '40px';
  9255. cbo.options[i] = option;
  9256. k = i;
  9257. }
  9258. cbo.options[k].selected = true;
  9259. $('#previous').selectpicker('refresh');
  9260. }";
  9261. return $return;
  9262. }
  9263. /**
  9264. * Display the form to allow moving an item.
  9265. *
  9266. * @param int $item_id Item ID
  9267. *
  9268. * @throws Exception
  9269. * @throws HTML_QuickForm_Error
  9270. *
  9271. * @return string HTML form
  9272. */
  9273. public function display_move_item($item_id)
  9274. {
  9275. $return = '';
  9276. if (is_numeric($item_id)) {
  9277. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9278. $sql = "SELECT * FROM $tbl_lp_item
  9279. WHERE iid = $item_id";
  9280. $res = Database::query($sql);
  9281. $row = Database::fetch_array($res);
  9282. switch ($row['item_type']) {
  9283. case 'dir':
  9284. case 'asset':
  9285. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9286. $return .= $this->display_item_form(
  9287. $row['item_type'],
  9288. get_lang('MoveCurrentChapter'),
  9289. 'move',
  9290. $item_id,
  9291. $row
  9292. );
  9293. break;
  9294. case TOOL_DOCUMENT:
  9295. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9296. $return .= $this->display_document_form('move', $item_id, $row);
  9297. break;
  9298. case TOOL_LINK:
  9299. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9300. $return .= $this->display_link_form('move', $item_id, $row);
  9301. break;
  9302. case TOOL_HOTPOTATOES:
  9303. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9304. $return .= $this->display_link_form('move', $item_id, $row);
  9305. break;
  9306. case TOOL_QUIZ:
  9307. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9308. $return .= $this->display_quiz_form('move', $item_id, $row);
  9309. break;
  9310. case TOOL_STUDENTPUBLICATION:
  9311. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9312. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9313. break;
  9314. case TOOL_FORUM:
  9315. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9316. $return .= $this->display_forum_form('move', $item_id, $row);
  9317. break;
  9318. case TOOL_THREAD:
  9319. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9320. $return .= $this->display_forum_form('move', $item_id, $row);
  9321. break;
  9322. }
  9323. }
  9324. return $return;
  9325. }
  9326. /**
  9327. * Return HTML form to allow prerequisites selection.
  9328. *
  9329. * @todo use FormValidator
  9330. *
  9331. * @param int Item ID
  9332. *
  9333. * @return string HTML form
  9334. */
  9335. public function display_item_prerequisites_form($item_id = 0)
  9336. {
  9337. $course_id = api_get_course_int_id();
  9338. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9339. $item_id = intval($item_id);
  9340. /* Current prerequisite */
  9341. $sql = "SELECT * FROM $tbl_lp_item
  9342. WHERE iid = $item_id";
  9343. $result = Database::query($sql);
  9344. $row = Database::fetch_array($result);
  9345. $prerequisiteId = $row['prerequisite'];
  9346. $return = '<legend>';
  9347. $return .= get_lang('AddEditPrerequisites');
  9348. $return .= '</legend>';
  9349. $return .= '<form method="POST">';
  9350. $return .= '<div class="table-responsive">';
  9351. $return .= '<table class="table table-hover">';
  9352. $return .= '<thead>';
  9353. $return .= '<tr>';
  9354. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9355. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9356. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9357. $return .= '</tr>';
  9358. $return .= '</thead>';
  9359. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9360. $return .= '<tbody>';
  9361. $return .= '<tr>';
  9362. $return .= '<td colspan="3">';
  9363. $return .= '<div class="radio learnpath"><label for="idNone">';
  9364. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9365. $return .= get_lang('None').'</label>';
  9366. $return .= '</div>';
  9367. $return .= '</tr>';
  9368. $sql = "SELECT * FROM $tbl_lp_item
  9369. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9370. $result = Database::query($sql);
  9371. $arrLP = [];
  9372. $selectedMinScore = [];
  9373. $selectedMaxScore = [];
  9374. while ($row = Database::fetch_array($result)) {
  9375. if ($row['id'] == $item_id) {
  9376. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9377. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9378. }
  9379. $arrLP[] = [
  9380. 'id' => $row['iid'],
  9381. 'item_type' => $row['item_type'],
  9382. 'title' => $row['title'],
  9383. 'ref' => $row['ref'],
  9384. 'description' => $row['description'],
  9385. 'parent_item_id' => $row['parent_item_id'],
  9386. 'previous_item_id' => $row['previous_item_id'],
  9387. 'next_item_id' => $row['next_item_id'],
  9388. 'max_score' => $row['max_score'],
  9389. 'min_score' => $row['min_score'],
  9390. 'mastery_score' => $row['mastery_score'],
  9391. 'prerequisite' => $row['prerequisite'],
  9392. 'display_order' => $row['display_order'],
  9393. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9394. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9395. ];
  9396. }
  9397. $this->tree_array($arrLP);
  9398. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9399. unset($this->arrMenu);
  9400. for ($i = 0; $i < count($arrLP); $i++) {
  9401. $item = $arrLP[$i];
  9402. if ($item['id'] == $item_id) {
  9403. break;
  9404. }
  9405. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9406. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9407. $return .= '<tr>';
  9408. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9409. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9410. $return .= '<label for="id'.$item['id'].'">';
  9411. $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'].'" />';
  9412. $icon_name = str_replace(' ', '', $item['item_type']);
  9413. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9414. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9415. } else {
  9416. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9417. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9418. } else {
  9419. $return .= Display::return_icon('folder_document.png');
  9420. }
  9421. }
  9422. $return .= $item['title'].'</label>';
  9423. $return .= '</div>';
  9424. $return .= '</td>';
  9425. if ($item['item_type'] == TOOL_QUIZ) {
  9426. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9427. $lpItemObj = new LpItem($course_id, $item['id']);
  9428. $exercise = new Exercise($course_id);
  9429. $exercise->read($lpItemObj->path);
  9430. $lpItemObj->max_score = $exercise->get_max_score();
  9431. $lpItemObj->update();
  9432. $item['max_score'] = $lpItemObj->max_score;
  9433. $return .= '<td>';
  9434. $return .= '<input
  9435. class="form-control"
  9436. size="4" maxlength="3"
  9437. name="min_'.$item['id'].'"
  9438. type="number"
  9439. min="0"
  9440. step="1"
  9441. max="'.$item['max_score'].'"
  9442. value="'.$selectedMinScoreValue.'"
  9443. />';
  9444. $return .= '</td>';
  9445. $return .= '<td>';
  9446. $return .= '<input
  9447. class="form-control"
  9448. size="4"
  9449. maxlength="3"
  9450. name="max_'.$item['id'].'"
  9451. type="number"
  9452. min="0"
  9453. step="1"
  9454. max="'.$item['max_score'].'"
  9455. value="'.$selectedMaxScoreValue.'"
  9456. />';
  9457. $return .= '</td>';
  9458. }
  9459. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9460. $return .= '<td>';
  9461. $return .= '<input
  9462. size="4"
  9463. maxlength="3"
  9464. name="min_'.$item['id'].'"
  9465. type="number"
  9466. min="0"
  9467. step="1"
  9468. max="'.$item['max_score'].'"
  9469. value="'.$selectedMinScoreValue.'"
  9470. />';
  9471. $return .= '</td>';
  9472. $return .= '<td>';
  9473. $return .= '<input
  9474. size="4"
  9475. maxlength="3"
  9476. name="max_'.$item['id'].'"
  9477. type="number"
  9478. min="0"
  9479. step="1"
  9480. max="'.$item['max_score'].'"
  9481. value="'.$selectedMaxScoreValue.'"
  9482. />';
  9483. $return .= '</td>';
  9484. }
  9485. $return .= '</tr>';
  9486. }
  9487. $return .= '<tr>';
  9488. $return .= '</tr>';
  9489. $return .= '</tbody>';
  9490. $return .= '</table>';
  9491. $return .= '</div>';
  9492. $return .= '<div class="form-group">';
  9493. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9494. get_lang('ModifyPrerequisites').'</button>';
  9495. $return .= '</form>';
  9496. return $return;
  9497. }
  9498. /**
  9499. * Return HTML list to allow prerequisites selection for lp.
  9500. *
  9501. * @return string HTML form
  9502. */
  9503. public function display_lp_prerequisites_list()
  9504. {
  9505. $course_id = api_get_course_int_id();
  9506. $lp_id = $this->lp_id;
  9507. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9508. // get current prerequisite
  9509. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9510. $result = Database::query($sql);
  9511. $row = Database::fetch_array($result);
  9512. $prerequisiteId = $row['prerequisite'];
  9513. $session_id = api_get_session_id();
  9514. $session_condition = api_get_session_condition($session_id, true, true);
  9515. $sql = "SELECT * FROM $tbl_lp
  9516. WHERE c_id = $course_id $session_condition
  9517. ORDER BY display_order ";
  9518. $rs = Database::query($sql);
  9519. $return = '';
  9520. $return .= '<select name="prerequisites" class="form-control">';
  9521. $return .= '<option value="0">'.get_lang('None').'</option>';
  9522. if (Database::num_rows($rs) > 0) {
  9523. while ($row = Database::fetch_array($rs)) {
  9524. if ($row['id'] == $lp_id) {
  9525. continue;
  9526. }
  9527. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9528. }
  9529. }
  9530. $return .= '</select>';
  9531. return $return;
  9532. }
  9533. /**
  9534. * Creates a list with all the documents in it.
  9535. *
  9536. * @param bool $showInvisibleFiles
  9537. *
  9538. * @throws Exception
  9539. * @throws HTML_QuickForm_Error
  9540. *
  9541. * @return string
  9542. */
  9543. public function get_documents($showInvisibleFiles = false)
  9544. {
  9545. $course_info = api_get_course_info();
  9546. $sessionId = api_get_session_id();
  9547. $documentTree = DocumentManager::get_document_preview(
  9548. $course_info,
  9549. $this->lp_id,
  9550. null,
  9551. $sessionId,
  9552. true,
  9553. null,
  9554. null,
  9555. $showInvisibleFiles,
  9556. true
  9557. );
  9558. $headers = [
  9559. get_lang('Files'),
  9560. get_lang('CreateTheDocument'),
  9561. get_lang('CreateReadOutText'),
  9562. get_lang('Upload'),
  9563. ];
  9564. $form = new FormValidator(
  9565. 'form_upload',
  9566. 'POST',
  9567. $this->getCurrentBuildingModeURL(),
  9568. '',
  9569. ['enctype' => 'multipart/form-data']
  9570. );
  9571. $folders = DocumentManager::get_all_document_folders(
  9572. api_get_course_info(),
  9573. 0,
  9574. true
  9575. );
  9576. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9577. DocumentManager::build_directory_selector(
  9578. $folders,
  9579. $lpPathInfo['id'],
  9580. [],
  9581. true,
  9582. $form,
  9583. 'directory_parent_id'
  9584. );
  9585. $group = [
  9586. $form->createElement(
  9587. 'radio',
  9588. 'if_exists',
  9589. get_lang("UplWhatIfFileExists"),
  9590. get_lang('UplDoNothing'),
  9591. 'nothing'
  9592. ),
  9593. $form->createElement(
  9594. 'radio',
  9595. 'if_exists',
  9596. null,
  9597. get_lang('UplOverwriteLong'),
  9598. 'overwrite'
  9599. ),
  9600. $form->createElement(
  9601. 'radio',
  9602. 'if_exists',
  9603. null,
  9604. get_lang('UplRenameLong'),
  9605. 'rename'
  9606. ),
  9607. ];
  9608. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9609. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9610. $defaultFileExistsOption = 'rename';
  9611. if (!empty($fileExistsOption)) {
  9612. $defaultFileExistsOption = $fileExistsOption;
  9613. }
  9614. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9615. // Check box options
  9616. $form->addElement(
  9617. 'checkbox',
  9618. 'unzip',
  9619. get_lang('Options'),
  9620. get_lang('Uncompress')
  9621. );
  9622. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9623. $form->addMultipleUpload($url);
  9624. $new = $this->display_document_form('add', 0);
  9625. $frmReadOutText = $this->displayFrmReadOutText('add');
  9626. $tabs = Display::tabs(
  9627. $headers,
  9628. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9629. 'subtab'
  9630. );
  9631. return $tabs;
  9632. }
  9633. /**
  9634. * Creates a list with all the exercises (quiz) in it.
  9635. *
  9636. * @return string
  9637. */
  9638. public function get_exercises()
  9639. {
  9640. $course_id = api_get_course_int_id();
  9641. $session_id = api_get_session_id();
  9642. $userInfo = api_get_user_info();
  9643. // New for hotpotatoes.
  9644. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9645. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9646. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9647. $condition_session = api_get_session_condition($session_id, true, true);
  9648. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9649. $activeCondition = ' active <> -1 ';
  9650. if ($setting) {
  9651. $activeCondition = ' active = 1 ';
  9652. }
  9653. $sql_quiz = "SELECT * FROM $tbl_quiz
  9654. WHERE c_id = $course_id AND $activeCondition $condition_session
  9655. ORDER BY title ASC";
  9656. $sql_hot = "SELECT * FROM $tbl_doc
  9657. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9658. ORDER BY id ASC";
  9659. $res_quiz = Database::query($sql_quiz);
  9660. $res_hot = Database::query($sql_hot);
  9661. $return = '<ul class="lp_resource">';
  9662. $return .= '<li class="lp_resource_element">';
  9663. $return .= Display::return_icon('new_exercice.png');
  9664. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9665. get_lang('NewExercise').'</a>';
  9666. $return .= '</li>';
  9667. $previewIcon = Display::return_icon(
  9668. 'preview_view.png',
  9669. get_lang('Preview')
  9670. );
  9671. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9672. // Display hotpotatoes
  9673. while ($row_hot = Database::fetch_array($res_hot)) {
  9674. $link = Display::url(
  9675. $previewIcon,
  9676. $exerciseUrl.'&file='.$row_hot['path'],
  9677. ['target' => '_blank']
  9678. );
  9679. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9680. $return .= '<a class="moved" href="#">';
  9681. $return .= Display::return_icon(
  9682. 'move_everywhere.png',
  9683. get_lang('Move'),
  9684. [],
  9685. ICON_SIZE_TINY
  9686. );
  9687. $return .= '</a> ';
  9688. $return .= Display::return_icon('hotpotatoes_s.png');
  9689. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9690. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9691. $return .= '</li>';
  9692. }
  9693. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9694. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9695. $title = strip_tags(
  9696. api_html_entity_decode($row_quiz['title'])
  9697. );
  9698. $link = Display::url(
  9699. $previewIcon,
  9700. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9701. ['target' => '_blank']
  9702. );
  9703. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9704. $return .= '<a class="moved" href="#">';
  9705. $return .= Display::return_icon(
  9706. 'move_everywhere.png',
  9707. get_lang('Move'),
  9708. [],
  9709. ICON_SIZE_TINY
  9710. );
  9711. $return .= '</a> ';
  9712. $return .= Display::return_icon(
  9713. 'quiz.png',
  9714. '',
  9715. [],
  9716. ICON_SIZE_TINY
  9717. );
  9718. $sessionStar = api_get_session_image(
  9719. $row_quiz['session_id'],
  9720. $userInfo['status']
  9721. );
  9722. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id.'">'.
  9723. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  9724. '</a>';
  9725. $return .= '</li>';
  9726. }
  9727. $return .= '</ul>';
  9728. return $return;
  9729. }
  9730. /**
  9731. * Creates a list with all the links in it.
  9732. *
  9733. * @return string
  9734. */
  9735. public function get_links()
  9736. {
  9737. $selfUrl = api_get_self();
  9738. $courseIdReq = api_get_cidreq();
  9739. $course = api_get_course_info();
  9740. $userInfo = api_get_user_info();
  9741. $course_id = $course['real_id'];
  9742. $tbl_link = Database::get_course_table(TABLE_LINK);
  9743. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9744. $moveEverywhereIcon = Display::return_icon(
  9745. 'move_everywhere.png',
  9746. get_lang('Move'),
  9747. [],
  9748. ICON_SIZE_TINY
  9749. );
  9750. $session_id = api_get_session_id();
  9751. $condition_session = api_get_session_condition(
  9752. $session_id,
  9753. true,
  9754. true,
  9755. "link.session_id"
  9756. );
  9757. $sql = "SELECT
  9758. link.id as link_id,
  9759. link.title as link_title,
  9760. link.session_id as link_session_id,
  9761. link.category_id as category_id,
  9762. link_category.category_title as category_title
  9763. FROM $tbl_link as link
  9764. LEFT JOIN $linkCategoryTable as link_category
  9765. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9766. WHERE link.c_id = ".$course_id." $condition_session
  9767. ORDER BY link_category.category_title ASC, link.title ASC";
  9768. $result = Database::query($sql);
  9769. $categorizedLinks = [];
  9770. $categories = [];
  9771. while ($link = Database::fetch_array($result)) {
  9772. if (!$link['category_id']) {
  9773. $link['category_title'] = get_lang('Uncategorized');
  9774. }
  9775. $categories[$link['category_id']] = $link['category_title'];
  9776. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9777. }
  9778. $linksHtmlCode =
  9779. '<script>
  9780. function toggle_tool(tool, id) {
  9781. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9782. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9783. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9784. } else {
  9785. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9786. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9787. }
  9788. }
  9789. </script>
  9790. <ul class="lp_resource">
  9791. <li class="lp_resource_element">
  9792. '.Display::return_icon('linksnew.gif').'
  9793. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9794. get_lang('LinkAdd').'
  9795. </a>
  9796. </li>';
  9797. foreach ($categorizedLinks as $categoryId => $links) {
  9798. $linkNodes = null;
  9799. foreach ($links as $key => $linkInfo) {
  9800. $title = $linkInfo['link_title'];
  9801. $linkSessionId = $linkInfo['link_session_id'];
  9802. $link = Display::url(
  9803. Display::return_icon('preview_view.png', get_lang('Preview')),
  9804. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9805. ['target' => '_blank']
  9806. );
  9807. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9808. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9809. $linkNodes .=
  9810. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9811. <a class="moved" href="#">'.
  9812. $moveEverywhereIcon.
  9813. '</a>
  9814. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9815. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9816. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9817. Security::remove_XSS($title).$sessionStar.$link.
  9818. '</a>
  9819. </li>';
  9820. }
  9821. }
  9822. $linksHtmlCode .=
  9823. '<li>
  9824. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9825. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9826. align="absbottom" />
  9827. </a>
  9828. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9829. </li>
  9830. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9831. }
  9832. $linksHtmlCode .= '</ul>';
  9833. return $linksHtmlCode;
  9834. }
  9835. /**
  9836. * Creates a list with all the student publications in it.
  9837. *
  9838. * @return string
  9839. */
  9840. public function get_student_publications()
  9841. {
  9842. $return = '<ul class="lp_resource">';
  9843. $return .= '<li class="lp_resource_element">';
  9844. $return .= Display::return_icon('works_new.gif');
  9845. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9846. get_lang('AddAssignmentPage').'</a>';
  9847. $return .= '</li>';
  9848. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9849. $works = getWorkListTeacher(0, 100, null, null, null);
  9850. if (!empty($works)) {
  9851. foreach ($works as $work) {
  9852. $link = Display::url(
  9853. Display::return_icon('preview_view.png', get_lang('Preview')),
  9854. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9855. ['target' => '_blank']
  9856. );
  9857. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9858. $return .= '<a class="moved" href="#">';
  9859. $return .= Display::return_icon(
  9860. 'move_everywhere.png',
  9861. get_lang('Move'),
  9862. [],
  9863. ICON_SIZE_TINY
  9864. );
  9865. $return .= '</a> ';
  9866. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9867. $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.'">'.
  9868. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9869. </a>';
  9870. $return .= '</li>';
  9871. }
  9872. }
  9873. $return .= '</ul>';
  9874. return $return;
  9875. }
  9876. /**
  9877. * Creates a list with all the forums in it.
  9878. *
  9879. * @return string
  9880. */
  9881. public function get_forums()
  9882. {
  9883. require_once '../forum/forumfunction.inc.php';
  9884. require_once '../forum/forumconfig.inc.php';
  9885. $forumCategories = get_forum_categories();
  9886. $forumsInNoCategory = get_forums_in_category(0);
  9887. if (!empty($forumsInNoCategory)) {
  9888. $forumCategories = array_merge(
  9889. $forumCategories,
  9890. [
  9891. [
  9892. 'cat_id' => 0,
  9893. 'session_id' => 0,
  9894. 'visibility' => 1,
  9895. 'cat_comment' => null,
  9896. ],
  9897. ]
  9898. );
  9899. }
  9900. $forumList = get_forums();
  9901. $a_forums = [];
  9902. foreach ($forumCategories as $forumCategory) {
  9903. // The forums in this category.
  9904. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9905. if (!empty($forumsInCategory)) {
  9906. foreach ($forumList as $forum) {
  9907. if (isset($forum['forum_category']) &&
  9908. $forum['forum_category'] == $forumCategory['cat_id']
  9909. ) {
  9910. $a_forums[] = $forum;
  9911. }
  9912. }
  9913. }
  9914. }
  9915. $return = '<ul class="lp_resource">';
  9916. // First add link
  9917. $return .= '<li class="lp_resource_element">';
  9918. $return .= Display::return_icon('new_forum.png');
  9919. $return .= Display::url(
  9920. get_lang('CreateANewForum'),
  9921. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9922. 'action' => 'add',
  9923. 'content' => 'forum',
  9924. 'lp_id' => $this->lp_id,
  9925. ]),
  9926. ['title' => get_lang('CreateANewForum')]
  9927. );
  9928. $return .= '</li>';
  9929. $return .= '<script>
  9930. function toggle_forum(forum_id) {
  9931. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9932. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9933. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9934. } else {
  9935. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9936. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9937. }
  9938. }
  9939. </script>';
  9940. foreach ($a_forums as $forum) {
  9941. if (!empty($forum['forum_id'])) {
  9942. $link = Display::url(
  9943. Display::return_icon('preview_view.png', get_lang('Preview')),
  9944. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9945. ['target' => '_blank']
  9946. );
  9947. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9948. $return .= '<a class="moved" href="#">';
  9949. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9950. $return .= ' </a>';
  9951. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9952. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9953. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9954. </a>
  9955. <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">'.
  9956. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9957. $return .= '</li>';
  9958. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9959. $a_threads = get_threads($forum['forum_id']);
  9960. if (is_array($a_threads)) {
  9961. foreach ($a_threads as $thread) {
  9962. $link = Display::url(
  9963. Display::return_icon('preview_view.png', get_lang('Preview')),
  9964. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9965. ['target' => '_blank']
  9966. );
  9967. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9968. $return .= '&nbsp;<a class="moved" href="#">';
  9969. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9970. $return .= ' </a>';
  9971. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9972. $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.'">'.
  9973. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9974. $return .= '</li>';
  9975. }
  9976. }
  9977. $return .= '</div>';
  9978. }
  9979. }
  9980. $return .= '</ul>';
  9981. return $return;
  9982. }
  9983. /**
  9984. * // TODO: The output encoding should be equal to the system encoding.
  9985. *
  9986. * Exports the learning path as a SCORM package. This is the main function that
  9987. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9988. * whole thing and returns the zip.
  9989. *
  9990. * This method needs to be called in PHP5, as it will fail with non-adequate
  9991. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9992. * you need to call it on a learnpath object.
  9993. *
  9994. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9995. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9996. * path has been modified, it should use the generic method here below.
  9997. *
  9998. * @return string Returns the zip package string, or null if error
  9999. */
  10000. public function scormExport()
  10001. {
  10002. api_set_more_memory_and_time_limits();
  10003. $_course = api_get_course_info();
  10004. $course_id = $_course['real_id'];
  10005. // Create the zip handler (this will remain available throughout the method).
  10006. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  10007. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10008. $temp_dir_short = uniqid('scorm_export', true);
  10009. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  10010. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  10011. $zip_folder = new PclZip($temp_zip_file);
  10012. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  10013. $root_path = $main_path = api_get_path(SYS_PATH);
  10014. $files_cleanup = [];
  10015. // Place to temporarily stash the zip file.
  10016. // create the temp dir if it doesn't exist
  10017. // or do a cleanup before creating the zip file.
  10018. if (!is_dir($temp_zip_dir)) {
  10019. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  10020. } else {
  10021. // Cleanup: Check the temp dir for old files and delete them.
  10022. $handle = opendir($temp_zip_dir);
  10023. while (false !== ($file = readdir($handle))) {
  10024. if ($file != '.' && $file != '..') {
  10025. unlink("$temp_zip_dir/$file");
  10026. }
  10027. }
  10028. closedir($handle);
  10029. }
  10030. $zip_files = $zip_files_abs = $zip_files_dist = [];
  10031. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  10032. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  10033. ) {
  10034. // Remove the possible . at the end of the path.
  10035. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  10036. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  10037. mkdir(
  10038. $dest_path_to_scorm_folder,
  10039. api_get_permissions_for_new_directories(),
  10040. true
  10041. );
  10042. copyr(
  10043. $current_course_path.'/scorm/'.$this->path,
  10044. $dest_path_to_scorm_folder,
  10045. ['imsmanifest'],
  10046. $zip_files
  10047. );
  10048. }
  10049. // Build a dummy imsmanifest structure.
  10050. // Do not add to the zip yet (we still need it).
  10051. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  10052. // Aggregation Model official document, section "2.3 Content Packaging".
  10053. // We are going to build a UTF-8 encoded manifest.
  10054. // Later we will recode it to the desired (and supported) encoding.
  10055. $xmldoc = new DOMDocument('1.0');
  10056. $root = $xmldoc->createElement('manifest');
  10057. $root->setAttribute('identifier', 'SingleCourseManifest');
  10058. $root->setAttribute('version', '1.1');
  10059. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10060. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10061. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10062. $root->setAttribute(
  10063. 'xsi:schemaLocation',
  10064. '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'
  10065. );
  10066. // Build mandatory sub-root container elements.
  10067. $metadata = $xmldoc->createElement('metadata');
  10068. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10069. $metadata->appendChild($md_schema);
  10070. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10071. $metadata->appendChild($md_schemaversion);
  10072. $root->appendChild($metadata);
  10073. $organizations = $xmldoc->createElement('organizations');
  10074. $resources = $xmldoc->createElement('resources');
  10075. // Build the only organization we will use in building our learnpaths.
  10076. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10077. $organization = $xmldoc->createElement('organization');
  10078. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10079. // To set the title of the SCORM entity (=organization), we take the name given
  10080. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10081. // learning path charset) as it is the encoding that defines how it is stored
  10082. // in the database. Then we convert it to HTML entities again as the "&" character
  10083. // alone is not authorized in XML (must be &amp;).
  10084. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10085. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10086. $organization->appendChild($org_title);
  10087. $folder_name = 'document';
  10088. // Removes the learning_path/scorm_folder path when exporting see #4841
  10089. $path_to_remove = '';
  10090. $path_to_replace = '';
  10091. $result = $this->generate_lp_folder($_course);
  10092. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10093. $path_to_remove = 'document'.$result['dir'];
  10094. $path_to_replace = $folder_name.'/';
  10095. }
  10096. // Fixes chamilo scorm exports
  10097. if ($this->ref === 'chamilo_scorm_export') {
  10098. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10099. }
  10100. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10101. $link_updates = [];
  10102. $links_to_create = [];
  10103. foreach ($this->ordered_items as $index => $itemId) {
  10104. /** @var learnpathItem $item */
  10105. $item = $this->items[$itemId];
  10106. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10107. // Get included documents from this item.
  10108. if ($item->type === 'sco') {
  10109. $inc_docs = $item->get_resources_from_source(
  10110. null,
  10111. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10112. );
  10113. } else {
  10114. $inc_docs = $item->get_resources_from_source();
  10115. }
  10116. // Give a child element <item> to the <organization> element.
  10117. $my_item_id = $item->get_id();
  10118. $my_item = $xmldoc->createElement('item');
  10119. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10120. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10121. $my_item->setAttribute('isvisible', 'true');
  10122. // Give a child element <title> to the <item> element.
  10123. $my_title = $xmldoc->createElement(
  10124. 'title',
  10125. htmlspecialchars(
  10126. api_utf8_encode($item->get_title()),
  10127. ENT_QUOTES,
  10128. 'UTF-8'
  10129. )
  10130. );
  10131. $my_item->appendChild($my_title);
  10132. // Give a child element <adlcp:prerequisites> to the <item> element.
  10133. $my_prereqs = $xmldoc->createElement(
  10134. 'adlcp:prerequisites',
  10135. $this->get_scorm_prereq_string($my_item_id)
  10136. );
  10137. $my_prereqs->setAttribute('type', 'aicc_script');
  10138. $my_item->appendChild($my_prereqs);
  10139. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10140. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10141. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10142. //$xmldoc->createElement('adlcp:timelimitaction','');
  10143. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10144. //$xmldoc->createElement('adlcp:datafromlms','');
  10145. // Give a child element <adlcp:masteryscore> to the <item> element.
  10146. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10147. $my_item->appendChild($my_masteryscore);
  10148. // Attach this item to the organization element or hits parent if there is one.
  10149. if (!empty($item->parent) && $item->parent != 0) {
  10150. $children = $organization->childNodes;
  10151. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10152. if (is_object($possible_parent)) {
  10153. $possible_parent->appendChild($my_item);
  10154. } else {
  10155. if ($this->debug > 0) {
  10156. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10157. }
  10158. }
  10159. } else {
  10160. if ($this->debug > 0) {
  10161. error_log('No parent');
  10162. }
  10163. $organization->appendChild($my_item);
  10164. }
  10165. // Get the path of the file(s) from the course directory root.
  10166. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10167. $my_xml_file_path = $my_file_path;
  10168. if (!empty($path_to_remove)) {
  10169. // From docs
  10170. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10171. // From quiz
  10172. if ($this->ref === 'chamilo_scorm_export') {
  10173. $path_to_remove = 'scorm/'.$this->path.'/';
  10174. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10175. }
  10176. }
  10177. $my_sub_dir = dirname($my_file_path);
  10178. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10179. $my_xml_sub_dir = $my_sub_dir;
  10180. // Give a <resource> child to the <resources> element
  10181. $my_resource = $xmldoc->createElement('resource');
  10182. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10183. $my_resource->setAttribute('type', 'webcontent');
  10184. $my_resource->setAttribute('href', $my_xml_file_path);
  10185. // adlcp:scormtype can be either 'sco' or 'asset'.
  10186. if ($item->type === 'sco') {
  10187. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10188. } else {
  10189. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10190. }
  10191. // xml:base is the base directory to find the files declared in this resource.
  10192. $my_resource->setAttribute('xml:base', '');
  10193. // Give a <file> child to the <resource> element.
  10194. $my_file = $xmldoc->createElement('file');
  10195. $my_file->setAttribute('href', $my_xml_file_path);
  10196. $my_resource->appendChild($my_file);
  10197. // Dependency to other files - not yet supported.
  10198. $i = 1;
  10199. if ($inc_docs) {
  10200. foreach ($inc_docs as $doc_info) {
  10201. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10202. continue;
  10203. }
  10204. $my_dep = $xmldoc->createElement('resource');
  10205. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10206. $my_dep->setAttribute('identifier', $res_id);
  10207. $my_dep->setAttribute('type', 'webcontent');
  10208. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10209. $my_dep_file = $xmldoc->createElement('file');
  10210. // Check type of URL.
  10211. if ($doc_info[1] == 'remote') {
  10212. // Remote file. Save url as is.
  10213. $my_dep_file->setAttribute('href', $doc_info[0]);
  10214. $my_dep->setAttribute('xml:base', '');
  10215. } elseif ($doc_info[1] === 'local') {
  10216. switch ($doc_info[2]) {
  10217. case 'url':
  10218. // Local URL - save path as url for now, don't zip file.
  10219. $abs_path = api_get_path(SYS_PATH).
  10220. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10221. $current_dir = dirname($abs_path);
  10222. $current_dir = str_replace('\\', '/', $current_dir);
  10223. $file_path = realpath($abs_path);
  10224. $file_path = str_replace('\\', '/', $file_path);
  10225. $my_dep_file->setAttribute('href', $file_path);
  10226. $my_dep->setAttribute('xml:base', '');
  10227. if (strstr($file_path, $main_path) !== false) {
  10228. // The calculated real path is really inside Chamilo's root path.
  10229. // Reduce file path to what's under the DocumentRoot.
  10230. $replace = $file_path;
  10231. $file_path = substr($file_path, strlen($root_path) - 1);
  10232. $destinationFile = $file_path;
  10233. if (strstr($file_path, 'upload/users') !== false) {
  10234. $pos = strpos($file_path, 'my_files/');
  10235. if ($pos !== false) {
  10236. $onlyDirectory = str_replace(
  10237. 'upload/users/',
  10238. '',
  10239. substr($file_path, $pos, strlen($file_path))
  10240. );
  10241. }
  10242. $replace = $onlyDirectory;
  10243. $destinationFile = $replace;
  10244. }
  10245. $zip_files_abs[] = $file_path;
  10246. $link_updates[$my_file_path][] = [
  10247. 'orig' => $doc_info[0],
  10248. 'dest' => $destinationFile,
  10249. 'replace' => $replace,
  10250. ];
  10251. $my_dep_file->setAttribute('href', $file_path);
  10252. $my_dep->setAttribute('xml:base', '');
  10253. } elseif (empty($file_path)) {
  10254. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10255. $file_path = str_replace('//', '/', $file_path);
  10256. if (file_exists($file_path)) {
  10257. // We get the relative path.
  10258. $file_path = substr($file_path, strlen($current_dir));
  10259. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10260. $link_updates[$my_file_path][] = [
  10261. 'orig' => $doc_info[0],
  10262. 'dest' => $file_path,
  10263. ];
  10264. $my_dep_file->setAttribute('href', $file_path);
  10265. $my_dep->setAttribute('xml:base', '');
  10266. }
  10267. }
  10268. break;
  10269. case 'abs':
  10270. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10271. $my_dep_file->setAttribute('href', $doc_info[0]);
  10272. $my_dep->setAttribute('xml:base', '');
  10273. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10274. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10275. $abs_img_path_without_subdir = $doc_info[0];
  10276. $relp = api_get_path(REL_PATH); // The url-append config param.
  10277. $pos = strpos($abs_img_path_without_subdir, $relp);
  10278. if ($pos === 0) {
  10279. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10280. }
  10281. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10282. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10283. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10284. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10285. // Check if the current document is in that path.
  10286. if (strstr($file_path, $cur_path) !== false) {
  10287. $destinationFile = substr($file_path, strlen($cur_path));
  10288. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10289. $fileToTest = $cur_path.$my_file_path;
  10290. if (!empty($path_to_remove)) {
  10291. $fileToTest = str_replace(
  10292. $path_to_remove.'/',
  10293. $path_to_replace,
  10294. $cur_path.$my_file_path
  10295. );
  10296. }
  10297. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10298. // Put the current document in the zip (this array is the array
  10299. // that will manage documents already in the course folder - relative).
  10300. $zip_files[] = $filePathNoCoursePart;
  10301. // Update the links to the current document in the
  10302. // containing document (make them relative).
  10303. $link_updates[$my_file_path][] = [
  10304. 'orig' => $doc_info[0],
  10305. 'dest' => $destinationFile,
  10306. 'replace' => $relative_path,
  10307. ];
  10308. $my_dep_file->setAttribute('href', $file_path);
  10309. $my_dep->setAttribute('xml:base', '');
  10310. } elseif (strstr($file_path, $main_path) !== false) {
  10311. // The calculated real path is really inside Chamilo's root path.
  10312. // Reduce file path to what's under the DocumentRoot.
  10313. $file_path = substr($file_path, strlen($root_path));
  10314. $zip_files_abs[] = $file_path;
  10315. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10316. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10317. $my_dep->setAttribute('xml:base', '');
  10318. } elseif (empty($file_path)) {
  10319. // Probably this is an image inside "/main" directory
  10320. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10321. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10322. if (file_exists($file_path)) {
  10323. if (strstr($file_path, 'main/default_course_document') !== false) {
  10324. // We get the relative path.
  10325. $pos = strpos($file_path, 'main/default_course_document/');
  10326. if ($pos !== false) {
  10327. $onlyDirectory = str_replace(
  10328. 'main/default_course_document/',
  10329. '',
  10330. substr($file_path, $pos, strlen($file_path))
  10331. );
  10332. }
  10333. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10334. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10335. $zip_files_abs[] = $fileAbs;
  10336. $link_updates[$my_file_path][] = [
  10337. 'orig' => $doc_info[0],
  10338. 'dest' => $destinationFile,
  10339. ];
  10340. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10341. $my_dep->setAttribute('xml:base', '');
  10342. }
  10343. }
  10344. }
  10345. break;
  10346. case 'rel':
  10347. // Path relative to the current document.
  10348. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10349. if (substr($doc_info[0], 0, 2) === '..') {
  10350. // Relative path going up.
  10351. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10352. $current_dir = str_replace('\\', '/', $current_dir);
  10353. $file_path = realpath($current_dir.$doc_info[0]);
  10354. $file_path = str_replace('\\', '/', $file_path);
  10355. if (strstr($file_path, $main_path) !== false) {
  10356. // The calculated real path is really inside Chamilo's root path.
  10357. // Reduce file path to what's under the DocumentRoot.
  10358. $file_path = substr($file_path, strlen($root_path));
  10359. $zip_files_abs[] = $file_path;
  10360. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10361. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10362. $my_dep->setAttribute('xml:base', '');
  10363. }
  10364. } else {
  10365. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10366. $my_dep_file->setAttribute('href', $doc_info[0]);
  10367. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10368. }
  10369. break;
  10370. default:
  10371. $my_dep_file->setAttribute('href', $doc_info[0]);
  10372. $my_dep->setAttribute('xml:base', '');
  10373. break;
  10374. }
  10375. }
  10376. $my_dep->appendChild($my_dep_file);
  10377. $resources->appendChild($my_dep);
  10378. $dependency = $xmldoc->createElement('dependency');
  10379. $dependency->setAttribute('identifierref', $res_id);
  10380. $my_resource->appendChild($dependency);
  10381. $i++;
  10382. }
  10383. }
  10384. $resources->appendChild($my_resource);
  10385. $zip_files[] = $my_file_path;
  10386. } else {
  10387. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10388. switch ($item->type) {
  10389. case TOOL_LINK:
  10390. $my_item = $xmldoc->createElement('item');
  10391. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10392. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10393. $my_item->setAttribute('isvisible', 'true');
  10394. // Give a child element <title> to the <item> element.
  10395. $my_title = $xmldoc->createElement(
  10396. 'title',
  10397. htmlspecialchars(
  10398. api_utf8_encode($item->get_title()),
  10399. ENT_QUOTES,
  10400. 'UTF-8'
  10401. )
  10402. );
  10403. $my_item->appendChild($my_title);
  10404. // Give a child element <adlcp:prerequisites> to the <item> element.
  10405. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10406. $my_prereqs->setAttribute('type', 'aicc_script');
  10407. $my_item->appendChild($my_prereqs);
  10408. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10409. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10410. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10411. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10412. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10413. //$xmldoc->createElement('adlcp:datafromlms', '');
  10414. // Give a child element <adlcp:masteryscore> to the <item> element.
  10415. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10416. $my_item->appendChild($my_masteryscore);
  10417. // Attach this item to the organization element or its parent if there is one.
  10418. if (!empty($item->parent) && $item->parent != 0) {
  10419. $children = $organization->childNodes;
  10420. for ($i = 0; $i < $children->length; $i++) {
  10421. $item_temp = $children->item($i);
  10422. if ($item_temp->nodeName == 'item') {
  10423. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10424. $item_temp->appendChild($my_item);
  10425. }
  10426. }
  10427. }
  10428. } else {
  10429. $organization->appendChild($my_item);
  10430. }
  10431. $my_file_path = 'link_'.$item->get_id().'.html';
  10432. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10433. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10434. $rs = Database::query($sql);
  10435. if ($link = Database::fetch_array($rs)) {
  10436. $url = $link['url'];
  10437. $title = stripslashes($link['title']);
  10438. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10439. $my_xml_file_path = $my_file_path;
  10440. $my_sub_dir = dirname($my_file_path);
  10441. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10442. $my_xml_sub_dir = $my_sub_dir;
  10443. // Give a <resource> child to the <resources> element.
  10444. $my_resource = $xmldoc->createElement('resource');
  10445. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10446. $my_resource->setAttribute('type', 'webcontent');
  10447. $my_resource->setAttribute('href', $my_xml_file_path);
  10448. // adlcp:scormtype can be either 'sco' or 'asset'.
  10449. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10450. // xml:base is the base directory to find the files declared in this resource.
  10451. $my_resource->setAttribute('xml:base', '');
  10452. // give a <file> child to the <resource> element.
  10453. $my_file = $xmldoc->createElement('file');
  10454. $my_file->setAttribute('href', $my_xml_file_path);
  10455. $my_resource->appendChild($my_file);
  10456. $resources->appendChild($my_resource);
  10457. }
  10458. break;
  10459. case TOOL_QUIZ:
  10460. $exe_id = $item->path;
  10461. // Should be using ref when everything will be cleaned up in this regard.
  10462. $exe = new Exercise();
  10463. $exe->read($exe_id);
  10464. $my_item = $xmldoc->createElement('item');
  10465. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10466. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10467. $my_item->setAttribute('isvisible', 'true');
  10468. // Give a child element <title> to the <item> element.
  10469. $my_title = $xmldoc->createElement(
  10470. 'title',
  10471. htmlspecialchars(
  10472. api_utf8_encode($item->get_title()),
  10473. ENT_QUOTES,
  10474. 'UTF-8'
  10475. )
  10476. );
  10477. $my_item->appendChild($my_title);
  10478. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10479. $my_item->appendChild($my_max_score);
  10480. // Give a child element <adlcp:prerequisites> to the <item> element.
  10481. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10482. $my_prereqs->setAttribute('type', 'aicc_script');
  10483. $my_item->appendChild($my_prereqs);
  10484. // Give a child element <adlcp:masteryscore> to the <item> element.
  10485. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10486. $my_item->appendChild($my_masteryscore);
  10487. // Attach this item to the organization element or hits parent if there is one.
  10488. if (!empty($item->parent) && $item->parent != 0) {
  10489. $children = $organization->childNodes;
  10490. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10491. if ($possible_parent) {
  10492. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10493. $possible_parent->appendChild($my_item);
  10494. }
  10495. }
  10496. } else {
  10497. $organization->appendChild($my_item);
  10498. }
  10499. // Get the path of the file(s) from the course directory root
  10500. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10501. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10502. // Write the contents of the exported exercise into a (big) html file
  10503. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10504. $scormExercise = new ScormExercise($exe, true);
  10505. $contents = $scormExercise->export();
  10506. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10507. $res = file_put_contents($tmp_file_path, $contents);
  10508. if ($res === false) {
  10509. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10510. }
  10511. $files_cleanup[] = $tmp_file_path;
  10512. $my_xml_file_path = $my_file_path;
  10513. $my_sub_dir = dirname($my_file_path);
  10514. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10515. $my_xml_sub_dir = $my_sub_dir;
  10516. // Give a <resource> child to the <resources> element.
  10517. $my_resource = $xmldoc->createElement('resource');
  10518. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10519. $my_resource->setAttribute('type', 'webcontent');
  10520. $my_resource->setAttribute('href', $my_xml_file_path);
  10521. // adlcp:scormtype can be either 'sco' or 'asset'.
  10522. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10523. // xml:base is the base directory to find the files declared in this resource.
  10524. $my_resource->setAttribute('xml:base', '');
  10525. // Give a <file> child to the <resource> element.
  10526. $my_file = $xmldoc->createElement('file');
  10527. $my_file->setAttribute('href', $my_xml_file_path);
  10528. $my_resource->appendChild($my_file);
  10529. // Get included docs.
  10530. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10531. // Dependency to other files - not yet supported.
  10532. $i = 1;
  10533. foreach ($inc_docs as $doc_info) {
  10534. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10535. continue;
  10536. }
  10537. $my_dep = $xmldoc->createElement('resource');
  10538. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10539. $my_dep->setAttribute('identifier', $res_id);
  10540. $my_dep->setAttribute('type', 'webcontent');
  10541. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10542. $my_dep_file = $xmldoc->createElement('file');
  10543. // Check type of URL.
  10544. if ($doc_info[1] == 'remote') {
  10545. // Remote file. Save url as is.
  10546. $my_dep_file->setAttribute('href', $doc_info[0]);
  10547. $my_dep->setAttribute('xml:base', '');
  10548. } elseif ($doc_info[1] == 'local') {
  10549. switch ($doc_info[2]) {
  10550. case 'url': // Local URL - save path as url for now, don't zip file.
  10551. // Save file but as local file (retrieve from URL).
  10552. $abs_path = api_get_path(SYS_PATH).
  10553. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10554. $current_dir = dirname($abs_path);
  10555. $current_dir = str_replace('\\', '/', $current_dir);
  10556. $file_path = realpath($abs_path);
  10557. $file_path = str_replace('\\', '/', $file_path);
  10558. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10559. $my_dep->setAttribute('xml:base', '');
  10560. if (strstr($file_path, $main_path) !== false) {
  10561. // The calculated real path is really inside the chamilo root path.
  10562. // Reduce file path to what's under the DocumentRoot.
  10563. $file_path = substr($file_path, strlen($root_path));
  10564. $zip_files_abs[] = $file_path;
  10565. $link_updates[$my_file_path][] = [
  10566. 'orig' => $doc_info[0],
  10567. 'dest' => 'document/'.$file_path,
  10568. ];
  10569. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10570. $my_dep->setAttribute('xml:base', '');
  10571. } elseif (empty($file_path)) {
  10572. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10573. $file_path = str_replace('//', '/', $file_path);
  10574. if (file_exists($file_path)) {
  10575. $file_path = substr($file_path, strlen($current_dir));
  10576. // We get the relative path.
  10577. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10578. $link_updates[$my_file_path][] = [
  10579. 'orig' => $doc_info[0],
  10580. 'dest' => 'document/'.$file_path,
  10581. ];
  10582. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10583. $my_dep->setAttribute('xml:base', '');
  10584. }
  10585. }
  10586. break;
  10587. case 'abs':
  10588. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10589. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10590. $current_dir = str_replace('\\', '/', $current_dir);
  10591. $file_path = realpath($doc_info[0]);
  10592. $file_path = str_replace('\\', '/', $file_path);
  10593. $my_dep_file->setAttribute('href', $file_path);
  10594. $my_dep->setAttribute('xml:base', '');
  10595. if (strstr($file_path, $main_path) !== false) {
  10596. // The calculated real path is really inside the chamilo root path.
  10597. // Reduce file path to what's under the DocumentRoot.
  10598. $file_path = substr($file_path, strlen($root_path));
  10599. $zip_files_abs[] = $file_path;
  10600. $link_updates[$my_file_path][] = [
  10601. 'orig' => $doc_info[0],
  10602. 'dest' => $file_path,
  10603. ];
  10604. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10605. $my_dep->setAttribute('xml:base', '');
  10606. } elseif (empty($file_path)) {
  10607. $docSysPartPath = str_replace(
  10608. api_get_path(REL_COURSE_PATH),
  10609. '',
  10610. $doc_info[0]
  10611. );
  10612. $docSysPartPathNoCourseCode = str_replace(
  10613. $_course['directory'].'/',
  10614. '',
  10615. $docSysPartPath
  10616. );
  10617. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10618. if (file_exists($docSysPath)) {
  10619. $file_path = $docSysPartPathNoCourseCode;
  10620. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10621. $link_updates[$my_file_path][] = [
  10622. 'orig' => $doc_info[0],
  10623. 'dest' => $file_path,
  10624. ];
  10625. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10626. $my_dep->setAttribute('xml:base', '');
  10627. }
  10628. }
  10629. break;
  10630. case 'rel':
  10631. // Path relative to the current document. Save xml:base as current document's
  10632. // directory and save file in zip as subdir.file_path
  10633. if (substr($doc_info[0], 0, 2) === '..') {
  10634. // Relative path going up.
  10635. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10636. $current_dir = str_replace('\\', '/', $current_dir);
  10637. $file_path = realpath($current_dir.$doc_info[0]);
  10638. $file_path = str_replace('\\', '/', $file_path);
  10639. //error_log($file_path.' <-> '.$main_path, 0);
  10640. if (strstr($file_path, $main_path) !== false) {
  10641. // The calculated real path is really inside Chamilo's root path.
  10642. // Reduce file path to what's under the DocumentRoot.
  10643. $file_path = substr($file_path, strlen($root_path));
  10644. $file_path_dest = $file_path;
  10645. // File path is courses/CHAMILO/document/....
  10646. $info_file_path = explode('/', $file_path);
  10647. if ($info_file_path[0] == 'courses') {
  10648. // Add character "/" in file path.
  10649. $file_path_dest = 'document/'.$file_path;
  10650. }
  10651. $zip_files_abs[] = $file_path;
  10652. $link_updates[$my_file_path][] = [
  10653. 'orig' => $doc_info[0],
  10654. 'dest' => $file_path_dest,
  10655. ];
  10656. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10657. $my_dep->setAttribute('xml:base', '');
  10658. }
  10659. } else {
  10660. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10661. $my_dep_file->setAttribute('href', $doc_info[0]);
  10662. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10663. }
  10664. break;
  10665. default:
  10666. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10667. $my_dep->setAttribute('xml:base', '');
  10668. break;
  10669. }
  10670. }
  10671. $my_dep->appendChild($my_dep_file);
  10672. $resources->appendChild($my_dep);
  10673. $dependency = $xmldoc->createElement('dependency');
  10674. $dependency->setAttribute('identifierref', $res_id);
  10675. $my_resource->appendChild($dependency);
  10676. $i++;
  10677. }
  10678. $resources->appendChild($my_resource);
  10679. $zip_files[] = $my_file_path;
  10680. break;
  10681. default:
  10682. // Get the path of the file(s) from the course directory root
  10683. $my_file_path = 'non_exportable.html';
  10684. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10685. $my_xml_file_path = $my_file_path;
  10686. $my_sub_dir = dirname($my_file_path);
  10687. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10688. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10689. $my_xml_sub_dir = $my_sub_dir;
  10690. // Give a <resource> child to the <resources> element.
  10691. $my_resource = $xmldoc->createElement('resource');
  10692. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10693. $my_resource->setAttribute('type', 'webcontent');
  10694. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10695. // adlcp:scormtype can be either 'sco' or 'asset'.
  10696. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10697. // xml:base is the base directory to find the files declared in this resource.
  10698. $my_resource->setAttribute('xml:base', '');
  10699. // Give a <file> child to the <resource> element.
  10700. $my_file = $xmldoc->createElement('file');
  10701. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10702. $my_resource->appendChild($my_file);
  10703. $resources->appendChild($my_resource);
  10704. break;
  10705. }
  10706. }
  10707. }
  10708. $organizations->appendChild($organization);
  10709. $root->appendChild($organizations);
  10710. $root->appendChild($resources);
  10711. $xmldoc->appendChild($root);
  10712. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10713. // then add the file to the zip, then destroy the file (this is done automatically).
  10714. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10715. foreach ($zip_files as $file_path) {
  10716. if (empty($file_path)) {
  10717. continue;
  10718. }
  10719. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10720. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10721. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10722. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10723. }
  10724. $this->create_path($dest_file);
  10725. @copy($filePath, $dest_file);
  10726. // Check if the file needs a link update.
  10727. if (in_array($file_path, array_keys($link_updates))) {
  10728. $string = file_get_contents($dest_file);
  10729. unlink($dest_file);
  10730. foreach ($link_updates[$file_path] as $old_new) {
  10731. // This is an ugly hack that allows .flv files to be found by the flv player that
  10732. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10733. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10734. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10735. if (substr($old_new['dest'], -3) === 'flv' &&
  10736. substr($old_new['dest'], 0, 5) === 'main/'
  10737. ) {
  10738. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10739. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10740. substr($old_new['dest'], 0, 6) === 'video/'
  10741. ) {
  10742. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10743. }
  10744. // Fix to avoid problems with default_course_document
  10745. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10746. $newDestination = $old_new['dest'];
  10747. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10748. $newDestination = $old_new['replace'];
  10749. }
  10750. } else {
  10751. $newDestination = str_replace('document/', '', $old_new['dest']);
  10752. }
  10753. $string = str_replace($old_new['orig'], $newDestination, $string);
  10754. // Add files inside the HTMLs
  10755. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10756. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10757. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10758. copy(
  10759. $sys_course_path.$new_path,
  10760. $destinationFile
  10761. );
  10762. }
  10763. }
  10764. file_put_contents($dest_file, $string);
  10765. }
  10766. if (file_exists($filePath) && $copyAll) {
  10767. $extension = $this->get_extension($filePath);
  10768. if (in_array($extension, ['html', 'html'])) {
  10769. $containerOrigin = dirname($filePath);
  10770. $containerDestination = dirname($dest_file);
  10771. $finder = new Finder();
  10772. $finder->files()->in($containerOrigin)
  10773. ->notName('*_DELETED_*')
  10774. ->exclude('share_folder')
  10775. ->exclude('chat_files')
  10776. ->exclude('certificates')
  10777. ;
  10778. if (is_dir($containerOrigin) &&
  10779. is_dir($containerDestination)
  10780. ) {
  10781. $fs = new Filesystem();
  10782. $fs->mirror(
  10783. $containerOrigin,
  10784. $containerDestination,
  10785. $finder
  10786. );
  10787. }
  10788. }
  10789. }
  10790. }
  10791. foreach ($zip_files_abs as $file_path) {
  10792. if (empty($file_path)) {
  10793. continue;
  10794. }
  10795. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10796. continue;
  10797. }
  10798. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10799. if (strstr($file_path, 'upload/users') !== false) {
  10800. $pos = strpos($file_path, 'my_files/');
  10801. if ($pos !== false) {
  10802. $onlyDirectory = str_replace(
  10803. 'upload/users/',
  10804. '',
  10805. substr($file_path, $pos, strlen($file_path))
  10806. );
  10807. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10808. }
  10809. }
  10810. if (strstr($file_path, 'default_course_document/') !== false) {
  10811. $replace = str_replace('/main', '', $file_path);
  10812. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10813. }
  10814. if (empty($dest_file)) {
  10815. continue;
  10816. }
  10817. $this->create_path($dest_file);
  10818. copy($main_path.$file_path, $dest_file);
  10819. // Check if the file needs a link update.
  10820. if (in_array($file_path, array_keys($link_updates))) {
  10821. $string = file_get_contents($dest_file);
  10822. unlink($dest_file);
  10823. foreach ($link_updates[$file_path] as $old_new) {
  10824. // This is an ugly hack that allows .flv files to be found by the flv player that
  10825. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10826. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10827. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10828. if (substr($old_new['dest'], -3) == 'flv' &&
  10829. substr($old_new['dest'], 0, 5) == 'main/'
  10830. ) {
  10831. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10832. }
  10833. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10834. }
  10835. file_put_contents($dest_file, $string);
  10836. }
  10837. }
  10838. if (is_array($links_to_create)) {
  10839. foreach ($links_to_create as $file => $link) {
  10840. $content = '<!DOCTYPE html><head>
  10841. <meta charset="'.api_get_language_isocode().'" />
  10842. <title>'.$link['title'].'</title>
  10843. </head>
  10844. <body dir="'.api_get_text_direction().'">
  10845. <div style="text-align:center">
  10846. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10847. </body>
  10848. </html>';
  10849. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10850. }
  10851. }
  10852. // Add non exportable message explanation.
  10853. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10854. $file_content = '<!DOCTYPE html><head>
  10855. <meta charset="'.api_get_language_isocode().'" />
  10856. <title>'.$lang_not_exportable.'</title>
  10857. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10858. </head>
  10859. <body dir="'.api_get_text_direction().'">';
  10860. $file_content .=
  10861. <<<EOD
  10862. <style>
  10863. .error-message {
  10864. font-family: arial, verdana, helvetica, sans-serif;
  10865. border-width: 1px;
  10866. border-style: solid;
  10867. left: 50%;
  10868. margin: 10px auto;
  10869. min-height: 30px;
  10870. padding: 5px;
  10871. right: 50%;
  10872. width: 500px;
  10873. background-color: #FFD1D1;
  10874. border-color: #FF0000;
  10875. color: #000;
  10876. }
  10877. </style>
  10878. <body>
  10879. <div class="error-message">
  10880. $lang_not_exportable
  10881. </div>
  10882. </body>
  10883. </html>
  10884. EOD;
  10885. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10886. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10887. }
  10888. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10889. // Add the extra files that go along with a SCORM package.
  10890. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10891. $fs = new Filesystem();
  10892. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10893. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10894. $manifest = @$xmldoc->saveXML();
  10895. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10896. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10897. $zip_folder->add(
  10898. $archivePath.'/'.$temp_dir_short,
  10899. PCLZIP_OPT_REMOVE_PATH,
  10900. $archivePath.'/'.$temp_dir_short.'/'
  10901. );
  10902. // Clean possible temporary files.
  10903. foreach ($files_cleanup as $file) {
  10904. $res = unlink($file);
  10905. if ($res === false) {
  10906. error_log(
  10907. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10908. 0
  10909. );
  10910. }
  10911. }
  10912. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10913. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10914. }
  10915. /**
  10916. * @param int $lp_id
  10917. *
  10918. * @return bool
  10919. */
  10920. public function scorm_export_to_pdf($lp_id)
  10921. {
  10922. $lp_id = (int) $lp_id;
  10923. $files_to_export = [];
  10924. $course_data = api_get_course_info($this->cc);
  10925. if (!empty($course_data)) {
  10926. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10927. $list = self::get_flat_ordered_items_list($lp_id);
  10928. if (!empty($list)) {
  10929. foreach ($list as $item_id) {
  10930. $item = $this->items[$item_id];
  10931. switch ($item->type) {
  10932. case 'document':
  10933. //Getting documents from a LP with chamilo documents
  10934. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10935. // Try loading document from the base course.
  10936. if (empty($file_data) && !empty($sessionId)) {
  10937. $file_data = DocumentManager::get_document_data_by_id(
  10938. $item->path,
  10939. $this->cc,
  10940. false,
  10941. 0
  10942. );
  10943. }
  10944. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10945. if (file_exists($file_path)) {
  10946. $files_to_export[] = [
  10947. 'title' => $item->get_title(),
  10948. 'path' => $file_path,
  10949. ];
  10950. }
  10951. break;
  10952. case 'asset': //commes from a scorm package generated by chamilo
  10953. case 'sco':
  10954. $file_path = $scorm_path.'/'.$item->path;
  10955. if (file_exists($file_path)) {
  10956. $files_to_export[] = [
  10957. 'title' => $item->get_title(),
  10958. 'path' => $file_path,
  10959. ];
  10960. }
  10961. break;
  10962. case 'dir':
  10963. $files_to_export[] = [
  10964. 'title' => $item->get_title(),
  10965. 'path' => null,
  10966. ];
  10967. break;
  10968. }
  10969. }
  10970. }
  10971. $pdf = new PDF();
  10972. $result = $pdf->html_to_pdf(
  10973. $files_to_export,
  10974. $this->name,
  10975. $this->cc,
  10976. true
  10977. );
  10978. return $result;
  10979. }
  10980. return false;
  10981. }
  10982. /**
  10983. * Temp function to be moved in main_api or the best place around for this.
  10984. * Creates a file path if it doesn't exist.
  10985. *
  10986. * @param string $path
  10987. */
  10988. public function create_path($path)
  10989. {
  10990. $path_bits = explode('/', dirname($path));
  10991. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10992. $path_built = IS_WINDOWS_OS ? '' : '/';
  10993. foreach ($path_bits as $bit) {
  10994. if (!empty($bit)) {
  10995. $new_path = $path_built.$bit;
  10996. if (is_dir($new_path)) {
  10997. $path_built = $new_path.'/';
  10998. } else {
  10999. mkdir($new_path, api_get_permissions_for_new_directories());
  11000. $path_built = $new_path.'/';
  11001. }
  11002. }
  11003. }
  11004. }
  11005. /**
  11006. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  11007. *
  11008. * @return bool The results of the unlink function, or false if there was no image to start with
  11009. */
  11010. public function delete_lp_image()
  11011. {
  11012. $img = $this->get_preview_image();
  11013. if ($img != '') {
  11014. $del_file = $this->get_preview_image_path(null, 'sys');
  11015. if (isset($del_file) && file_exists($del_file)) {
  11016. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  11017. if (file_exists($del_file_2)) {
  11018. unlink($del_file_2);
  11019. }
  11020. $this->set_preview_image('');
  11021. return @unlink($del_file);
  11022. }
  11023. }
  11024. return false;
  11025. }
  11026. /**
  11027. * Uploads an author image to the upload/learning_path/images directory.
  11028. *
  11029. * @param array The image array, coming from the $_FILES superglobal
  11030. *
  11031. * @return bool True on success, false on error
  11032. */
  11033. public function upload_image($image_array)
  11034. {
  11035. if (!empty($image_array['name'])) {
  11036. $upload_ok = process_uploaded_file($image_array);
  11037. $has_attachment = true;
  11038. }
  11039. if ($upload_ok && $has_attachment) {
  11040. $courseDir = api_get_course_path().'/upload/learning_path/images';
  11041. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  11042. $updir = $sys_course_path.$courseDir;
  11043. // Try to add an extension to the file if it hasn't one.
  11044. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  11045. if (filter_extension($new_file_name)) {
  11046. $file_extension = explode('.', $image_array['name']);
  11047. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  11048. $filename = uniqid('');
  11049. $new_file_name = $filename.'.'.$file_extension;
  11050. $new_path = $updir.'/'.$new_file_name;
  11051. // Resize the image.
  11052. $temp = new Image($image_array['tmp_name']);
  11053. $temp->resize(104);
  11054. $result = $temp->send_image($new_path);
  11055. // Storing the image filename.
  11056. if ($result) {
  11057. $this->set_preview_image($new_file_name);
  11058. //Resize to 64px to use on course homepage
  11059. $temp->resize(64);
  11060. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11061. return true;
  11062. }
  11063. }
  11064. }
  11065. return false;
  11066. }
  11067. /**
  11068. * @param int $lp_id
  11069. * @param string $status
  11070. */
  11071. public function set_autolaunch($lp_id, $status)
  11072. {
  11073. $course_id = api_get_course_int_id();
  11074. $lp_id = intval($lp_id);
  11075. $status = intval($status);
  11076. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11077. // Setting everything to autolaunch = 0
  11078. $attributes['autolaunch'] = 0;
  11079. $where = [
  11080. 'session_id = ? AND c_id = ? ' => [
  11081. api_get_session_id(),
  11082. $course_id,
  11083. ],
  11084. ];
  11085. Database::update($lp_table, $attributes, $where);
  11086. if ($status == 1) {
  11087. //Setting my lp_id to autolaunch = 1
  11088. $attributes['autolaunch'] = 1;
  11089. $where = [
  11090. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11091. $lp_id,
  11092. api_get_session_id(),
  11093. $course_id,
  11094. ],
  11095. ];
  11096. Database::update($lp_table, $attributes, $where);
  11097. }
  11098. }
  11099. /**
  11100. * Gets previous_item_id for the next element of the lp_item table.
  11101. *
  11102. * @author Isaac flores paz
  11103. *
  11104. * @return int Previous item ID
  11105. */
  11106. public function select_previous_item_id()
  11107. {
  11108. $course_id = api_get_course_int_id();
  11109. if ($this->debug > 0) {
  11110. error_log('In learnpath::select_previous_item_id()', 0);
  11111. }
  11112. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11113. // Get the max order of the items
  11114. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11115. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11116. $rs_max_order = Database::query($sql);
  11117. $row_max_order = Database::fetch_object($rs_max_order);
  11118. $max_order = $row_max_order->display_order;
  11119. // Get the previous item ID
  11120. $sql = "SELECT iid as previous FROM $table_lp_item
  11121. WHERE
  11122. c_id = $course_id AND
  11123. lp_id = ".$this->lp_id." AND
  11124. display_order = '$max_order' ";
  11125. $rs_max = Database::query($sql);
  11126. $row_max = Database::fetch_object($rs_max);
  11127. // Return the previous item ID
  11128. return $row_max->previous;
  11129. }
  11130. /**
  11131. * Copies an LP.
  11132. */
  11133. public function copy()
  11134. {
  11135. // Course builder
  11136. $cb = new CourseBuilder();
  11137. //Setting tools that will be copied
  11138. $cb->set_tools_to_build(['learnpaths']);
  11139. //Setting elements that will be copied
  11140. $cb->set_tools_specific_id_list(
  11141. ['learnpaths' => [$this->lp_id]]
  11142. );
  11143. $course = $cb->build();
  11144. //Course restorer
  11145. $course_restorer = new CourseRestorer($course);
  11146. $course_restorer->set_add_text_in_items(true);
  11147. $course_restorer->set_tool_copy_settings(
  11148. ['learnpaths' => ['reset_dates' => true]]
  11149. );
  11150. $course_restorer->restore(
  11151. api_get_course_id(),
  11152. api_get_session_id(),
  11153. false,
  11154. false
  11155. );
  11156. }
  11157. /**
  11158. * Verify document size.
  11159. *
  11160. * @param string $s
  11161. *
  11162. * @return bool
  11163. */
  11164. public static function verify_document_size($s)
  11165. {
  11166. $post_max = ini_get('post_max_size');
  11167. if (substr($post_max, -1, 1) == 'M') {
  11168. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11169. } elseif (substr($post_max, -1, 1) == 'G') {
  11170. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11171. }
  11172. $upl_max = ini_get('upload_max_filesize');
  11173. if (substr($upl_max, -1, 1) == 'M') {
  11174. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11175. } elseif (substr($upl_max, -1, 1) == 'G') {
  11176. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11177. }
  11178. $documents_total_space = DocumentManager::documents_total_space();
  11179. $course_max_space = DocumentManager::get_course_quota();
  11180. $total_size = filesize($s) + $documents_total_space;
  11181. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11182. return true;
  11183. } else {
  11184. return false;
  11185. }
  11186. }
  11187. /**
  11188. * Clear LP prerequisites.
  11189. */
  11190. public function clear_prerequisites()
  11191. {
  11192. $course_id = $this->get_course_int_id();
  11193. if ($this->debug > 0) {
  11194. error_log('In learnpath::clear_prerequisites()', 0);
  11195. }
  11196. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11197. $lp_id = $this->get_id();
  11198. //Cleaning prerequisites
  11199. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11200. WHERE c_id = $course_id AND lp_id = $lp_id";
  11201. Database::query($sql);
  11202. //Cleaning mastery score for exercises
  11203. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11204. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11205. Database::query($sql);
  11206. }
  11207. public function set_previous_step_as_prerequisite_for_all_items()
  11208. {
  11209. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11210. $course_id = $this->get_course_int_id();
  11211. $lp_id = $this->get_id();
  11212. if (!empty($this->items)) {
  11213. $previous_item_id = null;
  11214. $previous_item_max = 0;
  11215. $previous_item_type = null;
  11216. $last_item_not_dir = null;
  11217. $last_item_not_dir_type = null;
  11218. $last_item_not_dir_max = null;
  11219. foreach ($this->ordered_items as $itemId) {
  11220. $item = $this->getItem($itemId);
  11221. // if there was a previous item... (otherwise jump to set it)
  11222. if (!empty($previous_item_id)) {
  11223. $current_item_id = $item->get_id(); //save current id
  11224. if ($item->get_type() != 'dir') {
  11225. // Current item is not a folder, so it qualifies to get a prerequisites
  11226. if ($last_item_not_dir_type == 'quiz') {
  11227. // if previous is quiz, mark its max score as default score to be achieved
  11228. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11229. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11230. Database::query($sql);
  11231. }
  11232. // now simply update the prerequisite to set it to the last non-chapter item
  11233. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11234. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11235. Database::query($sql);
  11236. // record item as 'non-chapter' reference
  11237. $last_item_not_dir = $item->get_id();
  11238. $last_item_not_dir_type = $item->get_type();
  11239. $last_item_not_dir_max = $item->get_max();
  11240. }
  11241. } else {
  11242. if ($item->get_type() != 'dir') {
  11243. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11244. $last_item_not_dir = $item->get_id();
  11245. $last_item_not_dir_type = $item->get_type();
  11246. $last_item_not_dir_max = $item->get_max();
  11247. }
  11248. }
  11249. // Saving the item as "previous item" for the next loop
  11250. $previous_item_id = $item->get_id();
  11251. $previous_item_max = $item->get_max();
  11252. $previous_item_type = $item->get_type();
  11253. }
  11254. }
  11255. }
  11256. /**
  11257. * @param array $params
  11258. *
  11259. * @throws \Doctrine\ORM\OptimisticLockException
  11260. *
  11261. * @return int
  11262. */
  11263. public static function createCategory($params)
  11264. {
  11265. $em = Database::getManager();
  11266. $item = new CLpCategory();
  11267. $item->setName($params['name']);
  11268. $item->setCId($params['c_id']);
  11269. $em->persist($item);
  11270. $em->flush();
  11271. api_item_property_update(
  11272. api_get_course_info(),
  11273. TOOL_LEARNPATH_CATEGORY,
  11274. $item->getId(),
  11275. 'visible',
  11276. api_get_user_id()
  11277. );
  11278. return $item->getId();
  11279. }
  11280. /**
  11281. * @param array $params
  11282. *
  11283. * @throws \Doctrine\ORM\ORMException
  11284. * @throws \Doctrine\ORM\OptimisticLockException
  11285. * @throws \Doctrine\ORM\TransactionRequiredException
  11286. */
  11287. public static function updateCategory($params)
  11288. {
  11289. $em = Database::getManager();
  11290. /** @var CLpCategory $item */
  11291. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11292. if ($item) {
  11293. $item->setName($params['name']);
  11294. $em->merge($item);
  11295. $em->flush();
  11296. }
  11297. }
  11298. /**
  11299. * @param int $id
  11300. *
  11301. * @throws \Doctrine\ORM\ORMException
  11302. * @throws \Doctrine\ORM\OptimisticLockException
  11303. * @throws \Doctrine\ORM\TransactionRequiredException
  11304. */
  11305. public static function moveUpCategory($id)
  11306. {
  11307. $id = (int) $id;
  11308. $em = Database::getManager();
  11309. /** @var CLpCategory $item */
  11310. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11311. if ($item) {
  11312. $position = $item->getPosition() - 1;
  11313. $item->setPosition($position);
  11314. $em->persist($item);
  11315. $em->flush();
  11316. }
  11317. }
  11318. /**
  11319. * @param int $id
  11320. *
  11321. * @throws \Doctrine\ORM\ORMException
  11322. * @throws \Doctrine\ORM\OptimisticLockException
  11323. * @throws \Doctrine\ORM\TransactionRequiredException
  11324. */
  11325. public static function moveDownCategory($id)
  11326. {
  11327. $id = (int) $id;
  11328. $em = Database::getManager();
  11329. /** @var CLpCategory $item */
  11330. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11331. if ($item) {
  11332. $position = $item->getPosition() + 1;
  11333. $item->setPosition($position);
  11334. $em->persist($item);
  11335. $em->flush();
  11336. }
  11337. }
  11338. /**
  11339. * @param int $courseId
  11340. *
  11341. * @throws \Doctrine\ORM\Query\QueryException
  11342. *
  11343. * @return int|mixed
  11344. */
  11345. public static function getCountCategories($courseId)
  11346. {
  11347. if (empty($courseId)) {
  11348. return 0;
  11349. }
  11350. $em = Database::getManager();
  11351. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11352. $query->setParameter('id', $courseId);
  11353. return $query->getSingleScalarResult();
  11354. }
  11355. /**
  11356. * @param int $courseId
  11357. *
  11358. * @return mixed
  11359. */
  11360. public static function getCategories($courseId)
  11361. {
  11362. $em = Database::getManager();
  11363. //Default behaviour
  11364. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11365. array('cId' => $course_id),
  11366. array('name' => 'ASC')
  11367. );*/
  11368. // Using doctrine extensions
  11369. /** @var SortableRepository $repo */
  11370. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11371. $items = $repo
  11372. ->getBySortableGroupsQuery(['cId' => $courseId])
  11373. ->getResult();
  11374. return $items;
  11375. }
  11376. /**
  11377. * @param int $id
  11378. *
  11379. * @throws \Doctrine\ORM\ORMException
  11380. * @throws \Doctrine\ORM\OptimisticLockException
  11381. * @throws \Doctrine\ORM\TransactionRequiredException
  11382. *
  11383. * @return CLpCategory
  11384. */
  11385. public static function getCategory($id)
  11386. {
  11387. $id = (int) $id;
  11388. $em = Database::getManager();
  11389. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11390. return $item;
  11391. }
  11392. /**
  11393. * @param int $courseId
  11394. *
  11395. * @return array
  11396. */
  11397. public static function getCategoryByCourse($courseId)
  11398. {
  11399. $em = Database::getManager();
  11400. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11401. ['cId' => $courseId]
  11402. );
  11403. return $items;
  11404. }
  11405. /**
  11406. * @param int $id
  11407. *
  11408. * @throws \Doctrine\ORM\ORMException
  11409. * @throws \Doctrine\ORM\OptimisticLockException
  11410. * @throws \Doctrine\ORM\TransactionRequiredException
  11411. *
  11412. * @return mixed
  11413. */
  11414. public static function deleteCategory($id)
  11415. {
  11416. $em = Database::getManager();
  11417. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11418. if ($item) {
  11419. $courseId = $item->getCId();
  11420. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11421. $query->setParameter('id', $courseId);
  11422. $query->setParameter('catId', $item->getId());
  11423. $lps = $query->getResult();
  11424. // Setting category = 0.
  11425. if ($lps) {
  11426. foreach ($lps as $lpItem) {
  11427. $lpItem->setCategoryId(0);
  11428. }
  11429. }
  11430. // Removing category.
  11431. $em->remove($item);
  11432. $em->flush();
  11433. $courseInfo = api_get_course_info_by_id($courseId);
  11434. $sessionId = api_get_session_id();
  11435. // Delete link tool
  11436. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11437. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11438. // Delete tools
  11439. $sql = "DELETE FROM $tbl_tool
  11440. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11441. Database::query($sql);
  11442. }
  11443. }
  11444. /**
  11445. * @param int $courseId
  11446. * @param bool $addSelectOption
  11447. *
  11448. * @return mixed
  11449. */
  11450. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11451. {
  11452. $items = self::getCategoryByCourse($courseId);
  11453. $cats = [];
  11454. if ($addSelectOption) {
  11455. $cats = [get_lang('SelectACategory')];
  11456. }
  11457. if (!empty($items)) {
  11458. foreach ($items as $cat) {
  11459. $cats[$cat->getId()] = $cat->getName();
  11460. }
  11461. }
  11462. return $cats;
  11463. }
  11464. /**
  11465. * @param string $courseCode
  11466. * @param int $lpId
  11467. * @param int $user_id
  11468. *
  11469. * @return learnpath
  11470. */
  11471. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11472. {
  11473. $debug = 0;
  11474. $learnPath = null;
  11475. $lpObject = Session::read('lpobject');
  11476. if ($lpObject !== null) {
  11477. $learnPath = unserialize($lpObject);
  11478. if ($debug) {
  11479. error_log('getLpFromSession: unserialize');
  11480. error_log('------getLpFromSession------');
  11481. error_log('------unserialize------');
  11482. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11483. error_log("api_get_sessionid: ".api_get_session_id());
  11484. }
  11485. }
  11486. if (!is_object($learnPath)) {
  11487. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11488. if ($debug) {
  11489. error_log('------getLpFromSession------');
  11490. error_log('getLpFromSession: create new learnpath');
  11491. error_log("create new LP with $courseCode - $lpId - $user_id");
  11492. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11493. error_log("api_get_sessionid: ".api_get_session_id());
  11494. }
  11495. }
  11496. return $learnPath;
  11497. }
  11498. /**
  11499. * @param int $itemId
  11500. *
  11501. * @return learnpathItem|false
  11502. */
  11503. public function getItem($itemId)
  11504. {
  11505. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11506. return $this->items[$itemId];
  11507. }
  11508. return false;
  11509. }
  11510. /**
  11511. * @return int
  11512. */
  11513. public function getCategoryId()
  11514. {
  11515. return (int) $this->categoryId;
  11516. }
  11517. /**
  11518. * @param int $categoryId
  11519. *
  11520. * @return bool
  11521. */
  11522. public function setCategoryId($categoryId)
  11523. {
  11524. $this->categoryId = (int) $categoryId;
  11525. $table = Database::get_course_table(TABLE_LP_MAIN);
  11526. $lp_id = $this->get_id();
  11527. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11528. WHERE iid = $lp_id";
  11529. Database::query($sql);
  11530. return true;
  11531. }
  11532. /**
  11533. * Get whether this is a learning path with the possibility to subscribe
  11534. * users or not.
  11535. *
  11536. * @return int
  11537. */
  11538. public function getSubscribeUsers()
  11539. {
  11540. return $this->subscribeUsers;
  11541. }
  11542. /**
  11543. * Set whether this is a learning path with the possibility to subscribe
  11544. * users or not.
  11545. *
  11546. * @param int $value (0 = false, 1 = true)
  11547. *
  11548. * @return bool
  11549. */
  11550. public function setSubscribeUsers($value)
  11551. {
  11552. if ($this->debug > 0) {
  11553. error_log('In learnpath::set_subscribe_users()', 0);
  11554. }
  11555. $this->subscribeUsers = (int) $value;
  11556. $table = Database::get_course_table(TABLE_LP_MAIN);
  11557. $lp_id = $this->get_id();
  11558. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11559. WHERE iid = $lp_id";
  11560. Database::query($sql);
  11561. return true;
  11562. }
  11563. /**
  11564. * Calculate the count of stars for a user in this LP
  11565. * This calculation is based on the following rules:
  11566. * - the student gets one star when he gets to 50% of the learning path
  11567. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11568. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11569. * - the student gets the final star when the score for the *last* test is >= 80%.
  11570. *
  11571. * @param int $sessionId Optional. The session ID
  11572. *
  11573. * @return int The count of stars
  11574. */
  11575. public function getCalculateStars($sessionId = 0)
  11576. {
  11577. $stars = 0;
  11578. $progress = self::getProgress(
  11579. $this->lp_id,
  11580. $this->user_id,
  11581. $this->course_int_id,
  11582. $sessionId
  11583. );
  11584. if ($progress >= 50) {
  11585. $stars++;
  11586. }
  11587. // Calculate stars chapters evaluation
  11588. $exercisesItems = $this->getExercisesItems();
  11589. if (!empty($exercisesItems)) {
  11590. $totalResult = 0;
  11591. foreach ($exercisesItems as $exerciseItem) {
  11592. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11593. $this->user_id,
  11594. $exerciseItem->path,
  11595. $this->course_int_id,
  11596. $sessionId,
  11597. $this->lp_id,
  11598. $exerciseItem->db_id
  11599. );
  11600. $exerciseResultInfo = end($exerciseResultInfo);
  11601. if (!$exerciseResultInfo) {
  11602. continue;
  11603. }
  11604. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11605. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11606. } else {
  11607. $exerciseResult = 0;
  11608. }
  11609. $totalResult += $exerciseResult;
  11610. }
  11611. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11612. if ($totalExerciseAverage >= 50) {
  11613. $stars++;
  11614. }
  11615. if ($totalExerciseAverage >= 80) {
  11616. $stars++;
  11617. }
  11618. }
  11619. // Calculate star for final evaluation
  11620. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11621. if (!empty($finalEvaluationItem)) {
  11622. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11623. $this->user_id,
  11624. $finalEvaluationItem->path,
  11625. $this->course_int_id,
  11626. $sessionId,
  11627. $this->lp_id,
  11628. $finalEvaluationItem->db_id
  11629. );
  11630. $evaluationResultInfo = end($evaluationResultInfo);
  11631. if ($evaluationResultInfo) {
  11632. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11633. if ($evaluationResult >= 80) {
  11634. $stars++;
  11635. }
  11636. }
  11637. }
  11638. return $stars;
  11639. }
  11640. /**
  11641. * Get the items of exercise type.
  11642. *
  11643. * @return array The items. Otherwise return false
  11644. */
  11645. public function getExercisesItems()
  11646. {
  11647. $exercises = [];
  11648. foreach ($this->items as $item) {
  11649. if ($item->type != 'quiz') {
  11650. continue;
  11651. }
  11652. $exercises[] = $item;
  11653. }
  11654. array_pop($exercises);
  11655. return $exercises;
  11656. }
  11657. /**
  11658. * Get the item of exercise type (evaluation type).
  11659. *
  11660. * @return array The final evaluation. Otherwise return false
  11661. */
  11662. public function getFinalEvaluationItem()
  11663. {
  11664. $exercises = [];
  11665. foreach ($this->items as $item) {
  11666. if ($item->type != 'quiz') {
  11667. continue;
  11668. }
  11669. $exercises[] = $item;
  11670. }
  11671. return array_pop($exercises);
  11672. }
  11673. /**
  11674. * Calculate the total points achieved for the current user in this learning path.
  11675. *
  11676. * @param int $sessionId Optional. The session Id
  11677. *
  11678. * @return int
  11679. */
  11680. public function getCalculateScore($sessionId = 0)
  11681. {
  11682. // Calculate stars chapters evaluation
  11683. $exercisesItems = $this->getExercisesItems();
  11684. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11685. $totalExercisesResult = 0;
  11686. $totalEvaluationResult = 0;
  11687. if ($exercisesItems !== false) {
  11688. foreach ($exercisesItems as $exerciseItem) {
  11689. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11690. $this->user_id,
  11691. $exerciseItem->path,
  11692. $this->course_int_id,
  11693. $sessionId,
  11694. $this->lp_id,
  11695. $exerciseItem->db_id
  11696. );
  11697. $exerciseResultInfo = end($exerciseResultInfo);
  11698. if (!$exerciseResultInfo) {
  11699. continue;
  11700. }
  11701. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11702. }
  11703. }
  11704. if (!empty($finalEvaluationItem)) {
  11705. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11706. $this->user_id,
  11707. $finalEvaluationItem->path,
  11708. $this->course_int_id,
  11709. $sessionId,
  11710. $this->lp_id,
  11711. $finalEvaluationItem->db_id
  11712. );
  11713. $evaluationResultInfo = end($evaluationResultInfo);
  11714. if ($evaluationResultInfo) {
  11715. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11716. }
  11717. }
  11718. return $totalExercisesResult + $totalEvaluationResult;
  11719. }
  11720. /**
  11721. * Check if URL is not allowed to be show in a iframe.
  11722. *
  11723. * @param string $src
  11724. *
  11725. * @return string
  11726. */
  11727. public function fixBlockedLinks($src)
  11728. {
  11729. $urlInfo = parse_url($src);
  11730. $platformProtocol = 'https';
  11731. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11732. $platformProtocol = 'http';
  11733. }
  11734. $protocolFixApplied = false;
  11735. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11736. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11737. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11738. if ($platformProtocol != $scheme) {
  11739. Session::write('x_frame_source', $src);
  11740. $src = 'blank.php?error=x_frames_options';
  11741. $protocolFixApplied = true;
  11742. }
  11743. if ($protocolFixApplied == false) {
  11744. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11745. // Check X-Frame-Options
  11746. $ch = curl_init();
  11747. $options = [
  11748. CURLOPT_URL => $src,
  11749. CURLOPT_RETURNTRANSFER => true,
  11750. CURLOPT_HEADER => true,
  11751. CURLOPT_FOLLOWLOCATION => true,
  11752. CURLOPT_ENCODING => "",
  11753. CURLOPT_AUTOREFERER => true,
  11754. CURLOPT_CONNECTTIMEOUT => 120,
  11755. CURLOPT_TIMEOUT => 120,
  11756. CURLOPT_MAXREDIRS => 10,
  11757. ];
  11758. $proxySettings = api_get_configuration_value('proxy_settings');
  11759. if (!empty($proxySettings) &&
  11760. isset($proxySettings['curl_setopt_array'])
  11761. ) {
  11762. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11763. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11764. }
  11765. curl_setopt_array($ch, $options);
  11766. $response = curl_exec($ch);
  11767. $httpCode = curl_getinfo($ch);
  11768. $headers = substr($response, 0, $httpCode['header_size']);
  11769. $error = false;
  11770. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11771. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11772. ) {
  11773. $error = true;
  11774. }
  11775. if ($error) {
  11776. Session::write('x_frame_source', $src);
  11777. $src = 'blank.php?error=x_frames_options';
  11778. }
  11779. }
  11780. }
  11781. return $src;
  11782. }
  11783. /**
  11784. * Check if this LP has a created forum in the basis course.
  11785. *
  11786. * @return bool
  11787. */
  11788. public function lpHasForum()
  11789. {
  11790. $forumTable = Database::get_course_table(TABLE_FORUM);
  11791. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11792. $fakeFrom = "
  11793. $forumTable f
  11794. INNER JOIN $itemProperty ip
  11795. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11796. ";
  11797. $resultData = Database::select(
  11798. 'COUNT(f.iid) AS qty',
  11799. $fakeFrom,
  11800. [
  11801. 'where' => [
  11802. 'ip.visibility != ? AND ' => 2,
  11803. 'ip.tool = ? AND ' => TOOL_FORUM,
  11804. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11805. 'f.lp_id = ?' => intval($this->lp_id),
  11806. ],
  11807. ],
  11808. 'first'
  11809. );
  11810. return $resultData['qty'] > 0;
  11811. }
  11812. /**
  11813. * Get the forum for this learning path.
  11814. *
  11815. * @param int $sessionId
  11816. *
  11817. * @return bool
  11818. */
  11819. public function getForum($sessionId = 0)
  11820. {
  11821. $forumTable = Database::get_course_table(TABLE_FORUM);
  11822. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11823. $fakeFrom = "$forumTable f
  11824. INNER JOIN $itemProperty ip ";
  11825. if ($this->lp_session_id == 0) {
  11826. $fakeFrom .= "
  11827. ON (
  11828. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11829. f.session_id = ip.session_id OR ip.session_id IS NULL
  11830. )
  11831. )
  11832. ";
  11833. } else {
  11834. $fakeFrom .= "
  11835. ON (
  11836. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11837. )
  11838. ";
  11839. }
  11840. $resultData = Database::select(
  11841. 'f.*',
  11842. $fakeFrom,
  11843. [
  11844. 'where' => [
  11845. 'ip.visibility != ? AND ' => 2,
  11846. 'ip.tool = ? AND ' => TOOL_FORUM,
  11847. 'f.session_id = ? AND ' => $sessionId,
  11848. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11849. 'f.lp_id = ?' => intval($this->lp_id),
  11850. ],
  11851. ],
  11852. 'first'
  11853. );
  11854. if (empty($resultData)) {
  11855. return false;
  11856. }
  11857. return $resultData;
  11858. }
  11859. /**
  11860. * Create a forum for this learning path.
  11861. *
  11862. * @param int $forumCategoryId
  11863. *
  11864. * @return int The forum ID if was created. Otherwise return false
  11865. */
  11866. public function createForum($forumCategoryId)
  11867. {
  11868. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11869. $forumId = store_forum(
  11870. [
  11871. 'lp_id' => $this->lp_id,
  11872. 'forum_title' => $this->name,
  11873. 'forum_comment' => null,
  11874. 'forum_category' => intval($forumCategoryId),
  11875. 'students_can_edit_group' => ['students_can_edit' => 0],
  11876. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11877. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11878. 'group_forum' => 0,
  11879. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11880. ],
  11881. [],
  11882. true
  11883. );
  11884. return $forumId;
  11885. }
  11886. /**
  11887. * Get the LP Final Item form.
  11888. *
  11889. * @throws Exception
  11890. * @throws HTML_QuickForm_Error
  11891. *
  11892. * @return string
  11893. */
  11894. public function getFinalItemForm()
  11895. {
  11896. $finalItem = $this->getFinalItem();
  11897. $title = '';
  11898. if ($finalItem) {
  11899. $title = $finalItem->get_title();
  11900. $buttonText = get_lang('Save');
  11901. $content = $this->getSavedFinalItem();
  11902. } else {
  11903. $buttonText = get_lang('LPCreateDocument');
  11904. $content = $this->getFinalItemTemplate();
  11905. }
  11906. $courseInfo = api_get_course_info();
  11907. $result = $this->generate_lp_folder($courseInfo);
  11908. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11909. $relative_prefix = '../../';
  11910. $editorConfig = [
  11911. 'ToolbarSet' => 'LearningPathDocuments',
  11912. 'Width' => '100%',
  11913. 'Height' => '500',
  11914. 'FullPage' => true,
  11915. 'CreateDocumentDir' => $relative_prefix,
  11916. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11917. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11918. ];
  11919. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11920. 'type' => 'document',
  11921. 'lp_id' => $this->lp_id,
  11922. ]);
  11923. $form = new FormValidator('final_item', 'POST', $url);
  11924. $form->addText('title', get_lang('Title'));
  11925. $form->addButtonSave($buttonText);
  11926. $form->addHtml(
  11927. Display::return_message(
  11928. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11929. 'normal',
  11930. false
  11931. )
  11932. );
  11933. $renderer = $form->defaultRenderer();
  11934. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11935. $form->addHtmlEditor(
  11936. 'content_lp_certificate',
  11937. null,
  11938. true,
  11939. false,
  11940. $editorConfig,
  11941. true
  11942. );
  11943. $form->addHidden('action', 'add_final_item');
  11944. $form->addHidden('path', Session::read('pathItem'));
  11945. $form->addHidden('previous', $this->get_last());
  11946. $form->setDefaults(
  11947. ['title' => $title, 'content_lp_certificate' => $content]
  11948. );
  11949. if ($form->validate()) {
  11950. $values = $form->exportValues();
  11951. $lastItemId = $this->get_last();
  11952. if (!$finalItem) {
  11953. $documentId = $this->create_document(
  11954. $this->course_info,
  11955. $values['content_lp_certificate'],
  11956. $values['title']
  11957. );
  11958. $this->add_item(
  11959. 0,
  11960. $lastItemId,
  11961. 'final_item',
  11962. $documentId,
  11963. $values['title'],
  11964. ''
  11965. );
  11966. Display::addFlash(
  11967. Display::return_message(get_lang('Added'))
  11968. );
  11969. } else {
  11970. $this->edit_document($this->course_info);
  11971. }
  11972. }
  11973. return $form->returnForm();
  11974. }
  11975. /**
  11976. * Check if the current lp item is first, both, last or none from lp list.
  11977. *
  11978. * @param int $currentItemId
  11979. *
  11980. * @return string
  11981. */
  11982. public function isFirstOrLastItem($currentItemId)
  11983. {
  11984. if ($this->debug > 0) {
  11985. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11986. }
  11987. $lpItemId = [];
  11988. $typeListNotToVerify = self::getChapterTypes();
  11989. // Using get_toc() function instead $this->items because returns the correct order of the items
  11990. foreach ($this->get_toc() as $item) {
  11991. if (!in_array($item['type'], $typeListNotToVerify)) {
  11992. $lpItemId[] = $item['id'];
  11993. }
  11994. }
  11995. $lastLpItemIndex = count($lpItemId) - 1;
  11996. $position = array_search($currentItemId, $lpItemId);
  11997. switch ($position) {
  11998. case 0:
  11999. if (!$lastLpItemIndex) {
  12000. $answer = 'both';
  12001. break;
  12002. }
  12003. $answer = 'first';
  12004. break;
  12005. case $lastLpItemIndex:
  12006. $answer = 'last';
  12007. break;
  12008. default:
  12009. $answer = 'none';
  12010. }
  12011. return $answer;
  12012. }
  12013. /**
  12014. * Get whether this is a learning path with the accumulated SCORM time or not.
  12015. *
  12016. * @return int
  12017. */
  12018. public function getAccumulateScormTime()
  12019. {
  12020. return $this->accumulateScormTime;
  12021. }
  12022. /**
  12023. * Set whether this is a learning path with the accumulated SCORM time or not.
  12024. *
  12025. * @param int $value (0 = false, 1 = true)
  12026. *
  12027. * @return bool Always returns true
  12028. */
  12029. public function setAccumulateScormTime($value)
  12030. {
  12031. if ($this->debug > 0) {
  12032. error_log('In learnpath::setAccumulateScormTime()', 0);
  12033. }
  12034. $this->accumulateScormTime = intval($value);
  12035. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  12036. $lp_id = $this->get_id();
  12037. $sql = "UPDATE $lp_table
  12038. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  12039. WHERE iid = $lp_id";
  12040. Database::query($sql);
  12041. return true;
  12042. }
  12043. /**
  12044. * Returns an HTML-formatted link to a resource, to incorporate directly into
  12045. * the new learning path tool.
  12046. *
  12047. * The function is a big switch on tool type.
  12048. * In each case, we query the corresponding table for information and build the link
  12049. * with that information.
  12050. *
  12051. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  12052. * previous work (display_addedresource_link_in_learnpath())
  12053. *
  12054. * @param int $course_id Course code
  12055. * @param int $learningPathId The learning path ID (in lp table)
  12056. * @param int $id_in_path the unique index in the items table
  12057. * @param int $lpViewId
  12058. *
  12059. * @return string
  12060. */
  12061. public static function rl_get_resource_link_for_learnpath(
  12062. $course_id,
  12063. $learningPathId,
  12064. $id_in_path,
  12065. $lpViewId
  12066. ) {
  12067. $session_id = api_get_session_id();
  12068. $course_info = api_get_course_info_by_id($course_id);
  12069. $learningPathId = (int) $learningPathId;
  12070. $id_in_path = (int) $id_in_path;
  12071. $lpViewId = (int) $lpViewId;
  12072. $em = Database::getManager();
  12073. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12074. /** @var CLpItem $rowItem */
  12075. $rowItem = $lpItemRepo->findOneBy([
  12076. 'cId' => $course_id,
  12077. 'lpId' => $learningPathId,
  12078. 'iid' => $id_in_path,
  12079. ]);
  12080. if (!$rowItem) {
  12081. // Try one more time with "id"
  12082. /** @var CLpItem $rowItem */
  12083. $rowItem = $lpItemRepo->findOneBy([
  12084. 'cId' => $course_id,
  12085. 'lpId' => $learningPathId,
  12086. 'id' => $id_in_path,
  12087. ]);
  12088. if (!$rowItem) {
  12089. return -1;
  12090. }
  12091. }
  12092. $course_code = $course_info['code'];
  12093. $type = $rowItem->getItemType();
  12094. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12095. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12096. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12097. $link = '';
  12098. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12099. switch ($type) {
  12100. case 'dir':
  12101. return $main_dir_path.'lp/blank.php';
  12102. case TOOL_CALENDAR_EVENT:
  12103. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12104. case TOOL_ANNOUNCEMENT:
  12105. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12106. case TOOL_LINK:
  12107. $linkInfo = Link::getLinkInfo($id);
  12108. if (isset($linkInfo['url'])) {
  12109. return $linkInfo['url'];
  12110. }
  12111. return '';
  12112. case TOOL_QUIZ:
  12113. if (empty($id)) {
  12114. return '';
  12115. }
  12116. // Get the lp_item_view with the highest view_count.
  12117. $learnpathItemViewResult = $em
  12118. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12119. ->findBy(
  12120. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12121. ['viewCount' => 'DESC'],
  12122. 1
  12123. );
  12124. /** @var CLpItemView $learnpathItemViewData */
  12125. $learnpathItemViewData = current($learnpathItemViewResult);
  12126. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12127. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12128. .http_build_query([
  12129. 'lp_init' => 1,
  12130. 'learnpath_item_view_id' => $learnpathItemViewId,
  12131. 'learnpath_id' => $learningPathId,
  12132. 'learnpath_item_id' => $id_in_path,
  12133. 'exerciseId' => $id,
  12134. ]);
  12135. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12136. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12137. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12138. $myrow = Database::fetch_array($result);
  12139. $path = $myrow['path'];
  12140. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12141. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12142. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12143. case TOOL_FORUM:
  12144. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12145. case TOOL_THREAD:
  12146. // forum post
  12147. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12148. if (empty($id)) {
  12149. return '';
  12150. }
  12151. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12152. $result = Database::query($sql);
  12153. $myrow = Database::fetch_array($result);
  12154. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12155. .$extraParams;
  12156. case TOOL_POST:
  12157. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12158. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12159. $myrow = Database::fetch_array($result);
  12160. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12161. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12162. case TOOL_READOUT_TEXT:
  12163. return api_get_path(WEB_CODE_PATH).'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12164. .$extraParams;
  12165. case TOOL_DOCUMENT:
  12166. $document = $em
  12167. ->getRepository('ChamiloCourseBundle:CDocument')
  12168. ->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12169. if (empty($document)) {
  12170. // Try with normal id
  12171. $document = $em
  12172. ->getRepository('ChamiloCourseBundle:CDocument')
  12173. ->findOneBy(['cId' => $course_id, 'id' => $id]);
  12174. if (empty($document)) {
  12175. return '';
  12176. }
  12177. }
  12178. $documentPathInfo = pathinfo($document->getPath());
  12179. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  12180. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12181. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  12182. $openmethod = 2;
  12183. $officedoc = false;
  12184. Session::write('openmethod', $openmethod);
  12185. Session::write('officedoc', $officedoc);
  12186. if ($showDirectUrl) {
  12187. return $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12188. }
  12189. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12190. case TOOL_LP_FINAL_ITEM:
  12191. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12192. .$extraParams;
  12193. case 'assignments':
  12194. return $main_dir_path.'work/work.php?'.$extraParams;
  12195. case TOOL_DROPBOX:
  12196. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12197. case 'introduction_text': //DEPRECATED
  12198. return '';
  12199. case TOOL_COURSE_DESCRIPTION:
  12200. return $main_dir_path.'course_description?'.$extraParams;
  12201. case TOOL_GROUP:
  12202. return $main_dir_path.'group/group.php?'.$extraParams;
  12203. case TOOL_USER:
  12204. return $main_dir_path.'user/user.php?'.$extraParams;
  12205. case TOOL_STUDENTPUBLICATION:
  12206. if (!empty($rowItem->getPath())) {
  12207. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12208. }
  12209. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12210. } //end switch
  12211. return $link;
  12212. }
  12213. /**
  12214. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12215. *
  12216. * @author Yannick Warnier <ywarnier@beeznest.org>
  12217. *
  12218. * @param string $course_code Course code
  12219. * @param int $learningPathId
  12220. * @param int $id_in_path The resource ID
  12221. *
  12222. * @return string
  12223. */
  12224. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12225. {
  12226. $_course = api_get_course_info($course_code);
  12227. $course_id = $_course['real_id'];
  12228. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12229. $learningPathId = (int) $learningPathId;
  12230. $id_in_path = (int) $id_in_path;
  12231. $sql = "SELECT item_type, title, ref
  12232. FROM $tbl_lp_item
  12233. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12234. $res_item = Database::query($sql);
  12235. if (Database::num_rows($res_item) < 1) {
  12236. return '';
  12237. }
  12238. $row_item = Database::fetch_array($res_item);
  12239. $type = strtolower($row_item['item_type']);
  12240. $id = $row_item['ref'];
  12241. $output = '';
  12242. switch ($type) {
  12243. case TOOL_CALENDAR_EVENT:
  12244. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12245. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12246. $myrow = Database::fetch_array($result);
  12247. $output = $myrow['title'];
  12248. break;
  12249. case TOOL_ANNOUNCEMENT:
  12250. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12251. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12252. $myrow = Database::fetch_array($result);
  12253. $output = $myrow['title'];
  12254. break;
  12255. case TOOL_LINK:
  12256. // Doesn't take $target into account.
  12257. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12258. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12259. $myrow = Database::fetch_array($result);
  12260. $output = $myrow['title'];
  12261. break;
  12262. case TOOL_QUIZ:
  12263. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12264. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12265. $myrow = Database::fetch_array($result);
  12266. $output = $myrow['title'];
  12267. break;
  12268. case TOOL_FORUM:
  12269. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12270. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12271. $myrow = Database::fetch_array($result);
  12272. $output = $myrow['forum_name'];
  12273. break;
  12274. case TOOL_THREAD: //=topics
  12275. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12276. // Grabbing the title of the post.
  12277. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12278. $result_title = Database::query($sql_title);
  12279. $myrow_title = Database::fetch_array($result_title);
  12280. $output = $myrow_title['post_title'];
  12281. break;
  12282. case TOOL_POST:
  12283. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12284. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  12285. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12286. $result = Database::query($sql);
  12287. $post = Database::fetch_array($result);
  12288. $output = $post['post_title'];
  12289. break;
  12290. case 'dir':
  12291. $title = $row_item['title'];
  12292. if (!empty($title)) {
  12293. $output = $title;
  12294. } else {
  12295. $output = '-';
  12296. }
  12297. break;
  12298. case TOOL_DOCUMENT:
  12299. $title = $row_item['title'];
  12300. if (!empty($title)) {
  12301. $output = $title;
  12302. } else {
  12303. $output = '-';
  12304. }
  12305. break;
  12306. case 'hotpotatoes':
  12307. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12308. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12309. $myrow = Database::fetch_array($result);
  12310. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12311. $last = count($pathname) - 1; // Making a correct name for the link.
  12312. $filename = $pathname[$last]; // Making a correct name for the link.
  12313. $ext = explode('.', $filename);
  12314. $ext = strtolower($ext[sizeof($ext) - 1]);
  12315. $myrow['path'] = rawurlencode($myrow['path']);
  12316. $output = $filename;
  12317. break;
  12318. }
  12319. return stripslashes($output);
  12320. }
  12321. /**
  12322. * Get the parent names for the current item.
  12323. *
  12324. * @param int $newItemId Optional. The item ID
  12325. *
  12326. * @return array
  12327. */
  12328. public function getCurrentItemParentNames($newItemId = 0)
  12329. {
  12330. $newItemId = $newItemId ?: $this->get_current_item_id();
  12331. $return = [];
  12332. $item = $this->getItem($newItemId);
  12333. $parent = $this->getItem($item->get_parent());
  12334. while ($parent) {
  12335. $return[] = $parent->get_title();
  12336. $parent = $this->getItem($parent->get_parent());
  12337. }
  12338. return array_reverse($return);
  12339. }
  12340. /**
  12341. * Reads and process "lp_subscription_settings" setting.
  12342. *
  12343. * @return array
  12344. */
  12345. public static function getSubscriptionSettings()
  12346. {
  12347. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12348. if (empty($subscriptionSettings)) {
  12349. // By default allow both settings
  12350. $subscriptionSettings = [
  12351. 'allow_add_users_to_lp' => true,
  12352. 'allow_add_users_to_lp_category' => true,
  12353. ];
  12354. } else {
  12355. $subscriptionSettings = $subscriptionSettings['options'];
  12356. }
  12357. return $subscriptionSettings;
  12358. }
  12359. /**
  12360. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12361. */
  12362. public function exportToCourseBuildFormat()
  12363. {
  12364. if (!api_is_allowed_to_edit()) {
  12365. return false;
  12366. }
  12367. $courseBuilder = new CourseBuilder();
  12368. $itemList = [];
  12369. /** @var learnpathItem $item */
  12370. foreach ($this->items as $item) {
  12371. $itemList[$item->get_type()][] = $item->get_path();
  12372. }
  12373. if (empty($itemList)) {
  12374. return false;
  12375. }
  12376. if (isset($itemList['document'])) {
  12377. // Get parents
  12378. foreach ($itemList['document'] as $documentId) {
  12379. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12380. if (!empty($documentInfo['parents'])) {
  12381. foreach ($documentInfo['parents'] as $parentInfo) {
  12382. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12383. continue;
  12384. }
  12385. $itemList['document'][] = $parentInfo['iid'];
  12386. }
  12387. }
  12388. }
  12389. $courseInfo = api_get_course_info();
  12390. foreach ($itemList['document'] as $documentId) {
  12391. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12392. $items = DocumentManager::get_resources_from_source_html(
  12393. $documentInfo['absolute_path'],
  12394. true,
  12395. TOOL_DOCUMENT
  12396. );
  12397. if (!empty($items)) {
  12398. foreach ($items as $item) {
  12399. // Get information about source url
  12400. $url = $item[0]; // url
  12401. $scope = $item[1]; // scope (local, remote)
  12402. $type = $item[2]; // type (rel, abs, url)
  12403. $origParseUrl = parse_url($url);
  12404. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12405. if ($scope == 'local') {
  12406. if ($type == 'abs' || $type == 'rel') {
  12407. $documentFile = strstr($realOrigPath, 'document');
  12408. if (strpos($realOrigPath, $documentFile) !== false) {
  12409. $documentFile = str_replace('document', '', $documentFile);
  12410. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12411. // Document found! Add it to the list
  12412. if ($itemDocumentId) {
  12413. $itemList['document'][] = $itemDocumentId;
  12414. }
  12415. }
  12416. }
  12417. }
  12418. }
  12419. }
  12420. }
  12421. $courseBuilder->build_documents(
  12422. api_get_session_id(),
  12423. $this->get_course_int_id(),
  12424. true,
  12425. $itemList['document']
  12426. );
  12427. }
  12428. if (isset($itemList['quiz'])) {
  12429. $courseBuilder->build_quizzes(
  12430. api_get_session_id(),
  12431. $this->get_course_int_id(),
  12432. true,
  12433. $itemList['quiz']
  12434. );
  12435. }
  12436. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12437. /*if (!empty($itemList['thread'])) {
  12438. $postList = [];
  12439. foreach ($itemList['thread'] as $postId) {
  12440. $post = get_post_information($postId);
  12441. if ($post) {
  12442. if (!isset($itemList['forum'])) {
  12443. $itemList['forum'] = [];
  12444. }
  12445. $itemList['forum'][] = $post['forum_id'];
  12446. $postList[] = $postId;
  12447. }
  12448. }
  12449. if (!empty($postList)) {
  12450. $courseBuilder->build_forum_posts(
  12451. $this->get_course_int_id(),
  12452. null,
  12453. null,
  12454. $postList
  12455. );
  12456. }
  12457. }*/
  12458. if (!empty($itemList['thread'])) {
  12459. $threadList = [];
  12460. $em = Database::getManager();
  12461. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12462. foreach ($itemList['thread'] as $threadId) {
  12463. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12464. $thread = $repo->find($threadId);
  12465. if ($thread) {
  12466. $itemList['forum'][] = $thread->getForumId();
  12467. $threadList[] = $thread->getIid();
  12468. }
  12469. }
  12470. if (!empty($threadList)) {
  12471. $courseBuilder->build_forum_topics(
  12472. api_get_session_id(),
  12473. $this->get_course_int_id(),
  12474. null,
  12475. $threadList
  12476. );
  12477. }
  12478. }
  12479. $forumCategoryList = [];
  12480. if (isset($itemList['forum'])) {
  12481. foreach ($itemList['forum'] as $forumId) {
  12482. $forumInfo = get_forums($forumId);
  12483. $forumCategoryList[] = $forumInfo['forum_category'];
  12484. }
  12485. }
  12486. if (!empty($forumCategoryList)) {
  12487. $courseBuilder->build_forum_category(
  12488. api_get_session_id(),
  12489. $this->get_course_int_id(),
  12490. true,
  12491. $forumCategoryList
  12492. );
  12493. }
  12494. if (!empty($itemList['forum'])) {
  12495. $courseBuilder->build_forums(
  12496. api_get_session_id(),
  12497. $this->get_course_int_id(),
  12498. true,
  12499. $itemList['forum']
  12500. );
  12501. }
  12502. if (isset($itemList['link'])) {
  12503. $courseBuilder->build_links(
  12504. api_get_session_id(),
  12505. $this->get_course_int_id(),
  12506. true,
  12507. $itemList['link']
  12508. );
  12509. }
  12510. if (!empty($itemList['student_publication'])) {
  12511. $courseBuilder->build_works(
  12512. api_get_session_id(),
  12513. $this->get_course_int_id(),
  12514. true,
  12515. $itemList['student_publication']
  12516. );
  12517. }
  12518. $courseBuilder->build_learnpaths(
  12519. api_get_session_id(),
  12520. $this->get_course_int_id(),
  12521. true,
  12522. [$this->get_id()],
  12523. false
  12524. );
  12525. $courseBuilder->restoreDocumentsFromList();
  12526. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12527. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12528. $result = DocumentManager::file_send_for_download(
  12529. $zipPath,
  12530. true,
  12531. $this->get_name().'.zip'
  12532. );
  12533. if ($result) {
  12534. api_not_allowed();
  12535. }
  12536. return true;
  12537. }
  12538. /**
  12539. * Get the depth level of LP item.
  12540. *
  12541. * @param array $items
  12542. * @param int $currentItemId
  12543. *
  12544. * @return int
  12545. */
  12546. private static function get_level_for_item($items, $currentItemId)
  12547. {
  12548. $parentItemId = 0;
  12549. if (isset($items[$currentItemId])) {
  12550. $parentItemId = $items[$currentItemId]->parent;
  12551. }
  12552. if ($parentItemId == 0) {
  12553. return 0;
  12554. } else {
  12555. return self::get_level_for_item($items, $parentItemId) + 1;
  12556. }
  12557. }
  12558. /**
  12559. * Generate the link for a learnpath category as course tool.
  12560. *
  12561. * @param int $categoryId
  12562. *
  12563. * @return string
  12564. */
  12565. private static function getCategoryLinkForTool($categoryId)
  12566. {
  12567. $categoryId = (int) $categoryId;
  12568. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12569. .http_build_query(
  12570. [
  12571. 'action' => 'view_category',
  12572. 'id' => $categoryId,
  12573. ]
  12574. );
  12575. return $link;
  12576. }
  12577. /**
  12578. * Return the scorm item type object with spaces replaced with _
  12579. * The return result is use to build a css classname like scorm_type_$return.
  12580. *
  12581. * @param $in_type
  12582. *
  12583. * @return mixed
  12584. */
  12585. private static function format_scorm_type_item($in_type)
  12586. {
  12587. return str_replace(' ', '_', $in_type);
  12588. }
  12589. /**
  12590. * Check and obtain the lp final item if exist.
  12591. *
  12592. * @return learnpathItem
  12593. */
  12594. private function getFinalItem()
  12595. {
  12596. if (empty($this->items)) {
  12597. return null;
  12598. }
  12599. foreach ($this->items as $item) {
  12600. if ($item->type !== 'final_item') {
  12601. continue;
  12602. }
  12603. return $item;
  12604. }
  12605. }
  12606. /**
  12607. * Get the LP Final Item Template.
  12608. *
  12609. * @return string
  12610. */
  12611. private function getFinalItemTemplate()
  12612. {
  12613. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12614. }
  12615. /**
  12616. * Get the LP Final Item Url.
  12617. *
  12618. * @return string
  12619. */
  12620. private function getSavedFinalItem()
  12621. {
  12622. $finalItem = $this->getFinalItem();
  12623. $doc = DocumentManager::get_document_data_by_id(
  12624. $finalItem->path,
  12625. $this->cc
  12626. );
  12627. if ($doc && file_exists($doc['absolute_path'])) {
  12628. return file_get_contents($doc['absolute_path']);
  12629. }
  12630. return '';
  12631. }
  12632. }