learnpath.class.php 528 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. if ($debug) {
  241. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  242. error_log('-- Start while--');
  243. }
  244. $lp_item_id_list = [];
  245. while ($row = Database::fetch_array($res)) {
  246. $lp_item_id_list[] = $row['iid'];
  247. switch ($this->type) {
  248. case 3: //aicc
  249. $oItem = new aiccItem('db', $row['iid'], $course_id);
  250. if (is_object($oItem)) {
  251. $my_item_id = $oItem->get_id();
  252. $oItem->set_lp_view($this->lp_view_id, $course_id);
  253. $oItem->set_prevent_reinit($this->prevent_reinit);
  254. // Don't use reference here as the next loop will make the pointed object change.
  255. $this->items[$my_item_id] = $oItem;
  256. $this->refs_list[$oItem->ref] = $my_item_id;
  257. if ($debug) {
  258. error_log(
  259. 'learnpath::__construct() - '.
  260. 'aicc object with id '.$my_item_id.
  261. ' set in items[]',
  262. 0
  263. );
  264. }
  265. }
  266. break;
  267. case 2:
  268. $oItem = new scormItem('db', $row['iid'], $course_id);
  269. if (is_object($oItem)) {
  270. $my_item_id = $oItem->get_id();
  271. $oItem->set_lp_view($this->lp_view_id, $course_id);
  272. $oItem->set_prevent_reinit($this->prevent_reinit);
  273. // Don't use reference here as the next loop will make the pointed object change.
  274. $this->items[$my_item_id] = $oItem;
  275. $this->refs_list[$oItem->ref] = $my_item_id;
  276. if ($debug) {
  277. error_log('object with id '.$my_item_id.' set in items[]');
  278. }
  279. }
  280. break;
  281. case 1:
  282. default:
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  285. }
  286. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  287. if ($debug) {
  288. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  289. }
  290. if (is_object($oItem)) {
  291. $my_item_id = $oItem->get_id();
  292. // Moved down to when we are sure the item_view exists.
  293. //$oItem->set_lp_view($this->lp_view_id);
  294. $oItem->set_prevent_reinit($this->prevent_reinit);
  295. // Don't use reference here as the next loop will make the pointed object change.
  296. $this->items[$my_item_id] = $oItem;
  297. $this->refs_list[$my_item_id] = $my_item_id;
  298. if ($debug) {
  299. error_log(
  300. 'learnpath::__construct() '.__LINE__.
  301. ' - object with id '.$my_item_id.' set in items[]'
  302. );
  303. }
  304. }
  305. break;
  306. }
  307. // Setting the object level with variable $this->items[$i][parent]
  308. foreach ($this->items as $itemLPObject) {
  309. $level = self::get_level_for_item(
  310. $this->items,
  311. $itemLPObject->db_id
  312. );
  313. $itemLPObject->level = $level;
  314. }
  315. // Setting the view in the item object.
  316. if (is_object($this->items[$row['iid']])) {
  317. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  318. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  319. $this->items[$row['iid']]->current_start_time = 0;
  320. $this->items[$row['iid']]->current_stop_time = 0;
  321. }
  322. }
  323. }
  324. if ($debug) {
  325. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  326. }
  327. if (!empty($lp_item_id_list)) {
  328. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  329. if (!empty($lp_item_id_list_to_string)) {
  330. // Get last viewing vars.
  331. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  332. // This query should only return one or zero result.
  333. $sql = "SELECT lp_item_id, status
  334. FROM $itemViewTable
  335. WHERE
  336. c_id = $course_id AND
  337. lp_view_id = ".$this->get_view_id()." AND
  338. lp_item_id IN ('".$lp_item_id_list_to_string."')
  339. ORDER BY view_count DESC ";
  340. if ($debug) {
  341. error_log(
  342. 'learnpath::__construct() - Selecting item_views: '.$sql,
  343. 0
  344. );
  345. }
  346. $status_list = [];
  347. $res = Database::query($sql);
  348. while ($row = Database:: fetch_array($res)) {
  349. $status_list[$row['lp_item_id']] = $row['status'];
  350. }
  351. foreach ($lp_item_id_list as $item_id) {
  352. if (isset($status_list[$item_id])) {
  353. $status = $status_list[$item_id];
  354. if (is_object($this->items[$item_id])) {
  355. $this->items[$item_id]->set_status($status);
  356. if (empty($status)) {
  357. $this->items[$item_id]->set_status(
  358. $this->default_status
  359. );
  360. }
  361. }
  362. } else {
  363. if (!api_is_invitee()) {
  364. if (is_object($this->items[$item_id])) {
  365. $this->items[$item_id]->set_status(
  366. $this->default_status
  367. );
  368. }
  369. if (!empty($this->lp_view_id)) {
  370. // Add that row to the lp_item_view table so that
  371. // we have something to show in the stats page.
  372. $params = [
  373. 'c_id' => $course_id,
  374. 'lp_item_id' => $item_id,
  375. 'lp_view_id' => $this->lp_view_id,
  376. 'view_count' => 1,
  377. 'status' => 'not attempted',
  378. 'start_time' => time(),
  379. 'total_time' => 0,
  380. 'score' => 0,
  381. ];
  382. $insertId = Database::insert($itemViewTable, $params);
  383. if ($insertId) {
  384. $sql = "UPDATE $itemViewTable SET id = iid
  385. WHERE iid = $insertId";
  386. Database::query($sql);
  387. }
  388. $this->items[$item_id]->set_lp_view(
  389. $this->lp_view_id,
  390. $course_id
  391. );
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. $this->ordered_items = self::get_flat_ordered_items_list(
  399. $this->get_id(),
  400. 0,
  401. $course_id
  402. );
  403. $this->max_ordered_items = 0;
  404. foreach ($this->ordered_items as $index => $dummy) {
  405. if ($index > $this->max_ordered_items && !empty($dummy)) {
  406. $this->max_ordered_items = $index;
  407. }
  408. }
  409. // TODO: Define the current item better.
  410. $this->first();
  411. if ($debug) {
  412. error_log('lp_view_session_id '.$this->lp_view_session_id);
  413. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  414. }
  415. } else {
  416. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  417. }
  418. }
  419. }
  420. /**
  421. * @return string
  422. */
  423. public function getCourseCode()
  424. {
  425. return $this->cc;
  426. }
  427. /**
  428. * @return int
  429. */
  430. public function get_course_int_id()
  431. {
  432. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  433. }
  434. /**
  435. * @param $course_id
  436. *
  437. * @return int
  438. */
  439. public function set_course_int_id($course_id)
  440. {
  441. return $this->course_int_id = (int) $course_id;
  442. }
  443. /**
  444. * Function rewritten based on old_add_item() from Yannick Warnier.
  445. * Due the fact that users can decide where the item should come, I had to overlook this function and
  446. * I found it better to rewrite it. Old function is still available.
  447. * Added also the possibility to add a description.
  448. *
  449. * @param int $parent
  450. * @param int $previous
  451. * @param string $type
  452. * @param int $id resource ID (ref)
  453. * @param string $title
  454. * @param string $description
  455. * @param int $prerequisites
  456. * @param int $max_time_allowed
  457. * @param int $userId
  458. *
  459. * @return int
  460. */
  461. public function add_item(
  462. $parent,
  463. $previous,
  464. $type = 'dir',
  465. $id,
  466. $title,
  467. $description,
  468. $prerequisites = 0,
  469. $max_time_allowed = 0,
  470. $userId = 0
  471. ) {
  472. $course_id = $this->course_info['real_id'];
  473. if ($this->debug > 0) {
  474. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  475. }
  476. if (empty($course_id)) {
  477. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  478. $this->course_info = api_get_course_info($this->cc);
  479. $course_id = $this->course_info['real_id'];
  480. }
  481. $userId = empty($userId) ? api_get_user_id() : $userId;
  482. $sessionId = api_get_session_id();
  483. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  484. $_course = $this->course_info;
  485. $parent = (int) $parent;
  486. $previous = (int) $previous;
  487. $id = (int) $id;
  488. $max_time_allowed = htmlentities($max_time_allowed);
  489. if (empty($max_time_allowed)) {
  490. $max_time_allowed = 0;
  491. }
  492. $sql = "SELECT COUNT(iid) AS num
  493. FROM $tbl_lp_item
  494. WHERE
  495. c_id = $course_id AND
  496. lp_id = ".$this->get_id()." AND
  497. parent_item_id = ".$parent;
  498. $res_count = Database::query($sql);
  499. $row = Database::fetch_array($res_count);
  500. $num = $row['num'];
  501. $tmp_previous = 0;
  502. $display_order = 0;
  503. $next = 0;
  504. if ($num > 0) {
  505. if (empty($previous)) {
  506. $sql = "SELECT iid, next_item_id, display_order
  507. FROM $tbl_lp_item
  508. WHERE
  509. c_id = $course_id AND
  510. lp_id = ".$this->get_id()." AND
  511. parent_item_id = $parent AND
  512. previous_item_id = 0 OR
  513. previous_item_id = $parent";
  514. $result = Database::query($sql);
  515. $row = Database::fetch_array($result);
  516. if ($row) {
  517. $next = $row['iid'];
  518. }
  519. } else {
  520. $previous = (int) $previous;
  521. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  522. FROM $tbl_lp_item
  523. WHERE
  524. c_id = $course_id AND
  525. lp_id = ".$this->get_id()." AND
  526. id = $previous";
  527. $result = Database::query($sql);
  528. $row = Database::fetch_array($result);
  529. if ($row) {
  530. $tmp_previous = $row['iid'];
  531. $next = $row['next_item_id'];
  532. $display_order = $row['display_order'];
  533. }
  534. }
  535. }
  536. $id = (int) $id;
  537. $typeCleaned = Database::escape_string($type);
  538. $max_score = 100;
  539. if ($type === 'quiz') {
  540. $sql = 'SELECT SUM(ponderation)
  541. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  542. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  543. ON
  544. quiz_question.id = quiz_rel_question.question_id AND
  545. quiz_question.c_id = quiz_rel_question.c_id
  546. WHERE
  547. quiz_rel_question.exercice_id = '.$id." AND
  548. quiz_question.c_id = $course_id AND
  549. quiz_rel_question.c_id = $course_id ";
  550. $rsQuiz = Database::query($sql);
  551. $max_score = Database::result($rsQuiz, 0, 0);
  552. // Disabling the exercise if we add it inside a LP
  553. $exercise = new Exercise($course_id);
  554. $exercise->read($id);
  555. $exercise->disable();
  556. $exercise->save();
  557. }
  558. $params = [
  559. 'c_id' => $course_id,
  560. 'lp_id' => $this->get_id(),
  561. 'item_type' => $typeCleaned,
  562. 'ref' => '',
  563. 'title' => $title,
  564. 'description' => $description,
  565. 'path' => $id,
  566. 'max_score' => $max_score,
  567. 'parent_item_id' => $parent,
  568. 'previous_item_id' => $previous,
  569. 'next_item_id' => (int) $next,
  570. 'display_order' => $display_order + 1,
  571. 'prerequisite' => $prerequisites,
  572. 'max_time_allowed' => $max_time_allowed,
  573. 'min_score' => 0,
  574. 'launch_data' => '',
  575. ];
  576. if ($prerequisites != 0) {
  577. $params['prerequisite'] = $prerequisites;
  578. }
  579. $new_item_id = Database::insert($tbl_lp_item, $params);
  580. if ($new_item_id) {
  581. if ($this->debug > 2) {
  582. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  583. }
  584. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  585. Database::query($sql);
  586. if (!empty($next)) {
  587. $sql = "UPDATE $tbl_lp_item
  588. SET previous_item_id = $new_item_id
  589. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  590. Database::query($sql);
  591. }
  592. // Update the item that should be before the new item.
  593. if (!empty($tmp_previous)) {
  594. $sql = "UPDATE $tbl_lp_item
  595. SET next_item_id = $new_item_id
  596. WHERE c_id = $course_id AND id = $tmp_previous";
  597. Database::query($sql);
  598. }
  599. // Update all the items after the new item.
  600. $sql = "UPDATE $tbl_lp_item
  601. SET display_order = display_order + 1
  602. WHERE
  603. c_id = $course_id AND
  604. lp_id = ".$this->get_id()." AND
  605. iid <> $new_item_id AND
  606. parent_item_id = $parent AND
  607. display_order > $display_order";
  608. Database::query($sql);
  609. // Update the item that should come after the new item.
  610. $sql = "UPDATE $tbl_lp_item
  611. SET ref = $new_item_id
  612. WHERE c_id = $course_id AND iid = $new_item_id";
  613. Database::query($sql);
  614. $sql = "UPDATE $tbl_lp_item
  615. SET previous_item_id = ".$this->getLastInFirstLevel()."
  616. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  617. Database::query($sql);
  618. // Upload audio.
  619. if (!empty($_FILES['mp3']['name'])) {
  620. // Create the audio folder if it does not exist yet.
  621. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  622. if (!is_dir($filepath.'audio')) {
  623. mkdir(
  624. $filepath.'audio',
  625. api_get_permissions_for_new_directories()
  626. );
  627. $audio_id = add_document(
  628. $_course,
  629. '/audio',
  630. 'folder',
  631. 0,
  632. 'audio',
  633. '',
  634. 0,
  635. true,
  636. null,
  637. $sessionId,
  638. $userId
  639. );
  640. api_item_property_update(
  641. $_course,
  642. TOOL_DOCUMENT,
  643. $audio_id,
  644. 'FolderCreated',
  645. $userId,
  646. null,
  647. null,
  648. null,
  649. null,
  650. $sessionId
  651. );
  652. api_item_property_update(
  653. $_course,
  654. TOOL_DOCUMENT,
  655. $audio_id,
  656. 'invisible',
  657. $userId,
  658. null,
  659. null,
  660. null,
  661. null,
  662. $sessionId
  663. );
  664. }
  665. $file_path = handle_uploaded_document(
  666. $_course,
  667. $_FILES['mp3'],
  668. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  669. '/audio',
  670. $userId,
  671. '',
  672. '',
  673. '',
  674. '',
  675. false
  676. );
  677. // Getting the filename only.
  678. $file_components = explode('/', $file_path);
  679. $file = $file_components[count($file_components) - 1];
  680. // Store the mp3 file in the lp_item table.
  681. $sql = "UPDATE $tbl_lp_item SET
  682. audio = '".Database::escape_string($file)."'
  683. WHERE iid = '".intval($new_item_id)."'";
  684. Database::query($sql);
  685. }
  686. }
  687. return $new_item_id;
  688. }
  689. /**
  690. * Static admin function allowing addition of a learnpath to a course.
  691. *
  692. * @param string $courseCode
  693. * @param string $name
  694. * @param string $description
  695. * @param string $learnpath
  696. * @param string $origin
  697. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  698. * @param string $publicated_on
  699. * @param string $expired_on
  700. * @param int $categoryId
  701. * @param int $userId
  702. *
  703. * @return int The new learnpath ID on success, 0 on failure
  704. */
  705. public static function add_lp(
  706. $courseCode,
  707. $name,
  708. $description = '',
  709. $learnpath = 'guess',
  710. $origin = 'zip',
  711. $zipname = '',
  712. $publicated_on = '',
  713. $expired_on = '',
  714. $categoryId = 0,
  715. $userId = 0
  716. ) {
  717. global $charset;
  718. if (!empty($courseCode)) {
  719. $courseInfo = api_get_course_info($courseCode);
  720. $course_id = $courseInfo['real_id'];
  721. } else {
  722. $course_id = api_get_course_int_id();
  723. $courseInfo = api_get_course_info();
  724. }
  725. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  726. // Check course code exists.
  727. // Check lp_name doesn't exist, otherwise append something.
  728. $i = 0;
  729. $name = Database::escape_string($name);
  730. $categoryId = (int) $categoryId;
  731. // Session id.
  732. $session_id = api_get_session_id();
  733. $userId = empty($userId) ? api_get_user_id() : $userId;
  734. $check_name = "SELECT * FROM $tbl_lp
  735. WHERE c_id = $course_id AND name = '$name'";
  736. $res_name = Database::query($check_name);
  737. if (empty($publicated_on)) {
  738. $publicated_on = null;
  739. } else {
  740. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  741. }
  742. if (empty($expired_on)) {
  743. $expired_on = null;
  744. } else {
  745. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  746. }
  747. while (Database::num_rows($res_name)) {
  748. // There is already one such name, update the current one a bit.
  749. $i++;
  750. $name = $name.' - '.$i;
  751. $check_name = "SELECT * FROM $tbl_lp
  752. WHERE c_id = $course_id AND name = '$name'";
  753. $res_name = Database::query($check_name);
  754. }
  755. // New name does not exist yet; keep it.
  756. // Escape description.
  757. // Kevin: added htmlentities().
  758. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  759. $type = 1;
  760. switch ($learnpath) {
  761. case 'guess':
  762. break;
  763. case 'dokeos':
  764. case 'chamilo':
  765. $type = 1;
  766. break;
  767. case 'aicc':
  768. break;
  769. }
  770. switch ($origin) {
  771. case 'zip':
  772. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  773. break;
  774. case 'manual':
  775. default:
  776. $get_max = "SELECT MAX(display_order)
  777. FROM $tbl_lp WHERE c_id = $course_id";
  778. $res_max = Database::query($get_max);
  779. if (Database::num_rows($res_max) < 1) {
  780. $dsp = 1;
  781. } else {
  782. $row = Database::fetch_array($res_max);
  783. $dsp = $row[0] + 1;
  784. }
  785. $params = [
  786. 'c_id' => $course_id,
  787. 'lp_type' => $type,
  788. 'name' => $name,
  789. 'description' => $description,
  790. 'path' => '',
  791. 'default_view_mod' => 'embedded',
  792. 'default_encoding' => 'UTF-8',
  793. 'display_order' => $dsp,
  794. 'content_maker' => 'Chamilo',
  795. 'content_local' => 'local',
  796. 'js_lib' => '',
  797. 'session_id' => $session_id,
  798. 'created_on' => api_get_utc_datetime(),
  799. 'modified_on' => api_get_utc_datetime(),
  800. 'publicated_on' => $publicated_on,
  801. 'expired_on' => $expired_on,
  802. 'category_id' => $categoryId,
  803. 'force_commit' => 0,
  804. 'content_license' => '',
  805. 'debug' => 0,
  806. 'theme' => '',
  807. 'preview_image' => '',
  808. 'author' => '',
  809. 'prerequisite' => 0,
  810. 'hide_toc_frame' => 0,
  811. 'seriousgame_mode' => 0,
  812. 'autolaunch' => 0,
  813. 'max_attempts' => 0,
  814. 'subscribe_users' => 0,
  815. 'accumulate_scorm_time' => 1,
  816. ];
  817. $id = Database::insert($tbl_lp, $params);
  818. if ($id > 0) {
  819. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  820. Database::query($sql);
  821. // Insert into item_property.
  822. api_item_property_update(
  823. $courseInfo,
  824. TOOL_LEARNPATH,
  825. $id,
  826. 'LearnpathAdded',
  827. $userId
  828. );
  829. api_set_default_visibility(
  830. $id,
  831. TOOL_LEARNPATH,
  832. 0,
  833. $courseInfo,
  834. $session_id,
  835. $userId
  836. );
  837. return $id;
  838. }
  839. break;
  840. }
  841. }
  842. /**
  843. * Auto completes the parents of an item in case it's been completed or passed.
  844. *
  845. * @param int $item Optional ID of the item from which to look for parents
  846. */
  847. public function autocomplete_parents($item)
  848. {
  849. $debug = $this->debug;
  850. if ($debug) {
  851. error_log('Learnpath::autocomplete_parents()');
  852. }
  853. if (empty($item)) {
  854. $item = $this->current;
  855. }
  856. $currentItem = $this->getItem($item);
  857. if ($currentItem) {
  858. $parent_id = $currentItem->get_parent();
  859. $parent = $this->getItem($parent_id);
  860. if ($parent) {
  861. // if $item points to an object and there is a parent.
  862. if ($debug) {
  863. error_log(
  864. 'Autocompleting parent of item '.$item.' '.
  865. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  866. 0
  867. );
  868. }
  869. // New experiment including failed and browsed in completed status.
  870. //$current_status = $currentItem->get_status();
  871. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  872. // Fixes chapter auto complete
  873. if (true) {
  874. // If the current item is completed or passes or succeeded.
  875. $updateParentStatus = true;
  876. if ($debug) {
  877. error_log('Status of current item is alright');
  878. }
  879. foreach ($parent->get_children() as $childItemId) {
  880. $childItem = $this->getItem($childItemId);
  881. // If children was not set try to get the info
  882. if (empty($childItem->db_item_view_id)) {
  883. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  884. }
  885. // Check all his brothers (parent's children) for completion status.
  886. if ($childItemId != $item) {
  887. if ($debug) {
  888. error_log(
  889. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  890. 0
  891. );
  892. }
  893. // Trying completing parents of failed and browsed items as well.
  894. if ($childItem->status_is(
  895. [
  896. 'completed',
  897. 'passed',
  898. 'succeeded',
  899. 'browsed',
  900. 'failed',
  901. ]
  902. )
  903. ) {
  904. // Keep completion status to true.
  905. continue;
  906. } else {
  907. if ($debug > 2) {
  908. error_log(
  909. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
  910. 0
  911. );
  912. }
  913. $updateParentStatus = false;
  914. break;
  915. }
  916. }
  917. }
  918. if ($updateParentStatus) {
  919. // If all the children were completed:
  920. $parent->set_status('completed');
  921. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  922. // Force the status to "completed"
  923. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  924. $this->update_queue[$parent->get_id()] = 'completed';
  925. if ($debug) {
  926. error_log(
  927. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  928. print_r($this->update_queue, 1),
  929. 0
  930. );
  931. }
  932. // Recursive call.
  933. $this->autocomplete_parents($parent->get_id());
  934. }
  935. }
  936. } else {
  937. if ($debug) {
  938. error_log("Parent #$parent_id does not exists");
  939. }
  940. }
  941. } else {
  942. if ($debug) {
  943. error_log("#$item is an item that doesn't have parents");
  944. }
  945. }
  946. }
  947. /**
  948. * Closes the current resource.
  949. *
  950. * Stops the timer
  951. * Saves into the database if required
  952. * Clears the current resource data from this object
  953. *
  954. * @return bool True on success, false on failure
  955. */
  956. public function close()
  957. {
  958. if ($this->debug > 0) {
  959. error_log('In learnpath::close()', 0);
  960. }
  961. if (empty($this->lp_id)) {
  962. $this->error = 'Trying to close this learnpath but no ID is set';
  963. return false;
  964. }
  965. $this->current_time_stop = time();
  966. $this->ordered_items = [];
  967. $this->index = 0;
  968. unset($this->lp_id);
  969. //unset other stuff
  970. return true;
  971. }
  972. /**
  973. * Static admin function allowing removal of a learnpath.
  974. *
  975. * @param array $courseInfo
  976. * @param int $id Learnpath ID
  977. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  978. *
  979. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  980. */
  981. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  982. {
  983. $course_id = api_get_course_int_id();
  984. if (!empty($courseInfo)) {
  985. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  986. }
  987. // TODO: Implement a way of getting this to work when the current object is not set.
  988. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  989. // If an ID is specifically given and the current LP is not the same, prevent delete.
  990. if (!empty($id) && ($id != $this->lp_id)) {
  991. return false;
  992. }
  993. $lp = Database::get_course_table(TABLE_LP_MAIN);
  994. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  995. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  996. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  997. // Delete lp item id.
  998. foreach ($this->items as $lpItemId => $dummy) {
  999. $sql = "DELETE FROM $lp_item_view
  1000. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  1001. Database::query($sql);
  1002. }
  1003. // Proposed by Christophe (nickname: clefevre)
  1004. $sql = "DELETE FROM $lp_item
  1005. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1006. Database::query($sql);
  1007. $sql = "DELETE FROM $lp_view
  1008. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1009. Database::query($sql);
  1010. self::toggle_publish($this->lp_id, 'i');
  1011. if ($this->type == 2 || $this->type == 3) {
  1012. // This is a scorm learning path, delete the files as well.
  1013. $sql = "SELECT path FROM $lp
  1014. WHERE iid = ".$this->lp_id;
  1015. $res = Database::query($sql);
  1016. if (Database::num_rows($res) > 0) {
  1017. $row = Database::fetch_array($res);
  1018. $path = $row['path'];
  1019. $sql = "SELECT id FROM $lp
  1020. WHERE
  1021. c_id = $course_id AND
  1022. path = '$path' AND
  1023. iid != ".$this->lp_id;
  1024. $res = Database::query($sql);
  1025. if (Database::num_rows($res) > 0) {
  1026. // Another learning path uses this directory, so don't delete it.
  1027. if ($this->debug > 2) {
  1028. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1029. }
  1030. } else {
  1031. // No other LP uses that directory, delete it.
  1032. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1033. // The absolute system path for this course.
  1034. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1035. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1036. if ($this->debug > 2) {
  1037. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1038. }
  1039. // Proposed by Christophe (clefevre).
  1040. if (strcmp(substr($path, -2), "/.") == 0) {
  1041. $path = substr($path, 0, -1); // Remove "." at the end.
  1042. }
  1043. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1044. rmdirr($course_scorm_dir.$path);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1050. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1051. // Delete tools
  1052. $sql = "DELETE FROM $tbl_tool
  1053. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1054. Database::query($sql);
  1055. $sql = "DELETE FROM $lp
  1056. WHERE iid = ".$this->lp_id;
  1057. Database::query($sql);
  1058. // Updates the display order of all lps.
  1059. $this->update_display_order();
  1060. api_item_property_update(
  1061. api_get_course_info(),
  1062. TOOL_LEARNPATH,
  1063. $this->lp_id,
  1064. 'delete',
  1065. api_get_user_id()
  1066. );
  1067. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1068. api_get_course_id(),
  1069. 4,
  1070. $id,
  1071. api_get_session_id()
  1072. );
  1073. if ($link_info !== false) {
  1074. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1075. }
  1076. if (api_get_setting('search_enabled') == 'true') {
  1077. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1078. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1079. }
  1080. }
  1081. /**
  1082. * Removes all the children of one item - dangerous!
  1083. *
  1084. * @param int $id Element ID of which children have to be removed
  1085. *
  1086. * @return int Total number of children removed
  1087. */
  1088. public function delete_children_items($id)
  1089. {
  1090. $course_id = $this->course_info['real_id'];
  1091. if ($this->debug > 0) {
  1092. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1093. }
  1094. $num = 0;
  1095. if (empty($id) || $id != strval(intval($id))) {
  1096. return false;
  1097. }
  1098. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1099. $sql = "SELECT * FROM $lp_item
  1100. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1101. $res = Database::query($sql);
  1102. while ($row = Database::fetch_array($res)) {
  1103. $num += $this->delete_children_items($row['iid']);
  1104. $sql = "DELETE FROM $lp_item
  1105. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1106. Database::query($sql);
  1107. $num++;
  1108. }
  1109. return $num;
  1110. }
  1111. /**
  1112. * Removes an item from the current learnpath.
  1113. *
  1114. * @param int $id Elem ID (0 if first)
  1115. *
  1116. * @return int Number of elements moved
  1117. *
  1118. * @todo implement resource removal
  1119. */
  1120. public function delete_item($id)
  1121. {
  1122. $course_id = api_get_course_int_id();
  1123. if ($this->debug > 0) {
  1124. error_log('In learnpath::delete_item()', 0);
  1125. }
  1126. // TODO: Implement the resource removal.
  1127. if (empty($id) || $id != strval(intval($id))) {
  1128. return false;
  1129. }
  1130. // First select item to get previous, next, and display order.
  1131. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1132. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1133. $res_sel = Database::query($sql_sel);
  1134. if (Database::num_rows($res_sel) < 1) {
  1135. return false;
  1136. }
  1137. $row = Database::fetch_array($res_sel);
  1138. $previous = $row['previous_item_id'];
  1139. $next = $row['next_item_id'];
  1140. $display = $row['display_order'];
  1141. $parent = $row['parent_item_id'];
  1142. $lp = $row['lp_id'];
  1143. // Delete children items.
  1144. $num = $this->delete_children_items($id);
  1145. if ($this->debug > 2) {
  1146. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1147. }
  1148. // Now delete the item.
  1149. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1150. if ($this->debug > 2) {
  1151. error_log('Deleting item: '.$sql_del, 0);
  1152. }
  1153. Database::query($sql_del);
  1154. // Now update surrounding items.
  1155. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1156. WHERE iid = $previous";
  1157. Database::query($sql_upd);
  1158. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1159. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1160. Database::query($sql_upd);
  1161. // Now update all following items with new display order.
  1162. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1163. WHERE
  1164. c_id = $course_id AND
  1165. lp_id = $lp AND
  1166. parent_item_id = $parent AND
  1167. display_order > $display";
  1168. Database::query($sql_all);
  1169. //Removing prerequisites since the item will not longer exist
  1170. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1171. WHERE c_id = $course_id AND prerequisite = $id";
  1172. Database::query($sql_all);
  1173. $sql = "UPDATE $lp_item
  1174. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1175. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1176. Database::query($sql);
  1177. // Remove from search engine if enabled.
  1178. if (api_get_setting('search_enabled') === 'true') {
  1179. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1180. $sql = 'SELECT * FROM %s
  1181. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1182. LIMIT 1';
  1183. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1184. $res = Database::query($sql);
  1185. if (Database::num_rows($res) > 0) {
  1186. $row2 = Database::fetch_array($res);
  1187. $di = new ChamiloIndexer();
  1188. $di->remove_document($row2['search_did']);
  1189. }
  1190. $sql = 'DELETE FROM %s
  1191. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1192. LIMIT 1';
  1193. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1194. Database::query($sql);
  1195. }
  1196. }
  1197. /**
  1198. * Updates an item's content in place.
  1199. *
  1200. * @param int $id Element ID
  1201. * @param int $parent Parent item ID
  1202. * @param int $previous Previous item ID
  1203. * @param string $title Item title
  1204. * @param string $description Item description
  1205. * @param string $prerequisites Prerequisites (optional)
  1206. * @param array $audio The array resulting of the $_FILES[mp3] element
  1207. * @param int $max_time_allowed
  1208. * @param string $url
  1209. *
  1210. * @return bool True on success, false on error
  1211. */
  1212. public function edit_item(
  1213. $id,
  1214. $parent,
  1215. $previous,
  1216. $title,
  1217. $description,
  1218. $prerequisites = '0',
  1219. $audio = [],
  1220. $max_time_allowed = 0,
  1221. $url = ''
  1222. ) {
  1223. $course_id = api_get_course_int_id();
  1224. $_course = api_get_course_info();
  1225. $id = (int) $id;
  1226. if (empty($max_time_allowed)) {
  1227. $max_time_allowed = 0;
  1228. }
  1229. if (empty($id) || empty($_course)) {
  1230. return false;
  1231. }
  1232. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1233. $sql = "SELECT * FROM $tbl_lp_item
  1234. WHERE iid = $id";
  1235. $res_select = Database::query($sql);
  1236. $row_select = Database::fetch_array($res_select);
  1237. $audio_update_sql = '';
  1238. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1239. // Create the audio folder if it does not exist yet.
  1240. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1241. if (!is_dir($filepath.'audio')) {
  1242. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1243. $audio_id = add_document(
  1244. $_course,
  1245. '/audio',
  1246. 'folder',
  1247. 0,
  1248. 'audio'
  1249. );
  1250. api_item_property_update(
  1251. $_course,
  1252. TOOL_DOCUMENT,
  1253. $audio_id,
  1254. 'FolderCreated',
  1255. api_get_user_id(),
  1256. null,
  1257. null,
  1258. null,
  1259. null,
  1260. api_get_session_id()
  1261. );
  1262. api_item_property_update(
  1263. $_course,
  1264. TOOL_DOCUMENT,
  1265. $audio_id,
  1266. 'invisible',
  1267. api_get_user_id(),
  1268. null,
  1269. null,
  1270. null,
  1271. null,
  1272. api_get_session_id()
  1273. );
  1274. }
  1275. // Upload file in documents.
  1276. $pi = pathinfo($audio['name']);
  1277. if ($pi['extension'] === 'mp3') {
  1278. $c_det = api_get_course_info($this->cc);
  1279. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1280. $path = handle_uploaded_document(
  1281. $c_det,
  1282. $audio,
  1283. $bp,
  1284. '/audio',
  1285. api_get_user_id(),
  1286. 0,
  1287. null,
  1288. 0,
  1289. 'rename',
  1290. false,
  1291. 0
  1292. );
  1293. $path = substr($path, 7);
  1294. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1295. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1296. }
  1297. }
  1298. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1299. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1300. // TODO: htmlspecialchars to be checked for encoding related problems.
  1301. if ($same_parent && $same_previous) {
  1302. // Only update title and description.
  1303. $sql = "UPDATE $tbl_lp_item
  1304. SET title = '".Database::escape_string($title)."',
  1305. prerequisite = '".$prerequisites."',
  1306. description = '".Database::escape_string($description)."'
  1307. ".$audio_update_sql.",
  1308. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1309. WHERE iid = $id";
  1310. Database::query($sql);
  1311. } else {
  1312. $old_parent = $row_select['parent_item_id'];
  1313. $old_previous = $row_select['previous_item_id'];
  1314. $old_next = $row_select['next_item_id'];
  1315. $old_order = $row_select['display_order'];
  1316. $old_prerequisite = $row_select['prerequisite'];
  1317. $old_max_time_allowed = $row_select['max_time_allowed'];
  1318. /* BEGIN -- virtually remove the current item id */
  1319. /* for the next and previous item it is like the current item doesn't exist anymore */
  1320. if ($old_previous != 0) {
  1321. // Next
  1322. $sql = "UPDATE $tbl_lp_item
  1323. SET next_item_id = $old_next
  1324. WHERE iid = $old_previous";
  1325. Database::query($sql);
  1326. }
  1327. if (!empty($old_next)) {
  1328. // Previous
  1329. $sql = "UPDATE $tbl_lp_item
  1330. SET previous_item_id = $old_previous
  1331. WHERE iid = $old_next";
  1332. Database::query($sql);
  1333. }
  1334. // display_order - 1 for every item with a display_order
  1335. // bigger then the display_order of the current item.
  1336. $sql = "UPDATE $tbl_lp_item
  1337. SET display_order = display_order - 1
  1338. WHERE
  1339. c_id = $course_id AND
  1340. display_order > $old_order AND
  1341. lp_id = ".$this->lp_id." AND
  1342. parent_item_id = $old_parent";
  1343. Database::query($sql);
  1344. /* END -- virtually remove the current item id */
  1345. /* BEGIN -- update the current item id to his new location */
  1346. if ($previous == 0) {
  1347. // Select the data of the item that should come after the current item.
  1348. $sql = "SELECT id, display_order
  1349. FROM $tbl_lp_item
  1350. WHERE
  1351. c_id = $course_id AND
  1352. lp_id = ".$this->lp_id." AND
  1353. parent_item_id = $parent AND
  1354. previous_item_id = $previous";
  1355. $res_select_old = Database::query($sql);
  1356. $row_select_old = Database::fetch_array($res_select_old);
  1357. // If the new parent didn't have children before.
  1358. if (Database::num_rows($res_select_old) == 0) {
  1359. $new_next = 0;
  1360. $new_order = 1;
  1361. } else {
  1362. $new_next = $row_select_old['id'];
  1363. $new_order = $row_select_old['display_order'];
  1364. }
  1365. } else {
  1366. // Select the data of the item that should come before the current item.
  1367. $sql = "SELECT next_item_id, display_order
  1368. FROM $tbl_lp_item
  1369. WHERE iid = $previous";
  1370. $res_select_old = Database::query($sql);
  1371. $row_select_old = Database::fetch_array($res_select_old);
  1372. $new_next = $row_select_old['next_item_id'];
  1373. $new_order = $row_select_old['display_order'] + 1;
  1374. }
  1375. // TODO: htmlspecialchars to be checked for encoding related problems.
  1376. // Update the current item with the new data.
  1377. $sql = "UPDATE $tbl_lp_item
  1378. SET
  1379. title = '".Database::escape_string($title)."',
  1380. description = '".Database::escape_string($description)."',
  1381. parent_item_id = $parent,
  1382. previous_item_id = $previous,
  1383. next_item_id = $new_next,
  1384. display_order = $new_order
  1385. $audio_update_sql
  1386. WHERE iid = $id";
  1387. Database::query($sql);
  1388. if ($previous != 0) {
  1389. // Update the previous item's next_item_id.
  1390. $sql = "UPDATE $tbl_lp_item
  1391. SET next_item_id = $id
  1392. WHERE iid = $previous";
  1393. Database::query($sql);
  1394. }
  1395. if (!empty($new_next)) {
  1396. // Update the next item's previous_item_id.
  1397. $sql = "UPDATE $tbl_lp_item
  1398. SET previous_item_id = $id
  1399. WHERE iid = $new_next";
  1400. Database::query($sql);
  1401. }
  1402. if ($old_prerequisite != $prerequisites) {
  1403. $sql = "UPDATE $tbl_lp_item
  1404. SET prerequisite = '$prerequisites'
  1405. WHERE iid = $id";
  1406. Database::query($sql);
  1407. }
  1408. if ($old_max_time_allowed != $max_time_allowed) {
  1409. // update max time allowed
  1410. $sql = "UPDATE $tbl_lp_item
  1411. SET max_time_allowed = $max_time_allowed
  1412. WHERE iid = $id";
  1413. Database::query($sql);
  1414. }
  1415. // Update all the items with the same or a bigger display_order than the current item.
  1416. $sql = "UPDATE $tbl_lp_item
  1417. SET display_order = display_order + 1
  1418. WHERE
  1419. c_id = $course_id AND
  1420. lp_id = ".$this->get_id()." AND
  1421. iid <> $id AND
  1422. parent_item_id = $parent AND
  1423. display_order >= $new_order";
  1424. Database::query($sql);
  1425. }
  1426. if ($row_select['item_type'] == 'link') {
  1427. $link = new Link();
  1428. $linkId = $row_select['path'];
  1429. $link->updateLink($linkId, $url);
  1430. }
  1431. }
  1432. /**
  1433. * Updates an item's prereq in place.
  1434. *
  1435. * @param int $id Element ID
  1436. * @param string $prerequisite_id Prerequisite Element ID
  1437. * @param int $minScore Prerequisite min score
  1438. * @param int $maxScore Prerequisite max score
  1439. *
  1440. * @return bool True on success, false on error
  1441. */
  1442. public function edit_item_prereq(
  1443. $id,
  1444. $prerequisite_id,
  1445. $minScore = 0,
  1446. $maxScore = 100
  1447. ) {
  1448. if ($this->debug > 0) {
  1449. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$minScore.','.$maxScore.')', 0);
  1450. }
  1451. $id = (int) $id;
  1452. $prerequisite_id = (int) $prerequisite_id;
  1453. if (empty($id)) {
  1454. return false;
  1455. }
  1456. if (empty($minScore) || $minScore < 0) {
  1457. $minScore = 0;
  1458. }
  1459. if (empty($maxScore) || $maxScore < 0) {
  1460. $maxScore = 100;
  1461. }
  1462. $minScore = floatval($minScore);
  1463. $maxScore = floatval($maxScore);
  1464. if (empty($prerequisite_id)) {
  1465. $prerequisite_id = 'NULL';
  1466. $minScore = 0;
  1467. $maxScore = 100;
  1468. }
  1469. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1470. $sql = " UPDATE $tbl_lp_item
  1471. SET
  1472. prerequisite = $prerequisite_id ,
  1473. prerequisite_min_score = $minScore ,
  1474. prerequisite_max_score = $maxScore
  1475. WHERE iid = $id";
  1476. Database::query($sql);
  1477. return true;
  1478. }
  1479. /**
  1480. * Gets all the chapters belonging to the same parent as the item/chapter given
  1481. * Can also be called as abstract method.
  1482. *
  1483. * @deprecated not used
  1484. *
  1485. * @param int $id Item ID
  1486. *
  1487. * @return array A list of all the "brother items" (or an empty array on failure)
  1488. */
  1489. public function getSiblingDirectories($id)
  1490. {
  1491. $course_id = api_get_course_int_id();
  1492. if (empty($id) || $id != strval(intval($id))) {
  1493. return [];
  1494. }
  1495. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1496. $sql_parent = "SELECT * FROM $lp_item
  1497. WHERE iid = $id AND item_type='dir'";
  1498. $res_parent = Database::query($sql_parent);
  1499. if (Database::num_rows($res_parent) > 0) {
  1500. $row_parent = Database::fetch_array($res_parent);
  1501. $parent = $row_parent['parent_item_id'];
  1502. $sql = "SELECT * FROM $lp_item
  1503. WHERE
  1504. parent_item_id = $parent AND
  1505. iid = $id AND
  1506. item_type='dir'
  1507. ORDER BY display_order";
  1508. $res_bros = Database::query($sql);
  1509. $list = [];
  1510. while ($row_bro = Database::fetch_array($res_bros)) {
  1511. $list[] = $row_bro;
  1512. }
  1513. return $list;
  1514. }
  1515. return [];
  1516. }
  1517. /**
  1518. * Gets all the items belonging to the same parent as the item given
  1519. * Can also be called as abstract method.
  1520. *
  1521. * @deprecated not used
  1522. *
  1523. * @param int $id Item ID
  1524. *
  1525. * @return array A list of all the "brother items" (or an empty array on failure)
  1526. */
  1527. public function get_brother_items($id)
  1528. {
  1529. $course_id = api_get_course_int_id();
  1530. if (empty($id) || $id != strval(intval($id))) {
  1531. return [];
  1532. }
  1533. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1534. $sql_parent = "SELECT * FROM $lp_item
  1535. WHERE iid = $id";
  1536. $res_parent = Database::query($sql_parent);
  1537. if (Database::num_rows($res_parent) > 0) {
  1538. $row_parent = Database::fetch_array($res_parent);
  1539. $parent = $row_parent['parent_item_id'];
  1540. $sql = "SELECT * FROM $lp_item
  1541. WHERE c_id = $course_id AND parent_item_id = $parent
  1542. ORDER BY display_order";
  1543. $res_bros = Database::query($sql);
  1544. $list = [];
  1545. while ($row_bro = Database::fetch_array($res_bros)) {
  1546. $list[] = $row_bro;
  1547. }
  1548. return $list;
  1549. }
  1550. return [];
  1551. }
  1552. /**
  1553. * Get the specific prefix index terms of this learning path.
  1554. *
  1555. * @param string $prefix
  1556. *
  1557. * @return array Array of terms
  1558. */
  1559. public function get_common_index_terms_by_prefix($prefix)
  1560. {
  1561. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1562. $terms = get_specific_field_values_list_by_prefix(
  1563. $prefix,
  1564. $this->cc,
  1565. TOOL_LEARNPATH,
  1566. $this->lp_id
  1567. );
  1568. $prefix_terms = [];
  1569. if (!empty($terms)) {
  1570. foreach ($terms as $term) {
  1571. $prefix_terms[] = $term['value'];
  1572. }
  1573. }
  1574. return $prefix_terms;
  1575. }
  1576. /**
  1577. * Gets the number of items currently completed.
  1578. *
  1579. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1580. *
  1581. * @return int The number of items currently completed
  1582. */
  1583. public function get_complete_items_count($failedStatusException = false)
  1584. {
  1585. $i = 0;
  1586. $completedStatusList = [
  1587. 'completed',
  1588. 'passed',
  1589. 'succeeded',
  1590. 'browsed',
  1591. ];
  1592. if (!$failedStatusException) {
  1593. $completedStatusList[] = 'failed';
  1594. }
  1595. foreach ($this->items as $id => $dummy) {
  1596. // Trying failed and browsed considered "progressed" as well.
  1597. if ($this->items[$id]->status_is($completedStatusList) &&
  1598. $this->items[$id]->get_type() != 'dir'
  1599. ) {
  1600. $i++;
  1601. }
  1602. }
  1603. return $i;
  1604. }
  1605. /**
  1606. * Gets the current item ID.
  1607. *
  1608. * @return int The current learnpath item id
  1609. */
  1610. public function get_current_item_id()
  1611. {
  1612. $current = 0;
  1613. if (!empty($this->current)) {
  1614. $current = (int) $this->current;
  1615. }
  1616. return $current;
  1617. }
  1618. /**
  1619. * Force to get the first learnpath item id.
  1620. *
  1621. * @return int The current learnpath item id
  1622. */
  1623. public function get_first_item_id()
  1624. {
  1625. $current = 0;
  1626. if (is_array($this->ordered_items)) {
  1627. $current = $this->ordered_items[0];
  1628. }
  1629. return $current;
  1630. }
  1631. /**
  1632. * Gets the total number of items available for viewing in this SCORM.
  1633. *
  1634. * @return int The total number of items
  1635. */
  1636. public function get_total_items_count()
  1637. {
  1638. return count($this->items);
  1639. }
  1640. /**
  1641. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1642. *
  1643. * @return int The total no-chapters number of items
  1644. */
  1645. public function getTotalItemsCountWithoutDirs()
  1646. {
  1647. $total = 0;
  1648. $typeListNotToCount = self::getChapterTypes();
  1649. foreach ($this->items as $temp2) {
  1650. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1651. $total++;
  1652. }
  1653. }
  1654. return $total;
  1655. }
  1656. /**
  1657. * Sets the first element URL.
  1658. */
  1659. public function first()
  1660. {
  1661. if ($this->debug > 0) {
  1662. error_log('In learnpath::first()', 0);
  1663. error_log('$this->last_item_seen '.$this->last_item_seen);
  1664. }
  1665. // Test if the last_item_seen exists and is not a dir.
  1666. if (count($this->ordered_items) == 0) {
  1667. $this->index = 0;
  1668. }
  1669. if (!empty($this->last_item_seen) &&
  1670. !empty($this->items[$this->last_item_seen]) &&
  1671. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1672. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1673. //&& !$this->items[$this->last_item_seen]->is_done()
  1674. ) {
  1675. if ($this->debug > 2) {
  1676. error_log(
  1677. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1678. $this->items[$this->last_item_seen]->get_type()
  1679. );
  1680. }
  1681. $index = -1;
  1682. foreach ($this->ordered_items as $myindex => $item_id) {
  1683. if ($item_id == $this->last_item_seen) {
  1684. $index = $myindex;
  1685. break;
  1686. }
  1687. }
  1688. if ($index == -1) {
  1689. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1690. if ($this->debug > 2) {
  1691. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1692. }
  1693. return false;
  1694. } else {
  1695. $this->last = $this->last_item_seen;
  1696. $this->current = $this->last_item_seen;
  1697. $this->index = $index;
  1698. }
  1699. } else {
  1700. if ($this->debug > 2) {
  1701. error_log('In learnpath::first() - No last item seen', 0);
  1702. }
  1703. $index = 0;
  1704. // Loop through all ordered items and stop at the first item that is
  1705. // not a directory *and* that has not been completed yet.
  1706. while (!empty($this->ordered_items[$index]) &&
  1707. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1708. (
  1709. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1710. $this->items[$this->ordered_items[$index]]->is_done() === true
  1711. ) && $index < $this->max_ordered_items) {
  1712. $index++;
  1713. }
  1714. $this->last = $this->current;
  1715. // current is
  1716. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1717. $this->index = $index;
  1718. if ($this->debug > 2) {
  1719. error_log('$index '.$index);
  1720. error_log('In learnpath::first() - No last item seen');
  1721. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1722. }
  1723. }
  1724. if ($this->debug > 2) {
  1725. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1726. }
  1727. }
  1728. /**
  1729. * Gets the information about an item in a format usable as JavaScript to update
  1730. * the JS API by just printing this content into the <head> section of the message frame.
  1731. *
  1732. * @param int $item_id
  1733. *
  1734. * @return string
  1735. */
  1736. public function get_js_info($item_id = 0)
  1737. {
  1738. if ($this->debug > 0) {
  1739. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1740. }
  1741. $info = '';
  1742. $item_id = (int) $item_id;
  1743. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1744. //if item is defined, return values from DB
  1745. $oItem = $this->items[$item_id];
  1746. $info .= '<script language="javascript">';
  1747. $info .= "top.set_score(".$oItem->get_score().");\n";
  1748. $info .= "top.set_max(".$oItem->get_max().");\n";
  1749. $info .= "top.set_min(".$oItem->get_min().");\n";
  1750. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1751. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1752. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1753. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1754. $info .= "top.set_flag_synchronized();";
  1755. $info .= '</script>';
  1756. if ($this->debug > 2) {
  1757. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1758. }
  1759. return $info;
  1760. } else {
  1761. // If item_id is empty, just update to default SCORM data.
  1762. $info .= '<script language="javascript">';
  1763. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1764. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1765. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1766. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1767. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1768. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1769. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1770. $info .= "top.set_flag_synchronized();";
  1771. $info .= '</script>';
  1772. if ($this->debug > 2) {
  1773. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1774. }
  1775. return $info;
  1776. }
  1777. }
  1778. /**
  1779. * Gets the js library from the database.
  1780. *
  1781. * @return string The name of the javascript library to be used
  1782. */
  1783. public function get_js_lib()
  1784. {
  1785. $lib = '';
  1786. if (!empty($this->js_lib)) {
  1787. $lib = $this->js_lib;
  1788. }
  1789. return $lib;
  1790. }
  1791. /**
  1792. * Gets the learnpath database ID.
  1793. *
  1794. * @return int Learnpath ID in the lp table
  1795. */
  1796. public function get_id()
  1797. {
  1798. if (!empty($this->lp_id)) {
  1799. return (int) $this->lp_id;
  1800. }
  1801. return 0;
  1802. }
  1803. /**
  1804. * Gets the last element URL.
  1805. *
  1806. * @return string URL to load into the viewer
  1807. */
  1808. public function get_last()
  1809. {
  1810. // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1811. if (count($this->ordered_items) > 0) {
  1812. $this->index = count($this->ordered_items) - 1;
  1813. return $this->ordered_items[$this->index];
  1814. }
  1815. return false;
  1816. }
  1817. /**
  1818. * Get the last element in the first level.
  1819. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1820. *
  1821. * @return mixed
  1822. */
  1823. public function getLastInFirstLevel()
  1824. {
  1825. try {
  1826. $lastId = Database::getManager()
  1827. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1828. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1829. ->setMaxResults(1)
  1830. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1831. ->getSingleScalarResult();
  1832. return $lastId;
  1833. } catch (Exception $exception) {
  1834. return 0;
  1835. }
  1836. }
  1837. /**
  1838. * Gets the navigation bar for the learnpath display screen.
  1839. *
  1840. * @param string $barId
  1841. *
  1842. * @return string The HTML string to use as a navigation bar
  1843. */
  1844. public function get_navigation_bar($barId = '')
  1845. {
  1846. if (empty($barId)) {
  1847. $barId = 'control-top';
  1848. }
  1849. $lpId = $this->lp_id;
  1850. $mycurrentitemid = $this->get_current_item_id();
  1851. $reportingText = get_lang('Reporting');
  1852. $previousText = get_lang('ScormPrevious');
  1853. $nextText = get_lang('ScormNext');
  1854. $fullScreenText = get_lang('ScormExitFullScreen');
  1855. $settings = api_get_configuration_value('lp_view_settings');
  1856. $display = isset($settings['display']) ? $settings['display'] : false;
  1857. $reportingIcon = '
  1858. <a class="icon-toolbar"
  1859. id="stats_link"
  1860. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1861. onclick="window.parent.API.save_asset(); return true;"
  1862. target="content_name" title="'.$reportingText.'">
  1863. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1864. </a>';
  1865. if (!empty($display)) {
  1866. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1867. if ($showReporting === false) {
  1868. $reportingIcon = '';
  1869. }
  1870. }
  1871. $hideArrows = false;
  1872. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1873. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1874. }
  1875. $previousIcon = '';
  1876. $nextIcon = '';
  1877. if ($hideArrows === false) {
  1878. $previousIcon = '
  1879. <a class="icon-toolbar" id="scorm-previous" href="#"
  1880. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1881. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1882. </a>';
  1883. $nextIcon = '
  1884. <a class="icon-toolbar" id="scorm-next" href="#"
  1885. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1886. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1887. </a>';
  1888. }
  1889. if ($this->mode === 'fullscreen') {
  1890. $navbar = '
  1891. <span id="'.$barId.'" class="buttons">
  1892. '.$reportingIcon.'
  1893. '.$previousIcon.'
  1894. '.$nextIcon.'
  1895. <a class="icon-toolbar" id="view-embedded"
  1896. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1897. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1898. </a>
  1899. </span>';
  1900. } else {
  1901. $navbar = '
  1902. <span id="'.$barId.'" class="buttons text-right">
  1903. '.$reportingIcon.'
  1904. '.$previousIcon.'
  1905. '.$nextIcon.'
  1906. </span>';
  1907. }
  1908. return $navbar;
  1909. }
  1910. /**
  1911. * Gets the next resource in queue (url).
  1912. *
  1913. * @return string URL to load into the viewer
  1914. */
  1915. public function get_next_index()
  1916. {
  1917. if ($this->debug > 0) {
  1918. error_log('In learnpath::get_next_index()', 0);
  1919. }
  1920. // TODO
  1921. $index = $this->index;
  1922. $index++;
  1923. if ($this->debug > 2) {
  1924. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1925. }
  1926. while (
  1927. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1928. $index < $this->max_ordered_items
  1929. ) {
  1930. $index++;
  1931. if ($index == $this->max_ordered_items) {
  1932. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1933. return $this->index;
  1934. } else {
  1935. return $index;
  1936. }
  1937. }
  1938. }
  1939. if (empty($this->ordered_items[$index])) {
  1940. return $this->index;
  1941. }
  1942. if ($this->debug > 2) {
  1943. error_log('index is now '.$index, 0);
  1944. }
  1945. return $index;
  1946. }
  1947. /**
  1948. * Gets item_id for the next element.
  1949. *
  1950. * @return int Next item (DB) ID
  1951. */
  1952. public function get_next_item_id()
  1953. {
  1954. if ($this->debug > 0) {
  1955. error_log('In learnpath::get_next_item_id()', 0);
  1956. }
  1957. $new_index = $this->get_next_index();
  1958. if (!empty($new_index)) {
  1959. if (isset($this->ordered_items[$new_index])) {
  1960. if ($this->debug > 2) {
  1961. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1962. }
  1963. return $this->ordered_items[$new_index];
  1964. }
  1965. }
  1966. if ($this->debug > 2) {
  1967. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1968. }
  1969. return 0;
  1970. }
  1971. /**
  1972. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1973. *
  1974. * Generally, the package provided is in the form of a zip file, so the function
  1975. * has been written to test a zip file. If not a zip, the function will return the
  1976. * default return value: ''
  1977. *
  1978. * @param string $file_path the path to the file
  1979. * @param string $file_name the original name of the file
  1980. *
  1981. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1982. */
  1983. public static function get_package_type($file_path, $file_name)
  1984. {
  1985. // Get name of the zip file without the extension.
  1986. $file_info = pathinfo($file_name);
  1987. $extension = $file_info['extension']; // Extension only.
  1988. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1989. 'dll',
  1990. 'exe',
  1991. ])) {
  1992. return 'oogie';
  1993. }
  1994. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1995. 'dll',
  1996. 'exe',
  1997. ])) {
  1998. return 'woogie';
  1999. }
  2000. $zipFile = new PclZip($file_path);
  2001. // Check the zip content (real size and file extension).
  2002. $zipContentArray = $zipFile->listContent();
  2003. $package_type = '';
  2004. $manifest = '';
  2005. $aicc_match_crs = 0;
  2006. $aicc_match_au = 0;
  2007. $aicc_match_des = 0;
  2008. $aicc_match_cst = 0;
  2009. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2010. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2011. foreach ($zipContentArray as $thisContent) {
  2012. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2013. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2014. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2015. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2016. $package_type = 'scorm';
  2017. break; // Exit the foreach loop.
  2018. } elseif (
  2019. preg_match('/aicc\//i', $thisContent['filename']) ||
  2020. in_array(
  2021. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2022. ['crs', 'au', 'des', 'cst']
  2023. )
  2024. ) {
  2025. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2026. switch ($ext) {
  2027. case 'crs':
  2028. $aicc_match_crs = 1;
  2029. break;
  2030. case 'au':
  2031. $aicc_match_au = 1;
  2032. break;
  2033. case 'des':
  2034. $aicc_match_des = 1;
  2035. break;
  2036. case 'cst':
  2037. $aicc_match_cst = 1;
  2038. break;
  2039. default:
  2040. break;
  2041. }
  2042. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2043. } else {
  2044. $package_type = '';
  2045. }
  2046. }
  2047. }
  2048. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2049. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2050. $package_type = 'aicc';
  2051. }
  2052. // Try with chamilo course builder
  2053. if (empty($package_type)) {
  2054. $package_type = 'chamilo';
  2055. }
  2056. return $package_type;
  2057. }
  2058. /**
  2059. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2060. *
  2061. * @return string URL to load into the viewer
  2062. */
  2063. public function get_previous_index()
  2064. {
  2065. $index = $this->index;
  2066. if (isset($this->ordered_items[$index - 1])) {
  2067. $index--;
  2068. while (isset($this->ordered_items[$index]) &&
  2069. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2070. ) {
  2071. $index--;
  2072. if ($index < 0) {
  2073. return $this->index;
  2074. }
  2075. }
  2076. }
  2077. return $index;
  2078. }
  2079. /**
  2080. * Gets item_id for the next element.
  2081. *
  2082. * @return int Previous item (DB) ID
  2083. */
  2084. public function get_previous_item_id()
  2085. {
  2086. $index = $this->get_previous_index();
  2087. return $this->ordered_items[$index];
  2088. }
  2089. /**
  2090. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2091. *
  2092. * @param int $lpItemId
  2093. * @param string $autostart
  2094. *
  2095. * @return string The mediaplayer HTML
  2096. */
  2097. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2098. {
  2099. $course_id = api_get_course_int_id();
  2100. $_course = api_get_course_info();
  2101. if (empty($_course)) {
  2102. return '';
  2103. }
  2104. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2105. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2106. $lpItemId = (int) $lpItemId;
  2107. /** @var learnpathItem $item */
  2108. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2109. $itemViewId = 0;
  2110. if ($item) {
  2111. $itemViewId = (int) $item->db_item_view_id;
  2112. }
  2113. // Getting all the information about the item.
  2114. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2115. 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. lp_view.iid = $itemViewId AND
  2120. lpi.iid = $lpItemId AND
  2121. lp_view.c_id = $course_id";
  2122. $result = Database::query($sql);
  2123. $row = Database::fetch_assoc($result);
  2124. $output = '';
  2125. if (!empty($row['audio'])) {
  2126. $list = $_SESSION['oLP']->get_toc();
  2127. switch ($row['item_type']) {
  2128. case 'quiz':
  2129. $type_quiz = false;
  2130. foreach ($list as $toc) {
  2131. if ($toc['id'] == $_SESSION['oLP']->current) {
  2132. $type_quiz = true;
  2133. }
  2134. }
  2135. if ($type_quiz) {
  2136. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2137. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2138. } else {
  2139. $autostart_audio = $autostart;
  2140. }
  2141. }
  2142. break;
  2143. case TOOL_READOUT_TEXT:;
  2144. $autostart_audio = 'false';
  2145. break;
  2146. default:
  2147. $autostart_audio = 'true';
  2148. }
  2149. $courseInfo = api_get_course_info();
  2150. $audio = $row['audio'];
  2151. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2152. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2153. if (!file_exists($file)) {
  2154. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2155. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2156. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2157. }
  2158. $player = Display::getMediaPlayer(
  2159. $file,
  2160. [
  2161. 'id' => 'lp_audio_media_player',
  2162. 'url' => $url,
  2163. 'autoplay' => $autostart_audio,
  2164. 'width' => '100%',
  2165. ]
  2166. );
  2167. // The mp3 player.
  2168. $output = '<div id="container">';
  2169. $output .= $player;
  2170. $output .= '</div>';
  2171. }
  2172. return $output;
  2173. }
  2174. /**
  2175. * @param int $studentId
  2176. * @param int $prerequisite
  2177. * @param array $courseInfo
  2178. * @param int $sessionId
  2179. *
  2180. * @return bool
  2181. */
  2182. public static function isBlockedByPrerequisite(
  2183. $studentId,
  2184. $prerequisite,
  2185. $courseInfo,
  2186. $sessionId
  2187. ) {
  2188. if (empty($courseInfo)) {
  2189. return false;
  2190. }
  2191. $courseId = $courseInfo['real_id'];
  2192. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2193. if ($allow) {
  2194. if (api_is_allowed_to_edit() ||
  2195. api_is_platform_admin(true) ||
  2196. api_is_drh() ||
  2197. api_is_coach($sessionId, $courseId, false)
  2198. ) {
  2199. return false;
  2200. }
  2201. }
  2202. $isBlocked = false;
  2203. if (!empty($prerequisite)) {
  2204. $progress = self::getProgress(
  2205. $prerequisite,
  2206. $studentId,
  2207. $courseId,
  2208. $sessionId
  2209. );
  2210. if ($progress < 100) {
  2211. $isBlocked = true;
  2212. }
  2213. if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  2214. // Block if it does not exceed minimum time
  2215. // Minimum time (in minutes) to pass the learning path
  2216. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2217. if ($accumulateWorkTime > 0) {
  2218. // Total time in course (sum of times in learning paths from course)
  2219. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2220. // Connect with the plugin_licences_course_session table
  2221. // which indicates what percentage of the time applies
  2222. // Minimum connection percentage
  2223. $perc = 100;
  2224. // Time from the course
  2225. $tc = $accumulateWorkTimeTotal;
  2226. // Percentage of the learning paths
  2227. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2228. // Minimum time for each learning path
  2229. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2230. // Spent time (in seconds) so far in the learning path
  2231. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2232. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2233. if ($lpTime < ($accumulateWorkTime * 60)) {
  2234. $isBlocked = true;
  2235. }
  2236. }
  2237. }
  2238. }
  2239. return $isBlocked;
  2240. }
  2241. /**
  2242. * Checks if the learning path is visible for student after the progress
  2243. * of its prerequisite is completed, considering the time availability and
  2244. * the LP visibility.
  2245. *
  2246. * @param int $lp_id
  2247. * @param int $student_id
  2248. * @param array $courseInfo
  2249. * @param int $sessionId
  2250. *
  2251. * @return bool
  2252. */
  2253. public static function is_lp_visible_for_student(
  2254. $lp_id,
  2255. $student_id,
  2256. $courseInfo = [],
  2257. $sessionId = 0
  2258. ) {
  2259. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2260. $lp_id = (int) $lp_id;
  2261. $sessionId = (int) $sessionId;
  2262. if (empty($courseInfo)) {
  2263. return false;
  2264. }
  2265. if (empty($sessionId)) {
  2266. $sessionId = api_get_session_id();
  2267. }
  2268. $courseId = $courseInfo['real_id'];
  2269. $itemInfo = api_get_item_property_info(
  2270. $courseId,
  2271. TOOL_LEARNPATH,
  2272. $lp_id,
  2273. $sessionId
  2274. );
  2275. // If the item was deleted.
  2276. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2277. return false;
  2278. }
  2279. // @todo remove this query and load the row info as a parameter
  2280. $table = Database::get_course_table(TABLE_LP_MAIN);
  2281. // Get current prerequisite
  2282. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2283. FROM $table
  2284. WHERE iid = $lp_id";
  2285. $rs = Database::query($sql);
  2286. $now = time();
  2287. if (Database::num_rows($rs) > 0) {
  2288. $row = Database::fetch_array($rs, 'ASSOC');
  2289. $prerequisite = $row['prerequisite'];
  2290. $is_visible = true;
  2291. $isBlocked = self::isBlockedByPrerequisite(
  2292. $student_id,
  2293. $prerequisite,
  2294. $courseInfo,
  2295. $sessionId
  2296. );
  2297. if ($isBlocked) {
  2298. $is_visible = false;
  2299. }
  2300. // Also check the time availability of the LP
  2301. if ($is_visible) {
  2302. // Adding visibility restrictions
  2303. if (!empty($row['publicated_on'])) {
  2304. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2305. $is_visible = false;
  2306. }
  2307. }
  2308. // Blocking empty start times see BT#2800
  2309. global $_custom;
  2310. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2311. $_custom['lps_hidden_when_no_start_date']
  2312. ) {
  2313. if (empty($row['publicated_on'])) {
  2314. $is_visible = false;
  2315. }
  2316. }
  2317. if (!empty($row['expired_on'])) {
  2318. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2319. $is_visible = false;
  2320. }
  2321. }
  2322. }
  2323. if ($is_visible) {
  2324. $subscriptionSettings = self::getSubscriptionSettings();
  2325. // Check if the subscription users/group to a LP is ON
  2326. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2327. $subscriptionSettings['allow_add_users_to_lp'] === true
  2328. ) {
  2329. // Try group
  2330. $is_visible = false;
  2331. // Checking only the user visibility
  2332. $userVisibility = api_get_item_visibility(
  2333. $courseInfo,
  2334. 'learnpath',
  2335. $row['id'],
  2336. $sessionId,
  2337. $student_id,
  2338. 'LearnpathSubscription'
  2339. );
  2340. if ($userVisibility == 1) {
  2341. $is_visible = true;
  2342. } else {
  2343. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id, $courseId);
  2344. if (!empty($userGroups)) {
  2345. foreach ($userGroups as $groupInfo) {
  2346. $groupId = $groupInfo['iid'];
  2347. $userVisibility = api_get_item_visibility(
  2348. $courseInfo,
  2349. 'learnpath',
  2350. $row['id'],
  2351. $sessionId,
  2352. null,
  2353. 'LearnpathSubscription',
  2354. $groupId
  2355. );
  2356. if ($userVisibility == 1) {
  2357. $is_visible = true;
  2358. break;
  2359. }
  2360. }
  2361. }
  2362. }
  2363. }
  2364. }
  2365. return $is_visible;
  2366. }
  2367. return false;
  2368. }
  2369. /**
  2370. * @param int $lpId
  2371. * @param int $userId
  2372. * @param int $courseId
  2373. * @param int $sessionId
  2374. *
  2375. * @return int
  2376. */
  2377. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2378. {
  2379. $lpId = (int) $lpId;
  2380. $userId = (int) $userId;
  2381. $courseId = (int) $courseId;
  2382. $sessionId = (int) $sessionId;
  2383. $sessionCondition = api_get_session_condition($sessionId);
  2384. $table = Database::get_course_table(TABLE_LP_VIEW);
  2385. $sql = "SELECT progress FROM $table
  2386. WHERE
  2387. c_id = $courseId AND
  2388. lp_id = $lpId AND
  2389. user_id = $userId $sessionCondition ";
  2390. $res = Database::query($sql);
  2391. $progress = 0;
  2392. if (Database::num_rows($res) > 0) {
  2393. $row = Database::fetch_array($res);
  2394. $progress = (int) $row['progress'];
  2395. }
  2396. return $progress;
  2397. }
  2398. /**
  2399. * @param array $lpList
  2400. * @param int $userId
  2401. * @param int $courseId
  2402. * @param int $sessionId
  2403. *
  2404. * @return array
  2405. */
  2406. public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
  2407. {
  2408. $lpList = array_map('intval', $lpList);
  2409. if (empty($lpList)) {
  2410. return [];
  2411. }
  2412. $lpList = implode("','", $lpList);
  2413. $userId = (int) $userId;
  2414. $courseId = (int) $courseId;
  2415. $sessionId = (int) $sessionId;
  2416. $sessionCondition = api_get_session_condition($sessionId);
  2417. $table = Database::get_course_table(TABLE_LP_VIEW);
  2418. $sql = "SELECT lp_id, progress FROM $table
  2419. WHERE
  2420. c_id = $courseId AND
  2421. lp_id IN ('".$lpList."') AND
  2422. user_id = $userId $sessionCondition ";
  2423. $res = Database::query($sql);
  2424. if (Database::num_rows($res) > 0) {
  2425. $list = [];
  2426. while ($row = Database::fetch_array($res)) {
  2427. $list[$row['lp_id']] = $row['progress'];
  2428. }
  2429. return $list;
  2430. }
  2431. return [];
  2432. }
  2433. /**
  2434. * Displays a progress bar
  2435. * completed so far.
  2436. *
  2437. * @param int $percentage Progress value to display
  2438. * @param string $text_add Text to display near the progress value
  2439. *
  2440. * @return string HTML string containing the progress bar
  2441. */
  2442. public static function get_progress_bar($percentage = -1, $text_add = '')
  2443. {
  2444. $text = $percentage.$text_add;
  2445. $output = '<div class="progress">
  2446. <div id="progress_bar_value"
  2447. class="progress-bar progress-bar-success" role="progressbar"
  2448. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2449. '.$text.'
  2450. </div>
  2451. </div>';
  2452. return $output;
  2453. }
  2454. /**
  2455. * @param string $mode can be '%' or 'abs'
  2456. * otherwise this value will be used $this->progress_bar_mode
  2457. *
  2458. * @return string
  2459. */
  2460. public function getProgressBar($mode = null)
  2461. {
  2462. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2463. return self::get_progress_bar($percentage, $text_add);
  2464. }
  2465. /**
  2466. * Gets the progress bar info to display inside the progress bar.
  2467. * Also used by scorm_api.php.
  2468. *
  2469. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2470. * we display a number of completed elements per total elements
  2471. * @param int $add Additional steps to fake as completed
  2472. *
  2473. * @return array Percentage or number and symbol (% or /xx)
  2474. */
  2475. public function get_progress_bar_text($mode = '', $add = 0)
  2476. {
  2477. if ($this->debug > 0) {
  2478. error_log('In learnpath::get_progress_bar_text()', 0);
  2479. }
  2480. if (empty($mode)) {
  2481. $mode = $this->progress_bar_mode;
  2482. }
  2483. $total_items = $this->getTotalItemsCountWithoutDirs();
  2484. if ($this->debug > 2) {
  2485. error_log('Total items available in this learnpath: '.$total_items, 0);
  2486. }
  2487. $completeItems = $this->get_complete_items_count();
  2488. if ($this->debug > 2) {
  2489. error_log('Items completed so far: '.$completeItems, 0);
  2490. }
  2491. if ($add != 0) {
  2492. $completeItems += $add;
  2493. if ($this->debug > 2) {
  2494. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2495. }
  2496. }
  2497. $text = '';
  2498. if ($completeItems > $total_items) {
  2499. $completeItems = $total_items;
  2500. }
  2501. $percentage = 0;
  2502. if ($mode == '%') {
  2503. if ($total_items > 0) {
  2504. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2505. } else {
  2506. $percentage = 0;
  2507. }
  2508. $percentage = number_format($percentage, 0);
  2509. $text = '%';
  2510. } elseif ($mode == 'abs') {
  2511. $percentage = $completeItems;
  2512. $text = '/'.$total_items;
  2513. }
  2514. return [
  2515. $percentage,
  2516. $text,
  2517. ];
  2518. }
  2519. /**
  2520. * Gets the progress bar mode.
  2521. *
  2522. * @return string The progress bar mode attribute
  2523. */
  2524. public function get_progress_bar_mode()
  2525. {
  2526. if (!empty($this->progress_bar_mode)) {
  2527. return $this->progress_bar_mode;
  2528. }
  2529. return '%';
  2530. }
  2531. /**
  2532. * Gets the learnpath theme (remote or local).
  2533. *
  2534. * @return string Learnpath theme
  2535. */
  2536. public function get_theme()
  2537. {
  2538. if (!empty($this->theme)) {
  2539. return $this->theme;
  2540. }
  2541. return '';
  2542. }
  2543. /**
  2544. * Gets the learnpath session id.
  2545. *
  2546. * @return int
  2547. */
  2548. public function get_lp_session_id()
  2549. {
  2550. if (!empty($this->lp_session_id)) {
  2551. return (int) $this->lp_session_id;
  2552. }
  2553. return 0;
  2554. }
  2555. /**
  2556. * Gets the learnpath image.
  2557. *
  2558. * @return string Web URL of the LP image
  2559. */
  2560. public function get_preview_image()
  2561. {
  2562. if (!empty($this->preview_image)) {
  2563. return $this->preview_image;
  2564. }
  2565. return '';
  2566. }
  2567. /**
  2568. * @param string $size
  2569. * @param string $path_type
  2570. *
  2571. * @return bool|string
  2572. */
  2573. public function get_preview_image_path($size = null, $path_type = 'web')
  2574. {
  2575. $preview_image = $this->get_preview_image();
  2576. if (isset($preview_image) && !empty($preview_image)) {
  2577. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2578. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2579. if (isset($size)) {
  2580. $info = pathinfo($preview_image);
  2581. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2582. if (file_exists($image_sys_path.$image_custom_size)) {
  2583. if ($path_type == 'web') {
  2584. return $image_path.$image_custom_size;
  2585. } else {
  2586. return $image_sys_path.$image_custom_size;
  2587. }
  2588. }
  2589. } else {
  2590. if ($path_type == 'web') {
  2591. return $image_path.$preview_image;
  2592. } else {
  2593. return $image_sys_path.$preview_image;
  2594. }
  2595. }
  2596. }
  2597. return false;
  2598. }
  2599. /**
  2600. * Gets the learnpath author.
  2601. *
  2602. * @return string LP's author
  2603. */
  2604. public function get_author()
  2605. {
  2606. if (!empty($this->author)) {
  2607. return $this->author;
  2608. }
  2609. return '';
  2610. }
  2611. /**
  2612. * Gets hide table of contents.
  2613. *
  2614. * @return int
  2615. */
  2616. public function getHideTableOfContents()
  2617. {
  2618. return (int) $this->hide_toc_frame;
  2619. }
  2620. /**
  2621. * Generate a new prerequisites string for a given item. If this item was a sco and
  2622. * its prerequisites were strings (instead of IDs), then transform those strings into
  2623. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2624. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2625. * same rule as the scormExport() method.
  2626. *
  2627. * @param int $item_id Item ID
  2628. *
  2629. * @return string Prerequisites string ready for the export as SCORM
  2630. */
  2631. public function get_scorm_prereq_string($item_id)
  2632. {
  2633. if ($this->debug > 0) {
  2634. error_log('In learnpath::get_scorm_prereq_string()');
  2635. }
  2636. if (!is_object($this->items[$item_id])) {
  2637. return false;
  2638. }
  2639. /** @var learnpathItem $oItem */
  2640. $oItem = $this->items[$item_id];
  2641. $prereq = $oItem->get_prereq_string();
  2642. if (empty($prereq)) {
  2643. return '';
  2644. }
  2645. if (preg_match('/^\d+$/', $prereq) &&
  2646. isset($this->items[$prereq]) &&
  2647. is_object($this->items[$prereq])
  2648. ) {
  2649. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2650. // then simply return it (with the ITEM_ prefix).
  2651. //return 'ITEM_' . $prereq;
  2652. return $this->items[$prereq]->ref;
  2653. } else {
  2654. if (isset($this->refs_list[$prereq])) {
  2655. // It's a simple string item from which the ID can be found in the refs list,
  2656. // so we can transform it directly to an ID for export.
  2657. return $this->items[$this->refs_list[$prereq]]->ref;
  2658. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2659. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2660. } else {
  2661. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2662. // and replace them, one by one, by the internal IDs (chamilo db)
  2663. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2664. // by a space as well.
  2665. $find = [
  2666. '&',
  2667. '|',
  2668. '~',
  2669. '=',
  2670. '<>',
  2671. '{',
  2672. '}',
  2673. '*',
  2674. '(',
  2675. ')',
  2676. ];
  2677. $replace = [
  2678. ' ',
  2679. ' ',
  2680. ' ',
  2681. ' ',
  2682. ' ',
  2683. ' ',
  2684. ' ',
  2685. ' ',
  2686. ' ',
  2687. ' ',
  2688. ];
  2689. $prereq_mod = str_replace($find, $replace, $prereq);
  2690. $ids = explode(' ', $prereq_mod);
  2691. foreach ($ids as $id) {
  2692. $id = trim($id);
  2693. if (isset($this->refs_list[$id])) {
  2694. $prereq = preg_replace(
  2695. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2696. 'ITEM_'.$this->refs_list[$id],
  2697. $prereq
  2698. );
  2699. }
  2700. }
  2701. return $prereq;
  2702. }
  2703. }
  2704. }
  2705. /**
  2706. * Returns the XML DOM document's node.
  2707. *
  2708. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2709. * @param string $id The identifier to look for
  2710. *
  2711. * @return mixed The reference to the element found with that identifier. False if not found
  2712. */
  2713. public function get_scorm_xml_node(&$children, $id)
  2714. {
  2715. for ($i = 0; $i < $children->length; $i++) {
  2716. $item_temp = $children->item($i);
  2717. if ($item_temp->nodeName == 'item') {
  2718. if ($item_temp->getAttribute('identifier') == $id) {
  2719. return $item_temp;
  2720. }
  2721. }
  2722. $subchildren = $item_temp->childNodes;
  2723. if ($subchildren && $subchildren->length > 0) {
  2724. $val = $this->get_scorm_xml_node($subchildren, $id);
  2725. if (is_object($val)) {
  2726. return $val;
  2727. }
  2728. }
  2729. }
  2730. return false;
  2731. }
  2732. /**
  2733. * Gets the status list for all LP's items.
  2734. *
  2735. * @return array Array of [index] => [item ID => current status]
  2736. */
  2737. public function get_items_status_list()
  2738. {
  2739. $list = [];
  2740. foreach ($this->ordered_items as $item_id) {
  2741. $list[] = [
  2742. $item_id => $this->items[$item_id]->get_status(),
  2743. ];
  2744. }
  2745. return $list;
  2746. }
  2747. /**
  2748. * Return the number of interactions for the given learnpath Item View ID.
  2749. * This method can be used as static.
  2750. *
  2751. * @param int $lp_iv_id Item View ID
  2752. * @param int $course_id course id
  2753. *
  2754. * @return int
  2755. */
  2756. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2757. {
  2758. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2759. $lp_iv_id = (int) $lp_iv_id;
  2760. $course_id = (int) $course_id;
  2761. $sql = "SELECT count(*) FROM $table
  2762. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2763. $res = Database::query($sql);
  2764. $num = 0;
  2765. if (Database::num_rows($res)) {
  2766. $row = Database::fetch_array($res);
  2767. $num = $row[0];
  2768. }
  2769. return $num;
  2770. }
  2771. /**
  2772. * Return the interactions as an array for the given lp_iv_id.
  2773. * This method can be used as static.
  2774. *
  2775. * @param int $lp_iv_id Learnpath Item View ID
  2776. *
  2777. * @return array
  2778. *
  2779. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2780. */
  2781. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2782. {
  2783. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2784. $list = [];
  2785. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2786. $lp_iv_id = (int) $lp_iv_id;
  2787. if (empty($lp_iv_id) || empty($course_id)) {
  2788. return [];
  2789. }
  2790. $sql = "SELECT * FROM $table
  2791. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2792. ORDER BY order_id ASC";
  2793. $res = Database::query($sql);
  2794. $num = Database::num_rows($res);
  2795. if ($num > 0) {
  2796. $list[] = [
  2797. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2798. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2799. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2800. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2801. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2802. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2803. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2804. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2805. 'student_response_formatted' => '',
  2806. ];
  2807. while ($row = Database::fetch_array($res)) {
  2808. $studentResponseFormatted = urldecode($row['student_response']);
  2809. $content_student_response = explode('__|', $studentResponseFormatted);
  2810. if (count($content_student_response) > 0) {
  2811. if (count($content_student_response) >= 3) {
  2812. // Pop the element off the end of array.
  2813. array_pop($content_student_response);
  2814. }
  2815. $studentResponseFormatted = implode(',', $content_student_response);
  2816. }
  2817. $list[] = [
  2818. 'order_id' => $row['order_id'] + 1,
  2819. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2820. 'type' => $row['interaction_type'],
  2821. 'time' => $row['completion_time'],
  2822. 'correct_responses' => '', // Hide correct responses from students.
  2823. 'student_response' => $row['student_response'],
  2824. 'result' => $row['result'],
  2825. 'latency' => $row['latency'],
  2826. 'student_response_formatted' => $studentResponseFormatted,
  2827. ];
  2828. }
  2829. }
  2830. return $list;
  2831. }
  2832. /**
  2833. * Return the number of objectives for the given learnpath Item View ID.
  2834. * This method can be used as static.
  2835. *
  2836. * @param int $lp_iv_id Item View ID
  2837. * @param int $course_id Course ID
  2838. *
  2839. * @return int Number of objectives
  2840. */
  2841. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2842. {
  2843. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2844. $course_id = (int) $course_id;
  2845. $lp_iv_id = (int) $lp_iv_id;
  2846. $sql = "SELECT count(*) FROM $table
  2847. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2848. //@todo seems that this always returns 0
  2849. $res = Database::query($sql);
  2850. $num = 0;
  2851. if (Database::num_rows($res)) {
  2852. $row = Database::fetch_array($res);
  2853. $num = $row[0];
  2854. }
  2855. return $num;
  2856. }
  2857. /**
  2858. * Return the objectives as an array for the given lp_iv_id.
  2859. * This method can be used as static.
  2860. *
  2861. * @param int $lpItemViewId Learnpath Item View ID
  2862. * @param int $course_id
  2863. *
  2864. * @return array
  2865. *
  2866. * @todo Translate labels
  2867. */
  2868. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2869. {
  2870. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2871. $lpItemViewId = (int) $lpItemViewId;
  2872. if (empty($course_id) || empty($lpItemViewId)) {
  2873. return [];
  2874. }
  2875. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2876. $sql = "SELECT * FROM $table
  2877. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2878. ORDER BY order_id ASC";
  2879. $res = Database::query($sql);
  2880. $num = Database::num_rows($res);
  2881. $list = [];
  2882. if ($num > 0) {
  2883. $list[] = [
  2884. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2885. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2886. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2887. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2888. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2889. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2890. ];
  2891. while ($row = Database::fetch_array($res)) {
  2892. $list[] = [
  2893. 'order_id' => $row['order_id'] + 1,
  2894. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2895. 'score_raw' => $row['score_raw'],
  2896. 'score_max' => $row['score_max'],
  2897. 'score_min' => $row['score_min'],
  2898. 'status' => $row['status'],
  2899. ];
  2900. }
  2901. }
  2902. return $list;
  2903. }
  2904. /**
  2905. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2906. * used by get_html_toc() to be ready to display.
  2907. *
  2908. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2909. */
  2910. public function get_toc()
  2911. {
  2912. $toc = [];
  2913. foreach ($this->ordered_items as $item_id) {
  2914. if ($this->debug > 2) {
  2915. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2916. }
  2917. // TODO: Change this link generation and use new function instead.
  2918. $toc[] = [
  2919. 'id' => $item_id,
  2920. 'title' => $this->items[$item_id]->get_title(),
  2921. 'status' => $this->items[$item_id]->get_status(),
  2922. 'level' => $this->items[$item_id]->get_level(),
  2923. 'type' => $this->items[$item_id]->get_type(),
  2924. 'description' => $this->items[$item_id]->get_description(),
  2925. 'path' => $this->items[$item_id]->get_path(),
  2926. 'parent' => $this->items[$item_id]->get_parent(),
  2927. ];
  2928. }
  2929. if ($this->debug > 2) {
  2930. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2931. }
  2932. return $toc;
  2933. }
  2934. /**
  2935. * Generate and return the table of contents for this learnpath. The JS
  2936. * table returned is used inside of scorm_api.php.
  2937. *
  2938. * @param string $varname
  2939. *
  2940. * @return string A JS array variable construction
  2941. */
  2942. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2943. {
  2944. $toc = $varname.' = new Array();';
  2945. foreach ($this->ordered_items as $item_id) {
  2946. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2947. }
  2948. return $toc;
  2949. }
  2950. /**
  2951. * Gets the learning path type.
  2952. *
  2953. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2954. *
  2955. * @return mixed Type ID or name, depending on the parameter
  2956. */
  2957. public function get_type($get_name = false)
  2958. {
  2959. $res = false;
  2960. if (!empty($this->type) && (!$get_name)) {
  2961. $res = $this->type;
  2962. }
  2963. return $res;
  2964. }
  2965. /**
  2966. * Gets the learning path type as static method.
  2967. *
  2968. * @param int $lp_id
  2969. *
  2970. * @return mixed Type ID or name, depending on the parameter
  2971. */
  2972. public static function get_type_static($lp_id = 0)
  2973. {
  2974. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2975. $lp_id = (int) $lp_id;
  2976. $sql = "SELECT lp_type FROM $tbl_lp
  2977. WHERE iid = $lp_id";
  2978. $res = Database::query($sql);
  2979. if ($res === false) {
  2980. return null;
  2981. }
  2982. if (Database::num_rows($res) <= 0) {
  2983. return null;
  2984. }
  2985. $row = Database::fetch_array($res);
  2986. return $row['lp_type'];
  2987. }
  2988. /**
  2989. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2990. * This method can be used as abstract and is recursive.
  2991. *
  2992. * @param int $lp Learnpath ID
  2993. * @param int $parent Parent ID of the items to look for
  2994. * @param int $course_id
  2995. *
  2996. * @return array Ordered list of item IDs (empty array on error)
  2997. */
  2998. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2999. {
  3000. if (empty($course_id)) {
  3001. $course_id = api_get_course_int_id();
  3002. } else {
  3003. $course_id = (int) $course_id;
  3004. }
  3005. $list = [];
  3006. if (empty($lp)) {
  3007. return $list;
  3008. }
  3009. $lp = (int) $lp;
  3010. $parent = (int) $parent;
  3011. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3012. $sql = "SELECT iid FROM $tbl_lp_item
  3013. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  3014. ORDER BY display_order";
  3015. $res = Database::query($sql);
  3016. while ($row = Database::fetch_array($res)) {
  3017. $sublist = self::get_flat_ordered_items_list(
  3018. $lp,
  3019. $row['iid'],
  3020. $course_id
  3021. );
  3022. $list[] = $row['iid'];
  3023. foreach ($sublist as $item) {
  3024. $list[] = $item;
  3025. }
  3026. }
  3027. return $list;
  3028. }
  3029. /**
  3030. * @return array
  3031. */
  3032. public static function getChapterTypes()
  3033. {
  3034. return [
  3035. 'dir',
  3036. ];
  3037. }
  3038. /**
  3039. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3040. *
  3041. * @param $tree
  3042. *
  3043. * @return array HTML TOC ready to display
  3044. */
  3045. public function getParentToc($tree)
  3046. {
  3047. if (empty($tree)) {
  3048. $tree = $this->get_toc();
  3049. }
  3050. $dirTypes = self::getChapterTypes();
  3051. $myCurrentId = $this->get_current_item_id();
  3052. $listParent = [];
  3053. $listChildren = [];
  3054. $listNotParent = [];
  3055. $list = [];
  3056. foreach ($tree as $subtree) {
  3057. if (in_array($subtree['type'], $dirTypes)) {
  3058. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3059. $subtree['children'] = $listChildren;
  3060. if (!empty($subtree['children'])) {
  3061. foreach ($subtree['children'] as $subItem) {
  3062. if ($subItem['id'] == $this->current) {
  3063. $subtree['parent_current'] = 'in';
  3064. $subtree['current'] = 'on';
  3065. }
  3066. }
  3067. }
  3068. $listParent[] = $subtree;
  3069. }
  3070. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3071. $classStatus = [
  3072. 'not attempted' => 'scorm_not_attempted',
  3073. 'incomplete' => 'scorm_not_attempted',
  3074. 'failed' => 'scorm_failed',
  3075. 'completed' => 'scorm_completed',
  3076. 'passed' => 'scorm_completed',
  3077. 'succeeded' => 'scorm_completed',
  3078. 'browsed' => 'scorm_completed',
  3079. ];
  3080. if (isset($classStatus[$subtree['status']])) {
  3081. $cssStatus = $classStatus[$subtree['status']];
  3082. }
  3083. $title = Security::remove_XSS($subtree['title']);
  3084. unset($subtree['title']);
  3085. if (empty($title)) {
  3086. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3087. }
  3088. $classStyle = null;
  3089. if ($subtree['id'] == $this->current) {
  3090. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3091. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3092. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3093. }
  3094. $subtree['title'] = $title;
  3095. $subtree['class'] = $classStyle.' '.$cssStatus;
  3096. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3097. $subtree['current_id'] = $myCurrentId;
  3098. $listNotParent[] = $subtree;
  3099. }
  3100. }
  3101. $list['are_parents'] = $listParent;
  3102. $list['not_parents'] = $listNotParent;
  3103. return $list;
  3104. }
  3105. /**
  3106. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3107. *
  3108. * @param array $tree
  3109. * @param int $id
  3110. * @param bool $parent
  3111. *
  3112. * @return array HTML TOC ready to display
  3113. */
  3114. public function getChildrenToc($tree, $id, $parent = true)
  3115. {
  3116. if (empty($tree)) {
  3117. $tree = $this->get_toc();
  3118. }
  3119. $dirTypes = self::getChapterTypes();
  3120. $mycurrentitemid = $this->get_current_item_id();
  3121. $list = [];
  3122. $classStatus = [
  3123. 'not attempted' => 'scorm_not_attempted',
  3124. 'incomplete' => 'scorm_not_attempted',
  3125. 'failed' => 'scorm_failed',
  3126. 'completed' => 'scorm_completed',
  3127. 'passed' => 'scorm_completed',
  3128. 'succeeded' => 'scorm_completed',
  3129. 'browsed' => 'scorm_completed',
  3130. ];
  3131. foreach ($tree as $subtree) {
  3132. $subtree['tree'] = null;
  3133. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3134. if ($subtree['id'] == $this->current) {
  3135. $subtree['current'] = 'active';
  3136. } else {
  3137. $subtree['current'] = null;
  3138. }
  3139. if (isset($classStatus[$subtree['status']])) {
  3140. $cssStatus = $classStatus[$subtree['status']];
  3141. }
  3142. $title = Security::remove_XSS($subtree['title']);
  3143. unset($subtree['title']);
  3144. if (empty($title)) {
  3145. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3146. }
  3147. $classStyle = null;
  3148. if ($subtree['id'] == $this->current) {
  3149. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3150. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3151. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3152. }
  3153. if (in_array($subtree['type'], $dirTypes)) {
  3154. $subtree['title'] = stripslashes($title);
  3155. } else {
  3156. $subtree['title'] = $title;
  3157. $subtree['class'] = $classStyle.' '.$cssStatus;
  3158. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3159. $subtree['current_id'] = $mycurrentitemid;
  3160. }
  3161. $list[] = $subtree;
  3162. }
  3163. }
  3164. return $list;
  3165. }
  3166. /**
  3167. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3168. *
  3169. * @param array $toc_list
  3170. *
  3171. * @return array HTML TOC ready to display
  3172. */
  3173. public function getListArrayToc($toc_list = [])
  3174. {
  3175. if (empty($toc_list)) {
  3176. $toc_list = $this->get_toc();
  3177. }
  3178. // Temporary variables.
  3179. $mycurrentitemid = $this->get_current_item_id();
  3180. $list = [];
  3181. $arrayList = [];
  3182. $classStatus = [
  3183. 'not attempted' => 'scorm_not_attempted',
  3184. 'incomplete' => 'scorm_not_attempted',
  3185. 'failed' => 'scorm_failed',
  3186. 'completed' => 'scorm_completed',
  3187. 'passed' => 'scorm_completed',
  3188. 'succeeded' => 'scorm_completed',
  3189. 'browsed' => 'scorm_completed',
  3190. ];
  3191. foreach ($toc_list as $item) {
  3192. $list['id'] = $item['id'];
  3193. $list['status'] = $item['status'];
  3194. $cssStatus = null;
  3195. if (isset($classStatus[$item['status']])) {
  3196. $cssStatus = $classStatus[$item['status']];
  3197. }
  3198. $classStyle = ' ';
  3199. $dirTypes = self::getChapterTypes();
  3200. if (in_array($item['type'], $dirTypes)) {
  3201. $classStyle = 'scorm_item_section ';
  3202. }
  3203. if ($item['id'] == $this->current) {
  3204. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3205. } elseif (!in_array($item['type'], $dirTypes)) {
  3206. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3207. }
  3208. $title = $item['title'];
  3209. if (empty($title)) {
  3210. $title = self::rl_get_resource_name(
  3211. api_get_course_id(),
  3212. $this->get_id(),
  3213. $item['id']
  3214. );
  3215. }
  3216. $title = Security::remove_XSS($item['title']);
  3217. if (empty($item['description'])) {
  3218. $list['description'] = $title;
  3219. } else {
  3220. $list['description'] = $item['description'];
  3221. }
  3222. $list['class'] = $classStyle.' '.$cssStatus;
  3223. $list['level'] = $item['level'];
  3224. $list['type'] = $item['type'];
  3225. if (in_array($item['type'], $dirTypes)) {
  3226. $list['css_level'] = 'level_'.$item['level'];
  3227. } else {
  3228. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3229. }
  3230. if (in_array($item['type'], $dirTypes)) {
  3231. $list['title'] = stripslashes($title);
  3232. } else {
  3233. $list['title'] = stripslashes($title);
  3234. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3235. $list['current_id'] = $mycurrentitemid;
  3236. }
  3237. $arrayList[] = $list;
  3238. }
  3239. return $arrayList;
  3240. }
  3241. /**
  3242. * Returns an HTML-formatted string ready to display with teacher buttons
  3243. * in LP view menu.
  3244. *
  3245. * @return string HTML TOC ready to display
  3246. */
  3247. public function get_teacher_toc_buttons()
  3248. {
  3249. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3250. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3251. $html = '';
  3252. if ($isAllow && $hideIcons == false) {
  3253. if ($this->get_lp_session_id() == api_get_session_id()) {
  3254. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3255. $html .= '<div class="btn-group">';
  3256. $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'>".
  3257. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3258. $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'>".
  3259. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3260. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3261. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3262. $html .= '</div>';
  3263. $html .= '</div>';
  3264. }
  3265. }
  3266. return $html;
  3267. }
  3268. /**
  3269. * Gets the learnpath maker name - generally the editor's name.
  3270. *
  3271. * @return string Learnpath maker name
  3272. */
  3273. public function get_maker()
  3274. {
  3275. if (!empty($this->maker)) {
  3276. return $this->maker;
  3277. }
  3278. return '';
  3279. }
  3280. /**
  3281. * Gets the learnpath name/title.
  3282. *
  3283. * @return string Learnpath name/title
  3284. */
  3285. public function get_name()
  3286. {
  3287. if (!empty($this->name)) {
  3288. return $this->name;
  3289. }
  3290. return 'N/A';
  3291. }
  3292. /**
  3293. * Gets a link to the resource from the present location, depending on item ID.
  3294. *
  3295. * @param string $type Type of link expected
  3296. * @param int $item_id Learnpath item ID
  3297. * @param bool $provided_toc
  3298. *
  3299. * @return string $provided_toc Link to the lp_item resource
  3300. */
  3301. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3302. {
  3303. $course_id = $this->get_course_int_id();
  3304. if ($this->debug > 0) {
  3305. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3306. }
  3307. if (empty($item_id)) {
  3308. if ($this->debug > 2) {
  3309. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3310. error_log('using current: '.$this->get_current_item_id(), 0);
  3311. }
  3312. $item_id = $this->get_current_item_id();
  3313. if (empty($item_id)) {
  3314. if ($this->debug > 2) {
  3315. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3316. }
  3317. //still empty, this means there was no item_id given and we are not in an object context or
  3318. //the object property is empty, return empty link
  3319. $this->first();
  3320. return '';
  3321. }
  3322. }
  3323. $file = '';
  3324. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3325. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3326. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3327. $item_id = (int) $item_id;
  3328. $sql = "SELECT
  3329. l.lp_type as ltype,
  3330. l.path as lpath,
  3331. li.item_type as litype,
  3332. li.path as lipath,
  3333. li.parameters as liparams
  3334. FROM $lp_table l
  3335. INNER JOIN $lp_item_table li
  3336. ON (li.lp_id = l.iid)
  3337. WHERE
  3338. li.iid = $item_id
  3339. ";
  3340. if ($this->debug > 2) {
  3341. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3342. }
  3343. $res = Database::query($sql);
  3344. if (Database::num_rows($res) > 0) {
  3345. $row = Database::fetch_array($res);
  3346. $lp_type = $row['ltype'];
  3347. $lp_path = $row['lpath'];
  3348. $lp_item_type = $row['litype'];
  3349. $lp_item_path = $row['lipath'];
  3350. $lp_item_params = $row['liparams'];
  3351. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3352. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3353. }
  3354. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3355. if ($type === 'http') {
  3356. //web path
  3357. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3358. } else {
  3359. $course_path = $sys_course_path; //system path
  3360. }
  3361. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3362. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3363. if (in_array(
  3364. $lp_item_type,
  3365. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3366. )
  3367. ) {
  3368. $lp_type = 1;
  3369. }
  3370. if ($this->debug > 2) {
  3371. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3372. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3373. }
  3374. // Now go through the specific cases to get the end of the path
  3375. // @todo Use constants instead of int values.
  3376. switch ($lp_type) {
  3377. case 1:
  3378. $file = self::rl_get_resource_link_for_learnpath(
  3379. $course_id,
  3380. $this->get_id(),
  3381. $item_id,
  3382. $this->get_view_id()
  3383. );
  3384. if ($this->debug > 0) {
  3385. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3386. }
  3387. switch ($lp_item_type) {
  3388. case 'document':
  3389. // Shows a button to download the file instead of just downloading the file directly.
  3390. $documentPathInfo = pathinfo($file);
  3391. if (isset($documentPathInfo['extension'])) {
  3392. $parsed = parse_url($documentPathInfo['extension']);
  3393. if (isset($parsed['path'])) {
  3394. $extension = $parsed['path'];
  3395. $extensionsToDownload = [
  3396. 'zip',
  3397. 'ppt',
  3398. 'pptx',
  3399. 'ods',
  3400. 'xlsx',
  3401. 'xls',
  3402. 'csv',
  3403. 'doc',
  3404. 'docx',
  3405. 'dot',
  3406. ];
  3407. if (in_array($extension, $extensionsToDownload)) {
  3408. $file = api_get_path(WEB_CODE_PATH).
  3409. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3410. }
  3411. }
  3412. }
  3413. break;
  3414. case 'dir':
  3415. $file = 'lp_content.php?type=dir';
  3416. break;
  3417. case 'link':
  3418. if (Link::is_youtube_link($file)) {
  3419. $src = Link::get_youtube_video_id($file);
  3420. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3421. } elseif (Link::isVimeoLink($file)) {
  3422. $src = Link::getVimeoLinkId($file);
  3423. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3424. } else {
  3425. // If the current site is HTTPS and the link is
  3426. // HTTP, browsers will refuse opening the link
  3427. $urlId = api_get_current_access_url_id();
  3428. $url = api_get_access_url($urlId, false);
  3429. $protocol = substr($url['url'], 0, 5);
  3430. if ($protocol === 'https') {
  3431. $linkProtocol = substr($file, 0, 5);
  3432. if ($linkProtocol === 'http:') {
  3433. //this is the special intervention case
  3434. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3435. }
  3436. }
  3437. }
  3438. break;
  3439. case 'quiz':
  3440. // Check how much attempts of a exercise exits in lp
  3441. $lp_item_id = $this->get_current_item_id();
  3442. $lp_view_id = $this->get_view_id();
  3443. $prevent_reinit = null;
  3444. if (isset($this->items[$this->current])) {
  3445. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3446. }
  3447. if (empty($provided_toc)) {
  3448. if ($this->debug > 0) {
  3449. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3450. }
  3451. $list = $this->get_toc();
  3452. } else {
  3453. if ($this->debug > 0) {
  3454. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3455. }
  3456. $list = $provided_toc;
  3457. }
  3458. $type_quiz = false;
  3459. foreach ($list as $toc) {
  3460. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3461. $type_quiz = true;
  3462. }
  3463. }
  3464. if ($type_quiz) {
  3465. $lp_item_id = (int) $lp_item_id;
  3466. $lp_view_id = (int) $lp_view_id;
  3467. $sql = "SELECT count(*) FROM $lp_item_view_table
  3468. WHERE
  3469. c_id = $course_id AND
  3470. lp_item_id='".$lp_item_id."' AND
  3471. lp_view_id ='".$lp_view_id."' AND
  3472. status='completed'";
  3473. $result = Database::query($sql);
  3474. $row_count = Database:: fetch_row($result);
  3475. $count_item_view = (int) $row_count[0];
  3476. $not_multiple_attempt = 0;
  3477. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3478. $not_multiple_attempt = 1;
  3479. }
  3480. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3481. }
  3482. break;
  3483. }
  3484. $tmp_array = explode('/', $file);
  3485. $document_name = $tmp_array[count($tmp_array) - 1];
  3486. if (strpos($document_name, '_DELETED_')) {
  3487. $file = 'blank.php?error=document_deleted';
  3488. }
  3489. break;
  3490. case 2:
  3491. if ($this->debug > 2) {
  3492. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3493. }
  3494. if ($lp_item_type != 'dir') {
  3495. // Quite complex here:
  3496. // We want to make sure 'http://' (and similar) links can
  3497. // be loaded as is (withouth the Chamilo path in front) but
  3498. // some contents use this form: resource.htm?resource=http://blablabla
  3499. // which means we have to find a protocol at the path's start, otherwise
  3500. // it should not be considered as an external URL.
  3501. // if ($this->prerequisites_match($item_id)) {
  3502. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3503. if ($this->debug > 2) {
  3504. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3505. }
  3506. // Distant url, return as is.
  3507. $file = $lp_item_path;
  3508. } else {
  3509. if ($this->debug > 2) {
  3510. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3511. }
  3512. // Prevent getting untranslatable urls.
  3513. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3514. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3515. // Prepare the path.
  3516. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3517. // TODO: Fix this for urls with protocol header.
  3518. $file = str_replace('//', '/', $file);
  3519. $file = str_replace(':/', '://', $file);
  3520. if (substr($lp_path, -1) == '/') {
  3521. $lp_path = substr($lp_path, 0, -1);
  3522. }
  3523. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3524. // if file not found.
  3525. $decoded = html_entity_decode($lp_item_path);
  3526. list($decoded) = explode('?', $decoded);
  3527. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3528. $file = self::rl_get_resource_link_for_learnpath(
  3529. $course_id,
  3530. $this->get_id(),
  3531. $item_id,
  3532. $this->get_view_id()
  3533. );
  3534. if (empty($file)) {
  3535. $file = 'blank.php?error=document_not_found';
  3536. } else {
  3537. $tmp_array = explode('/', $file);
  3538. $document_name = $tmp_array[count($tmp_array) - 1];
  3539. if (strpos($document_name, '_DELETED_')) {
  3540. $file = 'blank.php?error=document_deleted';
  3541. } else {
  3542. $file = 'blank.php?error=document_not_found';
  3543. }
  3544. }
  3545. } else {
  3546. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3547. }
  3548. }
  3549. }
  3550. // We want to use parameters if they were defined in the imsmanifest
  3551. if (strpos($file, 'blank.php') === false) {
  3552. $lp_item_params = ltrim($lp_item_params, '?');
  3553. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3554. }
  3555. } else {
  3556. $file = 'lp_content.php?type=dir';
  3557. }
  3558. break;
  3559. case 3:
  3560. if ($this->debug > 2) {
  3561. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3562. }
  3563. // Formatting AICC HACP append URL.
  3564. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3565. if (!empty($lp_item_params)) {
  3566. $aicc_append .= $lp_item_params.'&';
  3567. }
  3568. if ($lp_item_type != 'dir') {
  3569. // Quite complex here:
  3570. // We want to make sure 'http://' (and similar) links can
  3571. // be loaded as is (withouth the Chamilo path in front) but
  3572. // some contents use this form: resource.htm?resource=http://blablabla
  3573. // which means we have to find a protocol at the path's start, otherwise
  3574. // it should not be considered as an external URL.
  3575. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3576. if ($this->debug > 2) {
  3577. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3578. }
  3579. // Distant url, return as is.
  3580. $file = $lp_item_path;
  3581. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3582. /*
  3583. if (stristr($file,'<servername>') !== false) {
  3584. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3585. }
  3586. */
  3587. if (stripos($file, '<servername>') !== false) {
  3588. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3589. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3590. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3591. }
  3592. $file .= $aicc_append;
  3593. } else {
  3594. if ($this->debug > 2) {
  3595. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3596. }
  3597. // Prevent getting untranslatable urls.
  3598. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3599. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3600. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3601. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3602. // TODO: Fix this for urls with protocol header.
  3603. $file = str_replace('//', '/', $file);
  3604. $file = str_replace(':/', '://', $file);
  3605. $file .= $aicc_append;
  3606. }
  3607. } else {
  3608. $file = 'lp_content.php?type=dir';
  3609. }
  3610. break;
  3611. case 4:
  3612. break;
  3613. default:
  3614. break;
  3615. }
  3616. // Replace &amp; by & because &amp; will break URL with params
  3617. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3618. }
  3619. if ($this->debug > 2) {
  3620. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3621. }
  3622. return $file;
  3623. }
  3624. /**
  3625. * Gets the latest usable view or generate a new one.
  3626. *
  3627. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3628. *
  3629. * @return int DB lp_view id
  3630. */
  3631. public function get_view($attempt_num = 0)
  3632. {
  3633. $search = '';
  3634. // Use $attempt_num to enable multi-views management (disabled so far).
  3635. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3636. $search = 'AND view_count = '.$attempt_num;
  3637. }
  3638. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3639. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3640. $course_id = api_get_course_int_id();
  3641. $sessionId = api_get_session_id();
  3642. $sql = "SELECT iid, view_count FROM $lp_view_table
  3643. WHERE
  3644. c_id = $course_id AND
  3645. lp_id = ".$this->get_id()." AND
  3646. user_id = ".$this->get_user_id()." AND
  3647. session_id = $sessionId
  3648. $search
  3649. ORDER BY view_count DESC";
  3650. $res = Database::query($sql);
  3651. if (Database::num_rows($res) > 0) {
  3652. $row = Database::fetch_array($res);
  3653. $this->lp_view_id = $row['iid'];
  3654. } elseif (!api_is_invitee()) {
  3655. // There is no database record, create one.
  3656. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3657. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3658. Database::query($sql);
  3659. $id = Database::insert_id();
  3660. $this->lp_view_id = $id;
  3661. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3662. Database::query($sql);
  3663. }
  3664. return $this->lp_view_id;
  3665. }
  3666. /**
  3667. * Gets the current view id.
  3668. *
  3669. * @return int View ID (from lp_view)
  3670. */
  3671. public function get_view_id()
  3672. {
  3673. if (!empty($this->lp_view_id)) {
  3674. return (int) $this->lp_view_id;
  3675. }
  3676. return 0;
  3677. }
  3678. /**
  3679. * Gets the update queue.
  3680. *
  3681. * @return array Array containing IDs of items to be updated by JavaScript
  3682. */
  3683. public function get_update_queue()
  3684. {
  3685. return $this->update_queue;
  3686. }
  3687. /**
  3688. * Gets the user ID.
  3689. *
  3690. * @return int User ID
  3691. */
  3692. public function get_user_id()
  3693. {
  3694. if (!empty($this->user_id)) {
  3695. return (int) $this->user_id;
  3696. }
  3697. return false;
  3698. }
  3699. /**
  3700. * Checks if any of the items has an audio element attached.
  3701. *
  3702. * @return bool True or false
  3703. */
  3704. public function has_audio()
  3705. {
  3706. $has = false;
  3707. foreach ($this->items as $i => $item) {
  3708. if (!empty($this->items[$i]->audio)) {
  3709. $has = true;
  3710. break;
  3711. }
  3712. }
  3713. return $has;
  3714. }
  3715. /**
  3716. * Moves an item up and down at its level.
  3717. *
  3718. * @param int $id Item to move up and down
  3719. * @param string $direction Direction 'up' or 'down'
  3720. *
  3721. * @return bool|int
  3722. */
  3723. public function move_item($id, $direction)
  3724. {
  3725. $course_id = api_get_course_int_id();
  3726. if ($this->debug > 0) {
  3727. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3728. }
  3729. if (empty($id) || empty($direction)) {
  3730. return false;
  3731. }
  3732. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3733. $sql_sel = "SELECT *
  3734. FROM $tbl_lp_item
  3735. WHERE
  3736. iid = $id
  3737. ";
  3738. $res_sel = Database::query($sql_sel);
  3739. // Check if elem exists.
  3740. if (Database::num_rows($res_sel) < 1) {
  3741. return false;
  3742. }
  3743. // Gather data.
  3744. $row = Database::fetch_array($res_sel);
  3745. $previous = $row['previous_item_id'];
  3746. $next = $row['next_item_id'];
  3747. $display = $row['display_order'];
  3748. $parent = $row['parent_item_id'];
  3749. $lp = $row['lp_id'];
  3750. // Update the item (switch with previous/next one).
  3751. switch ($direction) {
  3752. case 'up':
  3753. if ($this->debug > 2) {
  3754. error_log('Movement up detected', 0);
  3755. }
  3756. if ($display > 1) {
  3757. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3758. WHERE iid = $previous";
  3759. if ($this->debug > 2) {
  3760. error_log('Selecting previous: '.$sql_sel2, 0);
  3761. }
  3762. $res_sel2 = Database::query($sql_sel2);
  3763. if (Database::num_rows($res_sel2) < 1) {
  3764. $previous_previous = 0;
  3765. }
  3766. // Gather data.
  3767. $row2 = Database::fetch_array($res_sel2);
  3768. $previous_previous = $row2['previous_item_id'];
  3769. // Update previous_previous item (switch "next" with current).
  3770. if ($previous_previous != 0) {
  3771. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3772. next_item_id = $id
  3773. WHERE iid = $previous_previous";
  3774. if ($this->debug > 2) {
  3775. error_log($sql_upd2, 0);
  3776. }
  3777. Database::query($sql_upd2);
  3778. }
  3779. // Update previous item (switch with current).
  3780. if ($previous != 0) {
  3781. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3782. next_item_id = $next,
  3783. previous_item_id = $id,
  3784. display_order = display_order +1
  3785. WHERE iid = $previous";
  3786. if ($this->debug > 2) {
  3787. error_log($sql_upd2, 0);
  3788. }
  3789. Database::query($sql_upd2);
  3790. }
  3791. // Update current item (switch with previous).
  3792. if ($id != 0) {
  3793. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3794. next_item_id = $previous,
  3795. previous_item_id = $previous_previous,
  3796. display_order = display_order-1
  3797. WHERE c_id = ".$course_id." AND id = $id";
  3798. if ($this->debug > 2) {
  3799. error_log($sql_upd2, 0);
  3800. }
  3801. Database::query($sql_upd2);
  3802. }
  3803. // Update next item (new previous item).
  3804. if (!empty($next)) {
  3805. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3806. WHERE iid = $next";
  3807. if ($this->debug > 2) {
  3808. error_log($sql_upd2, 0);
  3809. }
  3810. Database::query($sql_upd2);
  3811. }
  3812. $display = $display - 1;
  3813. }
  3814. break;
  3815. case 'down':
  3816. if ($this->debug > 2) {
  3817. error_log('Movement down detected', 0);
  3818. }
  3819. if ($next != 0) {
  3820. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3821. WHERE iid = $next";
  3822. if ($this->debug > 2) {
  3823. error_log('Selecting next: '.$sql_sel2, 0);
  3824. }
  3825. $res_sel2 = Database::query($sql_sel2);
  3826. if (Database::num_rows($res_sel2) < 1) {
  3827. $next_next = 0;
  3828. }
  3829. // Gather data.
  3830. $row2 = Database::fetch_array($res_sel2);
  3831. $next_next = $row2['next_item_id'];
  3832. // Update previous item (switch with current).
  3833. if ($previous != 0) {
  3834. $sql_upd2 = "UPDATE $tbl_lp_item
  3835. SET next_item_id = $next
  3836. WHERE iid = $previous";
  3837. Database::query($sql_upd2);
  3838. }
  3839. // Update current item (switch with previous).
  3840. if ($id != 0) {
  3841. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3842. previous_item_id = $next,
  3843. next_item_id = $next_next,
  3844. display_order = display_order + 1
  3845. WHERE iid = $id";
  3846. Database::query($sql_upd2);
  3847. }
  3848. // Update next item (new previous item).
  3849. if ($next != 0) {
  3850. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3851. previous_item_id = $previous,
  3852. next_item_id = $id,
  3853. display_order = display_order-1
  3854. WHERE iid = $next";
  3855. Database::query($sql_upd2);
  3856. }
  3857. // Update next_next item (switch "previous" with current).
  3858. if ($next_next != 0) {
  3859. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3860. previous_item_id = $id
  3861. WHERE iid = $next_next";
  3862. Database::query($sql_upd2);
  3863. }
  3864. $display = $display + 1;
  3865. }
  3866. break;
  3867. default:
  3868. return false;
  3869. }
  3870. return $display;
  3871. }
  3872. /**
  3873. * Move a LP up (display_order).
  3874. *
  3875. * @param int $lp_id Learnpath ID
  3876. * @param int $categoryId Category ID
  3877. *
  3878. * @return bool
  3879. */
  3880. public static function move_up($lp_id, $categoryId = 0)
  3881. {
  3882. $courseId = api_get_course_int_id();
  3883. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3884. $categoryCondition = '';
  3885. if (!empty($categoryId)) {
  3886. $categoryId = (int) $categoryId;
  3887. $categoryCondition = " AND category_id = $categoryId";
  3888. }
  3889. $sql = "SELECT * FROM $lp_table
  3890. WHERE c_id = $courseId
  3891. $categoryCondition
  3892. ORDER BY display_order";
  3893. $res = Database::query($sql);
  3894. if ($res === false) {
  3895. return false;
  3896. }
  3897. $lps = [];
  3898. $lp_order = [];
  3899. $num = Database::num_rows($res);
  3900. // First check the order is correct, globally (might be wrong because
  3901. // of versions < 1.8.4)
  3902. if ($num > 0) {
  3903. $i = 1;
  3904. while ($row = Database::fetch_array($res)) {
  3905. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3906. $sql = "UPDATE $lp_table SET display_order = $i
  3907. WHERE iid = ".$row['iid'];
  3908. Database::query($sql);
  3909. }
  3910. $row['display_order'] = $i;
  3911. $lps[$row['iid']] = $row;
  3912. $lp_order[$i] = $row['iid'];
  3913. $i++;
  3914. }
  3915. }
  3916. if ($num > 1) { // If there's only one element, no need to sort.
  3917. $order = $lps[$lp_id]['display_order'];
  3918. if ($order > 1) { // If it's the first element, no need to move up.
  3919. $sql = "UPDATE $lp_table SET display_order = $order
  3920. WHERE iid = ".$lp_order[$order - 1];
  3921. Database::query($sql);
  3922. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3923. WHERE iid = $lp_id";
  3924. Database::query($sql);
  3925. }
  3926. }
  3927. return true;
  3928. }
  3929. /**
  3930. * Move a learnpath down (display_order).
  3931. *
  3932. * @param int $lp_id Learnpath ID
  3933. * @param int $categoryId Category ID
  3934. *
  3935. * @return bool
  3936. */
  3937. public static function move_down($lp_id, $categoryId = 0)
  3938. {
  3939. $courseId = api_get_course_int_id();
  3940. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3941. $categoryCondition = '';
  3942. if (!empty($categoryId)) {
  3943. $categoryId = (int) $categoryId;
  3944. $categoryCondition = " AND category_id = $categoryId";
  3945. }
  3946. $sql = "SELECT * FROM $lp_table
  3947. WHERE c_id = $courseId
  3948. $categoryCondition
  3949. ORDER BY display_order";
  3950. $res = Database::query($sql);
  3951. if ($res === false) {
  3952. return false;
  3953. }
  3954. $lps = [];
  3955. $lp_order = [];
  3956. $num = Database::num_rows($res);
  3957. $max = 0;
  3958. // First check the order is correct, globally (might be wrong because
  3959. // of versions < 1.8.4).
  3960. if ($num > 0) {
  3961. $i = 1;
  3962. while ($row = Database::fetch_array($res)) {
  3963. $max = $i;
  3964. if ($row['display_order'] != $i) {
  3965. // If we find a gap in the order, we need to fix it.
  3966. $sql = "UPDATE $lp_table SET display_order = $i
  3967. WHERE iid = ".$row['iid'];
  3968. Database::query($sql);
  3969. }
  3970. $row['display_order'] = $i;
  3971. $lps[$row['iid']] = $row;
  3972. $lp_order[$i] = $row['iid'];
  3973. $i++;
  3974. }
  3975. }
  3976. if ($num > 1) { // If there's only one element, no need to sort.
  3977. $order = $lps[$lp_id]['display_order'];
  3978. if ($order < $max) { // If it's the first element, no need to move up.
  3979. $sql = "UPDATE $lp_table SET display_order = $order
  3980. WHERE iid = ".$lp_order[$order + 1];
  3981. Database::query($sql);
  3982. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3983. WHERE iid = $lp_id";
  3984. Database::query($sql);
  3985. }
  3986. }
  3987. return true;
  3988. }
  3989. /**
  3990. * Updates learnpath attributes to point to the next element
  3991. * The last part is similar to set_current_item but processing the other way around.
  3992. */
  3993. public function next()
  3994. {
  3995. if ($this->debug > 0) {
  3996. error_log('In learnpath::next()', 0);
  3997. }
  3998. $this->last = $this->get_current_item_id();
  3999. $this->items[$this->last]->save(
  4000. false,
  4001. $this->prerequisites_match($this->last)
  4002. );
  4003. $this->autocomplete_parents($this->last);
  4004. $new_index = $this->get_next_index();
  4005. if ($this->debug > 2) {
  4006. error_log('New index: '.$new_index, 0);
  4007. }
  4008. $this->index = $new_index;
  4009. if ($this->debug > 2) {
  4010. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  4011. }
  4012. $this->current = $this->ordered_items[$new_index];
  4013. if ($this->debug > 2) {
  4014. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  4015. }
  4016. }
  4017. /**
  4018. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  4019. * class, this might be redefined to allow several behaviours depending on the document type.
  4020. *
  4021. * @param int $id Resource ID
  4022. */
  4023. public function open($id)
  4024. {
  4025. if ($this->debug > 0) {
  4026. error_log('In learnpath::open()', 0);
  4027. }
  4028. // TODO:
  4029. // set the current resource attribute to this resource
  4030. // switch on element type (redefine in child class?)
  4031. // set status for this item to "opened"
  4032. // start timer
  4033. // initialise score
  4034. $this->index = 0; //or = the last item seen (see $this->last)
  4035. }
  4036. /**
  4037. * Check that all prerequisites are fulfilled. Returns true and an
  4038. * empty string on success, returns false
  4039. * and the prerequisite string on error.
  4040. * This function is based on the rules for aicc_script language as
  4041. * described in the SCORM 1.2 CAM documentation page 108.
  4042. *
  4043. * @param int $itemId Optional item ID. If none given, uses the current open item.
  4044. *
  4045. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  4046. * string otherwise
  4047. */
  4048. public function prerequisites_match($itemId = null)
  4049. {
  4050. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  4051. if ($allow) {
  4052. if (api_is_allowed_to_edit() ||
  4053. api_is_platform_admin(true) ||
  4054. api_is_drh() ||
  4055. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4056. ) {
  4057. return true;
  4058. }
  4059. }
  4060. $debug = $this->debug;
  4061. if ($debug > 0) {
  4062. error_log('In learnpath::prerequisites_match()');
  4063. }
  4064. if (empty($itemId)) {
  4065. $itemId = $this->current;
  4066. }
  4067. $currentItem = $this->getItem($itemId);
  4068. if ($currentItem) {
  4069. if ($this->type == 2) {
  4070. // Getting prereq from scorm
  4071. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4072. } else {
  4073. $prereq_string = $currentItem->get_prereq_string();
  4074. }
  4075. if (empty($prereq_string)) {
  4076. if ($debug > 0) {
  4077. error_log('Found prereq_string is empty return true');
  4078. }
  4079. return true;
  4080. }
  4081. // Clean spaces.
  4082. $prereq_string = str_replace(' ', '', $prereq_string);
  4083. if ($debug > 0) {
  4084. error_log('Found prereq_string: '.$prereq_string, 0);
  4085. }
  4086. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4087. $result = $currentItem->parse_prereq(
  4088. $prereq_string,
  4089. $this->items,
  4090. $this->refs_list,
  4091. $this->get_user_id()
  4092. );
  4093. if ($result === false) {
  4094. $this->set_error_msg($currentItem->prereq_alert);
  4095. }
  4096. } else {
  4097. $result = true;
  4098. if ($debug > 1) {
  4099. error_log('$this->items['.$itemId.'] was not an object', 0);
  4100. }
  4101. }
  4102. if ($debug > 1) {
  4103. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4104. }
  4105. return $result;
  4106. }
  4107. /**
  4108. * Updates learnpath attributes to point to the previous element
  4109. * The last part is similar to set_current_item but processing the other way around.
  4110. */
  4111. public function previous()
  4112. {
  4113. $this->last = $this->get_current_item_id();
  4114. $this->items[$this->last]->save(
  4115. false,
  4116. $this->prerequisites_match($this->last)
  4117. );
  4118. $this->autocomplete_parents($this->last);
  4119. $new_index = $this->get_previous_index();
  4120. $this->index = $new_index;
  4121. $this->current = $this->ordered_items[$new_index];
  4122. }
  4123. /**
  4124. * Publishes a learnpath. This basically means show or hide the learnpath
  4125. * to normal users.
  4126. * Can be used as abstract.
  4127. *
  4128. * @param int $lp_id Learnpath ID
  4129. * @param int $set_visibility New visibility
  4130. *
  4131. * @return bool
  4132. */
  4133. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4134. {
  4135. $action = 'visible';
  4136. if ($set_visibility != 1) {
  4137. $action = 'invisible';
  4138. self::toggle_publish($lp_id, 'i');
  4139. }
  4140. return api_item_property_update(
  4141. api_get_course_info(),
  4142. TOOL_LEARNPATH,
  4143. $lp_id,
  4144. $action,
  4145. api_get_user_id()
  4146. );
  4147. }
  4148. /**
  4149. * Publishes a learnpath category.
  4150. * This basically means show or hide the learnpath category to normal users.
  4151. *
  4152. * @param int $id
  4153. * @param int $visibility
  4154. *
  4155. * @throws \Doctrine\ORM\NonUniqueResultException
  4156. * @throws \Doctrine\ORM\ORMException
  4157. * @throws \Doctrine\ORM\OptimisticLockException
  4158. * @throws \Doctrine\ORM\TransactionRequiredException
  4159. *
  4160. * @return bool
  4161. */
  4162. public static function toggleCategoryVisibility($id, $visibility = 1)
  4163. {
  4164. $action = 'visible';
  4165. if ($visibility != 1) {
  4166. $action = 'invisible';
  4167. $list = new LearnpathList(
  4168. api_get_user_id(),
  4169. null,
  4170. null,
  4171. null,
  4172. false,
  4173. $id
  4174. );
  4175. $lpList = $list->get_flat_list();
  4176. foreach ($lpList as $lp) {
  4177. self::toggle_visibility($lp['iid'], 0);
  4178. }
  4179. self::toggleCategoryPublish($id, 0);
  4180. }
  4181. return api_item_property_update(
  4182. api_get_course_info(),
  4183. TOOL_LEARNPATH_CATEGORY,
  4184. $id,
  4185. $action,
  4186. api_get_user_id()
  4187. );
  4188. }
  4189. /**
  4190. * Publishes a learnpath. This basically means show or hide the learnpath
  4191. * on the course homepage
  4192. * Can be used as abstract.
  4193. *
  4194. * @param int $lp_id Learnpath id
  4195. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4196. *
  4197. * @return bool
  4198. */
  4199. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4200. {
  4201. $course_id = api_get_course_int_id();
  4202. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4203. $lp_id = (int) $lp_id;
  4204. $sql = "SELECT * FROM $tbl_lp
  4205. WHERE iid = $lp_id";
  4206. $result = Database::query($sql);
  4207. if (Database::num_rows($result)) {
  4208. $row = Database::fetch_array($result);
  4209. $name = Database::escape_string($row['name']);
  4210. if ($set_visibility == 'i') {
  4211. $v = 0;
  4212. }
  4213. if ($set_visibility == 'v') {
  4214. $v = 1;
  4215. }
  4216. $session_id = api_get_session_id();
  4217. $session_condition = api_get_session_condition($session_id);
  4218. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4219. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4220. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4221. $sql = "SELECT * FROM $tbl_tool
  4222. WHERE
  4223. c_id = $course_id AND
  4224. (link = '$link' OR link = '$oldLink') AND
  4225. image = 'scormbuilder.gif' AND
  4226. (
  4227. link LIKE '$link%' OR
  4228. link LIKE '$oldLink%'
  4229. )
  4230. $session_condition
  4231. ";
  4232. $result = Database::query($sql);
  4233. $num = Database::num_rows($result);
  4234. if ($set_visibility == 'i' && $num > 0) {
  4235. $sql = "DELETE FROM $tbl_tool
  4236. WHERE
  4237. c_id = $course_id AND
  4238. (link = '$link' OR link = '$oldLink') AND
  4239. image='scormbuilder.gif'
  4240. $session_condition";
  4241. Database::query($sql);
  4242. } elseif ($set_visibility == 'v' && $num == 0) {
  4243. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4244. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4245. Database::query($sql);
  4246. $insertId = Database::insert_id();
  4247. if ($insertId) {
  4248. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4249. Database::query($sql);
  4250. }
  4251. } elseif ($set_visibility == 'v' && $num > 0) {
  4252. $sql = "UPDATE $tbl_tool SET
  4253. c_id = $course_id,
  4254. name = '$name',
  4255. link = '$link',
  4256. image = 'scormbuilder.gif',
  4257. visibility = '$v',
  4258. admin = '0',
  4259. address = 'pastillegris.gif',
  4260. added_tool = 0,
  4261. session_id = $session_id
  4262. WHERE
  4263. c_id = ".$course_id." AND
  4264. (link = '$link' OR link = '$oldLink') AND
  4265. image='scormbuilder.gif'
  4266. $session_condition
  4267. ";
  4268. Database::query($sql);
  4269. } else {
  4270. // Parameter and database incompatible, do nothing, exit.
  4271. return false;
  4272. }
  4273. } else {
  4274. return false;
  4275. }
  4276. }
  4277. /**
  4278. * Publishes a learnpath.
  4279. * Show or hide the learnpath category on the course homepage.
  4280. *
  4281. * @param int $id
  4282. * @param int $setVisibility
  4283. *
  4284. * @throws \Doctrine\ORM\NonUniqueResultException
  4285. * @throws \Doctrine\ORM\ORMException
  4286. * @throws \Doctrine\ORM\OptimisticLockException
  4287. * @throws \Doctrine\ORM\TransactionRequiredException
  4288. *
  4289. * @return bool
  4290. */
  4291. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4292. {
  4293. $courseId = api_get_course_int_id();
  4294. $sessionId = api_get_session_id();
  4295. $sessionCondition = api_get_session_condition(
  4296. $sessionId,
  4297. true,
  4298. false,
  4299. 't.sessionId'
  4300. );
  4301. $em = Database::getManager();
  4302. /** @var CLpCategory $category */
  4303. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4304. if (!$category) {
  4305. return false;
  4306. }
  4307. if (empty($courseId)) {
  4308. return false;
  4309. }
  4310. $link = self::getCategoryLinkForTool($id);
  4311. /** @var CTool $tool */
  4312. $tool = $em->createQuery("
  4313. SELECT t FROM ChamiloCourseBundle:CTool t
  4314. WHERE
  4315. t.cId = :course AND
  4316. t.link = :link1 AND
  4317. t.image = 'lp_category.gif' AND
  4318. t.link LIKE :link2
  4319. $sessionCondition
  4320. ")
  4321. ->setParameters([
  4322. 'course' => (int) $courseId,
  4323. 'link1' => $link,
  4324. 'link2' => "$link%",
  4325. ])
  4326. ->getOneOrNullResult();
  4327. if ($setVisibility == 0 && $tool) {
  4328. $em->remove($tool);
  4329. $em->flush();
  4330. return true;
  4331. }
  4332. if ($setVisibility == 1 && !$tool) {
  4333. $tool = new CTool();
  4334. $tool
  4335. ->setCategory('authoring')
  4336. ->setCId($courseId)
  4337. ->setName(strip_tags($category->getName()))
  4338. ->setLink($link)
  4339. ->setImage('lp_category.gif')
  4340. ->setVisibility(1)
  4341. ->setAdmin(0)
  4342. ->setAddress('pastillegris.gif')
  4343. ->setAddedTool(0)
  4344. ->setSessionId($sessionId)
  4345. ->setTarget('_self');
  4346. $em->persist($tool);
  4347. $em->flush();
  4348. $tool->setId($tool->getIid());
  4349. $em->persist($tool);
  4350. $em->flush();
  4351. return true;
  4352. }
  4353. if ($setVisibility == 1 && $tool) {
  4354. $tool
  4355. ->setName(strip_tags($category->getName()))
  4356. ->setVisibility(1);
  4357. $em->persist($tool);
  4358. $em->flush();
  4359. return true;
  4360. }
  4361. return false;
  4362. }
  4363. /**
  4364. * Check if the learnpath category is visible for a user.
  4365. *
  4366. * @param CLpCategory $category
  4367. * @param User $user
  4368. * @param int
  4369. * @param int
  4370. *
  4371. * @return bool
  4372. */
  4373. public static function categoryIsVisibleForStudent(
  4374. CLpCategory $category,
  4375. User $user,
  4376. $courseId = 0,
  4377. $sessionId = 0
  4378. ) {
  4379. $subscriptionSettings = self::getSubscriptionSettings();
  4380. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4381. return true;
  4382. }
  4383. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4384. if ($isAllowedToEdit) {
  4385. return true;
  4386. }
  4387. if (empty($category)) {
  4388. return false;
  4389. }
  4390. $users = $category->getUsers();
  4391. if (empty($users) || !$users->count()) {
  4392. return true;
  4393. }
  4394. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4395. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4396. if ($category->hasUserAdded($user)) {
  4397. return true;
  4398. }
  4399. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4400. if (!empty($groups)) {
  4401. $em = Database::getManager();
  4402. /** @var ItemPropertyRepository $itemRepo */
  4403. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4404. /** @var CourseRepository $courseRepo */
  4405. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4406. $session = null;
  4407. if (!empty($sessionId)) {
  4408. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4409. }
  4410. $course = $courseRepo->find($courseId);
  4411. // Subscribed groups to a LP
  4412. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4413. TOOL_LEARNPATH_CATEGORY,
  4414. $category->getId(),
  4415. $course,
  4416. $session
  4417. );
  4418. if (!empty($subscribedGroupsInLp)) {
  4419. $groups = array_column($groups, 'iid');
  4420. /** @var CItemProperty $item */
  4421. foreach ($subscribedGroupsInLp as $item) {
  4422. if ($item->getGroup() &&
  4423. in_array($item->getGroup()->getId(), $groups)
  4424. ) {
  4425. return true;
  4426. }
  4427. }
  4428. }
  4429. }
  4430. return false;
  4431. }
  4432. /**
  4433. * Check if a learnpath category is published as course tool.
  4434. *
  4435. * @param CLpCategory $category
  4436. * @param int $courseId
  4437. *
  4438. * @return bool
  4439. */
  4440. public static function categoryIsPublished(
  4441. CLpCategory $category,
  4442. $courseId
  4443. ) {
  4444. $link = self::getCategoryLinkForTool($category->getId());
  4445. $em = Database::getManager();
  4446. $tools = $em
  4447. ->createQuery("
  4448. SELECT t FROM ChamiloCourseBundle:CTool t
  4449. WHERE t.cId = :course AND
  4450. t.name = :name AND
  4451. t.image = 'lp_category.gif' AND
  4452. t.link LIKE :link
  4453. ")
  4454. ->setParameters([
  4455. 'course' => $courseId,
  4456. 'name' => strip_tags($category->getName()),
  4457. 'link' => "$link%",
  4458. ])
  4459. ->getResult();
  4460. /** @var CTool $tool */
  4461. $tool = current($tools);
  4462. return $tool ? $tool->getVisibility() : false;
  4463. }
  4464. /**
  4465. * Restart the whole learnpath. Return the URL of the first element.
  4466. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4467. * To use a similar method statically, use the create_new_attempt() method.
  4468. *
  4469. * @return bool
  4470. */
  4471. public function restart()
  4472. {
  4473. if ($this->debug > 0) {
  4474. error_log('In learnpath::restart()', 0);
  4475. }
  4476. // TODO
  4477. // Call autosave method to save the current progress.
  4478. //$this->index = 0;
  4479. if (api_is_invitee()) {
  4480. return false;
  4481. }
  4482. $session_id = api_get_session_id();
  4483. $course_id = api_get_course_int_id();
  4484. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4485. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4486. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4487. if ($this->debug > 2) {
  4488. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4489. }
  4490. Database::query($sql);
  4491. $view_id = Database::insert_id();
  4492. if ($view_id) {
  4493. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4494. Database::query($sql);
  4495. $this->lp_view_id = $view_id;
  4496. $this->attempt = $this->attempt + 1;
  4497. } else {
  4498. $this->error = 'Could not insert into item_view table...';
  4499. return false;
  4500. }
  4501. $this->autocomplete_parents($this->current);
  4502. foreach ($this->items as $index => $dummy) {
  4503. $this->items[$index]->restart();
  4504. $this->items[$index]->set_lp_view($this->lp_view_id);
  4505. }
  4506. $this->first();
  4507. return true;
  4508. }
  4509. /**
  4510. * Saves the current item.
  4511. *
  4512. * @return bool
  4513. */
  4514. public function save_current()
  4515. {
  4516. $debug = $this->debug;
  4517. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4518. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4519. if ($debug) {
  4520. error_log('save_current() saving item '.$this->current, 0);
  4521. error_log(''.print_r($this->items, true), 0);
  4522. }
  4523. if (isset($this->items[$this->current]) &&
  4524. is_object($this->items[$this->current])
  4525. ) {
  4526. if ($debug) {
  4527. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4528. }
  4529. $res = $this->items[$this->current]->save(
  4530. false,
  4531. $this->prerequisites_match($this->current)
  4532. );
  4533. $this->autocomplete_parents($this->current);
  4534. $status = $this->items[$this->current]->get_status();
  4535. $this->update_queue[$this->current] = $status;
  4536. if ($debug) {
  4537. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4538. }
  4539. return $res;
  4540. }
  4541. return false;
  4542. }
  4543. /**
  4544. * Saves the given item.
  4545. *
  4546. * @param int $item_id Optional (will take from $_REQUEST if null)
  4547. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4548. *
  4549. * @return bool
  4550. */
  4551. public function save_item($item_id = null, $from_outside = true)
  4552. {
  4553. $debug = $this->debug;
  4554. if ($debug) {
  4555. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4556. }
  4557. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4558. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4559. if (empty($item_id)) {
  4560. $item_id = (int) $_REQUEST['id'];
  4561. }
  4562. if (empty($item_id)) {
  4563. $item_id = $this->get_current_item_id();
  4564. }
  4565. if (isset($this->items[$item_id]) &&
  4566. is_object($this->items[$item_id])
  4567. ) {
  4568. if ($debug) {
  4569. error_log('Object exists');
  4570. }
  4571. // Saving the item.
  4572. $res = $this->items[$item_id]->save(
  4573. $from_outside,
  4574. $this->prerequisites_match($item_id)
  4575. );
  4576. if ($debug) {
  4577. error_log('update_queue before:');
  4578. error_log(print_r($this->update_queue, 1));
  4579. }
  4580. $this->autocomplete_parents($item_id);
  4581. $status = $this->items[$item_id]->get_status();
  4582. $this->update_queue[$item_id] = $status;
  4583. if ($debug) {
  4584. error_log('get_status(): '.$status);
  4585. error_log('update_queue after:');
  4586. error_log(print_r($this->update_queue, 1));
  4587. }
  4588. return $res;
  4589. }
  4590. return false;
  4591. }
  4592. /**
  4593. * Saves the last item seen's ID only in case.
  4594. */
  4595. public function save_last()
  4596. {
  4597. $course_id = api_get_course_int_id();
  4598. $debug = $this->debug;
  4599. if ($debug) {
  4600. error_log('In learnpath::save_last()', 0);
  4601. }
  4602. $session_condition = api_get_session_condition(
  4603. api_get_session_id(),
  4604. true,
  4605. false
  4606. );
  4607. $table = Database::get_course_table(TABLE_LP_VIEW);
  4608. if (isset($this->current) && !api_is_invitee()) {
  4609. if ($debug) {
  4610. error_log('Saving current item ('.$this->current.') for later review', 0);
  4611. }
  4612. $sql = "UPDATE $table SET
  4613. last_item = ".$this->get_current_item_id()."
  4614. WHERE
  4615. c_id = $course_id AND
  4616. lp_id = ".$this->get_id()." AND
  4617. user_id = ".$this->get_user_id()." ".$session_condition;
  4618. if ($debug) {
  4619. error_log('Saving last item seen : '.$sql, 0);
  4620. }
  4621. Database::query($sql);
  4622. }
  4623. if (!api_is_invitee()) {
  4624. // Save progress.
  4625. list($progress) = $this->get_progress_bar_text('%');
  4626. if ($progress >= 0 && $progress <= 100) {
  4627. $progress = (int) $progress;
  4628. $sql = "UPDATE $table SET
  4629. progress = $progress
  4630. WHERE
  4631. c_id = $course_id AND
  4632. lp_id = ".$this->get_id()." AND
  4633. user_id = ".$this->get_user_id()." ".$session_condition;
  4634. // Ignore errors as some tables might not have the progress field just yet.
  4635. Database::query($sql);
  4636. $this->progress_db = $progress;
  4637. }
  4638. }
  4639. }
  4640. /**
  4641. * Sets the current item ID (checks if valid and authorized first).
  4642. *
  4643. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4644. */
  4645. public function set_current_item($item_id = null)
  4646. {
  4647. $debug = $this->debug;
  4648. if ($debug) {
  4649. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4650. }
  4651. if (empty($item_id)) {
  4652. if ($debug) {
  4653. error_log('No new current item given, ignore...', 0);
  4654. }
  4655. // Do nothing.
  4656. } else {
  4657. if ($debug) {
  4658. error_log('New current item given is '.$item_id.'...', 0);
  4659. }
  4660. if (is_numeric($item_id)) {
  4661. $item_id = (int) $item_id;
  4662. // TODO: Check in database here.
  4663. $this->last = $this->current;
  4664. $this->current = $item_id;
  4665. // TODO: Update $this->index as well.
  4666. foreach ($this->ordered_items as $index => $item) {
  4667. if ($item == $this->current) {
  4668. $this->index = $index;
  4669. break;
  4670. }
  4671. }
  4672. if ($debug) {
  4673. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4674. }
  4675. } else {
  4676. if ($debug) {
  4677. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4678. }
  4679. }
  4680. }
  4681. }
  4682. /**
  4683. * Sets the encoding.
  4684. *
  4685. * @param string $enc New encoding
  4686. *
  4687. * @return bool
  4688. *
  4689. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4690. */
  4691. public function set_encoding($enc = 'UTF-8')
  4692. {
  4693. $enc = api_refine_encoding_id($enc);
  4694. if (empty($enc)) {
  4695. $enc = api_get_system_encoding();
  4696. }
  4697. if (api_is_encoding_supported($enc)) {
  4698. $lp = $this->get_id();
  4699. if ($lp != 0) {
  4700. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4701. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4702. WHERE iid = ".$lp;
  4703. $res = Database::query($sql);
  4704. return $res;
  4705. }
  4706. }
  4707. return false;
  4708. }
  4709. /**
  4710. * Sets the JS lib setting in the database directly.
  4711. * This is the JavaScript library file this lp needs to load on startup.
  4712. *
  4713. * @param string $lib Proximity setting
  4714. *
  4715. * @return bool True on update success. False otherwise.
  4716. */
  4717. public function set_jslib($lib = '')
  4718. {
  4719. $lp = $this->get_id();
  4720. if ($lp != 0) {
  4721. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4722. $lib = Database::escape_string($lib);
  4723. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4724. WHERE iid = $lp";
  4725. $res = Database::query($sql);
  4726. return $res;
  4727. }
  4728. return false;
  4729. }
  4730. /**
  4731. * Sets the name of the LP maker (publisher) (and save).
  4732. *
  4733. * @param string $name Optional string giving the new content_maker of this learnpath
  4734. *
  4735. * @return bool True
  4736. */
  4737. public function set_maker($name = '')
  4738. {
  4739. if (empty($name)) {
  4740. return false;
  4741. }
  4742. $this->maker = $name;
  4743. $table = Database::get_course_table(TABLE_LP_MAIN);
  4744. $lp_id = $this->get_id();
  4745. $sql = "UPDATE $table SET
  4746. content_maker = '".Database::escape_string($this->maker)."'
  4747. WHERE iid = $lp_id";
  4748. Database::query($sql);
  4749. return true;
  4750. }
  4751. /**
  4752. * Sets the name of the current learnpath (and save).
  4753. *
  4754. * @param string $name Optional string giving the new name of this learnpath
  4755. *
  4756. * @return bool True/False
  4757. */
  4758. public function set_name($name = null)
  4759. {
  4760. if (empty($name)) {
  4761. return false;
  4762. }
  4763. $this->name = Database::escape_string($name);
  4764. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4765. $lp_id = $this->get_id();
  4766. $course_id = $this->course_info['real_id'];
  4767. $sql = "UPDATE $lp_table SET
  4768. name = '".Database::escape_string($this->name)."'
  4769. WHERE iid = $lp_id";
  4770. $result = Database::query($sql);
  4771. // If the lp is visible on the homepage, change his name there.
  4772. if (Database::affected_rows($result)) {
  4773. $session_id = api_get_session_id();
  4774. $session_condition = api_get_session_condition($session_id);
  4775. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4776. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4777. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4778. WHERE
  4779. c_id = $course_id AND
  4780. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4781. Database::query($sql);
  4782. return true;
  4783. }
  4784. return false;
  4785. }
  4786. /**
  4787. * Set index specified prefix terms for all items in this path.
  4788. *
  4789. * @param string $terms_string Comma-separated list of terms
  4790. * @param string $prefix Xapian term prefix
  4791. *
  4792. * @return bool False on error, true otherwise
  4793. */
  4794. public function set_terms_by_prefix($terms_string, $prefix)
  4795. {
  4796. $course_id = api_get_course_int_id();
  4797. if (api_get_setting('search_enabled') !== 'true') {
  4798. return false;
  4799. }
  4800. if (!extension_loaded('xapian')) {
  4801. return false;
  4802. }
  4803. $terms_string = trim($terms_string);
  4804. $terms = explode(',', $terms_string);
  4805. array_walk($terms, 'trim_value');
  4806. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4807. // Don't do anything if no change, verify only at DB, not the search engine.
  4808. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4809. return false;
  4810. }
  4811. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4812. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4813. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4814. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4815. $lp_id = (int) $_POST['lp_id'];
  4816. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4817. $result = Database::query($sql);
  4818. $di = new ChamiloIndexer();
  4819. while ($lp_item = Database::fetch_array($result)) {
  4820. // Get search_did.
  4821. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4822. $sql = 'SELECT * FROM %s
  4823. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4824. LIMIT 1';
  4825. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4826. //echo $sql; echo '<br>';
  4827. $res = Database::query($sql);
  4828. if (Database::num_rows($res) > 0) {
  4829. $se_ref = Database::fetch_array($res);
  4830. // Compare terms.
  4831. $doc = $di->get_document($se_ref['search_did']);
  4832. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4833. $xterms = [];
  4834. foreach ($xapian_terms as $xapian_term) {
  4835. $xterms[] = substr($xapian_term['name'], 1);
  4836. }
  4837. $dterms = $terms;
  4838. $missing_terms = array_diff($dterms, $xterms);
  4839. $deprecated_terms = array_diff($xterms, $dterms);
  4840. // Save it to search engine.
  4841. foreach ($missing_terms as $term) {
  4842. $doc->add_term($prefix.$term, 1);
  4843. }
  4844. foreach ($deprecated_terms as $term) {
  4845. $doc->remove_term($prefix.$term);
  4846. }
  4847. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4848. $di->getDb()->flush();
  4849. }
  4850. }
  4851. return true;
  4852. }
  4853. /**
  4854. * Sets the theme of the LP (local/remote) (and save).
  4855. *
  4856. * @param string $name Optional string giving the new theme of this learnpath
  4857. *
  4858. * @return bool Returns true if theme name is not empty
  4859. */
  4860. public function set_theme($name = '')
  4861. {
  4862. $this->theme = $name;
  4863. $table = Database::get_course_table(TABLE_LP_MAIN);
  4864. $lp_id = $this->get_id();
  4865. $sql = "UPDATE $table
  4866. SET theme = '".Database::escape_string($this->theme)."'
  4867. WHERE iid = $lp_id";
  4868. Database::query($sql);
  4869. return true;
  4870. }
  4871. /**
  4872. * Sets the image of an LP (and save).
  4873. *
  4874. * @param string $name Optional string giving the new image of this learnpath
  4875. *
  4876. * @return bool Returns true if theme name is not empty
  4877. */
  4878. public function set_preview_image($name = '')
  4879. {
  4880. $this->preview_image = $name;
  4881. $table = Database::get_course_table(TABLE_LP_MAIN);
  4882. $lp_id = $this->get_id();
  4883. $sql = "UPDATE $table SET
  4884. preview_image = '".Database::escape_string($this->preview_image)."'
  4885. WHERE iid = $lp_id";
  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. $this->author = $name;
  4899. $table = Database::get_course_table(TABLE_LP_MAIN);
  4900. $lp_id = $this->get_id();
  4901. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4902. WHERE iid = $lp_id";
  4903. Database::query($sql);
  4904. return true;
  4905. }
  4906. /**
  4907. * Sets the hide_toc_frame parameter of a LP (and save).
  4908. *
  4909. * @param int $hide 1 if frame is hidden 0 then else
  4910. *
  4911. * @return bool Returns true if author's name is not empty
  4912. */
  4913. public function set_hide_toc_frame($hide)
  4914. {
  4915. if (intval($hide) == $hide) {
  4916. $this->hide_toc_frame = $hide;
  4917. $table = Database::get_course_table(TABLE_LP_MAIN);
  4918. $lp_id = $this->get_id();
  4919. $sql = "UPDATE $table SET
  4920. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4921. WHERE iid = $lp_id";
  4922. if ($this->debug > 2) {
  4923. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4924. }
  4925. Database::query($sql);
  4926. return true;
  4927. }
  4928. return false;
  4929. }
  4930. /**
  4931. * Sets the prerequisite of a LP (and save).
  4932. *
  4933. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4934. *
  4935. * @return bool returns true if prerequisite is not empty
  4936. */
  4937. public function set_prerequisite($prerequisite)
  4938. {
  4939. $this->prerequisite = (int) $prerequisite;
  4940. $table = Database::get_course_table(TABLE_LP_MAIN);
  4941. $lp_id = $this->get_id();
  4942. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4943. WHERE iid = $lp_id";
  4944. Database::query($sql);
  4945. return true;
  4946. }
  4947. /**
  4948. * Sets the location/proximity of the LP (local/remote) (and save).
  4949. *
  4950. * @param string $name Optional string giving the new location of this learnpath
  4951. *
  4952. * @return bool True on success / False on error
  4953. */
  4954. public function set_proximity($name = '')
  4955. {
  4956. if (empty($name)) {
  4957. return false;
  4958. }
  4959. $this->proximity = $name;
  4960. $table = Database::get_course_table(TABLE_LP_MAIN);
  4961. $lp_id = $this->get_id();
  4962. $sql = "UPDATE $table SET
  4963. content_local = '".Database::escape_string($name)."'
  4964. WHERE iid = $lp_id";
  4965. Database::query($sql);
  4966. return true;
  4967. }
  4968. /**
  4969. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4970. *
  4971. * @param int $id DB ID of the item
  4972. */
  4973. public function set_previous_item($id)
  4974. {
  4975. if ($this->debug > 0) {
  4976. error_log('In learnpath::set_previous_item()', 0);
  4977. }
  4978. $this->last = $id;
  4979. }
  4980. /**
  4981. * Sets use_max_score.
  4982. *
  4983. * @param int $use_max_score Optional string giving the new location of this learnpath
  4984. *
  4985. * @return bool True on success / False on error
  4986. */
  4987. public function set_use_max_score($use_max_score = 1)
  4988. {
  4989. $use_max_score = (int) $use_max_score;
  4990. $this->use_max_score = $use_max_score;
  4991. $table = Database::get_course_table(TABLE_LP_MAIN);
  4992. $lp_id = $this->get_id();
  4993. $sql = "UPDATE $table SET
  4994. use_max_score = '".$this->use_max_score."'
  4995. WHERE iid = $lp_id";
  4996. Database::query($sql);
  4997. return true;
  4998. }
  4999. /**
  5000. * Sets and saves the expired_on date.
  5001. *
  5002. * @param string $expired_on Optional string giving the new author of this learnpath
  5003. *
  5004. * @throws \Doctrine\ORM\OptimisticLockException
  5005. *
  5006. * @return bool Returns true if author's name is not empty
  5007. */
  5008. public function set_expired_on($expired_on)
  5009. {
  5010. $em = Database::getManager();
  5011. /** @var CLp $lp */
  5012. $lp = $em
  5013. ->getRepository('ChamiloCourseBundle:CLp')
  5014. ->findOneBy(
  5015. [
  5016. 'iid' => $this->get_id(),
  5017. ]
  5018. );
  5019. if (!$lp) {
  5020. return false;
  5021. }
  5022. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5023. $lp->setExpiredOn($this->expired_on);
  5024. $em->persist($lp);
  5025. $em->flush();
  5026. return true;
  5027. }
  5028. /**
  5029. * Sets and saves the publicated_on date.
  5030. *
  5031. * @param string $publicated_on Optional string giving the new author of this learnpath
  5032. *
  5033. * @throws \Doctrine\ORM\OptimisticLockException
  5034. *
  5035. * @return bool Returns true if author's name is not empty
  5036. */
  5037. public function set_publicated_on($publicated_on)
  5038. {
  5039. $em = Database::getManager();
  5040. /** @var CLp $lp */
  5041. $lp = $em
  5042. ->getRepository('ChamiloCourseBundle:CLp')
  5043. ->findOneBy(
  5044. [
  5045. 'iid' => $this->get_id(),
  5046. ]
  5047. );
  5048. if (!$lp) {
  5049. return false;
  5050. }
  5051. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5052. $lp->setPublicatedOn($this->publicated_on);
  5053. $em->persist($lp);
  5054. $em->flush();
  5055. return true;
  5056. }
  5057. /**
  5058. * Sets and saves the expired_on date.
  5059. *
  5060. * @return bool Returns true if author's name is not empty
  5061. */
  5062. public function set_modified_on()
  5063. {
  5064. $this->modified_on = api_get_utc_datetime();
  5065. $table = Database::get_course_table(TABLE_LP_MAIN);
  5066. $lp_id = $this->get_id();
  5067. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5068. WHERE iid = $lp_id";
  5069. Database::query($sql);
  5070. return true;
  5071. }
  5072. /**
  5073. * Sets the object's error message.
  5074. *
  5075. * @param string $error Error message. If empty, reinits the error string
  5076. */
  5077. public function set_error_msg($error = '')
  5078. {
  5079. if ($this->debug > 0) {
  5080. error_log('In learnpath::set_error_msg()', 0);
  5081. }
  5082. if (empty($error)) {
  5083. $this->error = '';
  5084. } else {
  5085. $this->error .= $error;
  5086. }
  5087. }
  5088. /**
  5089. * Launches the current item if not 'sco'
  5090. * (starts timer and make sure there is a record ready in the DB).
  5091. *
  5092. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5093. *
  5094. * @return bool
  5095. */
  5096. public function start_current_item($allow_new_attempt = false)
  5097. {
  5098. $debug = $this->debug;
  5099. if ($debug) {
  5100. error_log('In learnpath::start_current_item()');
  5101. error_log('current: '.$this->current);
  5102. }
  5103. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5104. $type = $this->get_type();
  5105. $item_type = $this->items[$this->current]->get_type();
  5106. if (($type == 2 && $item_type != 'sco') ||
  5107. ($type == 3 && $item_type != 'au') ||
  5108. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5109. ) {
  5110. if ($debug) {
  5111. error_log('item type: '.$item_type);
  5112. error_log('lp type: '.$type);
  5113. }
  5114. $this->items[$this->current]->open($allow_new_attempt);
  5115. $this->autocomplete_parents($this->current);
  5116. $prereq_check = $this->prerequisites_match($this->current);
  5117. if ($debug) {
  5118. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5119. }
  5120. $this->items[$this->current]->save(false, $prereq_check);
  5121. }
  5122. // If sco, then it is supposed to have been updated by some other call.
  5123. if ($item_type == 'sco') {
  5124. $this->items[$this->current]->restart();
  5125. }
  5126. }
  5127. if ($debug) {
  5128. error_log('lp_view_session_id');
  5129. error_log($this->lp_view_session_id);
  5130. error_log('api session id');
  5131. error_log(api_get_session_id());
  5132. error_log('End of learnpath::start_current_item()');
  5133. }
  5134. return true;
  5135. }
  5136. /**
  5137. * Stops the processing and counters for the old item (as held in $this->last).
  5138. *
  5139. * @return bool True/False
  5140. */
  5141. public function stop_previous_item()
  5142. {
  5143. $debug = $this->debug;
  5144. if ($debug) {
  5145. error_log('In learnpath::stop_previous_item()', 0);
  5146. }
  5147. if ($this->last != 0 && $this->last != $this->current &&
  5148. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5149. ) {
  5150. if ($debug) {
  5151. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5152. }
  5153. switch ($this->get_type()) {
  5154. case '3':
  5155. if ($this->items[$this->last]->get_type() != 'au') {
  5156. if ($debug) {
  5157. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5158. }
  5159. $this->items[$this->last]->close();
  5160. } else {
  5161. if ($debug) {
  5162. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5163. }
  5164. }
  5165. break;
  5166. case '2':
  5167. if ($this->items[$this->last]->get_type() != 'sco') {
  5168. if ($debug) {
  5169. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5170. }
  5171. $this->items[$this->last]->close();
  5172. } else {
  5173. if ($debug) {
  5174. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5175. }
  5176. }
  5177. break;
  5178. case '1':
  5179. default:
  5180. if ($debug) {
  5181. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5182. }
  5183. $this->items[$this->last]->close();
  5184. break;
  5185. }
  5186. } else {
  5187. if ($debug) {
  5188. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5189. }
  5190. return false;
  5191. }
  5192. return true;
  5193. }
  5194. /**
  5195. * Updates the default view mode from fullscreen to embedded and inversely.
  5196. *
  5197. * @return string The current default view mode ('fullscreen' or 'embedded')
  5198. */
  5199. public function update_default_view_mode()
  5200. {
  5201. $table = Database::get_course_table(TABLE_LP_MAIN);
  5202. $sql = "SELECT * FROM $table
  5203. WHERE iid = ".$this->get_id();
  5204. $res = Database::query($sql);
  5205. if (Database::num_rows($res) > 0) {
  5206. $row = Database::fetch_array($res);
  5207. $default_view_mode = $row['default_view_mod'];
  5208. $view_mode = $default_view_mode;
  5209. switch ($default_view_mode) {
  5210. case 'fullscreen': // default with popup
  5211. $view_mode = 'embedded';
  5212. break;
  5213. case 'embedded': // default view with left menu
  5214. $view_mode = 'embedframe';
  5215. break;
  5216. case 'embedframe': //folded menu
  5217. $view_mode = 'impress';
  5218. break;
  5219. case 'impress':
  5220. $view_mode = 'fullscreen';
  5221. break;
  5222. }
  5223. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5224. WHERE iid = ".$this->get_id();
  5225. Database::query($sql);
  5226. $this->mode = $view_mode;
  5227. return $view_mode;
  5228. }
  5229. return -1;
  5230. }
  5231. /**
  5232. * Updates the default behaviour about auto-commiting SCORM updates.
  5233. *
  5234. * @return bool True if auto-commit has been set to 'on', false otherwise
  5235. */
  5236. public function update_default_scorm_commit()
  5237. {
  5238. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5239. $sql = "SELECT * FROM $lp_table
  5240. WHERE iid = ".$this->get_id();
  5241. $res = Database::query($sql);
  5242. if (Database::num_rows($res) > 0) {
  5243. $row = Database::fetch_array($res);
  5244. $force = $row['force_commit'];
  5245. if ($force == 1) {
  5246. $force = 0;
  5247. $force_return = false;
  5248. } elseif ($force == 0) {
  5249. $force = 1;
  5250. $force_return = true;
  5251. }
  5252. $sql = "UPDATE $lp_table SET force_commit = $force
  5253. WHERE iid = ".$this->get_id();
  5254. Database::query($sql);
  5255. $this->force_commit = $force_return;
  5256. return $force_return;
  5257. }
  5258. return -1;
  5259. }
  5260. /**
  5261. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5262. *
  5263. * @return bool True on success, false on failure
  5264. */
  5265. public function update_display_order()
  5266. {
  5267. $course_id = api_get_course_int_id();
  5268. $table = Database::get_course_table(TABLE_LP_MAIN);
  5269. $sql = "SELECT * FROM $table
  5270. WHERE c_id = $course_id
  5271. ORDER BY display_order";
  5272. $res = Database::query($sql);
  5273. if ($res === false) {
  5274. return false;
  5275. }
  5276. $num = Database::num_rows($res);
  5277. // First check the order is correct, globally (might be wrong because
  5278. // of versions < 1.8.4).
  5279. if ($num > 0) {
  5280. $i = 1;
  5281. while ($row = Database::fetch_array($res)) {
  5282. if ($row['display_order'] != $i) {
  5283. // If we find a gap in the order, we need to fix it.
  5284. $sql = "UPDATE $table SET display_order = $i
  5285. WHERE iid = ".$row['iid'];
  5286. Database::query($sql);
  5287. }
  5288. $i++;
  5289. }
  5290. }
  5291. return true;
  5292. }
  5293. /**
  5294. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5295. *
  5296. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5297. */
  5298. public function update_reinit()
  5299. {
  5300. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5301. $sql = "SELECT * FROM $lp_table
  5302. WHERE iid = ".$this->get_id();
  5303. $res = Database::query($sql);
  5304. if (Database::num_rows($res) > 0) {
  5305. $row = Database::fetch_array($res);
  5306. $force = $row['prevent_reinit'];
  5307. if ($force == 1) {
  5308. $force = 0;
  5309. } elseif ($force == 0) {
  5310. $force = 1;
  5311. }
  5312. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5313. WHERE iid = ".$this->get_id();
  5314. Database::query($sql);
  5315. $this->prevent_reinit = $force;
  5316. return $force;
  5317. }
  5318. return -1;
  5319. }
  5320. /**
  5321. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5322. *
  5323. * @return string 'single', 'multi' or 'seriousgame'
  5324. *
  5325. * @author ndiechburg <noel@cblue.be>
  5326. */
  5327. public function get_attempt_mode()
  5328. {
  5329. //Set default value for seriousgame_mode
  5330. if (!isset($this->seriousgame_mode)) {
  5331. $this->seriousgame_mode = 0;
  5332. }
  5333. // Set default value for prevent_reinit
  5334. if (!isset($this->prevent_reinit)) {
  5335. $this->prevent_reinit = 1;
  5336. }
  5337. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5338. return 'seriousgame';
  5339. }
  5340. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5341. return 'single';
  5342. }
  5343. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5344. return 'multiple';
  5345. }
  5346. return 'single';
  5347. }
  5348. /**
  5349. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5350. *
  5351. * @param string 'seriousgame', 'single' or 'multiple'
  5352. *
  5353. * @return bool
  5354. *
  5355. * @author ndiechburg <noel@cblue.be>
  5356. */
  5357. public function set_attempt_mode($mode)
  5358. {
  5359. switch ($mode) {
  5360. case 'seriousgame':
  5361. $sg_mode = 1;
  5362. $prevent_reinit = 1;
  5363. break;
  5364. case 'single':
  5365. $sg_mode = 0;
  5366. $prevent_reinit = 1;
  5367. break;
  5368. case 'multiple':
  5369. $sg_mode = 0;
  5370. $prevent_reinit = 0;
  5371. break;
  5372. default:
  5373. $sg_mode = 0;
  5374. $prevent_reinit = 0;
  5375. break;
  5376. }
  5377. $this->prevent_reinit = $prevent_reinit;
  5378. $this->seriousgame_mode = $sg_mode;
  5379. $table = Database::get_course_table(TABLE_LP_MAIN);
  5380. $sql = "UPDATE $table SET
  5381. prevent_reinit = $prevent_reinit ,
  5382. seriousgame_mode = $sg_mode
  5383. WHERE iid = ".$this->get_id();
  5384. $res = Database::query($sql);
  5385. if ($res) {
  5386. return true;
  5387. } else {
  5388. return false;
  5389. }
  5390. }
  5391. /**
  5392. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5393. *
  5394. * @author ndiechburg <noel@cblue.be>
  5395. */
  5396. public function switch_attempt_mode()
  5397. {
  5398. if ($this->debug > 0) {
  5399. error_log('In learnpath::switch_attempt_mode()', 0);
  5400. }
  5401. $mode = $this->get_attempt_mode();
  5402. switch ($mode) {
  5403. case 'single':
  5404. $next_mode = 'multiple';
  5405. break;
  5406. case 'multiple':
  5407. $next_mode = 'seriousgame';
  5408. break;
  5409. case 'seriousgame':
  5410. $next_mode = 'single';
  5411. break;
  5412. default:
  5413. $next_mode = 'single';
  5414. break;
  5415. }
  5416. $this->set_attempt_mode($next_mode);
  5417. }
  5418. /**
  5419. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5420. * but possibility to do again a completed item.
  5421. *
  5422. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5423. *
  5424. * @author ndiechburg <noel@cblue.be>
  5425. */
  5426. public function set_seriousgame_mode()
  5427. {
  5428. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5429. $sql = "SELECT * FROM $lp_table
  5430. WHERE iid = ".$this->get_id();
  5431. $res = Database::query($sql);
  5432. if (Database::num_rows($res) > 0) {
  5433. $row = Database::fetch_array($res);
  5434. $force = $row['seriousgame_mode'];
  5435. if ($force == 1) {
  5436. $force = 0;
  5437. } elseif ($force == 0) {
  5438. $force = 1;
  5439. }
  5440. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5441. WHERE iid = ".$this->get_id();
  5442. Database::query($sql);
  5443. $this->seriousgame_mode = $force;
  5444. return $force;
  5445. }
  5446. return -1;
  5447. }
  5448. /**
  5449. * Updates the "scorm_debug" value that shows or hide the debug window.
  5450. *
  5451. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5452. */
  5453. public function update_scorm_debug()
  5454. {
  5455. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5456. $sql = "SELECT * FROM $lp_table
  5457. WHERE iid = ".$this->get_id();
  5458. $res = Database::query($sql);
  5459. if (Database::num_rows($res) > 0) {
  5460. $row = Database::fetch_array($res);
  5461. $force = $row['debug'];
  5462. if ($force == 1) {
  5463. $force = 0;
  5464. } elseif ($force == 0) {
  5465. $force = 1;
  5466. }
  5467. $sql = "UPDATE $lp_table SET debug = $force
  5468. WHERE iid = ".$this->get_id();
  5469. Database::query($sql);
  5470. $this->scorm_debug = $force;
  5471. return $force;
  5472. }
  5473. return -1;
  5474. }
  5475. /**
  5476. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5477. *
  5478. * @author Kevin Van Den Haute
  5479. *
  5480. * @param array
  5481. */
  5482. public function tree_array($array)
  5483. {
  5484. $array = $this->sort_tree_array($array);
  5485. $this->create_tree_array($array);
  5486. }
  5487. /**
  5488. * Creates an array with the elements of the learning path tree in it.
  5489. *
  5490. * @author Kevin Van Den Haute
  5491. *
  5492. * @param array $array
  5493. * @param int $parent
  5494. * @param int $depth
  5495. * @param array $tmp
  5496. */
  5497. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5498. {
  5499. if (is_array($array)) {
  5500. for ($i = 0; $i < count($array); $i++) {
  5501. if ($array[$i]['parent_item_id'] == $parent) {
  5502. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5503. $tmp[] = $array[$i]['parent_item_id'];
  5504. $depth++;
  5505. }
  5506. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5507. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5508. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5509. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5510. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5511. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5512. $this->arrMenu[] = [
  5513. 'id' => $array[$i]['id'],
  5514. 'ref' => $ref,
  5515. 'item_type' => $array[$i]['item_type'],
  5516. 'title' => $array[$i]['title'],
  5517. 'path' => $path,
  5518. 'description' => $array[$i]['description'],
  5519. 'parent_item_id' => $array[$i]['parent_item_id'],
  5520. 'previous_item_id' => $array[$i]['previous_item_id'],
  5521. 'next_item_id' => $array[$i]['next_item_id'],
  5522. 'min_score' => $array[$i]['min_score'],
  5523. 'max_score' => $array[$i]['max_score'],
  5524. 'mastery_score' => $array[$i]['mastery_score'],
  5525. 'display_order' => $array[$i]['display_order'],
  5526. 'prerequisite' => $preq,
  5527. 'depth' => $depth,
  5528. 'audio' => $audio,
  5529. 'prerequisite_min_score' => $prerequisiteMinScore,
  5530. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5531. ];
  5532. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5533. }
  5534. }
  5535. }
  5536. }
  5537. /**
  5538. * Sorts a multi dimensional array by parent id and display order.
  5539. *
  5540. * @author Kevin Van Den Haute
  5541. *
  5542. * @param array $array (array with al the learning path items in it)
  5543. *
  5544. * @return array
  5545. */
  5546. public function sort_tree_array($array)
  5547. {
  5548. foreach ($array as $key => $row) {
  5549. $parent[$key] = $row['parent_item_id'];
  5550. $position[$key] = $row['display_order'];
  5551. }
  5552. if (count($array) > 0) {
  5553. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5554. }
  5555. return $array;
  5556. }
  5557. /**
  5558. * Function that creates a html list of learning path items so that we can add audio files to them.
  5559. *
  5560. * @author Kevin Van Den Haute
  5561. *
  5562. * @return string
  5563. */
  5564. public function overview()
  5565. {
  5566. $return = '';
  5567. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5568. // we need to start a form when we want to update all the mp3 files
  5569. if ($update_audio == 'true') {
  5570. $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">';
  5571. }
  5572. $return .= '<div id="message"></div>';
  5573. if (count($this->items) == 0) {
  5574. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5575. } else {
  5576. $return_audio = '<table class="data_table">';
  5577. $return_audio .= '<tr>';
  5578. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5579. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5580. $return_audio .= '</tr>';
  5581. if ($update_audio != 'true') {
  5582. $return .= '<div class="col-md-12">';
  5583. $return .= self::return_new_tree($update_audio);
  5584. $return .= '</div>';
  5585. $return .= Display::div(
  5586. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5587. ['style' => 'float:left; margin-top:15px;width:100%']
  5588. );
  5589. } else {
  5590. $return_audio .= self::return_new_tree($update_audio);
  5591. $return .= $return_audio.'</table>';
  5592. }
  5593. // We need to close the form when we are updating the mp3 files.
  5594. if ($update_audio == 'true') {
  5595. $return .= '<div class="footer-audio">';
  5596. $return .= Display::button(
  5597. 'save_audio',
  5598. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5599. ['class' => 'btn btn-primary', 'type' => 'submit']
  5600. );
  5601. $return .= '</div>';
  5602. }
  5603. }
  5604. // We need to close the form when we are updating the mp3 files.
  5605. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5606. $return .= '</form>';
  5607. }
  5608. return $return;
  5609. }
  5610. /**
  5611. * @param string $update_audio
  5612. *
  5613. * @return array
  5614. */
  5615. public function processBuildMenuElements($update_audio = 'false')
  5616. {
  5617. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5618. $course_id = api_get_course_int_id();
  5619. $table = Database::get_course_table(TABLE_LP_ITEM);
  5620. $sql = "SELECT * FROM $table
  5621. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5622. $result = Database::query($sql);
  5623. $arrLP = [];
  5624. while ($row = Database::fetch_array($result)) {
  5625. $arrLP[] = [
  5626. 'id' => $row['iid'],
  5627. 'item_type' => $row['item_type'],
  5628. 'title' => Security::remove_XSS($row['title']),
  5629. 'path' => $row['path'],
  5630. 'description' => Security::remove_XSS($row['description']),
  5631. 'parent_item_id' => $row['parent_item_id'],
  5632. 'previous_item_id' => $row['previous_item_id'],
  5633. 'next_item_id' => $row['next_item_id'],
  5634. 'max_score' => $row['max_score'],
  5635. 'min_score' => $row['min_score'],
  5636. 'mastery_score' => $row['mastery_score'],
  5637. 'prerequisite' => $row['prerequisite'],
  5638. 'display_order' => $row['display_order'],
  5639. 'audio' => $row['audio'],
  5640. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5641. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5642. ];
  5643. }
  5644. $this->tree_array($arrLP);
  5645. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5646. unset($this->arrMenu);
  5647. $default_data = null;
  5648. $default_content = null;
  5649. $elements = [];
  5650. $return_audio = null;
  5651. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5652. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5653. for ($i = 0; $i < count($arrLP); $i++) {
  5654. $title = $arrLP[$i]['title'];
  5655. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5656. // Link for the documents
  5657. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5658. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5659. $title_cut = Display::url(
  5660. $title_cut,
  5661. $url,
  5662. [
  5663. 'class' => 'ajax moved',
  5664. 'data-title' => $title,
  5665. 'title' => $title,
  5666. ]
  5667. );
  5668. }
  5669. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5670. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5671. Session::write('pathItem', $arrLP[$i]['path']);
  5672. }
  5673. $oddClass = 'row_even';
  5674. if (($i % 2) == 0) {
  5675. $oddClass = 'row_odd';
  5676. }
  5677. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5678. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5679. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5680. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5681. } else {
  5682. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5683. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5684. } else {
  5685. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5686. $icon = Display::return_icon('certificate.png');
  5687. } else {
  5688. $icon = Display::return_icon('folder_document.gif');
  5689. }
  5690. }
  5691. }
  5692. // The audio column.
  5693. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5694. $audio = '';
  5695. if (!$update_audio || $update_audio != 'true') {
  5696. if (empty($arrLP[$i]['audio'])) {
  5697. $audio .= '';
  5698. }
  5699. } else {
  5700. $types = self::getChapterTypes();
  5701. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5702. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5703. if (!empty($arrLP[$i]['audio'])) {
  5704. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5705. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5706. }
  5707. }
  5708. }
  5709. $return_audio .= Display::span($icon.' '.$title).
  5710. Display::tag(
  5711. 'td',
  5712. $audio,
  5713. ['style' => '']
  5714. );
  5715. $return_audio .= '</td>';
  5716. $move_icon = '';
  5717. $move_item_icon = '';
  5718. $edit_icon = '';
  5719. $delete_icon = '';
  5720. $audio_icon = '';
  5721. $prerequisities_icon = '';
  5722. $forumIcon = '';
  5723. $previewIcon = '';
  5724. $pluginCalendarIcon = '';
  5725. $orderIcons = '';
  5726. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5727. $plugin = null;
  5728. if ($pluginCalendar) {
  5729. $plugin = LearningCalendarPlugin::create();
  5730. }
  5731. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5732. if ($is_allowed_to_edit) {
  5733. if (!$update_audio || $update_audio != 'true') {
  5734. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5735. $move_icon .= '<a class="moved" href="#">';
  5736. $move_icon .= Display::return_icon(
  5737. 'move_everywhere.png',
  5738. get_lang('Move'),
  5739. [],
  5740. ICON_SIZE_TINY
  5741. );
  5742. $move_icon .= '</a>';
  5743. }
  5744. }
  5745. // No edit for this item types
  5746. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5747. if ($arrLP[$i]['item_type'] != 'dir') {
  5748. $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">';
  5749. $edit_icon .= Display::return_icon(
  5750. 'edit.png',
  5751. get_lang('LearnpathEditModule'),
  5752. [],
  5753. ICON_SIZE_TINY
  5754. );
  5755. $edit_icon .= '</a>';
  5756. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5757. $forumThread = null;
  5758. if (isset($this->items[$arrLP[$i]['id']])) {
  5759. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5760. $this->course_int_id,
  5761. $this->lp_session_id
  5762. );
  5763. }
  5764. if ($forumThread) {
  5765. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5766. 'action' => 'dissociate_forum',
  5767. 'id' => $arrLP[$i]['id'],
  5768. 'lp_id' => $this->lp_id,
  5769. ]);
  5770. $forumIcon = Display::url(
  5771. Display::return_icon(
  5772. 'forum.png',
  5773. get_lang('DissociateForumToLPItem'),
  5774. [],
  5775. ICON_SIZE_TINY
  5776. ),
  5777. $forumIconUrl,
  5778. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5779. );
  5780. } else {
  5781. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5782. 'action' => 'create_forum',
  5783. 'id' => $arrLP[$i]['id'],
  5784. 'lp_id' => $this->lp_id,
  5785. ]);
  5786. $forumIcon = Display::url(
  5787. Display::return_icon(
  5788. 'forum.png',
  5789. get_lang('AssociateForumToLPItem'),
  5790. [],
  5791. ICON_SIZE_TINY
  5792. ),
  5793. $forumIconUrl,
  5794. ['class' => 'btn btn-default lp-btn-associate-forum']
  5795. );
  5796. }
  5797. }
  5798. } else {
  5799. $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">';
  5800. $edit_icon .= Display::return_icon(
  5801. 'edit.png',
  5802. get_lang('LearnpathEditModule'),
  5803. [],
  5804. ICON_SIZE_TINY
  5805. );
  5806. $edit_icon .= '</a>';
  5807. }
  5808. } else {
  5809. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5810. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5811. $edit_icon .= Display::return_icon(
  5812. 'edit.png',
  5813. get_lang('Edit'),
  5814. [],
  5815. ICON_SIZE_TINY
  5816. );
  5817. $edit_icon .= '</a>';
  5818. }
  5819. }
  5820. if ($pluginCalendar) {
  5821. $pluginLink = $pluginUrl.
  5822. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5823. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5824. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5825. if ($itemInfo && $itemInfo['value'] == 1) {
  5826. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5827. }
  5828. $pluginCalendarIcon = Display::url(
  5829. $iconCalendar,
  5830. $pluginLink,
  5831. ['class' => 'btn btn-default']
  5832. );
  5833. }
  5834. $delete_icon .= ' <a
  5835. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5836. onclick="return confirmation(\''.addslashes($title).'\');"
  5837. class="btn btn-default">';
  5838. $delete_icon .= Display::return_icon(
  5839. 'delete.png',
  5840. get_lang('LearnpathDeleteModule'),
  5841. [],
  5842. ICON_SIZE_TINY
  5843. );
  5844. $delete_icon .= '</a>';
  5845. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5846. $previewImage = Display::return_icon(
  5847. 'preview_view.png',
  5848. get_lang('Preview'),
  5849. [],
  5850. ICON_SIZE_TINY
  5851. );
  5852. switch ($arrLP[$i]['item_type']) {
  5853. case TOOL_DOCUMENT:
  5854. case TOOL_LP_FINAL_ITEM:
  5855. case TOOL_READOUT_TEXT:
  5856. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5857. $previewIcon = Display::url(
  5858. $previewImage,
  5859. $urlPreviewLink,
  5860. [
  5861. 'target' => '_blank',
  5862. 'class' => 'btn btn-default',
  5863. 'data-title' => $arrLP[$i]['title'],
  5864. 'title' => $arrLP[$i]['title'],
  5865. ]
  5866. );
  5867. break;
  5868. case TOOL_THREAD:
  5869. case TOOL_FORUM:
  5870. case TOOL_QUIZ:
  5871. case TOOL_STUDENTPUBLICATION:
  5872. case TOOL_LP_FINAL_ITEM:
  5873. case TOOL_LINK:
  5874. //$target = '';
  5875. //$class = 'btn btn-default ajax';
  5876. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5877. $class = 'btn btn-default';
  5878. $target = '_blank';
  5879. //}
  5880. $link = self::rl_get_resource_link_for_learnpath(
  5881. $this->course_int_id,
  5882. $this->lp_id,
  5883. $arrLP[$i]['id'],
  5884. 0
  5885. );
  5886. $previewIcon = Display::url(
  5887. $previewImage,
  5888. $link,
  5889. [
  5890. 'class' => $class,
  5891. 'data-title' => $arrLP[$i]['title'],
  5892. 'title' => $arrLP[$i]['title'],
  5893. 'target' => $target,
  5894. ]
  5895. );
  5896. break;
  5897. default:
  5898. $previewIcon = Display::url(
  5899. $previewImage,
  5900. $url.'&action=view_item',
  5901. ['class' => 'btn btn-default', 'target' => '_blank']
  5902. );
  5903. break;
  5904. }
  5905. if ($arrLP[$i]['item_type'] != 'dir') {
  5906. $prerequisities_icon = Display::url(
  5907. Display::return_icon(
  5908. 'accept.png',
  5909. get_lang('LearnpathPrerequisites'),
  5910. [],
  5911. ICON_SIZE_TINY
  5912. ),
  5913. $url.'&action=edit_item_prereq',
  5914. ['class' => 'btn btn-default']
  5915. );
  5916. if ($arrLP[$i]['item_type'] != 'final_item') {
  5917. $move_item_icon = Display::url(
  5918. Display::return_icon(
  5919. 'move.png',
  5920. get_lang('Move'),
  5921. [],
  5922. ICON_SIZE_TINY
  5923. ),
  5924. $url.'&action=move_item',
  5925. ['class' => 'btn btn-default']
  5926. );
  5927. }
  5928. $audio_icon = Display::url(
  5929. Display::return_icon(
  5930. 'audio.png',
  5931. get_lang('UplUpload'),
  5932. [],
  5933. ICON_SIZE_TINY
  5934. ),
  5935. $url.'&action=add_audio',
  5936. ['class' => 'btn btn-default']
  5937. );
  5938. }
  5939. }
  5940. if ($update_audio != 'true') {
  5941. $row = $move_icon.' '.$icon.
  5942. Display::span($title_cut).
  5943. Display::tag(
  5944. 'div',
  5945. "<div class=\"btn-group btn-group-xs\">
  5946. $previewIcon
  5947. $audio
  5948. $edit_icon
  5949. $pluginCalendarIcon
  5950. $forumIcon
  5951. $prerequisities_icon
  5952. $move_item_icon
  5953. $audio_icon
  5954. $delete_icon
  5955. </div>",
  5956. ['class' => 'btn-toolbar button_actions']
  5957. );
  5958. } else {
  5959. $row =
  5960. Display::span($title.$icon).
  5961. Display::span($audio, ['class' => 'button_actions']);
  5962. }
  5963. $parent_id = $arrLP[$i]['parent_item_id'];
  5964. $default_data[$arrLP[$i]['id']] = $row;
  5965. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5966. if (empty($parent_id)) {
  5967. $elements[$arrLP[$i]['id']]['data'] = $row;
  5968. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5969. } else {
  5970. $parent_arrays = [];
  5971. if ($arrLP[$i]['depth'] > 1) {
  5972. //Getting list of parents
  5973. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5974. foreach ($arrLP as $item) {
  5975. if ($item['id'] == $parent_id) {
  5976. if ($item['parent_item_id'] == 0) {
  5977. $parent_id = $item['id'];
  5978. break;
  5979. } else {
  5980. $parent_id = $item['parent_item_id'];
  5981. if (empty($parent_arrays)) {
  5982. $parent_arrays[] = intval($item['id']);
  5983. }
  5984. $parent_arrays[] = $parent_id;
  5985. break;
  5986. }
  5987. }
  5988. }
  5989. }
  5990. }
  5991. if (!empty($parent_arrays)) {
  5992. $parent_arrays = array_reverse($parent_arrays);
  5993. $val = '$elements';
  5994. $x = 0;
  5995. foreach ($parent_arrays as $item) {
  5996. if ($x != count($parent_arrays) - 1) {
  5997. $val .= '["'.$item.'"]["children"]';
  5998. } else {
  5999. $val .= '["'.$item.'"]["children"]';
  6000. }
  6001. $x++;
  6002. }
  6003. $val .= "";
  6004. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6005. eval($code_str);
  6006. } else {
  6007. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6008. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6009. }
  6010. }
  6011. }
  6012. return [
  6013. 'elements' => $elements,
  6014. 'default_data' => $default_data,
  6015. 'default_content' => $default_content,
  6016. 'return_audio' => $return_audio,
  6017. ];
  6018. }
  6019. /**
  6020. * @param string $updateAudio true/false strings
  6021. *
  6022. * @return string
  6023. */
  6024. public function returnLpItemList($updateAudio)
  6025. {
  6026. $result = $this->processBuildMenuElements($updateAudio);
  6027. $html = self::print_recursive(
  6028. $result['elements'],
  6029. $result['default_data'],
  6030. $result['default_content']
  6031. );
  6032. if (!empty($html)) {
  6033. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6034. }
  6035. return $html;
  6036. }
  6037. /**
  6038. * @param string $update_audio
  6039. * @param bool $drop_element_here
  6040. *
  6041. * @return string
  6042. */
  6043. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6044. {
  6045. $return = '';
  6046. $result = $this->processBuildMenuElements($update_audio);
  6047. $list = '<ul id="lp_item_list">';
  6048. $tree = $this->print_recursive(
  6049. $result['elements'],
  6050. $result['default_data'],
  6051. $result['default_content']
  6052. );
  6053. if (!empty($tree)) {
  6054. $list .= $tree;
  6055. } else {
  6056. if ($drop_element_here) {
  6057. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6058. }
  6059. }
  6060. $list .= '</ul>';
  6061. $return .= Display::panelCollapse(
  6062. $this->name,
  6063. $list,
  6064. 'scorm-list',
  6065. null,
  6066. 'scorm-list-accordion',
  6067. 'scorm-list-collapse'
  6068. );
  6069. if ($update_audio === 'true') {
  6070. $return = $result['return_audio'];
  6071. }
  6072. return $return;
  6073. }
  6074. /**
  6075. * @param array $elements
  6076. * @param array $default_data
  6077. * @param array $default_content
  6078. *
  6079. * @return string
  6080. */
  6081. public function print_recursive($elements, $default_data, $default_content)
  6082. {
  6083. $return = '';
  6084. foreach ($elements as $key => $item) {
  6085. if (isset($item['load_data']) || empty($item['data'])) {
  6086. $item['data'] = $default_data[$item['load_data']];
  6087. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6088. }
  6089. $sub_list = '';
  6090. if (isset($item['type']) && $item['type'] == 'dir') {
  6091. // empty value
  6092. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6093. }
  6094. if (empty($item['children'])) {
  6095. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6096. $active = null;
  6097. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6098. $active = 'active';
  6099. }
  6100. $return .= Display::tag(
  6101. 'li',
  6102. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6103. ['id' => $key, 'class' => 'record li_container']
  6104. );
  6105. } else {
  6106. // Sections
  6107. $data = '';
  6108. if (isset($item['children'])) {
  6109. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6110. }
  6111. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6112. $return .= Display::tag(
  6113. 'li',
  6114. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6115. ['id' => $key, 'class' => 'record li_container']
  6116. );
  6117. }
  6118. }
  6119. return $return;
  6120. }
  6121. /**
  6122. * This function builds the action menu.
  6123. *
  6124. * @param bool $returnContent Optional
  6125. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6126. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6127. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6128. *
  6129. * @return string
  6130. */
  6131. public function build_action_menu(
  6132. $returnContent = false,
  6133. $showRequirementButtons = true,
  6134. $isConfigPage = false,
  6135. $allowExpand = true
  6136. ) {
  6137. $actionsLeft = '';
  6138. $actionsRight = '';
  6139. $actionsLeft .= Display::url(
  6140. Display::return_icon(
  6141. 'back.png',
  6142. get_lang('ReturnToLearningPaths'),
  6143. '',
  6144. ICON_SIZE_MEDIUM
  6145. ),
  6146. 'lp_controller.php?'.api_get_cidreq()
  6147. );
  6148. $actionsLeft .= Display::url(
  6149. Display::return_icon(
  6150. 'preview_view.png',
  6151. get_lang('Preview'),
  6152. '',
  6153. ICON_SIZE_MEDIUM
  6154. ),
  6155. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6156. 'action' => 'view',
  6157. 'lp_id' => $this->lp_id,
  6158. 'isStudentView' => 'true',
  6159. ])
  6160. );
  6161. $actionsLeft .= Display::url(
  6162. Display::return_icon(
  6163. 'upload_audio.png',
  6164. get_lang('UpdateAllAudioFragments'),
  6165. '',
  6166. ICON_SIZE_MEDIUM
  6167. ),
  6168. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6169. 'action' => 'admin_view',
  6170. 'lp_id' => $this->lp_id,
  6171. 'updateaudio' => 'true',
  6172. ])
  6173. );
  6174. if (!$isConfigPage) {
  6175. $actionsLeft .= Display::url(
  6176. Display::return_icon(
  6177. 'settings.png',
  6178. get_lang('CourseSettings'),
  6179. '',
  6180. ICON_SIZE_MEDIUM
  6181. ),
  6182. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6183. 'action' => 'edit',
  6184. 'lp_id' => $this->lp_id,
  6185. ])
  6186. );
  6187. } else {
  6188. $actionsLeft .= Display::url(
  6189. Display::return_icon(
  6190. 'edit.png',
  6191. get_lang('Edit'),
  6192. '',
  6193. ICON_SIZE_MEDIUM
  6194. ),
  6195. 'lp_controller.php?'.http_build_query([
  6196. 'action' => 'build',
  6197. 'lp_id' => $this->lp_id,
  6198. ]).'&'.api_get_cidreq()
  6199. );
  6200. }
  6201. if ($allowExpand) {
  6202. $actionsLeft .= Display::url(
  6203. Display::return_icon(
  6204. 'expand.png',
  6205. get_lang('Expand'),
  6206. ['id' => 'expand'],
  6207. ICON_SIZE_MEDIUM
  6208. ).
  6209. Display::return_icon(
  6210. 'contract.png',
  6211. get_lang('Collapse'),
  6212. ['id' => 'contract', 'class' => 'hide'],
  6213. ICON_SIZE_MEDIUM
  6214. ),
  6215. '#',
  6216. ['role' => 'button', 'id' => 'hide_bar_template']
  6217. );
  6218. }
  6219. if ($showRequirementButtons) {
  6220. $buttons = [
  6221. [
  6222. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6223. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6224. 'action' => 'set_previous_step_as_prerequisite',
  6225. 'lp_id' => $this->lp_id,
  6226. ]),
  6227. ],
  6228. [
  6229. 'title' => get_lang('ClearAllPrerequisites'),
  6230. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6231. 'action' => 'clear_prerequisites',
  6232. 'lp_id' => $this->lp_id,
  6233. ]),
  6234. ],
  6235. ];
  6236. $actionsRight = Display::groupButtonWithDropDown(
  6237. get_lang('PrerequisitesOptions'),
  6238. $buttons,
  6239. true
  6240. );
  6241. }
  6242. $toolbar = Display::toolbarAction(
  6243. 'actions-lp-controller',
  6244. [$actionsLeft, $actionsRight]
  6245. );
  6246. if ($returnContent) {
  6247. return $toolbar;
  6248. }
  6249. echo $toolbar;
  6250. }
  6251. /**
  6252. * Creates the default learning path folder.
  6253. *
  6254. * @param array $course
  6255. * @param int $creatorId
  6256. *
  6257. * @return bool
  6258. */
  6259. public static function generate_learning_path_folder($course, $creatorId = 0)
  6260. {
  6261. // Creating learning_path folder
  6262. $dir = '/learning_path';
  6263. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6264. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6265. $folder = false;
  6266. if (!is_dir($filepath.'/'.$dir)) {
  6267. $folderData = create_unexisting_directory(
  6268. $course,
  6269. $creatorId,
  6270. 0,
  6271. null,
  6272. 0,
  6273. $filepath,
  6274. $dir,
  6275. get_lang('LearningPaths'),
  6276. 0
  6277. );
  6278. if (!empty($folderData)) {
  6279. $folder = true;
  6280. }
  6281. } else {
  6282. $folder = true;
  6283. }
  6284. return $folder;
  6285. }
  6286. /**
  6287. * @param array $course
  6288. * @param string $lp_name
  6289. * @param int $creatorId
  6290. *
  6291. * @return array
  6292. */
  6293. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6294. {
  6295. $filepath = '';
  6296. $dir = '/learning_path/';
  6297. if (empty($lp_name)) {
  6298. $lp_name = $this->name;
  6299. }
  6300. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6301. $folder = self::generate_learning_path_folder($course, $creatorId);
  6302. // Limits title size
  6303. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6304. $dir = $dir.$title;
  6305. // Creating LP folder
  6306. $documentId = null;
  6307. if ($folder) {
  6308. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6309. if (!is_dir($filepath.'/'.$dir)) {
  6310. $folderData = create_unexisting_directory(
  6311. $course,
  6312. $creatorId,
  6313. 0,
  6314. 0,
  6315. 0,
  6316. $filepath,
  6317. $dir,
  6318. $lp_name
  6319. );
  6320. if (!empty($folderData)) {
  6321. $folder = true;
  6322. }
  6323. $documentId = $folderData['id'];
  6324. } else {
  6325. $folder = true;
  6326. }
  6327. $dir = $dir.'/';
  6328. if ($folder) {
  6329. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6330. }
  6331. }
  6332. if (empty($documentId)) {
  6333. $dir = api_remove_trailing_slash($dir);
  6334. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6335. }
  6336. $array = [
  6337. 'dir' => $dir,
  6338. 'filepath' => $filepath,
  6339. 'folder' => $folder,
  6340. 'id' => $documentId,
  6341. ];
  6342. return $array;
  6343. }
  6344. /**
  6345. * Create a new document //still needs some finetuning.
  6346. *
  6347. * @param array $courseInfo
  6348. * @param string $content
  6349. * @param string $title
  6350. * @param string $extension
  6351. * @param int $parentId
  6352. * @param int $creatorId creator id
  6353. *
  6354. * @return int
  6355. */
  6356. public function create_document(
  6357. $courseInfo,
  6358. $content = '',
  6359. $title = '',
  6360. $extension = 'html',
  6361. $parentId = 0,
  6362. $creatorId = 0
  6363. ) {
  6364. if (!empty($courseInfo)) {
  6365. $course_id = $courseInfo['real_id'];
  6366. } else {
  6367. $course_id = api_get_course_int_id();
  6368. }
  6369. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6370. $sessionId = api_get_session_id();
  6371. // Generates folder
  6372. $result = $this->generate_lp_folder($courseInfo);
  6373. $dir = $result['dir'];
  6374. if (empty($parentId) || $parentId == '/') {
  6375. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6376. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6377. if ($parentId === '/') {
  6378. $dir = '/';
  6379. }
  6380. // Please, do not modify this dirname formatting.
  6381. if (strstr($dir, '..')) {
  6382. $dir = '/';
  6383. }
  6384. if (!empty($dir[0]) && $dir[0] == '.') {
  6385. $dir = substr($dir, 1);
  6386. }
  6387. if (!empty($dir[0]) && $dir[0] != '/') {
  6388. $dir = '/'.$dir;
  6389. }
  6390. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6391. $dir .= '/';
  6392. }
  6393. } else {
  6394. $parentInfo = DocumentManager::get_document_data_by_id(
  6395. $parentId,
  6396. $courseInfo['code']
  6397. );
  6398. if (!empty($parentInfo)) {
  6399. $dir = $parentInfo['path'].'/';
  6400. }
  6401. }
  6402. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6403. if (!is_dir($filepath)) {
  6404. $dir = '/';
  6405. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6406. }
  6407. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6408. // is already escaped twice when it gets here.
  6409. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6410. if (!empty($title)) {
  6411. $title = api_replace_dangerous_char(stripslashes($title));
  6412. } else {
  6413. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6414. }
  6415. $title = disable_dangerous_file($title);
  6416. $filename = $title;
  6417. $content = !empty($content) ? $content : $_POST['content_lp'];
  6418. $tmp_filename = $filename;
  6419. $i = 0;
  6420. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6421. $tmp_filename = $filename.'_'.++$i;
  6422. }
  6423. $filename = $tmp_filename.'.'.$extension;
  6424. if ($extension == 'html') {
  6425. $content = stripslashes($content);
  6426. $content = str_replace(
  6427. api_get_path(WEB_COURSE_PATH),
  6428. api_get_path(REL_PATH).'courses/',
  6429. $content
  6430. );
  6431. // Change the path of mp3 to absolute.
  6432. // The first regexp deals with :// urls.
  6433. $content = preg_replace(
  6434. "|(flashvars=\"file=)([^:/]+)/|",
  6435. "$1".api_get_path(
  6436. REL_COURSE_PATH
  6437. ).$courseInfo['path'].'/document/',
  6438. $content
  6439. );
  6440. // The second regexp deals with audio/ urls.
  6441. $content = preg_replace(
  6442. "|(flashvars=\"file=)([^/]+)/|",
  6443. "$1".api_get_path(
  6444. REL_COURSE_PATH
  6445. ).$courseInfo['path'].'/document/$2/',
  6446. $content
  6447. );
  6448. // For flv player: To prevent edition problem with firefox,
  6449. // we have to use a strange tip (don't blame me please).
  6450. $content = str_replace(
  6451. '</body>',
  6452. '<style type="text/css">body{}</style></body>',
  6453. $content
  6454. );
  6455. }
  6456. if (!file_exists($filepath.$filename)) {
  6457. if ($fp = @fopen($filepath.$filename, 'w')) {
  6458. fputs($fp, $content);
  6459. fclose($fp);
  6460. $file_size = filesize($filepath.$filename);
  6461. $save_file_path = $dir.$filename;
  6462. $document_id = add_document(
  6463. $courseInfo,
  6464. $save_file_path,
  6465. 'file',
  6466. $file_size,
  6467. $tmp_filename,
  6468. '',
  6469. 0, //readonly
  6470. true,
  6471. null,
  6472. $sessionId,
  6473. $creatorId
  6474. );
  6475. if ($document_id) {
  6476. api_item_property_update(
  6477. $courseInfo,
  6478. TOOL_DOCUMENT,
  6479. $document_id,
  6480. 'DocumentAdded',
  6481. $creatorId,
  6482. null,
  6483. null,
  6484. null,
  6485. null,
  6486. $sessionId
  6487. );
  6488. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6489. $new_title = $originalTitle;
  6490. if ($new_comment || $new_title) {
  6491. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6492. $ct = '';
  6493. if ($new_comment) {
  6494. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6495. }
  6496. if ($new_title) {
  6497. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6498. }
  6499. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6500. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6501. Database::query($sql);
  6502. }
  6503. }
  6504. return $document_id;
  6505. }
  6506. }
  6507. }
  6508. /**
  6509. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6510. *
  6511. * @param array $_course array
  6512. */
  6513. public function edit_document($_course)
  6514. {
  6515. $course_id = api_get_course_int_id();
  6516. $urlAppend = api_get_configuration_value('url_append');
  6517. // Please, do not modify this dirname formatting.
  6518. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6519. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6520. if (strstr($dir, '..')) {
  6521. $dir = '/';
  6522. }
  6523. if (isset($dir[0]) && $dir[0] == '.') {
  6524. $dir = substr($dir, 1);
  6525. }
  6526. if (isset($dir[0]) && $dir[0] != '/') {
  6527. $dir = '/'.$dir;
  6528. }
  6529. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6530. $dir .= '/';
  6531. }
  6532. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6533. if (!is_dir($filepath)) {
  6534. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6535. }
  6536. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6537. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6538. $document_id = (int) $_POST['path'];
  6539. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6540. if (empty($documentInfo)) {
  6541. // Try with iid
  6542. $table = Database::get_course_table(TABLE_DOCUMENT);
  6543. $sql = "SELECT id, path FROM $table
  6544. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6545. $res_doc = Database::query($sql);
  6546. $row = Database::fetch_array($res_doc);
  6547. if ($row) {
  6548. $document_id = $row['id'];
  6549. $documentPath = $row['path'];
  6550. }
  6551. } else {
  6552. $documentPath = $documentInfo['path'];
  6553. }
  6554. $content = stripslashes($_POST['content_lp']);
  6555. $file = $filepath.$documentPath;
  6556. if (!file_exists($file)) {
  6557. return false;
  6558. }
  6559. if ($fp = @fopen($file, 'w')) {
  6560. $content = str_replace(
  6561. api_get_path(WEB_COURSE_PATH),
  6562. $urlAppend.api_get_path(REL_COURSE_PATH),
  6563. $content
  6564. );
  6565. // Change the path of mp3 to absolute.
  6566. // The first regexp deals with :// urls.
  6567. $content = preg_replace(
  6568. "|(flashvars=\"file=)([^:/]+)/|",
  6569. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6570. $content
  6571. );
  6572. // The second regexp deals with audio/ urls.
  6573. $content = preg_replace(
  6574. "|(flashvars=\"file=)([^:/]+)/|",
  6575. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6576. $content
  6577. );
  6578. fputs($fp, $content);
  6579. fclose($fp);
  6580. $sql = "UPDATE $table_doc SET
  6581. title='".Database::escape_string($_POST['title'])."'
  6582. WHERE c_id = $course_id AND id = ".$document_id;
  6583. Database::query($sql);
  6584. }
  6585. }
  6586. }
  6587. /**
  6588. * Displays the selected item, with a panel for manipulating the item.
  6589. *
  6590. * @param int $item_id
  6591. * @param string $msg
  6592. * @param bool $show_actions
  6593. *
  6594. * @return string
  6595. */
  6596. public function display_item($item_id, $msg = null, $show_actions = true)
  6597. {
  6598. $course_id = api_get_course_int_id();
  6599. $return = '';
  6600. if (is_numeric($item_id)) {
  6601. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6602. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6603. WHERE lp.iid = ".intval($item_id);
  6604. $result = Database::query($sql);
  6605. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6606. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6607. // Prevents wrong parent selection for document, see Bug#1251.
  6608. if ($row['item_type'] != 'dir') {
  6609. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6610. }
  6611. if ($show_actions) {
  6612. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6613. }
  6614. $return .= '<div style="padding:10px;">';
  6615. if ($msg != '') {
  6616. $return .= $msg;
  6617. }
  6618. $return .= '<h3>'.$row['title'].'</h3>';
  6619. switch ($row['item_type']) {
  6620. case TOOL_THREAD:
  6621. $link = $this->rl_get_resource_link_for_learnpath(
  6622. $course_id,
  6623. $row['lp_id'],
  6624. $item_id,
  6625. 0
  6626. );
  6627. $return .= Display::url(
  6628. get_lang('GoToThread'),
  6629. $link,
  6630. ['class' => 'btn btn-primary']
  6631. );
  6632. break;
  6633. case TOOL_FORUM:
  6634. $return .= Display::url(
  6635. get_lang('GoToForum'),
  6636. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6637. ['class' => 'btn btn-primary']
  6638. );
  6639. break;
  6640. case TOOL_QUIZ:
  6641. if (!empty($row['path'])) {
  6642. $exercise = new Exercise();
  6643. $exercise->read($row['path']);
  6644. $return .= $exercise->description.'<br />';
  6645. $return .= Display::url(
  6646. get_lang('GoToExercise'),
  6647. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6648. ['class' => 'btn btn-primary']
  6649. );
  6650. }
  6651. break;
  6652. case TOOL_LP_FINAL_ITEM:
  6653. $return .= $this->getSavedFinalItem();
  6654. break;
  6655. case TOOL_DOCUMENT:
  6656. case TOOL_READOUT_TEXT:
  6657. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6658. $sql_doc = "SELECT path FROM $tbl_doc
  6659. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6660. $result = Database::query($sql_doc);
  6661. $path_file = Database::result($result, 0, 0);
  6662. $path_parts = pathinfo($path_file);
  6663. // TODO: Correct the following naive comparisons.
  6664. if (in_array($path_parts['extension'], [
  6665. 'html',
  6666. 'txt',
  6667. 'png',
  6668. 'jpg',
  6669. 'JPG',
  6670. 'jpeg',
  6671. 'JPEG',
  6672. 'gif',
  6673. 'swf',
  6674. 'pdf',
  6675. 'htm',
  6676. ])) {
  6677. $return .= $this->display_document($row['path'], true, true);
  6678. }
  6679. break;
  6680. case TOOL_HOTPOTATOES:
  6681. $return .= $this->display_document($row['path'], false, true);
  6682. break;
  6683. }
  6684. $return .= '</div>';
  6685. }
  6686. }
  6687. return $return;
  6688. }
  6689. /**
  6690. * Shows the needed forms for editing a specific item.
  6691. *
  6692. * @param int $item_id
  6693. *
  6694. * @throws Exception
  6695. * @throws HTML_QuickForm_Error
  6696. *
  6697. * @return string
  6698. */
  6699. public function display_edit_item($item_id)
  6700. {
  6701. $course_id = api_get_course_int_id();
  6702. $return = '';
  6703. $item_id = (int) $item_id;
  6704. if (empty($item_id)) {
  6705. return '';
  6706. }
  6707. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6708. $sql = "SELECT * FROM $tbl_lp_item
  6709. WHERE iid = ".$item_id;
  6710. $res = Database::query($sql);
  6711. $row = Database::fetch_array($res);
  6712. switch ($row['item_type']) {
  6713. case 'dir':
  6714. case 'asset':
  6715. case 'sco':
  6716. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6717. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6718. $return .= $this->display_item_form(
  6719. $row['item_type'],
  6720. get_lang('EditCurrentChapter').' :',
  6721. 'edit',
  6722. $item_id,
  6723. $row
  6724. );
  6725. } else {
  6726. $return .= $this->display_item_form(
  6727. $row['item_type'],
  6728. get_lang('EditCurrentChapter').' :',
  6729. 'edit_item',
  6730. $item_id,
  6731. $row
  6732. );
  6733. }
  6734. break;
  6735. case TOOL_DOCUMENT:
  6736. case TOOL_READOUT_TEXT:
  6737. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6738. $sql = "SELECT lp.*, doc.path as dir
  6739. FROM $tbl_lp_item as lp
  6740. LEFT JOIN $tbl_doc as doc
  6741. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6742. WHERE
  6743. doc.c_id = $course_id AND
  6744. lp.iid = ".$item_id;
  6745. $res_step = Database::query($sql);
  6746. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6747. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6748. if ($row['item_type'] === TOOL_DOCUMENT) {
  6749. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6750. }
  6751. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6752. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6753. }
  6754. break;
  6755. case TOOL_LINK:
  6756. $linkId = (int) $row['path'];
  6757. if (!empty($linkId)) {
  6758. $table = Database::get_course_table(TABLE_LINK);
  6759. $sql = 'SELECT url FROM '.$table.'
  6760. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6761. $res_link = Database::query($sql);
  6762. $row_link = Database::fetch_array($res_link);
  6763. if (empty($row_link)) {
  6764. // Try with id
  6765. $sql = 'SELECT url FROM '.$table.'
  6766. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6767. $res_link = Database::query($sql);
  6768. $row_link = Database::fetch_array($res_link);
  6769. }
  6770. if (is_array($row_link)) {
  6771. $row['url'] = $row_link['url'];
  6772. }
  6773. }
  6774. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6775. $return .= $this->display_link_form('edit', $item_id, $row);
  6776. break;
  6777. case TOOL_LP_FINAL_ITEM:
  6778. Session::write('finalItem', true);
  6779. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6780. $sql = "SELECT lp.*, doc.path as dir
  6781. FROM $tbl_lp_item as lp
  6782. LEFT JOIN $tbl_doc as doc
  6783. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6784. WHERE
  6785. doc.c_id = $course_id AND
  6786. lp.iid = ".$item_id;
  6787. $res_step = Database::query($sql);
  6788. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6789. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6790. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6791. break;
  6792. case TOOL_QUIZ:
  6793. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6794. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6795. break;
  6796. case TOOL_HOTPOTATOES:
  6797. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6798. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6799. break;
  6800. case TOOL_STUDENTPUBLICATION:
  6801. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6802. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6803. break;
  6804. case TOOL_FORUM:
  6805. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6806. $return .= $this->display_forum_form('edit', $item_id, $row);
  6807. break;
  6808. case TOOL_THREAD:
  6809. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6810. $return .= $this->display_thread_form('edit', $item_id, $row);
  6811. break;
  6812. }
  6813. return $return;
  6814. }
  6815. /**
  6816. * Function that displays a list with al the resources that
  6817. * could be added to the learning path.
  6818. *
  6819. * @throws Exception
  6820. * @throws HTML_QuickForm_Error
  6821. *
  6822. * @return bool
  6823. */
  6824. public function display_resources()
  6825. {
  6826. $course_code = api_get_course_id();
  6827. // Get all the docs.
  6828. $documents = $this->get_documents(true);
  6829. // Get all the exercises.
  6830. $exercises = $this->get_exercises();
  6831. // Get all the links.
  6832. $links = $this->get_links();
  6833. // Get all the student publications.
  6834. $works = $this->get_student_publications();
  6835. // Get all the forums.
  6836. $forums = $this->get_forums(null, $course_code);
  6837. // Get the final item form (see BT#11048) .
  6838. $finish = $this->getFinalItemForm();
  6839. $headers = [
  6840. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6841. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6842. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6843. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6844. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6845. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6846. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6847. ];
  6848. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6849. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6850. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  6851. echo Display::tabs(
  6852. $headers,
  6853. [
  6854. $documents,
  6855. $exercises,
  6856. $links,
  6857. $works,
  6858. $forums,
  6859. $dir,
  6860. $finish,
  6861. ],
  6862. 'resource_tab',
  6863. [],
  6864. [],
  6865. $selected
  6866. );
  6867. return true;
  6868. }
  6869. /**
  6870. * Returns the extension of a document.
  6871. *
  6872. * @param string $filename
  6873. *
  6874. * @return string Extension (part after the last dot)
  6875. */
  6876. public function get_extension($filename)
  6877. {
  6878. $explode = explode('.', $filename);
  6879. return $explode[count($explode) - 1];
  6880. }
  6881. /**
  6882. * Displays a document by id.
  6883. *
  6884. * @param int $id
  6885. * @param bool $show_title
  6886. * @param bool $iframe
  6887. * @param bool $edit_link
  6888. *
  6889. * @return string
  6890. */
  6891. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6892. {
  6893. $_course = api_get_course_info();
  6894. $course_id = api_get_course_int_id();
  6895. $id = (int) $id;
  6896. $return = '';
  6897. $table = Database::get_course_table(TABLE_DOCUMENT);
  6898. $sql_doc = "SELECT * FROM $table
  6899. WHERE c_id = $course_id AND iid = $id";
  6900. $res_doc = Database::query($sql_doc);
  6901. $row_doc = Database::fetch_array($res_doc);
  6902. // TODO: Add a path filter.
  6903. if ($iframe) {
  6904. $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>';
  6905. } else {
  6906. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6907. }
  6908. return $return;
  6909. }
  6910. /**
  6911. * Return HTML form to add/edit a quiz.
  6912. *
  6913. * @param string $action Action (add/edit)
  6914. * @param int $id Item ID if already exists
  6915. * @param mixed $extra_info Extra information (quiz ID if integer)
  6916. *
  6917. * @throws Exception
  6918. *
  6919. * @return string HTML form
  6920. */
  6921. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6922. {
  6923. $course_id = api_get_course_int_id();
  6924. $id = (int) $id;
  6925. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6926. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6927. if ($id != 0 && is_array($extra_info)) {
  6928. $item_title = $extra_info['title'];
  6929. $item_description = $extra_info['description'];
  6930. } elseif (is_numeric($extra_info)) {
  6931. $sql = "SELECT title, description
  6932. FROM $tbl_quiz
  6933. WHERE c_id = $course_id AND iid = ".$extra_info;
  6934. $result = Database::query($sql);
  6935. $row = Database::fetch_array($result);
  6936. $item_title = $row['title'];
  6937. $item_description = $row['description'];
  6938. } else {
  6939. $item_title = '';
  6940. $item_description = '';
  6941. }
  6942. $item_title = Security::remove_XSS($item_title);
  6943. $item_description = Security::remove_XSS($item_description);
  6944. $parent = 0;
  6945. if ($id != 0 && is_array($extra_info)) {
  6946. $parent = $extra_info['parent_item_id'];
  6947. }
  6948. $sql = "SELECT * FROM $tbl_lp_item
  6949. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6950. $result = Database::query($sql);
  6951. $arrLP = [];
  6952. while ($row = Database::fetch_array($result)) {
  6953. $arrLP[] = [
  6954. 'id' => $row['iid'],
  6955. 'item_type' => $row['item_type'],
  6956. 'title' => $row['title'],
  6957. 'path' => $row['path'],
  6958. 'description' => $row['description'],
  6959. 'parent_item_id' => $row['parent_item_id'],
  6960. 'previous_item_id' => $row['previous_item_id'],
  6961. 'next_item_id' => $row['next_item_id'],
  6962. 'display_order' => $row['display_order'],
  6963. 'max_score' => $row['max_score'],
  6964. 'min_score' => $row['min_score'],
  6965. 'mastery_score' => $row['mastery_score'],
  6966. 'prerequisite' => $row['prerequisite'],
  6967. 'max_time_allowed' => $row['max_time_allowed'],
  6968. ];
  6969. }
  6970. $this->tree_array($arrLP);
  6971. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6972. unset($this->arrMenu);
  6973. $form = new FormValidator(
  6974. 'quiz_form',
  6975. 'POST',
  6976. $this->getCurrentBuildingModeURL()
  6977. );
  6978. $defaults = [];
  6979. if ($action === 'add') {
  6980. $legend = get_lang('CreateTheExercise');
  6981. } elseif ($action === 'move') {
  6982. $legend = get_lang('MoveTheCurrentExercise');
  6983. } else {
  6984. $legend = get_lang('EditCurrentExecice');
  6985. }
  6986. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6987. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6988. }
  6989. $form->addHeader($legend);
  6990. if ($action != 'move') {
  6991. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  6992. $defaults['title'] = $item_title;
  6993. }
  6994. // Select for Parent item, root or chapter
  6995. $selectParent = $form->addSelect(
  6996. 'parent',
  6997. get_lang('Parent'),
  6998. [],
  6999. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7000. );
  7001. $selectParent->addOption($this->name, 0);
  7002. $arrHide = [
  7003. $id,
  7004. ];
  7005. for ($i = 0; $i < count($arrLP); $i++) {
  7006. if ($action != 'add') {
  7007. if (
  7008. ($arrLP[$i]['item_type'] == 'dir') &&
  7009. !in_array($arrLP[$i]['id'], $arrHide) &&
  7010. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7011. ) {
  7012. $selectParent->addOption(
  7013. $arrLP[$i]['title'],
  7014. $arrLP[$i]['id'],
  7015. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7016. );
  7017. if ($parent == $arrLP[$i]['id']) {
  7018. $selectParent->setSelected($arrLP[$i]['id']);
  7019. }
  7020. } else {
  7021. $arrHide[] = $arrLP[$i]['id'];
  7022. }
  7023. } else {
  7024. if ($arrLP[$i]['item_type'] == 'dir') {
  7025. $selectParent->addOption(
  7026. $arrLP[$i]['title'],
  7027. $arrLP[$i]['id'],
  7028. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7029. );
  7030. if ($parent == $arrLP[$i]['id']) {
  7031. $selectParent->setSelected($arrLP[$i]['id']);
  7032. }
  7033. }
  7034. }
  7035. }
  7036. if (is_array($arrLP)) {
  7037. reset($arrLP);
  7038. }
  7039. $selectPrevious = $form->addSelect(
  7040. 'previous',
  7041. get_lang('Position'),
  7042. [],
  7043. ['id' => 'previous']
  7044. );
  7045. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7046. for ($i = 0; $i < count($arrLP); $i++) {
  7047. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7048. $arrLP[$i]['id'] != $id
  7049. ) {
  7050. $selectPrevious->addOption(
  7051. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7052. $arrLP[$i]['id']
  7053. );
  7054. if (is_array($extra_info)) {
  7055. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7056. $selectPrevious->setSelected($arrLP[$i]['id']);
  7057. }
  7058. } elseif ($action == 'add') {
  7059. $selectPrevious->setSelected($arrLP[$i]['id']);
  7060. }
  7061. }
  7062. }
  7063. if ($action != 'move') {
  7064. $arrHide = [];
  7065. for ($i = 0; $i < count($arrLP); $i++) {
  7066. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7067. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7068. }
  7069. }
  7070. }
  7071. if ($action == 'add') {
  7072. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7073. } else {
  7074. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7075. }
  7076. if ($action == 'move') {
  7077. $form->addHidden('title', $item_title);
  7078. $form->addHidden('description', $item_description);
  7079. }
  7080. if (is_numeric($extra_info)) {
  7081. $form->addHidden('path', $extra_info);
  7082. } elseif (is_array($extra_info)) {
  7083. $form->addHidden('path', $extra_info['path']);
  7084. }
  7085. $form->addHidden('type', TOOL_QUIZ);
  7086. $form->addHidden('post_time', time());
  7087. $form->setDefaults($defaults);
  7088. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7089. }
  7090. /**
  7091. * Addition of Hotpotatoes tests.
  7092. *
  7093. * @param string $action
  7094. * @param int $id Internal ID of the item
  7095. * @param string $extra_info
  7096. *
  7097. * @return string HTML structure to display the hotpotatoes addition formular
  7098. */
  7099. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7100. {
  7101. $course_id = api_get_course_int_id();
  7102. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7103. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7104. if ($id != 0 && is_array($extra_info)) {
  7105. $item_title = stripslashes($extra_info['title']);
  7106. $item_description = stripslashes($extra_info['description']);
  7107. } elseif (is_numeric($extra_info)) {
  7108. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7109. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7110. WHERE
  7111. c_id = ".$course_id." AND
  7112. path LIKE '".$uploadPath."/%/%htm%' AND
  7113. iid = ".(int) $extra_info."
  7114. ORDER BY iid ASC";
  7115. $res_hot = Database::query($sql);
  7116. $row = Database::fetch_array($res_hot);
  7117. $item_title = $row['title'];
  7118. $item_description = $row['description'];
  7119. if (!empty($row['comment'])) {
  7120. $item_title = $row['comment'];
  7121. }
  7122. } else {
  7123. $item_title = '';
  7124. $item_description = '';
  7125. }
  7126. if ($id != 0 && is_array($extra_info)) {
  7127. $parent = $extra_info['parent_item_id'];
  7128. } else {
  7129. $parent = 0;
  7130. }
  7131. $sql = "SELECT * FROM $tbl_lp_item
  7132. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7133. $result = Database::query($sql);
  7134. $arrLP = [];
  7135. while ($row = Database::fetch_array($result)) {
  7136. $arrLP[] = [
  7137. 'id' => $row['id'],
  7138. 'item_type' => $row['item_type'],
  7139. 'title' => $row['title'],
  7140. 'path' => $row['path'],
  7141. 'description' => $row['description'],
  7142. 'parent_item_id' => $row['parent_item_id'],
  7143. 'previous_item_id' => $row['previous_item_id'],
  7144. 'next_item_id' => $row['next_item_id'],
  7145. 'display_order' => $row['display_order'],
  7146. 'max_score' => $row['max_score'],
  7147. 'min_score' => $row['min_score'],
  7148. 'mastery_score' => $row['mastery_score'],
  7149. 'prerequisite' => $row['prerequisite'],
  7150. 'max_time_allowed' => $row['max_time_allowed'],
  7151. ];
  7152. }
  7153. $legend = '<legend>';
  7154. if ($action == 'add') {
  7155. $legend .= get_lang('CreateTheExercise');
  7156. } elseif ($action == 'move') {
  7157. $legend .= get_lang('MoveTheCurrentExercise');
  7158. } else {
  7159. $legend .= get_lang('EditCurrentExecice');
  7160. }
  7161. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7162. $legend .= Display:: return_message(
  7163. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7164. );
  7165. }
  7166. $legend .= '</legend>';
  7167. $return = '<form method="POST">';
  7168. $return .= $legend;
  7169. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7170. $return .= '<tr>';
  7171. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7172. $return .= '<td class="input">';
  7173. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7174. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7175. $arrHide = [
  7176. $id,
  7177. ];
  7178. if (count($arrLP) > 0) {
  7179. for ($i = 0; $i < count($arrLP); $i++) {
  7180. if ($action != 'add') {
  7181. if ($arrLP[$i]['item_type'] == 'dir' &&
  7182. !in_array($arrLP[$i]['id'], $arrHide) &&
  7183. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7184. ) {
  7185. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7186. } else {
  7187. $arrHide[] = $arrLP[$i]['id'];
  7188. }
  7189. } else {
  7190. if ($arrLP[$i]['item_type'] == 'dir') {
  7191. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7192. }
  7193. }
  7194. }
  7195. reset($arrLP);
  7196. }
  7197. $return .= '</select>';
  7198. $return .= '</td>';
  7199. $return .= '</tr>';
  7200. $return .= '<tr>';
  7201. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7202. $return .= '<td class="input">';
  7203. $return .= '<select id="previous" name="previous" size="1">';
  7204. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7205. for ($i = 0; $i < count($arrLP); $i++) {
  7206. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7207. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7208. $selected = 'selected="selected" ';
  7209. } elseif ($action == 'add') {
  7210. $selected = 'selected="selected" ';
  7211. } else {
  7212. $selected = '';
  7213. }
  7214. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7215. }
  7216. }
  7217. $return .= '</select>';
  7218. $return .= '</td>';
  7219. $return .= '</tr>';
  7220. if ($action != 'move') {
  7221. $return .= '<tr>';
  7222. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7223. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7224. $return .= '</tr>';
  7225. $id_prerequisite = 0;
  7226. if (is_array($arrLP) && count($arrLP) > 0) {
  7227. foreach ($arrLP as $key => $value) {
  7228. if ($value['id'] == $id) {
  7229. $id_prerequisite = $value['prerequisite'];
  7230. break;
  7231. }
  7232. }
  7233. $arrHide = [];
  7234. for ($i = 0; $i < count($arrLP); $i++) {
  7235. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7236. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7237. }
  7238. }
  7239. }
  7240. }
  7241. $return .= '<tr>';
  7242. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7243. get_lang('SaveHotpotatoes').'</button></td>';
  7244. $return .= '</tr>';
  7245. $return .= '</table>';
  7246. if ($action == 'move') {
  7247. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7248. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7249. }
  7250. if (is_numeric($extra_info)) {
  7251. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7252. } elseif (is_array($extra_info)) {
  7253. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7254. }
  7255. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7256. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7257. $return .= '</form>';
  7258. return $return;
  7259. }
  7260. /**
  7261. * Return the form to display the forum edit/add option.
  7262. *
  7263. * @param string $action
  7264. * @param int $id ID of the lp_item if already exists
  7265. * @param string $extra_info
  7266. *
  7267. * @throws Exception
  7268. *
  7269. * @return string HTML form
  7270. */
  7271. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7272. {
  7273. $course_id = api_get_course_int_id();
  7274. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7275. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7276. if ($id != 0 && is_array($extra_info)) {
  7277. $item_title = stripslashes($extra_info['title']);
  7278. } elseif (is_numeric($extra_info)) {
  7279. $sql = "SELECT forum_title as title, forum_comment as comment
  7280. FROM $tbl_forum
  7281. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7282. $result = Database::query($sql);
  7283. $row = Database::fetch_array($result);
  7284. $item_title = $row['title'];
  7285. $item_description = $row['comment'];
  7286. } else {
  7287. $item_title = '';
  7288. $item_description = '';
  7289. }
  7290. if ($id != 0 && is_array($extra_info)) {
  7291. $parent = $extra_info['parent_item_id'];
  7292. } else {
  7293. $parent = 0;
  7294. }
  7295. $sql = "SELECT * FROM $tbl_lp_item
  7296. WHERE
  7297. c_id = $course_id AND
  7298. lp_id = ".$this->lp_id;
  7299. $result = Database::query($sql);
  7300. $arrLP = [];
  7301. while ($row = Database::fetch_array($result)) {
  7302. $arrLP[] = [
  7303. 'id' => $row['iid'],
  7304. 'item_type' => $row['item_type'],
  7305. 'title' => $row['title'],
  7306. 'path' => $row['path'],
  7307. 'description' => $row['description'],
  7308. 'parent_item_id' => $row['parent_item_id'],
  7309. 'previous_item_id' => $row['previous_item_id'],
  7310. 'next_item_id' => $row['next_item_id'],
  7311. 'display_order' => $row['display_order'],
  7312. 'max_score' => $row['max_score'],
  7313. 'min_score' => $row['min_score'],
  7314. 'mastery_score' => $row['mastery_score'],
  7315. 'prerequisite' => $row['prerequisite'],
  7316. ];
  7317. }
  7318. $this->tree_array($arrLP);
  7319. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7320. unset($this->arrMenu);
  7321. if ($action == 'add') {
  7322. $legend = get_lang('CreateTheForum');
  7323. } elseif ($action == 'move') {
  7324. $legend = get_lang('MoveTheCurrentForum');
  7325. } else {
  7326. $legend = get_lang('EditCurrentForum');
  7327. }
  7328. $form = new FormValidator(
  7329. 'forum_form',
  7330. 'POST',
  7331. $this->getCurrentBuildingModeURL()
  7332. );
  7333. $defaults = [];
  7334. $form->addHeader($legend);
  7335. if ($action != 'move') {
  7336. $form->addText(
  7337. 'title',
  7338. get_lang('Title'),
  7339. true,
  7340. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7341. );
  7342. $defaults['title'] = $item_title;
  7343. }
  7344. $selectParent = $form->addSelect(
  7345. 'parent',
  7346. get_lang('Parent'),
  7347. [],
  7348. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7349. );
  7350. $selectParent->addOption($this->name, 0);
  7351. $arrHide = [
  7352. $id,
  7353. ];
  7354. for ($i = 0; $i < count($arrLP); $i++) {
  7355. if ($action != 'add') {
  7356. if ($arrLP[$i]['item_type'] == 'dir' &&
  7357. !in_array($arrLP[$i]['id'], $arrHide) &&
  7358. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7359. ) {
  7360. $selectParent->addOption(
  7361. $arrLP[$i]['title'],
  7362. $arrLP[$i]['id'],
  7363. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7364. );
  7365. if ($parent == $arrLP[$i]['id']) {
  7366. $selectParent->setSelected($arrLP[$i]['id']);
  7367. }
  7368. } else {
  7369. $arrHide[] = $arrLP[$i]['id'];
  7370. }
  7371. } else {
  7372. if ($arrLP[$i]['item_type'] == 'dir') {
  7373. $selectParent->addOption(
  7374. $arrLP[$i]['title'],
  7375. $arrLP[$i]['id'],
  7376. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7377. );
  7378. if ($parent == $arrLP[$i]['id']) {
  7379. $selectParent->setSelected($arrLP[$i]['id']);
  7380. }
  7381. }
  7382. }
  7383. }
  7384. if (is_array($arrLP)) {
  7385. reset($arrLP);
  7386. }
  7387. $selectPrevious = $form->addSelect(
  7388. 'previous',
  7389. get_lang('Position'),
  7390. [],
  7391. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7392. );
  7393. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7394. for ($i = 0; $i < count($arrLP); $i++) {
  7395. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7396. $arrLP[$i]['id'] != $id
  7397. ) {
  7398. $selectPrevious->addOption(
  7399. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7400. $arrLP[$i]['id']
  7401. );
  7402. if (isset($extra_info['previous_item_id']) &&
  7403. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7404. ) {
  7405. $selectPrevious->setSelected($arrLP[$i]['id']);
  7406. } elseif ($action == 'add') {
  7407. $selectPrevious->setSelected($arrLP[$i]['id']);
  7408. }
  7409. }
  7410. }
  7411. if ($action != 'move') {
  7412. $id_prerequisite = 0;
  7413. if (is_array($arrLP)) {
  7414. foreach ($arrLP as $key => $value) {
  7415. if ($value['id'] == $id) {
  7416. $id_prerequisite = $value['prerequisite'];
  7417. break;
  7418. }
  7419. }
  7420. }
  7421. $arrHide = [];
  7422. for ($i = 0; $i < count($arrLP); $i++) {
  7423. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7424. if (isset($extra_info['previous_item_id']) &&
  7425. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7426. ) {
  7427. $s_selected_position = $arrLP[$i]['id'];
  7428. } elseif ($action == 'add') {
  7429. $s_selected_position = 0;
  7430. }
  7431. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7432. }
  7433. }
  7434. }
  7435. if ($action == 'add') {
  7436. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7437. } else {
  7438. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7439. }
  7440. if ($action == 'move') {
  7441. $form->addHidden('title', $item_title);
  7442. $form->addHidden('description', $item_description);
  7443. }
  7444. if (is_numeric($extra_info)) {
  7445. $form->addHidden('path', $extra_info);
  7446. } elseif (is_array($extra_info)) {
  7447. $form->addHidden('path', $extra_info['path']);
  7448. }
  7449. $form->addHidden('type', TOOL_FORUM);
  7450. $form->addHidden('post_time', time());
  7451. $form->setDefaults($defaults);
  7452. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7453. }
  7454. /**
  7455. * Return HTML form to add/edit forum threads.
  7456. *
  7457. * @param string $action
  7458. * @param int $id Item ID if already exists in learning path
  7459. * @param string $extra_info
  7460. *
  7461. * @throws Exception
  7462. *
  7463. * @return string HTML form
  7464. */
  7465. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7466. {
  7467. $course_id = api_get_course_int_id();
  7468. if (empty($course_id)) {
  7469. return null;
  7470. }
  7471. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7472. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7473. if ($id != 0 && is_array($extra_info)) {
  7474. $item_title = stripslashes($extra_info['title']);
  7475. } elseif (is_numeric($extra_info)) {
  7476. $sql = "SELECT thread_title as title FROM $tbl_forum
  7477. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7478. $result = Database::query($sql);
  7479. $row = Database::fetch_array($result);
  7480. $item_title = $row['title'];
  7481. $item_description = '';
  7482. } else {
  7483. $item_title = '';
  7484. $item_description = '';
  7485. }
  7486. if ($id != 0 && is_array($extra_info)) {
  7487. $parent = $extra_info['parent_item_id'];
  7488. } else {
  7489. $parent = 0;
  7490. }
  7491. $sql = "SELECT * FROM $tbl_lp_item
  7492. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7493. $result = Database::query($sql);
  7494. $arrLP = [];
  7495. while ($row = Database::fetch_array($result)) {
  7496. $arrLP[] = [
  7497. 'id' => $row['iid'],
  7498. 'item_type' => $row['item_type'],
  7499. 'title' => $row['title'],
  7500. 'path' => $row['path'],
  7501. 'description' => $row['description'],
  7502. 'parent_item_id' => $row['parent_item_id'],
  7503. 'previous_item_id' => $row['previous_item_id'],
  7504. 'next_item_id' => $row['next_item_id'],
  7505. 'display_order' => $row['display_order'],
  7506. 'max_score' => $row['max_score'],
  7507. 'min_score' => $row['min_score'],
  7508. 'mastery_score' => $row['mastery_score'],
  7509. 'prerequisite' => $row['prerequisite'],
  7510. ];
  7511. }
  7512. $this->tree_array($arrLP);
  7513. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7514. unset($this->arrMenu);
  7515. $form = new FormValidator(
  7516. 'thread_form',
  7517. 'POST',
  7518. $this->getCurrentBuildingModeURL()
  7519. );
  7520. $defaults = [];
  7521. if ($action == 'add') {
  7522. $legend = get_lang('CreateTheForum');
  7523. } elseif ($action == 'move') {
  7524. $legend = get_lang('MoveTheCurrentForum');
  7525. } else {
  7526. $legend = get_lang('EditCurrentForum');
  7527. }
  7528. $form->addHeader($legend);
  7529. $selectParent = $form->addSelect(
  7530. 'parent',
  7531. get_lang('Parent'),
  7532. [],
  7533. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7534. );
  7535. $selectParent->addOption($this->name, 0);
  7536. $arrHide = [
  7537. $id,
  7538. ];
  7539. for ($i = 0; $i < count($arrLP); $i++) {
  7540. if ($action != 'add') {
  7541. if (
  7542. ($arrLP[$i]['item_type'] == 'dir') &&
  7543. !in_array($arrLP[$i]['id'], $arrHide) &&
  7544. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7545. ) {
  7546. $selectParent->addOption(
  7547. $arrLP[$i]['title'],
  7548. $arrLP[$i]['id'],
  7549. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7550. );
  7551. if ($parent == $arrLP[$i]['id']) {
  7552. $selectParent->setSelected($arrLP[$i]['id']);
  7553. }
  7554. } else {
  7555. $arrHide[] = $arrLP[$i]['id'];
  7556. }
  7557. } else {
  7558. if ($arrLP[$i]['item_type'] == 'dir') {
  7559. $selectParent->addOption(
  7560. $arrLP[$i]['title'],
  7561. $arrLP[$i]['id'],
  7562. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7563. );
  7564. if ($parent == $arrLP[$i]['id']) {
  7565. $selectParent->setSelected($arrLP[$i]['id']);
  7566. }
  7567. }
  7568. }
  7569. }
  7570. if ($arrLP != null) {
  7571. reset($arrLP);
  7572. }
  7573. $selectPrevious = $form->addSelect(
  7574. 'previous',
  7575. get_lang('Position'),
  7576. [],
  7577. ['id' => 'previous']
  7578. );
  7579. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7580. for ($i = 0; $i < count($arrLP); $i++) {
  7581. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7582. $selectPrevious->addOption(
  7583. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7584. $arrLP[$i]['id']
  7585. );
  7586. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7587. $selectPrevious->setSelected($arrLP[$i]['id']);
  7588. } elseif ($action == 'add') {
  7589. $selectPrevious->setSelected($arrLP[$i]['id']);
  7590. }
  7591. }
  7592. }
  7593. if ($action != 'move') {
  7594. $form->addText(
  7595. 'title',
  7596. get_lang('Title'),
  7597. true,
  7598. ['id' => 'idTitle']
  7599. );
  7600. $defaults['title'] = $item_title;
  7601. $id_prerequisite = 0;
  7602. if ($arrLP != null) {
  7603. foreach ($arrLP as $key => $value) {
  7604. if ($value['id'] == $id) {
  7605. $id_prerequisite = $value['prerequisite'];
  7606. break;
  7607. }
  7608. }
  7609. }
  7610. $arrHide = [];
  7611. $s_selected_position = 0;
  7612. for ($i = 0; $i < count($arrLP); $i++) {
  7613. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7614. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7615. $s_selected_position = $arrLP[$i]['id'];
  7616. } elseif ($action == 'add') {
  7617. $s_selected_position = 0;
  7618. }
  7619. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7620. }
  7621. }
  7622. $selectPrerequisites = $form->addSelect(
  7623. 'prerequisites',
  7624. get_lang('LearnpathPrerequisites'),
  7625. [],
  7626. ['id' => 'prerequisites']
  7627. );
  7628. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7629. foreach ($arrHide as $key => $value) {
  7630. $selectPrerequisites->addOption($value['value'], $key);
  7631. if ($key == $s_selected_position && $action == 'add') {
  7632. $selectPrerequisites->setSelected($key);
  7633. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7634. $selectPrerequisites->setSelected($key);
  7635. }
  7636. }
  7637. }
  7638. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7639. if ($action == 'move') {
  7640. $form->addHidden('title', $item_title);
  7641. $form->addHidden('description', $item_description);
  7642. }
  7643. if (is_numeric($extra_info)) {
  7644. $form->addHidden('path', $extra_info);
  7645. } elseif (is_array($extra_info)) {
  7646. $form->addHidden('path', $extra_info['path']);
  7647. }
  7648. $form->addHidden('type', TOOL_THREAD);
  7649. $form->addHidden('post_time', time());
  7650. $form->setDefaults($defaults);
  7651. return $form->returnForm();
  7652. }
  7653. /**
  7654. * Return the HTML form to display an item (generally a dir item).
  7655. *
  7656. * @param string $item_type
  7657. * @param string $title
  7658. * @param string $action
  7659. * @param int $id
  7660. * @param string $extra_info
  7661. *
  7662. * @throws Exception
  7663. * @throws HTML_QuickForm_Error
  7664. *
  7665. * @return string HTML form
  7666. */
  7667. public function display_item_form(
  7668. $item_type,
  7669. $title = '',
  7670. $action = 'add_item',
  7671. $id = 0,
  7672. $extra_info = 'new'
  7673. ) {
  7674. $_course = api_get_course_info();
  7675. global $charset;
  7676. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7677. $item_title = '';
  7678. $item_description = '';
  7679. $item_path_fck = '';
  7680. if ($id != 0 && is_array($extra_info)) {
  7681. $item_title = $extra_info['title'];
  7682. $item_description = $extra_info['description'];
  7683. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7684. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7685. }
  7686. $parent = 0;
  7687. if ($id != 0 && is_array($extra_info)) {
  7688. $parent = $extra_info['parent_item_id'];
  7689. }
  7690. $id = (int) $id;
  7691. $sql = "SELECT * FROM $tbl_lp_item
  7692. WHERE
  7693. lp_id = ".$this->lp_id." AND
  7694. iid != $id";
  7695. if ($item_type == 'dir') {
  7696. $sql .= " AND parent_item_id = 0";
  7697. }
  7698. $result = Database::query($sql);
  7699. $arrLP = [];
  7700. while ($row = Database::fetch_array($result)) {
  7701. $arrLP[] = [
  7702. 'id' => $row['iid'],
  7703. 'item_type' => $row['item_type'],
  7704. 'title' => $row['title'],
  7705. 'path' => $row['path'],
  7706. 'description' => $row['description'],
  7707. 'parent_item_id' => $row['parent_item_id'],
  7708. 'previous_item_id' => $row['previous_item_id'],
  7709. 'next_item_id' => $row['next_item_id'],
  7710. 'max_score' => $row['max_score'],
  7711. 'min_score' => $row['min_score'],
  7712. 'mastery_score' => $row['mastery_score'],
  7713. 'prerequisite' => $row['prerequisite'],
  7714. 'display_order' => $row['display_order'],
  7715. ];
  7716. }
  7717. $this->tree_array($arrLP);
  7718. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7719. unset($this->arrMenu);
  7720. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7721. $form = new FormValidator('form', 'POST', $url);
  7722. $defaults['title'] = api_html_entity_decode(
  7723. $item_title,
  7724. ENT_QUOTES,
  7725. $charset
  7726. );
  7727. $defaults['description'] = $item_description;
  7728. $form->addHeader($title);
  7729. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7730. $arrHide[0]['padding'] = 20;
  7731. $charset = api_get_system_encoding();
  7732. for ($i = 0; $i < count($arrLP); $i++) {
  7733. if ($action != 'add') {
  7734. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7735. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7736. ) {
  7737. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7738. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7739. if ($parent == $arrLP[$i]['id']) {
  7740. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7741. }
  7742. }
  7743. } else {
  7744. if ($arrLP[$i]['item_type'] == 'dir') {
  7745. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7746. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7747. if ($parent == $arrLP[$i]['id']) {
  7748. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7749. }
  7750. }
  7751. }
  7752. }
  7753. if ($action != 'move') {
  7754. $form->addElement('text', 'title', get_lang('Title'));
  7755. $form->applyFilter('title', 'html_filter');
  7756. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7757. } else {
  7758. $form->addElement('hidden', 'title');
  7759. }
  7760. $parentSelect = $form->addElement(
  7761. 'select',
  7762. 'parent',
  7763. get_lang('Parent'),
  7764. '',
  7765. [
  7766. 'id' => 'idParent',
  7767. 'onchange' => "javascript: load_cbo(this.value);",
  7768. ]
  7769. );
  7770. foreach ($arrHide as $key => $value) {
  7771. $parentSelect->addOption(
  7772. $value['value'],
  7773. $key,
  7774. 'style="padding-left:'.$value['padding'].'px;"'
  7775. );
  7776. $lastPosition = $key;
  7777. }
  7778. if (!empty($s_selected_parent)) {
  7779. $parentSelect->setSelected($s_selected_parent);
  7780. }
  7781. if (is_array($arrLP)) {
  7782. reset($arrLP);
  7783. }
  7784. $arrHide = [];
  7785. // POSITION
  7786. for ($i = 0; $i < count($arrLP); $i++) {
  7787. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7788. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7789. //this is the same!
  7790. if (isset($extra_info['previous_item_id']) &&
  7791. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7792. ) {
  7793. $s_selected_position = $arrLP[$i]['id'];
  7794. } elseif ($action == 'add') {
  7795. $s_selected_position = $arrLP[$i]['id'];
  7796. }
  7797. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7798. }
  7799. }
  7800. $position = $form->addElement(
  7801. 'select',
  7802. 'previous',
  7803. get_lang('Position'),
  7804. '',
  7805. ['id' => 'previous']
  7806. );
  7807. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7808. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7809. $lastPosition = null;
  7810. foreach ($arrHide as $key => $value) {
  7811. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7812. $lastPosition = $key;
  7813. }
  7814. if (!empty($s_selected_position)) {
  7815. $position->setSelected($s_selected_position);
  7816. }
  7817. // When new chapter add at the end
  7818. if ($action == 'add_item') {
  7819. $position->setSelected($lastPosition);
  7820. }
  7821. if (is_array($arrLP)) {
  7822. reset($arrLP);
  7823. }
  7824. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7825. //fix in order to use the tab
  7826. if ($item_type == 'dir') {
  7827. $form->addElement('hidden', 'type', 'dir');
  7828. }
  7829. $extension = null;
  7830. if (!empty($item_path)) {
  7831. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7832. }
  7833. //assets can't be modified
  7834. //$item_type == 'asset' ||
  7835. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7836. if ($item_type == 'sco') {
  7837. $form->addElement(
  7838. 'html',
  7839. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7840. );
  7841. }
  7842. $renderer = $form->defaultRenderer();
  7843. $renderer->setElementTemplate(
  7844. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7845. 'content_lp'
  7846. );
  7847. $relative_prefix = '';
  7848. $editor_config = [
  7849. 'ToolbarSet' => 'LearningPathDocuments',
  7850. 'Width' => '100%',
  7851. 'Height' => '500',
  7852. 'FullPage' => true,
  7853. 'CreateDocumentDir' => $relative_prefix,
  7854. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7855. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7856. ];
  7857. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7858. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7859. $defaults['content_lp'] = file_get_contents($content_path);
  7860. }
  7861. if (!empty($id)) {
  7862. $form->addHidden('id', $id);
  7863. }
  7864. $form->addElement('hidden', 'type', $item_type);
  7865. $form->addElement('hidden', 'post_time', time());
  7866. $form->setDefaults($defaults);
  7867. return $form->returnForm();
  7868. }
  7869. /**
  7870. * @return string
  7871. */
  7872. public function getCurrentBuildingModeURL()
  7873. {
  7874. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7875. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7876. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7877. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7878. $currentUrl = api_get_self().'?'.api_get_cidreq().
  7879. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7880. return $currentUrl;
  7881. }
  7882. /**
  7883. * Returns the form to update or create a document.
  7884. *
  7885. * @param string $action (add/edit)
  7886. * @param int $id ID of the lp_item (if already exists)
  7887. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7888. *
  7889. * @throws Exception
  7890. * @throws HTML_QuickForm_Error
  7891. *
  7892. * @return string HTML form
  7893. */
  7894. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7895. {
  7896. $course_id = api_get_course_int_id();
  7897. $_course = api_get_course_info();
  7898. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7899. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7900. $no_display_edit_textarea = false;
  7901. $item_description = '';
  7902. //If action==edit document
  7903. //We don't display the document form if it's not an editable document (html or txt file)
  7904. if ($action === 'edit') {
  7905. if (is_array($extra_info)) {
  7906. $path_parts = pathinfo($extra_info['dir']);
  7907. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7908. $no_display_edit_textarea = true;
  7909. }
  7910. }
  7911. }
  7912. $no_display_add = false;
  7913. // If action==add an existing document
  7914. // We don't display the document form if it's not an editable document (html or txt file).
  7915. if ($action === 'add') {
  7916. if (is_numeric($extra_info)) {
  7917. $extra_info = (int) $extra_info;
  7918. $sql_doc = "SELECT path FROM $tbl_doc
  7919. WHERE c_id = $course_id AND iid = ".$extra_info;
  7920. $result = Database::query($sql_doc);
  7921. $path_file = Database::result($result, 0, 0);
  7922. $path_parts = pathinfo($path_file);
  7923. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7924. $no_display_add = true;
  7925. }
  7926. }
  7927. }
  7928. if ($id != 0 && is_array($extra_info)) {
  7929. $item_title = stripslashes($extra_info['title']);
  7930. $item_description = stripslashes($extra_info['description']);
  7931. if (empty($item_title)) {
  7932. $path_parts = pathinfo($extra_info['path']);
  7933. $item_title = stripslashes($path_parts['filename']);
  7934. }
  7935. } elseif (is_numeric($extra_info)) {
  7936. $sql = "SELECT path, title FROM $tbl_doc
  7937. WHERE
  7938. c_id = ".$course_id." AND
  7939. iid = ".intval($extra_info);
  7940. $result = Database::query($sql);
  7941. $row = Database::fetch_array($result);
  7942. $item_title = $row['title'];
  7943. $item_title = str_replace('_', ' ', $item_title);
  7944. if (empty($item_title)) {
  7945. $path_parts = pathinfo($row['path']);
  7946. $item_title = stripslashes($path_parts['filename']);
  7947. }
  7948. } else {
  7949. $item_title = '';
  7950. $item_description = '';
  7951. }
  7952. $return = '<legend>';
  7953. $parent = 0;
  7954. if ($id != 0 && is_array($extra_info)) {
  7955. $parent = $extra_info['parent_item_id'];
  7956. }
  7957. $sql = "SELECT * FROM $tbl_lp_item
  7958. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7959. $result = Database::query($sql);
  7960. $arrLP = [];
  7961. while ($row = Database::fetch_array($result)) {
  7962. $arrLP[] = [
  7963. 'id' => $row['iid'],
  7964. 'item_type' => $row['item_type'],
  7965. 'title' => $row['title'],
  7966. 'path' => $row['path'],
  7967. 'description' => $row['description'],
  7968. 'parent_item_id' => $row['parent_item_id'],
  7969. 'previous_item_id' => $row['previous_item_id'],
  7970. 'next_item_id' => $row['next_item_id'],
  7971. 'display_order' => $row['display_order'],
  7972. 'max_score' => $row['max_score'],
  7973. 'min_score' => $row['min_score'],
  7974. 'mastery_score' => $row['mastery_score'],
  7975. 'prerequisite' => $row['prerequisite'],
  7976. ];
  7977. }
  7978. $this->tree_array($arrLP);
  7979. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7980. unset($this->arrMenu);
  7981. if ($action == 'add') {
  7982. $return .= get_lang('CreateTheDocument');
  7983. } elseif ($action == 'move') {
  7984. $return .= get_lang('MoveTheCurrentDocument');
  7985. } else {
  7986. $return .= get_lang('EditTheCurrentDocument');
  7987. }
  7988. $return .= '</legend>';
  7989. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7990. $return .= Display::return_message(
  7991. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7992. false
  7993. );
  7994. }
  7995. $form = new FormValidator(
  7996. 'form',
  7997. 'POST',
  7998. $this->getCurrentBuildingModeURL(),
  7999. '',
  8000. ['enctype' => 'multipart/form-data']
  8001. );
  8002. $defaults['title'] = Security::remove_XSS($item_title);
  8003. if (empty($item_title)) {
  8004. $defaults['title'] = Security::remove_XSS($item_title);
  8005. }
  8006. $defaults['description'] = $item_description;
  8007. $form->addElement('html', $return);
  8008. if ($action != 'move') {
  8009. $data = $this->generate_lp_folder($_course);
  8010. if ($action != 'edit') {
  8011. $folders = DocumentManager::get_all_document_folders(
  8012. $_course,
  8013. 0,
  8014. true
  8015. );
  8016. DocumentManager::build_directory_selector(
  8017. $folders,
  8018. '',
  8019. [],
  8020. true,
  8021. $form,
  8022. 'directory_parent_id'
  8023. );
  8024. }
  8025. if (isset($data['id'])) {
  8026. $defaults['directory_parent_id'] = $data['id'];
  8027. }
  8028. $form->addElement(
  8029. 'text',
  8030. 'title',
  8031. get_lang('Title'),
  8032. ['id' => 'idTitle', 'class' => 'col-md-4']
  8033. );
  8034. $form->applyFilter('title', 'html_filter');
  8035. }
  8036. $arrHide[0]['value'] = $this->name;
  8037. $arrHide[0]['padding'] = 20;
  8038. for ($i = 0; $i < count($arrLP); $i++) {
  8039. if ($action != 'add') {
  8040. if ($arrLP[$i]['item_type'] == 'dir' &&
  8041. !in_array($arrLP[$i]['id'], $arrHide) &&
  8042. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8043. ) {
  8044. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8045. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8046. }
  8047. } else {
  8048. if ($arrLP[$i]['item_type'] == 'dir') {
  8049. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8050. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8051. }
  8052. }
  8053. }
  8054. $parentSelect = $form->addSelect(
  8055. 'parent',
  8056. get_lang('Parent'),
  8057. [],
  8058. [
  8059. 'id' => 'idParent',
  8060. 'onchange' => 'javascript: load_cbo(this.value);',
  8061. ]
  8062. );
  8063. $my_count = 0;
  8064. foreach ($arrHide as $key => $value) {
  8065. if ($my_count != 0) {
  8066. // The LP name is also the first section and is not in the same charset like the other sections.
  8067. $value['value'] = Security::remove_XSS($value['value']);
  8068. $parentSelect->addOption(
  8069. $value['value'],
  8070. $key,
  8071. 'style="padding-left:'.$value['padding'].'px;"'
  8072. );
  8073. } else {
  8074. $value['value'] = Security::remove_XSS($value['value']);
  8075. $parentSelect->addOption(
  8076. $value['value'],
  8077. $key,
  8078. 'style="padding-left:'.$value['padding'].'px;"'
  8079. );
  8080. }
  8081. $my_count++;
  8082. }
  8083. if (!empty($id)) {
  8084. $parentSelect->setSelected($parent);
  8085. } else {
  8086. $parent_item_id = Session::read('parent_item_id', 0);
  8087. $parentSelect->setSelected($parent_item_id);
  8088. }
  8089. if (is_array($arrLP)) {
  8090. reset($arrLP);
  8091. }
  8092. $arrHide = [];
  8093. // POSITION
  8094. for ($i = 0; $i < count($arrLP); $i++) {
  8095. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8096. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8097. ) {
  8098. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8099. }
  8100. }
  8101. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8102. $position = $form->addSelect(
  8103. 'previous',
  8104. get_lang('Position'),
  8105. [],
  8106. ['id' => 'previous']
  8107. );
  8108. $position->addOption(get_lang('FirstPosition'), 0);
  8109. foreach ($arrHide as $key => $value) {
  8110. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8111. $position->addOption(
  8112. $value['value'],
  8113. $key,
  8114. 'style="padding-left:'.$padding.'px;"'
  8115. );
  8116. }
  8117. $position->setSelected($selectedPosition);
  8118. if (is_array($arrLP)) {
  8119. reset($arrLP);
  8120. }
  8121. if ($action != 'move') {
  8122. $arrHide = [];
  8123. for ($i = 0; $i < count($arrLP); $i++) {
  8124. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8125. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8126. ) {
  8127. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8128. }
  8129. }
  8130. if (!$no_display_add) {
  8131. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8132. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8133. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8134. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8135. ) {
  8136. if (isset($_POST['content'])) {
  8137. $content = stripslashes($_POST['content']);
  8138. } elseif (is_array($extra_info)) {
  8139. //If it's an html document or a text file
  8140. if (!$no_display_edit_textarea) {
  8141. $content = $this->display_document(
  8142. $extra_info['path'],
  8143. false,
  8144. false
  8145. );
  8146. }
  8147. } elseif (is_numeric($extra_info)) {
  8148. $content = $this->display_document(
  8149. $extra_info,
  8150. false,
  8151. false
  8152. );
  8153. } else {
  8154. $content = '';
  8155. }
  8156. if (!$no_display_edit_textarea) {
  8157. // We need to calculate here some specific settings for the online editor.
  8158. // The calculated settings work for documents in the Documents tool
  8159. // (on the root or in subfolders).
  8160. // For documents in native scorm packages it is unclear whether the
  8161. // online editor should be activated or not.
  8162. // A new document, it is in the root of the repository.
  8163. $relative_path = '';
  8164. $relative_prefix = '';
  8165. if (is_array($extra_info) && $extra_info != 'new') {
  8166. // The document already exists. Whe have to determine its relative path towards the repository root.
  8167. $relative_path = explode('/', $extra_info['dir']);
  8168. $cnt = count($relative_path) - 2;
  8169. if ($cnt < 0) {
  8170. $cnt = 0;
  8171. }
  8172. $relative_prefix = str_repeat('../', $cnt);
  8173. $relative_path = array_slice($relative_path, 1, $cnt);
  8174. $relative_path = implode('/', $relative_path);
  8175. if (strlen($relative_path) > 0) {
  8176. $relative_path = $relative_path.'/';
  8177. }
  8178. } else {
  8179. $result = $this->generate_lp_folder($_course);
  8180. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8181. $relative_prefix = '../../';
  8182. }
  8183. $editor_config = [
  8184. 'ToolbarSet' => 'LearningPathDocuments',
  8185. 'Width' => '100%',
  8186. 'Height' => '500',
  8187. 'FullPage' => true,
  8188. 'CreateDocumentDir' => $relative_prefix,
  8189. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8190. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8191. ];
  8192. if ($_GET['action'] == 'add_item') {
  8193. $class = 'add';
  8194. $text = get_lang('LPCreateDocument');
  8195. } else {
  8196. if ($_GET['action'] == 'edit_item') {
  8197. $class = 'save';
  8198. $text = get_lang('SaveDocument');
  8199. }
  8200. }
  8201. $form->addButtonSave($text, 'submit_button');
  8202. $renderer = $form->defaultRenderer();
  8203. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8204. $form->addElement('html', '<div class="editor-lp">');
  8205. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8206. $form->addElement('html', '</div>');
  8207. $defaults['content_lp'] = $content;
  8208. }
  8209. } elseif (is_numeric($extra_info)) {
  8210. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8211. $return = $this->display_document($extra_info, true, true, true);
  8212. $form->addElement('html', $return);
  8213. }
  8214. }
  8215. }
  8216. if (isset($extra_info['item_type']) &&
  8217. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8218. ) {
  8219. $parentSelect->freeze();
  8220. $position->freeze();
  8221. }
  8222. if ($action == 'move') {
  8223. $form->addElement('hidden', 'title', $item_title);
  8224. $form->addElement('hidden', 'description', $item_description);
  8225. }
  8226. if (is_numeric($extra_info)) {
  8227. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8228. $form->addElement('hidden', 'path', $extra_info);
  8229. } elseif (is_array($extra_info)) {
  8230. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8231. $form->addElement('hidden', 'path', $extra_info['path']);
  8232. }
  8233. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8234. $form->addElement('hidden', 'post_time', time());
  8235. $form->setDefaults($defaults);
  8236. return $form->returnForm();
  8237. }
  8238. /**
  8239. * Returns the form to update or create a read-out text.
  8240. *
  8241. * @param string $action "add" or "edit"
  8242. * @param int $id ID of the lp_item (if already exists)
  8243. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8244. *
  8245. * @throws Exception
  8246. * @throws HTML_QuickForm_Error
  8247. *
  8248. * @return string HTML form
  8249. */
  8250. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8251. {
  8252. $course_id = api_get_course_int_id();
  8253. $_course = api_get_course_info();
  8254. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8255. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8256. $no_display_edit_textarea = false;
  8257. $item_description = '';
  8258. //If action==edit document
  8259. //We don't display the document form if it's not an editable document (html or txt file)
  8260. if ($action == 'edit') {
  8261. if (is_array($extra_info)) {
  8262. $path_parts = pathinfo($extra_info['dir']);
  8263. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8264. $no_display_edit_textarea = true;
  8265. }
  8266. }
  8267. }
  8268. $no_display_add = false;
  8269. if ($id != 0 && is_array($extra_info)) {
  8270. $item_title = stripslashes($extra_info['title']);
  8271. $item_description = stripslashes($extra_info['description']);
  8272. $item_terms = stripslashes($extra_info['terms']);
  8273. if (empty($item_title)) {
  8274. $path_parts = pathinfo($extra_info['path']);
  8275. $item_title = stripslashes($path_parts['filename']);
  8276. }
  8277. } elseif (is_numeric($extra_info)) {
  8278. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8279. $result = Database::query($sql);
  8280. $row = Database::fetch_array($result);
  8281. $item_title = $row['title'];
  8282. $item_title = str_replace('_', ' ', $item_title);
  8283. if (empty($item_title)) {
  8284. $path_parts = pathinfo($row['path']);
  8285. $item_title = stripslashes($path_parts['filename']);
  8286. }
  8287. } else {
  8288. $item_title = '';
  8289. $item_description = '';
  8290. }
  8291. if ($id != 0 && is_array($extra_info)) {
  8292. $parent = $extra_info['parent_item_id'];
  8293. } else {
  8294. $parent = 0;
  8295. }
  8296. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8297. $result = Database::query($sql);
  8298. $arrLP = [];
  8299. while ($row = Database::fetch_array($result)) {
  8300. $arrLP[] = [
  8301. 'id' => $row['iid'],
  8302. 'item_type' => $row['item_type'],
  8303. 'title' => $row['title'],
  8304. 'path' => $row['path'],
  8305. 'description' => $row['description'],
  8306. 'parent_item_id' => $row['parent_item_id'],
  8307. 'previous_item_id' => $row['previous_item_id'],
  8308. 'next_item_id' => $row['next_item_id'],
  8309. 'display_order' => $row['display_order'],
  8310. 'max_score' => $row['max_score'],
  8311. 'min_score' => $row['min_score'],
  8312. 'mastery_score' => $row['mastery_score'],
  8313. 'prerequisite' => $row['prerequisite'],
  8314. ];
  8315. }
  8316. $this->tree_array($arrLP);
  8317. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8318. unset($this->arrMenu);
  8319. if ($action == 'add') {
  8320. $formHeader = get_lang('CreateTheDocument');
  8321. } else {
  8322. $formHeader = get_lang('EditTheCurrentDocument');
  8323. }
  8324. if ('edit' === $action) {
  8325. $urlAudioIcon = Display::url(
  8326. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8327. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8328. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8329. );
  8330. } else {
  8331. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8332. }
  8333. $form = new FormValidator(
  8334. 'frm_add_reading',
  8335. 'POST',
  8336. $this->getCurrentBuildingModeURL(),
  8337. '',
  8338. ['enctype' => 'multipart/form-data']
  8339. );
  8340. $form->addHeader($formHeader);
  8341. $form->addHtml(
  8342. Display::return_message(
  8343. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8344. 'normal',
  8345. false
  8346. )
  8347. );
  8348. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8349. $defaults['description'] = $item_description;
  8350. $data = $this->generate_lp_folder($_course);
  8351. if ($action != 'edit') {
  8352. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8353. DocumentManager::build_directory_selector(
  8354. $folders,
  8355. '',
  8356. [],
  8357. true,
  8358. $form,
  8359. 'directory_parent_id'
  8360. );
  8361. }
  8362. if (isset($data['id'])) {
  8363. $defaults['directory_parent_id'] = $data['id'];
  8364. }
  8365. $form->addElement(
  8366. 'text',
  8367. 'title',
  8368. get_lang('Title')
  8369. );
  8370. $form->applyFilter('title', 'trim');
  8371. $form->applyFilter('title', 'html_filter');
  8372. $arrHide[0]['value'] = $this->name;
  8373. $arrHide[0]['padding'] = 20;
  8374. for ($i = 0; $i < count($arrLP); $i++) {
  8375. if ($action != 'add') {
  8376. if ($arrLP[$i]['item_type'] == 'dir' &&
  8377. !in_array($arrLP[$i]['id'], $arrHide) &&
  8378. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8379. ) {
  8380. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8381. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8382. }
  8383. } else {
  8384. if ($arrLP[$i]['item_type'] == 'dir') {
  8385. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8386. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8387. }
  8388. }
  8389. }
  8390. $parent_select = $form->addSelect(
  8391. 'parent',
  8392. get_lang('Parent'),
  8393. [],
  8394. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8395. );
  8396. $my_count = 0;
  8397. foreach ($arrHide as $key => $value) {
  8398. if ($my_count != 0) {
  8399. // The LP name is also the first section and is not in the same charset like the other sections.
  8400. $value['value'] = Security::remove_XSS($value['value']);
  8401. $parent_select->addOption(
  8402. $value['value'],
  8403. $key,
  8404. 'style="padding-left:'.$value['padding'].'px;"'
  8405. );
  8406. } else {
  8407. $value['value'] = Security::remove_XSS($value['value']);
  8408. $parent_select->addOption(
  8409. $value['value'],
  8410. $key,
  8411. 'style="padding-left:'.$value['padding'].'px;"'
  8412. );
  8413. }
  8414. $my_count++;
  8415. }
  8416. if (!empty($id)) {
  8417. $parent_select->setSelected($parent);
  8418. } else {
  8419. $parent_item_id = Session::read('parent_item_id', 0);
  8420. $parent_select->setSelected($parent_item_id);
  8421. }
  8422. if (is_array($arrLP)) {
  8423. reset($arrLP);
  8424. }
  8425. $arrHide = [];
  8426. $s_selected_position = null;
  8427. // POSITION
  8428. $lastPosition = null;
  8429. for ($i = 0; $i < count($arrLP); $i++) {
  8430. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8431. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8432. ) {
  8433. if ((isset($extra_info['previous_item_id']) &&
  8434. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8435. ) {
  8436. $s_selected_position = $arrLP[$i]['id'];
  8437. }
  8438. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8439. }
  8440. $lastPosition = $arrLP[$i]['id'];
  8441. }
  8442. if (empty($s_selected_position)) {
  8443. $s_selected_position = $lastPosition;
  8444. }
  8445. $position = $form->addSelect(
  8446. 'previous',
  8447. get_lang('Position'),
  8448. []
  8449. );
  8450. $position->addOption(get_lang('FirstPosition'), 0);
  8451. foreach ($arrHide as $key => $value) {
  8452. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8453. $position->addOption(
  8454. $value['value'],
  8455. $key,
  8456. 'style="padding-left:'.$padding.'px;"'
  8457. );
  8458. }
  8459. $position->setSelected($s_selected_position);
  8460. if (is_array($arrLP)) {
  8461. reset($arrLP);
  8462. }
  8463. $arrHide = [];
  8464. for ($i = 0; $i < count($arrLP); $i++) {
  8465. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8466. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8467. ) {
  8468. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8469. }
  8470. }
  8471. if (!$no_display_add) {
  8472. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8473. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8474. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8475. if (!$no_display_edit_textarea) {
  8476. $content = '';
  8477. if (isset($_POST['content'])) {
  8478. $content = stripslashes($_POST['content']);
  8479. } elseif (is_array($extra_info)) {
  8480. $content = $this->display_document($extra_info['path'], false, false);
  8481. } elseif (is_numeric($extra_info)) {
  8482. $content = $this->display_document($extra_info, false, false);
  8483. }
  8484. // A new document, it is in the root of the repository.
  8485. if (is_array($extra_info) && $extra_info != 'new') {
  8486. } else {
  8487. $this->generate_lp_folder($_course);
  8488. }
  8489. if ($_GET['action'] == 'add_item') {
  8490. $text = get_lang('LPCreateDocument');
  8491. } else {
  8492. $text = get_lang('SaveDocument');
  8493. }
  8494. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8495. $form
  8496. ->defaultRenderer()
  8497. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8498. $form->addButtonSave($text, 'submit_button');
  8499. $defaults['content_lp'] = $content;
  8500. }
  8501. } elseif (is_numeric($extra_info)) {
  8502. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8503. $return = $this->display_document($extra_info, true, true, true);
  8504. $form->addElement('html', $return);
  8505. }
  8506. }
  8507. if (is_numeric($extra_info)) {
  8508. $form->addElement('hidden', 'path', $extra_info);
  8509. } elseif (is_array($extra_info)) {
  8510. $form->addElement('hidden', 'path', $extra_info['path']);
  8511. }
  8512. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8513. $form->addElement('hidden', 'post_time', time());
  8514. $form->setDefaults($defaults);
  8515. return $form->returnForm();
  8516. }
  8517. /**
  8518. * @param array $courseInfo
  8519. * @param string $content
  8520. * @param string $title
  8521. * @param int $parentId
  8522. *
  8523. * @throws \Doctrine\ORM\ORMException
  8524. * @throws \Doctrine\ORM\OptimisticLockException
  8525. * @throws \Doctrine\ORM\TransactionRequiredException
  8526. *
  8527. * @return int
  8528. */
  8529. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8530. {
  8531. $creatorId = api_get_user_id();
  8532. $sessionId = api_get_session_id();
  8533. // Generates folder
  8534. $result = $this->generate_lp_folder($courseInfo);
  8535. $dir = $result['dir'];
  8536. if (empty($parentId) || $parentId == '/') {
  8537. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8538. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8539. if ($parentId === '/') {
  8540. $dir = '/';
  8541. }
  8542. // Please, do not modify this dirname formatting.
  8543. if (strstr($dir, '..')) {
  8544. $dir = '/';
  8545. }
  8546. if (!empty($dir[0]) && $dir[0] == '.') {
  8547. $dir = substr($dir, 1);
  8548. }
  8549. if (!empty($dir[0]) && $dir[0] != '/') {
  8550. $dir = '/'.$dir;
  8551. }
  8552. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8553. $dir .= '/';
  8554. }
  8555. } else {
  8556. $parentInfo = DocumentManager::get_document_data_by_id(
  8557. $parentId,
  8558. $courseInfo['code']
  8559. );
  8560. if (!empty($parentInfo)) {
  8561. $dir = $parentInfo['path'].'/';
  8562. }
  8563. }
  8564. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8565. if (!is_dir($filepath)) {
  8566. $dir = '/';
  8567. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8568. }
  8569. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8570. if (!empty($title)) {
  8571. $title = api_replace_dangerous_char(stripslashes($title));
  8572. } else {
  8573. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8574. }
  8575. $title = disable_dangerous_file($title);
  8576. $filename = $title;
  8577. $content = !empty($content) ? $content : $_POST['content_lp'];
  8578. $tmpFileName = $filename;
  8579. $i = 0;
  8580. while (file_exists($filepath.$tmpFileName.'.html')) {
  8581. $tmpFileName = $filename.'_'.++$i;
  8582. }
  8583. $filename = $tmpFileName.'.html';
  8584. $content = stripslashes($content);
  8585. if (file_exists($filepath.$filename)) {
  8586. return 0;
  8587. }
  8588. $putContent = file_put_contents($filepath.$filename, $content);
  8589. if ($putContent === false) {
  8590. return 0;
  8591. }
  8592. $fileSize = filesize($filepath.$filename);
  8593. $saveFilePath = $dir.$filename;
  8594. $documentId = add_document(
  8595. $courseInfo,
  8596. $saveFilePath,
  8597. 'file',
  8598. $fileSize,
  8599. $tmpFileName,
  8600. '',
  8601. 0, //readonly
  8602. true,
  8603. null,
  8604. $sessionId,
  8605. $creatorId
  8606. );
  8607. if (!$documentId) {
  8608. return 0;
  8609. }
  8610. api_item_property_update(
  8611. $courseInfo,
  8612. TOOL_DOCUMENT,
  8613. $documentId,
  8614. 'DocumentAdded',
  8615. $creatorId,
  8616. null,
  8617. null,
  8618. null,
  8619. null,
  8620. $sessionId
  8621. );
  8622. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8623. $newTitle = $originalTitle;
  8624. if ($newComment || $newTitle) {
  8625. $em = Database::getManager();
  8626. /** @var CDocument $doc */
  8627. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8628. if ($newComment) {
  8629. $doc->setComment($newComment);
  8630. }
  8631. if ($newTitle) {
  8632. $doc->setTitle($newTitle);
  8633. }
  8634. $em->persist($doc);
  8635. $em->flush();
  8636. }
  8637. return $documentId;
  8638. }
  8639. /**
  8640. * Return HTML form to add/edit a link item.
  8641. *
  8642. * @param string $action (add/edit)
  8643. * @param int $id Item ID if exists
  8644. * @param mixed $extra_info
  8645. *
  8646. * @throws Exception
  8647. * @throws HTML_QuickForm_Error
  8648. *
  8649. * @return string HTML form
  8650. */
  8651. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8652. {
  8653. $course_id = api_get_course_int_id();
  8654. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8655. $tbl_link = Database::get_course_table(TABLE_LINK);
  8656. $item_title = '';
  8657. $item_description = '';
  8658. $item_url = '';
  8659. if ($id != 0 && is_array($extra_info)) {
  8660. $item_title = stripslashes($extra_info['title']);
  8661. $item_description = stripslashes($extra_info['description']);
  8662. $item_url = stripslashes($extra_info['url']);
  8663. } elseif (is_numeric($extra_info)) {
  8664. $extra_info = (int) $extra_info;
  8665. $sql = "SELECT title, description, url
  8666. FROM $tbl_link
  8667. WHERE c_id = $course_id AND iid = $extra_info";
  8668. $result = Database::query($sql);
  8669. $row = Database::fetch_array($result);
  8670. $item_title = $row['title'];
  8671. $item_description = $row['description'];
  8672. $item_url = $row['url'];
  8673. }
  8674. $form = new FormValidator(
  8675. 'edit_link',
  8676. 'POST',
  8677. $this->getCurrentBuildingModeURL()
  8678. );
  8679. $defaults = [];
  8680. $parent = 0;
  8681. if ($id != 0 && is_array($extra_info)) {
  8682. $parent = $extra_info['parent_item_id'];
  8683. }
  8684. $sql = "SELECT * FROM $tbl_lp_item
  8685. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8686. $result = Database::query($sql);
  8687. $arrLP = [];
  8688. while ($row = Database::fetch_array($result)) {
  8689. $arrLP[] = [
  8690. 'id' => $row['id'],
  8691. 'item_type' => $row['item_type'],
  8692. 'title' => $row['title'],
  8693. 'path' => $row['path'],
  8694. 'description' => $row['description'],
  8695. 'parent_item_id' => $row['parent_item_id'],
  8696. 'previous_item_id' => $row['previous_item_id'],
  8697. 'next_item_id' => $row['next_item_id'],
  8698. 'display_order' => $row['display_order'],
  8699. 'max_score' => $row['max_score'],
  8700. 'min_score' => $row['min_score'],
  8701. 'mastery_score' => $row['mastery_score'],
  8702. 'prerequisite' => $row['prerequisite'],
  8703. ];
  8704. }
  8705. $this->tree_array($arrLP);
  8706. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8707. unset($this->arrMenu);
  8708. if ($action == 'add') {
  8709. $legend = get_lang('CreateTheLink');
  8710. } elseif ($action == 'move') {
  8711. $legend = get_lang('MoveCurrentLink');
  8712. } else {
  8713. $legend = get_lang('EditCurrentLink');
  8714. }
  8715. $form->addHeader($legend);
  8716. if ($action != 'move') {
  8717. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8718. $defaults['title'] = $item_title;
  8719. }
  8720. $selectParent = $form->addSelect(
  8721. 'parent',
  8722. get_lang('Parent'),
  8723. [],
  8724. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8725. );
  8726. $selectParent->addOption($this->name, 0);
  8727. $arrHide = [
  8728. $id,
  8729. ];
  8730. $parent_item_id = Session::read('parent_item_id', 0);
  8731. for ($i = 0; $i < count($arrLP); $i++) {
  8732. if ($action != 'add') {
  8733. if (
  8734. ($arrLP[$i]['item_type'] == 'dir') &&
  8735. !in_array($arrLP[$i]['id'], $arrHide) &&
  8736. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8737. ) {
  8738. $selectParent->addOption(
  8739. $arrLP[$i]['title'],
  8740. $arrLP[$i]['id'],
  8741. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8742. );
  8743. if ($parent == $arrLP[$i]['id']) {
  8744. $selectParent->setSelected($arrLP[$i]['id']);
  8745. }
  8746. } else {
  8747. $arrHide[] = $arrLP[$i]['id'];
  8748. }
  8749. } else {
  8750. if ($arrLP[$i]['item_type'] == 'dir') {
  8751. $selectParent->addOption(
  8752. $arrLP[$i]['title'],
  8753. $arrLP[$i]['id'],
  8754. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8755. );
  8756. if ($parent_item_id == $arrLP[$i]['id']) {
  8757. $selectParent->setSelected($arrLP[$i]['id']);
  8758. }
  8759. }
  8760. }
  8761. }
  8762. if (is_array($arrLP)) {
  8763. reset($arrLP);
  8764. }
  8765. $selectPrevious = $form->addSelect(
  8766. 'previous',
  8767. get_lang('Position'),
  8768. [],
  8769. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8770. );
  8771. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8772. for ($i = 0; $i < count($arrLP); $i++) {
  8773. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8774. $selectPrevious->addOption(
  8775. $arrLP[$i]['title'],
  8776. $arrLP[$i]['id']
  8777. );
  8778. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8779. $selectPrevious->setSelected($arrLP[$i]['id']);
  8780. } elseif ($action == 'add') {
  8781. $selectPrevious->setSelected($arrLP[$i]['id']);
  8782. }
  8783. }
  8784. }
  8785. if ($action != 'move') {
  8786. $urlAttributes = ['class' => 'learnpath_item_form'];
  8787. if (is_numeric($extra_info)) {
  8788. $urlAttributes['disabled'] = 'disabled';
  8789. }
  8790. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8791. $defaults['url'] = $item_url;
  8792. $arrHide = [];
  8793. for ($i = 0; $i < count($arrLP); $i++) {
  8794. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8795. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8796. }
  8797. }
  8798. }
  8799. if ($action == 'add') {
  8800. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8801. } else {
  8802. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8803. }
  8804. if ($action == 'move') {
  8805. $form->addHidden('title', $item_title);
  8806. $form->addHidden('description', $item_description);
  8807. }
  8808. if (is_numeric($extra_info)) {
  8809. $form->addHidden('path', $extra_info);
  8810. } elseif (is_array($extra_info)) {
  8811. $form->addHidden('path', $extra_info['path']);
  8812. }
  8813. $form->addHidden('type', TOOL_LINK);
  8814. $form->addHidden('post_time', time());
  8815. $form->setDefaults($defaults);
  8816. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8817. }
  8818. /**
  8819. * Return HTML form to add/edit a student publication (work).
  8820. *
  8821. * @param string $action
  8822. * @param int $id Item ID if already exists
  8823. * @param string $extra_info
  8824. *
  8825. * @throws Exception
  8826. *
  8827. * @return string HTML form
  8828. */
  8829. public function display_student_publication_form(
  8830. $action = 'add',
  8831. $id = 0,
  8832. $extra_info = ''
  8833. ) {
  8834. $course_id = api_get_course_int_id();
  8835. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8836. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8837. $item_title = get_lang('Student_publication');
  8838. if ($id != 0 && is_array($extra_info)) {
  8839. $item_title = stripslashes($extra_info['title']);
  8840. $item_description = stripslashes($extra_info['description']);
  8841. } elseif (is_numeric($extra_info)) {
  8842. $extra_info = (int) $extra_info;
  8843. $sql = "SELECT title, description
  8844. FROM $tbl_publication
  8845. WHERE c_id = $course_id AND id = ".$extra_info;
  8846. $result = Database::query($sql);
  8847. $row = Database::fetch_array($result);
  8848. if ($row) {
  8849. $item_title = $row['title'];
  8850. }
  8851. }
  8852. $parent = 0;
  8853. if ($id != 0 && is_array($extra_info)) {
  8854. $parent = $extra_info['parent_item_id'];
  8855. }
  8856. $sql = "SELECT * FROM $tbl_lp_item
  8857. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8858. $result = Database::query($sql);
  8859. $arrLP = [];
  8860. while ($row = Database::fetch_array($result)) {
  8861. $arrLP[] = [
  8862. 'id' => $row['iid'],
  8863. 'item_type' => $row['item_type'],
  8864. 'title' => $row['title'],
  8865. 'path' => $row['path'],
  8866. 'description' => $row['description'],
  8867. 'parent_item_id' => $row['parent_item_id'],
  8868. 'previous_item_id' => $row['previous_item_id'],
  8869. 'next_item_id' => $row['next_item_id'],
  8870. 'display_order' => $row['display_order'],
  8871. 'max_score' => $row['max_score'],
  8872. 'min_score' => $row['min_score'],
  8873. 'mastery_score' => $row['mastery_score'],
  8874. 'prerequisite' => $row['prerequisite'],
  8875. ];
  8876. }
  8877. $this->tree_array($arrLP);
  8878. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8879. unset($this->arrMenu);
  8880. $form = new FormValidator('frm_student_publication', 'post', '#');
  8881. if ($action == 'add') {
  8882. $form->addHeader(get_lang('Student_publication'));
  8883. } elseif ($action == 'move') {
  8884. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8885. } else {
  8886. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8887. }
  8888. if ($action != 'move') {
  8889. $form->addText(
  8890. 'title',
  8891. get_lang('Title'),
  8892. true,
  8893. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8894. );
  8895. }
  8896. $parentSelect = $form->addSelect(
  8897. 'parent',
  8898. get_lang('Parent'),
  8899. ['0' => $this->name],
  8900. [
  8901. 'onchange' => 'javascript: load_cbo(this.value);',
  8902. 'class' => 'learnpath_item_form',
  8903. 'id' => 'idParent',
  8904. ]
  8905. );
  8906. $arrHide = [$id];
  8907. for ($i = 0; $i < count($arrLP); $i++) {
  8908. if ($action != 'add') {
  8909. if (
  8910. ($arrLP[$i]['item_type'] == 'dir') &&
  8911. !in_array($arrLP[$i]['id'], $arrHide) &&
  8912. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8913. ) {
  8914. $parentSelect->addOption(
  8915. $arrLP[$i]['title'],
  8916. $arrLP[$i]['id'],
  8917. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8918. );
  8919. if ($parent == $arrLP[$i]['id']) {
  8920. $parentSelect->setSelected($arrLP[$i]['id']);
  8921. }
  8922. } else {
  8923. $arrHide[] = $arrLP[$i]['id'];
  8924. }
  8925. } else {
  8926. if ($arrLP[$i]['item_type'] == 'dir') {
  8927. $parentSelect->addOption(
  8928. $arrLP[$i]['title'],
  8929. $arrLP[$i]['id'],
  8930. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8931. );
  8932. if ($parent == $arrLP[$i]['id']) {
  8933. $parentSelect->setSelected($arrLP[$i]['id']);
  8934. }
  8935. }
  8936. }
  8937. }
  8938. if (is_array($arrLP)) {
  8939. reset($arrLP);
  8940. }
  8941. $previousSelect = $form->addSelect(
  8942. 'previous',
  8943. get_lang('Position'),
  8944. ['0' => get_lang('FirstPosition')],
  8945. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8946. );
  8947. for ($i = 0; $i < count($arrLP); $i++) {
  8948. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8949. $previousSelect->addOption(
  8950. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8951. $arrLP[$i]['id']
  8952. );
  8953. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8954. $previousSelect->setSelected($arrLP[$i]['id']);
  8955. } elseif ($action == 'add') {
  8956. $previousSelect->setSelected($arrLP[$i]['id']);
  8957. }
  8958. }
  8959. }
  8960. if ($action == 'add') {
  8961. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8962. } else {
  8963. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8964. }
  8965. if ($action == 'move') {
  8966. $form->addHidden('title', $item_title);
  8967. $form->addHidden('description', $item_description);
  8968. }
  8969. if (is_numeric($extra_info)) {
  8970. $form->addHidden('path', $extra_info);
  8971. } elseif (is_array($extra_info)) {
  8972. $form->addHidden('path', $extra_info['path']);
  8973. }
  8974. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8975. $form->addHidden('post_time', time());
  8976. $form->setDefaults(['title' => $item_title]);
  8977. $return = '<div class="sectioncomment">';
  8978. $return .= $form->returnForm();
  8979. $return .= '</div>';
  8980. return $return;
  8981. }
  8982. /**
  8983. * Displays the menu for manipulating a step.
  8984. *
  8985. * @param id $item_id
  8986. * @param string $item_type
  8987. *
  8988. * @return string
  8989. */
  8990. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8991. {
  8992. $_course = api_get_course_info();
  8993. $course_code = api_get_course_id();
  8994. $item_id = (int) $item_id;
  8995. $return = '<div class="actions">';
  8996. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8997. $sql = "SELECT * FROM $tbl_lp_item
  8998. WHERE iid = ".$item_id;
  8999. $result = Database::query($sql);
  9000. $row = Database::fetch_assoc($result);
  9001. $audio_player = null;
  9002. // We display an audio player if needed.
  9003. if (!empty($row['audio'])) {
  9004. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9005. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9006. .'<audio src="'.$webAudioPath.'" controls>'
  9007. .'</div><br>';
  9008. }
  9009. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9010. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9011. $return .= Display::url(
  9012. Display::return_icon(
  9013. 'edit.png',
  9014. get_lang('Edit'),
  9015. [],
  9016. ICON_SIZE_SMALL
  9017. ),
  9018. $url.'&action=edit_item&path_item='.$row['path']
  9019. );
  9020. $return .= Display::url(
  9021. Display::return_icon(
  9022. 'move.png',
  9023. get_lang('Move'),
  9024. [],
  9025. ICON_SIZE_SMALL
  9026. ),
  9027. $url.'&action=move_item'
  9028. );
  9029. }
  9030. // Commented for now as prerequisites cannot be added to chapters.
  9031. if ($item_type != 'dir') {
  9032. $return .= Display::url(
  9033. Display::return_icon(
  9034. 'accept.png',
  9035. get_lang('LearnpathPrerequisites'),
  9036. [],
  9037. ICON_SIZE_SMALL
  9038. ),
  9039. $url.'&action=edit_item_prereq'
  9040. );
  9041. }
  9042. $return .= Display::url(
  9043. Display::return_icon(
  9044. 'delete.png',
  9045. get_lang('Delete'),
  9046. [],
  9047. ICON_SIZE_SMALL
  9048. ),
  9049. $url.'&action=delete_item'
  9050. );
  9051. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  9052. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9053. if (empty($documentData)) {
  9054. // Try with iid
  9055. $table = Database::get_course_table(TABLE_DOCUMENT);
  9056. $sql = "SELECT path FROM $table
  9057. WHERE
  9058. c_id = ".api_get_course_int_id()." AND
  9059. iid = ".$row['path']." AND
  9060. path NOT LIKE '%_DELETED_%'";
  9061. $result = Database::query($sql);
  9062. $documentData = Database::fetch_array($result);
  9063. if ($documentData) {
  9064. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  9065. }
  9066. }
  9067. if (isset($documentData['absolute_path_from_document'])) {
  9068. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  9069. }
  9070. }
  9071. $return .= '</div>';
  9072. if (!empty($audio_player)) {
  9073. $return .= $audio_player;
  9074. }
  9075. return $return;
  9076. }
  9077. /**
  9078. * Creates the javascript needed for filling up the checkboxes without page reload.
  9079. *
  9080. * @return string
  9081. */
  9082. public function get_js_dropdown_array()
  9083. {
  9084. $course_id = api_get_course_int_id();
  9085. $return = 'var child_name = new Array();'."\n";
  9086. $return .= 'var child_value = new Array();'."\n\n";
  9087. $return .= 'child_name[0] = new Array();'."\n";
  9088. $return .= 'child_value[0] = new Array();'."\n\n";
  9089. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9090. $sql = "SELECT * FROM ".$tbl_lp_item."
  9091. WHERE
  9092. c_id = $course_id AND
  9093. lp_id = ".$this->lp_id." AND
  9094. parent_item_id = 0
  9095. ORDER BY display_order ASC";
  9096. $res_zero = Database::query($sql);
  9097. $i = 0;
  9098. while ($row_zero = Database::fetch_array($res_zero)) {
  9099. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9100. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9101. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9102. }
  9103. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9104. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9105. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9106. }
  9107. }
  9108. $return .= "\n";
  9109. $sql = "SELECT * FROM $tbl_lp_item
  9110. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9111. $res = Database::query($sql);
  9112. while ($row = Database::fetch_array($res)) {
  9113. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9114. WHERE
  9115. c_id = ".$course_id." AND
  9116. parent_item_id = ".$row['iid']."
  9117. ORDER BY display_order ASC";
  9118. $res_parent = Database::query($sql_parent);
  9119. $i = 0;
  9120. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9121. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9122. while ($row_parent = Database::fetch_array($res_parent)) {
  9123. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9124. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9125. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9126. }
  9127. $return .= "\n";
  9128. }
  9129. $return .= "
  9130. function load_cbo(id) {
  9131. if (!id) {
  9132. return false;
  9133. }
  9134. var cbo = document.getElementById('previous');
  9135. for(var i = cbo.length - 1; i > 0; i--) {
  9136. cbo.options[i] = null;
  9137. }
  9138. var k=0;
  9139. for(var i = 1; i <= child_name[id].length; i++){
  9140. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9141. option.style.paddingLeft = '40px';
  9142. cbo.options[i] = option;
  9143. k = i;
  9144. }
  9145. cbo.options[k].selected = true;
  9146. $('#previous').selectpicker('refresh');
  9147. }";
  9148. return $return;
  9149. }
  9150. /**
  9151. * Display the form to allow moving an item.
  9152. *
  9153. * @param int $item_id Item ID
  9154. *
  9155. * @throws Exception
  9156. * @throws HTML_QuickForm_Error
  9157. *
  9158. * @return string HTML form
  9159. */
  9160. public function display_move_item($item_id)
  9161. {
  9162. $return = '';
  9163. if (is_numeric($item_id)) {
  9164. $item_id = (int) $item_id;
  9165. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9166. $sql = "SELECT * FROM $tbl_lp_item
  9167. WHERE iid = $item_id";
  9168. $res = Database::query($sql);
  9169. $row = Database::fetch_array($res);
  9170. switch ($row['item_type']) {
  9171. case 'dir':
  9172. case 'asset':
  9173. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9174. $return .= $this->display_item_form(
  9175. $row['item_type'],
  9176. get_lang('MoveCurrentChapter'),
  9177. 'move',
  9178. $item_id,
  9179. $row
  9180. );
  9181. break;
  9182. case TOOL_DOCUMENT:
  9183. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9184. $return .= $this->display_document_form('move', $item_id, $row);
  9185. break;
  9186. case TOOL_LINK:
  9187. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9188. $return .= $this->display_link_form('move', $item_id, $row);
  9189. break;
  9190. case TOOL_HOTPOTATOES:
  9191. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9192. $return .= $this->display_link_form('move', $item_id, $row);
  9193. break;
  9194. case TOOL_QUIZ:
  9195. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9196. $return .= $this->display_quiz_form('move', $item_id, $row);
  9197. break;
  9198. case TOOL_STUDENTPUBLICATION:
  9199. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9200. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9201. break;
  9202. case TOOL_FORUM:
  9203. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9204. $return .= $this->display_forum_form('move', $item_id, $row);
  9205. break;
  9206. case TOOL_THREAD:
  9207. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9208. $return .= $this->display_forum_form('move', $item_id, $row);
  9209. break;
  9210. }
  9211. }
  9212. return $return;
  9213. }
  9214. /**
  9215. * Return HTML form to allow prerequisites selection.
  9216. *
  9217. * @todo use FormValidator
  9218. *
  9219. * @param int Item ID
  9220. *
  9221. * @return string HTML form
  9222. */
  9223. public function display_item_prerequisites_form($item_id = 0)
  9224. {
  9225. $course_id = api_get_course_int_id();
  9226. $item_id = (int) $item_id;
  9227. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9228. /* Current prerequisite */
  9229. $sql = "SELECT * FROM $tbl_lp_item
  9230. WHERE iid = $item_id";
  9231. $result = Database::query($sql);
  9232. $row = Database::fetch_array($result);
  9233. $prerequisiteId = $row['prerequisite'];
  9234. $return = '<legend>';
  9235. $return .= get_lang('AddEditPrerequisites');
  9236. $return .= '</legend>';
  9237. $return .= '<form method="POST">';
  9238. $return .= '<div class="table-responsive">';
  9239. $return .= '<table class="table table-hover">';
  9240. $return .= '<thead>';
  9241. $return .= '<tr>';
  9242. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9243. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9244. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9245. $return .= '</tr>';
  9246. $return .= '</thead>';
  9247. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9248. $return .= '<tbody>';
  9249. $return .= '<tr>';
  9250. $return .= '<td colspan="3">';
  9251. $return .= '<div class="radio learnpath"><label for="idNone">';
  9252. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9253. $return .= get_lang('None').'</label>';
  9254. $return .= '</div>';
  9255. $return .= '</tr>';
  9256. $sql = "SELECT * FROM $tbl_lp_item
  9257. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9258. $result = Database::query($sql);
  9259. $arrLP = [];
  9260. $selectedMinScore = [];
  9261. $selectedMaxScore = [];
  9262. $masteryScore = [];
  9263. while ($row = Database::fetch_array($result)) {
  9264. if ($row['iid'] == $item_id) {
  9265. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9266. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9267. }
  9268. $masteryScore[$row['iid']] = $row['mastery_score'];
  9269. $arrLP[] = [
  9270. 'id' => $row['iid'],
  9271. 'item_type' => $row['item_type'],
  9272. 'title' => $row['title'],
  9273. 'ref' => $row['ref'],
  9274. 'description' => $row['description'],
  9275. 'parent_item_id' => $row['parent_item_id'],
  9276. 'previous_item_id' => $row['previous_item_id'],
  9277. 'next_item_id' => $row['next_item_id'],
  9278. 'max_score' => $row['max_score'],
  9279. 'min_score' => $row['min_score'],
  9280. 'mastery_score' => $row['mastery_score'],
  9281. 'prerequisite' => $row['prerequisite'],
  9282. 'display_order' => $row['display_order'],
  9283. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9284. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9285. ];
  9286. }
  9287. $this->tree_array($arrLP);
  9288. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9289. unset($this->arrMenu);
  9290. for ($i = 0; $i < count($arrLP); $i++) {
  9291. $item = $arrLP[$i];
  9292. if ($item['id'] == $item_id) {
  9293. break;
  9294. }
  9295. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9296. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9297. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  9298. $return .= '<tr>';
  9299. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9300. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9301. $return .= '<label for="id'.$item['id'].'">';
  9302. $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'].'" />';
  9303. $icon_name = str_replace(' ', '', $item['item_type']);
  9304. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9305. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9306. } else {
  9307. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9308. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9309. } else {
  9310. $return .= Display::return_icon('folder_document.png');
  9311. }
  9312. }
  9313. $return .= $item['title'].'</label>';
  9314. $return .= '</div>';
  9315. $return .= '</td>';
  9316. if ($item['item_type'] == TOOL_QUIZ) {
  9317. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9318. $lpItemObj = new LpItem($course_id, $item['id']);
  9319. $exercise = new Exercise($course_id);
  9320. $exercise->read($lpItemObj->path);
  9321. $lpItemObj->max_score = $exercise->get_max_score();
  9322. $lpItemObj->update();
  9323. $item['max_score'] = $lpItemObj->max_score;
  9324. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  9325. // Backwards compatibility with 1.9.x use mastery_score as min value
  9326. $selectedMinScoreValue = $masteryScoreAsMinValue;
  9327. }
  9328. $return .= '<td>';
  9329. $return .= '<input
  9330. class="form-control"
  9331. size="4" maxlength="3"
  9332. name="min_'.$item['id'].'"
  9333. type="number"
  9334. min="0"
  9335. step="1"
  9336. max="'.$item['max_score'].'"
  9337. value="'.$selectedMinScoreValue.'"
  9338. />';
  9339. $return .= '</td>';
  9340. $return .= '<td>';
  9341. $return .= '<input
  9342. class="form-control"
  9343. size="4"
  9344. maxlength="3"
  9345. name="max_'.$item['id'].'"
  9346. type="number"
  9347. min="0"
  9348. step="1"
  9349. max="'.$item['max_score'].'"
  9350. value="'.$selectedMaxScoreValue.'"
  9351. />';
  9352. $return .= '</td>';
  9353. }
  9354. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9355. $return .= '<td>';
  9356. $return .= '<input
  9357. size="4"
  9358. maxlength="3"
  9359. name="min_'.$item['id'].'"
  9360. type="number"
  9361. min="0"
  9362. step="1"
  9363. max="'.$item['max_score'].'"
  9364. value="'.$selectedMinScoreValue.'"
  9365. />';
  9366. $return .= '</td>';
  9367. $return .= '<td>';
  9368. $return .= '<input
  9369. size="4"
  9370. maxlength="3"
  9371. name="max_'.$item['id'].'"
  9372. type="number"
  9373. min="0"
  9374. step="1"
  9375. max="'.$item['max_score'].'"
  9376. value="'.$selectedMaxScoreValue.'"
  9377. />';
  9378. $return .= '</td>';
  9379. }
  9380. $return .= '</tr>';
  9381. }
  9382. $return .= '<tr>';
  9383. $return .= '</tr>';
  9384. $return .= '</tbody>';
  9385. $return .= '</table>';
  9386. $return .= '</div>';
  9387. $return .= '<div class="form-group">';
  9388. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9389. get_lang('ModifyPrerequisites').'</button>';
  9390. $return .= '</form>';
  9391. return $return;
  9392. }
  9393. /**
  9394. * Return HTML list to allow prerequisites selection for lp.
  9395. *
  9396. * @return string HTML form
  9397. */
  9398. public function display_lp_prerequisites_list()
  9399. {
  9400. $course_id = api_get_course_int_id();
  9401. $lp_id = $this->lp_id;
  9402. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9403. // get current prerequisite
  9404. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9405. $result = Database::query($sql);
  9406. $row = Database::fetch_array($result);
  9407. $prerequisiteId = $row['prerequisite'];
  9408. $session_id = api_get_session_id();
  9409. $session_condition = api_get_session_condition($session_id, true, true);
  9410. $sql = "SELECT * FROM $tbl_lp
  9411. WHERE c_id = $course_id $session_condition
  9412. ORDER BY display_order ";
  9413. $rs = Database::query($sql);
  9414. $return = '';
  9415. $return .= '<select name="prerequisites" class="form-control">';
  9416. $return .= '<option value="0">'.get_lang('None').'</option>';
  9417. if (Database::num_rows($rs) > 0) {
  9418. while ($row = Database::fetch_array($rs)) {
  9419. if ($row['id'] == $lp_id) {
  9420. continue;
  9421. }
  9422. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9423. }
  9424. }
  9425. $return .= '</select>';
  9426. return $return;
  9427. }
  9428. /**
  9429. * Creates a list with all the documents in it.
  9430. *
  9431. * @param bool $showInvisibleFiles
  9432. *
  9433. * @throws Exception
  9434. * @throws HTML_QuickForm_Error
  9435. *
  9436. * @return string
  9437. */
  9438. public function get_documents($showInvisibleFiles = false)
  9439. {
  9440. $course_info = api_get_course_info();
  9441. $sessionId = api_get_session_id();
  9442. $documentTree = DocumentManager::get_document_preview(
  9443. $course_info,
  9444. $this->lp_id,
  9445. null,
  9446. $sessionId,
  9447. true,
  9448. null,
  9449. null,
  9450. $showInvisibleFiles,
  9451. true
  9452. );
  9453. $headers = [
  9454. get_lang('Files'),
  9455. get_lang('CreateTheDocument'),
  9456. get_lang('CreateReadOutText'),
  9457. get_lang('Upload'),
  9458. ];
  9459. $form = new FormValidator(
  9460. 'form_upload',
  9461. 'POST',
  9462. $this->getCurrentBuildingModeURL(),
  9463. '',
  9464. ['enctype' => 'multipart/form-data']
  9465. );
  9466. $folders = DocumentManager::get_all_document_folders(
  9467. api_get_course_info(),
  9468. 0,
  9469. true
  9470. );
  9471. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9472. DocumentManager::build_directory_selector(
  9473. $folders,
  9474. $lpPathInfo['id'],
  9475. [],
  9476. true,
  9477. $form,
  9478. 'directory_parent_id'
  9479. );
  9480. $group = [
  9481. $form->createElement(
  9482. 'radio',
  9483. 'if_exists',
  9484. get_lang('UplWhatIfFileExists'),
  9485. get_lang('UplDoNothing'),
  9486. 'nothing'
  9487. ),
  9488. $form->createElement(
  9489. 'radio',
  9490. 'if_exists',
  9491. null,
  9492. get_lang('UplOverwriteLong'),
  9493. 'overwrite'
  9494. ),
  9495. $form->createElement(
  9496. 'radio',
  9497. 'if_exists',
  9498. null,
  9499. get_lang('UplRenameLong'),
  9500. 'rename'
  9501. ),
  9502. ];
  9503. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9504. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9505. $defaultFileExistsOption = 'rename';
  9506. if (!empty($fileExistsOption)) {
  9507. $defaultFileExistsOption = $fileExistsOption;
  9508. }
  9509. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9510. // Check box options
  9511. $form->addElement(
  9512. 'checkbox',
  9513. 'unzip',
  9514. get_lang('Options'),
  9515. get_lang('Uncompress')
  9516. );
  9517. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9518. $form->addMultipleUpload($url);
  9519. $new = $this->display_document_form('add', 0);
  9520. $frmReadOutText = $this->displayFrmReadOutText('add');
  9521. $tabs = Display::tabs(
  9522. $headers,
  9523. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9524. 'subtab'
  9525. );
  9526. return $tabs;
  9527. }
  9528. /**
  9529. * Creates a list with all the exercises (quiz) in it.
  9530. *
  9531. * @return string
  9532. */
  9533. public function get_exercises()
  9534. {
  9535. $course_id = api_get_course_int_id();
  9536. $session_id = api_get_session_id();
  9537. $userInfo = api_get_user_info();
  9538. // New for hotpotatoes.
  9539. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9540. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9541. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9542. $condition_session = api_get_session_condition($session_id, true, true);
  9543. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9544. $activeCondition = ' active <> -1 ';
  9545. if ($setting) {
  9546. $activeCondition = ' active = 1 ';
  9547. }
  9548. $categoryCondition = '';
  9549. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9550. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9551. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9552. }
  9553. $keywordCondition = '';
  9554. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9555. if (!empty($keyword)) {
  9556. $keyword = Database::escape_string($keyword);
  9557. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9558. }
  9559. $sql_quiz = "SELECT * FROM $tbl_quiz
  9560. WHERE
  9561. c_id = $course_id AND
  9562. $activeCondition
  9563. $condition_session
  9564. $categoryCondition
  9565. $keywordCondition
  9566. ORDER BY title ASC";
  9567. $sql_hot = "SELECT * FROM $tbl_doc
  9568. WHERE
  9569. c_id = $course_id AND
  9570. path LIKE '".$uploadPath."/%/%htm%'
  9571. $condition_session
  9572. ORDER BY id ASC";
  9573. $res_quiz = Database::query($sql_quiz);
  9574. $res_hot = Database::query($sql_hot);
  9575. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9576. // Create a search-box
  9577. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9578. $form->addHidden('action', 'add_item');
  9579. $form->addHidden('type', 'step');
  9580. $form->addHidden('lp_id', $this->lp_id);
  9581. $form->addHidden('lp_build_selected', '2');
  9582. $form->addCourseHiddenParams();
  9583. $form->addText(
  9584. 'keyword',
  9585. get_lang('Search'),
  9586. false,
  9587. [
  9588. 'aria-label' => get_lang('Search'),
  9589. ]
  9590. );
  9591. if (api_get_configuration_value('allow_exercise_categories')) {
  9592. $manager = new ExerciseCategoryManager();
  9593. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9594. if (!empty($options)) {
  9595. $form->addSelect(
  9596. 'category_id',
  9597. get_lang('Category'),
  9598. $options,
  9599. ['placeholder' => get_lang('SelectAnOption')]
  9600. );
  9601. }
  9602. }
  9603. $form->addButtonSearch(get_lang('Search'));
  9604. $return = $form->returnForm();
  9605. $return .= '<ul class="lp_resource">';
  9606. $return .= '<li class="lp_resource_element">';
  9607. $return .= Display::return_icon('new_exercice.png');
  9608. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9609. get_lang('NewExercise').'</a>';
  9610. $return .= '</li>';
  9611. $previewIcon = Display::return_icon(
  9612. 'preview_view.png',
  9613. get_lang('Preview')
  9614. );
  9615. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9616. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9617. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9618. // Display hotpotatoes
  9619. while ($row_hot = Database::fetch_array($res_hot)) {
  9620. $link = Display::url(
  9621. $previewIcon,
  9622. $exerciseUrl.'&file='.$row_hot['path'],
  9623. ['target' => '_blank']
  9624. );
  9625. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9626. $return .= '<a class="moved" href="#">';
  9627. $return .= Display::return_icon(
  9628. 'move_everywhere.png',
  9629. get_lang('Move'),
  9630. [],
  9631. ICON_SIZE_TINY
  9632. );
  9633. $return .= '</a> ';
  9634. $return .= Display::return_icon('hotpotatoes_s.png');
  9635. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9636. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9637. $return .= '</li>';
  9638. }
  9639. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9640. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9641. $title = strip_tags(
  9642. api_html_entity_decode($row_quiz['title'])
  9643. );
  9644. $visibility = api_get_item_visibility(
  9645. ['real_id' => $course_id],
  9646. TOOL_QUIZ,
  9647. $row_quiz['iid'],
  9648. $session_id
  9649. );
  9650. $link = Display::url(
  9651. $previewIcon,
  9652. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9653. ['target' => '_blank']
  9654. );
  9655. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9656. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9657. $return .= $quizIcon;
  9658. $sessionStar = api_get_session_image(
  9659. $row_quiz['session_id'],
  9660. $userInfo['status']
  9661. );
  9662. $return .= Display::url(
  9663. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9664. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9665. [
  9666. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9667. ]
  9668. );
  9669. $return .= '</li>';
  9670. }
  9671. $return .= '</ul>';
  9672. return $return;
  9673. }
  9674. /**
  9675. * Creates a list with all the links in it.
  9676. *
  9677. * @return string
  9678. */
  9679. public function get_links()
  9680. {
  9681. $selfUrl = api_get_self();
  9682. $courseIdReq = api_get_cidreq();
  9683. $course = api_get_course_info();
  9684. $userInfo = api_get_user_info();
  9685. $course_id = $course['real_id'];
  9686. $tbl_link = Database::get_course_table(TABLE_LINK);
  9687. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9688. $moveEverywhereIcon = Display::return_icon(
  9689. 'move_everywhere.png',
  9690. get_lang('Move'),
  9691. [],
  9692. ICON_SIZE_TINY
  9693. );
  9694. $session_id = api_get_session_id();
  9695. $condition_session = api_get_session_condition(
  9696. $session_id,
  9697. true,
  9698. true,
  9699. 'link.session_id'
  9700. );
  9701. $sql = "SELECT
  9702. link.id as link_id,
  9703. link.title as link_title,
  9704. link.session_id as link_session_id,
  9705. link.category_id as category_id,
  9706. link_category.category_title as category_title
  9707. FROM $tbl_link as link
  9708. LEFT JOIN $linkCategoryTable as link_category
  9709. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9710. WHERE link.c_id = $course_id $condition_session
  9711. ORDER BY link_category.category_title ASC, link.title ASC";
  9712. $result = Database::query($sql);
  9713. $categorizedLinks = [];
  9714. $categories = [];
  9715. while ($link = Database::fetch_array($result)) {
  9716. if (!$link['category_id']) {
  9717. $link['category_title'] = get_lang('Uncategorized');
  9718. }
  9719. $categories[$link['category_id']] = $link['category_title'];
  9720. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9721. }
  9722. $linksHtmlCode =
  9723. '<script>
  9724. function toggle_tool(tool, id) {
  9725. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9726. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9727. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9728. } else {
  9729. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9730. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9731. }
  9732. }
  9733. </script>
  9734. <ul class="lp_resource">
  9735. <li class="lp_resource_element">
  9736. '.Display::return_icon('linksnew.gif').'
  9737. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9738. get_lang('LinkAdd').'
  9739. </a>
  9740. </li>';
  9741. foreach ($categorizedLinks as $categoryId => $links) {
  9742. $linkNodes = null;
  9743. foreach ($links as $key => $linkInfo) {
  9744. $title = $linkInfo['link_title'];
  9745. $linkSessionId = $linkInfo['link_session_id'];
  9746. $link = Display::url(
  9747. Display::return_icon('preview_view.png', get_lang('Preview')),
  9748. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9749. ['target' => '_blank']
  9750. );
  9751. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9752. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9753. $linkNodes .=
  9754. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9755. <a class="moved" href="#">'.
  9756. $moveEverywhereIcon.
  9757. '</a>
  9758. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9759. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9760. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9761. Security::remove_XSS($title).$sessionStar.$link.
  9762. '</a>
  9763. </li>';
  9764. }
  9765. }
  9766. $linksHtmlCode .=
  9767. '<li>
  9768. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9769. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9770. align="absbottom" />
  9771. </a>
  9772. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9773. </li>
  9774. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9775. }
  9776. $linksHtmlCode .= '</ul>';
  9777. return $linksHtmlCode;
  9778. }
  9779. /**
  9780. * Creates a list with all the student publications in it.
  9781. *
  9782. * @return string
  9783. */
  9784. public function get_student_publications()
  9785. {
  9786. $return = '<ul class="lp_resource">';
  9787. $return .= '<li class="lp_resource_element">';
  9788. $return .= Display::return_icon('works_new.gif');
  9789. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9790. get_lang('AddAssignmentPage').'</a>';
  9791. $return .= '</li>';
  9792. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9793. $works = getWorkListTeacher(0, 100, null, null, null);
  9794. if (!empty($works)) {
  9795. foreach ($works as $work) {
  9796. $link = Display::url(
  9797. Display::return_icon('preview_view.png', get_lang('Preview')),
  9798. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9799. ['target' => '_blank']
  9800. );
  9801. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9802. $return .= '<a class="moved" href="#">';
  9803. $return .= Display::return_icon(
  9804. 'move_everywhere.png',
  9805. get_lang('Move'),
  9806. [],
  9807. ICON_SIZE_TINY
  9808. );
  9809. $return .= '</a> ';
  9810. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9811. $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.'">'.
  9812. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9813. </a>';
  9814. $return .= '</li>';
  9815. }
  9816. }
  9817. $return .= '</ul>';
  9818. return $return;
  9819. }
  9820. /**
  9821. * Creates a list with all the forums in it.
  9822. *
  9823. * @return string
  9824. */
  9825. public function get_forums()
  9826. {
  9827. require_once '../forum/forumfunction.inc.php';
  9828. $forumCategories = get_forum_categories();
  9829. $forumsInNoCategory = get_forums_in_category(0);
  9830. if (!empty($forumsInNoCategory)) {
  9831. $forumCategories = array_merge(
  9832. $forumCategories,
  9833. [
  9834. [
  9835. 'cat_id' => 0,
  9836. 'session_id' => 0,
  9837. 'visibility' => 1,
  9838. 'cat_comment' => null,
  9839. ],
  9840. ]
  9841. );
  9842. }
  9843. $forumList = get_forums();
  9844. $a_forums = [];
  9845. foreach ($forumCategories as $forumCategory) {
  9846. // The forums in this category.
  9847. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9848. if (!empty($forumsInCategory)) {
  9849. foreach ($forumList as $forum) {
  9850. if (isset($forum['forum_category']) &&
  9851. $forum['forum_category'] == $forumCategory['cat_id']
  9852. ) {
  9853. $a_forums[] = $forum;
  9854. }
  9855. }
  9856. }
  9857. }
  9858. $return = '<ul class="lp_resource">';
  9859. // First add link
  9860. $return .= '<li class="lp_resource_element">';
  9861. $return .= Display::return_icon('new_forum.png');
  9862. $return .= Display::url(
  9863. get_lang('CreateANewForum'),
  9864. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9865. 'action' => 'add',
  9866. 'content' => 'forum',
  9867. 'lp_id' => $this->lp_id,
  9868. ]),
  9869. ['title' => get_lang('CreateANewForum')]
  9870. );
  9871. $return .= '</li>';
  9872. $return .= '<script>
  9873. function toggle_forum(forum_id) {
  9874. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9875. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9876. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9877. } else {
  9878. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9879. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9880. }
  9881. }
  9882. </script>';
  9883. foreach ($a_forums as $forum) {
  9884. if (!empty($forum['forum_id'])) {
  9885. $link = Display::url(
  9886. Display::return_icon('preview_view.png', get_lang('Preview')),
  9887. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9888. ['target' => '_blank']
  9889. );
  9890. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9891. $return .= '<a class="moved" href="#">';
  9892. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9893. $return .= ' </a>';
  9894. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9895. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9896. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9897. </a>
  9898. <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">'.
  9899. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9900. $return .= '</li>';
  9901. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9902. $a_threads = get_threads($forum['forum_id']);
  9903. if (is_array($a_threads)) {
  9904. foreach ($a_threads as $thread) {
  9905. $link = Display::url(
  9906. Display::return_icon('preview_view.png', get_lang('Preview')),
  9907. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9908. ['target' => '_blank']
  9909. );
  9910. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9911. $return .= '&nbsp;<a class="moved" href="#">';
  9912. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9913. $return .= ' </a>';
  9914. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9915. $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.'">'.
  9916. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9917. $return .= '</li>';
  9918. }
  9919. }
  9920. $return .= '</div>';
  9921. }
  9922. }
  9923. $return .= '</ul>';
  9924. return $return;
  9925. }
  9926. /**
  9927. * // TODO: The output encoding should be equal to the system encoding.
  9928. *
  9929. * Exports the learning path as a SCORM package. This is the main function that
  9930. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9931. * whole thing and returns the zip.
  9932. *
  9933. * This method needs to be called in PHP5, as it will fail with non-adequate
  9934. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9935. * you need to call it on a learnpath object.
  9936. *
  9937. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9938. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9939. * path has been modified, it should use the generic method here below.
  9940. *
  9941. * @return string Returns the zip package string, or null if error
  9942. */
  9943. public function scormExport()
  9944. {
  9945. api_set_more_memory_and_time_limits();
  9946. $_course = api_get_course_info();
  9947. $course_id = $_course['real_id'];
  9948. // Create the zip handler (this will remain available throughout the method).
  9949. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9950. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9951. $temp_dir_short = uniqid('scorm_export', true);
  9952. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9953. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9954. $zip_folder = new PclZip($temp_zip_file);
  9955. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9956. $root_path = $main_path = api_get_path(SYS_PATH);
  9957. $files_cleanup = [];
  9958. // Place to temporarily stash the zip file.
  9959. // create the temp dir if it doesn't exist
  9960. // or do a cleanup before creating the zip file.
  9961. if (!is_dir($temp_zip_dir)) {
  9962. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9963. } else {
  9964. // Cleanup: Check the temp dir for old files and delete them.
  9965. $handle = opendir($temp_zip_dir);
  9966. while (false !== ($file = readdir($handle))) {
  9967. if ($file != '.' && $file != '..') {
  9968. unlink("$temp_zip_dir/$file");
  9969. }
  9970. }
  9971. closedir($handle);
  9972. }
  9973. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9974. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9975. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9976. ) {
  9977. // Remove the possible . at the end of the path.
  9978. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9979. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9980. mkdir(
  9981. $dest_path_to_scorm_folder,
  9982. api_get_permissions_for_new_directories(),
  9983. true
  9984. );
  9985. copyr(
  9986. $current_course_path.'/scorm/'.$this->path,
  9987. $dest_path_to_scorm_folder,
  9988. ['imsmanifest'],
  9989. $zip_files
  9990. );
  9991. }
  9992. // Build a dummy imsmanifest structure.
  9993. // Do not add to the zip yet (we still need it).
  9994. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9995. // Aggregation Model official document, section "2.3 Content Packaging".
  9996. // We are going to build a UTF-8 encoded manifest.
  9997. // Later we will recode it to the desired (and supported) encoding.
  9998. $xmldoc = new DOMDocument('1.0');
  9999. $root = $xmldoc->createElement('manifest');
  10000. $root->setAttribute('identifier', 'SingleCourseManifest');
  10001. $root->setAttribute('version', '1.1');
  10002. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10003. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10004. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10005. $root->setAttribute(
  10006. 'xsi:schemaLocation',
  10007. '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'
  10008. );
  10009. // Build mandatory sub-root container elements.
  10010. $metadata = $xmldoc->createElement('metadata');
  10011. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10012. $metadata->appendChild($md_schema);
  10013. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10014. $metadata->appendChild($md_schemaversion);
  10015. $root->appendChild($metadata);
  10016. $organizations = $xmldoc->createElement('organizations');
  10017. $resources = $xmldoc->createElement('resources');
  10018. // Build the only organization we will use in building our learnpaths.
  10019. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10020. $organization = $xmldoc->createElement('organization');
  10021. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10022. // To set the title of the SCORM entity (=organization), we take the name given
  10023. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10024. // learning path charset) as it is the encoding that defines how it is stored
  10025. // in the database. Then we convert it to HTML entities again as the "&" character
  10026. // alone is not authorized in XML (must be &amp;).
  10027. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10028. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10029. $organization->appendChild($org_title);
  10030. $folder_name = 'document';
  10031. // Removes the learning_path/scorm_folder path when exporting see #4841
  10032. $path_to_remove = '';
  10033. $path_to_replace = '';
  10034. $result = $this->generate_lp_folder($_course);
  10035. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10036. $path_to_remove = 'document'.$result['dir'];
  10037. $path_to_replace = $folder_name.'/';
  10038. }
  10039. // Fixes chamilo scorm exports
  10040. if ($this->ref === 'chamilo_scorm_export') {
  10041. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10042. }
  10043. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10044. $link_updates = [];
  10045. $links_to_create = [];
  10046. foreach ($this->ordered_items as $index => $itemId) {
  10047. /** @var learnpathItem $item */
  10048. $item = $this->items[$itemId];
  10049. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10050. // Get included documents from this item.
  10051. if ($item->type === 'sco') {
  10052. $inc_docs = $item->get_resources_from_source(
  10053. null,
  10054. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10055. );
  10056. } else {
  10057. $inc_docs = $item->get_resources_from_source();
  10058. }
  10059. // Give a child element <item> to the <organization> element.
  10060. $my_item_id = $item->get_id();
  10061. $my_item = $xmldoc->createElement('item');
  10062. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10063. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10064. $my_item->setAttribute('isvisible', 'true');
  10065. // Give a child element <title> to the <item> element.
  10066. $my_title = $xmldoc->createElement(
  10067. 'title',
  10068. htmlspecialchars(
  10069. api_utf8_encode($item->get_title()),
  10070. ENT_QUOTES,
  10071. 'UTF-8'
  10072. )
  10073. );
  10074. $my_item->appendChild($my_title);
  10075. // Give a child element <adlcp:prerequisites> to the <item> element.
  10076. $my_prereqs = $xmldoc->createElement(
  10077. 'adlcp:prerequisites',
  10078. $this->get_scorm_prereq_string($my_item_id)
  10079. );
  10080. $my_prereqs->setAttribute('type', 'aicc_script');
  10081. $my_item->appendChild($my_prereqs);
  10082. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10083. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10084. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10085. //$xmldoc->createElement('adlcp:timelimitaction','');
  10086. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10087. //$xmldoc->createElement('adlcp:datafromlms','');
  10088. // Give a child element <adlcp:masteryscore> to the <item> element.
  10089. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10090. $my_item->appendChild($my_masteryscore);
  10091. // Attach this item to the organization element or hits parent if there is one.
  10092. if (!empty($item->parent) && $item->parent != 0) {
  10093. $children = $organization->childNodes;
  10094. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10095. if (is_object($possible_parent)) {
  10096. $possible_parent->appendChild($my_item);
  10097. } else {
  10098. if ($this->debug > 0) {
  10099. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10100. }
  10101. }
  10102. } else {
  10103. if ($this->debug > 0) {
  10104. error_log('No parent');
  10105. }
  10106. $organization->appendChild($my_item);
  10107. }
  10108. // Get the path of the file(s) from the course directory root.
  10109. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10110. $my_xml_file_path = $my_file_path;
  10111. if (!empty($path_to_remove)) {
  10112. // From docs
  10113. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10114. // From quiz
  10115. if ($this->ref === 'chamilo_scorm_export') {
  10116. $path_to_remove = 'scorm/'.$this->path.'/';
  10117. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10118. }
  10119. }
  10120. $my_sub_dir = dirname($my_file_path);
  10121. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10122. $my_xml_sub_dir = $my_sub_dir;
  10123. // Give a <resource> child to the <resources> element
  10124. $my_resource = $xmldoc->createElement('resource');
  10125. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10126. $my_resource->setAttribute('type', 'webcontent');
  10127. $my_resource->setAttribute('href', $my_xml_file_path);
  10128. // adlcp:scormtype can be either 'sco' or 'asset'.
  10129. if ($item->type === 'sco') {
  10130. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10131. } else {
  10132. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10133. }
  10134. // xml:base is the base directory to find the files declared in this resource.
  10135. $my_resource->setAttribute('xml:base', '');
  10136. // Give a <file> child to the <resource> element.
  10137. $my_file = $xmldoc->createElement('file');
  10138. $my_file->setAttribute('href', $my_xml_file_path);
  10139. $my_resource->appendChild($my_file);
  10140. // Dependency to other files - not yet supported.
  10141. $i = 1;
  10142. if ($inc_docs) {
  10143. foreach ($inc_docs as $doc_info) {
  10144. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10145. continue;
  10146. }
  10147. $my_dep = $xmldoc->createElement('resource');
  10148. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10149. $my_dep->setAttribute('identifier', $res_id);
  10150. $my_dep->setAttribute('type', 'webcontent');
  10151. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10152. $my_dep_file = $xmldoc->createElement('file');
  10153. // Check type of URL.
  10154. if ($doc_info[1] == 'remote') {
  10155. // Remote file. Save url as is.
  10156. $my_dep_file->setAttribute('href', $doc_info[0]);
  10157. $my_dep->setAttribute('xml:base', '');
  10158. } elseif ($doc_info[1] === 'local') {
  10159. switch ($doc_info[2]) {
  10160. case 'url':
  10161. // Local URL - save path as url for now, don't zip file.
  10162. $abs_path = api_get_path(SYS_PATH).
  10163. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10164. $current_dir = dirname($abs_path);
  10165. $current_dir = str_replace('\\', '/', $current_dir);
  10166. $file_path = realpath($abs_path);
  10167. $file_path = str_replace('\\', '/', $file_path);
  10168. $my_dep_file->setAttribute('href', $file_path);
  10169. $my_dep->setAttribute('xml:base', '');
  10170. if (strstr($file_path, $main_path) !== false) {
  10171. // The calculated real path is really inside Chamilo's root path.
  10172. // Reduce file path to what's under the DocumentRoot.
  10173. $replace = $file_path;
  10174. $file_path = substr($file_path, strlen($root_path) - 1);
  10175. $destinationFile = $file_path;
  10176. if (strstr($file_path, 'upload/users') !== false) {
  10177. $pos = strpos($file_path, 'my_files/');
  10178. if ($pos !== false) {
  10179. $onlyDirectory = str_replace(
  10180. 'upload/users/',
  10181. '',
  10182. substr($file_path, $pos, strlen($file_path))
  10183. );
  10184. }
  10185. $replace = $onlyDirectory;
  10186. $destinationFile = $replace;
  10187. }
  10188. $zip_files_abs[] = $file_path;
  10189. $link_updates[$my_file_path][] = [
  10190. 'orig' => $doc_info[0],
  10191. 'dest' => $destinationFile,
  10192. 'replace' => $replace,
  10193. ];
  10194. $my_dep_file->setAttribute('href', $file_path);
  10195. $my_dep->setAttribute('xml:base', '');
  10196. } elseif (empty($file_path)) {
  10197. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10198. $file_path = str_replace('//', '/', $file_path);
  10199. if (file_exists($file_path)) {
  10200. // We get the relative path.
  10201. $file_path = substr($file_path, strlen($current_dir));
  10202. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10203. $link_updates[$my_file_path][] = [
  10204. 'orig' => $doc_info[0],
  10205. 'dest' => $file_path,
  10206. ];
  10207. $my_dep_file->setAttribute('href', $file_path);
  10208. $my_dep->setAttribute('xml:base', '');
  10209. }
  10210. }
  10211. break;
  10212. case 'abs':
  10213. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10214. $my_dep_file->setAttribute('href', $doc_info[0]);
  10215. $my_dep->setAttribute('xml:base', '');
  10216. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10217. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10218. $abs_img_path_without_subdir = $doc_info[0];
  10219. $relp = api_get_path(REL_PATH); // The url-append config param.
  10220. $pos = strpos($abs_img_path_without_subdir, $relp);
  10221. if ($pos === 0) {
  10222. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10223. }
  10224. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10225. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10226. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10227. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10228. // Check if the current document is in that path.
  10229. if (strstr($file_path, $cur_path) !== false) {
  10230. $destinationFile = substr($file_path, strlen($cur_path));
  10231. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10232. $fileToTest = $cur_path.$my_file_path;
  10233. if (!empty($path_to_remove)) {
  10234. $fileToTest = str_replace(
  10235. $path_to_remove.'/',
  10236. $path_to_replace,
  10237. $cur_path.$my_file_path
  10238. );
  10239. }
  10240. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10241. // Put the current document in the zip (this array is the array
  10242. // that will manage documents already in the course folder - relative).
  10243. $zip_files[] = $filePathNoCoursePart;
  10244. // Update the links to the current document in the
  10245. // containing document (make them relative).
  10246. $link_updates[$my_file_path][] = [
  10247. 'orig' => $doc_info[0],
  10248. 'dest' => $destinationFile,
  10249. 'replace' => $relative_path,
  10250. ];
  10251. $my_dep_file->setAttribute('href', $file_path);
  10252. $my_dep->setAttribute('xml:base', '');
  10253. } elseif (strstr($file_path, $main_path) !== false) {
  10254. // The calculated real path is really inside Chamilo's root path.
  10255. // Reduce file path to what's under the DocumentRoot.
  10256. $file_path = substr($file_path, strlen($root_path));
  10257. $zip_files_abs[] = $file_path;
  10258. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10259. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10260. $my_dep->setAttribute('xml:base', '');
  10261. } elseif (empty($file_path)) {
  10262. // Probably this is an image inside "/main" directory
  10263. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10264. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10265. if (file_exists($file_path)) {
  10266. if (strstr($file_path, 'main/default_course_document') !== false) {
  10267. // We get the relative path.
  10268. $pos = strpos($file_path, 'main/default_course_document/');
  10269. if ($pos !== false) {
  10270. $onlyDirectory = str_replace(
  10271. 'main/default_course_document/',
  10272. '',
  10273. substr($file_path, $pos, strlen($file_path))
  10274. );
  10275. }
  10276. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10277. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10278. $zip_files_abs[] = $fileAbs;
  10279. $link_updates[$my_file_path][] = [
  10280. 'orig' => $doc_info[0],
  10281. 'dest' => $destinationFile,
  10282. ];
  10283. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10284. $my_dep->setAttribute('xml:base', '');
  10285. }
  10286. }
  10287. }
  10288. break;
  10289. case 'rel':
  10290. // Path relative to the current document.
  10291. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10292. if (substr($doc_info[0], 0, 2) === '..') {
  10293. // Relative path going up.
  10294. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10295. $current_dir = str_replace('\\', '/', $current_dir);
  10296. $file_path = realpath($current_dir.$doc_info[0]);
  10297. $file_path = str_replace('\\', '/', $file_path);
  10298. if (strstr($file_path, $main_path) !== false) {
  10299. // The calculated real path is really inside Chamilo's root path.
  10300. // Reduce file path to what's under the DocumentRoot.
  10301. $file_path = substr($file_path, strlen($root_path));
  10302. $zip_files_abs[] = $file_path;
  10303. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10304. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10305. $my_dep->setAttribute('xml:base', '');
  10306. }
  10307. } else {
  10308. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10309. $my_dep_file->setAttribute('href', $doc_info[0]);
  10310. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10311. }
  10312. break;
  10313. default:
  10314. $my_dep_file->setAttribute('href', $doc_info[0]);
  10315. $my_dep->setAttribute('xml:base', '');
  10316. break;
  10317. }
  10318. }
  10319. $my_dep->appendChild($my_dep_file);
  10320. $resources->appendChild($my_dep);
  10321. $dependency = $xmldoc->createElement('dependency');
  10322. $dependency->setAttribute('identifierref', $res_id);
  10323. $my_resource->appendChild($dependency);
  10324. $i++;
  10325. }
  10326. }
  10327. $resources->appendChild($my_resource);
  10328. $zip_files[] = $my_file_path;
  10329. } else {
  10330. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10331. switch ($item->type) {
  10332. case TOOL_LINK:
  10333. $my_item = $xmldoc->createElement('item');
  10334. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10335. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10336. $my_item->setAttribute('isvisible', 'true');
  10337. // Give a child element <title> to the <item> element.
  10338. $my_title = $xmldoc->createElement(
  10339. 'title',
  10340. htmlspecialchars(
  10341. api_utf8_encode($item->get_title()),
  10342. ENT_QUOTES,
  10343. 'UTF-8'
  10344. )
  10345. );
  10346. $my_item->appendChild($my_title);
  10347. // Give a child element <adlcp:prerequisites> to the <item> element.
  10348. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10349. $my_prereqs->setAttribute('type', 'aicc_script');
  10350. $my_item->appendChild($my_prereqs);
  10351. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10352. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10353. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10354. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10355. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10356. //$xmldoc->createElement('adlcp:datafromlms', '');
  10357. // Give a child element <adlcp:masteryscore> to the <item> element.
  10358. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10359. $my_item->appendChild($my_masteryscore);
  10360. // Attach this item to the organization element or its parent if there is one.
  10361. if (!empty($item->parent) && $item->parent != 0) {
  10362. $children = $organization->childNodes;
  10363. for ($i = 0; $i < $children->length; $i++) {
  10364. $item_temp = $children->item($i);
  10365. if ($item_temp->nodeName == 'item') {
  10366. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10367. $item_temp->appendChild($my_item);
  10368. }
  10369. }
  10370. }
  10371. } else {
  10372. $organization->appendChild($my_item);
  10373. }
  10374. $my_file_path = 'link_'.$item->get_id().'.html';
  10375. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10376. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10377. $rs = Database::query($sql);
  10378. if ($link = Database::fetch_array($rs)) {
  10379. $url = $link['url'];
  10380. $title = stripslashes($link['title']);
  10381. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10382. $my_xml_file_path = $my_file_path;
  10383. $my_sub_dir = dirname($my_file_path);
  10384. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10385. $my_xml_sub_dir = $my_sub_dir;
  10386. // Give a <resource> child to the <resources> element.
  10387. $my_resource = $xmldoc->createElement('resource');
  10388. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10389. $my_resource->setAttribute('type', 'webcontent');
  10390. $my_resource->setAttribute('href', $my_xml_file_path);
  10391. // adlcp:scormtype can be either 'sco' or 'asset'.
  10392. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10393. // xml:base is the base directory to find the files declared in this resource.
  10394. $my_resource->setAttribute('xml:base', '');
  10395. // give a <file> child to the <resource> element.
  10396. $my_file = $xmldoc->createElement('file');
  10397. $my_file->setAttribute('href', $my_xml_file_path);
  10398. $my_resource->appendChild($my_file);
  10399. $resources->appendChild($my_resource);
  10400. }
  10401. break;
  10402. case TOOL_QUIZ:
  10403. $exe_id = $item->path;
  10404. // Should be using ref when everything will be cleaned up in this regard.
  10405. $exe = new Exercise();
  10406. $exe->read($exe_id);
  10407. $my_item = $xmldoc->createElement('item');
  10408. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10409. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10410. $my_item->setAttribute('isvisible', 'true');
  10411. // Give a child element <title> to the <item> element.
  10412. $my_title = $xmldoc->createElement(
  10413. 'title',
  10414. htmlspecialchars(
  10415. api_utf8_encode($item->get_title()),
  10416. ENT_QUOTES,
  10417. 'UTF-8'
  10418. )
  10419. );
  10420. $my_item->appendChild($my_title);
  10421. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10422. $my_item->appendChild($my_max_score);
  10423. // Give a child element <adlcp:prerequisites> to the <item> element.
  10424. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10425. $my_prereqs->setAttribute('type', 'aicc_script');
  10426. $my_item->appendChild($my_prereqs);
  10427. // Give a child element <adlcp:masteryscore> to the <item> element.
  10428. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10429. $my_item->appendChild($my_masteryscore);
  10430. // Attach this item to the organization element or hits parent if there is one.
  10431. if (!empty($item->parent) && $item->parent != 0) {
  10432. $children = $organization->childNodes;
  10433. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10434. if ($possible_parent) {
  10435. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10436. $possible_parent->appendChild($my_item);
  10437. }
  10438. }
  10439. } else {
  10440. $organization->appendChild($my_item);
  10441. }
  10442. // Get the path of the file(s) from the course directory root
  10443. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10444. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10445. // Write the contents of the exported exercise into a (big) html file
  10446. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10447. $scormExercise = new ScormExercise($exe, true);
  10448. $contents = $scormExercise->export();
  10449. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10450. $res = file_put_contents($tmp_file_path, $contents);
  10451. if ($res === false) {
  10452. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10453. }
  10454. $files_cleanup[] = $tmp_file_path;
  10455. $my_xml_file_path = $my_file_path;
  10456. $my_sub_dir = dirname($my_file_path);
  10457. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10458. $my_xml_sub_dir = $my_sub_dir;
  10459. // Give a <resource> child to the <resources> element.
  10460. $my_resource = $xmldoc->createElement('resource');
  10461. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10462. $my_resource->setAttribute('type', 'webcontent');
  10463. $my_resource->setAttribute('href', $my_xml_file_path);
  10464. // adlcp:scormtype can be either 'sco' or 'asset'.
  10465. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10466. // xml:base is the base directory to find the files declared in this resource.
  10467. $my_resource->setAttribute('xml:base', '');
  10468. // Give a <file> child to the <resource> element.
  10469. $my_file = $xmldoc->createElement('file');
  10470. $my_file->setAttribute('href', $my_xml_file_path);
  10471. $my_resource->appendChild($my_file);
  10472. // Get included docs.
  10473. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10474. // Dependency to other files - not yet supported.
  10475. $i = 1;
  10476. foreach ($inc_docs as $doc_info) {
  10477. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10478. continue;
  10479. }
  10480. $my_dep = $xmldoc->createElement('resource');
  10481. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10482. $my_dep->setAttribute('identifier', $res_id);
  10483. $my_dep->setAttribute('type', 'webcontent');
  10484. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10485. $my_dep_file = $xmldoc->createElement('file');
  10486. // Check type of URL.
  10487. if ($doc_info[1] == 'remote') {
  10488. // Remote file. Save url as is.
  10489. $my_dep_file->setAttribute('href', $doc_info[0]);
  10490. $my_dep->setAttribute('xml:base', '');
  10491. } elseif ($doc_info[1] == 'local') {
  10492. switch ($doc_info[2]) {
  10493. case 'url': // Local URL - save path as url for now, don't zip file.
  10494. // Save file but as local file (retrieve from URL).
  10495. $abs_path = api_get_path(SYS_PATH).
  10496. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10497. $current_dir = dirname($abs_path);
  10498. $current_dir = str_replace('\\', '/', $current_dir);
  10499. $file_path = realpath($abs_path);
  10500. $file_path = str_replace('\\', '/', $file_path);
  10501. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10502. $my_dep->setAttribute('xml:base', '');
  10503. if (strstr($file_path, $main_path) !== false) {
  10504. // The calculated real path is really inside the chamilo root path.
  10505. // Reduce file path to what's under the DocumentRoot.
  10506. $file_path = substr($file_path, strlen($root_path));
  10507. $zip_files_abs[] = $file_path;
  10508. $link_updates[$my_file_path][] = [
  10509. 'orig' => $doc_info[0],
  10510. 'dest' => 'document/'.$file_path,
  10511. ];
  10512. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10513. $my_dep->setAttribute('xml:base', '');
  10514. } elseif (empty($file_path)) {
  10515. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10516. $file_path = str_replace('//', '/', $file_path);
  10517. if (file_exists($file_path)) {
  10518. $file_path = substr($file_path, strlen($current_dir));
  10519. // We get the relative path.
  10520. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10521. $link_updates[$my_file_path][] = [
  10522. 'orig' => $doc_info[0],
  10523. 'dest' => 'document/'.$file_path,
  10524. ];
  10525. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10526. $my_dep->setAttribute('xml:base', '');
  10527. }
  10528. }
  10529. break;
  10530. case 'abs':
  10531. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10532. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10533. $current_dir = str_replace('\\', '/', $current_dir);
  10534. $file_path = realpath($doc_info[0]);
  10535. $file_path = str_replace('\\', '/', $file_path);
  10536. $my_dep_file->setAttribute('href', $file_path);
  10537. $my_dep->setAttribute('xml:base', '');
  10538. if (strstr($file_path, $main_path) !== false) {
  10539. // The calculated real path is really inside the chamilo root path.
  10540. // Reduce file path to what's under the DocumentRoot.
  10541. $file_path = substr($file_path, strlen($root_path));
  10542. $zip_files_abs[] = $file_path;
  10543. $link_updates[$my_file_path][] = [
  10544. 'orig' => $doc_info[0],
  10545. 'dest' => $file_path,
  10546. ];
  10547. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10548. $my_dep->setAttribute('xml:base', '');
  10549. } elseif (empty($file_path)) {
  10550. $docSysPartPath = str_replace(
  10551. api_get_path(REL_COURSE_PATH),
  10552. '',
  10553. $doc_info[0]
  10554. );
  10555. $docSysPartPathNoCourseCode = str_replace(
  10556. $_course['directory'].'/',
  10557. '',
  10558. $docSysPartPath
  10559. );
  10560. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10561. if (file_exists($docSysPath)) {
  10562. $file_path = $docSysPartPathNoCourseCode;
  10563. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10564. $link_updates[$my_file_path][] = [
  10565. 'orig' => $doc_info[0],
  10566. 'dest' => $file_path,
  10567. ];
  10568. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10569. $my_dep->setAttribute('xml:base', '');
  10570. }
  10571. }
  10572. break;
  10573. case 'rel':
  10574. // Path relative to the current document. Save xml:base as current document's
  10575. // directory and save file in zip as subdir.file_path
  10576. if (substr($doc_info[0], 0, 2) === '..') {
  10577. // Relative path going up.
  10578. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10579. $current_dir = str_replace('\\', '/', $current_dir);
  10580. $file_path = realpath($current_dir.$doc_info[0]);
  10581. $file_path = str_replace('\\', '/', $file_path);
  10582. if (strstr($file_path, $main_path) !== false) {
  10583. // The calculated real path is really inside Chamilo's root path.
  10584. // Reduce file path to what's under the DocumentRoot.
  10585. $file_path = substr($file_path, strlen($root_path));
  10586. $file_path_dest = $file_path;
  10587. // File path is courses/CHAMILO/document/....
  10588. $info_file_path = explode('/', $file_path);
  10589. if ($info_file_path[0] == 'courses') {
  10590. // Add character "/" in file path.
  10591. $file_path_dest = 'document/'.$file_path;
  10592. }
  10593. $zip_files_abs[] = $file_path;
  10594. $link_updates[$my_file_path][] = [
  10595. 'orig' => $doc_info[0],
  10596. 'dest' => $file_path_dest,
  10597. ];
  10598. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10599. $my_dep->setAttribute('xml:base', '');
  10600. }
  10601. } else {
  10602. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10603. $my_dep_file->setAttribute('href', $doc_info[0]);
  10604. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10605. }
  10606. break;
  10607. default:
  10608. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10609. $my_dep->setAttribute('xml:base', '');
  10610. break;
  10611. }
  10612. }
  10613. $my_dep->appendChild($my_dep_file);
  10614. $resources->appendChild($my_dep);
  10615. $dependency = $xmldoc->createElement('dependency');
  10616. $dependency->setAttribute('identifierref', $res_id);
  10617. $my_resource->appendChild($dependency);
  10618. $i++;
  10619. }
  10620. $resources->appendChild($my_resource);
  10621. $zip_files[] = $my_file_path;
  10622. break;
  10623. default:
  10624. // Get the path of the file(s) from the course directory root
  10625. $my_file_path = 'non_exportable.html';
  10626. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10627. $my_xml_file_path = $my_file_path;
  10628. $my_sub_dir = dirname($my_file_path);
  10629. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10630. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10631. $my_xml_sub_dir = $my_sub_dir;
  10632. // Give a <resource> child to the <resources> element.
  10633. $my_resource = $xmldoc->createElement('resource');
  10634. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10635. $my_resource->setAttribute('type', 'webcontent');
  10636. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10637. // adlcp:scormtype can be either 'sco' or 'asset'.
  10638. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10639. // xml:base is the base directory to find the files declared in this resource.
  10640. $my_resource->setAttribute('xml:base', '');
  10641. // Give a <file> child to the <resource> element.
  10642. $my_file = $xmldoc->createElement('file');
  10643. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10644. $my_resource->appendChild($my_file);
  10645. $resources->appendChild($my_resource);
  10646. break;
  10647. }
  10648. }
  10649. }
  10650. $organizations->appendChild($organization);
  10651. $root->appendChild($organizations);
  10652. $root->appendChild($resources);
  10653. $xmldoc->appendChild($root);
  10654. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10655. // then add the file to the zip, then destroy the file (this is done automatically).
  10656. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10657. foreach ($zip_files as $file_path) {
  10658. if (empty($file_path)) {
  10659. continue;
  10660. }
  10661. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10662. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10663. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10664. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10665. }
  10666. $this->create_path($dest_file);
  10667. @copy($filePath, $dest_file);
  10668. // Check if the file needs a link update.
  10669. if (in_array($file_path, array_keys($link_updates))) {
  10670. $string = file_get_contents($dest_file);
  10671. unlink($dest_file);
  10672. foreach ($link_updates[$file_path] as $old_new) {
  10673. // This is an ugly hack that allows .flv files to be found by the flv player that
  10674. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10675. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10676. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10677. if (substr($old_new['dest'], -3) === 'flv' &&
  10678. substr($old_new['dest'], 0, 5) === 'main/'
  10679. ) {
  10680. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10681. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10682. substr($old_new['dest'], 0, 6) === 'video/'
  10683. ) {
  10684. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10685. }
  10686. // Fix to avoid problems with default_course_document
  10687. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10688. $newDestination = $old_new['dest'];
  10689. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10690. $newDestination = $old_new['replace'];
  10691. }
  10692. } else {
  10693. $newDestination = str_replace('document/', '', $old_new['dest']);
  10694. }
  10695. $string = str_replace($old_new['orig'], $newDestination, $string);
  10696. // Add files inside the HTMLs
  10697. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10698. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10699. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10700. copy(
  10701. $sys_course_path.$new_path,
  10702. $destinationFile
  10703. );
  10704. }
  10705. }
  10706. file_put_contents($dest_file, $string);
  10707. }
  10708. if (file_exists($filePath) && $copyAll) {
  10709. $extension = $this->get_extension($filePath);
  10710. if (in_array($extension, ['html', 'html'])) {
  10711. $containerOrigin = dirname($filePath);
  10712. $containerDestination = dirname($dest_file);
  10713. $finder = new Finder();
  10714. $finder->files()->in($containerOrigin)
  10715. ->notName('*_DELETED_*')
  10716. ->exclude('share_folder')
  10717. ->exclude('chat_files')
  10718. ->exclude('certificates')
  10719. ;
  10720. if (is_dir($containerOrigin) &&
  10721. is_dir($containerDestination)
  10722. ) {
  10723. $fs = new Filesystem();
  10724. $fs->mirror(
  10725. $containerOrigin,
  10726. $containerDestination,
  10727. $finder
  10728. );
  10729. }
  10730. }
  10731. }
  10732. }
  10733. foreach ($zip_files_abs as $file_path) {
  10734. if (empty($file_path)) {
  10735. continue;
  10736. }
  10737. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10738. continue;
  10739. }
  10740. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10741. if (strstr($file_path, 'upload/users') !== false) {
  10742. $pos = strpos($file_path, 'my_files/');
  10743. if ($pos !== false) {
  10744. $onlyDirectory = str_replace(
  10745. 'upload/users/',
  10746. '',
  10747. substr($file_path, $pos, strlen($file_path))
  10748. );
  10749. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10750. }
  10751. }
  10752. if (strstr($file_path, 'default_course_document/') !== false) {
  10753. $replace = str_replace('/main', '', $file_path);
  10754. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10755. }
  10756. if (empty($dest_file)) {
  10757. continue;
  10758. }
  10759. $this->create_path($dest_file);
  10760. copy($main_path.$file_path, $dest_file);
  10761. // Check if the file needs a link update.
  10762. if (in_array($file_path, array_keys($link_updates))) {
  10763. $string = file_get_contents($dest_file);
  10764. unlink($dest_file);
  10765. foreach ($link_updates[$file_path] as $old_new) {
  10766. // This is an ugly hack that allows .flv files to be found by the flv player that
  10767. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10768. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10769. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10770. if (substr($old_new['dest'], -3) == 'flv' &&
  10771. substr($old_new['dest'], 0, 5) == 'main/'
  10772. ) {
  10773. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10774. }
  10775. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10776. }
  10777. file_put_contents($dest_file, $string);
  10778. }
  10779. }
  10780. if (is_array($links_to_create)) {
  10781. foreach ($links_to_create as $file => $link) {
  10782. $content = '<!DOCTYPE html><head>
  10783. <meta charset="'.api_get_language_isocode().'" />
  10784. <title>'.$link['title'].'</title>
  10785. </head>
  10786. <body dir="'.api_get_text_direction().'">
  10787. <div style="text-align:center">
  10788. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10789. </body>
  10790. </html>';
  10791. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10792. }
  10793. }
  10794. // Add non exportable message explanation.
  10795. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10796. $file_content = '<!DOCTYPE html><head>
  10797. <meta charset="'.api_get_language_isocode().'" />
  10798. <title>'.$lang_not_exportable.'</title>
  10799. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10800. </head>
  10801. <body dir="'.api_get_text_direction().'">';
  10802. $file_content .=
  10803. <<<EOD
  10804. <style>
  10805. .error-message {
  10806. font-family: arial, verdana, helvetica, sans-serif;
  10807. border-width: 1px;
  10808. border-style: solid;
  10809. left: 50%;
  10810. margin: 10px auto;
  10811. min-height: 30px;
  10812. padding: 5px;
  10813. right: 50%;
  10814. width: 500px;
  10815. background-color: #FFD1D1;
  10816. border-color: #FF0000;
  10817. color: #000;
  10818. }
  10819. </style>
  10820. <body>
  10821. <div class="error-message">
  10822. $lang_not_exportable
  10823. </div>
  10824. </body>
  10825. </html>
  10826. EOD;
  10827. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10828. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10829. }
  10830. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10831. // Add the extra files that go along with a SCORM package.
  10832. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10833. $fs = new Filesystem();
  10834. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10835. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10836. $manifest = @$xmldoc->saveXML();
  10837. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10838. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10839. $zip_folder->add(
  10840. $archivePath.'/'.$temp_dir_short,
  10841. PCLZIP_OPT_REMOVE_PATH,
  10842. $archivePath.'/'.$temp_dir_short.'/'
  10843. );
  10844. // Clean possible temporary files.
  10845. foreach ($files_cleanup as $file) {
  10846. $res = unlink($file);
  10847. if ($res === false) {
  10848. error_log(
  10849. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10850. 0
  10851. );
  10852. }
  10853. }
  10854. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10855. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10856. }
  10857. /**
  10858. * @param int $lp_id
  10859. *
  10860. * @return bool
  10861. */
  10862. public function scorm_export_to_pdf($lp_id)
  10863. {
  10864. $lp_id = (int) $lp_id;
  10865. $files_to_export = [];
  10866. $sessionId = api_get_session_id();
  10867. $course_data = api_get_course_info($this->cc);
  10868. if (!empty($course_data)) {
  10869. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10870. $list = self::get_flat_ordered_items_list($lp_id);
  10871. if (!empty($list)) {
  10872. foreach ($list as $item_id) {
  10873. $item = $this->items[$item_id];
  10874. switch ($item->type) {
  10875. case 'document':
  10876. // Getting documents from a LP with chamilo documents
  10877. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10878. // Try loading document from the base course.
  10879. if (empty($file_data) && !empty($sessionId)) {
  10880. $file_data = DocumentManager::get_document_data_by_id(
  10881. $item->path,
  10882. $this->cc,
  10883. false,
  10884. 0
  10885. );
  10886. }
  10887. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10888. if (file_exists($file_path)) {
  10889. $files_to_export[] = [
  10890. 'title' => $item->get_title(),
  10891. 'path' => $file_path,
  10892. ];
  10893. }
  10894. break;
  10895. case 'asset': //commes from a scorm package generated by chamilo
  10896. case 'sco':
  10897. $file_path = $scorm_path.'/'.$item->path;
  10898. if (file_exists($file_path)) {
  10899. $files_to_export[] = [
  10900. 'title' => $item->get_title(),
  10901. 'path' => $file_path,
  10902. ];
  10903. }
  10904. break;
  10905. case 'dir':
  10906. $files_to_export[] = [
  10907. 'title' => $item->get_title(),
  10908. 'path' => null,
  10909. ];
  10910. break;
  10911. }
  10912. }
  10913. }
  10914. $pdf = new PDF();
  10915. $result = $pdf->html_to_pdf(
  10916. $files_to_export,
  10917. $this->name,
  10918. $this->cc,
  10919. true,
  10920. true,
  10921. true,
  10922. $this->get_name()
  10923. );
  10924. return $result;
  10925. }
  10926. return false;
  10927. }
  10928. /**
  10929. * Temp function to be moved in main_api or the best place around for this.
  10930. * Creates a file path if it doesn't exist.
  10931. *
  10932. * @param string $path
  10933. */
  10934. public function create_path($path)
  10935. {
  10936. $path_bits = explode('/', dirname($path));
  10937. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10938. $path_built = IS_WINDOWS_OS ? '' : '/';
  10939. foreach ($path_bits as $bit) {
  10940. if (!empty($bit)) {
  10941. $new_path = $path_built.$bit;
  10942. if (is_dir($new_path)) {
  10943. $path_built = $new_path.'/';
  10944. } else {
  10945. mkdir($new_path, api_get_permissions_for_new_directories());
  10946. $path_built = $new_path.'/';
  10947. }
  10948. }
  10949. }
  10950. }
  10951. /**
  10952. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10953. *
  10954. * @return bool The results of the unlink function, or false if there was no image to start with
  10955. */
  10956. public function delete_lp_image()
  10957. {
  10958. $img = $this->get_preview_image();
  10959. if ($img != '') {
  10960. $del_file = $this->get_preview_image_path(null, 'sys');
  10961. if (isset($del_file) && file_exists($del_file)) {
  10962. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10963. if (file_exists($del_file_2)) {
  10964. unlink($del_file_2);
  10965. }
  10966. $this->set_preview_image('');
  10967. return @unlink($del_file);
  10968. }
  10969. }
  10970. return false;
  10971. }
  10972. /**
  10973. * Uploads an author image to the upload/learning_path/images directory.
  10974. *
  10975. * @param array The image array, coming from the $_FILES superglobal
  10976. *
  10977. * @return bool True on success, false on error
  10978. */
  10979. public function upload_image($image_array)
  10980. {
  10981. if (!empty($image_array['name'])) {
  10982. $upload_ok = process_uploaded_file($image_array);
  10983. $has_attachment = true;
  10984. }
  10985. if ($upload_ok && $has_attachment) {
  10986. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10987. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10988. $updir = $sys_course_path.$courseDir;
  10989. // Try to add an extension to the file if it hasn't one.
  10990. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10991. if (filter_extension($new_file_name)) {
  10992. $file_extension = explode('.', $image_array['name']);
  10993. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10994. $filename = uniqid('');
  10995. $new_file_name = $filename.'.'.$file_extension;
  10996. $new_path = $updir.'/'.$new_file_name;
  10997. // Resize the image.
  10998. $temp = new Image($image_array['tmp_name']);
  10999. $temp->resize(104);
  11000. $result = $temp->send_image($new_path);
  11001. // Storing the image filename.
  11002. if ($result) {
  11003. $this->set_preview_image($new_file_name);
  11004. //Resize to 64px to use on course homepage
  11005. $temp->resize(64);
  11006. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11007. return true;
  11008. }
  11009. }
  11010. }
  11011. return false;
  11012. }
  11013. /**
  11014. * @param int $lp_id
  11015. * @param string $status
  11016. */
  11017. public function set_autolaunch($lp_id, $status)
  11018. {
  11019. $course_id = api_get_course_int_id();
  11020. $lp_id = (int) $lp_id;
  11021. $status = (int) $status;
  11022. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11023. // Setting everything to autolaunch = 0
  11024. $attributes['autolaunch'] = 0;
  11025. $where = [
  11026. 'session_id = ? AND c_id = ? ' => [
  11027. api_get_session_id(),
  11028. $course_id,
  11029. ],
  11030. ];
  11031. Database::update($lp_table, $attributes, $where);
  11032. if ($status == 1) {
  11033. //Setting my lp_id to autolaunch = 1
  11034. $attributes['autolaunch'] = 1;
  11035. $where = [
  11036. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11037. $lp_id,
  11038. api_get_session_id(),
  11039. $course_id,
  11040. ],
  11041. ];
  11042. Database::update($lp_table, $attributes, $where);
  11043. }
  11044. }
  11045. /**
  11046. * Gets previous_item_id for the next element of the lp_item table.
  11047. *
  11048. * @author Isaac flores paz
  11049. *
  11050. * @return int Previous item ID
  11051. */
  11052. public function select_previous_item_id()
  11053. {
  11054. $course_id = api_get_course_int_id();
  11055. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11056. // Get the max order of the items
  11057. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11058. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11059. $rs_max_order = Database::query($sql);
  11060. $row_max_order = Database::fetch_object($rs_max_order);
  11061. $max_order = $row_max_order->display_order;
  11062. // Get the previous item ID
  11063. $sql = "SELECT iid as previous FROM $table_lp_item
  11064. WHERE
  11065. c_id = $course_id AND
  11066. lp_id = ".$this->lp_id." AND
  11067. display_order = '$max_order' ";
  11068. $rs_max = Database::query($sql);
  11069. $row_max = Database::fetch_object($rs_max);
  11070. // Return the previous item ID
  11071. return $row_max->previous;
  11072. }
  11073. /**
  11074. * Copies an LP.
  11075. */
  11076. public function copy()
  11077. {
  11078. // Course builder
  11079. $cb = new CourseBuilder();
  11080. //Setting tools that will be copied
  11081. $cb->set_tools_to_build(['learnpaths']);
  11082. //Setting elements that will be copied
  11083. $cb->set_tools_specific_id_list(
  11084. ['learnpaths' => [$this->lp_id]]
  11085. );
  11086. $course = $cb->build();
  11087. //Course restorer
  11088. $course_restorer = new CourseRestorer($course);
  11089. $course_restorer->set_add_text_in_items(true);
  11090. $course_restorer->set_tool_copy_settings(
  11091. ['learnpaths' => ['reset_dates' => true]]
  11092. );
  11093. $course_restorer->restore(
  11094. api_get_course_id(),
  11095. api_get_session_id(),
  11096. false,
  11097. false
  11098. );
  11099. }
  11100. /**
  11101. * Verify document size.
  11102. *
  11103. * @param string $s
  11104. *
  11105. * @return bool
  11106. */
  11107. public static function verify_document_size($s)
  11108. {
  11109. $post_max = ini_get('post_max_size');
  11110. if (substr($post_max, -1, 1) == 'M') {
  11111. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11112. } elseif (substr($post_max, -1, 1) == 'G') {
  11113. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11114. }
  11115. $upl_max = ini_get('upload_max_filesize');
  11116. if (substr($upl_max, -1, 1) == 'M') {
  11117. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11118. } elseif (substr($upl_max, -1, 1) == 'G') {
  11119. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11120. }
  11121. $documents_total_space = DocumentManager::documents_total_space();
  11122. $course_max_space = DocumentManager::get_course_quota();
  11123. $total_size = filesize($s) + $documents_total_space;
  11124. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11125. return true;
  11126. }
  11127. return false;
  11128. }
  11129. /**
  11130. * Clear LP prerequisites.
  11131. */
  11132. public function clear_prerequisites()
  11133. {
  11134. $course_id = $this->get_course_int_id();
  11135. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11136. $lp_id = $this->get_id();
  11137. // Cleaning prerequisites
  11138. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11139. WHERE c_id = $course_id AND lp_id = $lp_id";
  11140. Database::query($sql);
  11141. // Cleaning mastery score for exercises
  11142. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11143. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11144. Database::query($sql);
  11145. }
  11146. public function set_previous_step_as_prerequisite_for_all_items()
  11147. {
  11148. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11149. $course_id = $this->get_course_int_id();
  11150. $lp_id = $this->get_id();
  11151. if (!empty($this->items)) {
  11152. $previous_item_id = null;
  11153. $previous_item_max = 0;
  11154. $previous_item_type = null;
  11155. $last_item_not_dir = null;
  11156. $last_item_not_dir_type = null;
  11157. $last_item_not_dir_max = null;
  11158. foreach ($this->ordered_items as $itemId) {
  11159. $item = $this->getItem($itemId);
  11160. // if there was a previous item... (otherwise jump to set it)
  11161. if (!empty($previous_item_id)) {
  11162. $current_item_id = $item->get_id(); //save current id
  11163. if ($item->get_type() != 'dir') {
  11164. // Current item is not a folder, so it qualifies to get a prerequisites
  11165. if ($last_item_not_dir_type == 'quiz') {
  11166. // if previous is quiz, mark its max score as default score to be achieved
  11167. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11168. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11169. Database::query($sql);
  11170. }
  11171. // now simply update the prerequisite to set it to the last non-chapter item
  11172. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11173. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11174. Database::query($sql);
  11175. // record item as 'non-chapter' reference
  11176. $last_item_not_dir = $item->get_id();
  11177. $last_item_not_dir_type = $item->get_type();
  11178. $last_item_not_dir_max = $item->get_max();
  11179. }
  11180. } else {
  11181. if ($item->get_type() != 'dir') {
  11182. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11183. $last_item_not_dir = $item->get_id();
  11184. $last_item_not_dir_type = $item->get_type();
  11185. $last_item_not_dir_max = $item->get_max();
  11186. }
  11187. }
  11188. // Saving the item as "previous item" for the next loop
  11189. $previous_item_id = $item->get_id();
  11190. $previous_item_max = $item->get_max();
  11191. $previous_item_type = $item->get_type();
  11192. }
  11193. }
  11194. }
  11195. /**
  11196. * @param array $params
  11197. *
  11198. * @throws \Doctrine\ORM\OptimisticLockException
  11199. *
  11200. * @return int
  11201. */
  11202. public static function createCategory($params)
  11203. {
  11204. $em = Database::getManager();
  11205. $item = new CLpCategory();
  11206. $item->setName($params['name']);
  11207. $item->setCId($params['c_id']);
  11208. $em->persist($item);
  11209. $em->flush();
  11210. api_item_property_update(
  11211. api_get_course_info(),
  11212. TOOL_LEARNPATH_CATEGORY,
  11213. $item->getId(),
  11214. 'visible',
  11215. api_get_user_id()
  11216. );
  11217. return $item->getId();
  11218. }
  11219. /**
  11220. * @param array $params
  11221. *
  11222. * @throws \Doctrine\ORM\ORMException
  11223. * @throws \Doctrine\ORM\OptimisticLockException
  11224. * @throws \Doctrine\ORM\TransactionRequiredException
  11225. */
  11226. public static function updateCategory($params)
  11227. {
  11228. $em = Database::getManager();
  11229. /** @var CLpCategory $item */
  11230. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11231. if ($item) {
  11232. $item->setName($params['name']);
  11233. $em->merge($item);
  11234. $em->flush();
  11235. }
  11236. }
  11237. /**
  11238. * @param int $id
  11239. *
  11240. * @throws \Doctrine\ORM\ORMException
  11241. * @throws \Doctrine\ORM\OptimisticLockException
  11242. * @throws \Doctrine\ORM\TransactionRequiredException
  11243. */
  11244. public static function moveUpCategory($id)
  11245. {
  11246. $id = (int) $id;
  11247. $em = Database::getManager();
  11248. /** @var CLpCategory $item */
  11249. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11250. if ($item) {
  11251. $position = $item->getPosition() - 1;
  11252. $item->setPosition($position);
  11253. $em->persist($item);
  11254. $em->flush();
  11255. }
  11256. }
  11257. /**
  11258. * @param int $id
  11259. *
  11260. * @throws \Doctrine\ORM\ORMException
  11261. * @throws \Doctrine\ORM\OptimisticLockException
  11262. * @throws \Doctrine\ORM\TransactionRequiredException
  11263. */
  11264. public static function moveDownCategory($id)
  11265. {
  11266. $id = (int) $id;
  11267. $em = Database::getManager();
  11268. /** @var CLpCategory $item */
  11269. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11270. if ($item) {
  11271. $position = $item->getPosition() + 1;
  11272. $item->setPosition($position);
  11273. $em->persist($item);
  11274. $em->flush();
  11275. }
  11276. }
  11277. /**
  11278. * @param int $courseId
  11279. *
  11280. * @throws \Doctrine\ORM\Query\QueryException
  11281. *
  11282. * @return int|mixed
  11283. */
  11284. public static function getCountCategories($courseId)
  11285. {
  11286. if (empty($courseId)) {
  11287. return 0;
  11288. }
  11289. $em = Database::getManager();
  11290. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11291. $query->setParameter('id', $courseId);
  11292. return $query->getSingleScalarResult();
  11293. }
  11294. /**
  11295. * @param int $courseId
  11296. *
  11297. * @return mixed
  11298. */
  11299. public static function getCategories($courseId)
  11300. {
  11301. $em = Database::getManager();
  11302. // Using doctrine extensions
  11303. /** @var SortableRepository $repo */
  11304. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11305. $items = $repo
  11306. ->getBySortableGroupsQuery(['cId' => $courseId])
  11307. ->getResult();
  11308. return $items;
  11309. }
  11310. /**
  11311. * @param int $id
  11312. *
  11313. * @throws \Doctrine\ORM\ORMException
  11314. * @throws \Doctrine\ORM\OptimisticLockException
  11315. * @throws \Doctrine\ORM\TransactionRequiredException
  11316. *
  11317. * @return CLpCategory
  11318. */
  11319. public static function getCategory($id)
  11320. {
  11321. $id = (int) $id;
  11322. $em = Database::getManager();
  11323. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11324. return $item;
  11325. }
  11326. /**
  11327. * @param int $courseId
  11328. *
  11329. * @return array
  11330. */
  11331. public static function getCategoryByCourse($courseId)
  11332. {
  11333. $em = Database::getManager();
  11334. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11335. ['cId' => $courseId]
  11336. );
  11337. return $items;
  11338. }
  11339. /**
  11340. * @param int $id
  11341. *
  11342. * @throws \Doctrine\ORM\ORMException
  11343. * @throws \Doctrine\ORM\OptimisticLockException
  11344. * @throws \Doctrine\ORM\TransactionRequiredException
  11345. *
  11346. * @return mixed
  11347. */
  11348. public static function deleteCategory($id)
  11349. {
  11350. $em = Database::getManager();
  11351. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11352. if ($item) {
  11353. $courseId = $item->getCId();
  11354. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11355. $query->setParameter('id', $courseId);
  11356. $query->setParameter('catId', $item->getId());
  11357. $lps = $query->getResult();
  11358. // Setting category = 0.
  11359. if ($lps) {
  11360. foreach ($lps as $lpItem) {
  11361. $lpItem->setCategoryId(0);
  11362. }
  11363. }
  11364. // Removing category.
  11365. $em->remove($item);
  11366. $em->flush();
  11367. $courseInfo = api_get_course_info_by_id($courseId);
  11368. $sessionId = api_get_session_id();
  11369. // Delete link tool
  11370. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11371. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11372. // Delete tools
  11373. $sql = "DELETE FROM $tbl_tool
  11374. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11375. Database::query($sql);
  11376. return true;
  11377. }
  11378. return false;
  11379. }
  11380. /**
  11381. * @param int $courseId
  11382. * @param bool $addSelectOption
  11383. *
  11384. * @return mixed
  11385. */
  11386. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11387. {
  11388. $items = self::getCategoryByCourse($courseId);
  11389. $cats = [];
  11390. if ($addSelectOption) {
  11391. $cats = [get_lang('SelectACategory')];
  11392. }
  11393. if (!empty($items)) {
  11394. foreach ($items as $cat) {
  11395. $cats[$cat->getId()] = $cat->getName();
  11396. }
  11397. }
  11398. return $cats;
  11399. }
  11400. /**
  11401. * @param string $courseCode
  11402. * @param int $lpId
  11403. * @param int $user_id
  11404. *
  11405. * @return learnpath
  11406. */
  11407. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11408. {
  11409. $debug = 0;
  11410. $learnPath = null;
  11411. $lpObject = Session::read('lpobject');
  11412. if ($lpObject !== null) {
  11413. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11414. if ($debug) {
  11415. error_log('getLpFromSession: unserialize');
  11416. error_log('------getLpFromSession------');
  11417. error_log('------unserialize------');
  11418. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11419. error_log("api_get_sessionid: ".api_get_session_id());
  11420. }
  11421. }
  11422. if (!is_object($learnPath)) {
  11423. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11424. if ($debug) {
  11425. error_log('------getLpFromSession------');
  11426. error_log('getLpFromSession: create new learnpath');
  11427. error_log("create new LP with $courseCode - $lpId - $user_id");
  11428. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11429. error_log("api_get_sessionid: ".api_get_session_id());
  11430. }
  11431. }
  11432. return $learnPath;
  11433. }
  11434. /**
  11435. * @param int $itemId
  11436. *
  11437. * @return learnpathItem|false
  11438. */
  11439. public function getItem($itemId)
  11440. {
  11441. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11442. return $this->items[$itemId];
  11443. }
  11444. return false;
  11445. }
  11446. /**
  11447. * @return int
  11448. */
  11449. public function getCurrentAttempt()
  11450. {
  11451. $attempt = $this->getItem($this->get_current_item_id());
  11452. if ($attempt) {
  11453. $attemptId = $attempt->get_attempt_id();
  11454. return $attemptId;
  11455. }
  11456. return 0;
  11457. }
  11458. /**
  11459. * @return int
  11460. */
  11461. public function getCategoryId()
  11462. {
  11463. return (int) $this->categoryId;
  11464. }
  11465. /**
  11466. * @param int $categoryId
  11467. *
  11468. * @return bool
  11469. */
  11470. public function setCategoryId($categoryId)
  11471. {
  11472. $this->categoryId = (int) $categoryId;
  11473. $table = Database::get_course_table(TABLE_LP_MAIN);
  11474. $lp_id = $this->get_id();
  11475. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11476. WHERE iid = $lp_id";
  11477. Database::query($sql);
  11478. return true;
  11479. }
  11480. /**
  11481. * Get whether this is a learning path with the possibility to subscribe
  11482. * users or not.
  11483. *
  11484. * @return int
  11485. */
  11486. public function getSubscribeUsers()
  11487. {
  11488. return $this->subscribeUsers;
  11489. }
  11490. /**
  11491. * Set whether this is a learning path with the possibility to subscribe
  11492. * users or not.
  11493. *
  11494. * @param int $value (0 = false, 1 = true)
  11495. *
  11496. * @return bool
  11497. */
  11498. public function setSubscribeUsers($value)
  11499. {
  11500. $this->subscribeUsers = (int) $value;
  11501. $table = Database::get_course_table(TABLE_LP_MAIN);
  11502. $lp_id = $this->get_id();
  11503. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11504. WHERE iid = $lp_id";
  11505. Database::query($sql);
  11506. return true;
  11507. }
  11508. /**
  11509. * Calculate the count of stars for a user in this LP
  11510. * This calculation is based on the following rules:
  11511. * - the student gets one star when he gets to 50% of the learning path
  11512. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11513. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11514. * - the student gets the final star when the score for the *last* test is >= 80%.
  11515. *
  11516. * @param int $sessionId Optional. The session ID
  11517. *
  11518. * @return int The count of stars
  11519. */
  11520. public function getCalculateStars($sessionId = 0)
  11521. {
  11522. $stars = 0;
  11523. $progress = self::getProgress(
  11524. $this->lp_id,
  11525. $this->user_id,
  11526. $this->course_int_id,
  11527. $sessionId
  11528. );
  11529. if ($progress >= 50) {
  11530. $stars++;
  11531. }
  11532. // Calculate stars chapters evaluation
  11533. $exercisesItems = $this->getExercisesItems();
  11534. if (!empty($exercisesItems)) {
  11535. $totalResult = 0;
  11536. foreach ($exercisesItems as $exerciseItem) {
  11537. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11538. $this->user_id,
  11539. $exerciseItem->path,
  11540. $this->course_int_id,
  11541. $sessionId,
  11542. $this->lp_id,
  11543. $exerciseItem->db_id
  11544. );
  11545. $exerciseResultInfo = end($exerciseResultInfo);
  11546. if (!$exerciseResultInfo) {
  11547. continue;
  11548. }
  11549. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11550. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11551. } else {
  11552. $exerciseResult = 0;
  11553. }
  11554. $totalResult += $exerciseResult;
  11555. }
  11556. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11557. if ($totalExerciseAverage >= 50) {
  11558. $stars++;
  11559. }
  11560. if ($totalExerciseAverage >= 80) {
  11561. $stars++;
  11562. }
  11563. }
  11564. // Calculate star for final evaluation
  11565. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11566. if (!empty($finalEvaluationItem)) {
  11567. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11568. $this->user_id,
  11569. $finalEvaluationItem->path,
  11570. $this->course_int_id,
  11571. $sessionId,
  11572. $this->lp_id,
  11573. $finalEvaluationItem->db_id
  11574. );
  11575. $evaluationResultInfo = end($evaluationResultInfo);
  11576. if ($evaluationResultInfo) {
  11577. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11578. if ($evaluationResult >= 80) {
  11579. $stars++;
  11580. }
  11581. }
  11582. }
  11583. return $stars;
  11584. }
  11585. /**
  11586. * Get the items of exercise type.
  11587. *
  11588. * @return array The items. Otherwise return false
  11589. */
  11590. public function getExercisesItems()
  11591. {
  11592. $exercises = [];
  11593. foreach ($this->items as $item) {
  11594. if ($item->type != 'quiz') {
  11595. continue;
  11596. }
  11597. $exercises[] = $item;
  11598. }
  11599. array_pop($exercises);
  11600. return $exercises;
  11601. }
  11602. /**
  11603. * Get the item of exercise type (evaluation type).
  11604. *
  11605. * @return array The final evaluation. Otherwise return false
  11606. */
  11607. public function getFinalEvaluationItem()
  11608. {
  11609. $exercises = [];
  11610. foreach ($this->items as $item) {
  11611. if ($item->type != 'quiz') {
  11612. continue;
  11613. }
  11614. $exercises[] = $item;
  11615. }
  11616. return array_pop($exercises);
  11617. }
  11618. /**
  11619. * Calculate the total points achieved for the current user in this learning path.
  11620. *
  11621. * @param int $sessionId Optional. The session Id
  11622. *
  11623. * @return int
  11624. */
  11625. public function getCalculateScore($sessionId = 0)
  11626. {
  11627. // Calculate stars chapters evaluation
  11628. $exercisesItems = $this->getExercisesItems();
  11629. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11630. $totalExercisesResult = 0;
  11631. $totalEvaluationResult = 0;
  11632. if ($exercisesItems !== false) {
  11633. foreach ($exercisesItems as $exerciseItem) {
  11634. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11635. $this->user_id,
  11636. $exerciseItem->path,
  11637. $this->course_int_id,
  11638. $sessionId,
  11639. $this->lp_id,
  11640. $exerciseItem->db_id
  11641. );
  11642. $exerciseResultInfo = end($exerciseResultInfo);
  11643. if (!$exerciseResultInfo) {
  11644. continue;
  11645. }
  11646. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11647. }
  11648. }
  11649. if (!empty($finalEvaluationItem)) {
  11650. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11651. $this->user_id,
  11652. $finalEvaluationItem->path,
  11653. $this->course_int_id,
  11654. $sessionId,
  11655. $this->lp_id,
  11656. $finalEvaluationItem->db_id
  11657. );
  11658. $evaluationResultInfo = end($evaluationResultInfo);
  11659. if ($evaluationResultInfo) {
  11660. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11661. }
  11662. }
  11663. return $totalExercisesResult + $totalEvaluationResult;
  11664. }
  11665. /**
  11666. * Check if URL is not allowed to be show in a iframe.
  11667. *
  11668. * @param string $src
  11669. *
  11670. * @return string
  11671. */
  11672. public function fixBlockedLinks($src)
  11673. {
  11674. $urlInfo = parse_url($src);
  11675. $platformProtocol = 'https';
  11676. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11677. $platformProtocol = 'http';
  11678. }
  11679. $protocolFixApplied = false;
  11680. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11681. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11682. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11683. if ($platformProtocol != $scheme) {
  11684. Session::write('x_frame_source', $src);
  11685. $src = 'blank.php?error=x_frames_options';
  11686. $protocolFixApplied = true;
  11687. }
  11688. if ($protocolFixApplied == false) {
  11689. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11690. // Check X-Frame-Options
  11691. $ch = curl_init();
  11692. $options = [
  11693. CURLOPT_URL => $src,
  11694. CURLOPT_RETURNTRANSFER => true,
  11695. CURLOPT_HEADER => true,
  11696. CURLOPT_FOLLOWLOCATION => true,
  11697. CURLOPT_ENCODING => "",
  11698. CURLOPT_AUTOREFERER => true,
  11699. CURLOPT_CONNECTTIMEOUT => 120,
  11700. CURLOPT_TIMEOUT => 120,
  11701. CURLOPT_MAXREDIRS => 10,
  11702. ];
  11703. $proxySettings = api_get_configuration_value('proxy_settings');
  11704. if (!empty($proxySettings) &&
  11705. isset($proxySettings['curl_setopt_array'])
  11706. ) {
  11707. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11708. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11709. }
  11710. curl_setopt_array($ch, $options);
  11711. $response = curl_exec($ch);
  11712. $httpCode = curl_getinfo($ch);
  11713. $headers = substr($response, 0, $httpCode['header_size']);
  11714. $error = false;
  11715. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11716. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11717. ) {
  11718. $error = true;
  11719. }
  11720. if ($error) {
  11721. Session::write('x_frame_source', $src);
  11722. $src = 'blank.php?error=x_frames_options';
  11723. }
  11724. }
  11725. }
  11726. return $src;
  11727. }
  11728. /**
  11729. * Check if this LP has a created forum in the basis course.
  11730. *
  11731. * @return bool
  11732. */
  11733. public function lpHasForum()
  11734. {
  11735. $forumTable = Database::get_course_table(TABLE_FORUM);
  11736. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11737. $fakeFrom = "
  11738. $forumTable f
  11739. INNER JOIN $itemProperty ip
  11740. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11741. ";
  11742. $resultData = Database::select(
  11743. 'COUNT(f.iid) AS qty',
  11744. $fakeFrom,
  11745. [
  11746. 'where' => [
  11747. 'ip.visibility != ? AND ' => 2,
  11748. 'ip.tool = ? AND ' => TOOL_FORUM,
  11749. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11750. 'f.lp_id = ?' => intval($this->lp_id),
  11751. ],
  11752. ],
  11753. 'first'
  11754. );
  11755. return $resultData['qty'] > 0;
  11756. }
  11757. /**
  11758. * Get the forum for this learning path.
  11759. *
  11760. * @param int $sessionId
  11761. *
  11762. * @return bool
  11763. */
  11764. public function getForum($sessionId = 0)
  11765. {
  11766. $forumTable = Database::get_course_table(TABLE_FORUM);
  11767. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11768. $fakeFrom = "$forumTable f
  11769. INNER JOIN $itemProperty ip ";
  11770. if ($this->lp_session_id == 0) {
  11771. $fakeFrom .= "
  11772. ON (
  11773. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11774. f.session_id = ip.session_id OR ip.session_id IS NULL
  11775. )
  11776. )
  11777. ";
  11778. } else {
  11779. $fakeFrom .= "
  11780. ON (
  11781. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11782. )
  11783. ";
  11784. }
  11785. $resultData = Database::select(
  11786. 'f.*',
  11787. $fakeFrom,
  11788. [
  11789. 'where' => [
  11790. 'ip.visibility != ? AND ' => 2,
  11791. 'ip.tool = ? AND ' => TOOL_FORUM,
  11792. 'f.session_id = ? AND ' => $sessionId,
  11793. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11794. 'f.lp_id = ?' => intval($this->lp_id),
  11795. ],
  11796. ],
  11797. 'first'
  11798. );
  11799. if (empty($resultData)) {
  11800. return false;
  11801. }
  11802. return $resultData;
  11803. }
  11804. /**
  11805. * Create a forum for this learning path.
  11806. *
  11807. * @param int $forumCategoryId
  11808. *
  11809. * @return int The forum ID if was created. Otherwise return false
  11810. */
  11811. public function createForum($forumCategoryId)
  11812. {
  11813. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11814. $forumId = store_forum(
  11815. [
  11816. 'lp_id' => $this->lp_id,
  11817. 'forum_title' => $this->name,
  11818. 'forum_comment' => null,
  11819. 'forum_category' => (int) $forumCategoryId,
  11820. 'students_can_edit_group' => ['students_can_edit' => 0],
  11821. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11822. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11823. 'group_forum' => 0,
  11824. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11825. ],
  11826. [],
  11827. true
  11828. );
  11829. return $forumId;
  11830. }
  11831. /**
  11832. * Get the LP Final Item form.
  11833. *
  11834. * @throws Exception
  11835. * @throws HTML_QuickForm_Error
  11836. *
  11837. * @return string
  11838. */
  11839. public function getFinalItemForm()
  11840. {
  11841. $finalItem = $this->getFinalItem();
  11842. $title = '';
  11843. if ($finalItem) {
  11844. $title = $finalItem->get_title();
  11845. $buttonText = get_lang('Save');
  11846. $content = $this->getSavedFinalItem();
  11847. } else {
  11848. $buttonText = get_lang('LPCreateDocument');
  11849. $content = $this->getFinalItemTemplate();
  11850. }
  11851. $courseInfo = api_get_course_info();
  11852. $result = $this->generate_lp_folder($courseInfo);
  11853. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11854. $relative_prefix = '../../';
  11855. $editorConfig = [
  11856. 'ToolbarSet' => 'LearningPathDocuments',
  11857. 'Width' => '100%',
  11858. 'Height' => '500',
  11859. 'FullPage' => true,
  11860. 'CreateDocumentDir' => $relative_prefix,
  11861. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11862. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11863. ];
  11864. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11865. 'type' => 'document',
  11866. 'lp_id' => $this->lp_id,
  11867. ]);
  11868. $form = new FormValidator('final_item', 'POST', $url);
  11869. $form->addText('title', get_lang('Title'));
  11870. $form->addButtonSave($buttonText);
  11871. $form->addHtml(
  11872. Display::return_message(
  11873. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11874. 'normal',
  11875. false
  11876. )
  11877. );
  11878. $renderer = $form->defaultRenderer();
  11879. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11880. $form->addHtmlEditor(
  11881. 'content_lp_certificate',
  11882. null,
  11883. true,
  11884. false,
  11885. $editorConfig,
  11886. true
  11887. );
  11888. $form->addHidden('action', 'add_final_item');
  11889. $form->addHidden('path', Session::read('pathItem'));
  11890. $form->addHidden('previous', $this->get_last());
  11891. $form->setDefaults(
  11892. ['title' => $title, 'content_lp_certificate' => $content]
  11893. );
  11894. if ($form->validate()) {
  11895. $values = $form->exportValues();
  11896. $lastItemId = $this->getLastInFirstLevel();
  11897. if (!$finalItem) {
  11898. $documentId = $this->create_document(
  11899. $this->course_info,
  11900. $values['content_lp_certificate'],
  11901. $values['title']
  11902. );
  11903. $this->add_item(
  11904. 0,
  11905. $lastItemId,
  11906. 'final_item',
  11907. $documentId,
  11908. $values['title'],
  11909. ''
  11910. );
  11911. Display::addFlash(
  11912. Display::return_message(get_lang('Added'))
  11913. );
  11914. } else {
  11915. $this->edit_document($this->course_info);
  11916. }
  11917. }
  11918. return $form->returnForm();
  11919. }
  11920. /**
  11921. * Check if the current lp item is first, both, last or none from lp list.
  11922. *
  11923. * @param int $currentItemId
  11924. *
  11925. * @return string
  11926. */
  11927. public function isFirstOrLastItem($currentItemId)
  11928. {
  11929. $lpItemId = [];
  11930. $typeListNotToVerify = self::getChapterTypes();
  11931. // Using get_toc() function instead $this->items because returns the correct order of the items
  11932. foreach ($this->get_toc() as $item) {
  11933. if (!in_array($item['type'], $typeListNotToVerify)) {
  11934. $lpItemId[] = $item['id'];
  11935. }
  11936. }
  11937. $lastLpItemIndex = count($lpItemId) - 1;
  11938. $position = array_search($currentItemId, $lpItemId);
  11939. switch ($position) {
  11940. case 0:
  11941. if (!$lastLpItemIndex) {
  11942. $answer = 'both';
  11943. break;
  11944. }
  11945. $answer = 'first';
  11946. break;
  11947. case $lastLpItemIndex:
  11948. $answer = 'last';
  11949. break;
  11950. default:
  11951. $answer = 'none';
  11952. }
  11953. return $answer;
  11954. }
  11955. /**
  11956. * Get whether this is a learning path with the accumulated SCORM time or not.
  11957. *
  11958. * @return int
  11959. */
  11960. public function getAccumulateScormTime()
  11961. {
  11962. return $this->accumulateScormTime;
  11963. }
  11964. /**
  11965. * Set whether this is a learning path with the accumulated SCORM time or not.
  11966. *
  11967. * @param int $value (0 = false, 1 = true)
  11968. *
  11969. * @return bool Always returns true
  11970. */
  11971. public function setAccumulateScormTime($value)
  11972. {
  11973. $this->accumulateScormTime = (int) $value;
  11974. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11975. $lp_id = $this->get_id();
  11976. $sql = "UPDATE $lp_table
  11977. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11978. WHERE iid = $lp_id";
  11979. Database::query($sql);
  11980. return true;
  11981. }
  11982. /**
  11983. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11984. * the new learning path tool.
  11985. *
  11986. * The function is a big switch on tool type.
  11987. * In each case, we query the corresponding table for information and build the link
  11988. * with that information.
  11989. *
  11990. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11991. * previous work (display_addedresource_link_in_learnpath())
  11992. *
  11993. * @param int $course_id Course code
  11994. * @param int $learningPathId The learning path ID (in lp table)
  11995. * @param int $id_in_path the unique index in the items table
  11996. * @param int $lpViewId
  11997. *
  11998. * @return string
  11999. */
  12000. public static function rl_get_resource_link_for_learnpath(
  12001. $course_id,
  12002. $learningPathId,
  12003. $id_in_path,
  12004. $lpViewId
  12005. ) {
  12006. $session_id = api_get_session_id();
  12007. $course_info = api_get_course_info_by_id($course_id);
  12008. $learningPathId = (int) $learningPathId;
  12009. $id_in_path = (int) $id_in_path;
  12010. $lpViewId = (int) $lpViewId;
  12011. $em = Database::getManager();
  12012. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12013. /** @var CLpItem $rowItem */
  12014. $rowItem = $lpItemRepo->findOneBy([
  12015. 'cId' => $course_id,
  12016. 'lpId' => $learningPathId,
  12017. 'iid' => $id_in_path,
  12018. ]);
  12019. if (!$rowItem) {
  12020. // Try one more time with "id"
  12021. /** @var CLpItem $rowItem */
  12022. $rowItem = $lpItemRepo->findOneBy([
  12023. 'cId' => $course_id,
  12024. 'lpId' => $learningPathId,
  12025. 'id' => $id_in_path,
  12026. ]);
  12027. if (!$rowItem) {
  12028. return -1;
  12029. }
  12030. }
  12031. $course_code = $course_info['code'];
  12032. $type = $rowItem->getItemType();
  12033. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12034. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12035. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12036. $link = '';
  12037. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12038. switch ($type) {
  12039. case 'dir':
  12040. return $main_dir_path.'lp/blank.php';
  12041. case TOOL_CALENDAR_EVENT:
  12042. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12043. case TOOL_ANNOUNCEMENT:
  12044. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12045. case TOOL_LINK:
  12046. $linkInfo = Link::getLinkInfo($id);
  12047. if (isset($linkInfo['url'])) {
  12048. return $linkInfo['url'];
  12049. }
  12050. return '';
  12051. case TOOL_QUIZ:
  12052. if (empty($id)) {
  12053. return '';
  12054. }
  12055. // Get the lp_item_view with the highest view_count.
  12056. $learnpathItemViewResult = $em
  12057. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12058. ->findBy(
  12059. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12060. ['viewCount' => 'DESC'],
  12061. 1
  12062. );
  12063. /** @var CLpItemView $learnpathItemViewData */
  12064. $learnpathItemViewData = current($learnpathItemViewResult);
  12065. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12066. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12067. .http_build_query([
  12068. 'lp_init' => 1,
  12069. 'learnpath_item_view_id' => $learnpathItemViewId,
  12070. 'learnpath_id' => $learningPathId,
  12071. 'learnpath_item_id' => $id_in_path,
  12072. 'exerciseId' => $id,
  12073. ]);
  12074. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12075. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12076. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12077. $myrow = Database::fetch_array($result);
  12078. $path = $myrow['path'];
  12079. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12080. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12081. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12082. case TOOL_FORUM:
  12083. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12084. case TOOL_THREAD:
  12085. // forum post
  12086. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12087. if (empty($id)) {
  12088. return '';
  12089. }
  12090. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12091. $result = Database::query($sql);
  12092. $myrow = Database::fetch_array($result);
  12093. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12094. .$extraParams;
  12095. case TOOL_POST:
  12096. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12097. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12098. $myrow = Database::fetch_array($result);
  12099. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12100. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12101. case TOOL_READOUT_TEXT:
  12102. return api_get_path(WEB_CODE_PATH).
  12103. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  12104. case TOOL_DOCUMENT:
  12105. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  12106. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12107. if (empty($document)) {
  12108. // Try with normal id
  12109. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  12110. if (empty($document)) {
  12111. return '';
  12112. }
  12113. }
  12114. $documentPathInfo = pathinfo($document->getPath());
  12115. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  12116. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12117. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  12118. $openmethod = 2;
  12119. $officedoc = false;
  12120. Session::write('openmethod', $openmethod);
  12121. Session::write('officedoc', $officedoc);
  12122. if ($showDirectUrl) {
  12123. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12124. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  12125. if (Link::isPdfLink($file)) {
  12126. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  12127. return $pdfUrl;
  12128. }
  12129. }
  12130. return $file;
  12131. }
  12132. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12133. case TOOL_LP_FINAL_ITEM:
  12134. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12135. .$extraParams;
  12136. case 'assignments':
  12137. return $main_dir_path.'work/work.php?'.$extraParams;
  12138. case TOOL_DROPBOX:
  12139. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12140. case 'introduction_text': //DEPRECATED
  12141. return '';
  12142. case TOOL_COURSE_DESCRIPTION:
  12143. return $main_dir_path.'course_description?'.$extraParams;
  12144. case TOOL_GROUP:
  12145. return $main_dir_path.'group/group.php?'.$extraParams;
  12146. case TOOL_USER:
  12147. return $main_dir_path.'user/user.php?'.$extraParams;
  12148. case TOOL_STUDENTPUBLICATION:
  12149. if (!empty($rowItem->getPath())) {
  12150. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12151. }
  12152. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12153. }
  12154. return $link;
  12155. }
  12156. /**
  12157. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12158. *
  12159. * @author Yannick Warnier <ywarnier@beeznest.org>
  12160. *
  12161. * @param string $course_code Course code
  12162. * @param int $learningPathId
  12163. * @param int $id_in_path The resource ID
  12164. *
  12165. * @return string
  12166. */
  12167. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12168. {
  12169. $_course = api_get_course_info($course_code);
  12170. if (empty($_course)) {
  12171. return '';
  12172. }
  12173. $course_id = $_course['real_id'];
  12174. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12175. $learningPathId = (int) $learningPathId;
  12176. $id_in_path = (int) $id_in_path;
  12177. $sql = "SELECT item_type, title, ref
  12178. FROM $tbl_lp_item
  12179. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12180. $res_item = Database::query($sql);
  12181. if (Database::num_rows($res_item) < 1) {
  12182. return '';
  12183. }
  12184. $row_item = Database::fetch_array($res_item);
  12185. $type = strtolower($row_item['item_type']);
  12186. $id = $row_item['ref'];
  12187. $output = '';
  12188. switch ($type) {
  12189. case TOOL_CALENDAR_EVENT:
  12190. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12191. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12192. $myrow = Database::fetch_array($result);
  12193. $output = $myrow['title'];
  12194. break;
  12195. case TOOL_ANNOUNCEMENT:
  12196. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12197. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12198. $myrow = Database::fetch_array($result);
  12199. $output = $myrow['title'];
  12200. break;
  12201. case TOOL_LINK:
  12202. // Doesn't take $target into account.
  12203. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12204. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12205. $myrow = Database::fetch_array($result);
  12206. $output = $myrow['title'];
  12207. break;
  12208. case TOOL_QUIZ:
  12209. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12210. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12211. $myrow = Database::fetch_array($result);
  12212. $output = $myrow['title'];
  12213. break;
  12214. case TOOL_FORUM:
  12215. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12216. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12217. $myrow = Database::fetch_array($result);
  12218. $output = $myrow['forum_name'];
  12219. break;
  12220. case TOOL_THREAD:
  12221. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12222. // Grabbing the title of the post.
  12223. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12224. $result_title = Database::query($sql_title);
  12225. $myrow_title = Database::fetch_array($result_title);
  12226. $output = $myrow_title['post_title'];
  12227. break;
  12228. case TOOL_POST:
  12229. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12230. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12231. $result = Database::query($sql);
  12232. $post = Database::fetch_array($result);
  12233. $output = $post['post_title'];
  12234. break;
  12235. case 'dir':
  12236. case TOOL_DOCUMENT:
  12237. $title = $row_item['title'];
  12238. $output = '-';
  12239. if (!empty($title)) {
  12240. $output = $title;
  12241. }
  12242. break;
  12243. case 'hotpotatoes':
  12244. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12245. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12246. $myrow = Database::fetch_array($result);
  12247. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12248. $last = count($pathname) - 1; // Making a correct name for the link.
  12249. $filename = $pathname[$last]; // Making a correct name for the link.
  12250. $myrow['path'] = rawurlencode($myrow['path']);
  12251. $output = $filename;
  12252. break;
  12253. }
  12254. return stripslashes($output);
  12255. }
  12256. /**
  12257. * Get the parent names for the current item.
  12258. *
  12259. * @param int $newItemId Optional. The item ID
  12260. *
  12261. * @return array
  12262. */
  12263. public function getCurrentItemParentNames($newItemId = 0)
  12264. {
  12265. $newItemId = $newItemId ?: $this->get_current_item_id();
  12266. $return = [];
  12267. $item = $this->getItem($newItemId);
  12268. $parent = $this->getItem($item->get_parent());
  12269. while ($parent) {
  12270. $return[] = $parent->get_title();
  12271. $parent = $this->getItem($parent->get_parent());
  12272. }
  12273. return array_reverse($return);
  12274. }
  12275. /**
  12276. * Reads and process "lp_subscription_settings" setting.
  12277. *
  12278. * @return array
  12279. */
  12280. public static function getSubscriptionSettings()
  12281. {
  12282. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12283. if (empty($subscriptionSettings)) {
  12284. // By default allow both settings
  12285. $subscriptionSettings = [
  12286. 'allow_add_users_to_lp' => true,
  12287. 'allow_add_users_to_lp_category' => true,
  12288. ];
  12289. } else {
  12290. $subscriptionSettings = $subscriptionSettings['options'];
  12291. }
  12292. return $subscriptionSettings;
  12293. }
  12294. /**
  12295. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12296. */
  12297. public function exportToCourseBuildFormat()
  12298. {
  12299. if (!api_is_allowed_to_edit()) {
  12300. return false;
  12301. }
  12302. $courseBuilder = new CourseBuilder();
  12303. $itemList = [];
  12304. /** @var learnpathItem $item */
  12305. foreach ($this->items as $item) {
  12306. $itemList[$item->get_type()][] = $item->get_path();
  12307. }
  12308. if (empty($itemList)) {
  12309. return false;
  12310. }
  12311. if (isset($itemList['document'])) {
  12312. // Get parents
  12313. foreach ($itemList['document'] as $documentId) {
  12314. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12315. if (!empty($documentInfo['parents'])) {
  12316. foreach ($documentInfo['parents'] as $parentInfo) {
  12317. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12318. continue;
  12319. }
  12320. $itemList['document'][] = $parentInfo['iid'];
  12321. }
  12322. }
  12323. }
  12324. $courseInfo = api_get_course_info();
  12325. foreach ($itemList['document'] as $documentId) {
  12326. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12327. $items = DocumentManager::get_resources_from_source_html(
  12328. $documentInfo['absolute_path'],
  12329. true,
  12330. TOOL_DOCUMENT
  12331. );
  12332. if (!empty($items)) {
  12333. foreach ($items as $item) {
  12334. // Get information about source url
  12335. $url = $item[0]; // url
  12336. $scope = $item[1]; // scope (local, remote)
  12337. $type = $item[2]; // type (rel, abs, url)
  12338. $origParseUrl = parse_url($url);
  12339. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12340. if ($scope == 'local') {
  12341. if ($type == 'abs' || $type == 'rel') {
  12342. $documentFile = strstr($realOrigPath, 'document');
  12343. if (strpos($realOrigPath, $documentFile) !== false) {
  12344. $documentFile = str_replace('document', '', $documentFile);
  12345. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12346. // Document found! Add it to the list
  12347. if ($itemDocumentId) {
  12348. $itemList['document'][] = $itemDocumentId;
  12349. }
  12350. }
  12351. }
  12352. }
  12353. }
  12354. }
  12355. }
  12356. $courseBuilder->build_documents(
  12357. api_get_session_id(),
  12358. $this->get_course_int_id(),
  12359. true,
  12360. $itemList['document']
  12361. );
  12362. }
  12363. if (isset($itemList['quiz'])) {
  12364. $courseBuilder->build_quizzes(
  12365. api_get_session_id(),
  12366. $this->get_course_int_id(),
  12367. true,
  12368. $itemList['quiz']
  12369. );
  12370. }
  12371. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12372. /*if (!empty($itemList['thread'])) {
  12373. $postList = [];
  12374. foreach ($itemList['thread'] as $postId) {
  12375. $post = get_post_information($postId);
  12376. if ($post) {
  12377. if (!isset($itemList['forum'])) {
  12378. $itemList['forum'] = [];
  12379. }
  12380. $itemList['forum'][] = $post['forum_id'];
  12381. $postList[] = $postId;
  12382. }
  12383. }
  12384. if (!empty($postList)) {
  12385. $courseBuilder->build_forum_posts(
  12386. $this->get_course_int_id(),
  12387. null,
  12388. null,
  12389. $postList
  12390. );
  12391. }
  12392. }*/
  12393. if (!empty($itemList['thread'])) {
  12394. $threadList = [];
  12395. $em = Database::getManager();
  12396. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12397. foreach ($itemList['thread'] as $threadId) {
  12398. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12399. $thread = $repo->find($threadId);
  12400. if ($thread) {
  12401. $itemList['forum'][] = $thread->getForumId();
  12402. $threadList[] = $thread->getIid();
  12403. }
  12404. }
  12405. if (!empty($threadList)) {
  12406. $courseBuilder->build_forum_topics(
  12407. api_get_session_id(),
  12408. $this->get_course_int_id(),
  12409. null,
  12410. $threadList
  12411. );
  12412. }
  12413. }
  12414. $forumCategoryList = [];
  12415. if (isset($itemList['forum'])) {
  12416. foreach ($itemList['forum'] as $forumId) {
  12417. $forumInfo = get_forums($forumId);
  12418. $forumCategoryList[] = $forumInfo['forum_category'];
  12419. }
  12420. }
  12421. if (!empty($forumCategoryList)) {
  12422. $courseBuilder->build_forum_category(
  12423. api_get_session_id(),
  12424. $this->get_course_int_id(),
  12425. true,
  12426. $forumCategoryList
  12427. );
  12428. }
  12429. if (!empty($itemList['forum'])) {
  12430. $courseBuilder->build_forums(
  12431. api_get_session_id(),
  12432. $this->get_course_int_id(),
  12433. true,
  12434. $itemList['forum']
  12435. );
  12436. }
  12437. if (isset($itemList['link'])) {
  12438. $courseBuilder->build_links(
  12439. api_get_session_id(),
  12440. $this->get_course_int_id(),
  12441. true,
  12442. $itemList['link']
  12443. );
  12444. }
  12445. if (!empty($itemList['student_publication'])) {
  12446. $courseBuilder->build_works(
  12447. api_get_session_id(),
  12448. $this->get_course_int_id(),
  12449. true,
  12450. $itemList['student_publication']
  12451. );
  12452. }
  12453. $courseBuilder->build_learnpaths(
  12454. api_get_session_id(),
  12455. $this->get_course_int_id(),
  12456. true,
  12457. [$this->get_id()],
  12458. false
  12459. );
  12460. $courseBuilder->restoreDocumentsFromList();
  12461. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12462. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12463. $result = DocumentManager::file_send_for_download(
  12464. $zipPath,
  12465. true,
  12466. $this->get_name().'.zip'
  12467. );
  12468. if ($result) {
  12469. api_not_allowed();
  12470. }
  12471. return true;
  12472. }
  12473. /**
  12474. * Get whether this is a learning path with the accumulated work time or not.
  12475. *
  12476. * @return int
  12477. */
  12478. public function getAccumulateWorkTime()
  12479. {
  12480. return (int) $this->accumulateWorkTime;
  12481. }
  12482. /**
  12483. * Get whether this is a learning path with the accumulated work time or not.
  12484. *
  12485. * @return int
  12486. */
  12487. public function getAccumulateWorkTimeTotalCourse()
  12488. {
  12489. $table = Database::get_course_table(TABLE_LP_MAIN);
  12490. $sql = "SELECT SUM(accumulate_work_time) AS total
  12491. FROM $table
  12492. WHERE c_id = ".$this->course_int_id;
  12493. $result = Database::query($sql);
  12494. $row = Database::fetch_array($result);
  12495. return (int) $row['total'];
  12496. }
  12497. /**
  12498. * Set whether this is a learning path with the accumulated work time or not.
  12499. *
  12500. * @param int $value (0 = false, 1 = true)
  12501. *
  12502. * @return bool
  12503. */
  12504. public function setAccumulateWorkTime($value)
  12505. {
  12506. if (!api_get_configuration_value('lp_minimum_time')) {
  12507. return false;
  12508. }
  12509. $this->accumulateWorkTime = (int) $value;
  12510. $table = Database::get_course_table(TABLE_LP_MAIN);
  12511. $lp_id = $this->get_id();
  12512. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12513. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12514. Database::query($sql);
  12515. return true;
  12516. }
  12517. /**
  12518. * @param int $lpId
  12519. * @param int $courseId
  12520. *
  12521. * @return mixed
  12522. */
  12523. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12524. {
  12525. $lpId = (int) $lpId;
  12526. $courseId = (int) $courseId;
  12527. $table = Database::get_course_table(TABLE_LP_MAIN);
  12528. $sql = "SELECT accumulate_work_time
  12529. FROM $table
  12530. WHERE c_id = $courseId AND id = $lpId";
  12531. $result = Database::query($sql);
  12532. $row = Database::fetch_array($result);
  12533. return $row['accumulate_work_time'];
  12534. }
  12535. /**
  12536. * @param int $courseId
  12537. *
  12538. * @return int
  12539. */
  12540. public static function getAccumulateWorkTimeTotal($courseId)
  12541. {
  12542. $table = Database::get_course_table(TABLE_LP_MAIN);
  12543. $courseId = (int) $courseId;
  12544. $sql = "SELECT SUM(accumulate_work_time) AS total
  12545. FROM $table
  12546. WHERE c_id = $courseId";
  12547. $result = Database::query($sql);
  12548. $row = Database::fetch_array($result);
  12549. return (int) $row['total'];
  12550. }
  12551. /**
  12552. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12553. * and put the images in.
  12554. *
  12555. * @return array
  12556. */
  12557. public static function getIconSelect()
  12558. {
  12559. $theme = api_get_visual_theme();
  12560. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12561. $icons = ['' => get_lang('SelectAnOption')];
  12562. if (is_dir($path)) {
  12563. $finder = new Finder();
  12564. $finder->files()->in($path);
  12565. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12566. /** @var SplFileInfo $file */
  12567. foreach ($finder as $file) {
  12568. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12569. $icons[$file->getFilename()] = $file->getFilename();
  12570. }
  12571. }
  12572. }
  12573. return $icons;
  12574. }
  12575. /**
  12576. * @param int $lpId
  12577. *
  12578. * @return string
  12579. */
  12580. public static function getSelectedIcon($lpId)
  12581. {
  12582. $extraFieldValue = new ExtraFieldValue('lp');
  12583. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12584. $icon = '';
  12585. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12586. $icon = $lpIcon['value'];
  12587. }
  12588. return $icon;
  12589. }
  12590. /**
  12591. * @param int $lpId
  12592. *
  12593. * @return string
  12594. */
  12595. public static function getSelectedIconHtml($lpId)
  12596. {
  12597. $icon = self::getSelectedIcon($lpId);
  12598. if (empty($icon)) {
  12599. return '';
  12600. }
  12601. $theme = api_get_visual_theme();
  12602. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12603. return Display::img($path);
  12604. }
  12605. /**
  12606. * Get the depth level of LP item.
  12607. *
  12608. * @param array $items
  12609. * @param int $currentItemId
  12610. *
  12611. * @return int
  12612. */
  12613. private static function get_level_for_item($items, $currentItemId)
  12614. {
  12615. $parentItemId = 0;
  12616. if (isset($items[$currentItemId])) {
  12617. $parentItemId = $items[$currentItemId]->parent;
  12618. }
  12619. if ($parentItemId == 0) {
  12620. return 0;
  12621. } else {
  12622. return self::get_level_for_item($items, $parentItemId) + 1;
  12623. }
  12624. }
  12625. /**
  12626. * Generate the link for a learnpath category as course tool.
  12627. *
  12628. * @param int $categoryId
  12629. *
  12630. * @return string
  12631. */
  12632. private static function getCategoryLinkForTool($categoryId)
  12633. {
  12634. $categoryId = (int) $categoryId;
  12635. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12636. .http_build_query(
  12637. [
  12638. 'action' => 'view_category',
  12639. 'id' => $categoryId,
  12640. ]
  12641. );
  12642. return $link;
  12643. }
  12644. /**
  12645. * Return the scorm item type object with spaces replaced with _
  12646. * The return result is use to build a css classname like scorm_type_$return.
  12647. *
  12648. * @param $in_type
  12649. *
  12650. * @return mixed
  12651. */
  12652. private static function format_scorm_type_item($in_type)
  12653. {
  12654. return str_replace(' ', '_', $in_type);
  12655. }
  12656. /**
  12657. * Check and obtain the lp final item if exist.
  12658. *
  12659. * @return learnpathItem
  12660. */
  12661. private function getFinalItem()
  12662. {
  12663. if (empty($this->items)) {
  12664. return null;
  12665. }
  12666. foreach ($this->items as $item) {
  12667. if ($item->type !== 'final_item') {
  12668. continue;
  12669. }
  12670. return $item;
  12671. }
  12672. }
  12673. /**
  12674. * Get the LP Final Item Template.
  12675. *
  12676. * @return string
  12677. */
  12678. private function getFinalItemTemplate()
  12679. {
  12680. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12681. }
  12682. /**
  12683. * Get the LP Final Item Url.
  12684. *
  12685. * @return string
  12686. */
  12687. private function getSavedFinalItem()
  12688. {
  12689. $finalItem = $this->getFinalItem();
  12690. $doc = DocumentManager::get_document_data_by_id(
  12691. $finalItem->path,
  12692. $this->cc
  12693. );
  12694. if ($doc && file_exists($doc['absolute_path'])) {
  12695. return file_get_contents($doc['absolute_path']);
  12696. }
  12697. return '';
  12698. }
  12699. }