learnpath.class.php 509 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Framework\Container;
  4. use Chamilo\CoreBundle\Repository\CourseRepository;
  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\CItemProperty;
  9. use Chamilo\CourseBundle\Entity\CLp;
  10. use Chamilo\CourseBundle\Entity\CLpCategory;
  11. use Chamilo\CourseBundle\Entity\CLpItem;
  12. use Chamilo\CourseBundle\Entity\CLpItemView;
  13. use Chamilo\CourseBundle\Entity\CTool;
  14. use Chamilo\UserBundle\Entity\User;
  15. use ChamiloSession as Session;
  16. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  17. use Symfony\Component\Filesystem\Filesystem;
  18. use Symfony\Component\Finder\Finder;
  19. /**
  20. * Class learnpath
  21. * This class defines the parent attributes and methods for Chamilo learnpaths
  22. * and SCORM learnpaths. It is used by the scorm class.
  23. *
  24. * @todo decouple class
  25. *
  26. * @package chamilo.learnpath
  27. *
  28. * @author Yannick Warnier <ywarnier@beeznest.org>
  29. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  30. */
  31. class learnpath
  32. {
  33. public const MAX_LP_ITEM_TITLE_LENGTH = 32;
  34. public $attempt = 0; // The number for the current ID view.
  35. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  36. public $current; // Id of the current item the user is viewing.
  37. public $current_score; // The score of the current item.
  38. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  39. public $current_time_stop; // The time the user closed this resource.
  40. public $default_status = 'not attempted';
  41. public $encoding = 'UTF-8';
  42. public $error = '';
  43. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  44. public $index; // The index of the active learnpath_item in $ordered_items array.
  45. public $items = [];
  46. public $last; // item_id of last item viewed in the learning path.
  47. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  48. public $license; // Which license this course has been given - not used yet on 20060522.
  49. public $lp_id; // DB iid for this learnpath.
  50. public $lp_view_id; // DB ID for lp_view
  51. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  52. public $message = '';
  53. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  54. public $name; // Learnpath name (they generally have one).
  55. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  56. public $path = ''; // Path inside the scorm directory (if scorm).
  57. public $theme; // The current theme of the learning path.
  58. public $preview_image; // The current image of the learning path.
  59. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  60. public $accumulateWorkTime; // The min time of learnpath
  61. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  62. public $prevent_reinit = 1;
  63. // Describes the mode of progress bar display.
  64. public $seriousgame_mode = 0;
  65. public $progress_bar_mode = '%';
  66. // Percentage progress as saved in the db.
  67. public $progress_db = 0;
  68. public $proximity; // Wether the content is distant or local or unknown.
  69. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  70. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  71. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  72. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  73. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  74. public $user_id; //ID of the user that is viewing/using the course
  75. public $update_queue = [];
  76. public $scorm_debug = 0;
  77. public $arrMenu = []; // Array for the menu items.
  78. public $debug = 0; // Logging level.
  79. public $lp_session_id = 0;
  80. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  81. public $prerequisite = 0;
  82. public $use_max_score = 1; // 1 or 0
  83. public $subscribeUsers = 0; // Subscribe users or not
  84. public $created_on = '';
  85. public $modified_on = '';
  86. public $publicated_on = '';
  87. public $expired_on = '';
  88. public $ref = null;
  89. public $course_int_id;
  90. public $course_info = [];
  91. public $categoryId;
  92. /**
  93. * Constructor.
  94. * Needs a database handler, a course code and a learnpath id from the database.
  95. * Also builds the list of items into $this->items.
  96. *
  97. * @param string $course Course code
  98. * @param int $lp_id c_lp.iid
  99. * @param int $user_id
  100. */
  101. public function __construct($course, $lp_id, $user_id)
  102. {
  103. $debug = $this->debug;
  104. $this->encoding = api_get_system_encoding();
  105. if ($debug) {
  106. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  107. }
  108. if (empty($course)) {
  109. $course = api_get_course_id();
  110. }
  111. $course_info = api_get_course_info($course);
  112. if (!empty($course_info)) {
  113. $this->cc = $course_info['code'];
  114. $this->course_info = $course_info;
  115. $course_id = $course_info['real_id'];
  116. } else {
  117. $this->error = 'Course code does not exist in database.';
  118. }
  119. $lp_id = (int) $lp_id;
  120. $course_id = (int) $course_id;
  121. $this->set_course_int_id($course_id);
  122. // Check learnpath ID.
  123. if (empty($lp_id) || empty($course_id)) {
  124. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  125. } else {
  126. // TODO: Make it flexible to use any course_code (still using env course code here).
  127. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  128. $sql = "SELECT * FROM $lp_table
  129. WHERE iid = $lp_id";
  130. if ($debug) {
  131. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  132. }
  133. $res = Database::query($sql);
  134. if (Database::num_rows($res) > 0) {
  135. $this->lp_id = $lp_id;
  136. $row = Database::fetch_array($res);
  137. $this->type = $row['lp_type'];
  138. $this->name = stripslashes($row['name']);
  139. $this->proximity = $row['content_local'];
  140. $this->theme = $row['theme'];
  141. $this->maker = $row['content_maker'];
  142. $this->prevent_reinit = $row['prevent_reinit'];
  143. $this->seriousgame_mode = $row['seriousgame_mode'];
  144. $this->license = $row['content_license'];
  145. $this->scorm_debug = $row['debug'];
  146. $this->js_lib = $row['js_lib'];
  147. $this->path = $row['path'];
  148. $this->preview_image = $row['preview_image'];
  149. $this->author = $row['author'];
  150. $this->hide_toc_frame = $row['hide_toc_frame'];
  151. $this->lp_session_id = $row['session_id'];
  152. $this->use_max_score = $row['use_max_score'];
  153. $this->subscribeUsers = $row['subscribe_users'];
  154. $this->created_on = $row['created_on'];
  155. $this->modified_on = $row['modified_on'];
  156. $this->ref = $row['ref'];
  157. $this->categoryId = $row['category_id'];
  158. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  159. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  160. if (!empty($row['publicated_on'])) {
  161. $this->publicated_on = $row['publicated_on'];
  162. }
  163. if (!empty($row['expired_on'])) {
  164. $this->expired_on = $row['expired_on'];
  165. }
  166. if ($this->type == 2) {
  167. if ($row['force_commit'] == 1) {
  168. $this->force_commit = true;
  169. }
  170. }
  171. $this->mode = $row['default_view_mod'];
  172. // Check user ID.
  173. if (empty($user_id)) {
  174. $this->error = 'User ID is empty';
  175. } else {
  176. $userInfo = api_get_user_info($user_id);
  177. if (!empty($userInfo)) {
  178. $this->user_id = $userInfo['user_id'];
  179. } else {
  180. $this->error = 'User ID does not exist in database #'.$user_id;
  181. }
  182. }
  183. // End of variables checking.
  184. $session_id = api_get_session_id();
  185. // Get the session condition for learning paths of the base + session.
  186. $session = api_get_session_condition($session_id);
  187. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  188. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  189. // Selecting by view_count descending allows to get the highest view_count first.
  190. $sql = "SELECT * FROM $lp_table
  191. WHERE
  192. c_id = $course_id AND
  193. lp_id = $lp_id AND
  194. user_id = $user_id
  195. $session
  196. ORDER BY view_count DESC";
  197. $res = Database::query($sql);
  198. if ($debug) {
  199. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  200. }
  201. if (Database::num_rows($res) > 0) {
  202. if ($debug) {
  203. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  204. }
  205. $row = Database::fetch_array($res);
  206. $this->attempt = $row['view_count'];
  207. $this->lp_view_id = $row['id'];
  208. $this->last_item_seen = $row['last_item'];
  209. $this->progress_db = $row['progress'];
  210. $this->lp_view_session_id = $row['session_id'];
  211. } elseif (!api_is_invitee()) {
  212. if ($debug) {
  213. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  214. }
  215. $this->attempt = 1;
  216. $params = [
  217. 'c_id' => $course_id,
  218. 'lp_id' => $lp_id,
  219. 'user_id' => $user_id,
  220. 'view_count' => 1,
  221. 'session_id' => $session_id,
  222. 'last_item' => 0,
  223. ];
  224. $this->last_item_seen = 0;
  225. $this->lp_view_session_id = $session_id;
  226. $this->lp_view_id = Database::insert($lp_table, $params);
  227. if (!empty($this->lp_view_id)) {
  228. $sql = "UPDATE $lp_table SET id = iid
  229. WHERE iid = ".$this->lp_view_id;
  230. Database::query($sql);
  231. }
  232. }
  233. // Initialise items.
  234. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  235. $sql = "SELECT * FROM $lp_item_table
  236. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  237. ORDER BY parent_item_id, display_order";
  238. $res = Database::query($sql);
  239. $lp_item_id_list = [];
  240. while ($row = Database::fetch_array($res)) {
  241. $lp_item_id_list[] = $row['iid'];
  242. switch ($this->type) {
  243. case 3: //aicc
  244. $oItem = new aiccItem('db', $row['iid'], $course_id);
  245. if (is_object($oItem)) {
  246. $my_item_id = $oItem->get_id();
  247. $oItem->set_lp_view($this->lp_view_id, $course_id);
  248. $oItem->set_prevent_reinit($this->prevent_reinit);
  249. // Don't use reference here as the next loop will make the pointed object change.
  250. $this->items[$my_item_id] = $oItem;
  251. $this->refs_list[$oItem->ref] = $my_item_id;
  252. if ($debug) {
  253. error_log(
  254. 'learnpath::__construct() - '.
  255. 'aicc object with id '.$my_item_id.
  256. ' set in items[]',
  257. 0
  258. );
  259. }
  260. }
  261. break;
  262. case 2:
  263. $oItem = new scormItem('db', $row['iid'], $course_id);
  264. if (is_object($oItem)) {
  265. $my_item_id = $oItem->get_id();
  266. $oItem->set_lp_view($this->lp_view_id, $course_id);
  267. $oItem->set_prevent_reinit($this->prevent_reinit);
  268. // Don't use reference here as the next loop will make the pointed object change.
  269. $this->items[$my_item_id] = $oItem;
  270. $this->refs_list[$oItem->ref] = $my_item_id;
  271. if ($debug) {
  272. error_log('object with id '.$my_item_id.' set in items[]');
  273. }
  274. }
  275. break;
  276. case 1:
  277. default:
  278. if ($debug) {
  279. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  280. }
  281. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  282. if ($debug) {
  283. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  284. }
  285. if (is_object($oItem)) {
  286. $my_item_id = $oItem->get_id();
  287. // Moved down to when we are sure the item_view exists.
  288. //$oItem->set_lp_view($this->lp_view_id);
  289. $oItem->set_prevent_reinit($this->prevent_reinit);
  290. // Don't use reference here as the next loop will make the pointed object change.
  291. $this->items[$my_item_id] = $oItem;
  292. $this->refs_list[$my_item_id] = $my_item_id;
  293. if ($debug) {
  294. error_log(
  295. 'learnpath::__construct() '.__LINE__.
  296. ' - object with id '.$my_item_id.' set in items[]'
  297. );
  298. }
  299. }
  300. break;
  301. }
  302. // Setting the object level with variable $this->items[$i][parent]
  303. foreach ($this->items as $itemLPObject) {
  304. $level = self::get_level_for_item(
  305. $this->items,
  306. $itemLPObject->db_id
  307. );
  308. $itemLPObject->level = $level;
  309. }
  310. // Setting the view in the item object.
  311. if (is_object($this->items[$row['iid']])) {
  312. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  313. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  314. $this->items[$row['iid']]->current_start_time = 0;
  315. $this->items[$row['iid']]->current_stop_time = 0;
  316. }
  317. }
  318. }
  319. if (!empty($lp_item_id_list)) {
  320. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  321. if (!empty($lp_item_id_list_to_string)) {
  322. // Get last viewing vars.
  323. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  324. // This query should only return one or zero result.
  325. $sql = "SELECT lp_item_id, status
  326. FROM $itemViewTable
  327. WHERE
  328. c_id = $course_id AND
  329. lp_view_id = ".$this->get_view_id()." AND
  330. lp_item_id IN ('".$lp_item_id_list_to_string."')
  331. ORDER BY view_count DESC ";
  332. $status_list = [];
  333. $res = Database::query($sql);
  334. while ($row = Database:: fetch_array($res)) {
  335. $status_list[$row['lp_item_id']] = $row['status'];
  336. }
  337. foreach ($lp_item_id_list as $item_id) {
  338. if (isset($status_list[$item_id])) {
  339. $status = $status_list[$item_id];
  340. if (is_object($this->items[$item_id])) {
  341. $this->items[$item_id]->set_status($status);
  342. if (empty($status)) {
  343. $this->items[$item_id]->set_status(
  344. $this->default_status
  345. );
  346. }
  347. }
  348. } else {
  349. if (!api_is_invitee()) {
  350. if (is_object($this->items[$item_id])) {
  351. $this->items[$item_id]->set_status(
  352. $this->default_status
  353. );
  354. }
  355. if (!empty($this->lp_view_id)) {
  356. // Add that row to the lp_item_view table so that
  357. // we have something to show in the stats page.
  358. $params = [
  359. 'c_id' => $course_id,
  360. 'lp_item_id' => $item_id,
  361. 'lp_view_id' => $this->lp_view_id,
  362. 'view_count' => 1,
  363. 'status' => 'not attempted',
  364. 'start_time' => time(),
  365. 'total_time' => 0,
  366. 'score' => 0,
  367. ];
  368. $insertId = Database::insert($itemViewTable, $params);
  369. if ($insertId) {
  370. $sql = "UPDATE $itemViewTable SET id = iid
  371. WHERE iid = $insertId";
  372. Database::query($sql);
  373. }
  374. $this->items[$item_id]->set_lp_view(
  375. $this->lp_view_id,
  376. $course_id
  377. );
  378. }
  379. }
  380. }
  381. }
  382. }
  383. }
  384. $this->ordered_items = self::get_flat_ordered_items_list(
  385. $this->get_id(),
  386. 0,
  387. $course_id
  388. );
  389. $this->max_ordered_items = 0;
  390. foreach ($this->ordered_items as $index => $dummy) {
  391. if ($index > $this->max_ordered_items && !empty($dummy)) {
  392. $this->max_ordered_items = $index;
  393. }
  394. }
  395. // TODO: Define the current item better.
  396. $this->first();
  397. if ($debug) {
  398. error_log('lp_view_session_id '.$this->lp_view_session_id);
  399. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  400. }
  401. } else {
  402. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  403. }
  404. }
  405. }
  406. /**
  407. * @return string
  408. */
  409. public function getCourseCode()
  410. {
  411. return $this->cc;
  412. }
  413. /**
  414. * @return int
  415. */
  416. public function get_course_int_id()
  417. {
  418. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  419. }
  420. /**
  421. * @param $course_id
  422. *
  423. * @return int
  424. */
  425. public function set_course_int_id($course_id)
  426. {
  427. return $this->course_int_id = (int) $course_id;
  428. }
  429. /**
  430. * Function rewritten based on old_add_item() from Yannick Warnier.
  431. * Due the fact that users can decide where the item should come, I had to overlook this function and
  432. * I found it better to rewrite it. Old function is still available.
  433. * Added also the possibility to add a description.
  434. *
  435. * @param int $parent
  436. * @param int $previous
  437. * @param string $type
  438. * @param int $id resource ID (ref)
  439. * @param string $title
  440. * @param string $description
  441. * @param int $prerequisites
  442. * @param int $max_time_allowed
  443. * @param int $userId
  444. *
  445. * @return int
  446. */
  447. public function add_item(
  448. $parent,
  449. $previous,
  450. $type = 'dir',
  451. $id,
  452. $title,
  453. $description,
  454. $prerequisites = 0,
  455. $max_time_allowed = 0,
  456. $userId = 0
  457. ) {
  458. $course_id = $this->course_info['real_id'];
  459. if (empty($course_id)) {
  460. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  461. $this->course_info = api_get_course_info($this->cc);
  462. $course_id = $this->course_info['real_id'];
  463. }
  464. $userId = empty($userId) ? api_get_user_id() : $userId;
  465. $sessionId = api_get_session_id();
  466. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  467. $_course = $this->course_info;
  468. $parent = (int) $parent;
  469. $previous = (int) $previous;
  470. $id = (int) $id;
  471. $max_time_allowed = htmlentities($max_time_allowed);
  472. if (empty($max_time_allowed)) {
  473. $max_time_allowed = 0;
  474. }
  475. $sql = "SELECT COUNT(iid) AS num
  476. FROM $tbl_lp_item
  477. WHERE
  478. c_id = $course_id AND
  479. lp_id = ".$this->get_id()." AND
  480. parent_item_id = $parent ";
  481. $res_count = Database::query($sql);
  482. $row = Database::fetch_array($res_count);
  483. $num = $row['num'];
  484. $tmp_previous = 0;
  485. $display_order = 0;
  486. $next = 0;
  487. if ($num > 0) {
  488. if (empty($previous)) {
  489. $sql = "SELECT iid, next_item_id, display_order
  490. FROM $tbl_lp_item
  491. WHERE
  492. c_id = $course_id AND
  493. lp_id = ".$this->get_id()." AND
  494. parent_item_id = $parent AND
  495. previous_item_id = 0 OR
  496. previous_item_id = $parent";
  497. $result = Database::query($sql);
  498. $row = Database::fetch_array($result);
  499. if ($row) {
  500. $next = $row['iid'];
  501. }
  502. } else {
  503. $previous = (int) $previous;
  504. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  505. FROM $tbl_lp_item
  506. WHERE
  507. c_id = $course_id AND
  508. lp_id = ".$this->get_id()." AND
  509. id = $previous";
  510. $result = Database::query($sql);
  511. $row = Database::fetch_array($result);
  512. if ($row) {
  513. $tmp_previous = $row['iid'];
  514. $next = $row['next_item_id'];
  515. $display_order = $row['display_order'];
  516. }
  517. }
  518. }
  519. $id = (int) $id;
  520. $typeCleaned = Database::escape_string($type);
  521. $max_score = 100;
  522. if ($type === 'quiz') {
  523. $sql = 'SELECT SUM(ponderation)
  524. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  525. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  526. ON
  527. quiz_question.id = quiz_rel_question.question_id AND
  528. quiz_question.c_id = quiz_rel_question.c_id
  529. WHERE
  530. quiz_rel_question.exercice_id = '.$id." AND
  531. quiz_question.c_id = $course_id AND
  532. quiz_rel_question.c_id = $course_id ";
  533. $rsQuiz = Database::query($sql);
  534. $max_score = Database::result($rsQuiz, 0, 0);
  535. // Disabling the exercise if we add it inside a LP
  536. $exercise = new Exercise($course_id);
  537. $exercise->read($id);
  538. $exercise->disable();
  539. $exercise->save();
  540. }
  541. $params = [
  542. 'c_id' => $course_id,
  543. 'lp_id' => $this->get_id(),
  544. 'item_type' => $typeCleaned,
  545. 'ref' => '',
  546. 'title' => $title,
  547. 'description' => $description,
  548. 'path' => $id,
  549. 'max_score' => $max_score,
  550. 'parent_item_id' => $parent,
  551. 'previous_item_id' => $previous,
  552. 'next_item_id' => (int) $next,
  553. 'display_order' => $display_order + 1,
  554. 'prerequisite' => $prerequisites,
  555. 'max_time_allowed' => $max_time_allowed,
  556. 'min_score' => 0,
  557. 'launch_data' => '',
  558. ];
  559. if ($prerequisites != 0) {
  560. $params['prerequisite'] = $prerequisites;
  561. }
  562. $new_item_id = Database::insert($tbl_lp_item, $params);
  563. if ($new_item_id) {
  564. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  565. Database::query($sql);
  566. if (!empty($next)) {
  567. $sql = "UPDATE $tbl_lp_item
  568. SET previous_item_id = $new_item_id
  569. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  570. Database::query($sql);
  571. }
  572. // Update the item that should be before the new item.
  573. if (!empty($tmp_previous)) {
  574. $sql = "UPDATE $tbl_lp_item
  575. SET next_item_id = $new_item_id
  576. WHERE c_id = $course_id AND id = $tmp_previous";
  577. Database::query($sql);
  578. }
  579. // Update all the items after the new item.
  580. $sql = "UPDATE $tbl_lp_item
  581. SET display_order = display_order + 1
  582. WHERE
  583. c_id = $course_id AND
  584. lp_id = ".$this->get_id()." AND
  585. iid <> $new_item_id AND
  586. parent_item_id = $parent AND
  587. display_order > $display_order";
  588. Database::query($sql);
  589. // Update the item that should come after the new item.
  590. $sql = "UPDATE $tbl_lp_item
  591. SET ref = $new_item_id
  592. WHERE c_id = $course_id AND iid = $new_item_id";
  593. Database::query($sql);
  594. $sql = "UPDATE $tbl_lp_item
  595. SET previous_item_id = ".$this->getLastInFirstLevel()."
  596. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  597. Database::query($sql);
  598. // Upload audio.
  599. if (!empty($_FILES['mp3']['name'])) {
  600. // Create the audio folder if it does not exist yet.
  601. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  602. if (!is_dir($filepath.'audio')) {
  603. mkdir(
  604. $filepath.'audio',
  605. api_get_permissions_for_new_directories()
  606. );
  607. $audio_id = DocumentManager::addDocument(
  608. $_course,
  609. '/audio',
  610. 'folder',
  611. 0,
  612. 'audio',
  613. '',
  614. 0,
  615. true,
  616. null,
  617. $sessionId,
  618. $userId
  619. );
  620. }
  621. $file_path = handle_uploaded_document(
  622. $_course,
  623. $_FILES['mp3'],
  624. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  625. '/audio',
  626. $userId,
  627. '',
  628. '',
  629. '',
  630. '',
  631. false
  632. );
  633. // Getting the filename only.
  634. $file_components = explode('/', $file_path);
  635. $file = $file_components[count($file_components) - 1];
  636. // Store the mp3 file in the lp_item table.
  637. $sql = "UPDATE $tbl_lp_item SET
  638. audio = '".Database::escape_string($file)."'
  639. WHERE iid = '".intval($new_item_id)."'";
  640. Database::query($sql);
  641. }
  642. }
  643. return $new_item_id;
  644. }
  645. /**
  646. * Static admin function allowing addition of a learnpath to a course.
  647. *
  648. * @param string $courseCode
  649. * @param string $name
  650. * @param string $description
  651. * @param string $learnpath
  652. * @param string $origin
  653. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  654. * @param string $publicated_on
  655. * @param string $expired_on
  656. * @param int $categoryId
  657. * @param int $userId
  658. *
  659. * @return int The new learnpath ID on success, 0 on failure
  660. */
  661. public static function add_lp(
  662. $courseCode,
  663. $name,
  664. $description = '',
  665. $learnpath = 'guess',
  666. $origin = 'zip',
  667. $zipname = '',
  668. $publicated_on = '',
  669. $expired_on = '',
  670. $categoryId = 0,
  671. $userId = 0
  672. ) {
  673. global $charset;
  674. if (!empty($courseCode)) {
  675. $courseInfo = api_get_course_info($courseCode);
  676. $course_id = $courseInfo['real_id'];
  677. } else {
  678. $course_id = api_get_course_int_id();
  679. $courseInfo = api_get_course_info();
  680. }
  681. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  682. // Check course code exists.
  683. // Check lp_name doesn't exist, otherwise append something.
  684. $i = 0;
  685. $categoryId = (int) $categoryId;
  686. // Session id.
  687. $session_id = api_get_session_id();
  688. $userId = empty($userId) ? api_get_user_id() : $userId;
  689. if (empty($publicated_on)) {
  690. $publicated_on = null;
  691. } else {
  692. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  693. }
  694. if (empty($expired_on)) {
  695. $expired_on = null;
  696. } else {
  697. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  698. }
  699. $check_name = "SELECT * FROM $tbl_lp
  700. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."'";
  701. $res_name = Database::query($check_name);
  702. while (Database::num_rows($res_name)) {
  703. // There is already one such name, update the current one a bit.
  704. $i++;
  705. $name = $name.' - '.$i;
  706. $check_name = "SELECT * FROM $tbl_lp
  707. WHERE c_id = $course_id AND name = '".Database::escape_string($name)."' ";
  708. $res_name = Database::query($check_name);
  709. }
  710. // New name does not exist yet; keep it.
  711. // Escape description.
  712. // Kevin: added htmlentities().
  713. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  714. $type = 1;
  715. switch ($learnpath) {
  716. case 'guess':
  717. break;
  718. case 'dokeos':
  719. case 'chamilo':
  720. $type = 1;
  721. break;
  722. case 'aicc':
  723. break;
  724. }
  725. switch ($origin) {
  726. case 'zip':
  727. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  728. break;
  729. case 'manual':
  730. default:
  731. $get_max = "SELECT MAX(display_order)
  732. FROM $tbl_lp WHERE c_id = $course_id";
  733. $res_max = Database::query($get_max);
  734. if (Database::num_rows($res_max) < 1) {
  735. $dsp = 1;
  736. } else {
  737. $row = Database::fetch_array($res_max);
  738. $dsp = $row[0] + 1;
  739. }
  740. $params = [
  741. 'c_id' => $course_id,
  742. 'lp_type' => $type,
  743. 'name' => $name,
  744. 'description' => $description,
  745. 'path' => '',
  746. 'default_view_mod' => 'embedded',
  747. 'default_encoding' => 'UTF-8',
  748. 'display_order' => $dsp,
  749. 'content_maker' => 'Chamilo',
  750. 'content_local' => 'local',
  751. 'js_lib' => '',
  752. 'session_id' => $session_id,
  753. 'created_on' => api_get_utc_datetime(),
  754. 'modified_on' => api_get_utc_datetime(),
  755. 'publicated_on' => $publicated_on,
  756. 'expired_on' => $expired_on,
  757. 'category_id' => $categoryId,
  758. 'force_commit' => 0,
  759. 'content_license' => '',
  760. 'debug' => 0,
  761. 'theme' => '',
  762. 'preview_image' => '',
  763. 'author' => '',
  764. 'prerequisite' => 0,
  765. 'hide_toc_frame' => 0,
  766. 'seriousgame_mode' => 0,
  767. 'autolaunch' => 0,
  768. 'max_attempts' => 0,
  769. 'subscribe_users' => 0,
  770. 'accumulate_scorm_time' => 1,
  771. ];
  772. $id = Database::insert($tbl_lp, $params);
  773. if ($id > 0) {
  774. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  775. Database::query($sql);
  776. // Insert into item_property.
  777. api_item_property_update(
  778. $courseInfo,
  779. TOOL_LEARNPATH,
  780. $id,
  781. 'LearnpathAdded',
  782. $userId
  783. );
  784. api_set_default_visibility(
  785. $id,
  786. TOOL_LEARNPATH,
  787. 0,
  788. $courseInfo,
  789. $session_id,
  790. $userId
  791. );
  792. return $id;
  793. }
  794. break;
  795. }
  796. }
  797. /**
  798. * Auto completes the parents of an item in case it's been completed or passed.
  799. *
  800. * @param int $item Optional ID of the item from which to look for parents
  801. */
  802. public function autocomplete_parents($item)
  803. {
  804. $debug = $this->debug;
  805. if (empty($item)) {
  806. $item = $this->current;
  807. }
  808. $currentItem = $this->getItem($item);
  809. if ($currentItem) {
  810. $parent_id = $currentItem->get_parent();
  811. $parent = $this->getItem($parent_id);
  812. if ($parent) {
  813. // if $item points to an object and there is a parent.
  814. if ($debug) {
  815. error_log(
  816. 'Autocompleting parent of item '.$item.' '.
  817. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  818. 0
  819. );
  820. }
  821. // New experiment including failed and browsed in completed status.
  822. //$current_status = $currentItem->get_status();
  823. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  824. // Fixes chapter auto complete
  825. if (true) {
  826. // If the current item is completed or passes or succeeded.
  827. $updateParentStatus = true;
  828. if ($debug) {
  829. error_log('Status of current item is alright');
  830. }
  831. foreach ($parent->get_children() as $childItemId) {
  832. $childItem = $this->getItem($childItemId);
  833. // If children was not set try to get the info
  834. if (empty($childItem->db_item_view_id)) {
  835. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  836. }
  837. // Check all his brothers (parent's children) for completion status.
  838. if ($childItemId != $item) {
  839. if ($debug) {
  840. error_log(
  841. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  842. 0
  843. );
  844. }
  845. // Trying completing parents of failed and browsed items as well.
  846. if ($childItem->status_is(
  847. [
  848. 'completed',
  849. 'passed',
  850. 'succeeded',
  851. 'browsed',
  852. 'failed',
  853. ]
  854. )
  855. ) {
  856. // Keep completion status to true.
  857. continue;
  858. } else {
  859. if ($debug > 2) {
  860. error_log(
  861. '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,
  862. 0
  863. );
  864. }
  865. $updateParentStatus = false;
  866. break;
  867. }
  868. }
  869. }
  870. if ($updateParentStatus) {
  871. // If all the children were completed:
  872. $parent->set_status('completed');
  873. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  874. // Force the status to "completed"
  875. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  876. $this->update_queue[$parent->get_id()] = 'completed';
  877. if ($debug) {
  878. error_log(
  879. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  880. print_r($this->update_queue, 1),
  881. 0
  882. );
  883. }
  884. // Recursive call.
  885. $this->autocomplete_parents($parent->get_id());
  886. }
  887. }
  888. } else {
  889. if ($debug) {
  890. error_log("Parent #$parent_id does not exists");
  891. }
  892. }
  893. } else {
  894. if ($debug) {
  895. error_log("#$item is an item that doesn't have parents");
  896. }
  897. }
  898. }
  899. /**
  900. * Closes the current resource.
  901. *
  902. * Stops the timer
  903. * Saves into the database if required
  904. * Clears the current resource data from this object
  905. *
  906. * @return bool True on success, false on failure
  907. */
  908. public function close()
  909. {
  910. if (empty($this->lp_id)) {
  911. $this->error = 'Trying to close this learnpath but no ID is set';
  912. return false;
  913. }
  914. $this->current_time_stop = time();
  915. $this->ordered_items = [];
  916. $this->index = 0;
  917. unset($this->lp_id);
  918. //unset other stuff
  919. return true;
  920. }
  921. /**
  922. * Static admin function allowing removal of a learnpath.
  923. *
  924. * @param array $courseInfo
  925. * @param int $id Learnpath ID
  926. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  927. *
  928. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  929. */
  930. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  931. {
  932. $course_id = api_get_course_int_id();
  933. if (!empty($courseInfo)) {
  934. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  935. }
  936. // TODO: Implement a way of getting this to work when the current object is not set.
  937. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  938. // If an ID is specifically given and the current LP is not the same, prevent delete.
  939. if (!empty($id) && ($id != $this->lp_id)) {
  940. return false;
  941. }
  942. $lp = Database::get_course_table(TABLE_LP_MAIN);
  943. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  944. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  945. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  946. // Delete lp item id.
  947. foreach ($this->items as $lpItemId => $dummy) {
  948. $sql = "DELETE FROM $lp_item_view
  949. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  950. Database::query($sql);
  951. }
  952. // Proposed by Christophe (nickname: clefevre)
  953. $sql = "DELETE FROM $lp_item
  954. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  955. Database::query($sql);
  956. $sql = "DELETE FROM $lp_view
  957. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  958. Database::query($sql);
  959. self::toggle_publish($this->lp_id, 'i');
  960. if ($this->type == 2 || $this->type == 3) {
  961. // This is a scorm learning path, delete the files as well.
  962. $sql = "SELECT path FROM $lp
  963. WHERE iid = ".$this->lp_id;
  964. $res = Database::query($sql);
  965. if (Database::num_rows($res) > 0) {
  966. $row = Database::fetch_array($res);
  967. $path = $row['path'];
  968. $sql = "SELECT id FROM $lp
  969. WHERE
  970. c_id = $course_id AND
  971. path = '$path' AND
  972. iid != ".$this->lp_id;
  973. $res = Database::query($sql);
  974. if (Database::num_rows($res) > 0) {
  975. // Another learning path uses this directory, so don't delete it.
  976. if ($this->debug > 2) {
  977. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  978. }
  979. } else {
  980. // No other LP uses that directory, delete it.
  981. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  982. // The absolute system path for this course.
  983. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  984. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  985. if ($this->debug > 2) {
  986. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  987. }
  988. // Proposed by Christophe (clefevre).
  989. if (strcmp(substr($path, -2), "/.") == 0) {
  990. $path = substr($path, 0, -1); // Remove "." at the end.
  991. }
  992. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  993. rmdirr($course_scorm_dir.$path);
  994. }
  995. }
  996. }
  997. }
  998. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  999. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1000. // Delete tools
  1001. $sql = "DELETE FROM $tbl_tool
  1002. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1003. Database::query($sql);
  1004. $sql = "DELETE FROM $lp
  1005. WHERE iid = ".$this->lp_id;
  1006. Database::query($sql);
  1007. // Updates the display order of all lps.
  1008. $this->update_display_order();
  1009. api_item_property_update(
  1010. api_get_course_info(),
  1011. TOOL_LEARNPATH,
  1012. $this->lp_id,
  1013. 'delete',
  1014. api_get_user_id()
  1015. );
  1016. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1017. api_get_course_id(),
  1018. 4,
  1019. $id,
  1020. api_get_session_id()
  1021. );
  1022. if ($link_info !== false) {
  1023. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1024. }
  1025. if (api_get_setting('search_enabled') == 'true') {
  1026. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1027. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1028. }
  1029. }
  1030. /**
  1031. * Removes all the children of one item - dangerous!
  1032. *
  1033. * @param int $id Element ID of which children have to be removed
  1034. *
  1035. * @return int Total number of children removed
  1036. */
  1037. public function delete_children_items($id)
  1038. {
  1039. $course_id = $this->course_info['real_id'];
  1040. $num = 0;
  1041. $id = (int) $id;
  1042. if (empty($id) || empty($course_id)) {
  1043. return false;
  1044. }
  1045. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1046. $sql = "SELECT * FROM $lp_item
  1047. WHERE c_id = $course_id AND parent_item_id = $id";
  1048. $res = Database::query($sql);
  1049. while ($row = Database::fetch_array($res)) {
  1050. $num += $this->delete_children_items($row['iid']);
  1051. $sql = "DELETE FROM $lp_item
  1052. WHERE c_id = $course_id AND iid = ".$row['iid'];
  1053. Database::query($sql);
  1054. $num++;
  1055. }
  1056. return $num;
  1057. }
  1058. /**
  1059. * Removes an item from the current learnpath.
  1060. *
  1061. * @param int $id Elem ID (0 if first)
  1062. *
  1063. * @return int Number of elements moved
  1064. *
  1065. * @todo implement resource removal
  1066. */
  1067. public function delete_item($id)
  1068. {
  1069. $course_id = api_get_course_int_id();
  1070. $id = (int) $id;
  1071. // TODO: Implement the resource removal.
  1072. if (empty($id) || empty($course_id)) {
  1073. return false;
  1074. }
  1075. // First select item to get previous, next, and display order.
  1076. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1077. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1078. $res_sel = Database::query($sql_sel);
  1079. if (Database::num_rows($res_sel) < 1) {
  1080. return false;
  1081. }
  1082. $row = Database::fetch_array($res_sel);
  1083. $previous = $row['previous_item_id'];
  1084. $next = $row['next_item_id'];
  1085. $display = $row['display_order'];
  1086. $parent = $row['parent_item_id'];
  1087. $lp = $row['lp_id'];
  1088. // Delete children items.
  1089. $this->delete_children_items($id);
  1090. // Now delete the item.
  1091. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1092. Database::query($sql_del);
  1093. // Now update surrounding items.
  1094. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1095. WHERE iid = $previous";
  1096. Database::query($sql_upd);
  1097. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1098. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1099. Database::query($sql_upd);
  1100. // Now update all following items with new display order.
  1101. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1102. WHERE
  1103. c_id = $course_id AND
  1104. lp_id = $lp AND
  1105. parent_item_id = $parent AND
  1106. display_order > $display";
  1107. Database::query($sql_all);
  1108. //Removing prerequisites since the item will not longer exist
  1109. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1110. WHERE c_id = $course_id AND prerequisite = $id";
  1111. Database::query($sql_all);
  1112. $sql = "UPDATE $lp_item
  1113. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1114. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1115. Database::query($sql);
  1116. // Remove from search engine if enabled.
  1117. if (api_get_setting('search_enabled') === 'true') {
  1118. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1119. $sql = 'SELECT * FROM %s
  1120. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1121. LIMIT 1';
  1122. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1123. $res = Database::query($sql);
  1124. if (Database::num_rows($res) > 0) {
  1125. $row2 = Database::fetch_array($res);
  1126. $di = new ChamiloIndexer();
  1127. $di->remove_document($row2['search_did']);
  1128. }
  1129. $sql = 'DELETE FROM %s
  1130. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1131. LIMIT 1';
  1132. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1133. Database::query($sql);
  1134. }
  1135. }
  1136. /**
  1137. * Updates an item's content in place.
  1138. *
  1139. * @param int $id Element ID
  1140. * @param int $parent Parent item ID
  1141. * @param int $previous Previous item ID
  1142. * @param string $title Item title
  1143. * @param string $description Item description
  1144. * @param string $prerequisites Prerequisites (optional)
  1145. * @param array $audio The array resulting of the $_FILES[mp3] element
  1146. * @param int $max_time_allowed
  1147. * @param string $url
  1148. *
  1149. * @return bool True on success, false on error
  1150. */
  1151. public function edit_item(
  1152. $id,
  1153. $parent,
  1154. $previous,
  1155. $title,
  1156. $description,
  1157. $prerequisites = '0',
  1158. $audio = [],
  1159. $max_time_allowed = 0,
  1160. $url = ''
  1161. ) {
  1162. $course_id = api_get_course_int_id();
  1163. $_course = api_get_course_info();
  1164. $id = (int) $id;
  1165. if (empty($max_time_allowed)) {
  1166. $max_time_allowed = 0;
  1167. }
  1168. if (empty($id) || empty($_course)) {
  1169. return false;
  1170. }
  1171. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1172. $sql = "SELECT * FROM $tbl_lp_item
  1173. WHERE iid = $id";
  1174. $res_select = Database::query($sql);
  1175. $row_select = Database::fetch_array($res_select);
  1176. $audio_update_sql = '';
  1177. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1178. // Create the audio folder if it does not exist yet.
  1179. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1180. if (!is_dir($filepath.'audio')) {
  1181. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1182. $audio_id = DocumentManager::addDocument(
  1183. $_course,
  1184. '/audio',
  1185. 'folder',
  1186. 0,
  1187. 'audio'
  1188. );
  1189. }
  1190. // Upload file in documents.
  1191. $pi = pathinfo($audio['name']);
  1192. if ($pi['extension'] === 'mp3') {
  1193. $c_det = api_get_course_info($this->cc);
  1194. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1195. $path = handle_uploaded_document(
  1196. $c_det,
  1197. $audio,
  1198. $bp,
  1199. '/audio',
  1200. api_get_user_id(),
  1201. 0,
  1202. null,
  1203. 0,
  1204. 'rename',
  1205. false,
  1206. 0
  1207. );
  1208. $path = substr($path, 7);
  1209. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1210. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1211. }
  1212. }
  1213. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1214. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1215. // TODO: htmlspecialchars to be checked for encoding related problems.
  1216. if ($same_parent && $same_previous) {
  1217. // Only update title and description.
  1218. $sql = "UPDATE $tbl_lp_item
  1219. SET title = '".Database::escape_string($title)."',
  1220. prerequisite = '".$prerequisites."',
  1221. description = '".Database::escape_string($description)."'
  1222. ".$audio_update_sql.",
  1223. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1224. WHERE iid = $id";
  1225. Database::query($sql);
  1226. } else {
  1227. $old_parent = $row_select['parent_item_id'];
  1228. $old_previous = $row_select['previous_item_id'];
  1229. $old_next = $row_select['next_item_id'];
  1230. $old_order = $row_select['display_order'];
  1231. $old_prerequisite = $row_select['prerequisite'];
  1232. $old_max_time_allowed = $row_select['max_time_allowed'];
  1233. /* BEGIN -- virtually remove the current item id */
  1234. /* for the next and previous item it is like the current item doesn't exist anymore */
  1235. if ($old_previous != 0) {
  1236. // Next
  1237. $sql = "UPDATE $tbl_lp_item
  1238. SET next_item_id = $old_next
  1239. WHERE iid = $old_previous";
  1240. Database::query($sql);
  1241. }
  1242. if (!empty($old_next)) {
  1243. // Previous
  1244. $sql = "UPDATE $tbl_lp_item
  1245. SET previous_item_id = $old_previous
  1246. WHERE iid = $old_next";
  1247. Database::query($sql);
  1248. }
  1249. // display_order - 1 for every item with a display_order
  1250. // bigger then the display_order of the current item.
  1251. $sql = "UPDATE $tbl_lp_item
  1252. SET display_order = display_order - 1
  1253. WHERE
  1254. c_id = $course_id AND
  1255. display_order > $old_order AND
  1256. lp_id = ".$this->lp_id." AND
  1257. parent_item_id = $old_parent";
  1258. Database::query($sql);
  1259. /* END -- virtually remove the current item id */
  1260. /* BEGIN -- update the current item id to his new location */
  1261. if ($previous == 0) {
  1262. // Select the data of the item that should come after the current item.
  1263. $sql = "SELECT id, display_order
  1264. FROM $tbl_lp_item
  1265. WHERE
  1266. c_id = $course_id AND
  1267. lp_id = ".$this->lp_id." AND
  1268. parent_item_id = $parent AND
  1269. previous_item_id = $previous";
  1270. $res_select_old = Database::query($sql);
  1271. $row_select_old = Database::fetch_array($res_select_old);
  1272. // If the new parent didn't have children before.
  1273. if (Database::num_rows($res_select_old) == 0) {
  1274. $new_next = 0;
  1275. $new_order = 1;
  1276. } else {
  1277. $new_next = $row_select_old['id'];
  1278. $new_order = $row_select_old['display_order'];
  1279. }
  1280. } else {
  1281. // Select the data of the item that should come before the current item.
  1282. $sql = "SELECT next_item_id, display_order
  1283. FROM $tbl_lp_item
  1284. WHERE iid = $previous";
  1285. $res_select_old = Database::query($sql);
  1286. $row_select_old = Database::fetch_array($res_select_old);
  1287. $new_next = $row_select_old['next_item_id'];
  1288. $new_order = $row_select_old['display_order'] + 1;
  1289. }
  1290. // TODO: htmlspecialchars to be checked for encoding related problems.
  1291. // Update the current item with the new data.
  1292. $sql = "UPDATE $tbl_lp_item
  1293. SET
  1294. title = '".Database::escape_string($title)."',
  1295. description = '".Database::escape_string($description)."',
  1296. parent_item_id = $parent,
  1297. previous_item_id = $previous,
  1298. next_item_id = $new_next,
  1299. display_order = $new_order
  1300. $audio_update_sql
  1301. WHERE iid = $id";
  1302. Database::query($sql);
  1303. if ($previous != 0) {
  1304. // Update the previous item's next_item_id.
  1305. $sql = "UPDATE $tbl_lp_item
  1306. SET next_item_id = $id
  1307. WHERE iid = $previous";
  1308. Database::query($sql);
  1309. }
  1310. if (!empty($new_next)) {
  1311. // Update the next item's previous_item_id.
  1312. $sql = "UPDATE $tbl_lp_item
  1313. SET previous_item_id = $id
  1314. WHERE iid = $new_next";
  1315. Database::query($sql);
  1316. }
  1317. if ($old_prerequisite != $prerequisites) {
  1318. $sql = "UPDATE $tbl_lp_item
  1319. SET prerequisite = '$prerequisites'
  1320. WHERE iid = $id";
  1321. Database::query($sql);
  1322. }
  1323. if ($old_max_time_allowed != $max_time_allowed) {
  1324. // update max time allowed
  1325. $sql = "UPDATE $tbl_lp_item
  1326. SET max_time_allowed = $max_time_allowed
  1327. WHERE iid = $id";
  1328. Database::query($sql);
  1329. }
  1330. // Update all the items with the same or a bigger display_order than the current item.
  1331. $sql = "UPDATE $tbl_lp_item
  1332. SET display_order = display_order + 1
  1333. WHERE
  1334. c_id = $course_id AND
  1335. lp_id = ".$this->get_id()." AND
  1336. iid <> $id AND
  1337. parent_item_id = $parent AND
  1338. display_order >= $new_order";
  1339. Database::query($sql);
  1340. }
  1341. if ($row_select['item_type'] == 'link') {
  1342. $link = new Link();
  1343. $linkId = $row_select['path'];
  1344. $link->updateLink($linkId, $url);
  1345. }
  1346. }
  1347. /**
  1348. * Updates an item's prereq in place.
  1349. *
  1350. * @param int $id Element ID
  1351. * @param string $prerequisite_id Prerequisite Element ID
  1352. * @param int $minScore Prerequisite min score
  1353. * @param int $maxScore Prerequisite max score
  1354. *
  1355. * @return bool True on success, false on error
  1356. */
  1357. public function edit_item_prereq(
  1358. $id,
  1359. $prerequisite_id,
  1360. $minScore = 0,
  1361. $maxScore = 100
  1362. ) {
  1363. $id = (int) $id;
  1364. $prerequisite_id = (int) $prerequisite_id;
  1365. if (empty($id)) {
  1366. return false;
  1367. }
  1368. if (empty($minScore) || $minScore < 0) {
  1369. $minScore = 0;
  1370. }
  1371. if (empty($maxScore) || $maxScore < 0) {
  1372. $maxScore = 100;
  1373. }
  1374. $minScore = floatval($minScore);
  1375. $maxScore = floatval($maxScore);
  1376. if (empty($prerequisite_id)) {
  1377. $prerequisite_id = 'NULL';
  1378. $minScore = 0;
  1379. $maxScore = 100;
  1380. }
  1381. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1382. $sql = " UPDATE $tbl_lp_item
  1383. SET
  1384. prerequisite = $prerequisite_id ,
  1385. prerequisite_min_score = $minScore ,
  1386. prerequisite_max_score = $maxScore
  1387. WHERE iid = $id";
  1388. Database::query($sql);
  1389. return true;
  1390. }
  1391. /**
  1392. * Get the specific prefix index terms of this learning path.
  1393. *
  1394. * @param string $prefix
  1395. *
  1396. * @return array Array of terms
  1397. */
  1398. public function get_common_index_terms_by_prefix($prefix)
  1399. {
  1400. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1401. $terms = get_specific_field_values_list_by_prefix(
  1402. $prefix,
  1403. $this->cc,
  1404. TOOL_LEARNPATH,
  1405. $this->lp_id
  1406. );
  1407. $prefix_terms = [];
  1408. if (!empty($terms)) {
  1409. foreach ($terms as $term) {
  1410. $prefix_terms[] = $term['value'];
  1411. }
  1412. }
  1413. return $prefix_terms;
  1414. }
  1415. /**
  1416. * Gets the number of items currently completed.
  1417. *
  1418. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1419. *
  1420. * @return int The number of items currently completed
  1421. */
  1422. public function get_complete_items_count($failedStatusException = false)
  1423. {
  1424. $i = 0;
  1425. $completedStatusList = [
  1426. 'completed',
  1427. 'passed',
  1428. 'succeeded',
  1429. 'browsed',
  1430. ];
  1431. if (!$failedStatusException) {
  1432. $completedStatusList[] = 'failed';
  1433. }
  1434. foreach ($this->items as $id => $dummy) {
  1435. // Trying failed and browsed considered "progressed" as well.
  1436. if ($this->items[$id]->status_is($completedStatusList) &&
  1437. $this->items[$id]->get_type() != 'dir'
  1438. ) {
  1439. $i++;
  1440. }
  1441. }
  1442. return $i;
  1443. }
  1444. /**
  1445. * Gets the current item ID.
  1446. *
  1447. * @return int The current learnpath item id
  1448. */
  1449. public function get_current_item_id()
  1450. {
  1451. $current = 0;
  1452. if (!empty($this->current)) {
  1453. $current = (int) $this->current;
  1454. }
  1455. return $current;
  1456. }
  1457. /**
  1458. * Force to get the first learnpath item id.
  1459. *
  1460. * @return int The current learnpath item id
  1461. */
  1462. public function get_first_item_id()
  1463. {
  1464. $current = 0;
  1465. if (is_array($this->ordered_items)) {
  1466. $current = $this->ordered_items[0];
  1467. }
  1468. return $current;
  1469. }
  1470. /**
  1471. * Gets the total number of items available for viewing in this SCORM.
  1472. *
  1473. * @return int The total number of items
  1474. */
  1475. public function get_total_items_count()
  1476. {
  1477. return count($this->items);
  1478. }
  1479. /**
  1480. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1481. *
  1482. * @return int The total no-chapters number of items
  1483. */
  1484. public function getTotalItemsCountWithoutDirs()
  1485. {
  1486. $total = 0;
  1487. $typeListNotToCount = self::getChapterTypes();
  1488. foreach ($this->items as $temp2) {
  1489. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1490. $total++;
  1491. }
  1492. }
  1493. return $total;
  1494. }
  1495. /**
  1496. * Sets the first element URL.
  1497. */
  1498. public function first()
  1499. {
  1500. if ($this->debug > 0) {
  1501. error_log('In learnpath::first()', 0);
  1502. error_log('$this->last_item_seen '.$this->last_item_seen);
  1503. }
  1504. // Test if the last_item_seen exists and is not a dir.
  1505. if (count($this->ordered_items) == 0) {
  1506. $this->index = 0;
  1507. }
  1508. if (!empty($this->last_item_seen) &&
  1509. !empty($this->items[$this->last_item_seen]) &&
  1510. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1511. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1512. //&& !$this->items[$this->last_item_seen]->is_done()
  1513. ) {
  1514. if ($this->debug > 2) {
  1515. error_log(
  1516. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1517. $this->items[$this->last_item_seen]->get_type()
  1518. );
  1519. }
  1520. $index = -1;
  1521. foreach ($this->ordered_items as $myindex => $item_id) {
  1522. if ($item_id == $this->last_item_seen) {
  1523. $index = $myindex;
  1524. break;
  1525. }
  1526. }
  1527. if ($index == -1) {
  1528. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1529. if ($this->debug > 2) {
  1530. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1531. }
  1532. return false;
  1533. } else {
  1534. $this->last = $this->last_item_seen;
  1535. $this->current = $this->last_item_seen;
  1536. $this->index = $index;
  1537. }
  1538. } else {
  1539. if ($this->debug > 2) {
  1540. error_log('In learnpath::first() - No last item seen', 0);
  1541. }
  1542. $index = 0;
  1543. // Loop through all ordered items and stop at the first item that is
  1544. // not a directory *and* that has not been completed yet.
  1545. while (!empty($this->ordered_items[$index]) &&
  1546. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1547. (
  1548. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1549. $this->items[$this->ordered_items[$index]]->is_done() === true
  1550. ) && $index < $this->max_ordered_items) {
  1551. $index++;
  1552. }
  1553. $this->last = $this->current;
  1554. // current is
  1555. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1556. $this->index = $index;
  1557. if ($this->debug > 2) {
  1558. error_log('$index '.$index);
  1559. error_log('In learnpath::first() - No last item seen');
  1560. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1561. }
  1562. }
  1563. if ($this->debug > 2) {
  1564. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1565. }
  1566. }
  1567. /**
  1568. * Gets the js library from the database.
  1569. *
  1570. * @return string The name of the javascript library to be used
  1571. */
  1572. public function get_js_lib()
  1573. {
  1574. $lib = '';
  1575. if (!empty($this->js_lib)) {
  1576. $lib = $this->js_lib;
  1577. }
  1578. return $lib;
  1579. }
  1580. /**
  1581. * Gets the learnpath database ID.
  1582. *
  1583. * @return int Learnpath ID in the lp table
  1584. */
  1585. public function get_id()
  1586. {
  1587. if (!empty($this->lp_id)) {
  1588. return (int) $this->lp_id;
  1589. }
  1590. return 0;
  1591. }
  1592. /**
  1593. * Gets the last element URL.
  1594. *
  1595. * @return string URL to load into the viewer
  1596. */
  1597. public function get_last()
  1598. {
  1599. // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1600. if (count($this->ordered_items) > 0) {
  1601. $this->index = count($this->ordered_items) - 1;
  1602. return $this->ordered_items[$this->index];
  1603. }
  1604. return false;
  1605. }
  1606. /**
  1607. * Get the last element in the first level.
  1608. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1609. *
  1610. * @return mixed
  1611. */
  1612. public function getLastInFirstLevel()
  1613. {
  1614. try {
  1615. $lastId = Database::getManager()
  1616. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1617. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1618. ->setMaxResults(1)
  1619. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1620. ->getSingleScalarResult();
  1621. return $lastId;
  1622. } catch (Exception $exception) {
  1623. return 0;
  1624. }
  1625. }
  1626. /**
  1627. * Gets the navigation bar for the learnpath display screen.
  1628. *
  1629. * @param string $barId
  1630. *
  1631. * @return string The HTML string to use as a navigation bar
  1632. */
  1633. public function get_navigation_bar($barId = '')
  1634. {
  1635. if (empty($barId)) {
  1636. $barId = 'control-top';
  1637. }
  1638. $lpId = $this->lp_id;
  1639. $mycurrentitemid = $this->get_current_item_id();
  1640. $reportingText = get_lang('Reporting');
  1641. $previousText = get_lang('Previous');
  1642. $nextText = get_lang('Next');
  1643. $fullScreenText = get_lang('Back to normal screen');
  1644. $settings = api_get_configuration_value('lp_view_settings');
  1645. $display = isset($settings['display']) ? $settings['display'] : false;
  1646. $reportingIcon = '
  1647. <a class="icon-toolbar"
  1648. id="stats_link"
  1649. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1650. onclick="window.parent.API.save_asset(); return true;"
  1651. target="content_name" title="'.$reportingText.'">
  1652. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1653. </a>';
  1654. if (!empty($display)) {
  1655. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1656. if ($showReporting === false) {
  1657. $reportingIcon = '';
  1658. }
  1659. }
  1660. $hideArrows = false;
  1661. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1662. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1663. }
  1664. $previousIcon = '';
  1665. $nextIcon = '';
  1666. if ($hideArrows === false) {
  1667. $previousIcon = '
  1668. <a class="icon-toolbar" id="scorm-previous" href="#"
  1669. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1670. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1671. </a>';
  1672. $nextIcon = '
  1673. <a class="icon-toolbar" id="scorm-next" href="#"
  1674. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1675. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1676. </a>';
  1677. }
  1678. if ($this->mode === 'fullscreen') {
  1679. $navbar = '
  1680. <span id="'.$barId.'" class="buttons">
  1681. '.$reportingIcon.'
  1682. '.$previousIcon.'
  1683. '.$nextIcon.'
  1684. <a class="icon-toolbar" id="view-embedded"
  1685. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1686. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1687. </a>
  1688. </span>';
  1689. } else {
  1690. $navbar = '
  1691. <span id="'.$barId.'" class="buttons text-right">
  1692. '.$reportingIcon.'
  1693. '.$previousIcon.'
  1694. '.$nextIcon.'
  1695. </span>';
  1696. }
  1697. return $navbar;
  1698. }
  1699. /**
  1700. * Gets the next resource in queue (url).
  1701. *
  1702. * @return string URL to load into the viewer
  1703. */
  1704. public function get_next_index()
  1705. {
  1706. // TODO
  1707. $index = $this->index;
  1708. $index++;
  1709. while (
  1710. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1711. $index < $this->max_ordered_items
  1712. ) {
  1713. $index++;
  1714. if ($index == $this->max_ordered_items) {
  1715. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1716. return $this->index;
  1717. }
  1718. return $index;
  1719. }
  1720. }
  1721. if (empty($this->ordered_items[$index])) {
  1722. return $this->index;
  1723. }
  1724. return $index;
  1725. }
  1726. /**
  1727. * Gets item_id for the next element.
  1728. *
  1729. * @return int Next item (DB) ID
  1730. */
  1731. public function get_next_item_id()
  1732. {
  1733. $new_index = $this->get_next_index();
  1734. if (!empty($new_index)) {
  1735. if (isset($this->ordered_items[$new_index])) {
  1736. return $this->ordered_items[$new_index];
  1737. }
  1738. }
  1739. return 0;
  1740. }
  1741. /**
  1742. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1743. *
  1744. * Generally, the package provided is in the form of a zip file, so the function
  1745. * has been written to test a zip file. If not a zip, the function will return the
  1746. * default return value: ''
  1747. *
  1748. * @param string $file_path the path to the file
  1749. * @param string $file_name the original name of the file
  1750. *
  1751. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1752. */
  1753. public static function get_package_type($file_path, $file_name)
  1754. {
  1755. // Get name of the zip file without the extension.
  1756. $file_info = pathinfo($file_name);
  1757. $extension = $file_info['extension']; // Extension only.
  1758. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1759. 'dll',
  1760. 'exe',
  1761. ])) {
  1762. return 'oogie';
  1763. }
  1764. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1765. 'dll',
  1766. 'exe',
  1767. ])) {
  1768. return 'woogie';
  1769. }
  1770. $zipFile = new PclZip($file_path);
  1771. // Check the zip content (real size and file extension).
  1772. $zipContentArray = $zipFile->listContent();
  1773. $package_type = '';
  1774. $manifest = '';
  1775. $aicc_match_crs = 0;
  1776. $aicc_match_au = 0;
  1777. $aicc_match_des = 0;
  1778. $aicc_match_cst = 0;
  1779. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1780. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1781. foreach ($zipContentArray as $thisContent) {
  1782. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1783. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1784. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1785. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1786. $package_type = 'scorm';
  1787. break; // Exit the foreach loop.
  1788. } elseif (
  1789. preg_match('/aicc\//i', $thisContent['filename']) ||
  1790. in_array(
  1791. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1792. ['crs', 'au', 'des', 'cst']
  1793. )
  1794. ) {
  1795. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  1796. switch ($ext) {
  1797. case 'crs':
  1798. $aicc_match_crs = 1;
  1799. break;
  1800. case 'au':
  1801. $aicc_match_au = 1;
  1802. break;
  1803. case 'des':
  1804. $aicc_match_des = 1;
  1805. break;
  1806. case 'cst':
  1807. $aicc_match_cst = 1;
  1808. break;
  1809. default:
  1810. break;
  1811. }
  1812. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  1813. } else {
  1814. $package_type = '';
  1815. }
  1816. }
  1817. }
  1818. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  1819. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  1820. $package_type = 'aicc';
  1821. }
  1822. // Try with chamilo course builder
  1823. if (empty($package_type)) {
  1824. $package_type = 'chamilo';
  1825. }
  1826. return $package_type;
  1827. }
  1828. /**
  1829. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  1830. *
  1831. * @return string URL to load into the viewer
  1832. */
  1833. public function get_previous_index()
  1834. {
  1835. $index = $this->index;
  1836. if (isset($this->ordered_items[$index - 1])) {
  1837. $index--;
  1838. while (isset($this->ordered_items[$index]) &&
  1839. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  1840. ) {
  1841. $index--;
  1842. if ($index < 0) {
  1843. return $this->index;
  1844. }
  1845. }
  1846. }
  1847. return $index;
  1848. }
  1849. /**
  1850. * Gets item_id for the next element.
  1851. *
  1852. * @return int Previous item (DB) ID
  1853. */
  1854. public function get_previous_item_id()
  1855. {
  1856. $index = $this->get_previous_index();
  1857. return $this->ordered_items[$index];
  1858. }
  1859. /**
  1860. * Returns the HTML necessary to print a mediaplayer block inside a page.
  1861. *
  1862. * @param int $lpItemId
  1863. * @param string $autostart
  1864. *
  1865. * @return string The mediaplayer HTML
  1866. */
  1867. public function get_mediaplayer($lpItemId, $autostart = 'true')
  1868. {
  1869. $course_id = api_get_course_int_id();
  1870. $_course = api_get_course_info();
  1871. if (empty($_course)) {
  1872. return '';
  1873. }
  1874. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1875. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1876. $lpItemId = (int) $lpItemId;
  1877. /** @var learnpathItem $item */
  1878. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  1879. $itemViewId = 0;
  1880. if ($item) {
  1881. $itemViewId = (int) $item->db_item_view_id;
  1882. }
  1883. // Getting all the information about the item.
  1884. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  1885. FROM $tbl_lp_item as lpi
  1886. INNER JOIN $tbl_lp_item_view as lp_view
  1887. ON (lpi.iid = lp_view.lp_item_id)
  1888. WHERE
  1889. lp_view.iid = $itemViewId AND
  1890. lpi.iid = $lpItemId AND
  1891. lp_view.c_id = $course_id";
  1892. $result = Database::query($sql);
  1893. $row = Database::fetch_assoc($result);
  1894. $output = '';
  1895. if (!empty($row['audio'])) {
  1896. $list = $_SESSION['oLP']->get_toc();
  1897. switch ($row['item_type']) {
  1898. case 'quiz':
  1899. $type_quiz = false;
  1900. foreach ($list as $toc) {
  1901. if ($toc['id'] == $_SESSION['oLP']->current) {
  1902. $type_quiz = true;
  1903. }
  1904. }
  1905. if ($type_quiz) {
  1906. if ($_SESSION['oLP']->prevent_reinit == 1) {
  1907. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  1908. } else {
  1909. $autostart_audio = $autostart;
  1910. }
  1911. }
  1912. break;
  1913. case TOOL_READOUT_TEXT:;
  1914. $autostart_audio = 'false';
  1915. break;
  1916. default:
  1917. $autostart_audio = 'true';
  1918. }
  1919. $courseInfo = api_get_course_info();
  1920. $audio = $row['audio'];
  1921. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  1922. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  1923. if (!file_exists($file)) {
  1924. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  1925. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  1926. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  1927. }
  1928. $player = Display::getMediaPlayer(
  1929. $file,
  1930. [
  1931. 'id' => 'lp_audio_media_player',
  1932. 'url' => $url,
  1933. 'autoplay' => $autostart_audio,
  1934. 'width' => '100%',
  1935. ]
  1936. );
  1937. // The mp3 player.
  1938. $output = '<div id="container">';
  1939. $output .= $player;
  1940. $output .= '</div>';
  1941. }
  1942. return $output;
  1943. }
  1944. /**
  1945. * @param int $studentId
  1946. * @param int $prerequisite
  1947. * @param array $courseInfo
  1948. * @param int $sessionId
  1949. *
  1950. * @return bool
  1951. */
  1952. public static function isBlockedByPrerequisite(
  1953. $studentId,
  1954. $prerequisite,
  1955. $courseInfo,
  1956. $sessionId
  1957. ) {
  1958. if (empty($courseInfo)) {
  1959. return false;
  1960. }
  1961. $courseId = $courseInfo['real_id'];
  1962. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  1963. if ($allow) {
  1964. if (api_is_allowed_to_edit() ||
  1965. api_is_platform_admin(true) ||
  1966. api_is_drh() ||
  1967. api_is_coach($sessionId, $courseId, false)
  1968. ) {
  1969. return false;
  1970. }
  1971. }
  1972. $isBlocked = false;
  1973. if (!empty($prerequisite)) {
  1974. $progress = self::getProgress(
  1975. $prerequisite,
  1976. $studentId,
  1977. $courseId,
  1978. $sessionId
  1979. );
  1980. if ($progress < 100) {
  1981. $isBlocked = true;
  1982. }
  1983. if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  1984. // Block if it does not exceed minimum time
  1985. // Minimum time (in minutes) to pass the learning path
  1986. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  1987. if ($accumulateWorkTime > 0) {
  1988. // Total time in course (sum of times in learning paths from course)
  1989. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  1990. // Connect with the plugin_licences_course_session table
  1991. // which indicates what percentage of the time applies
  1992. // Minimum connection percentage
  1993. $perc = 100;
  1994. // Time from the course
  1995. $tc = $accumulateWorkTimeTotal;
  1996. // Percentage of the learning paths
  1997. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  1998. // Minimum time for each learning path
  1999. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2000. // Spent time (in seconds) so far in the learning path
  2001. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2002. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2003. if ($lpTime < ($accumulateWorkTime * 60)) {
  2004. $isBlocked = true;
  2005. }
  2006. }
  2007. }
  2008. }
  2009. return $isBlocked;
  2010. }
  2011. /**
  2012. * Checks if the learning path is visible for student after the progress
  2013. * of its prerequisite is completed, considering the time availability and
  2014. * the LP visibility.
  2015. *
  2016. * @param int $lp_id
  2017. * @param int $student_id
  2018. * @param array $courseInfo
  2019. * @param int $sessionId
  2020. *
  2021. * @return bool
  2022. */
  2023. public static function is_lp_visible_for_student(
  2024. $lp_id,
  2025. $student_id,
  2026. $courseInfo = [],
  2027. $sessionId = 0
  2028. ) {
  2029. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2030. $lp_id = (int) $lp_id;
  2031. $sessionId = (int) $sessionId;
  2032. if (empty($courseInfo)) {
  2033. return false;
  2034. }
  2035. if (empty($sessionId)) {
  2036. $sessionId = api_get_session_id();
  2037. }
  2038. $courseId = $courseInfo['real_id'];
  2039. $itemInfo = api_get_item_property_info(
  2040. $courseId,
  2041. TOOL_LEARNPATH,
  2042. $lp_id,
  2043. $sessionId
  2044. );
  2045. // If the item was deleted.
  2046. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2047. return false;
  2048. }
  2049. // @todo remove this query and load the row info as a parameter
  2050. $table = Database::get_course_table(TABLE_LP_MAIN);
  2051. // Get current prerequisite
  2052. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on, category_id
  2053. FROM $table
  2054. WHERE iid = $lp_id";
  2055. $rs = Database::query($sql);
  2056. $now = time();
  2057. if (Database::num_rows($rs) > 0) {
  2058. $row = Database::fetch_array($rs, 'ASSOC');
  2059. if (!empty($row['category_id'])) {
  2060. $em = Database::getManager();
  2061. $category = $em->getRepository('ChamiloCourseBundle:CLpCategory')->find($row['category_id']);
  2062. if (self::categoryIsVisibleForStudent($category, api_get_user_entity($student_id)) === false) {
  2063. return false;
  2064. }
  2065. }
  2066. $prerequisite = $row['prerequisite'];
  2067. $is_visible = true;
  2068. $isBlocked = self::isBlockedByPrerequisite(
  2069. $student_id,
  2070. $prerequisite,
  2071. $courseInfo,
  2072. $sessionId
  2073. );
  2074. if ($isBlocked) {
  2075. $is_visible = false;
  2076. }
  2077. // Also check the time availability of the LP
  2078. if ($is_visible) {
  2079. // Adding visibility restrictions
  2080. if (!empty($row['publicated_on'])) {
  2081. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2082. $is_visible = false;
  2083. }
  2084. }
  2085. // Blocking empty start times see BT#2800
  2086. global $_custom;
  2087. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2088. $_custom['lps_hidden_when_no_start_date']
  2089. ) {
  2090. if (empty($row['publicated_on'])) {
  2091. $is_visible = false;
  2092. }
  2093. }
  2094. if (!empty($row['expired_on'])) {
  2095. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2096. $is_visible = false;
  2097. }
  2098. }
  2099. }
  2100. if ($is_visible) {
  2101. $subscriptionSettings = self::getSubscriptionSettings();
  2102. // Check if the subscription users/group to a LP is ON
  2103. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2104. $subscriptionSettings['allow_add_users_to_lp'] === true
  2105. ) {
  2106. // Try group
  2107. $is_visible = false;
  2108. // Checking only the user visibility
  2109. $userVisibility = api_get_item_visibility(
  2110. $courseInfo,
  2111. 'learnpath',
  2112. $row['id'],
  2113. $sessionId,
  2114. $student_id,
  2115. 'LearnpathSubscription'
  2116. );
  2117. if ($userVisibility == 1) {
  2118. $is_visible = true;
  2119. } else {
  2120. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id, $courseId);
  2121. if (!empty($userGroups)) {
  2122. foreach ($userGroups as $groupInfo) {
  2123. $groupId = $groupInfo['iid'];
  2124. $userVisibility = api_get_item_visibility(
  2125. $courseInfo,
  2126. 'learnpath',
  2127. $row['id'],
  2128. $sessionId,
  2129. null,
  2130. 'LearnpathSubscription',
  2131. $groupId
  2132. );
  2133. if ($userVisibility == 1) {
  2134. $is_visible = true;
  2135. break;
  2136. }
  2137. }
  2138. }
  2139. }
  2140. }
  2141. }
  2142. return $is_visible;
  2143. }
  2144. return false;
  2145. }
  2146. /**
  2147. * @param int $lpId
  2148. * @param int $userId
  2149. * @param int $courseId
  2150. * @param int $sessionId
  2151. *
  2152. * @return int
  2153. */
  2154. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2155. {
  2156. $lpId = (int) $lpId;
  2157. $userId = (int) $userId;
  2158. $courseId = (int) $courseId;
  2159. $sessionId = (int) $sessionId;
  2160. $sessionCondition = api_get_session_condition($sessionId);
  2161. $table = Database::get_course_table(TABLE_LP_VIEW);
  2162. $sql = "SELECT progress FROM $table
  2163. WHERE
  2164. c_id = $courseId AND
  2165. lp_id = $lpId AND
  2166. user_id = $userId $sessionCondition ";
  2167. $res = Database::query($sql);
  2168. $progress = 0;
  2169. if (Database::num_rows($res) > 0) {
  2170. $row = Database::fetch_array($res);
  2171. $progress = (int) $row['progress'];
  2172. }
  2173. return $progress;
  2174. }
  2175. /**
  2176. * @param array $lpList
  2177. * @param int $userId
  2178. * @param int $courseId
  2179. * @param int $sessionId
  2180. *
  2181. * @return array
  2182. */
  2183. public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
  2184. {
  2185. $lpList = array_map('intval', $lpList);
  2186. if (empty($lpList)) {
  2187. return [];
  2188. }
  2189. $lpList = implode("','", $lpList);
  2190. $userId = (int) $userId;
  2191. $courseId = (int) $courseId;
  2192. $sessionId = (int) $sessionId;
  2193. $sessionCondition = api_get_session_condition($sessionId);
  2194. $table = Database::get_course_table(TABLE_LP_VIEW);
  2195. $sql = "SELECT lp_id, progress FROM $table
  2196. WHERE
  2197. c_id = $courseId AND
  2198. lp_id IN ('".$lpList."') AND
  2199. user_id = $userId $sessionCondition ";
  2200. $res = Database::query($sql);
  2201. if (Database::num_rows($res) > 0) {
  2202. $list = [];
  2203. while ($row = Database::fetch_array($res)) {
  2204. $list[$row['lp_id']] = $row['progress'];
  2205. }
  2206. return $list;
  2207. }
  2208. return [];
  2209. }
  2210. /**
  2211. * Displays a progress bar
  2212. * completed so far.
  2213. *
  2214. * @param int $percentage Progress value to display
  2215. * @param string $text_add Text to display near the progress value
  2216. *
  2217. * @return string HTML string containing the progress bar
  2218. */
  2219. public static function get_progress_bar($percentage = -1, $text_add = '')
  2220. {
  2221. $text = $percentage.$text_add;
  2222. $output = '<div class="progress">
  2223. <div id="progress_bar_value"
  2224. class="progress-bar progress-bar-success" role="progressbar"
  2225. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2226. '.$text.'
  2227. </div>
  2228. </div>';
  2229. return $output;
  2230. }
  2231. /**
  2232. * @param string $mode can be '%' or 'abs'
  2233. * otherwise this value will be used $this->progress_bar_mode
  2234. *
  2235. * @return string
  2236. */
  2237. public function getProgressBar($mode = null)
  2238. {
  2239. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2240. return self::get_progress_bar($percentage, $text_add);
  2241. }
  2242. /**
  2243. * Gets the progress bar info to display inside the progress bar.
  2244. * Also used by scorm_api.php.
  2245. *
  2246. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2247. * we display a number of completed elements per total elements
  2248. * @param int $add Additional steps to fake as completed
  2249. *
  2250. * @return array Percentage or number and symbol (% or /xx)
  2251. */
  2252. public function get_progress_bar_text($mode = '', $add = 0)
  2253. {
  2254. if (empty($mode)) {
  2255. $mode = $this->progress_bar_mode;
  2256. }
  2257. $total_items = $this->getTotalItemsCountWithoutDirs();
  2258. $completeItems = $this->get_complete_items_count();
  2259. if ($add != 0) {
  2260. $completeItems += $add;
  2261. }
  2262. $text = '';
  2263. if ($completeItems > $total_items) {
  2264. $completeItems = $total_items;
  2265. }
  2266. $percentage = 0;
  2267. if ($mode == '%') {
  2268. if ($total_items > 0) {
  2269. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2270. }
  2271. $percentage = number_format($percentage, 0);
  2272. $text = '%';
  2273. } elseif ($mode === 'abs') {
  2274. $percentage = $completeItems;
  2275. $text = '/'.$total_items;
  2276. }
  2277. return [
  2278. $percentage,
  2279. $text,
  2280. ];
  2281. }
  2282. /**
  2283. * Gets the progress bar mode.
  2284. *
  2285. * @return string The progress bar mode attribute
  2286. */
  2287. public function get_progress_bar_mode()
  2288. {
  2289. if (!empty($this->progress_bar_mode)) {
  2290. return $this->progress_bar_mode;
  2291. }
  2292. return '%';
  2293. }
  2294. /**
  2295. * Gets the learnpath theme (remote or local).
  2296. *
  2297. * @return string Learnpath theme
  2298. */
  2299. public function get_theme()
  2300. {
  2301. if (!empty($this->theme)) {
  2302. return $this->theme;
  2303. }
  2304. return '';
  2305. }
  2306. /**
  2307. * Gets the learnpath session id.
  2308. *
  2309. * @return int
  2310. */
  2311. public function get_lp_session_id()
  2312. {
  2313. if (!empty($this->lp_session_id)) {
  2314. return (int) $this->lp_session_id;
  2315. }
  2316. return 0;
  2317. }
  2318. /**
  2319. * Gets the learnpath image.
  2320. *
  2321. * @return string Web URL of the LP image
  2322. */
  2323. public function get_preview_image()
  2324. {
  2325. if (!empty($this->preview_image)) {
  2326. return $this->preview_image;
  2327. }
  2328. return '';
  2329. }
  2330. /**
  2331. * @param string $size
  2332. * @param string $path_type
  2333. *
  2334. * @return bool|string
  2335. */
  2336. public function get_preview_image_path($size = null, $path_type = 'web')
  2337. {
  2338. $preview_image = $this->get_preview_image();
  2339. if (isset($preview_image) && !empty($preview_image)) {
  2340. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2341. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2342. if (isset($size)) {
  2343. $info = pathinfo($preview_image);
  2344. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2345. if (file_exists($image_sys_path.$image_custom_size)) {
  2346. if ($path_type == 'web') {
  2347. return $image_path.$image_custom_size;
  2348. } else {
  2349. return $image_sys_path.$image_custom_size;
  2350. }
  2351. }
  2352. } else {
  2353. if ($path_type == 'web') {
  2354. return $image_path.$preview_image;
  2355. } else {
  2356. return $image_sys_path.$preview_image;
  2357. }
  2358. }
  2359. }
  2360. return false;
  2361. }
  2362. /**
  2363. * Gets the learnpath author.
  2364. *
  2365. * @return string LP's author
  2366. */
  2367. public function get_author()
  2368. {
  2369. if (!empty($this->author)) {
  2370. return $this->author;
  2371. }
  2372. return '';
  2373. }
  2374. /**
  2375. * Gets hide table of contents.
  2376. *
  2377. * @return int
  2378. */
  2379. public function getHideTableOfContents()
  2380. {
  2381. return (int) $this->hide_toc_frame;
  2382. }
  2383. /**
  2384. * Generate a new prerequisites string for a given item. If this item was a sco and
  2385. * its prerequisites were strings (instead of IDs), then transform those strings into
  2386. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2387. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2388. * same rule as the scormExport() method.
  2389. *
  2390. * @param int $item_id Item ID
  2391. *
  2392. * @return string Prerequisites string ready for the export as SCORM
  2393. */
  2394. public function get_scorm_prereq_string($item_id)
  2395. {
  2396. if ($this->debug > 0) {
  2397. error_log('In learnpath::get_scorm_prereq_string()');
  2398. }
  2399. if (!is_object($this->items[$item_id])) {
  2400. return false;
  2401. }
  2402. /** @var learnpathItem $oItem */
  2403. $oItem = $this->items[$item_id];
  2404. $prereq = $oItem->get_prereq_string();
  2405. if (empty($prereq)) {
  2406. return '';
  2407. }
  2408. if (preg_match('/^\d+$/', $prereq) &&
  2409. isset($this->items[$prereq]) &&
  2410. is_object($this->items[$prereq])
  2411. ) {
  2412. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2413. // then simply return it (with the ITEM_ prefix).
  2414. //return 'ITEM_' . $prereq;
  2415. return $this->items[$prereq]->ref;
  2416. } else {
  2417. if (isset($this->refs_list[$prereq])) {
  2418. // It's a simple string item from which the ID can be found in the refs list,
  2419. // so we can transform it directly to an ID for export.
  2420. return $this->items[$this->refs_list[$prereq]]->ref;
  2421. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2422. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2423. } else {
  2424. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2425. // and replace them, one by one, by the internal IDs (chamilo db)
  2426. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2427. // by a space as well.
  2428. $find = [
  2429. '&',
  2430. '|',
  2431. '~',
  2432. '=',
  2433. '<>',
  2434. '{',
  2435. '}',
  2436. '*',
  2437. '(',
  2438. ')',
  2439. ];
  2440. $replace = [
  2441. ' ',
  2442. ' ',
  2443. ' ',
  2444. ' ',
  2445. ' ',
  2446. ' ',
  2447. ' ',
  2448. ' ',
  2449. ' ',
  2450. ' ',
  2451. ];
  2452. $prereq_mod = str_replace($find, $replace, $prereq);
  2453. $ids = explode(' ', $prereq_mod);
  2454. foreach ($ids as $id) {
  2455. $id = trim($id);
  2456. if (isset($this->refs_list[$id])) {
  2457. $prereq = preg_replace(
  2458. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2459. 'ITEM_'.$this->refs_list[$id],
  2460. $prereq
  2461. );
  2462. }
  2463. }
  2464. return $prereq;
  2465. }
  2466. }
  2467. }
  2468. /**
  2469. * Returns the XML DOM document's node.
  2470. *
  2471. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2472. * @param string $id The identifier to look for
  2473. *
  2474. * @return mixed The reference to the element found with that identifier. False if not found
  2475. */
  2476. public function get_scorm_xml_node(&$children, $id)
  2477. {
  2478. for ($i = 0; $i < $children->length; $i++) {
  2479. $item_temp = $children->item($i);
  2480. if ($item_temp->nodeName == 'item') {
  2481. if ($item_temp->getAttribute('identifier') == $id) {
  2482. return $item_temp;
  2483. }
  2484. }
  2485. $subchildren = $item_temp->childNodes;
  2486. if ($subchildren && $subchildren->length > 0) {
  2487. $val = $this->get_scorm_xml_node($subchildren, $id);
  2488. if (is_object($val)) {
  2489. return $val;
  2490. }
  2491. }
  2492. }
  2493. return false;
  2494. }
  2495. /**
  2496. * Gets the status list for all LP's items.
  2497. *
  2498. * @return array Array of [index] => [item ID => current status]
  2499. */
  2500. public function get_items_status_list()
  2501. {
  2502. $list = [];
  2503. foreach ($this->ordered_items as $item_id) {
  2504. $list[] = [
  2505. $item_id => $this->items[$item_id]->get_status(),
  2506. ];
  2507. }
  2508. return $list;
  2509. }
  2510. /**
  2511. * Return the number of interactions for the given learnpath Item View ID.
  2512. * This method can be used as static.
  2513. *
  2514. * @param int $lp_iv_id Item View ID
  2515. * @param int $course_id course id
  2516. *
  2517. * @return int
  2518. */
  2519. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2520. {
  2521. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2522. $lp_iv_id = (int) $lp_iv_id;
  2523. $course_id = (int) $course_id;
  2524. $sql = "SELECT count(*) FROM $table
  2525. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2526. $res = Database::query($sql);
  2527. $num = 0;
  2528. if (Database::num_rows($res)) {
  2529. $row = Database::fetch_array($res);
  2530. $num = $row[0];
  2531. }
  2532. return $num;
  2533. }
  2534. /**
  2535. * Return the interactions as an array for the given lp_iv_id.
  2536. * This method can be used as static.
  2537. *
  2538. * @param int $lp_iv_id Learnpath Item View ID
  2539. *
  2540. * @return array
  2541. *
  2542. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2543. */
  2544. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2545. {
  2546. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2547. $list = [];
  2548. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2549. $lp_iv_id = (int) $lp_iv_id;
  2550. if (empty($lp_iv_id) || empty($course_id)) {
  2551. return [];
  2552. }
  2553. $sql = "SELECT * FROM $table
  2554. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2555. ORDER BY order_id ASC";
  2556. $res = Database::query($sql);
  2557. $num = Database::num_rows($res);
  2558. if ($num > 0) {
  2559. $list[] = [
  2560. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2561. 'id' => api_htmlentities(get_lang('Interaction ID'), ENT_QUOTES),
  2562. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2563. 'time' => api_htmlentities(get_lang('Time (finished at...)'), ENT_QUOTES),
  2564. 'correct_responses' => api_htmlentities(get_lang('Correct answers'), ENT_QUOTES),
  2565. 'student_response' => api_htmlentities(get_lang('Learner answers'), ENT_QUOTES),
  2566. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2567. 'latency' => api_htmlentities(get_lang('Time spent'), ENT_QUOTES),
  2568. 'student_response_formatted' => '',
  2569. ];
  2570. while ($row = Database::fetch_array($res)) {
  2571. $studentResponseFormatted = urldecode($row['student_response']);
  2572. $content_student_response = explode('__|', $studentResponseFormatted);
  2573. if (count($content_student_response) > 0) {
  2574. if (count($content_student_response) >= 3) {
  2575. // Pop the element off the end of array.
  2576. array_pop($content_student_response);
  2577. }
  2578. $studentResponseFormatted = implode(',', $content_student_response);
  2579. }
  2580. $list[] = [
  2581. 'order_id' => $row['order_id'] + 1,
  2582. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2583. 'type' => $row['interaction_type'],
  2584. 'time' => $row['completion_time'],
  2585. 'correct_responses' => '', // Hide correct responses from students.
  2586. 'student_response' => $row['student_response'],
  2587. 'result' => $row['result'],
  2588. 'latency' => $row['latency'],
  2589. 'student_response_formatted' => $studentResponseFormatted,
  2590. ];
  2591. }
  2592. }
  2593. return $list;
  2594. }
  2595. /**
  2596. * Return the number of objectives for the given learnpath Item View ID.
  2597. * This method can be used as static.
  2598. *
  2599. * @param int $lp_iv_id Item View ID
  2600. * @param int $course_id Course ID
  2601. *
  2602. * @return int Number of objectives
  2603. */
  2604. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2605. {
  2606. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2607. $course_id = (int) $course_id;
  2608. $lp_iv_id = (int) $lp_iv_id;
  2609. $sql = "SELECT count(*) FROM $table
  2610. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2611. //@todo seems that this always returns 0
  2612. $res = Database::query($sql);
  2613. $num = 0;
  2614. if (Database::num_rows($res)) {
  2615. $row = Database::fetch_array($res);
  2616. $num = $row[0];
  2617. }
  2618. return $num;
  2619. }
  2620. /**
  2621. * Return the objectives as an array for the given lp_iv_id.
  2622. * This method can be used as static.
  2623. *
  2624. * @param int $lpItemViewId Learnpath Item View ID
  2625. * @param int $course_id
  2626. *
  2627. * @return array
  2628. *
  2629. * @todo Translate labels
  2630. */
  2631. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2632. {
  2633. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2634. $lpItemViewId = (int) $lpItemViewId;
  2635. if (empty($course_id) || empty($lpItemViewId)) {
  2636. return [];
  2637. }
  2638. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2639. $sql = "SELECT * FROM $table
  2640. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2641. ORDER BY order_id ASC";
  2642. $res = Database::query($sql);
  2643. $num = Database::num_rows($res);
  2644. $list = [];
  2645. if ($num > 0) {
  2646. $list[] = [
  2647. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2648. 'objective_id' => api_htmlentities(get_lang('Objective ID'), ENT_QUOTES),
  2649. 'score_raw' => api_htmlentities(get_lang('Objective raw score'), ENT_QUOTES),
  2650. 'score_max' => api_htmlentities(get_lang('Objective max score'), ENT_QUOTES),
  2651. 'score_min' => api_htmlentities(get_lang('Objective min score'), ENT_QUOTES),
  2652. 'status' => api_htmlentities(get_lang('Objective status'), ENT_QUOTES),
  2653. ];
  2654. while ($row = Database::fetch_array($res)) {
  2655. $list[] = [
  2656. 'order_id' => $row['order_id'] + 1,
  2657. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2658. 'score_raw' => $row['score_raw'],
  2659. 'score_max' => $row['score_max'],
  2660. 'score_min' => $row['score_min'],
  2661. 'status' => $row['status'],
  2662. ];
  2663. }
  2664. }
  2665. return $list;
  2666. }
  2667. /**
  2668. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2669. * used by get_html_toc() to be ready to display.
  2670. *
  2671. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2672. */
  2673. public function get_toc()
  2674. {
  2675. $toc = [];
  2676. foreach ($this->ordered_items as $item_id) {
  2677. // TODO: Change this link generation and use new function instead.
  2678. $toc[] = [
  2679. 'id' => $item_id,
  2680. 'title' => $this->items[$item_id]->get_title(),
  2681. 'status' => $this->items[$item_id]->get_status(),
  2682. 'level' => $this->items[$item_id]->get_level(),
  2683. 'type' => $this->items[$item_id]->get_type(),
  2684. 'description' => $this->items[$item_id]->get_description(),
  2685. 'path' => $this->items[$item_id]->get_path(),
  2686. 'parent' => $this->items[$item_id]->get_parent(),
  2687. ];
  2688. }
  2689. return $toc;
  2690. }
  2691. /**
  2692. * Generate and return the table of contents for this learnpath. The JS
  2693. * table returned is used inside of scorm_api.php.
  2694. *
  2695. * @param string $varname
  2696. *
  2697. * @return string A JS array variable construction
  2698. */
  2699. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2700. {
  2701. $toc = $varname.' = new Array();';
  2702. foreach ($this->ordered_items as $item_id) {
  2703. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2704. }
  2705. return $toc;
  2706. }
  2707. /**
  2708. * Gets the learning path type.
  2709. *
  2710. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2711. *
  2712. * @return mixed Type ID or name, depending on the parameter
  2713. */
  2714. public function get_type($get_name = false)
  2715. {
  2716. $res = false;
  2717. if (!empty($this->type) && (!$get_name)) {
  2718. $res = $this->type;
  2719. }
  2720. return $res;
  2721. }
  2722. /**
  2723. * Gets the learning path type as static method.
  2724. *
  2725. * @param int $lp_id
  2726. *
  2727. * @return mixed Type ID or name, depending on the parameter
  2728. */
  2729. public static function get_type_static($lp_id = 0)
  2730. {
  2731. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2732. $lp_id = (int) $lp_id;
  2733. $sql = "SELECT lp_type FROM $tbl_lp
  2734. WHERE iid = $lp_id";
  2735. $res = Database::query($sql);
  2736. if ($res === false) {
  2737. return null;
  2738. }
  2739. if (Database::num_rows($res) <= 0) {
  2740. return null;
  2741. }
  2742. $row = Database::fetch_array($res);
  2743. return $row['lp_type'];
  2744. }
  2745. /**
  2746. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2747. * This method can be used as abstract and is recursive.
  2748. *
  2749. * @param int $lp Learnpath ID
  2750. * @param int $parent Parent ID of the items to look for
  2751. * @param int $course_id
  2752. *
  2753. * @return array Ordered list of item IDs (empty array on error)
  2754. */
  2755. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2756. {
  2757. if (empty($course_id)) {
  2758. $course_id = api_get_course_int_id();
  2759. } else {
  2760. $course_id = (int) $course_id;
  2761. }
  2762. $list = [];
  2763. if (empty($lp)) {
  2764. return $list;
  2765. }
  2766. $lp = (int) $lp;
  2767. $parent = (int) $parent;
  2768. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2769. $sql = "SELECT iid FROM $tbl_lp_item
  2770. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2771. ORDER BY display_order";
  2772. $res = Database::query($sql);
  2773. while ($row = Database::fetch_array($res)) {
  2774. $sublist = self::get_flat_ordered_items_list(
  2775. $lp,
  2776. $row['iid'],
  2777. $course_id
  2778. );
  2779. $list[] = $row['iid'];
  2780. foreach ($sublist as $item) {
  2781. $list[] = $item;
  2782. }
  2783. }
  2784. return $list;
  2785. }
  2786. /**
  2787. * @return array
  2788. */
  2789. public static function getChapterTypes()
  2790. {
  2791. return [
  2792. 'dir',
  2793. ];
  2794. }
  2795. /**
  2796. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2797. *
  2798. * @param $tree
  2799. *
  2800. * @return array HTML TOC ready to display
  2801. */
  2802. public function getParentToc($tree)
  2803. {
  2804. if (empty($tree)) {
  2805. $tree = $this->get_toc();
  2806. }
  2807. $dirTypes = self::getChapterTypes();
  2808. $myCurrentId = $this->get_current_item_id();
  2809. $listParent = [];
  2810. $listChildren = [];
  2811. $listNotParent = [];
  2812. $list = [];
  2813. foreach ($tree as $subtree) {
  2814. if (in_array($subtree['type'], $dirTypes)) {
  2815. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2816. $subtree['children'] = $listChildren;
  2817. if (!empty($subtree['children'])) {
  2818. foreach ($subtree['children'] as $subItem) {
  2819. if ($subItem['id'] == $this->current) {
  2820. $subtree['parent_current'] = 'in';
  2821. $subtree['current'] = 'on';
  2822. }
  2823. }
  2824. }
  2825. $listParent[] = $subtree;
  2826. }
  2827. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2828. $classStatus = [
  2829. 'not attempted' => 'scorm_not_attempted',
  2830. 'incomplete' => 'scorm_not_attempted',
  2831. 'failed' => 'scorm_failed',
  2832. 'completed' => 'scorm_completed',
  2833. 'passed' => 'scorm_completed',
  2834. 'succeeded' => 'scorm_completed',
  2835. 'browsed' => 'scorm_completed',
  2836. ];
  2837. if (isset($classStatus[$subtree['status']])) {
  2838. $cssStatus = $classStatus[$subtree['status']];
  2839. }
  2840. $title = Security::remove_XSS($subtree['title']);
  2841. unset($subtree['title']);
  2842. if (empty($title)) {
  2843. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2844. }
  2845. $classStyle = null;
  2846. if ($subtree['id'] == $this->current) {
  2847. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2848. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2849. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2850. }
  2851. $subtree['title'] = $title;
  2852. $subtree['class'] = $classStyle.' '.$cssStatus;
  2853. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2854. $subtree['current_id'] = $myCurrentId;
  2855. $listNotParent[] = $subtree;
  2856. }
  2857. }
  2858. $list['are_parents'] = $listParent;
  2859. $list['not_parents'] = $listNotParent;
  2860. return $list;
  2861. }
  2862. /**
  2863. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2864. *
  2865. * @param array $tree
  2866. * @param int $id
  2867. * @param bool $parent
  2868. *
  2869. * @return array HTML TOC ready to display
  2870. */
  2871. public function getChildrenToc($tree, $id, $parent = true)
  2872. {
  2873. if (empty($tree)) {
  2874. $tree = $this->get_toc();
  2875. }
  2876. $dirTypes = self::getChapterTypes();
  2877. $currentItemId = $this->get_current_item_id();
  2878. $list = [];
  2879. $classStatus = [
  2880. 'not attempted' => 'scorm_not_attempted',
  2881. 'incomplete' => 'scorm_not_attempted',
  2882. 'failed' => 'scorm_failed',
  2883. 'completed' => 'scorm_completed',
  2884. 'passed' => 'scorm_completed',
  2885. 'succeeded' => 'scorm_completed',
  2886. 'browsed' => 'scorm_completed',
  2887. ];
  2888. foreach ($tree as $subtree) {
  2889. $subtree['tree'] = null;
  2890. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  2891. if ($subtree['id'] == $this->current) {
  2892. $subtree['current'] = 'active';
  2893. } else {
  2894. $subtree['current'] = null;
  2895. }
  2896. if (isset($classStatus[$subtree['status']])) {
  2897. $cssStatus = $classStatus[$subtree['status']];
  2898. }
  2899. $title = Security::remove_XSS($subtree['title']);
  2900. unset($subtree['title']);
  2901. if (empty($title)) {
  2902. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2903. }
  2904. $classStyle = null;
  2905. if ($subtree['id'] == $this->current) {
  2906. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2907. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2908. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2909. }
  2910. if (in_array($subtree['type'], $dirTypes)) {
  2911. $subtree['title'] = stripslashes($title);
  2912. } else {
  2913. $subtree['title'] = $title;
  2914. $subtree['class'] = $classStyle.' '.$cssStatus;
  2915. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2916. $subtree['current_id'] = $currentItemId;
  2917. }
  2918. $list[] = $subtree;
  2919. }
  2920. }
  2921. return $list;
  2922. }
  2923. /**
  2924. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  2925. *
  2926. * @param array $toc_list
  2927. *
  2928. * @return array HTML TOC ready to display
  2929. */
  2930. public function getListArrayToc($toc_list = [])
  2931. {
  2932. if (empty($toc_list)) {
  2933. $toc_list = $this->get_toc();
  2934. }
  2935. // Temporary variables.
  2936. $currentItemId = $this->get_current_item_id();
  2937. $list = [];
  2938. $arrayList = [];
  2939. $classStatus = [
  2940. 'not attempted' => 'scorm_not_attempted',
  2941. 'incomplete' => 'scorm_not_attempted',
  2942. 'failed' => 'scorm_failed',
  2943. 'completed' => 'scorm_completed',
  2944. 'passed' => 'scorm_completed',
  2945. 'succeeded' => 'scorm_completed',
  2946. 'browsed' => 'scorm_completed',
  2947. ];
  2948. foreach ($toc_list as $item) {
  2949. $list['id'] = $item['id'];
  2950. $list['status'] = $item['status'];
  2951. $cssStatus = null;
  2952. if (isset($classStatus[$item['status']])) {
  2953. $cssStatus = $classStatus[$item['status']];
  2954. }
  2955. $classStyle = ' ';
  2956. $dirTypes = self::getChapterTypes();
  2957. if (in_array($item['type'], $dirTypes)) {
  2958. $classStyle = 'scorm_item_section ';
  2959. }
  2960. if ($item['id'] == $this->current) {
  2961. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2962. } elseif (!in_array($item['type'], $dirTypes)) {
  2963. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2964. }
  2965. $title = $item['title'];
  2966. if (empty($title)) {
  2967. $title = self::rl_get_resource_name(
  2968. api_get_course_id(),
  2969. $this->get_id(),
  2970. $item['id']
  2971. );
  2972. }
  2973. $title = Security::remove_XSS($item['title']);
  2974. if (empty($item['description'])) {
  2975. $list['description'] = $title;
  2976. } else {
  2977. $list['description'] = $item['description'];
  2978. }
  2979. $list['class'] = $classStyle.' '.$cssStatus;
  2980. $list['level'] = $item['level'];
  2981. $list['type'] = $item['type'];
  2982. if (in_array($item['type'], $dirTypes)) {
  2983. $list['css_level'] = 'level_'.$item['level'];
  2984. } else {
  2985. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  2986. }
  2987. if (in_array($item['type'], $dirTypes)) {
  2988. $list['title'] = stripslashes($title);
  2989. } else {
  2990. $list['title'] = stripslashes($title);
  2991. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  2992. $list['current_id'] = $currentItemId;
  2993. }
  2994. $arrayList[] = $list;
  2995. }
  2996. return $arrayList;
  2997. }
  2998. /**
  2999. * Returns an HTML-formatted string ready to display with teacher buttons
  3000. * in LP view menu.
  3001. *
  3002. * @return string HTML TOC ready to display
  3003. */
  3004. public function get_teacher_toc_buttons()
  3005. {
  3006. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3007. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3008. $html = '';
  3009. if ($isAllow && $hideIcons == false) {
  3010. if ($this->get_lp_session_id() == api_get_session_id()) {
  3011. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3012. $html .= '<div class="btn-group">';
  3013. $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'>".
  3014. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3015. $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'>".
  3016. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3017. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3018. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3019. $html .= '</div>';
  3020. $html .= '</div>';
  3021. }
  3022. }
  3023. return $html;
  3024. }
  3025. /**
  3026. * Gets the learnpath maker name - generally the editor's name.
  3027. *
  3028. * @return string Learnpath maker name
  3029. */
  3030. public function get_maker()
  3031. {
  3032. if (!empty($this->maker)) {
  3033. return $this->maker;
  3034. }
  3035. return '';
  3036. }
  3037. /**
  3038. * Gets the learnpath name/title.
  3039. *
  3040. * @return string Learnpath name/title
  3041. */
  3042. public function get_name()
  3043. {
  3044. if (!empty($this->name)) {
  3045. return $this->name;
  3046. }
  3047. return 'N/A';
  3048. }
  3049. /**
  3050. * @return string
  3051. */
  3052. public function getNameNoTags()
  3053. {
  3054. return strip_tags($this->get_name());
  3055. }
  3056. /**
  3057. * Gets a link to the resource from the present location, depending on item ID.
  3058. *
  3059. * @param string $type Type of link expected
  3060. * @param int $item_id Learnpath item ID
  3061. * @param bool $provided_toc
  3062. *
  3063. * @return string $provided_toc Link to the lp_item resource
  3064. */
  3065. public function get_link($type = 'http', $item_id = 0, $provided_toc = false)
  3066. {
  3067. $course_id = $this->get_course_int_id();
  3068. $item_id = (int) $item_id;
  3069. if (empty($item_id)) {
  3070. $item_id = $this->get_current_item_id();
  3071. if (empty($item_id)) {
  3072. //still empty, this means there was no item_id given and we are not in an object context or
  3073. //the object property is empty, return empty link
  3074. $this->first();
  3075. return '';
  3076. }
  3077. }
  3078. $file = '';
  3079. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3080. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3081. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3082. $sql = "SELECT
  3083. l.lp_type as ltype,
  3084. l.path as lpath,
  3085. li.item_type as litype,
  3086. li.path as lipath,
  3087. li.parameters as liparams
  3088. FROM $lp_table l
  3089. INNER JOIN $lp_item_table li
  3090. ON (li.lp_id = l.iid)
  3091. WHERE
  3092. li.iid = $item_id
  3093. ";
  3094. $res = Database::query($sql);
  3095. if (Database::num_rows($res) > 0) {
  3096. $row = Database::fetch_array($res);
  3097. $lp_type = $row['ltype'];
  3098. $lp_path = $row['lpath'];
  3099. $lp_item_type = $row['litype'];
  3100. $lp_item_path = $row['lipath'];
  3101. $lp_item_params = $row['liparams'];
  3102. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3103. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3104. }
  3105. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3106. if ($type === 'http') {
  3107. //web path
  3108. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3109. } else {
  3110. $course_path = $sys_course_path; //system path
  3111. }
  3112. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3113. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3114. if (in_array(
  3115. $lp_item_type,
  3116. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3117. )
  3118. ) {
  3119. $lp_type = 1;
  3120. }
  3121. // Now go through the specific cases to get the end of the path
  3122. // @todo Use constants instead of int values.
  3123. switch ($lp_type) {
  3124. case 1:
  3125. $file = self::rl_get_resource_link_for_learnpath(
  3126. $course_id,
  3127. $this->get_id(),
  3128. $item_id,
  3129. $this->get_view_id()
  3130. );
  3131. switch ($lp_item_type) {
  3132. case 'document':
  3133. // Shows a button to download the file instead of just downloading the file directly.
  3134. $documentPathInfo = pathinfo($file);
  3135. if (isset($documentPathInfo['extension'])) {
  3136. $parsed = parse_url($documentPathInfo['extension']);
  3137. if (isset($parsed['path'])) {
  3138. $extension = $parsed['path'];
  3139. $extensionsToDownload = [
  3140. 'zip',
  3141. 'ppt',
  3142. 'pptx',
  3143. 'ods',
  3144. 'xlsx',
  3145. 'xls',
  3146. 'csv',
  3147. 'doc',
  3148. 'docx',
  3149. 'dot',
  3150. ];
  3151. if (in_array($extension, $extensionsToDownload)) {
  3152. $file = api_get_path(WEB_CODE_PATH).
  3153. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3154. }
  3155. }
  3156. }
  3157. break;
  3158. case 'dir':
  3159. $file = 'lp_content.php?type=dir';
  3160. break;
  3161. case 'link':
  3162. if (Link::is_youtube_link($file)) {
  3163. $src = Link::get_youtube_video_id($file);
  3164. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3165. } elseif (Link::isVimeoLink($file)) {
  3166. $src = Link::getVimeoLinkId($file);
  3167. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3168. } else {
  3169. // If the current site is HTTPS and the link is
  3170. // HTTP, browsers will refuse opening the link
  3171. $urlId = api_get_current_access_url_id();
  3172. $url = api_get_access_url($urlId, false);
  3173. $protocol = substr($url['url'], 0, 5);
  3174. if ($protocol === 'https') {
  3175. $linkProtocol = substr($file, 0, 5);
  3176. if ($linkProtocol === 'http:') {
  3177. //this is the special intervention case
  3178. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3179. }
  3180. }
  3181. }
  3182. break;
  3183. case 'quiz':
  3184. // Check how much attempts of a exercise exits in lp
  3185. $lp_item_id = $this->get_current_item_id();
  3186. $lp_view_id = $this->get_view_id();
  3187. $prevent_reinit = null;
  3188. if (isset($this->items[$this->current])) {
  3189. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3190. }
  3191. if (empty($provided_toc)) {
  3192. if ($this->debug > 0) {
  3193. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3194. }
  3195. $list = $this->get_toc();
  3196. } else {
  3197. if ($this->debug > 0) {
  3198. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3199. }
  3200. $list = $provided_toc;
  3201. }
  3202. $type_quiz = false;
  3203. foreach ($list as $toc) {
  3204. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3205. $type_quiz = true;
  3206. }
  3207. }
  3208. if ($type_quiz) {
  3209. $lp_item_id = (int) $lp_item_id;
  3210. $lp_view_id = (int) $lp_view_id;
  3211. $sql = "SELECT count(*) FROM $lp_item_view_table
  3212. WHERE
  3213. c_id = $course_id AND
  3214. lp_item_id='".$lp_item_id."' AND
  3215. lp_view_id ='".$lp_view_id."' AND
  3216. status='completed'";
  3217. $result = Database::query($sql);
  3218. $row_count = Database:: fetch_row($result);
  3219. $count_item_view = (int) $row_count[0];
  3220. $not_multiple_attempt = 0;
  3221. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3222. $not_multiple_attempt = 1;
  3223. }
  3224. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3225. }
  3226. break;
  3227. }
  3228. $tmp_array = explode('/', $file);
  3229. $document_name = $tmp_array[count($tmp_array) - 1];
  3230. if (strpos($document_name, '_DELETED_')) {
  3231. $file = 'blank.php?error=document_deleted';
  3232. }
  3233. break;
  3234. case 2:
  3235. if ($this->debug > 2) {
  3236. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3237. }
  3238. if ($lp_item_type != 'dir') {
  3239. // Quite complex here:
  3240. // We want to make sure 'http://' (and similar) links can
  3241. // be loaded as is (withouth the Chamilo path in front) but
  3242. // some contents use this form: resource.htm?resource=http://blablabla
  3243. // which means we have to find a protocol at the path's start, otherwise
  3244. // it should not be considered as an external URL.
  3245. // if ($this->prerequisites_match($item_id)) {
  3246. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3247. if ($this->debug > 2) {
  3248. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3249. }
  3250. // Distant url, return as is.
  3251. $file = $lp_item_path;
  3252. } else {
  3253. if ($this->debug > 2) {
  3254. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3255. }
  3256. // Prevent getting untranslatable urls.
  3257. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3258. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3259. // Prepare the path.
  3260. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3261. // TODO: Fix this for urls with protocol header.
  3262. $file = str_replace('//', '/', $file);
  3263. $file = str_replace(':/', '://', $file);
  3264. if (substr($lp_path, -1) == '/') {
  3265. $lp_path = substr($lp_path, 0, -1);
  3266. }
  3267. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3268. // if file not found.
  3269. $decoded = html_entity_decode($lp_item_path);
  3270. list($decoded) = explode('?', $decoded);
  3271. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3272. $file = self::rl_get_resource_link_for_learnpath(
  3273. $course_id,
  3274. $this->get_id(),
  3275. $item_id,
  3276. $this->get_view_id()
  3277. );
  3278. if (empty($file)) {
  3279. $file = 'blank.php?error=document_not_found';
  3280. } else {
  3281. $tmp_array = explode('/', $file);
  3282. $document_name = $tmp_array[count($tmp_array) - 1];
  3283. if (strpos($document_name, '_DELETED_')) {
  3284. $file = 'blank.php?error=document_deleted';
  3285. } else {
  3286. $file = 'blank.php?error=document_not_found';
  3287. }
  3288. }
  3289. } else {
  3290. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3291. }
  3292. }
  3293. }
  3294. // We want to use parameters if they were defined in the imsmanifest
  3295. if (strpos($file, 'blank.php') === false) {
  3296. $lp_item_params = ltrim($lp_item_params, '?');
  3297. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3298. }
  3299. } else {
  3300. $file = 'lp_content.php?type=dir';
  3301. }
  3302. break;
  3303. case 3:
  3304. if ($this->debug > 2) {
  3305. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3306. }
  3307. // Formatting AICC HACP append URL.
  3308. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3309. if (!empty($lp_item_params)) {
  3310. $aicc_append .= $lp_item_params.'&';
  3311. }
  3312. if ($lp_item_type != 'dir') {
  3313. // Quite complex here:
  3314. // We want to make sure 'http://' (and similar) links can
  3315. // be loaded as is (withouth the Chamilo path in front) but
  3316. // some contents use this form: resource.htm?resource=http://blablabla
  3317. // which means we have to find a protocol at the path's start, otherwise
  3318. // it should not be considered as an external URL.
  3319. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3320. if ($this->debug > 2) {
  3321. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3322. }
  3323. // Distant url, return as is.
  3324. $file = $lp_item_path;
  3325. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3326. /*
  3327. if (stristr($file,'<servername>') !== false) {
  3328. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3329. }
  3330. */
  3331. if (stripos($file, '<servername>') !== false) {
  3332. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3333. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3334. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3335. }
  3336. $file .= $aicc_append;
  3337. } else {
  3338. if ($this->debug > 2) {
  3339. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3340. }
  3341. // Prevent getting untranslatable urls.
  3342. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3343. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3344. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3345. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3346. // TODO: Fix this for urls with protocol header.
  3347. $file = str_replace('//', '/', $file);
  3348. $file = str_replace(':/', '://', $file);
  3349. $file .= $aicc_append;
  3350. }
  3351. } else {
  3352. $file = 'lp_content.php?type=dir';
  3353. }
  3354. break;
  3355. case 4:
  3356. break;
  3357. default:
  3358. break;
  3359. }
  3360. // Replace &amp; by & because &amp; will break URL with params
  3361. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3362. }
  3363. if ($this->debug > 2) {
  3364. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3365. }
  3366. return $file;
  3367. }
  3368. /**
  3369. * Gets the latest usable view or generate a new one.
  3370. *
  3371. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3372. *
  3373. * @return int DB lp_view id
  3374. */
  3375. public function get_view($attempt_num = 0)
  3376. {
  3377. $search = '';
  3378. // Use $attempt_num to enable multi-views management (disabled so far).
  3379. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3380. $search = 'AND view_count = '.$attempt_num;
  3381. }
  3382. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3383. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3384. $course_id = api_get_course_int_id();
  3385. $sessionId = api_get_session_id();
  3386. $sql = "SELECT iid, view_count FROM $lp_view_table
  3387. WHERE
  3388. c_id = $course_id AND
  3389. lp_id = ".$this->get_id()." AND
  3390. user_id = ".$this->get_user_id()." AND
  3391. session_id = $sessionId
  3392. $search
  3393. ORDER BY view_count DESC";
  3394. $res = Database::query($sql);
  3395. if (Database::num_rows($res) > 0) {
  3396. $row = Database::fetch_array($res);
  3397. $this->lp_view_id = $row['iid'];
  3398. } elseif (!api_is_invitee()) {
  3399. // There is no database record, create one.
  3400. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3401. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3402. Database::query($sql);
  3403. $id = Database::insert_id();
  3404. $this->lp_view_id = $id;
  3405. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3406. Database::query($sql);
  3407. }
  3408. return $this->lp_view_id;
  3409. }
  3410. /**
  3411. * Gets the current view id.
  3412. *
  3413. * @return int View ID (from lp_view)
  3414. */
  3415. public function get_view_id()
  3416. {
  3417. if (!empty($this->lp_view_id)) {
  3418. return (int) $this->lp_view_id;
  3419. }
  3420. return 0;
  3421. }
  3422. /**
  3423. * Gets the update queue.
  3424. *
  3425. * @return array Array containing IDs of items to be updated by JavaScript
  3426. */
  3427. public function get_update_queue()
  3428. {
  3429. return $this->update_queue;
  3430. }
  3431. /**
  3432. * Gets the user ID.
  3433. *
  3434. * @return int User ID
  3435. */
  3436. public function get_user_id()
  3437. {
  3438. if (!empty($this->user_id)) {
  3439. return (int) $this->user_id;
  3440. }
  3441. return false;
  3442. }
  3443. /**
  3444. * Checks if any of the items has an audio element attached.
  3445. *
  3446. * @return bool True or false
  3447. */
  3448. public function has_audio()
  3449. {
  3450. $has = false;
  3451. foreach ($this->items as $i => $item) {
  3452. if (!empty($this->items[$i]->audio)) {
  3453. $has = true;
  3454. break;
  3455. }
  3456. }
  3457. return $has;
  3458. }
  3459. /**
  3460. * Moves an item up and down at its level.
  3461. *
  3462. * @param int $id Item to move up and down
  3463. * @param string $direction Direction 'up' or 'down'
  3464. *
  3465. * @return bool|int
  3466. */
  3467. public function move_item($id, $direction)
  3468. {
  3469. $course_id = api_get_course_int_id();
  3470. if (empty($id) || empty($direction)) {
  3471. return false;
  3472. }
  3473. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3474. $sql_sel = "SELECT *
  3475. FROM $tbl_lp_item
  3476. WHERE
  3477. iid = $id
  3478. ";
  3479. $res_sel = Database::query($sql_sel);
  3480. // Check if elem exists.
  3481. if (Database::num_rows($res_sel) < 1) {
  3482. return false;
  3483. }
  3484. // Gather data.
  3485. $row = Database::fetch_array($res_sel);
  3486. $previous = $row['previous_item_id'];
  3487. $next = $row['next_item_id'];
  3488. $display = $row['display_order'];
  3489. $parent = $row['parent_item_id'];
  3490. $lp = $row['lp_id'];
  3491. // Update the item (switch with previous/next one).
  3492. switch ($direction) {
  3493. case 'up':
  3494. if ($display > 1) {
  3495. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3496. WHERE iid = $previous";
  3497. $res_sel2 = Database::query($sql_sel2);
  3498. if (Database::num_rows($res_sel2) < 1) {
  3499. $previous_previous = 0;
  3500. }
  3501. // Gather data.
  3502. $row2 = Database::fetch_array($res_sel2);
  3503. $previous_previous = $row2['previous_item_id'];
  3504. // Update previous_previous item (switch "next" with current).
  3505. if ($previous_previous != 0) {
  3506. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3507. next_item_id = $id
  3508. WHERE iid = $previous_previous";
  3509. Database::query($sql_upd2);
  3510. }
  3511. // Update previous item (switch with current).
  3512. if ($previous != 0) {
  3513. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3514. next_item_id = $next,
  3515. previous_item_id = $id,
  3516. display_order = display_order +1
  3517. WHERE iid = $previous";
  3518. Database::query($sql_upd2);
  3519. }
  3520. // Update current item (switch with previous).
  3521. if ($id != 0) {
  3522. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3523. next_item_id = $previous,
  3524. previous_item_id = $previous_previous,
  3525. display_order = display_order-1
  3526. WHERE c_id = ".$course_id." AND id = $id";
  3527. Database::query($sql_upd2);
  3528. }
  3529. // Update next item (new previous item).
  3530. if (!empty($next)) {
  3531. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3532. WHERE iid = $next";
  3533. Database::query($sql_upd2);
  3534. }
  3535. $display = $display - 1;
  3536. }
  3537. break;
  3538. case 'down':
  3539. if ($next != 0) {
  3540. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3541. WHERE iid = $next";
  3542. $res_sel2 = Database::query($sql_sel2);
  3543. if (Database::num_rows($res_sel2) < 1) {
  3544. $next_next = 0;
  3545. }
  3546. // Gather data.
  3547. $row2 = Database::fetch_array($res_sel2);
  3548. $next_next = $row2['next_item_id'];
  3549. // Update previous item (switch with current).
  3550. if ($previous != 0) {
  3551. $sql_upd2 = "UPDATE $tbl_lp_item
  3552. SET next_item_id = $next
  3553. WHERE iid = $previous";
  3554. Database::query($sql_upd2);
  3555. }
  3556. // Update current item (switch with previous).
  3557. if ($id != 0) {
  3558. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3559. previous_item_id = $next,
  3560. next_item_id = $next_next,
  3561. display_order = display_order + 1
  3562. WHERE iid = $id";
  3563. Database::query($sql_upd2);
  3564. }
  3565. // Update next item (new previous item).
  3566. if ($next != 0) {
  3567. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3568. previous_item_id = $previous,
  3569. next_item_id = $id,
  3570. display_order = display_order-1
  3571. WHERE iid = $next";
  3572. Database::query($sql_upd2);
  3573. }
  3574. // Update next_next item (switch "previous" with current).
  3575. if ($next_next != 0) {
  3576. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3577. previous_item_id = $id
  3578. WHERE iid = $next_next";
  3579. Database::query($sql_upd2);
  3580. }
  3581. $display = $display + 1;
  3582. }
  3583. break;
  3584. default:
  3585. return false;
  3586. }
  3587. return $display;
  3588. }
  3589. /**
  3590. * Move a LP up (display_order).
  3591. *
  3592. * @param int $lp_id Learnpath ID
  3593. * @param int $categoryId Category ID
  3594. *
  3595. * @return bool
  3596. */
  3597. public static function move_up($lp_id, $categoryId = 0)
  3598. {
  3599. $courseId = api_get_course_int_id();
  3600. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3601. $categoryCondition = '';
  3602. if (!empty($categoryId)) {
  3603. $categoryId = (int) $categoryId;
  3604. $categoryCondition = " AND category_id = $categoryId";
  3605. }
  3606. $sql = "SELECT * FROM $lp_table
  3607. WHERE c_id = $courseId
  3608. $categoryCondition
  3609. ORDER BY display_order";
  3610. $res = Database::query($sql);
  3611. if ($res === false) {
  3612. return false;
  3613. }
  3614. $lps = [];
  3615. $lp_order = [];
  3616. $num = Database::num_rows($res);
  3617. // First check the order is correct, globally (might be wrong because
  3618. // of versions < 1.8.4)
  3619. if ($num > 0) {
  3620. $i = 1;
  3621. while ($row = Database::fetch_array($res)) {
  3622. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3623. $sql = "UPDATE $lp_table SET display_order = $i
  3624. WHERE iid = ".$row['iid'];
  3625. Database::query($sql);
  3626. }
  3627. $row['display_order'] = $i;
  3628. $lps[$row['iid']] = $row;
  3629. $lp_order[$i] = $row['iid'];
  3630. $i++;
  3631. }
  3632. }
  3633. if ($num > 1) { // If there's only one element, no need to sort.
  3634. $order = $lps[$lp_id]['display_order'];
  3635. if ($order > 1) { // If it's the first element, no need to move up.
  3636. $sql = "UPDATE $lp_table SET display_order = $order
  3637. WHERE iid = ".$lp_order[$order - 1];
  3638. Database::query($sql);
  3639. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3640. WHERE iid = $lp_id";
  3641. Database::query($sql);
  3642. }
  3643. }
  3644. return true;
  3645. }
  3646. /**
  3647. * Move a learnpath down (display_order).
  3648. *
  3649. * @param int $lp_id Learnpath ID
  3650. * @param int $categoryId Category ID
  3651. *
  3652. * @return bool
  3653. */
  3654. public static function move_down($lp_id, $categoryId = 0)
  3655. {
  3656. $courseId = api_get_course_int_id();
  3657. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3658. $categoryCondition = '';
  3659. if (!empty($categoryId)) {
  3660. $categoryId = (int) $categoryId;
  3661. $categoryCondition = " AND category_id = $categoryId";
  3662. }
  3663. $sql = "SELECT * FROM $lp_table
  3664. WHERE c_id = $courseId
  3665. $categoryCondition
  3666. ORDER BY display_order";
  3667. $res = Database::query($sql);
  3668. if ($res === false) {
  3669. return false;
  3670. }
  3671. $lps = [];
  3672. $lp_order = [];
  3673. $num = Database::num_rows($res);
  3674. $max = 0;
  3675. // First check the order is correct, globally (might be wrong because
  3676. // of versions < 1.8.4).
  3677. if ($num > 0) {
  3678. $i = 1;
  3679. while ($row = Database::fetch_array($res)) {
  3680. $max = $i;
  3681. if ($row['display_order'] != $i) {
  3682. // If we find a gap in the order, we need to fix it.
  3683. $sql = "UPDATE $lp_table SET display_order = $i
  3684. WHERE iid = ".$row['iid'];
  3685. Database::query($sql);
  3686. }
  3687. $row['display_order'] = $i;
  3688. $lps[$row['iid']] = $row;
  3689. $lp_order[$i] = $row['iid'];
  3690. $i++;
  3691. }
  3692. }
  3693. if ($num > 1) { // If there's only one element, no need to sort.
  3694. $order = $lps[$lp_id]['display_order'];
  3695. if ($order < $max) { // If it's the first element, no need to move up.
  3696. $sql = "UPDATE $lp_table SET display_order = $order
  3697. WHERE iid = ".$lp_order[$order + 1];
  3698. Database::query($sql);
  3699. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3700. WHERE iid = $lp_id";
  3701. Database::query($sql);
  3702. }
  3703. }
  3704. return true;
  3705. }
  3706. /**
  3707. * Updates learnpath attributes to point to the next element
  3708. * The last part is similar to set_current_item but processing the other way around.
  3709. */
  3710. public function next()
  3711. {
  3712. if ($this->debug > 0) {
  3713. error_log('In learnpath::next()', 0);
  3714. }
  3715. $this->last = $this->get_current_item_id();
  3716. $this->items[$this->last]->save(
  3717. false,
  3718. $this->prerequisites_match($this->last)
  3719. );
  3720. $this->autocomplete_parents($this->last);
  3721. $new_index = $this->get_next_index();
  3722. if ($this->debug > 2) {
  3723. error_log('New index: '.$new_index, 0);
  3724. }
  3725. $this->index = $new_index;
  3726. if ($this->debug > 2) {
  3727. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3728. }
  3729. $this->current = $this->ordered_items[$new_index];
  3730. if ($this->debug > 2) {
  3731. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3732. }
  3733. }
  3734. /**
  3735. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3736. * class, this might be redefined to allow several behaviours depending on the document type.
  3737. *
  3738. * @param int $id Resource ID
  3739. */
  3740. public function open($id)
  3741. {
  3742. // TODO:
  3743. // set the current resource attribute to this resource
  3744. // switch on element type (redefine in child class?)
  3745. // set status for this item to "opened"
  3746. // start timer
  3747. // initialise score
  3748. $this->index = 0; //or = the last item seen (see $this->last)
  3749. }
  3750. /**
  3751. * Check that all prerequisites are fulfilled. Returns true and an
  3752. * empty string on success, returns false
  3753. * and the prerequisite string on error.
  3754. * This function is based on the rules for aicc_script language as
  3755. * described in the SCORM 1.2 CAM documentation page 108.
  3756. *
  3757. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3758. *
  3759. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  3760. * string otherwise
  3761. */
  3762. public function prerequisites_match($itemId = null)
  3763. {
  3764. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3765. if ($allow) {
  3766. if (api_is_allowed_to_edit() ||
  3767. api_is_platform_admin(true) ||
  3768. api_is_drh() ||
  3769. api_is_coach(api_get_session_id(), api_get_course_int_id())
  3770. ) {
  3771. return true;
  3772. }
  3773. }
  3774. $debug = $this->debug;
  3775. if ($debug > 0) {
  3776. error_log('In learnpath::prerequisites_match()');
  3777. }
  3778. if (empty($itemId)) {
  3779. $itemId = $this->current;
  3780. }
  3781. $currentItem = $this->getItem($itemId);
  3782. if ($currentItem) {
  3783. if ($this->type == 2) {
  3784. // Getting prereq from scorm
  3785. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3786. } else {
  3787. $prereq_string = $currentItem->get_prereq_string();
  3788. }
  3789. if (empty($prereq_string)) {
  3790. if ($debug > 0) {
  3791. error_log('Found prereq_string is empty return true');
  3792. }
  3793. return true;
  3794. }
  3795. // Clean spaces.
  3796. $prereq_string = str_replace(' ', '', $prereq_string);
  3797. if ($debug > 0) {
  3798. error_log('Found prereq_string: '.$prereq_string, 0);
  3799. }
  3800. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3801. $result = $currentItem->parse_prereq(
  3802. $prereq_string,
  3803. $this->items,
  3804. $this->refs_list,
  3805. $this->get_user_id()
  3806. );
  3807. if ($result === false) {
  3808. $this->set_error_msg($currentItem->prereq_alert);
  3809. }
  3810. } else {
  3811. $result = true;
  3812. if ($debug > 1) {
  3813. error_log('$this->items['.$itemId.'] was not an object', 0);
  3814. }
  3815. }
  3816. if ($debug > 1) {
  3817. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3818. }
  3819. return $result;
  3820. }
  3821. /**
  3822. * Updates learnpath attributes to point to the previous element
  3823. * The last part is similar to set_current_item but processing the other way around.
  3824. */
  3825. public function previous()
  3826. {
  3827. $this->last = $this->get_current_item_id();
  3828. $this->items[$this->last]->save(
  3829. false,
  3830. $this->prerequisites_match($this->last)
  3831. );
  3832. $this->autocomplete_parents($this->last);
  3833. $new_index = $this->get_previous_index();
  3834. $this->index = $new_index;
  3835. $this->current = $this->ordered_items[$new_index];
  3836. }
  3837. /**
  3838. * Publishes a learnpath. This basically means show or hide the learnpath
  3839. * to normal users.
  3840. * Can be used as abstract.
  3841. *
  3842. * @param int $lp_id Learnpath ID
  3843. * @param int $set_visibility New visibility
  3844. *
  3845. * @return bool
  3846. */
  3847. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3848. {
  3849. $action = 'visible';
  3850. if ($set_visibility != 1) {
  3851. $action = 'invisible';
  3852. self::toggle_publish($lp_id, 'i');
  3853. }
  3854. return api_item_property_update(
  3855. api_get_course_info(),
  3856. TOOL_LEARNPATH,
  3857. $lp_id,
  3858. $action,
  3859. api_get_user_id()
  3860. );
  3861. }
  3862. /**
  3863. * Publishes a learnpath category.
  3864. * This basically means show or hide the learnpath category to normal users.
  3865. *
  3866. * @param int $id
  3867. * @param int $visibility
  3868. *
  3869. * @throws \Doctrine\ORM\NonUniqueResultException
  3870. * @throws \Doctrine\ORM\ORMException
  3871. * @throws \Doctrine\ORM\OptimisticLockException
  3872. * @throws \Doctrine\ORM\TransactionRequiredException
  3873. *
  3874. * @return bool
  3875. */
  3876. public static function toggleCategoryVisibility($id, $visibility = 1)
  3877. {
  3878. $action = 'visible';
  3879. if ($visibility != 1) {
  3880. self::toggleCategoryPublish($id, 0);
  3881. $action = 'invisible';
  3882. }
  3883. return api_item_property_update(
  3884. api_get_course_info(),
  3885. TOOL_LEARNPATH_CATEGORY,
  3886. $id,
  3887. $action,
  3888. api_get_user_id()
  3889. );
  3890. }
  3891. /**
  3892. * Publishes a learnpath. This basically means show or hide the learnpath
  3893. * on the course homepage
  3894. * Can be used as abstract.
  3895. *
  3896. * @param int $lp_id Learnpath id
  3897. * @param string $set_visibility New visibility (v/i - visible/invisible)
  3898. *
  3899. * @return bool
  3900. */
  3901. public static function toggle_publish($lp_id, $set_visibility = 'v')
  3902. {
  3903. $course_id = api_get_course_int_id();
  3904. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  3905. $lp_id = (int) $lp_id;
  3906. $sql = "SELECT * FROM $tbl_lp
  3907. WHERE iid = $lp_id";
  3908. $result = Database::query($sql);
  3909. if (Database::num_rows($result)) {
  3910. $row = Database::fetch_array($result);
  3911. $name = Database::escape_string($row['name']);
  3912. if ($set_visibility == 'i') {
  3913. $v = 0;
  3914. }
  3915. if ($set_visibility == 'v') {
  3916. $v = 1;
  3917. }
  3918. $session_id = api_get_session_id();
  3919. $session_condition = api_get_session_condition($session_id);
  3920. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  3921. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  3922. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  3923. $sql = "SELECT * FROM $tbl_tool
  3924. WHERE
  3925. c_id = $course_id AND
  3926. (link = '$link' OR link = '$oldLink') AND
  3927. image = 'scormbuilder.gif' AND
  3928. (
  3929. link LIKE '$link%' OR
  3930. link LIKE '$oldLink%'
  3931. )
  3932. $session_condition
  3933. ";
  3934. $result = Database::query($sql);
  3935. $num = Database::num_rows($result);
  3936. if ($set_visibility == 'i' && $num > 0) {
  3937. $sql = "DELETE FROM $tbl_tool
  3938. WHERE
  3939. c_id = $course_id AND
  3940. (link = '$link' OR link = '$oldLink') AND
  3941. image='scormbuilder.gif'
  3942. $session_condition";
  3943. Database::query($sql);
  3944. } elseif ($set_visibility == 'v' && $num == 0) {
  3945. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  3946. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  3947. Database::query($sql);
  3948. $insertId = Database::insert_id();
  3949. if ($insertId) {
  3950. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  3951. Database::query($sql);
  3952. }
  3953. } elseif ($set_visibility == 'v' && $num > 0) {
  3954. $sql = "UPDATE $tbl_tool SET
  3955. c_id = $course_id,
  3956. name = '$name',
  3957. link = '$link',
  3958. image = 'scormbuilder.gif',
  3959. visibility = '$v',
  3960. admin = '0',
  3961. address = 'pastillegris.gif',
  3962. added_tool = 0,
  3963. session_id = $session_id
  3964. WHERE
  3965. c_id = ".$course_id." AND
  3966. (link = '$link' OR link = '$oldLink') AND
  3967. image='scormbuilder.gif'
  3968. $session_condition
  3969. ";
  3970. Database::query($sql);
  3971. } else {
  3972. // Parameter and database incompatible, do nothing, exit.
  3973. return false;
  3974. }
  3975. } else {
  3976. return false;
  3977. }
  3978. }
  3979. /**
  3980. * Publishes a learnpath.
  3981. * Show or hide the learnpath category on the course homepage.
  3982. *
  3983. * @param int $id
  3984. * @param int $setVisibility
  3985. *
  3986. * @throws \Doctrine\ORM\NonUniqueResultException
  3987. * @throws \Doctrine\ORM\ORMException
  3988. * @throws \Doctrine\ORM\OptimisticLockException
  3989. * @throws \Doctrine\ORM\TransactionRequiredException
  3990. *
  3991. * @return bool
  3992. */
  3993. public static function toggleCategoryPublish($id, $setVisibility = 1)
  3994. {
  3995. $courseId = api_get_course_int_id();
  3996. $sessionId = api_get_session_id();
  3997. $sessionCondition = api_get_session_condition(
  3998. $sessionId,
  3999. true,
  4000. false,
  4001. 't.sessionId'
  4002. );
  4003. $em = Database::getManager();
  4004. /** @var CLpCategory $category */
  4005. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4006. if (!$category) {
  4007. return false;
  4008. }
  4009. if (empty($courseId)) {
  4010. return false;
  4011. }
  4012. $link = self::getCategoryLinkForTool($id);
  4013. /** @var CTool $tool */
  4014. $tool = $em->createQuery("
  4015. SELECT t FROM ChamiloCourseBundle:CTool t
  4016. WHERE
  4017. t.course = :course AND
  4018. t.link = :link1 AND
  4019. t.image LIKE 'lp_category.%' AND
  4020. t.link LIKE :link2
  4021. $sessionCondition
  4022. ")
  4023. ->setParameters([
  4024. 'course' => $courseId,
  4025. 'link1' => $link,
  4026. 'link2' => "$link%",
  4027. ])
  4028. ->getOneOrNullResult();
  4029. if ($setVisibility == 0 && $tool) {
  4030. $em->remove($tool);
  4031. $em->flush();
  4032. return true;
  4033. }
  4034. if ($setVisibility == 1 && !$tool) {
  4035. $tool = new CTool();
  4036. $tool
  4037. ->setCategory('authoring')
  4038. ->setCourse(api_get_course_entity($courseId))
  4039. ->setName(strip_tags($category->getName()))
  4040. ->setLink($link)
  4041. ->setImage('lp_category.png')
  4042. ->setVisibility(1)
  4043. ->setAdmin(0)
  4044. ->setAddress('pastillegris.gif')
  4045. ->setAddedTool(0)
  4046. ->setSessionId($sessionId)
  4047. ->setTarget('_self');
  4048. $em->persist($tool);
  4049. $em->flush();
  4050. $tool->setId($tool->getIid());
  4051. $em->persist($tool);
  4052. $em->flush();
  4053. return true;
  4054. }
  4055. if ($setVisibility == 1 && $tool) {
  4056. $tool
  4057. ->setName(strip_tags($category->getName()))
  4058. ->setVisibility(1);
  4059. $em->persist($tool);
  4060. $em->flush();
  4061. return true;
  4062. }
  4063. return false;
  4064. }
  4065. /**
  4066. * Check if the learnpath category is visible for a user.
  4067. *
  4068. * @param CLpCategory $category
  4069. * @param User $user
  4070. * @param int
  4071. * @param int
  4072. *
  4073. * @return bool
  4074. */
  4075. public static function categoryIsVisibleForStudent(
  4076. CLpCategory $category,
  4077. User $user,
  4078. $courseId = 0,
  4079. $sessionId = 0
  4080. ) {
  4081. if (empty($category)) {
  4082. return false;
  4083. }
  4084. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4085. if ($isAllowedToEdit) {
  4086. return true;
  4087. }
  4088. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4089. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4090. $courseInfo = api_get_course_info_by_id($courseId);
  4091. $categoryVisibility = api_get_item_visibility(
  4092. $courseInfo,
  4093. TOOL_LEARNPATH_CATEGORY,
  4094. $category->getId(),
  4095. $sessionId
  4096. );
  4097. if ($categoryVisibility !== 1 && $categoryVisibility != -1) {
  4098. return false;
  4099. }
  4100. $subscriptionSettings = self::getSubscriptionSettings();
  4101. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4102. return true;
  4103. }
  4104. $users = $category->getUsers();
  4105. if (empty($users) || !$users->count()) {
  4106. return true;
  4107. }
  4108. if ($category->hasUserAdded($user)) {
  4109. return true;
  4110. }
  4111. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4112. if (!empty($groups)) {
  4113. $em = Database::getManager();
  4114. /** @var ItemPropertyRepository $itemRepo */
  4115. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4116. /** @var CourseRepository $courseRepo */
  4117. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4118. $session = null;
  4119. if (!empty($sessionId)) {
  4120. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4121. }
  4122. $course = $courseRepo->find($courseId);
  4123. // Subscribed groups to a LP
  4124. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4125. TOOL_LEARNPATH_CATEGORY,
  4126. $category->getId(),
  4127. $course,
  4128. $session
  4129. );
  4130. if (!empty($subscribedGroupsInLp)) {
  4131. $groups = array_column($groups, 'iid');
  4132. /** @var CItemProperty $item */
  4133. foreach ($subscribedGroupsInLp as $item) {
  4134. if ($item->getGroup() &&
  4135. in_array($item->getGroup()->getId(), $groups)
  4136. ) {
  4137. return true;
  4138. }
  4139. }
  4140. }
  4141. }
  4142. return false;
  4143. }
  4144. /**
  4145. * Check if a learnpath category is published as course tool.
  4146. *
  4147. * @param CLpCategory $category
  4148. * @param int $courseId
  4149. *
  4150. * @return bool
  4151. */
  4152. public static function categoryIsPublished(
  4153. CLpCategory $category,
  4154. $courseId
  4155. ) {
  4156. $link = self::getCategoryLinkForTool($category->getId());
  4157. $em = Database::getManager();
  4158. $tools = $em
  4159. ->createQuery("
  4160. SELECT t FROM ChamiloCourseBundle:CTool t
  4161. WHERE t.course = :course AND
  4162. t.name = :name AND
  4163. t.image LIKE 'lp_category.%' AND
  4164. t.link LIKE :link
  4165. ")
  4166. ->setParameters([
  4167. 'course' => $courseId,
  4168. 'name' => strip_tags($category->getName()),
  4169. 'link' => "$link%",
  4170. ])
  4171. ->getResult();
  4172. /** @var CTool $tool */
  4173. $tool = current($tools);
  4174. return $tool ? $tool->getVisibility() : false;
  4175. }
  4176. /**
  4177. * Restart the whole learnpath. Return the URL of the first element.
  4178. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4179. * To use a similar method statically, use the create_new_attempt() method.
  4180. *
  4181. * @return bool
  4182. */
  4183. public function restart()
  4184. {
  4185. if ($this->debug > 0) {
  4186. error_log('In learnpath::restart()', 0);
  4187. }
  4188. // TODO
  4189. // Call autosave method to save the current progress.
  4190. //$this->index = 0;
  4191. if (api_is_invitee()) {
  4192. return false;
  4193. }
  4194. $session_id = api_get_session_id();
  4195. $course_id = api_get_course_int_id();
  4196. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4197. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4198. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4199. if ($this->debug > 2) {
  4200. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4201. }
  4202. Database::query($sql);
  4203. $view_id = Database::insert_id();
  4204. if ($view_id) {
  4205. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4206. Database::query($sql);
  4207. $this->lp_view_id = $view_id;
  4208. $this->attempt = $this->attempt + 1;
  4209. } else {
  4210. $this->error = 'Could not insert into item_view table...';
  4211. return false;
  4212. }
  4213. $this->autocomplete_parents($this->current);
  4214. foreach ($this->items as $index => $dummy) {
  4215. $this->items[$index]->restart();
  4216. $this->items[$index]->set_lp_view($this->lp_view_id);
  4217. }
  4218. $this->first();
  4219. return true;
  4220. }
  4221. /**
  4222. * Saves the current item.
  4223. *
  4224. * @return bool
  4225. */
  4226. public function save_current()
  4227. {
  4228. $debug = $this->debug;
  4229. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4230. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4231. if ($debug) {
  4232. error_log('save_current() saving item '.$this->current, 0);
  4233. error_log(''.print_r($this->items, true), 0);
  4234. }
  4235. if (isset($this->items[$this->current]) &&
  4236. is_object($this->items[$this->current])
  4237. ) {
  4238. if ($debug) {
  4239. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4240. }
  4241. $res = $this->items[$this->current]->save(
  4242. false,
  4243. $this->prerequisites_match($this->current)
  4244. );
  4245. $this->autocomplete_parents($this->current);
  4246. $status = $this->items[$this->current]->get_status();
  4247. $this->update_queue[$this->current] = $status;
  4248. if ($debug) {
  4249. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4250. }
  4251. return $res;
  4252. }
  4253. return false;
  4254. }
  4255. /**
  4256. * Saves the given item.
  4257. *
  4258. * @param int $item_id Optional (will take from $_REQUEST if null)
  4259. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4260. *
  4261. * @return bool
  4262. */
  4263. public function save_item($item_id = null, $from_outside = true)
  4264. {
  4265. $debug = $this->debug;
  4266. if ($debug) {
  4267. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4268. }
  4269. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4270. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4271. if (empty($item_id)) {
  4272. $item_id = (int) $_REQUEST['id'];
  4273. }
  4274. if (empty($item_id)) {
  4275. $item_id = $this->get_current_item_id();
  4276. }
  4277. if (isset($this->items[$item_id]) &&
  4278. is_object($this->items[$item_id])
  4279. ) {
  4280. if ($debug) {
  4281. error_log('Object exists');
  4282. }
  4283. // Saving the item.
  4284. $res = $this->items[$item_id]->save(
  4285. $from_outside,
  4286. $this->prerequisites_match($item_id)
  4287. );
  4288. if ($debug) {
  4289. error_log('update_queue before:');
  4290. error_log(print_r($this->update_queue, 1));
  4291. }
  4292. $this->autocomplete_parents($item_id);
  4293. $status = $this->items[$item_id]->get_status();
  4294. $this->update_queue[$item_id] = $status;
  4295. if ($debug) {
  4296. error_log('get_status(): '.$status);
  4297. error_log('update_queue after:');
  4298. error_log(print_r($this->update_queue, 1));
  4299. }
  4300. return $res;
  4301. }
  4302. return false;
  4303. }
  4304. /**
  4305. * Saves the last item seen's ID only in case.
  4306. */
  4307. public function save_last()
  4308. {
  4309. $course_id = api_get_course_int_id();
  4310. $debug = $this->debug;
  4311. if ($debug) {
  4312. error_log('In learnpath::save_last()', 0);
  4313. }
  4314. $session_condition = api_get_session_condition(
  4315. api_get_session_id(),
  4316. true,
  4317. false
  4318. );
  4319. $table = Database::get_course_table(TABLE_LP_VIEW);
  4320. if (isset($this->current) && !api_is_invitee()) {
  4321. if ($debug) {
  4322. error_log('Saving current item ('.$this->current.') for later review', 0);
  4323. }
  4324. $sql = "UPDATE $table SET
  4325. last_item = ".$this->get_current_item_id()."
  4326. WHERE
  4327. c_id = $course_id AND
  4328. lp_id = ".$this->get_id()." AND
  4329. user_id = ".$this->get_user_id()." ".$session_condition;
  4330. if ($debug) {
  4331. error_log('Saving last item seen : '.$sql, 0);
  4332. }
  4333. Database::query($sql);
  4334. }
  4335. if (!api_is_invitee()) {
  4336. // Save progress.
  4337. list($progress) = $this->get_progress_bar_text('%');
  4338. if ($progress >= 0 && $progress <= 100) {
  4339. $progress = (int) $progress;
  4340. $sql = "UPDATE $table SET
  4341. progress = $progress
  4342. WHERE
  4343. c_id = $course_id AND
  4344. lp_id = ".$this->get_id()." AND
  4345. user_id = ".$this->get_user_id()." ".$session_condition;
  4346. // Ignore errors as some tables might not have the progress field just yet.
  4347. Database::query($sql);
  4348. $this->progress_db = $progress;
  4349. }
  4350. }
  4351. }
  4352. /**
  4353. * Sets the current item ID (checks if valid and authorized first).
  4354. *
  4355. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4356. */
  4357. public function set_current_item($item_id = null)
  4358. {
  4359. $debug = $this->debug;
  4360. if ($debug) {
  4361. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4362. }
  4363. if (empty($item_id)) {
  4364. if ($debug) {
  4365. error_log('No new current item given, ignore...', 0);
  4366. }
  4367. // Do nothing.
  4368. } else {
  4369. if ($debug) {
  4370. error_log('New current item given is '.$item_id.'...', 0);
  4371. }
  4372. if (is_numeric($item_id)) {
  4373. $item_id = (int) $item_id;
  4374. // TODO: Check in database here.
  4375. $this->last = $this->current;
  4376. $this->current = $item_id;
  4377. // TODO: Update $this->index as well.
  4378. foreach ($this->ordered_items as $index => $item) {
  4379. if ($item == $this->current) {
  4380. $this->index = $index;
  4381. break;
  4382. }
  4383. }
  4384. if ($debug) {
  4385. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4386. }
  4387. } else {
  4388. if ($debug) {
  4389. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4390. }
  4391. }
  4392. }
  4393. }
  4394. /**
  4395. * Sets the encoding.
  4396. *
  4397. * @param string $enc New encoding
  4398. *
  4399. * @return bool
  4400. *
  4401. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4402. */
  4403. public function set_encoding($enc = 'UTF-8')
  4404. {
  4405. $enc = api_refine_encoding_id($enc);
  4406. if (empty($enc)) {
  4407. $enc = api_get_system_encoding();
  4408. }
  4409. if (api_is_encoding_supported($enc)) {
  4410. $lp = $this->get_id();
  4411. if ($lp != 0) {
  4412. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4413. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4414. WHERE iid = ".$lp;
  4415. $res = Database::query($sql);
  4416. return $res;
  4417. }
  4418. }
  4419. return false;
  4420. }
  4421. /**
  4422. * Sets the JS lib setting in the database directly.
  4423. * This is the JavaScript library file this lp needs to load on startup.
  4424. *
  4425. * @param string $lib Proximity setting
  4426. *
  4427. * @return bool True on update success. False otherwise.
  4428. */
  4429. public function set_jslib($lib = '')
  4430. {
  4431. $lp = $this->get_id();
  4432. if ($lp != 0) {
  4433. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4434. $lib = Database::escape_string($lib);
  4435. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4436. WHERE iid = $lp";
  4437. $res = Database::query($sql);
  4438. return $res;
  4439. }
  4440. return false;
  4441. }
  4442. /**
  4443. * Sets the name of the LP maker (publisher) (and save).
  4444. *
  4445. * @param string $name Optional string giving the new content_maker of this learnpath
  4446. *
  4447. * @return bool True
  4448. */
  4449. public function set_maker($name = '')
  4450. {
  4451. if (empty($name)) {
  4452. return false;
  4453. }
  4454. $this->maker = $name;
  4455. $table = Database::get_course_table(TABLE_LP_MAIN);
  4456. $lp_id = $this->get_id();
  4457. $sql = "UPDATE $table SET
  4458. content_maker = '".Database::escape_string($this->maker)."'
  4459. WHERE iid = $lp_id";
  4460. Database::query($sql);
  4461. return true;
  4462. }
  4463. /**
  4464. * Sets the name of the current learnpath (and save).
  4465. *
  4466. * @param string $name Optional string giving the new name of this learnpath
  4467. *
  4468. * @return bool True/False
  4469. */
  4470. public function set_name($name = null)
  4471. {
  4472. if (empty($name)) {
  4473. return false;
  4474. }
  4475. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4476. $name = Database::escape_string($name);
  4477. $this->name = $name;
  4478. $lp_id = $this->get_id();
  4479. $course_id = $this->course_info['real_id'];
  4480. $sql = "UPDATE $lp_table SET
  4481. name = '$name'
  4482. WHERE iid = $lp_id";
  4483. $result = Database::query($sql);
  4484. // If the lp is visible on the homepage, change his name there.
  4485. if (Database::affected_rows($result)) {
  4486. $session_id = api_get_session_id();
  4487. $session_condition = api_get_session_condition($session_id);
  4488. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4489. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4490. $sql = "UPDATE $tbl_tool SET name = '$name'
  4491. WHERE
  4492. c_id = $course_id AND
  4493. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4494. Database::query($sql);
  4495. return true;
  4496. }
  4497. return false;
  4498. }
  4499. /**
  4500. * Set index specified prefix terms for all items in this path.
  4501. *
  4502. * @param string $terms_string Comma-separated list of terms
  4503. * @param string $prefix Xapian term prefix
  4504. *
  4505. * @return bool False on error, true otherwise
  4506. */
  4507. public function set_terms_by_prefix($terms_string, $prefix)
  4508. {
  4509. $course_id = api_get_course_int_id();
  4510. if (api_get_setting('search_enabled') !== 'true') {
  4511. return false;
  4512. }
  4513. if (!extension_loaded('xapian')) {
  4514. return false;
  4515. }
  4516. $terms_string = trim($terms_string);
  4517. $terms = explode(',', $terms_string);
  4518. array_walk($terms, 'trim_value');
  4519. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4520. // Don't do anything if no change, verify only at DB, not the search engine.
  4521. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4522. return false;
  4523. }
  4524. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4525. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4526. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4527. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4528. $lp_id = (int) $_POST['lp_id'];
  4529. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4530. $result = Database::query($sql);
  4531. $di = new ChamiloIndexer();
  4532. while ($lp_item = Database::fetch_array($result)) {
  4533. // Get search_did.
  4534. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4535. $sql = 'SELECT * FROM %s
  4536. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4537. LIMIT 1';
  4538. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4539. //echo $sql; echo '<br>';
  4540. $res = Database::query($sql);
  4541. if (Database::num_rows($res) > 0) {
  4542. $se_ref = Database::fetch_array($res);
  4543. // Compare terms.
  4544. $doc = $di->get_document($se_ref['search_did']);
  4545. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4546. $xterms = [];
  4547. foreach ($xapian_terms as $xapian_term) {
  4548. $xterms[] = substr($xapian_term['name'], 1);
  4549. }
  4550. $dterms = $terms;
  4551. $missing_terms = array_diff($dterms, $xterms);
  4552. $deprecated_terms = array_diff($xterms, $dterms);
  4553. // Save it to search engine.
  4554. foreach ($missing_terms as $term) {
  4555. $doc->add_term($prefix.$term, 1);
  4556. }
  4557. foreach ($deprecated_terms as $term) {
  4558. $doc->remove_term($prefix.$term);
  4559. }
  4560. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4561. $di->getDb()->flush();
  4562. }
  4563. }
  4564. return true;
  4565. }
  4566. /**
  4567. * Sets the theme of the LP (local/remote) (and save).
  4568. *
  4569. * @param string $name Optional string giving the new theme of this learnpath
  4570. *
  4571. * @return bool Returns true if theme name is not empty
  4572. */
  4573. public function set_theme($name = '')
  4574. {
  4575. $this->theme = $name;
  4576. $table = Database::get_course_table(TABLE_LP_MAIN);
  4577. $lp_id = $this->get_id();
  4578. $sql = "UPDATE $table
  4579. SET theme = '".Database::escape_string($this->theme)."'
  4580. WHERE iid = $lp_id";
  4581. Database::query($sql);
  4582. return true;
  4583. }
  4584. /**
  4585. * Sets the image of an LP (and save).
  4586. *
  4587. * @param string $name Optional string giving the new image of this learnpath
  4588. *
  4589. * @return bool Returns true if theme name is not empty
  4590. */
  4591. public function set_preview_image($name = '')
  4592. {
  4593. $this->preview_image = $name;
  4594. $table = Database::get_course_table(TABLE_LP_MAIN);
  4595. $lp_id = $this->get_id();
  4596. $sql = "UPDATE $table SET
  4597. preview_image = '".Database::escape_string($this->preview_image)."'
  4598. WHERE iid = $lp_id";
  4599. Database::query($sql);
  4600. return true;
  4601. }
  4602. /**
  4603. * Sets the author of a LP (and save).
  4604. *
  4605. * @param string $name Optional string giving the new author of this learnpath
  4606. *
  4607. * @return bool Returns true if author's name is not empty
  4608. */
  4609. public function set_author($name = '')
  4610. {
  4611. $this->author = $name;
  4612. $table = Database::get_course_table(TABLE_LP_MAIN);
  4613. $lp_id = $this->get_id();
  4614. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4615. WHERE iid = $lp_id";
  4616. Database::query($sql);
  4617. return true;
  4618. }
  4619. /**
  4620. * Sets the hide_toc_frame parameter of a LP (and save).
  4621. *
  4622. * @param int $hide 1 if frame is hidden 0 then else
  4623. *
  4624. * @return bool Returns true if author's name is not empty
  4625. */
  4626. public function set_hide_toc_frame($hide)
  4627. {
  4628. if (intval($hide) == $hide) {
  4629. $this->hide_toc_frame = $hide;
  4630. $table = Database::get_course_table(TABLE_LP_MAIN);
  4631. $lp_id = $this->get_id();
  4632. $sql = "UPDATE $table SET
  4633. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4634. WHERE iid = $lp_id";
  4635. Database::query($sql);
  4636. return true;
  4637. }
  4638. return false;
  4639. }
  4640. /**
  4641. * Sets the prerequisite of a LP (and save).
  4642. *
  4643. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4644. *
  4645. * @return bool returns true if prerequisite is not empty
  4646. */
  4647. public function set_prerequisite($prerequisite)
  4648. {
  4649. $this->prerequisite = (int) $prerequisite;
  4650. $table = Database::get_course_table(TABLE_LP_MAIN);
  4651. $lp_id = $this->get_id();
  4652. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4653. WHERE iid = $lp_id";
  4654. Database::query($sql);
  4655. return true;
  4656. }
  4657. /**
  4658. * Sets the location/proximity of the LP (local/remote) (and save).
  4659. *
  4660. * @param string $name Optional string giving the new location of this learnpath
  4661. *
  4662. * @return bool True on success / False on error
  4663. */
  4664. public function set_proximity($name = '')
  4665. {
  4666. if (empty($name)) {
  4667. return false;
  4668. }
  4669. $this->proximity = $name;
  4670. $table = Database::get_course_table(TABLE_LP_MAIN);
  4671. $lp_id = $this->get_id();
  4672. $sql = "UPDATE $table SET
  4673. content_local = '".Database::escape_string($name)."'
  4674. WHERE iid = $lp_id";
  4675. Database::query($sql);
  4676. return true;
  4677. }
  4678. /**
  4679. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4680. *
  4681. * @param int $id DB ID of the item
  4682. */
  4683. public function set_previous_item($id)
  4684. {
  4685. if ($this->debug > 0) {
  4686. error_log('In learnpath::set_previous_item()', 0);
  4687. }
  4688. $this->last = $id;
  4689. }
  4690. /**
  4691. * Sets use_max_score.
  4692. *
  4693. * @param int $use_max_score Optional string giving the new location of this learnpath
  4694. *
  4695. * @return bool True on success / False on error
  4696. */
  4697. public function set_use_max_score($use_max_score = 1)
  4698. {
  4699. $use_max_score = (int) $use_max_score;
  4700. $this->use_max_score = $use_max_score;
  4701. $table = Database::get_course_table(TABLE_LP_MAIN);
  4702. $lp_id = $this->get_id();
  4703. $sql = "UPDATE $table SET
  4704. use_max_score = '".$this->use_max_score."'
  4705. WHERE iid = $lp_id";
  4706. Database::query($sql);
  4707. return true;
  4708. }
  4709. /**
  4710. * Sets and saves the expired_on date.
  4711. *
  4712. * @param string $expired_on Optional string giving the new author of this learnpath
  4713. *
  4714. * @throws \Doctrine\ORM\OptimisticLockException
  4715. *
  4716. * @return bool Returns true if author's name is not empty
  4717. */
  4718. public function set_expired_on($expired_on)
  4719. {
  4720. $em = Database::getManager();
  4721. /** @var CLp $lp */
  4722. $lp = $em
  4723. ->getRepository('ChamiloCourseBundle:CLp')
  4724. ->findOneBy(
  4725. [
  4726. 'iid' => $this->get_id(),
  4727. ]
  4728. );
  4729. if (!$lp) {
  4730. return false;
  4731. }
  4732. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4733. $lp->setExpiredOn($this->expired_on);
  4734. $em->persist($lp);
  4735. $em->flush();
  4736. return true;
  4737. }
  4738. /**
  4739. * Sets and saves the publicated_on date.
  4740. *
  4741. * @param string $publicated_on Optional string giving the new author of this learnpath
  4742. *
  4743. * @throws \Doctrine\ORM\OptimisticLockException
  4744. *
  4745. * @return bool Returns true if author's name is not empty
  4746. */
  4747. public function set_publicated_on($publicated_on)
  4748. {
  4749. $em = Database::getManager();
  4750. /** @var CLp $lp */
  4751. $lp = $em
  4752. ->getRepository('ChamiloCourseBundle:CLp')
  4753. ->findOneBy(
  4754. [
  4755. 'iid' => $this->get_id(),
  4756. ]
  4757. );
  4758. if (!$lp) {
  4759. return false;
  4760. }
  4761. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4762. $lp->setPublicatedOn($this->publicated_on);
  4763. $em->persist($lp);
  4764. $em->flush();
  4765. return true;
  4766. }
  4767. /**
  4768. * Sets and saves the expired_on date.
  4769. *
  4770. * @return bool Returns true if author's name is not empty
  4771. */
  4772. public function set_modified_on()
  4773. {
  4774. $this->modified_on = api_get_utc_datetime();
  4775. $table = Database::get_course_table(TABLE_LP_MAIN);
  4776. $lp_id = $this->get_id();
  4777. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  4778. WHERE iid = $lp_id";
  4779. Database::query($sql);
  4780. return true;
  4781. }
  4782. /**
  4783. * Sets the object's error message.
  4784. *
  4785. * @param string $error Error message. If empty, reinits the error string
  4786. */
  4787. public function set_error_msg($error = '')
  4788. {
  4789. if ($this->debug > 0) {
  4790. error_log('In learnpath::set_error_msg()', 0);
  4791. }
  4792. if (empty($error)) {
  4793. $this->error = '';
  4794. } else {
  4795. $this->error .= $error;
  4796. }
  4797. }
  4798. /**
  4799. * Launches the current item if not 'sco'
  4800. * (starts timer and make sure there is a record ready in the DB).
  4801. *
  4802. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  4803. *
  4804. * @return bool
  4805. */
  4806. public function start_current_item($allow_new_attempt = false)
  4807. {
  4808. $debug = $this->debug;
  4809. if ($debug) {
  4810. error_log('In learnpath::start_current_item()');
  4811. error_log('current: '.$this->current);
  4812. }
  4813. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  4814. $type = $this->get_type();
  4815. $item_type = $this->items[$this->current]->get_type();
  4816. if (($type == 2 && $item_type != 'sco') ||
  4817. ($type == 3 && $item_type != 'au') ||
  4818. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4819. ) {
  4820. if ($debug) {
  4821. error_log('item type: '.$item_type);
  4822. error_log('lp type: '.$type);
  4823. }
  4824. $this->items[$this->current]->open($allow_new_attempt);
  4825. $this->autocomplete_parents($this->current);
  4826. $prereq_check = $this->prerequisites_match($this->current);
  4827. if ($debug) {
  4828. error_log('start_current_item will save item with prereq: '.$prereq_check);
  4829. }
  4830. $this->items[$this->current]->save(false, $prereq_check);
  4831. }
  4832. // If sco, then it is supposed to have been updated by some other call.
  4833. if ($item_type == 'sco') {
  4834. $this->items[$this->current]->restart();
  4835. }
  4836. }
  4837. if ($debug) {
  4838. error_log('lp_view_session_id');
  4839. error_log($this->lp_view_session_id);
  4840. error_log('api session id');
  4841. error_log(api_get_session_id());
  4842. error_log('End of learnpath::start_current_item()');
  4843. }
  4844. return true;
  4845. }
  4846. /**
  4847. * Stops the processing and counters for the old item (as held in $this->last).
  4848. *
  4849. * @return bool True/False
  4850. */
  4851. public function stop_previous_item()
  4852. {
  4853. $debug = $this->debug;
  4854. if ($debug) {
  4855. error_log('In learnpath::stop_previous_item()', 0);
  4856. }
  4857. if ($this->last != 0 && $this->last != $this->current &&
  4858. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  4859. ) {
  4860. if ($debug) {
  4861. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  4862. }
  4863. switch ($this->get_type()) {
  4864. case '3':
  4865. if ($this->items[$this->last]->get_type() != 'au') {
  4866. if ($debug) {
  4867. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  4868. }
  4869. $this->items[$this->last]->close();
  4870. } else {
  4871. if ($debug) {
  4872. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  4873. }
  4874. }
  4875. break;
  4876. case '2':
  4877. if ($this->items[$this->last]->get_type() != 'sco') {
  4878. if ($debug) {
  4879. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  4880. }
  4881. $this->items[$this->last]->close();
  4882. } else {
  4883. if ($debug) {
  4884. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  4885. }
  4886. }
  4887. break;
  4888. case '1':
  4889. default:
  4890. if ($debug) {
  4891. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  4892. }
  4893. $this->items[$this->last]->close();
  4894. break;
  4895. }
  4896. } else {
  4897. if ($debug) {
  4898. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  4899. }
  4900. return false;
  4901. }
  4902. return true;
  4903. }
  4904. /**
  4905. * Updates the default view mode from fullscreen to embedded and inversely.
  4906. *
  4907. * @return string The current default view mode ('fullscreen' or 'embedded')
  4908. */
  4909. public function update_default_view_mode()
  4910. {
  4911. $table = Database::get_course_table(TABLE_LP_MAIN);
  4912. $sql = "SELECT * FROM $table
  4913. WHERE iid = ".$this->get_id();
  4914. $res = Database::query($sql);
  4915. if (Database::num_rows($res) > 0) {
  4916. $row = Database::fetch_array($res);
  4917. $default_view_mode = $row['default_view_mod'];
  4918. $view_mode = $default_view_mode;
  4919. switch ($default_view_mode) {
  4920. case 'fullscreen': // default with popup
  4921. $view_mode = 'embedded';
  4922. break;
  4923. case 'embedded': // default view with left menu
  4924. $view_mode = 'embedframe';
  4925. break;
  4926. case 'embedframe': //folded menu
  4927. $view_mode = 'impress';
  4928. break;
  4929. case 'impress':
  4930. $view_mode = 'fullscreen';
  4931. break;
  4932. }
  4933. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  4934. WHERE iid = ".$this->get_id();
  4935. Database::query($sql);
  4936. $this->mode = $view_mode;
  4937. return $view_mode;
  4938. }
  4939. return -1;
  4940. }
  4941. /**
  4942. * Updates the default behaviour about auto-commiting SCORM updates.
  4943. *
  4944. * @return bool True if auto-commit has been set to 'on', false otherwise
  4945. */
  4946. public function update_default_scorm_commit()
  4947. {
  4948. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4949. $sql = "SELECT * FROM $lp_table
  4950. WHERE iid = ".$this->get_id();
  4951. $res = Database::query($sql);
  4952. if (Database::num_rows($res) > 0) {
  4953. $row = Database::fetch_array($res);
  4954. $force = $row['force_commit'];
  4955. if ($force == 1) {
  4956. $force = 0;
  4957. $force_return = false;
  4958. } elseif ($force == 0) {
  4959. $force = 1;
  4960. $force_return = true;
  4961. }
  4962. $sql = "UPDATE $lp_table SET force_commit = $force
  4963. WHERE iid = ".$this->get_id();
  4964. Database::query($sql);
  4965. $this->force_commit = $force_return;
  4966. return $force_return;
  4967. }
  4968. return -1;
  4969. }
  4970. /**
  4971. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  4972. *
  4973. * @return bool True on success, false on failure
  4974. */
  4975. public function update_display_order()
  4976. {
  4977. $course_id = api_get_course_int_id();
  4978. $table = Database::get_course_table(TABLE_LP_MAIN);
  4979. $sql = "SELECT * FROM $table
  4980. WHERE c_id = $course_id
  4981. ORDER BY display_order";
  4982. $res = Database::query($sql);
  4983. if ($res === false) {
  4984. return false;
  4985. }
  4986. $num = Database::num_rows($res);
  4987. // First check the order is correct, globally (might be wrong because
  4988. // of versions < 1.8.4).
  4989. if ($num > 0) {
  4990. $i = 1;
  4991. while ($row = Database::fetch_array($res)) {
  4992. if ($row['display_order'] != $i) {
  4993. // If we find a gap in the order, we need to fix it.
  4994. $sql = "UPDATE $table SET display_order = $i
  4995. WHERE iid = ".$row['iid'];
  4996. Database::query($sql);
  4997. }
  4998. $i++;
  4999. }
  5000. }
  5001. return true;
  5002. }
  5003. /**
  5004. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5005. *
  5006. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5007. */
  5008. public function update_reinit()
  5009. {
  5010. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5011. $sql = "SELECT * FROM $lp_table
  5012. WHERE iid = ".$this->get_id();
  5013. $res = Database::query($sql);
  5014. if (Database::num_rows($res) > 0) {
  5015. $row = Database::fetch_array($res);
  5016. $force = $row['prevent_reinit'];
  5017. if ($force == 1) {
  5018. $force = 0;
  5019. } elseif ($force == 0) {
  5020. $force = 1;
  5021. }
  5022. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5023. WHERE iid = ".$this->get_id();
  5024. Database::query($sql);
  5025. $this->prevent_reinit = $force;
  5026. return $force;
  5027. }
  5028. return -1;
  5029. }
  5030. /**
  5031. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5032. *
  5033. * @return string 'single', 'multi' or 'seriousgame'
  5034. *
  5035. * @author ndiechburg <noel@cblue.be>
  5036. */
  5037. public function get_attempt_mode()
  5038. {
  5039. //Set default value for seriousgame_mode
  5040. if (!isset($this->seriousgame_mode)) {
  5041. $this->seriousgame_mode = 0;
  5042. }
  5043. // Set default value for prevent_reinit
  5044. if (!isset($this->prevent_reinit)) {
  5045. $this->prevent_reinit = 1;
  5046. }
  5047. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5048. return 'seriousgame';
  5049. }
  5050. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5051. return 'single';
  5052. }
  5053. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5054. return 'multiple';
  5055. }
  5056. return 'single';
  5057. }
  5058. /**
  5059. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5060. *
  5061. * @param string 'seriousgame', 'single' or 'multiple'
  5062. *
  5063. * @return bool
  5064. *
  5065. * @author ndiechburg <noel@cblue.be>
  5066. */
  5067. public function set_attempt_mode($mode)
  5068. {
  5069. switch ($mode) {
  5070. case 'seriousgame':
  5071. $sg_mode = 1;
  5072. $prevent_reinit = 1;
  5073. break;
  5074. case 'single':
  5075. $sg_mode = 0;
  5076. $prevent_reinit = 1;
  5077. break;
  5078. case 'multiple':
  5079. $sg_mode = 0;
  5080. $prevent_reinit = 0;
  5081. break;
  5082. default:
  5083. $sg_mode = 0;
  5084. $prevent_reinit = 0;
  5085. break;
  5086. }
  5087. $this->prevent_reinit = $prevent_reinit;
  5088. $this->seriousgame_mode = $sg_mode;
  5089. $table = Database::get_course_table(TABLE_LP_MAIN);
  5090. $sql = "UPDATE $table SET
  5091. prevent_reinit = $prevent_reinit ,
  5092. seriousgame_mode = $sg_mode
  5093. WHERE iid = ".$this->get_id();
  5094. $res = Database::query($sql);
  5095. if ($res) {
  5096. return true;
  5097. } else {
  5098. return false;
  5099. }
  5100. }
  5101. /**
  5102. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5103. *
  5104. * @author ndiechburg <noel@cblue.be>
  5105. */
  5106. public function switch_attempt_mode()
  5107. {
  5108. $mode = $this->get_attempt_mode();
  5109. switch ($mode) {
  5110. case 'single':
  5111. $next_mode = 'multiple';
  5112. break;
  5113. case 'multiple':
  5114. $next_mode = 'seriousgame';
  5115. break;
  5116. case 'seriousgame':
  5117. default:
  5118. $next_mode = 'single';
  5119. break;
  5120. }
  5121. $this->set_attempt_mode($next_mode);
  5122. }
  5123. /**
  5124. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5125. * but possibility to do again a completed item.
  5126. *
  5127. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5128. *
  5129. * @author ndiechburg <noel@cblue.be>
  5130. */
  5131. public function set_seriousgame_mode()
  5132. {
  5133. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5134. $sql = "SELECT * FROM $lp_table
  5135. WHERE iid = ".$this->get_id();
  5136. $res = Database::query($sql);
  5137. if (Database::num_rows($res) > 0) {
  5138. $row = Database::fetch_array($res);
  5139. $force = $row['seriousgame_mode'];
  5140. if ($force == 1) {
  5141. $force = 0;
  5142. } elseif ($force == 0) {
  5143. $force = 1;
  5144. }
  5145. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5146. WHERE iid = ".$this->get_id();
  5147. Database::query($sql);
  5148. $this->seriousgame_mode = $force;
  5149. return $force;
  5150. }
  5151. return -1;
  5152. }
  5153. /**
  5154. * Updates the "scorm_debug" value that shows or hide the debug window.
  5155. *
  5156. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5157. */
  5158. public function update_scorm_debug()
  5159. {
  5160. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5161. $sql = "SELECT * FROM $lp_table
  5162. WHERE iid = ".$this->get_id();
  5163. $res = Database::query($sql);
  5164. if (Database::num_rows($res) > 0) {
  5165. $row = Database::fetch_array($res);
  5166. $force = $row['debug'];
  5167. if ($force == 1) {
  5168. $force = 0;
  5169. } elseif ($force == 0) {
  5170. $force = 1;
  5171. }
  5172. $sql = "UPDATE $lp_table SET debug = $force
  5173. WHERE iid = ".$this->get_id();
  5174. Database::query($sql);
  5175. $this->scorm_debug = $force;
  5176. return $force;
  5177. }
  5178. return -1;
  5179. }
  5180. /**
  5181. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5182. *
  5183. * @author Kevin Van Den Haute
  5184. *
  5185. * @param array
  5186. */
  5187. public function tree_array($array)
  5188. {
  5189. $array = $this->sort_tree_array($array);
  5190. $this->create_tree_array($array);
  5191. }
  5192. /**
  5193. * Creates an array with the elements of the learning path tree in it.
  5194. *
  5195. * @author Kevin Van Den Haute
  5196. *
  5197. * @param array $array
  5198. * @param int $parent
  5199. * @param int $depth
  5200. * @param array $tmp
  5201. */
  5202. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5203. {
  5204. if (is_array($array)) {
  5205. for ($i = 0; $i < count($array); $i++) {
  5206. if ($array[$i]['parent_item_id'] == $parent) {
  5207. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5208. $tmp[] = $array[$i]['parent_item_id'];
  5209. $depth++;
  5210. }
  5211. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5212. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5213. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5214. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5215. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5216. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5217. $this->arrMenu[] = [
  5218. 'id' => $array[$i]['id'],
  5219. 'ref' => $ref,
  5220. 'item_type' => $array[$i]['item_type'],
  5221. 'title' => $array[$i]['title'],
  5222. 'title_raw' => $array[$i]['title_raw'],
  5223. 'path' => $path,
  5224. 'description' => $array[$i]['description'],
  5225. 'parent_item_id' => $array[$i]['parent_item_id'],
  5226. 'previous_item_id' => $array[$i]['previous_item_id'],
  5227. 'next_item_id' => $array[$i]['next_item_id'],
  5228. 'min_score' => $array[$i]['min_score'],
  5229. 'max_score' => $array[$i]['max_score'],
  5230. 'mastery_score' => $array[$i]['mastery_score'],
  5231. 'display_order' => $array[$i]['display_order'],
  5232. 'prerequisite' => $preq,
  5233. 'depth' => $depth,
  5234. 'audio' => $audio,
  5235. 'prerequisite_min_score' => $prerequisiteMinScore,
  5236. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5237. ];
  5238. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5239. }
  5240. }
  5241. }
  5242. }
  5243. /**
  5244. * Sorts a multi dimensional array by parent id and display order.
  5245. *
  5246. * @author Kevin Van Den Haute
  5247. *
  5248. * @param array $array (array with al the learning path items in it)
  5249. *
  5250. * @return array
  5251. */
  5252. public function sort_tree_array($array)
  5253. {
  5254. foreach ($array as $key => $row) {
  5255. $parent[$key] = $row['parent_item_id'];
  5256. $position[$key] = $row['display_order'];
  5257. }
  5258. if (count($array) > 0) {
  5259. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5260. }
  5261. return $array;
  5262. }
  5263. /**
  5264. * Function that creates a html list of learning path items so that we can add audio files to them.
  5265. *
  5266. * @author Kevin Van Den Haute
  5267. *
  5268. * @return string
  5269. */
  5270. public function overview()
  5271. {
  5272. $return = '';
  5273. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5274. // we need to start a form when we want to update all the mp3 files
  5275. if ($update_audio == 'true') {
  5276. $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">';
  5277. }
  5278. $return .= '<div id="message"></div>';
  5279. if (count($this->items) == 0) {
  5280. $return .= Display::return_message(get_lang('You should add some items to your learning path, otherwise you won\'t be able to attach audio files to them'), 'normal');
  5281. } else {
  5282. $return_audio = '<table class="data_table">';
  5283. $return_audio .= '<tr>';
  5284. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5285. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5286. $return_audio .= '</tr>';
  5287. if ($update_audio != 'true') {
  5288. $return .= '<div class="col-md-12">';
  5289. $return .= self::return_new_tree($update_audio);
  5290. $return .= '</div>';
  5291. $return .= Display::div(
  5292. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5293. ['style' => 'float:left; margin-top:15px;width:100%']
  5294. );
  5295. } else {
  5296. $return_audio .= self::return_new_tree($update_audio);
  5297. $return .= $return_audio.'</table>';
  5298. }
  5299. // We need to close the form when we are updating the mp3 files.
  5300. if ($update_audio == 'true') {
  5301. $return .= '<div class="footer-audio">';
  5302. $return .= Display::button(
  5303. 'save_audio',
  5304. '<em class="fa fa-file-audio-o"></em> '.get_lang('Save audio and organization'),
  5305. ['class' => 'btn btn-primary', 'type' => 'submit']
  5306. );
  5307. $return .= '</div>';
  5308. }
  5309. }
  5310. // We need to close the form when we are updating the mp3 files.
  5311. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5312. $return .= '</form>';
  5313. }
  5314. return $return;
  5315. }
  5316. /**
  5317. * @param string $update_audio
  5318. *
  5319. * @return array
  5320. */
  5321. public function processBuildMenuElements($update_audio = 'false')
  5322. {
  5323. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5324. $arrLP = $this->getItemsForForm();
  5325. $this->tree_array($arrLP);
  5326. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5327. unset($this->arrMenu);
  5328. $default_data = null;
  5329. $default_content = null;
  5330. $elements = [];
  5331. $return_audio = null;
  5332. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5333. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5334. $countItems = count($arrLP);
  5335. $upIcon = Display::return_icon(
  5336. 'up.png',
  5337. get_lang('Up'),
  5338. [],
  5339. ICON_SIZE_TINY
  5340. );
  5341. $disableUpIcon = Display::return_icon(
  5342. 'up_na.png',
  5343. get_lang('Up'),
  5344. [],
  5345. ICON_SIZE_TINY
  5346. );
  5347. $downIcon = Display::return_icon(
  5348. 'down.png',
  5349. get_lang('Down'),
  5350. [],
  5351. ICON_SIZE_TINY
  5352. );
  5353. $disableDownIcon = Display::return_icon(
  5354. 'down_na.png',
  5355. get_lang('Down'),
  5356. [],
  5357. ICON_SIZE_TINY
  5358. );
  5359. $show = api_get_configuration_value('show_full_lp_item_title_in_edition');
  5360. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5361. $plugin = null;
  5362. if ($pluginCalendar) {
  5363. $plugin = LearningCalendarPlugin::create();
  5364. }
  5365. for ($i = 0; $i < $countItems; $i++) {
  5366. $parent_id = $arrLP[$i]['parent_item_id'];
  5367. $title = $arrLP[$i]['title'];
  5368. $title_cut = $arrLP[$i]['title_raw'];
  5369. if ($show === false) {
  5370. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5371. }
  5372. // Link for the documents
  5373. if ($arrLP[$i]['item_type'] === 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5374. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5375. $title_cut = Display::url(
  5376. $title_cut,
  5377. $url,
  5378. [
  5379. 'class' => 'ajax moved',
  5380. 'data-title' => $title,
  5381. 'title' => $title,
  5382. ]
  5383. );
  5384. }
  5385. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5386. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5387. Session::write('pathItem', $arrLP[$i]['path']);
  5388. }
  5389. $oddClass = 'row_even';
  5390. if (($i % 2) == 0) {
  5391. $oddClass = 'row_odd';
  5392. }
  5393. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5394. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5395. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5396. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5397. } else {
  5398. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5399. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5400. } else {
  5401. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5402. $icon = Display::return_icon('certificate.png');
  5403. } else {
  5404. $icon = Display::return_icon('folder_document.png');
  5405. }
  5406. }
  5407. }
  5408. // The audio column.
  5409. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5410. $audio = '';
  5411. if (!$update_audio || $update_audio != 'true') {
  5412. if (empty($arrLP[$i]['audio'])) {
  5413. $audio .= '';
  5414. }
  5415. } else {
  5416. $types = self::getChapterTypes();
  5417. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5418. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5419. if (!empty($arrLP[$i]['audio'])) {
  5420. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5421. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('Remove audio');
  5422. }
  5423. }
  5424. }
  5425. $return_audio .= Display::span($icon.' '.$title).
  5426. Display::tag(
  5427. 'td',
  5428. $audio,
  5429. ['style' => '']
  5430. );
  5431. $return_audio .= '</td>';
  5432. $move_icon = '';
  5433. $move_item_icon = '';
  5434. $edit_icon = '';
  5435. $delete_icon = '';
  5436. $audio_icon = '';
  5437. $prerequisities_icon = '';
  5438. $forumIcon = '';
  5439. $previewIcon = '';
  5440. $pluginCalendarIcon = '';
  5441. $orderIcons = '';
  5442. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5443. if ($is_allowed_to_edit) {
  5444. if (!$update_audio || $update_audio != 'true') {
  5445. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5446. $move_icon .= '<a class="moved" href="#">';
  5447. $move_icon .= Display::return_icon(
  5448. 'move_everywhere.png',
  5449. get_lang('Move'),
  5450. [],
  5451. ICON_SIZE_TINY
  5452. );
  5453. $move_icon .= '</a>';
  5454. }
  5455. }
  5456. // No edit for this item types
  5457. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5458. if ($arrLP[$i]['item_type'] != 'dir') {
  5459. $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">';
  5460. $edit_icon .= Display::return_icon(
  5461. 'edit.png',
  5462. get_lang('Edit section description/name'),
  5463. [],
  5464. ICON_SIZE_TINY
  5465. );
  5466. $edit_icon .= '</a>';
  5467. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5468. $forumThread = null;
  5469. if (isset($this->items[$arrLP[$i]['id']])) {
  5470. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5471. $this->course_int_id,
  5472. $this->lp_session_id
  5473. );
  5474. }
  5475. if ($forumThread) {
  5476. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5477. 'action' => 'dissociate_forum',
  5478. 'id' => $arrLP[$i]['id'],
  5479. 'lp_id' => $this->lp_id,
  5480. ]);
  5481. $forumIcon = Display::url(
  5482. Display::return_icon(
  5483. 'forum.png',
  5484. get_lang('Dissociate the forum of this learning path item'),
  5485. [],
  5486. ICON_SIZE_TINY
  5487. ),
  5488. $forumIconUrl,
  5489. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5490. );
  5491. } else {
  5492. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5493. 'action' => 'create_forum',
  5494. 'id' => $arrLP[$i]['id'],
  5495. 'lp_id' => $this->lp_id,
  5496. ]);
  5497. $forumIcon = Display::url(
  5498. Display::return_icon(
  5499. 'forum.png',
  5500. get_lang('Associate a forum to this learning path item'),
  5501. [],
  5502. ICON_SIZE_TINY
  5503. ),
  5504. $forumIconUrl,
  5505. ['class' => 'btn btn-default lp-btn-associate-forum']
  5506. );
  5507. }
  5508. }
  5509. } else {
  5510. $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">';
  5511. $edit_icon .= Display::return_icon(
  5512. 'edit.png',
  5513. get_lang('Edit section description/name'),
  5514. [],
  5515. ICON_SIZE_TINY
  5516. );
  5517. $edit_icon .= '</a>';
  5518. }
  5519. } else {
  5520. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5521. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5522. $edit_icon .= Display::return_icon(
  5523. 'edit.png',
  5524. get_lang('Edit'),
  5525. [],
  5526. ICON_SIZE_TINY
  5527. );
  5528. $edit_icon .= '</a>';
  5529. }
  5530. }
  5531. if ($pluginCalendar) {
  5532. $pluginLink = $pluginUrl.
  5533. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5534. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('1 day'), [], ICON_SIZE_TINY);
  5535. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5536. if ($itemInfo && $itemInfo['value'] == 1) {
  5537. $iconCalendar = Display::return_icon('agenda.png', get_lang('1 day'), [], ICON_SIZE_TINY);
  5538. }
  5539. $pluginCalendarIcon = Display::url(
  5540. $iconCalendar,
  5541. $pluginLink,
  5542. ['class' => 'btn btn-default']
  5543. );
  5544. }
  5545. if ($arrLP[$i]['item_type'] != 'final_item') {
  5546. $orderIcons = Display::url(
  5547. $upIcon,
  5548. 'javascript:void(0)',
  5549. ['class' => 'btn btn-default order_items', 'data-dir' => 'up', 'data-id' => $arrLP[$i]['id']]
  5550. );
  5551. $orderIcons .= Display::url(
  5552. $downIcon,
  5553. 'javascript:void(0)',
  5554. ['class' => 'btn btn-default order_items', 'data-dir' => 'down', 'data-id' => $arrLP[$i]['id']]
  5555. );
  5556. }
  5557. $delete_icon .= ' <a
  5558. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5559. onclick="return confirmation(\''.addslashes($title).'\');"
  5560. class="btn btn-default">';
  5561. $delete_icon .= Display::return_icon(
  5562. 'delete.png',
  5563. get_lang('Delete section'),
  5564. [],
  5565. ICON_SIZE_TINY
  5566. );
  5567. $delete_icon .= '</a>';
  5568. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5569. $previewImage = Display::return_icon(
  5570. 'preview_view.png',
  5571. get_lang('Preview'),
  5572. [],
  5573. ICON_SIZE_TINY
  5574. );
  5575. switch ($arrLP[$i]['item_type']) {
  5576. case TOOL_DOCUMENT:
  5577. case TOOL_LP_FINAL_ITEM:
  5578. case TOOL_READOUT_TEXT:
  5579. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5580. $previewIcon = Display::url(
  5581. $previewImage,
  5582. $urlPreviewLink,
  5583. [
  5584. 'target' => '_blank',
  5585. 'class' => 'btn btn-default',
  5586. 'data-title' => $arrLP[$i]['title'],
  5587. 'title' => $arrLP[$i]['title'],
  5588. ]
  5589. );
  5590. break;
  5591. case TOOL_THREAD:
  5592. case TOOL_FORUM:
  5593. case TOOL_QUIZ:
  5594. case TOOL_STUDENTPUBLICATION:
  5595. case TOOL_LP_FINAL_ITEM:
  5596. case TOOL_LINK:
  5597. $class = 'btn btn-default';
  5598. $target = '_blank';
  5599. $link = self::rl_get_resource_link_for_learnpath(
  5600. $this->course_int_id,
  5601. $this->lp_id,
  5602. $arrLP[$i]['id'],
  5603. 0
  5604. );
  5605. $previewIcon = Display::url(
  5606. $previewImage,
  5607. $link,
  5608. [
  5609. 'class' => $class,
  5610. 'data-title' => $arrLP[$i]['title'],
  5611. 'title' => $arrLP[$i]['title'],
  5612. 'target' => $target,
  5613. ]
  5614. );
  5615. break;
  5616. default:
  5617. $previewIcon = Display::url(
  5618. $previewImage,
  5619. $url.'&action=view_item',
  5620. ['class' => 'btn btn-default', 'target' => '_blank']
  5621. );
  5622. break;
  5623. }
  5624. if ($arrLP[$i]['item_type'] != 'dir') {
  5625. $prerequisities_icon = Display::url(
  5626. Display::return_icon(
  5627. 'accept.png',
  5628. get_lang('Prerequisites'),
  5629. [],
  5630. ICON_SIZE_TINY
  5631. ),
  5632. $url.'&action=edit_item_prereq',
  5633. ['class' => 'btn btn-default']
  5634. );
  5635. if ($arrLP[$i]['item_type'] != 'final_item') {
  5636. $move_item_icon = Display::url(
  5637. Display::return_icon(
  5638. 'move.png',
  5639. get_lang('Move'),
  5640. [],
  5641. ICON_SIZE_TINY
  5642. ),
  5643. $url.'&action=move_item',
  5644. ['class' => 'btn btn-default']
  5645. );
  5646. }
  5647. $audio_icon = Display::url(
  5648. Display::return_icon(
  5649. 'audio.png',
  5650. get_lang('Upload'),
  5651. [],
  5652. ICON_SIZE_TINY
  5653. ),
  5654. $url.'&action=add_audio',
  5655. ['class' => 'btn btn-default']
  5656. );
  5657. }
  5658. }
  5659. if ($update_audio != 'true') {
  5660. $row = $move_icon.' '.$icon.
  5661. Display::span($title_cut).
  5662. Display::tag(
  5663. 'div',
  5664. "<div class=\"btn-group btn-group-xs\">
  5665. $previewIcon
  5666. $audio
  5667. $edit_icon
  5668. $pluginCalendarIcon
  5669. $forumIcon
  5670. $prerequisities_icon
  5671. $move_item_icon
  5672. $audio_icon
  5673. $orderIcons
  5674. $delete_icon
  5675. </div>",
  5676. ['class' => 'btn-toolbar button_actions']
  5677. );
  5678. } else {
  5679. $row =
  5680. Display::span($title.$icon).
  5681. Display::span($audio, ['class' => 'button_actions']);
  5682. }
  5683. $default_data[$arrLP[$i]['id']] = $row;
  5684. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5685. if (empty($parent_id)) {
  5686. $elements[$arrLP[$i]['id']]['data'] = $row;
  5687. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5688. } else {
  5689. $parent_arrays = [];
  5690. if ($arrLP[$i]['depth'] > 1) {
  5691. // Getting list of parents
  5692. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5693. foreach ($arrLP as $item) {
  5694. if ($item['id'] == $parent_id) {
  5695. if ($item['parent_item_id'] == 0) {
  5696. $parent_id = $item['id'];
  5697. break;
  5698. } else {
  5699. $parent_id = $item['parent_item_id'];
  5700. if (empty($parent_arrays)) {
  5701. $parent_arrays[] = intval($item['id']);
  5702. }
  5703. $parent_arrays[] = $parent_id;
  5704. break;
  5705. }
  5706. }
  5707. }
  5708. }
  5709. }
  5710. if (!empty($parent_arrays)) {
  5711. $parent_arrays = array_reverse($parent_arrays);
  5712. $val = '$elements';
  5713. $x = 0;
  5714. foreach ($parent_arrays as $item) {
  5715. if ($x != count($parent_arrays) - 1) {
  5716. $val .= '["'.$item.'"]["children"]';
  5717. } else {
  5718. $val .= '["'.$item.'"]["children"]';
  5719. }
  5720. $x++;
  5721. }
  5722. $val .= "";
  5723. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5724. eval($code_str);
  5725. } else {
  5726. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5727. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5728. }
  5729. }
  5730. }
  5731. return [
  5732. 'elements' => $elements,
  5733. 'default_data' => $default_data,
  5734. 'default_content' => $default_content,
  5735. 'return_audio' => $return_audio,
  5736. ];
  5737. }
  5738. /**
  5739. * @param string $updateAudio true/false strings
  5740. *
  5741. * @return string
  5742. */
  5743. public function returnLpItemList($updateAudio)
  5744. {
  5745. $result = $this->processBuildMenuElements($updateAudio);
  5746. $html = self::print_recursive(
  5747. $result['elements'],
  5748. $result['default_data'],
  5749. $result['default_content']
  5750. );
  5751. if (!empty($html)) {
  5752. $html .= Display::return_message(get_lang('Drag and drop an element here'));
  5753. }
  5754. return $html;
  5755. }
  5756. /**
  5757. * @param string $update_audio
  5758. * @param bool $drop_element_here
  5759. *
  5760. * @return string
  5761. */
  5762. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5763. {
  5764. $result = $this->processBuildMenuElements($update_audio);
  5765. $list = '<ul id="lp_item_list">';
  5766. $tree = $this->print_recursive(
  5767. $result['elements'],
  5768. $result['default_data'],
  5769. $result['default_content']
  5770. );
  5771. if (!empty($tree)) {
  5772. $list .= $tree;
  5773. } else {
  5774. if ($drop_element_here) {
  5775. $list .= Display::return_message(get_lang('Drag and drop an element here'));
  5776. }
  5777. }
  5778. $list .= '</ul>';
  5779. $return = Display::panelCollapse(
  5780. $this->name,
  5781. $list,
  5782. 'scorm-list',
  5783. null,
  5784. 'scorm-list-accordion',
  5785. 'scorm-list-collapse'
  5786. );
  5787. if ($update_audio === 'true') {
  5788. $return = $result['return_audio'];
  5789. }
  5790. return $return;
  5791. }
  5792. /**
  5793. * @param array $elements
  5794. * @param array $default_data
  5795. * @param array $default_content
  5796. *
  5797. * @return string
  5798. */
  5799. public function print_recursive($elements, $default_data, $default_content)
  5800. {
  5801. $return = '';
  5802. foreach ($elements as $key => $item) {
  5803. if (isset($item['load_data']) || empty($item['data'])) {
  5804. $item['data'] = $default_data[$item['load_data']];
  5805. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5806. }
  5807. $sub_list = '';
  5808. if (isset($item['type']) && $item['type'] === 'dir') {
  5809. // empty value
  5810. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  5811. }
  5812. if (empty($item['children'])) {
  5813. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5814. $active = null;
  5815. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5816. $active = 'active';
  5817. }
  5818. $return .= Display::tag(
  5819. 'li',
  5820. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  5821. ['id' => $key, 'class' => 'record li_container']
  5822. );
  5823. } else {
  5824. // Sections
  5825. $data = '';
  5826. if (isset($item['children'])) {
  5827. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5828. }
  5829. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5830. $return .= Display::tag(
  5831. 'li',
  5832. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  5833. ['id' => $key, 'class' => 'record li_container']
  5834. );
  5835. }
  5836. }
  5837. return $return;
  5838. }
  5839. /**
  5840. * This function builds the action menu.
  5841. *
  5842. * @param bool $returnContent Optional
  5843. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5844. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5845. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5846. *
  5847. * @return string
  5848. */
  5849. public function build_action_menu(
  5850. $returnContent = false,
  5851. $showRequirementButtons = true,
  5852. $isConfigPage = false,
  5853. $allowExpand = true
  5854. ) {
  5855. $actionsRight = '';
  5856. $actionsLeft = Display::url(
  5857. Display::return_icon(
  5858. 'back.png',
  5859. get_lang('Back to learning paths'),
  5860. '',
  5861. ICON_SIZE_MEDIUM
  5862. ),
  5863. 'lp_controller.php?'.api_get_cidreq()
  5864. );
  5865. $actionsLeft .= Display::url(
  5866. Display::return_icon(
  5867. 'preview_view.png',
  5868. get_lang('Preview'),
  5869. '',
  5870. ICON_SIZE_MEDIUM
  5871. ),
  5872. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5873. 'action' => 'view',
  5874. 'lp_id' => $this->lp_id,
  5875. 'isStudentView' => 'true',
  5876. ])
  5877. );
  5878. $actionsLeft .= Display::url(
  5879. Display::return_icon(
  5880. 'upload_audio.png',
  5881. get_lang('Add audio'),
  5882. '',
  5883. ICON_SIZE_MEDIUM
  5884. ),
  5885. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5886. 'action' => 'admin_view',
  5887. 'lp_id' => $this->lp_id,
  5888. 'updateaudio' => 'true',
  5889. ])
  5890. );
  5891. $subscriptionSettings = self::getSubscriptionSettings();
  5892. $request = api_request_uri();
  5893. if (strpos($request, 'edit') === false) {
  5894. $actionsLeft .= Display::url(
  5895. Display::return_icon(
  5896. 'settings.png',
  5897. get_lang('Course settings'),
  5898. '',
  5899. ICON_SIZE_MEDIUM
  5900. ),
  5901. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5902. 'action' => 'edit',
  5903. 'lp_id' => $this->lp_id,
  5904. ])
  5905. );
  5906. }
  5907. if (strpos($request, 'build') === false && strpos($request, 'add_item') === false) {
  5908. $actionsLeft .= Display::url(
  5909. Display::return_icon(
  5910. 'edit.png',
  5911. get_lang('Edit'),
  5912. '',
  5913. ICON_SIZE_MEDIUM
  5914. ),
  5915. 'lp_controller.php?'.http_build_query([
  5916. 'action' => 'build',
  5917. 'lp_id' => $this->lp_id,
  5918. ]).'&'.api_get_cidreq()
  5919. );
  5920. }
  5921. if (strpos(api_get_self(), 'lp_subscribe_users.php') === false) {
  5922. if ($this->subscribeUsers == 1 &&
  5923. $subscriptionSettings['allow_add_users_to_lp']) {
  5924. $actionsLeft .= Display::url(
  5925. Display::return_icon(
  5926. 'user.png',
  5927. get_lang('Subscribe users to learning path'),
  5928. '',
  5929. ICON_SIZE_MEDIUM
  5930. ),
  5931. api_get_path(WEB_CODE_PATH)."lp/lp_subscribe_users.php?lp_id=".$this->lp_id."&".api_get_cidreq()
  5932. );
  5933. }
  5934. }
  5935. if ($allowExpand) {
  5936. $actionsLeft .= Display::url(
  5937. Display::return_icon(
  5938. 'expand.png',
  5939. get_lang('Expand'),
  5940. ['id' => 'expand'],
  5941. ICON_SIZE_MEDIUM
  5942. ).
  5943. Display::return_icon(
  5944. 'contract.png',
  5945. get_lang('Collapse'),
  5946. ['id' => 'contract', 'class' => 'hide'],
  5947. ICON_SIZE_MEDIUM
  5948. ),
  5949. '#',
  5950. ['role' => 'button', 'id' => 'hide_bar_template']
  5951. );
  5952. }
  5953. if ($showRequirementButtons) {
  5954. $buttons = [
  5955. [
  5956. 'title' => get_lang('Set previous step as prerequisite for each step'),
  5957. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5958. 'action' => 'set_previous_step_as_prerequisite',
  5959. 'lp_id' => $this->lp_id,
  5960. ]),
  5961. ],
  5962. [
  5963. 'title' => get_lang('Clear all prerequisites'),
  5964. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5965. 'action' => 'clear_prerequisites',
  5966. 'lp_id' => $this->lp_id,
  5967. ]),
  5968. ],
  5969. ];
  5970. $actionsRight = Display::groupButtonWithDropDown(
  5971. get_lang('Prerequisites options'),
  5972. $buttons,
  5973. true
  5974. );
  5975. }
  5976. $toolbar = Display::toolbarAction(
  5977. 'actions-lp-controller',
  5978. [$actionsLeft, $actionsRight]
  5979. );
  5980. if ($returnContent) {
  5981. return $toolbar;
  5982. }
  5983. echo $toolbar;
  5984. }
  5985. /**
  5986. * Creates the default learning path folder.
  5987. *
  5988. * @param array $course
  5989. * @param int $creatorId
  5990. *
  5991. * @return bool
  5992. */
  5993. public static function generate_learning_path_folder($course, $creatorId = 0)
  5994. {
  5995. // Creating learning_path folder
  5996. $dir = '/learning_path';
  5997. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  5998. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  5999. $folder = false;
  6000. $folderData = create_unexisting_directory(
  6001. $course,
  6002. $creatorId,
  6003. 0,
  6004. null,
  6005. 0,
  6006. $filepath,
  6007. $dir,
  6008. get_lang('Learning paths'),
  6009. 0
  6010. );
  6011. if (!empty($folderData)) {
  6012. $folder = true;
  6013. }
  6014. return $folder;
  6015. }
  6016. /**
  6017. * @param array $course
  6018. * @param string $lp_name
  6019. * @param int $creatorId
  6020. *
  6021. * @return array
  6022. */
  6023. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6024. {
  6025. $filepath = '';
  6026. $dir = '/learning_path/';
  6027. if (empty($lp_name)) {
  6028. $lp_name = $this->name;
  6029. }
  6030. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6031. $folder = self::generate_learning_path_folder($course, $creatorId);
  6032. // Limits title size
  6033. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6034. $dir = $dir.$title;
  6035. // Creating LP folder
  6036. $documentId = null;
  6037. if ($folder) {
  6038. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6039. $folderData = create_unexisting_directory(
  6040. $course,
  6041. $creatorId,
  6042. 0,
  6043. 0,
  6044. 0,
  6045. $filepath,
  6046. $dir,
  6047. $lp_name
  6048. );
  6049. if (!empty($folderData)) {
  6050. $folder = true;
  6051. }
  6052. $documentId = $folderData->getIid();
  6053. $dir = $dir.'/';
  6054. if ($folder) {
  6055. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6056. }
  6057. }
  6058. if (empty($documentId)) {
  6059. $dir = api_remove_trailing_slash($dir);
  6060. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6061. }
  6062. $array = [
  6063. 'dir' => $dir,
  6064. 'filepath' => $filepath,
  6065. 'folder' => $folder,
  6066. 'id' => $documentId,
  6067. ];
  6068. return $array;
  6069. }
  6070. /**
  6071. * Create a new document //still needs some finetuning.
  6072. *
  6073. * @param array $courseInfo
  6074. * @param string $content
  6075. * @param string $title
  6076. * @param string $extension
  6077. * @param int $parentId
  6078. * @param int $creatorId creator id
  6079. *
  6080. * @return int
  6081. */
  6082. public function create_document(
  6083. $courseInfo,
  6084. $content = '',
  6085. $title = '',
  6086. $extension = 'html',
  6087. $parentId = 0,
  6088. $creatorId = 0
  6089. ) {
  6090. if (!empty($courseInfo)) {
  6091. $course_id = $courseInfo['real_id'];
  6092. } else {
  6093. $course_id = api_get_course_int_id();
  6094. }
  6095. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6096. $sessionId = api_get_session_id();
  6097. // Generates folder
  6098. $result = $this->generate_lp_folder($courseInfo);
  6099. $dir = $result['dir'];
  6100. if (empty($parentId) || $parentId == '/') {
  6101. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6102. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6103. if ($parentId === '/') {
  6104. $dir = '/';
  6105. }
  6106. // Please, do not modify this dirname formatting.
  6107. if (strstr($dir, '..')) {
  6108. $dir = '/';
  6109. }
  6110. if (!empty($dir[0]) && $dir[0] == '.') {
  6111. $dir = substr($dir, 1);
  6112. }
  6113. if (!empty($dir[0]) && $dir[0] != '/') {
  6114. $dir = '/'.$dir;
  6115. }
  6116. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6117. $dir .= '/';
  6118. }
  6119. } else {
  6120. $parentInfo = DocumentManager::get_document_data_by_id(
  6121. $parentId,
  6122. $courseInfo['code']
  6123. );
  6124. if (!empty($parentInfo)) {
  6125. $dir = $parentInfo['path'].'/';
  6126. }
  6127. }
  6128. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6129. // is already escaped twice when it gets here.
  6130. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6131. if (!empty($title)) {
  6132. $title = api_replace_dangerous_char(stripslashes($title));
  6133. } else {
  6134. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6135. }
  6136. $title = disable_dangerous_file($title);
  6137. $filename = $title;
  6138. $content = !empty($content) ? $content : $_POST['content_lp'];
  6139. $tmp_filename = $filename;
  6140. $filename = $tmp_filename.'.'.$extension;
  6141. if ($extension === 'html') {
  6142. $content = stripslashes($content);
  6143. $content = str_replace(
  6144. api_get_path(WEB_COURSE_PATH),
  6145. api_get_path(REL_PATH).'courses/',
  6146. $content
  6147. );
  6148. // Change the path of mp3 to absolute.
  6149. // The first regexp deals with :// urls.
  6150. $content = preg_replace(
  6151. "|(flashvars=\"file=)([^:/]+)/|",
  6152. "$1".api_get_path(
  6153. REL_COURSE_PATH
  6154. ).$courseInfo['path'].'/document/',
  6155. $content
  6156. );
  6157. // The second regexp deals with audio/ urls.
  6158. $content = preg_replace(
  6159. "|(flashvars=\"file=)([^/]+)/|",
  6160. "$1".api_get_path(
  6161. REL_COURSE_PATH
  6162. ).$courseInfo['path'].'/document/$2/',
  6163. $content
  6164. );
  6165. // For flv player: To prevent edition problem with firefox,
  6166. // we have to use a strange tip (don't blame me please).
  6167. $content = str_replace(
  6168. '</body>',
  6169. '<style type="text/css">body{}</style></body>',
  6170. $content
  6171. );
  6172. }
  6173. $save_file_path = $dir.$filename;
  6174. $document = DocumentManager::addDocument(
  6175. $courseInfo,
  6176. $save_file_path,
  6177. 'file',
  6178. '',
  6179. $tmp_filename,
  6180. '',
  6181. 0, //readonly
  6182. true,
  6183. null,
  6184. $sessionId,
  6185. $creatorId,
  6186. false,
  6187. $content,
  6188. $parentId
  6189. );
  6190. $document_id = $document->getIid();
  6191. if ($document_id) {
  6192. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6193. $new_title = $originalTitle;
  6194. if ($new_comment || $new_title) {
  6195. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6196. $ct = '';
  6197. if ($new_comment) {
  6198. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6199. }
  6200. if ($new_title) {
  6201. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6202. }
  6203. $sql = "UPDATE $tbl_doc SET ".substr($ct, 1)."
  6204. WHERE c_id = $course_id AND id = $document_id ";
  6205. Database::query($sql);
  6206. }
  6207. }
  6208. return $document_id;
  6209. }
  6210. /**
  6211. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6212. *
  6213. * @param array $_course array
  6214. */
  6215. public function edit_document($_course)
  6216. {
  6217. $course_id = api_get_course_int_id();
  6218. $urlAppend = api_get_configuration_value('url_append');
  6219. // Please, do not modify this dirname formatting.
  6220. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6221. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6222. if (strstr($dir, '..')) {
  6223. $dir = '/';
  6224. }
  6225. if (isset($dir[0]) && $dir[0] == '.') {
  6226. $dir = substr($dir, 1);
  6227. }
  6228. if (isset($dir[0]) && $dir[0] != '/') {
  6229. $dir = '/'.$dir;
  6230. }
  6231. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6232. $dir .= '/';
  6233. }
  6234. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6235. if (!is_dir($filepath)) {
  6236. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6237. }
  6238. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6239. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6240. $document_id = (int) $_POST['path'];
  6241. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6242. if (empty($documentInfo)) {
  6243. // Try with iid
  6244. $table = Database::get_course_table(TABLE_DOCUMENT);
  6245. $sql = "SELECT id, path FROM $table
  6246. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6247. $res_doc = Database::query($sql);
  6248. $row = Database::fetch_array($res_doc);
  6249. if ($row) {
  6250. $document_id = $row['id'];
  6251. $documentPath = $row['path'];
  6252. }
  6253. } else {
  6254. $documentPath = $documentInfo['path'];
  6255. }
  6256. $content = stripslashes($_POST['content_lp']);
  6257. $file = $filepath.$documentPath;
  6258. if (!file_exists($file)) {
  6259. return false;
  6260. }
  6261. if ($fp = @fopen($file, 'w')) {
  6262. $content = str_replace(
  6263. api_get_path(WEB_COURSE_PATH),
  6264. $urlAppend.api_get_path(REL_COURSE_PATH),
  6265. $content
  6266. );
  6267. // Change the path of mp3 to absolute.
  6268. // The first regexp deals with :// urls.
  6269. $content = preg_replace(
  6270. "|(flashvars=\"file=)([^:/]+)/|",
  6271. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6272. $content
  6273. );
  6274. // The second regexp deals with audio/ urls.
  6275. $content = preg_replace(
  6276. "|(flashvars=\"file=)([^:/]+)/|",
  6277. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6278. $content
  6279. );
  6280. fputs($fp, $content);
  6281. fclose($fp);
  6282. $sql = "UPDATE $table_doc SET
  6283. title='".Database::escape_string($_POST['title'])."'
  6284. WHERE c_id = $course_id AND id = ".$document_id;
  6285. Database::query($sql);
  6286. }
  6287. }
  6288. }
  6289. /**
  6290. * Displays the selected item, with a panel for manipulating the item.
  6291. *
  6292. * @param int $item_id
  6293. * @param string $msg
  6294. * @param bool $show_actions
  6295. *
  6296. * @return string
  6297. */
  6298. public function display_item($item_id, $msg = null, $show_actions = true)
  6299. {
  6300. $course_id = api_get_course_int_id();
  6301. $return = '';
  6302. if (is_numeric($item_id)) {
  6303. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6304. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6305. WHERE lp.iid = ".intval($item_id);
  6306. $result = Database::query($sql);
  6307. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6308. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6309. // Prevents wrong parent selection for document, see Bug#1251.
  6310. if ($row['item_type'] != 'dir') {
  6311. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6312. }
  6313. if ($show_actions) {
  6314. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6315. }
  6316. $return .= '<div style="padding:10px;">';
  6317. if ($msg != '') {
  6318. $return .= $msg;
  6319. }
  6320. $return .= '<h3>'.$row['title'].'</h3>';
  6321. switch ($row['item_type']) {
  6322. case TOOL_THREAD:
  6323. $link = $this->rl_get_resource_link_for_learnpath(
  6324. $course_id,
  6325. $row['lp_id'],
  6326. $item_id,
  6327. 0
  6328. );
  6329. $return .= Display::url(
  6330. get_lang('Go to thread'),
  6331. $link,
  6332. ['class' => 'btn btn-primary']
  6333. );
  6334. break;
  6335. case TOOL_FORUM:
  6336. $return .= Display::url(
  6337. get_lang('Go to the forum'),
  6338. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6339. ['class' => 'btn btn-primary']
  6340. );
  6341. break;
  6342. case TOOL_QUIZ:
  6343. if (!empty($row['path'])) {
  6344. $exercise = new Exercise();
  6345. $exercise->read($row['path']);
  6346. $return .= $exercise->description.'<br />';
  6347. $return .= Display::url(
  6348. get_lang('Go to exercise'),
  6349. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6350. ['class' => 'btn btn-primary']
  6351. );
  6352. }
  6353. break;
  6354. case TOOL_LP_FINAL_ITEM:
  6355. $return .= $this->getSavedFinalItem();
  6356. break;
  6357. case TOOL_DOCUMENT:
  6358. case TOOL_READOUT_TEXT:
  6359. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6360. $sql_doc = "SELECT path FROM $tbl_doc
  6361. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6362. $result = Database::query($sql_doc);
  6363. $path_file = Database::result($result, 0, 0);
  6364. $path_parts = pathinfo($path_file);
  6365. // TODO: Correct the following naive comparisons.
  6366. if (in_array($path_parts['extension'], [
  6367. 'html',
  6368. 'txt',
  6369. 'png',
  6370. 'jpg',
  6371. 'JPG',
  6372. 'jpeg',
  6373. 'JPEG',
  6374. 'gif',
  6375. 'swf',
  6376. 'pdf',
  6377. 'htm',
  6378. ])) {
  6379. $return .= $this->display_document($row['path'], true, true);
  6380. }
  6381. break;
  6382. case TOOL_HOTPOTATOES:
  6383. $return .= $this->display_document($row['path'], false, true);
  6384. break;
  6385. }
  6386. $return .= '</div>';
  6387. }
  6388. }
  6389. return $return;
  6390. }
  6391. /**
  6392. * Shows the needed forms for editing a specific item.
  6393. *
  6394. * @param int $item_id
  6395. *
  6396. * @throws Exception
  6397. * @throws HTML_QuickForm_Error
  6398. *
  6399. * @return string
  6400. */
  6401. public function display_edit_item($item_id)
  6402. {
  6403. $course_id = api_get_course_int_id();
  6404. $return = '';
  6405. $item_id = (int) $item_id;
  6406. if (empty($item_id)) {
  6407. return '';
  6408. }
  6409. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6410. $sql = "SELECT * FROM $tbl_lp_item
  6411. WHERE iid = ".$item_id;
  6412. $res = Database::query($sql);
  6413. $row = Database::fetch_array($res);
  6414. switch ($row['item_type']) {
  6415. case 'dir':
  6416. case 'asset':
  6417. case 'sco':
  6418. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6419. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6420. $return .= $this->display_item_form(
  6421. $row['item_type'],
  6422. get_lang('Edit the current section').' :',
  6423. 'edit',
  6424. $item_id,
  6425. $row
  6426. );
  6427. } else {
  6428. $return .= $this->display_item_form(
  6429. $row['item_type'],
  6430. get_lang('Edit the current section').' :',
  6431. 'edit_item',
  6432. $item_id,
  6433. $row
  6434. );
  6435. }
  6436. break;
  6437. case TOOL_DOCUMENT:
  6438. case TOOL_READOUT_TEXT:
  6439. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6440. $sql = "SELECT lp.*, doc.path as dir
  6441. FROM $tbl_lp_item as lp
  6442. LEFT JOIN $tbl_doc as doc
  6443. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6444. WHERE
  6445. doc.c_id = $course_id AND
  6446. lp.iid = ".$item_id;
  6447. $res_step = Database::query($sql);
  6448. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6449. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6450. if ($row['item_type'] === TOOL_DOCUMENT) {
  6451. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6452. }
  6453. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6454. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6455. }
  6456. break;
  6457. case TOOL_LINK:
  6458. $linkId = (int) $row['path'];
  6459. if (!empty($linkId)) {
  6460. $table = Database::get_course_table(TABLE_LINK);
  6461. $sql = 'SELECT url FROM '.$table.'
  6462. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6463. $res_link = Database::query($sql);
  6464. $row_link = Database::fetch_array($res_link);
  6465. if (empty($row_link)) {
  6466. // Try with id
  6467. $sql = 'SELECT url FROM '.$table.'
  6468. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6469. $res_link = Database::query($sql);
  6470. $row_link = Database::fetch_array($res_link);
  6471. }
  6472. if (is_array($row_link)) {
  6473. $row['url'] = $row_link['url'];
  6474. }
  6475. }
  6476. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6477. $return .= $this->display_link_form('edit', $item_id, $row);
  6478. break;
  6479. case TOOL_LP_FINAL_ITEM:
  6480. Session::write('finalItem', true);
  6481. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6482. $sql = "SELECT lp.*, doc.path as dir
  6483. FROM $tbl_lp_item as lp
  6484. LEFT JOIN $tbl_doc as doc
  6485. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6486. WHERE
  6487. doc.c_id = $course_id AND
  6488. lp.iid = ".$item_id;
  6489. $res_step = Database::query($sql);
  6490. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6491. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6492. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6493. break;
  6494. case TOOL_QUIZ:
  6495. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6496. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6497. break;
  6498. case TOOL_HOTPOTATOES:
  6499. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6500. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6501. break;
  6502. case TOOL_STUDENTPUBLICATION:
  6503. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6504. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6505. break;
  6506. case TOOL_FORUM:
  6507. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6508. $return .= $this->display_forum_form('edit', $item_id, $row);
  6509. break;
  6510. case TOOL_THREAD:
  6511. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6512. $return .= $this->display_thread_form('edit', $item_id, $row);
  6513. break;
  6514. }
  6515. return $return;
  6516. }
  6517. /**
  6518. * Function that displays a list with al the resources that
  6519. * could be added to the learning path.
  6520. *
  6521. * @throws Exception
  6522. * @throws HTML_QuickForm_Error
  6523. *
  6524. * @return bool
  6525. */
  6526. public function display_resources()
  6527. {
  6528. $course_code = api_get_course_id();
  6529. // Get all the docs.
  6530. $documents = $this->get_documents(true);
  6531. // Get all the exercises.
  6532. $exercises = $this->get_exercises();
  6533. // Get all the links.
  6534. $links = $this->get_links();
  6535. // Get all the student publications.
  6536. $works = $this->get_student_publications();
  6537. // Get all the forums.
  6538. $forums = $this->get_forums(null, $course_code);
  6539. // Get the final item form (see BT#11048) .
  6540. $finish = $this->getFinalItemForm();
  6541. $headers = [
  6542. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6543. Display::return_icon('quiz.png', get_lang('Tests'), [], ICON_SIZE_BIG),
  6544. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6545. Display::return_icon('works.png', get_lang('Assignments'), [], ICON_SIZE_BIG),
  6546. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6547. Display::return_icon('add_learnpath_section.png', get_lang('Add section'), [], ICON_SIZE_BIG),
  6548. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6549. ];
  6550. echo Display::return_message(get_lang('Click on the [Learner view] button to see your learning path'), 'normal');
  6551. $dir = $this->display_item_form('dir', get_lang('EnterDataAdd section'), 'add_item');
  6552. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  6553. echo Display::tabs(
  6554. $headers,
  6555. [
  6556. $documents,
  6557. $exercises,
  6558. $links,
  6559. $works,
  6560. $forums,
  6561. $dir,
  6562. $finish,
  6563. ],
  6564. 'resource_tab',
  6565. [],
  6566. [],
  6567. $selected
  6568. );
  6569. return true;
  6570. }
  6571. /**
  6572. * Returns the extension of a document.
  6573. *
  6574. * @param string $filename
  6575. *
  6576. * @return string Extension (part after the last dot)
  6577. */
  6578. public function get_extension($filename)
  6579. {
  6580. $explode = explode('.', $filename);
  6581. return $explode[count($explode) - 1];
  6582. }
  6583. /**
  6584. * Displays a document by id.
  6585. *
  6586. * @param int $id
  6587. * @param bool $show_title
  6588. * @param bool $iframe
  6589. * @param bool $edit_link
  6590. *
  6591. * @return string
  6592. */
  6593. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6594. {
  6595. $_course = api_get_course_info();
  6596. $course_id = api_get_course_int_id();
  6597. $id = (int) $id;
  6598. $return = '';
  6599. $table = Database::get_course_table(TABLE_DOCUMENT);
  6600. $sql_doc = "SELECT * FROM $table
  6601. WHERE c_id = $course_id AND iid = $id";
  6602. $res_doc = Database::query($sql_doc);
  6603. $row_doc = Database::fetch_array($res_doc);
  6604. // TODO: Add a path filter.
  6605. if ($iframe) {
  6606. $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>';
  6607. } else {
  6608. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6609. }
  6610. return $return;
  6611. }
  6612. /**
  6613. * Return HTML form to add/edit a quiz.
  6614. *
  6615. * @param string $action Action (add/edit)
  6616. * @param int $id Item ID if already exists
  6617. * @param mixed $extra_info Extra information (quiz ID if integer)
  6618. *
  6619. * @throws Exception
  6620. *
  6621. * @return string HTML form
  6622. */
  6623. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6624. {
  6625. $course_id = api_get_course_int_id();
  6626. $id = (int) $id;
  6627. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6628. if ($id != 0 && is_array($extra_info)) {
  6629. $item_title = $extra_info['title'];
  6630. $item_description = $extra_info['description'];
  6631. } elseif (is_numeric($extra_info)) {
  6632. $sql = "SELECT title, description
  6633. FROM $tbl_quiz
  6634. WHERE c_id = $course_id AND iid = ".$extra_info;
  6635. $result = Database::query($sql);
  6636. $row = Database::fetch_array($result);
  6637. $item_title = $row['title'];
  6638. $item_description = $row['description'];
  6639. } else {
  6640. $item_title = '';
  6641. $item_description = '';
  6642. }
  6643. $item_title = Security::remove_XSS($item_title);
  6644. $item_description = Security::remove_XSS($item_description);
  6645. $parent = 0;
  6646. if ($id != 0 && is_array($extra_info)) {
  6647. $parent = $extra_info['parent_item_id'];
  6648. }
  6649. $arrLP = $this->getItemsForForm();
  6650. $this->tree_array($arrLP);
  6651. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6652. unset($this->arrMenu);
  6653. $form = new FormValidator(
  6654. 'quiz_form',
  6655. 'POST',
  6656. $this->getCurrentBuildingModeURL()
  6657. );
  6658. $defaults = [];
  6659. if ($action === 'add') {
  6660. $legend = get_lang('Adding a test to the course');
  6661. } elseif ($action === 'move') {
  6662. $legend = get_lang('Move the current test');
  6663. } else {
  6664. $legend = get_lang('Edit the current test');
  6665. }
  6666. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6667. $legend .= Display::return_message(get_lang('Warning ! ! !').' ! '.get_lang('Warning ! ! !EditingDocument'));
  6668. }
  6669. $form->addHeader($legend);
  6670. if ($action != 'move') {
  6671. $this->setItemTitle($form);
  6672. $defaults['title'] = $item_title;
  6673. }
  6674. // Select for Parent item, root or chapter
  6675. $selectParent = $form->addSelect(
  6676. 'parent',
  6677. get_lang('Parent'),
  6678. [],
  6679. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6680. );
  6681. $selectParent->addOption($this->name, 0);
  6682. $arrHide = [
  6683. $id,
  6684. ];
  6685. for ($i = 0; $i < count($arrLP); $i++) {
  6686. if ($action != 'add') {
  6687. if (
  6688. ($arrLP[$i]['item_type'] == 'dir') &&
  6689. !in_array($arrLP[$i]['id'], $arrHide) &&
  6690. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6691. ) {
  6692. $selectParent->addOption(
  6693. $arrLP[$i]['title'],
  6694. $arrLP[$i]['id'],
  6695. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6696. );
  6697. if ($parent == $arrLP[$i]['id']) {
  6698. $selectParent->setSelected($arrLP[$i]['id']);
  6699. }
  6700. } else {
  6701. $arrHide[] = $arrLP[$i]['id'];
  6702. }
  6703. } else {
  6704. if ($arrLP[$i]['item_type'] == 'dir') {
  6705. $selectParent->addOption(
  6706. $arrLP[$i]['title'],
  6707. $arrLP[$i]['id'],
  6708. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6709. );
  6710. if ($parent == $arrLP[$i]['id']) {
  6711. $selectParent->setSelected($arrLP[$i]['id']);
  6712. }
  6713. }
  6714. }
  6715. }
  6716. if (is_array($arrLP)) {
  6717. reset($arrLP);
  6718. }
  6719. $selectPrevious = $form->addSelect(
  6720. 'previous',
  6721. get_lang('Position'),
  6722. [],
  6723. ['id' => 'previous']
  6724. );
  6725. $selectPrevious->addOption(get_lang('First position'), 0);
  6726. for ($i = 0; $i < count($arrLP); $i++) {
  6727. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6728. $arrLP[$i]['id'] != $id
  6729. ) {
  6730. $selectPrevious->addOption(
  6731. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6732. $arrLP[$i]['id']
  6733. );
  6734. if (is_array($extra_info)) {
  6735. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6736. $selectPrevious->setSelected($arrLP[$i]['id']);
  6737. }
  6738. } elseif ($action == 'add') {
  6739. $selectPrevious->setSelected($arrLP[$i]['id']);
  6740. }
  6741. }
  6742. }
  6743. if ($action != 'move') {
  6744. $arrHide = [];
  6745. for ($i = 0; $i < count($arrLP); $i++) {
  6746. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6747. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6748. }
  6749. }
  6750. }
  6751. if ($action === 'add') {
  6752. $form->addButtonSave(get_lang('Add test to course'), 'submit_button');
  6753. } else {
  6754. $form->addButtonSave(get_lang('Edit the current test'), 'submit_button');
  6755. }
  6756. if ($action === 'move') {
  6757. $form->addHidden('title', $item_title);
  6758. $form->addHidden('description', $item_description);
  6759. }
  6760. if (is_numeric($extra_info)) {
  6761. $form->addHidden('path', $extra_info);
  6762. } elseif (is_array($extra_info)) {
  6763. $form->addHidden('path', $extra_info['path']);
  6764. }
  6765. $form->addHidden('type', TOOL_QUIZ);
  6766. $form->addHidden('post_time', time());
  6767. $form->setDefaults($defaults);
  6768. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6769. }
  6770. /**
  6771. * Addition of Hotpotatoes tests.
  6772. *
  6773. * @param string $action
  6774. * @param int $id Internal ID of the item
  6775. * @param string $extra_info
  6776. *
  6777. * @return string HTML structure to display the hotpotatoes addition formular
  6778. */
  6779. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6780. {
  6781. $course_id = api_get_course_int_id();
  6782. $uploadPath = DIR_HOTPOTATOES;
  6783. if ($id != 0 && is_array($extra_info)) {
  6784. $item_title = stripslashes($extra_info['title']);
  6785. $item_description = stripslashes($extra_info['description']);
  6786. } elseif (is_numeric($extra_info)) {
  6787. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6788. $sql = "SELECT * FROM $TBL_DOCUMENT
  6789. WHERE
  6790. c_id = $course_id AND
  6791. path LIKE '".$uploadPath."/%/%htm%' AND
  6792. iid = ".(int) $extra_info."
  6793. ORDER BY iid ASC";
  6794. $res_hot = Database::query($sql);
  6795. $row = Database::fetch_array($res_hot);
  6796. $item_title = $row['title'];
  6797. $item_description = $row['description'];
  6798. if (!empty($row['comment'])) {
  6799. $item_title = $row['comment'];
  6800. }
  6801. } else {
  6802. $item_title = '';
  6803. $item_description = '';
  6804. }
  6805. $parent = 0;
  6806. if ($id != 0 && is_array($extra_info)) {
  6807. $parent = $extra_info['parent_item_id'];
  6808. }
  6809. $arrLP = $this->getItemsForForm();
  6810. $legend = '<legend>';
  6811. if ($action == 'add') {
  6812. $legend .= get_lang('Adding a test to the course');
  6813. } elseif ($action == 'move') {
  6814. $legend .= get_lang('Move the current test');
  6815. } else {
  6816. $legend .= get_lang('Edit the current test');
  6817. }
  6818. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6819. $legend .= Display:: return_message(
  6820. get_lang('Warning ! ! !').' ! '.get_lang('Warning ! ! !EditingDocument')
  6821. );
  6822. }
  6823. $legend .= '</legend>';
  6824. $return = '<form method="POST">';
  6825. $return .= $legend;
  6826. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6827. $return .= '<tr>';
  6828. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6829. $return .= '<td class="input">';
  6830. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6831. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6832. $arrHide = [$id];
  6833. if (count($arrLP) > 0) {
  6834. for ($i = 0; $i < count($arrLP); $i++) {
  6835. if ($action != 'add') {
  6836. if ($arrLP[$i]['item_type'] == 'dir' &&
  6837. !in_array($arrLP[$i]['id'], $arrHide) &&
  6838. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6839. ) {
  6840. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6841. } else {
  6842. $arrHide[] = $arrLP[$i]['id'];
  6843. }
  6844. } else {
  6845. if ($arrLP[$i]['item_type'] == 'dir') {
  6846. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6847. }
  6848. }
  6849. }
  6850. reset($arrLP);
  6851. }
  6852. $return .= '</select>';
  6853. $return .= '</td>';
  6854. $return .= '</tr>';
  6855. $return .= '<tr>';
  6856. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6857. $return .= '<td class="input">';
  6858. $return .= '<select id="previous" name="previous" size="1">';
  6859. $return .= '<option class="top" value="0">'.get_lang('First position').'</option>';
  6860. for ($i = 0; $i < count($arrLP); $i++) {
  6861. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6862. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6863. $selected = 'selected="selected" ';
  6864. } elseif ($action == 'add') {
  6865. $selected = 'selected="selected" ';
  6866. } else {
  6867. $selected = '';
  6868. }
  6869. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.
  6870. get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  6871. }
  6872. }
  6873. $return .= '</select>';
  6874. $return .= '</td>';
  6875. $return .= '</tr>';
  6876. if ($action != 'move') {
  6877. $return .= '<tr>';
  6878. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  6879. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  6880. $return .= '</tr>';
  6881. $id_prerequisite = 0;
  6882. if (is_array($arrLP) && count($arrLP) > 0) {
  6883. foreach ($arrLP as $key => $value) {
  6884. if ($value['id'] == $id) {
  6885. $id_prerequisite = $value['prerequisite'];
  6886. break;
  6887. }
  6888. }
  6889. $arrHide = [];
  6890. for ($i = 0; $i < count($arrLP); $i++) {
  6891. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6892. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6893. }
  6894. }
  6895. }
  6896. }
  6897. $return .= '<tr>';
  6898. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  6899. get_lang('Save hotpotatoes').'</button></td>';
  6900. $return .= '</tr>';
  6901. $return .= '</table>';
  6902. if ($action == 'move') {
  6903. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  6904. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  6905. }
  6906. if (is_numeric($extra_info)) {
  6907. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  6908. } elseif (is_array($extra_info)) {
  6909. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  6910. }
  6911. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  6912. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  6913. $return .= '</form>';
  6914. return $return;
  6915. }
  6916. /**
  6917. * Return the form to display the forum edit/add option.
  6918. *
  6919. * @param string $action
  6920. * @param int $id ID of the lp_item if already exists
  6921. * @param string $extra_info
  6922. *
  6923. * @throws Exception
  6924. *
  6925. * @return string HTML form
  6926. */
  6927. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  6928. {
  6929. $course_id = api_get_course_int_id();
  6930. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  6931. $item_title = '';
  6932. $item_description = '';
  6933. if ($id != 0 && is_array($extra_info)) {
  6934. $item_title = stripslashes($extra_info['title']);
  6935. } elseif (is_numeric($extra_info)) {
  6936. $sql = "SELECT forum_title as title, forum_comment as comment
  6937. FROM $tbl_forum
  6938. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  6939. $result = Database::query($sql);
  6940. $row = Database::fetch_array($result);
  6941. $item_title = $row['title'];
  6942. $item_description = $row['comment'];
  6943. }
  6944. $parent = 0;
  6945. if ($id != 0 && is_array($extra_info)) {
  6946. $parent = $extra_info['parent_item_id'];
  6947. }
  6948. $arrLP = $this->getItemsForForm();
  6949. $this->tree_array($arrLP);
  6950. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6951. unset($this->arrMenu);
  6952. if ($action == 'add') {
  6953. $legend = get_lang('Adding a forum to the course');
  6954. } elseif ($action == 'move') {
  6955. $legend = get_lang('Move the current forum');
  6956. } else {
  6957. $legend = get_lang('Edit the current forum');
  6958. }
  6959. $form = new FormValidator(
  6960. 'forum_form',
  6961. 'POST',
  6962. $this->getCurrentBuildingModeURL()
  6963. );
  6964. $defaults = [];
  6965. $form->addHeader($legend);
  6966. if ($action != 'move') {
  6967. $this->setItemTitle($form);
  6968. $defaults['title'] = $item_title;
  6969. }
  6970. $selectParent = $form->addSelect(
  6971. 'parent',
  6972. get_lang('Parent'),
  6973. [],
  6974. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  6975. );
  6976. $selectParent->addOption($this->name, 0);
  6977. $arrHide = [
  6978. $id,
  6979. ];
  6980. for ($i = 0; $i < count($arrLP); $i++) {
  6981. if ($action != 'add') {
  6982. if ($arrLP[$i]['item_type'] == 'dir' &&
  6983. !in_array($arrLP[$i]['id'], $arrHide) &&
  6984. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6985. ) {
  6986. $selectParent->addOption(
  6987. $arrLP[$i]['title'],
  6988. $arrLP[$i]['id'],
  6989. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6990. );
  6991. if ($parent == $arrLP[$i]['id']) {
  6992. $selectParent->setSelected($arrLP[$i]['id']);
  6993. }
  6994. } else {
  6995. $arrHide[] = $arrLP[$i]['id'];
  6996. }
  6997. } else {
  6998. if ($arrLP[$i]['item_type'] == 'dir') {
  6999. $selectParent->addOption(
  7000. $arrLP[$i]['title'],
  7001. $arrLP[$i]['id'],
  7002. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7003. );
  7004. if ($parent == $arrLP[$i]['id']) {
  7005. $selectParent->setSelected($arrLP[$i]['id']);
  7006. }
  7007. }
  7008. }
  7009. }
  7010. if (is_array($arrLP)) {
  7011. reset($arrLP);
  7012. }
  7013. $selectPrevious = $form->addSelect(
  7014. 'previous',
  7015. get_lang('Position'),
  7016. [],
  7017. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7018. );
  7019. $selectPrevious->addOption(get_lang('First position'), 0);
  7020. for ($i = 0; $i < count($arrLP); $i++) {
  7021. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7022. $arrLP[$i]['id'] != $id
  7023. ) {
  7024. $selectPrevious->addOption(
  7025. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7026. $arrLP[$i]['id']
  7027. );
  7028. if (isset($extra_info['previous_item_id']) &&
  7029. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7030. ) {
  7031. $selectPrevious->setSelected($arrLP[$i]['id']);
  7032. } elseif ($action == 'add') {
  7033. $selectPrevious->setSelected($arrLP[$i]['id']);
  7034. }
  7035. }
  7036. }
  7037. if ($action != 'move') {
  7038. $id_prerequisite = 0;
  7039. if (is_array($arrLP)) {
  7040. foreach ($arrLP as $key => $value) {
  7041. if ($value['id'] == $id) {
  7042. $id_prerequisite = $value['prerequisite'];
  7043. break;
  7044. }
  7045. }
  7046. }
  7047. $arrHide = [];
  7048. for ($i = 0; $i < count($arrLP); $i++) {
  7049. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7050. if (isset($extra_info['previous_item_id']) &&
  7051. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7052. ) {
  7053. $s_selected_position = $arrLP[$i]['id'];
  7054. } elseif ($action == 'add') {
  7055. $s_selected_position = 0;
  7056. }
  7057. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7058. }
  7059. }
  7060. }
  7061. if ($action == 'add') {
  7062. $form->addButtonSave(get_lang('Add forum to course'), 'submit_button');
  7063. } else {
  7064. $form->addButtonSave(get_lang('Edit the current forum'), 'submit_button');
  7065. }
  7066. if ($action == 'move') {
  7067. $form->addHidden('title', $item_title);
  7068. $form->addHidden('description', $item_description);
  7069. }
  7070. if (is_numeric($extra_info)) {
  7071. $form->addHidden('path', $extra_info);
  7072. } elseif (is_array($extra_info)) {
  7073. $form->addHidden('path', $extra_info['path']);
  7074. }
  7075. $form->addHidden('type', TOOL_FORUM);
  7076. $form->addHidden('post_time', time());
  7077. $form->setDefaults($defaults);
  7078. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7079. }
  7080. /**
  7081. * Return HTML form to add/edit forum threads.
  7082. *
  7083. * @param string $action
  7084. * @param int $id Item ID if already exists in learning path
  7085. * @param string $extra_info
  7086. *
  7087. * @throws Exception
  7088. *
  7089. * @return string HTML form
  7090. */
  7091. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7092. {
  7093. $course_id = api_get_course_int_id();
  7094. if (empty($course_id)) {
  7095. return null;
  7096. }
  7097. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7098. $item_title = '';
  7099. $item_description = '';
  7100. if ($id != 0 && is_array($extra_info)) {
  7101. $item_title = stripslashes($extra_info['title']);
  7102. } elseif (is_numeric($extra_info)) {
  7103. $sql = "SELECT thread_title as title FROM $tbl_forum
  7104. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7105. $result = Database::query($sql);
  7106. $row = Database::fetch_array($result);
  7107. $item_title = $row['title'];
  7108. $item_description = '';
  7109. }
  7110. $parent = 0;
  7111. if ($id != 0 && is_array($extra_info)) {
  7112. $parent = $extra_info['parent_item_id'];
  7113. }
  7114. $arrLP = $this->getItemsForForm();
  7115. $this->tree_array($arrLP);
  7116. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7117. unset($this->arrMenu);
  7118. $form = new FormValidator(
  7119. 'thread_form',
  7120. 'POST',
  7121. $this->getCurrentBuildingModeURL()
  7122. );
  7123. $defaults = [];
  7124. if ($action == 'add') {
  7125. $legend = get_lang('Adding a forum to the course');
  7126. } elseif ($action == 'move') {
  7127. $legend = get_lang('Move the current forum');
  7128. } else {
  7129. $legend = get_lang('Edit the current forum');
  7130. }
  7131. $form->addHeader($legend);
  7132. $selectParent = $form->addSelect(
  7133. 'parent',
  7134. get_lang('Parent'),
  7135. [],
  7136. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7137. );
  7138. $selectParent->addOption($this->name, 0);
  7139. $arrHide = [
  7140. $id,
  7141. ];
  7142. for ($i = 0; $i < count($arrLP); $i++) {
  7143. if ($action != 'add') {
  7144. if (
  7145. ($arrLP[$i]['item_type'] == 'dir') &&
  7146. !in_array($arrLP[$i]['id'], $arrHide) &&
  7147. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7148. ) {
  7149. $selectParent->addOption(
  7150. $arrLP[$i]['title'],
  7151. $arrLP[$i]['id'],
  7152. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7153. );
  7154. if ($parent == $arrLP[$i]['id']) {
  7155. $selectParent->setSelected($arrLP[$i]['id']);
  7156. }
  7157. } else {
  7158. $arrHide[] = $arrLP[$i]['id'];
  7159. }
  7160. } else {
  7161. if ($arrLP[$i]['item_type'] == 'dir') {
  7162. $selectParent->addOption(
  7163. $arrLP[$i]['title'],
  7164. $arrLP[$i]['id'],
  7165. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7166. );
  7167. if ($parent == $arrLP[$i]['id']) {
  7168. $selectParent->setSelected($arrLP[$i]['id']);
  7169. }
  7170. }
  7171. }
  7172. }
  7173. if ($arrLP != null) {
  7174. reset($arrLP);
  7175. }
  7176. $selectPrevious = $form->addSelect(
  7177. 'previous',
  7178. get_lang('Position'),
  7179. [],
  7180. ['id' => 'previous']
  7181. );
  7182. $selectPrevious->addOption(get_lang('First position'), 0);
  7183. for ($i = 0; $i < count($arrLP); $i++) {
  7184. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7185. $selectPrevious->addOption(
  7186. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7187. $arrLP[$i]['id']
  7188. );
  7189. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7190. $selectPrevious->setSelected($arrLP[$i]['id']);
  7191. } elseif ($action == 'add') {
  7192. $selectPrevious->setSelected($arrLP[$i]['id']);
  7193. }
  7194. }
  7195. }
  7196. if ($action != 'move') {
  7197. $this->setItemTitle($form);
  7198. $defaults['title'] = $item_title;
  7199. $id_prerequisite = 0;
  7200. if ($arrLP != null) {
  7201. foreach ($arrLP as $key => $value) {
  7202. if ($value['id'] == $id) {
  7203. $id_prerequisite = $value['prerequisite'];
  7204. break;
  7205. }
  7206. }
  7207. }
  7208. $arrHide = [];
  7209. $s_selected_position = 0;
  7210. for ($i = 0; $i < count($arrLP); $i++) {
  7211. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7212. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7213. $s_selected_position = $arrLP[$i]['id'];
  7214. } elseif ($action == 'add') {
  7215. $s_selected_position = 0;
  7216. }
  7217. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7218. }
  7219. }
  7220. $selectPrerequisites = $form->addSelect(
  7221. 'prerequisites',
  7222. get_lang('Prerequisites'),
  7223. [],
  7224. ['id' => 'prerequisites']
  7225. );
  7226. $selectPrerequisites->addOption(get_lang('No prerequisites'), 0);
  7227. foreach ($arrHide as $key => $value) {
  7228. $selectPrerequisites->addOption($value['value'], $key);
  7229. if ($key == $s_selected_position && $action == 'add') {
  7230. $selectPrerequisites->setSelected($key);
  7231. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7232. $selectPrerequisites->setSelected($key);
  7233. }
  7234. }
  7235. }
  7236. $form->addButtonSave(get_lang('Validate'), 'submit_button');
  7237. if ($action == 'move') {
  7238. $form->addHidden('title', $item_title);
  7239. $form->addHidden('description', $item_description);
  7240. }
  7241. if (is_numeric($extra_info)) {
  7242. $form->addHidden('path', $extra_info);
  7243. } elseif (is_array($extra_info)) {
  7244. $form->addHidden('path', $extra_info['path']);
  7245. }
  7246. $form->addHidden('type', TOOL_THREAD);
  7247. $form->addHidden('post_time', time());
  7248. $form->setDefaults($defaults);
  7249. return $form->returnForm();
  7250. }
  7251. /**
  7252. * Return the HTML form to display an item (generally a dir item).
  7253. *
  7254. * @param string $item_type
  7255. * @param string $title
  7256. * @param string $action
  7257. * @param int $id
  7258. * @param string $extra_info
  7259. *
  7260. * @throws Exception
  7261. * @throws HTML_QuickForm_Error
  7262. *
  7263. * @return string HTML form
  7264. */
  7265. public function display_item_form(
  7266. $item_type,
  7267. $title = '',
  7268. $action = 'add_item',
  7269. $id = 0,
  7270. $extra_info = 'new'
  7271. ) {
  7272. $_course = api_get_course_info();
  7273. global $charset;
  7274. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7275. $item_title = '';
  7276. $item_description = '';
  7277. $item_path_fck = '';
  7278. if ($id != 0 && is_array($extra_info)) {
  7279. $item_title = $extra_info['title'];
  7280. $item_description = $extra_info['description'];
  7281. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7282. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7283. }
  7284. $parent = 0;
  7285. if ($id != 0 && is_array($extra_info)) {
  7286. $parent = $extra_info['parent_item_id'];
  7287. }
  7288. $id = (int) $id;
  7289. $sql = "SELECT * FROM $tbl_lp_item
  7290. WHERE
  7291. lp_id = ".$this->lp_id." AND
  7292. iid != $id";
  7293. if ($item_type == 'dir') {
  7294. $sql .= " AND parent_item_id = 0";
  7295. }
  7296. $result = Database::query($sql);
  7297. $arrLP = [];
  7298. while ($row = Database::fetch_array($result)) {
  7299. $arrLP[] = [
  7300. 'id' => $row['iid'],
  7301. 'item_type' => $row['item_type'],
  7302. 'title' => $this->cleanItemTitle($row['title']),
  7303. 'title_raw' => $row['title'],
  7304. 'path' => $row['path'],
  7305. 'description' => $row['description'],
  7306. 'parent_item_id' => $row['parent_item_id'],
  7307. 'previous_item_id' => $row['previous_item_id'],
  7308. 'next_item_id' => $row['next_item_id'],
  7309. 'max_score' => $row['max_score'],
  7310. 'min_score' => $row['min_score'],
  7311. 'mastery_score' => $row['mastery_score'],
  7312. 'prerequisite' => $row['prerequisite'],
  7313. 'display_order' => $row['display_order'],
  7314. ];
  7315. }
  7316. $this->tree_array($arrLP);
  7317. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7318. unset($this->arrMenu);
  7319. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7320. $form = new FormValidator('form_'.$item_type, 'POST', $url);
  7321. $defaults['title'] = api_html_entity_decode(
  7322. $item_title,
  7323. ENT_QUOTES,
  7324. $charset
  7325. );
  7326. $defaults['description'] = $item_description;
  7327. $form->addHeader($title);
  7328. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7329. $arrHide[0]['padding'] = 20;
  7330. $charset = api_get_system_encoding();
  7331. for ($i = 0; $i < count($arrLP); $i++) {
  7332. if ($action != 'add') {
  7333. if ($arrLP[$i]['item_type'] === 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7334. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7335. ) {
  7336. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7337. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7338. if ($parent == $arrLP[$i]['id']) {
  7339. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7340. }
  7341. }
  7342. } else {
  7343. if ($arrLP[$i]['item_type'] === 'dir') {
  7344. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7345. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7346. if ($parent == $arrLP[$i]['id']) {
  7347. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7348. }
  7349. }
  7350. }
  7351. }
  7352. if ($action != 'move') {
  7353. $this->setItemTitle($form);
  7354. } else {
  7355. $form->addElement('hidden', 'title');
  7356. }
  7357. $parentSelect = $form->addElement(
  7358. 'select',
  7359. 'parent',
  7360. get_lang('Parent'),
  7361. '',
  7362. [
  7363. 'id' => 'idParent',
  7364. 'onchange' => 'javascript: load_cbo(this.value);',
  7365. ]
  7366. );
  7367. foreach ($arrHide as $key => $value) {
  7368. $parentSelect->addOption(
  7369. $value['value'],
  7370. $key,
  7371. 'style="padding-left:'.$value['padding'].'px;"'
  7372. );
  7373. $lastPosition = $key;
  7374. }
  7375. if (!empty($s_selected_parent)) {
  7376. $parentSelect->setSelected($s_selected_parent);
  7377. }
  7378. if (is_array($arrLP)) {
  7379. reset($arrLP);
  7380. }
  7381. $arrHide = [];
  7382. // POSITION
  7383. for ($i = 0; $i < count($arrLP); $i++) {
  7384. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7385. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7386. //this is the same!
  7387. if (isset($extra_info['previous_item_id']) &&
  7388. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7389. ) {
  7390. $s_selected_position = $arrLP[$i]['id'];
  7391. } elseif ($action == 'add') {
  7392. $s_selected_position = $arrLP[$i]['id'];
  7393. }
  7394. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7395. }
  7396. }
  7397. $position = $form->addElement(
  7398. 'select',
  7399. 'previous',
  7400. get_lang('Position'),
  7401. '',
  7402. ['id' => 'previous']
  7403. );
  7404. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7405. $position->addOption(get_lang('First position'), 0, 'style="padding-left:'.$padding.'px;"');
  7406. $lastPosition = null;
  7407. foreach ($arrHide as $key => $value) {
  7408. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7409. $lastPosition = $key;
  7410. }
  7411. if (!empty($s_selected_position)) {
  7412. $position->setSelected($s_selected_position);
  7413. }
  7414. // When new chapter add at the end
  7415. if ($action === 'add_item') {
  7416. $position->setSelected($lastPosition);
  7417. }
  7418. if (is_array($arrLP)) {
  7419. reset($arrLP);
  7420. }
  7421. $form->addButtonSave(get_lang('Save section'), 'submit_button');
  7422. //fix in order to use the tab
  7423. if ($item_type === 'dir') {
  7424. $form->addElement('hidden', 'type', 'dir');
  7425. }
  7426. $extension = null;
  7427. if (!empty($item_path)) {
  7428. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7429. }
  7430. //assets can't be modified
  7431. //$item_type == 'asset' ||
  7432. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7433. if ($item_type == 'sco') {
  7434. $form->addElement(
  7435. 'html',
  7436. '<script>alert("'.get_lang('Warning ! ! !WhenEditingScorm').'")</script>'
  7437. );
  7438. }
  7439. $renderer = $form->defaultRenderer();
  7440. $renderer->setElementTemplate(
  7441. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7442. 'content_lp'
  7443. );
  7444. $relative_prefix = '';
  7445. $editor_config = [
  7446. 'ToolbarSet' => 'LearningPathDocuments',
  7447. 'Width' => '100%',
  7448. 'Height' => '500',
  7449. 'FullPage' => true,
  7450. 'CreateDocumentDir' => $relative_prefix,
  7451. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7452. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7453. ];
  7454. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7455. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7456. $defaults['content_lp'] = file_get_contents($content_path);
  7457. }
  7458. if (!empty($id)) {
  7459. $form->addHidden('id', $id);
  7460. }
  7461. $form->addElement('hidden', 'type', $item_type);
  7462. $form->addElement('hidden', 'post_time', time());
  7463. $form->setDefaults($defaults);
  7464. return $form->returnForm();
  7465. }
  7466. /**
  7467. * @return string
  7468. */
  7469. public function getCurrentBuildingModeURL()
  7470. {
  7471. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7472. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7473. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7474. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7475. $currentUrl = api_get_self().'?'.api_get_cidreq().
  7476. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7477. return $currentUrl;
  7478. }
  7479. /**
  7480. * Returns the form to update or create a document.
  7481. *
  7482. * @param string $action (add/edit)
  7483. * @param int $id ID of the lp_item (if already exists)
  7484. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7485. *
  7486. * @throws Exception
  7487. * @throws HTML_QuickForm_Error
  7488. *
  7489. * @return string HTML form
  7490. */
  7491. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7492. {
  7493. $course_id = api_get_course_int_id();
  7494. $_course = api_get_course_info();
  7495. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7496. $no_display_edit_textarea = false;
  7497. $item_description = '';
  7498. //If action==edit document
  7499. //We don't display the document form if it's not an editable document (html or txt file)
  7500. if ($action === 'edit') {
  7501. if (is_array($extra_info)) {
  7502. $path_parts = pathinfo($extra_info['dir']);
  7503. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7504. $no_display_edit_textarea = true;
  7505. }
  7506. }
  7507. }
  7508. $no_display_add = false;
  7509. // If action==add an existing document
  7510. // We don't display the document form if it's not an editable document (html or txt file).
  7511. if ($action === 'add') {
  7512. if (is_numeric($extra_info)) {
  7513. $extra_info = (int) $extra_info;
  7514. $sql_doc = "SELECT path FROM $tbl_doc
  7515. WHERE c_id = $course_id AND iid = ".$extra_info;
  7516. $result = Database::query($sql_doc);
  7517. $path_file = Database::result($result, 0, 0);
  7518. $path_parts = pathinfo($path_file);
  7519. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7520. $no_display_add = true;
  7521. }
  7522. }
  7523. }
  7524. $item_title = '';
  7525. $item_description = '';
  7526. if ($id != 0 && is_array($extra_info)) {
  7527. $item_title = stripslashes($extra_info['title']);
  7528. $item_description = stripslashes($extra_info['description']);
  7529. if (empty($item_title)) {
  7530. $path_parts = pathinfo($extra_info['path']);
  7531. $item_title = stripslashes($path_parts['filename']);
  7532. }
  7533. } elseif (is_numeric($extra_info)) {
  7534. $sql = "SELECT path, title FROM $tbl_doc
  7535. WHERE
  7536. c_id = ".$course_id." AND
  7537. iid = ".intval($extra_info);
  7538. $result = Database::query($sql);
  7539. $row = Database::fetch_array($result);
  7540. $item_title = $row['title'];
  7541. $item_title = str_replace('_', ' ', $item_title);
  7542. if (empty($item_title)) {
  7543. $path_parts = pathinfo($row['path']);
  7544. $item_title = stripslashes($path_parts['filename']);
  7545. }
  7546. }
  7547. $return = '<legend>';
  7548. $parent = 0;
  7549. if ($id != 0 && is_array($extra_info)) {
  7550. $parent = $extra_info['parent_item_id'];
  7551. }
  7552. $arrLP = $this->getItemsForForm();
  7553. $this->tree_array($arrLP);
  7554. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7555. unset($this->arrMenu);
  7556. if ($action == 'add') {
  7557. $return .= get_lang('Create a new document');
  7558. } elseif ($action == 'move') {
  7559. $return .= get_lang('Move the current document');
  7560. } else {
  7561. $return .= get_lang('Edit the current document');
  7562. }
  7563. $return .= '</legend>';
  7564. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7565. $return .= Display::return_message(
  7566. '<strong>'.get_lang('Warning ! ! !').' !</strong><br />'.get_lang('Warning ! ! !EditingDocument'),
  7567. false
  7568. );
  7569. }
  7570. $form = new FormValidator(
  7571. 'form',
  7572. 'POST',
  7573. $this->getCurrentBuildingModeURL(),
  7574. '',
  7575. ['enctype' => 'multipart/form-data']
  7576. );
  7577. $defaults['title'] = Security::remove_XSS($item_title);
  7578. if (empty($item_title)) {
  7579. $defaults['title'] = Security::remove_XSS($item_title);
  7580. }
  7581. $defaults['description'] = $item_description;
  7582. $form->addElement('html', $return);
  7583. if ($action != 'move') {
  7584. $data = $this->generate_lp_folder($_course);
  7585. if ($action != 'edit') {
  7586. $folders = DocumentManager::get_all_document_folders(
  7587. $_course,
  7588. 0,
  7589. true
  7590. );
  7591. DocumentManager::build_directory_selector(
  7592. $folders,
  7593. '',
  7594. [],
  7595. true,
  7596. $form,
  7597. 'directory_parent_id'
  7598. );
  7599. }
  7600. if (isset($data['id'])) {
  7601. $defaults['directory_parent_id'] = $data['id'];
  7602. }
  7603. $this->setItemTitle($form);
  7604. }
  7605. $arrHide[0]['value'] = $this->name;
  7606. $arrHide[0]['padding'] = 20;
  7607. for ($i = 0; $i < count($arrLP); $i++) {
  7608. if ($action != 'add') {
  7609. if ($arrLP[$i]['item_type'] == 'dir' &&
  7610. !in_array($arrLP[$i]['id'], $arrHide) &&
  7611. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7612. ) {
  7613. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7614. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7615. }
  7616. } else {
  7617. if ($arrLP[$i]['item_type'] == 'dir') {
  7618. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7619. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7620. }
  7621. }
  7622. }
  7623. $parentSelect = $form->addSelect(
  7624. 'parent',
  7625. get_lang('Parent'),
  7626. [],
  7627. [
  7628. 'id' => 'idParent',
  7629. 'onchange' => 'javascript: load_cbo(this.value);',
  7630. ]
  7631. );
  7632. $my_count = 0;
  7633. foreach ($arrHide as $key => $value) {
  7634. if ($my_count != 0) {
  7635. // The LP name is also the first section and is not in the same charset like the other sections.
  7636. $value['value'] = Security::remove_XSS($value['value']);
  7637. $parentSelect->addOption(
  7638. $value['value'],
  7639. $key,
  7640. 'style="padding-left:'.$value['padding'].'px;"'
  7641. );
  7642. } else {
  7643. $value['value'] = Security::remove_XSS($value['value']);
  7644. $parentSelect->addOption(
  7645. $value['value'],
  7646. $key,
  7647. 'style="padding-left:'.$value['padding'].'px;"'
  7648. );
  7649. }
  7650. $my_count++;
  7651. }
  7652. if (!empty($id)) {
  7653. $parentSelect->setSelected($parent);
  7654. } else {
  7655. $parent_item_id = Session::read('parent_item_id', 0);
  7656. $parentSelect->setSelected($parent_item_id);
  7657. }
  7658. if (is_array($arrLP)) {
  7659. reset($arrLP);
  7660. }
  7661. $arrHide = [];
  7662. // POSITION
  7663. for ($i = 0; $i < count($arrLP); $i++) {
  7664. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7665. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7666. ) {
  7667. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7668. }
  7669. }
  7670. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  7671. $position = $form->addSelect(
  7672. 'previous',
  7673. get_lang('Position'),
  7674. [],
  7675. ['id' => 'previous']
  7676. );
  7677. $position->addOption(get_lang('First position'), 0);
  7678. foreach ($arrHide as $key => $value) {
  7679. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7680. $position->addOption(
  7681. $value['value'],
  7682. $key,
  7683. 'style="padding-left:'.$padding.'px;"'
  7684. );
  7685. }
  7686. $position->setSelected($selectedPosition);
  7687. if (is_array($arrLP)) {
  7688. reset($arrLP);
  7689. }
  7690. if ($action != 'move') {
  7691. $arrHide = [];
  7692. for ($i = 0; $i < count($arrLP); $i++) {
  7693. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7694. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7695. ) {
  7696. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7697. }
  7698. }
  7699. if (!$no_display_add) {
  7700. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7701. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7702. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  7703. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  7704. ) {
  7705. if (isset($_POST['content'])) {
  7706. $content = stripslashes($_POST['content']);
  7707. } elseif (is_array($extra_info)) {
  7708. //If it's an html document or a text file
  7709. if (!$no_display_edit_textarea) {
  7710. $content = $this->display_document(
  7711. $extra_info['path'],
  7712. false,
  7713. false
  7714. );
  7715. }
  7716. } elseif (is_numeric($extra_info)) {
  7717. $content = $this->display_document(
  7718. $extra_info,
  7719. false,
  7720. false
  7721. );
  7722. } else {
  7723. $content = '';
  7724. }
  7725. if (!$no_display_edit_textarea) {
  7726. // We need to calculate here some specific settings for the online editor.
  7727. // The calculated settings work for documents in the Documents tool
  7728. // (on the root or in subfolders).
  7729. // For documents in native scorm packages it is unclear whether the
  7730. // online editor should be activated or not.
  7731. // A new document, it is in the root of the repository.
  7732. $relative_path = '';
  7733. $relative_prefix = '';
  7734. if (is_array($extra_info) && $extra_info != 'new') {
  7735. // The document already exists. Whe have to determine its relative path towards the repository root.
  7736. $relative_path = explode('/', $extra_info['dir']);
  7737. $cnt = count($relative_path) - 2;
  7738. if ($cnt < 0) {
  7739. $cnt = 0;
  7740. }
  7741. $relative_prefix = str_repeat('../', $cnt);
  7742. $relative_path = array_slice($relative_path, 1, $cnt);
  7743. $relative_path = implode('/', $relative_path);
  7744. if (strlen($relative_path) > 0) {
  7745. $relative_path = $relative_path.'/';
  7746. }
  7747. } else {
  7748. $result = $this->generate_lp_folder($_course);
  7749. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7750. $relative_prefix = '../../';
  7751. }
  7752. $editor_config = [
  7753. 'ToolbarSet' => 'LearningPathDocuments',
  7754. 'Width' => '100%',
  7755. 'Height' => '500',
  7756. 'FullPage' => true,
  7757. 'CreateDocumentDir' => $relative_prefix,
  7758. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7759. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  7760. ];
  7761. if ($_GET['action'] == 'add_item') {
  7762. $class = 'add';
  7763. $text = get_lang('Add this document to the course');
  7764. } else {
  7765. if ($_GET['action'] == 'edit_item') {
  7766. $class = 'save';
  7767. $text = get_lang('Save document');
  7768. }
  7769. }
  7770. $form->addButtonSave($text, 'submit_button');
  7771. $renderer = $form->defaultRenderer();
  7772. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7773. $form->addElement('html', '<div class="editor-lp">');
  7774. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7775. $form->addElement('html', '</div>');
  7776. $defaults['content_lp'] = $content;
  7777. }
  7778. } elseif (is_numeric($extra_info)) {
  7779. $form->addButtonSave(get_lang('Save document'), 'submit_button');
  7780. $return = $this->display_document($extra_info, true, true, true);
  7781. $form->addElement('html', $return);
  7782. }
  7783. }
  7784. }
  7785. if (isset($extra_info['item_type']) &&
  7786. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7787. ) {
  7788. $parentSelect->freeze();
  7789. $position->freeze();
  7790. }
  7791. if ($action == 'move') {
  7792. $form->addElement('hidden', 'title', $item_title);
  7793. $form->addElement('hidden', 'description', $item_description);
  7794. }
  7795. if (is_numeric($extra_info)) {
  7796. $form->addButtonSave(get_lang('Save document'), 'submit_button');
  7797. $form->addElement('hidden', 'path', $extra_info);
  7798. } elseif (is_array($extra_info)) {
  7799. $form->addButtonSave(get_lang('Save document'), 'submit_button');
  7800. $form->addElement('hidden', 'path', $extra_info['path']);
  7801. }
  7802. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7803. $form->addElement('hidden', 'post_time', time());
  7804. $form->setDefaults($defaults);
  7805. return $form->returnForm();
  7806. }
  7807. /**
  7808. * Returns the form to update or create a read-out text.
  7809. *
  7810. * @param string $action "add" or "edit"
  7811. * @param int $id ID of the lp_item (if already exists)
  7812. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7813. *
  7814. * @throws Exception
  7815. * @throws HTML_QuickForm_Error
  7816. *
  7817. * @return string HTML form
  7818. */
  7819. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  7820. {
  7821. $course_id = api_get_course_int_id();
  7822. $_course = api_get_course_info();
  7823. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7824. $no_display_edit_textarea = false;
  7825. $item_description = '';
  7826. //If action==edit document
  7827. //We don't display the document form if it's not an editable document (html or txt file)
  7828. if ($action == 'edit') {
  7829. if (is_array($extra_info)) {
  7830. $path_parts = pathinfo($extra_info['dir']);
  7831. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7832. $no_display_edit_textarea = true;
  7833. }
  7834. }
  7835. }
  7836. $no_display_add = false;
  7837. $item_title = '';
  7838. $item_description = '';
  7839. if ($id != 0 && is_array($extra_info)) {
  7840. $item_title = stripslashes($extra_info['title']);
  7841. $item_description = stripslashes($extra_info['description']);
  7842. $item_terms = stripslashes($extra_info['terms']);
  7843. if (empty($item_title)) {
  7844. $path_parts = pathinfo($extra_info['path']);
  7845. $item_title = stripslashes($path_parts['filename']);
  7846. }
  7847. } elseif (is_numeric($extra_info)) {
  7848. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  7849. $result = Database::query($sql);
  7850. $row = Database::fetch_array($result);
  7851. $item_title = $row['title'];
  7852. $item_title = str_replace('_', ' ', $item_title);
  7853. if (empty($item_title)) {
  7854. $path_parts = pathinfo($row['path']);
  7855. $item_title = stripslashes($path_parts['filename']);
  7856. }
  7857. }
  7858. $parent = 0;
  7859. if ($id != 0 && is_array($extra_info)) {
  7860. $parent = $extra_info['parent_item_id'];
  7861. }
  7862. $arrLP = $this->getItemsForForm();
  7863. $this->tree_array($arrLP);
  7864. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7865. unset($this->arrMenu);
  7866. if ($action === 'add') {
  7867. $formHeader = get_lang('Create a new document');
  7868. } else {
  7869. $formHeader = get_lang('Edit the current document');
  7870. }
  7871. if ('edit' === $action) {
  7872. $urlAudioIcon = Display::url(
  7873. Display::return_icon('audio.png', get_lang('Create read-out text'), [], ICON_SIZE_TINY),
  7874. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  7875. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  7876. );
  7877. } else {
  7878. $urlAudioIcon = Display::return_icon('audio.png', get_lang('Create read-out text'), [], ICON_SIZE_TINY);
  7879. }
  7880. $form = new FormValidator(
  7881. 'frm_add_reading',
  7882. 'POST',
  7883. $this->getCurrentBuildingModeURL(),
  7884. '',
  7885. ['enctype' => 'multipart/form-data']
  7886. );
  7887. $form->addHeader($formHeader);
  7888. $form->addHtml(
  7889. Display::return_message(
  7890. sprintf(get_lang('You need attach a audio file according to the text, clicking on the %s icon.'), $urlAudioIcon),
  7891. 'normal',
  7892. false
  7893. )
  7894. );
  7895. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  7896. $defaults['description'] = $item_description;
  7897. $data = $this->generate_lp_folder($_course);
  7898. if ($action != 'edit') {
  7899. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  7900. DocumentManager::build_directory_selector(
  7901. $folders,
  7902. '',
  7903. [],
  7904. true,
  7905. $form,
  7906. 'directory_parent_id'
  7907. );
  7908. }
  7909. if (isset($data['id'])) {
  7910. $defaults['directory_parent_id'] = $data['id'];
  7911. }
  7912. $this->setItemTitle($form);
  7913. $arrHide[0]['value'] = $this->name;
  7914. $arrHide[0]['padding'] = 20;
  7915. for ($i = 0; $i < count($arrLP); $i++) {
  7916. if ($action != 'add') {
  7917. if ($arrLP[$i]['item_type'] == 'dir' &&
  7918. !in_array($arrLP[$i]['id'], $arrHide) &&
  7919. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7920. ) {
  7921. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7922. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7923. }
  7924. } else {
  7925. if ($arrLP[$i]['item_type'] == 'dir') {
  7926. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7927. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7928. }
  7929. }
  7930. }
  7931. $parent_select = $form->addSelect(
  7932. 'parent',
  7933. get_lang('Parent'),
  7934. [],
  7935. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  7936. );
  7937. $my_count = 0;
  7938. foreach ($arrHide as $key => $value) {
  7939. if ($my_count != 0) {
  7940. // The LP name is also the first section and is not in the same charset like the other sections.
  7941. $value['value'] = Security::remove_XSS($value['value']);
  7942. $parent_select->addOption(
  7943. $value['value'],
  7944. $key,
  7945. 'style="padding-left:'.$value['padding'].'px;"'
  7946. );
  7947. } else {
  7948. $value['value'] = Security::remove_XSS($value['value']);
  7949. $parent_select->addOption(
  7950. $value['value'],
  7951. $key,
  7952. 'style="padding-left:'.$value['padding'].'px;"'
  7953. );
  7954. }
  7955. $my_count++;
  7956. }
  7957. if (!empty($id)) {
  7958. $parent_select->setSelected($parent);
  7959. } else {
  7960. $parent_item_id = Session::read('parent_item_id', 0);
  7961. $parent_select->setSelected($parent_item_id);
  7962. }
  7963. if (is_array($arrLP)) {
  7964. reset($arrLP);
  7965. }
  7966. $arrHide = [];
  7967. $s_selected_position = null;
  7968. // POSITION
  7969. $lastPosition = null;
  7970. for ($i = 0; $i < count($arrLP); $i++) {
  7971. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  7972. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7973. ) {
  7974. if ((isset($extra_info['previous_item_id']) &&
  7975. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  7976. ) {
  7977. $s_selected_position = $arrLP[$i]['id'];
  7978. }
  7979. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7980. }
  7981. $lastPosition = $arrLP[$i]['id'];
  7982. }
  7983. if (empty($s_selected_position)) {
  7984. $s_selected_position = $lastPosition;
  7985. }
  7986. $position = $form->addSelect(
  7987. 'previous',
  7988. get_lang('Position'),
  7989. []
  7990. );
  7991. $position->addOption(get_lang('First position'), 0);
  7992. foreach ($arrHide as $key => $value) {
  7993. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7994. $position->addOption(
  7995. $value['value'],
  7996. $key,
  7997. 'style="padding-left:'.$padding.'px;"'
  7998. );
  7999. }
  8000. $position->setSelected($s_selected_position);
  8001. if (is_array($arrLP)) {
  8002. reset($arrLP);
  8003. }
  8004. $arrHide = [];
  8005. for ($i = 0; $i < count($arrLP); $i++) {
  8006. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8007. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8008. ) {
  8009. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8010. }
  8011. }
  8012. if (!$no_display_add) {
  8013. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8014. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8015. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8016. if (!$no_display_edit_textarea) {
  8017. $content = '';
  8018. if (isset($_POST['content'])) {
  8019. $content = stripslashes($_POST['content']);
  8020. } elseif (is_array($extra_info)) {
  8021. $content = $this->display_document($extra_info['path'], false, false);
  8022. } elseif (is_numeric($extra_info)) {
  8023. $content = $this->display_document($extra_info, false, false);
  8024. }
  8025. // A new document, it is in the root of the repository.
  8026. if (is_array($extra_info) && $extra_info != 'new') {
  8027. } else {
  8028. $this->generate_lp_folder($_course);
  8029. }
  8030. if ($_GET['action'] == 'add_item') {
  8031. $text = get_lang('Add this document to the course');
  8032. } else {
  8033. $text = get_lang('Save document');
  8034. }
  8035. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8036. $form
  8037. ->defaultRenderer()
  8038. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8039. $form->addButtonSave($text, 'submit_button');
  8040. $defaults['content_lp'] = $content;
  8041. }
  8042. } elseif (is_numeric($extra_info)) {
  8043. $form->addButtonSave(get_lang('Save document'), 'submit_button');
  8044. $return = $this->display_document($extra_info, true, true, true);
  8045. $form->addElement('html', $return);
  8046. }
  8047. }
  8048. if (is_numeric($extra_info)) {
  8049. $form->addElement('hidden', 'path', $extra_info);
  8050. } elseif (is_array($extra_info)) {
  8051. $form->addElement('hidden', 'path', $extra_info['path']);
  8052. }
  8053. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8054. $form->addElement('hidden', 'post_time', time());
  8055. $form->setDefaults($defaults);
  8056. return $form->returnForm();
  8057. }
  8058. /**
  8059. * @param array $courseInfo
  8060. * @param string $content
  8061. * @param string $title
  8062. * @param int $parentId
  8063. *
  8064. * @throws \Doctrine\ORM\ORMException
  8065. * @throws \Doctrine\ORM\OptimisticLockException
  8066. * @throws \Doctrine\ORM\TransactionRequiredException
  8067. *
  8068. * @return int
  8069. */
  8070. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8071. {
  8072. $creatorId = api_get_user_id();
  8073. $sessionId = api_get_session_id();
  8074. // Generates folder
  8075. $result = $this->generate_lp_folder($courseInfo);
  8076. $dir = $result['dir'];
  8077. if (empty($parentId) || $parentId == '/') {
  8078. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8079. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8080. if ($parentId === '/') {
  8081. $dir = '/';
  8082. }
  8083. // Please, do not modify this dirname formatting.
  8084. if (strstr($dir, '..')) {
  8085. $dir = '/';
  8086. }
  8087. if (!empty($dir[0]) && $dir[0] == '.') {
  8088. $dir = substr($dir, 1);
  8089. }
  8090. if (!empty($dir[0]) && $dir[0] != '/') {
  8091. $dir = '/'.$dir;
  8092. }
  8093. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8094. $dir .= '/';
  8095. }
  8096. } else {
  8097. $parentInfo = DocumentManager::get_document_data_by_id(
  8098. $parentId,
  8099. $courseInfo['code']
  8100. );
  8101. if (!empty($parentInfo)) {
  8102. $dir = $parentInfo['path'].'/';
  8103. }
  8104. }
  8105. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8106. if (!is_dir($filepath)) {
  8107. $dir = '/';
  8108. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8109. }
  8110. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8111. if (!empty($title)) {
  8112. $title = api_replace_dangerous_char(stripslashes($title));
  8113. } else {
  8114. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8115. }
  8116. $title = disable_dangerous_file($title);
  8117. $filename = $title;
  8118. $content = !empty($content) ? $content : $_POST['content_lp'];
  8119. $tmpFileName = $filename;
  8120. $i = 0;
  8121. while (file_exists($filepath.$tmpFileName.'.html')) {
  8122. $tmpFileName = $filename.'_'.++$i;
  8123. }
  8124. $filename = $tmpFileName.'.html';
  8125. $content = stripslashes($content);
  8126. if (file_exists($filepath.$filename)) {
  8127. return 0;
  8128. }
  8129. $putContent = file_put_contents($filepath.$filename, $content);
  8130. if ($putContent === false) {
  8131. return 0;
  8132. }
  8133. $fileSize = filesize($filepath.$filename);
  8134. $saveFilePath = $dir.$filename;
  8135. $document = DocumentManager::addDocument(
  8136. $courseInfo,
  8137. $saveFilePath,
  8138. 'file',
  8139. $fileSize,
  8140. $tmpFileName,
  8141. '',
  8142. 0, //readonly
  8143. true,
  8144. null,
  8145. $sessionId,
  8146. $creatorId
  8147. );
  8148. $documentId = $document->getId();
  8149. if (!$document) {
  8150. return 0;
  8151. }
  8152. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8153. $newTitle = $originalTitle;
  8154. if ($newComment || $newTitle) {
  8155. $em = Database::getManager();
  8156. if ($newComment) {
  8157. $document->setComment($newComment);
  8158. }
  8159. if ($newTitle) {
  8160. $document->setTitle($newTitle);
  8161. }
  8162. $em->persist($document);
  8163. $em->flush();
  8164. }
  8165. return $documentId;
  8166. }
  8167. /**
  8168. * Return HTML form to add/edit a link item.
  8169. *
  8170. * @param string $action (add/edit)
  8171. * @param int $id Item ID if exists
  8172. * @param mixed $extra_info
  8173. *
  8174. * @throws Exception
  8175. * @throws HTML_QuickForm_Error
  8176. *
  8177. * @return string HTML form
  8178. */
  8179. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8180. {
  8181. $course_id = api_get_course_int_id();
  8182. $tbl_link = Database::get_course_table(TABLE_LINK);
  8183. $item_title = '';
  8184. $item_description = '';
  8185. $item_url = '';
  8186. if ($id != 0 && is_array($extra_info)) {
  8187. $item_title = stripslashes($extra_info['title']);
  8188. $item_description = stripslashes($extra_info['description']);
  8189. $item_url = stripslashes($extra_info['url']);
  8190. } elseif (is_numeric($extra_info)) {
  8191. $extra_info = (int) $extra_info;
  8192. $sql = "SELECT title, description, url
  8193. FROM $tbl_link
  8194. WHERE c_id = $course_id AND iid = $extra_info";
  8195. $result = Database::query($sql);
  8196. $row = Database::fetch_array($result);
  8197. $item_title = $row['title'];
  8198. $item_description = $row['description'];
  8199. $item_url = $row['url'];
  8200. }
  8201. $form = new FormValidator(
  8202. 'edit_link',
  8203. 'POST',
  8204. $this->getCurrentBuildingModeURL()
  8205. );
  8206. $defaults = [];
  8207. $parent = 0;
  8208. if ($id != 0 && is_array($extra_info)) {
  8209. $parent = $extra_info['parent_item_id'];
  8210. }
  8211. $arrLP = $this->getItemsForForm();
  8212. $this->tree_array($arrLP);
  8213. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8214. unset($this->arrMenu);
  8215. if ($action == 'add') {
  8216. $legend = get_lang('Adding a link to the course');
  8217. } elseif ($action == 'move') {
  8218. $legend = get_lang('Move the current link');
  8219. } else {
  8220. $legend = get_lang('Edit the current link');
  8221. }
  8222. $form->addHeader($legend);
  8223. if ($action != 'move') {
  8224. $this->setItemTitle($form);
  8225. $defaults['title'] = $item_title;
  8226. }
  8227. $selectParent = $form->addSelect(
  8228. 'parent',
  8229. get_lang('Parent'),
  8230. [],
  8231. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8232. );
  8233. $selectParent->addOption($this->name, 0);
  8234. $arrHide = [
  8235. $id,
  8236. ];
  8237. $parent_item_id = Session::read('parent_item_id', 0);
  8238. for ($i = 0; $i < count($arrLP); $i++) {
  8239. if ($action != 'add') {
  8240. if (
  8241. ($arrLP[$i]['item_type'] == 'dir') &&
  8242. !in_array($arrLP[$i]['id'], $arrHide) &&
  8243. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8244. ) {
  8245. $selectParent->addOption(
  8246. $arrLP[$i]['title'],
  8247. $arrLP[$i]['id'],
  8248. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8249. );
  8250. if ($parent == $arrLP[$i]['id']) {
  8251. $selectParent->setSelected($arrLP[$i]['id']);
  8252. }
  8253. } else {
  8254. $arrHide[] = $arrLP[$i]['id'];
  8255. }
  8256. } else {
  8257. if ($arrLP[$i]['item_type'] == 'dir') {
  8258. $selectParent->addOption(
  8259. $arrLP[$i]['title'],
  8260. $arrLP[$i]['id'],
  8261. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8262. );
  8263. if ($parent_item_id == $arrLP[$i]['id']) {
  8264. $selectParent->setSelected($arrLP[$i]['id']);
  8265. }
  8266. }
  8267. }
  8268. }
  8269. if (is_array($arrLP)) {
  8270. reset($arrLP);
  8271. }
  8272. $selectPrevious = $form->addSelect(
  8273. 'previous',
  8274. get_lang('Position'),
  8275. [],
  8276. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8277. );
  8278. $selectPrevious->addOption(get_lang('First position'), 0);
  8279. for ($i = 0; $i < count($arrLP); $i++) {
  8280. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8281. $selectPrevious->addOption(
  8282. $arrLP[$i]['title'],
  8283. $arrLP[$i]['id']
  8284. );
  8285. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8286. $selectPrevious->setSelected($arrLP[$i]['id']);
  8287. } elseif ($action == 'add') {
  8288. $selectPrevious->setSelected($arrLP[$i]['id']);
  8289. }
  8290. }
  8291. }
  8292. if ($action != 'move') {
  8293. $urlAttributes = ['class' => 'learnpath_item_form'];
  8294. if (is_numeric($extra_info)) {
  8295. $urlAttributes['disabled'] = 'disabled';
  8296. }
  8297. $form->addElement('url', 'url', get_lang('URL'), $urlAttributes);
  8298. $defaults['url'] = $item_url;
  8299. $arrHide = [];
  8300. for ($i = 0; $i < count($arrLP); $i++) {
  8301. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8302. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8303. }
  8304. }
  8305. }
  8306. if ($action == 'add') {
  8307. $form->addButtonSave(get_lang('Add link to course'), 'submit_button');
  8308. } else {
  8309. $form->addButtonSave(get_lang('Edit the current link'), 'submit_button');
  8310. }
  8311. if ($action == 'move') {
  8312. $form->addHidden('title', $item_title);
  8313. $form->addHidden('description', $item_description);
  8314. }
  8315. if (is_numeric($extra_info)) {
  8316. $form->addHidden('path', $extra_info);
  8317. } elseif (is_array($extra_info)) {
  8318. $form->addHidden('path', $extra_info['path']);
  8319. }
  8320. $form->addHidden('type', TOOL_LINK);
  8321. $form->addHidden('post_time', time());
  8322. $form->setDefaults($defaults);
  8323. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8324. }
  8325. /**
  8326. * Return HTML form to add/edit a student publication (work).
  8327. *
  8328. * @param string $action
  8329. * @param int $id Item ID if already exists
  8330. * @param string $extra_info
  8331. *
  8332. * @throws Exception
  8333. *
  8334. * @return string HTML form
  8335. */
  8336. public function display_student_publication_form(
  8337. $action = 'add',
  8338. $id = 0,
  8339. $extra_info = ''
  8340. ) {
  8341. $course_id = api_get_course_int_id();
  8342. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8343. $item_title = get_lang('Assignments');
  8344. if ($id != 0 && is_array($extra_info)) {
  8345. $item_title = stripslashes($extra_info['title']);
  8346. $item_description = stripslashes($extra_info['description']);
  8347. } elseif (is_numeric($extra_info)) {
  8348. $extra_info = (int) $extra_info;
  8349. $sql = "SELECT title, description
  8350. FROM $tbl_publication
  8351. WHERE c_id = $course_id AND id = ".$extra_info;
  8352. $result = Database::query($sql);
  8353. $row = Database::fetch_array($result);
  8354. if ($row) {
  8355. $item_title = $row['title'];
  8356. }
  8357. }
  8358. $parent = 0;
  8359. if ($id != 0 && is_array($extra_info)) {
  8360. $parent = $extra_info['parent_item_id'];
  8361. }
  8362. $arrLP = $this->getItemsForForm();
  8363. $this->tree_array($arrLP);
  8364. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8365. unset($this->arrMenu);
  8366. $form = new FormValidator('frm_student_publication', 'post', '#');
  8367. if ($action == 'add') {
  8368. $form->addHeader(get_lang('Assignments'));
  8369. } elseif ($action == 'move') {
  8370. $form->addHeader(get_lang('Move the current assignment'));
  8371. } else {
  8372. $form->addHeader(get_lang('Edit the current assignment'));
  8373. }
  8374. if ($action != 'move') {
  8375. $this->setItemTitle($form);
  8376. }
  8377. $parentSelect = $form->addSelect(
  8378. 'parent',
  8379. get_lang('Parent'),
  8380. ['0' => $this->name],
  8381. [
  8382. 'onchange' => 'javascript: load_cbo(this.value);',
  8383. 'class' => 'learnpath_item_form',
  8384. 'id' => 'idParent',
  8385. ]
  8386. );
  8387. $arrHide = [$id];
  8388. for ($i = 0; $i < count($arrLP); $i++) {
  8389. if ($action != 'add') {
  8390. if (
  8391. ($arrLP[$i]['item_type'] == 'dir') &&
  8392. !in_array($arrLP[$i]['id'], $arrHide) &&
  8393. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8394. ) {
  8395. $parentSelect->addOption(
  8396. $arrLP[$i]['title'],
  8397. $arrLP[$i]['id'],
  8398. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8399. );
  8400. if ($parent == $arrLP[$i]['id']) {
  8401. $parentSelect->setSelected($arrLP[$i]['id']);
  8402. }
  8403. } else {
  8404. $arrHide[] = $arrLP[$i]['id'];
  8405. }
  8406. } else {
  8407. if ($arrLP[$i]['item_type'] == 'dir') {
  8408. $parentSelect->addOption(
  8409. $arrLP[$i]['title'],
  8410. $arrLP[$i]['id'],
  8411. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8412. );
  8413. if ($parent == $arrLP[$i]['id']) {
  8414. $parentSelect->setSelected($arrLP[$i]['id']);
  8415. }
  8416. }
  8417. }
  8418. }
  8419. if (is_array($arrLP)) {
  8420. reset($arrLP);
  8421. }
  8422. $previousSelect = $form->addSelect(
  8423. 'previous',
  8424. get_lang('Position'),
  8425. ['0' => get_lang('First position')],
  8426. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8427. );
  8428. for ($i = 0; $i < count($arrLP); $i++) {
  8429. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8430. $previousSelect->addOption(
  8431. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8432. $arrLP[$i]['id']
  8433. );
  8434. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8435. $previousSelect->setSelected($arrLP[$i]['id']);
  8436. } elseif ($action == 'add') {
  8437. $previousSelect->setSelected($arrLP[$i]['id']);
  8438. }
  8439. }
  8440. }
  8441. if ($action == 'add') {
  8442. $form->addButtonCreate(get_lang('Add assignment to course'), 'submit_button');
  8443. } else {
  8444. $form->addButtonCreate(get_lang('Edit the current assignment'), 'submit_button');
  8445. }
  8446. if ($action == 'move') {
  8447. $form->addHidden('title', $item_title);
  8448. $form->addHidden('description', $item_description);
  8449. }
  8450. if (is_numeric($extra_info)) {
  8451. $form->addHidden('path', $extra_info);
  8452. } elseif (is_array($extra_info)) {
  8453. $form->addHidden('path', $extra_info['path']);
  8454. }
  8455. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8456. $form->addHidden('post_time', time());
  8457. $form->setDefaults(['title' => $item_title]);
  8458. $return = '<div class="sectioncomment">';
  8459. $return .= $form->returnForm();
  8460. $return .= '</div>';
  8461. return $return;
  8462. }
  8463. /**
  8464. * Displays the menu for manipulating a step.
  8465. *
  8466. * @param id $item_id
  8467. * @param string $item_type
  8468. *
  8469. * @return string
  8470. */
  8471. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8472. {
  8473. $_course = api_get_course_info();
  8474. $course_code = api_get_course_id();
  8475. $item_id = (int) $item_id;
  8476. $return = '<div class="actions">';
  8477. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8478. $sql = "SELECT * FROM $tbl_lp_item
  8479. WHERE iid = ".$item_id;
  8480. $result = Database::query($sql);
  8481. $row = Database::fetch_assoc($result);
  8482. $audio_player = null;
  8483. // We display an audio player if needed.
  8484. if (!empty($row['audio'])) {
  8485. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  8486. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  8487. .'<audio src="'.$webAudioPath.'" controls>'
  8488. .'</div><br>';
  8489. }
  8490. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8491. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8492. $return .= Display::url(
  8493. Display::return_icon(
  8494. 'edit.png',
  8495. get_lang('Edit'),
  8496. [],
  8497. ICON_SIZE_SMALL
  8498. ),
  8499. $url.'&action=edit_item&path_item='.$row['path']
  8500. );
  8501. $return .= Display::url(
  8502. Display::return_icon(
  8503. 'move.png',
  8504. get_lang('Move'),
  8505. [],
  8506. ICON_SIZE_SMALL
  8507. ),
  8508. $url.'&action=move_item'
  8509. );
  8510. }
  8511. // Commented for now as prerequisites cannot be added to chapters.
  8512. if ($item_type != 'dir') {
  8513. $return .= Display::url(
  8514. Display::return_icon(
  8515. 'accept.png',
  8516. get_lang('Prerequisites'),
  8517. [],
  8518. ICON_SIZE_SMALL
  8519. ),
  8520. $url.'&action=edit_item_prereq'
  8521. );
  8522. }
  8523. $return .= Display::url(
  8524. Display::return_icon(
  8525. 'delete.png',
  8526. get_lang('Delete'),
  8527. [],
  8528. ICON_SIZE_SMALL
  8529. ),
  8530. $url.'&action=delete_item'
  8531. );
  8532. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  8533. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8534. if (empty($documentData)) {
  8535. // Try with iid
  8536. $table = Database::get_course_table(TABLE_DOCUMENT);
  8537. $sql = "SELECT path FROM $table
  8538. WHERE
  8539. c_id = ".api_get_course_int_id()." AND
  8540. iid = ".$row['path']." AND
  8541. path NOT LIKE '%_DELETED_%'";
  8542. $result = Database::query($sql);
  8543. $documentData = Database::fetch_array($result);
  8544. if ($documentData) {
  8545. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  8546. }
  8547. }
  8548. if (isset($documentData['absolute_path_from_document'])) {
  8549. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  8550. }
  8551. }
  8552. $return .= '</div>';
  8553. if (!empty($audio_player)) {
  8554. $return .= $audio_player;
  8555. }
  8556. return $return;
  8557. }
  8558. /**
  8559. * Creates the javascript needed for filling up the checkboxes without page reload.
  8560. *
  8561. * @return string
  8562. */
  8563. public function get_js_dropdown_array()
  8564. {
  8565. $course_id = api_get_course_int_id();
  8566. $return = 'var child_name = new Array();'."\n";
  8567. $return .= 'var child_value = new Array();'."\n\n";
  8568. $return .= 'child_name[0] = new Array();'."\n";
  8569. $return .= 'child_value[0] = new Array();'."\n\n";
  8570. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8571. $sql = "SELECT * FROM ".$tbl_lp_item."
  8572. WHERE
  8573. c_id = $course_id AND
  8574. lp_id = ".$this->lp_id." AND
  8575. parent_item_id = 0
  8576. ORDER BY display_order ASC";
  8577. $res_zero = Database::query($sql);
  8578. $i = 0;
  8579. $list = $this->getItemsForForm(true);
  8580. foreach ($list as $row_zero) {
  8581. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8582. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8583. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8584. }
  8585. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8586. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8587. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8588. }
  8589. }
  8590. $return .= "\n";
  8591. $sql = "SELECT * FROM $tbl_lp_item
  8592. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8593. $res = Database::query($sql);
  8594. while ($row = Database::fetch_array($res)) {
  8595. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8596. WHERE
  8597. c_id = ".$course_id." AND
  8598. parent_item_id = ".$row['iid']."
  8599. ORDER BY display_order ASC";
  8600. $res_parent = Database::query($sql_parent);
  8601. $i = 0;
  8602. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8603. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8604. while ($row_parent = Database::fetch_array($res_parent)) {
  8605. $js_var = json_encode(get_lang('After').' '.$this->cleanItemTitle($row_parent['title']));
  8606. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8607. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8608. }
  8609. $return .= "\n";
  8610. }
  8611. $return .= "
  8612. function load_cbo(id) {
  8613. if (!id) {
  8614. return false;
  8615. }
  8616. var cbo = document.getElementById('previous');
  8617. for(var i = cbo.length - 1; i > 0; i--) {
  8618. cbo.options[i] = null;
  8619. }
  8620. var k=0;
  8621. for(var i = 1; i <= child_name[id].length; i++){
  8622. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  8623. option.style.paddingLeft = '40px';
  8624. cbo.options[i] = option;
  8625. k = i;
  8626. }
  8627. cbo.options[k].selected = true;
  8628. $('#previous').selectpicker('refresh');
  8629. }";
  8630. return $return;
  8631. }
  8632. /**
  8633. * Display the form to allow moving an item.
  8634. *
  8635. * @param int $item_id Item ID
  8636. *
  8637. * @throws Exception
  8638. * @throws HTML_QuickForm_Error
  8639. *
  8640. * @return string HTML form
  8641. */
  8642. public function display_move_item($item_id)
  8643. {
  8644. $return = '';
  8645. if (is_numeric($item_id)) {
  8646. $item_id = (int) $item_id;
  8647. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8648. $sql = "SELECT * FROM $tbl_lp_item
  8649. WHERE iid = $item_id";
  8650. $res = Database::query($sql);
  8651. $row = Database::fetch_array($res);
  8652. switch ($row['item_type']) {
  8653. case 'dir':
  8654. case 'asset':
  8655. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8656. $return .= $this->display_item_form(
  8657. $row['item_type'],
  8658. get_lang('Move the current section'),
  8659. 'move',
  8660. $item_id,
  8661. $row
  8662. );
  8663. break;
  8664. case TOOL_DOCUMENT:
  8665. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8666. $return .= $this->display_document_form('move', $item_id, $row);
  8667. break;
  8668. case TOOL_LINK:
  8669. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8670. $return .= $this->display_link_form('move', $item_id, $row);
  8671. break;
  8672. case TOOL_HOTPOTATOES:
  8673. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8674. $return .= $this->display_link_form('move', $item_id, $row);
  8675. break;
  8676. case TOOL_QUIZ:
  8677. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8678. $return .= $this->display_quiz_form('move', $item_id, $row);
  8679. break;
  8680. case TOOL_STUDENTPUBLICATION:
  8681. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8682. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8683. break;
  8684. case TOOL_FORUM:
  8685. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8686. $return .= $this->display_forum_form('move', $item_id, $row);
  8687. break;
  8688. case TOOL_THREAD:
  8689. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8690. $return .= $this->display_forum_form('move', $item_id, $row);
  8691. break;
  8692. }
  8693. }
  8694. return $return;
  8695. }
  8696. /**
  8697. * Return HTML form to allow prerequisites selection.
  8698. *
  8699. * @todo use FormValidator
  8700. *
  8701. * @param int Item ID
  8702. *
  8703. * @return string HTML form
  8704. */
  8705. public function display_item_prerequisites_form($item_id = 0)
  8706. {
  8707. $course_id = api_get_course_int_id();
  8708. $item_id = (int) $item_id;
  8709. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8710. /* Current prerequisite */
  8711. $sql = "SELECT * FROM $tbl_lp_item
  8712. WHERE iid = $item_id";
  8713. $result = Database::query($sql);
  8714. $row = Database::fetch_array($result);
  8715. $prerequisiteId = $row['prerequisite'];
  8716. $return = '<legend>';
  8717. $return .= get_lang('Add/edit prerequisites');
  8718. $return .= '</legend>';
  8719. $return .= '<form method="POST">';
  8720. $return .= '<div class="table-responsive">';
  8721. $return .= '<table class="table table-hover">';
  8722. $return .= '<thead>';
  8723. $return .= '<tr>';
  8724. $return .= '<th>'.get_lang('Prerequisites').'</th>';
  8725. $return .= '<th width="140">'.get_lang('minimum').'</th>';
  8726. $return .= '<th width="140">'.get_lang('maximum').'</th>';
  8727. $return .= '</tr>';
  8728. $return .= '</thead>';
  8729. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8730. $return .= '<tbody>';
  8731. $return .= '<tr>';
  8732. $return .= '<td colspan="3">';
  8733. $return .= '<div class="radio learnpath"><label for="idnone">';
  8734. $return .= '<input checked="checked" id="idnone" name="prerequisites" type="radio" />';
  8735. $return .= get_lang('none').'</label>';
  8736. $return .= '</div>';
  8737. $return .= '</tr>';
  8738. $sql = "SELECT * FROM $tbl_lp_item
  8739. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8740. $result = Database::query($sql);
  8741. $selectedMinScore = [];
  8742. $selectedMaxScore = [];
  8743. $masteryScore = [];
  8744. while ($row = Database::fetch_array($result)) {
  8745. if ($row['iid'] == $item_id) {
  8746. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8747. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8748. }
  8749. $masteryScore[$row['iid']] = $row['mastery_score'];
  8750. }
  8751. $arrLP = $this->getItemsForForm();
  8752. $this->tree_array($arrLP);
  8753. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8754. unset($this->arrMenu);
  8755. for ($i = 0; $i < count($arrLP); $i++) {
  8756. $item = $arrLP[$i];
  8757. if ($item['id'] == $item_id) {
  8758. break;
  8759. }
  8760. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8761. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8762. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  8763. $return .= '<tr>';
  8764. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8765. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8766. $return .= '<label for="id'.$item['id'].'">';
  8767. $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'].'" />';
  8768. $icon_name = str_replace(' ', '', $item['item_type']);
  8769. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8770. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8771. } else {
  8772. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8773. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8774. } else {
  8775. $return .= Display::return_icon('folder_document.png');
  8776. }
  8777. }
  8778. $return .= $item['title'].'</label>';
  8779. $return .= '</div>';
  8780. $return .= '</td>';
  8781. if ($item['item_type'] == TOOL_QUIZ) {
  8782. // lets update max_score Tests information depending of the Tests Advanced properties
  8783. $lpItemObj = new LpItem($course_id, $item['id']);
  8784. $exercise = new Exercise($course_id);
  8785. $exercise->read($lpItemObj->path);
  8786. $lpItemObj->max_score = $exercise->get_max_score();
  8787. $lpItemObj->update();
  8788. $item['max_score'] = $lpItemObj->max_score;
  8789. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  8790. // Backwards compatibility with 1.9.x use mastery_score as min value
  8791. $selectedMinScoreValue = $masteryScoreAsMinValue;
  8792. }
  8793. $return .= '<td>';
  8794. $return .= '<input
  8795. class="form-control"
  8796. size="4" maxlength="3"
  8797. name="min_'.$item['id'].'"
  8798. type="number"
  8799. min="0"
  8800. step="1"
  8801. max="'.$item['max_score'].'"
  8802. value="'.$selectedMinScoreValue.'"
  8803. />';
  8804. $return .= '</td>';
  8805. $return .= '<td>';
  8806. $return .= '<input
  8807. class="form-control"
  8808. size="4"
  8809. maxlength="3"
  8810. name="max_'.$item['id'].'"
  8811. type="number"
  8812. min="0"
  8813. step="1"
  8814. max="'.$item['max_score'].'"
  8815. value="'.$selectedMaxScoreValue.'"
  8816. />';
  8817. $return .= '</td>';
  8818. }
  8819. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8820. $return .= '<td>';
  8821. $return .= '<input
  8822. size="4"
  8823. maxlength="3"
  8824. name="min_'.$item['id'].'"
  8825. type="number"
  8826. min="0"
  8827. step="1"
  8828. max="'.$item['max_score'].'"
  8829. value="'.$selectedMinScoreValue.'"
  8830. />';
  8831. $return .= '</td>';
  8832. $return .= '<td>';
  8833. $return .= '<input
  8834. size="4"
  8835. maxlength="3"
  8836. name="max_'.$item['id'].'"
  8837. type="number"
  8838. min="0"
  8839. step="1"
  8840. max="'.$item['max_score'].'"
  8841. value="'.$selectedMaxScoreValue.'"
  8842. />';
  8843. $return .= '</td>';
  8844. }
  8845. $return .= '</tr>';
  8846. }
  8847. $return .= '<tr>';
  8848. $return .= '</tr>';
  8849. $return .= '</tbody>';
  8850. $return .= '</table>';
  8851. $return .= '</div>';
  8852. $return .= '<div class="form-group">';
  8853. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  8854. get_lang('Save prerequisites settings').'</button>';
  8855. $return .= '</form>';
  8856. return $return;
  8857. }
  8858. /**
  8859. * Return HTML list to allow prerequisites selection for lp.
  8860. *
  8861. * @return string HTML form
  8862. */
  8863. public function display_lp_prerequisites_list()
  8864. {
  8865. $course_id = api_get_course_int_id();
  8866. $lp_id = $this->lp_id;
  8867. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  8868. // get current prerequisite
  8869. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  8870. $result = Database::query($sql);
  8871. $row = Database::fetch_array($result);
  8872. $prerequisiteId = $row['prerequisite'];
  8873. $session_id = api_get_session_id();
  8874. $session_condition = api_get_session_condition($session_id, true, true);
  8875. $sql = "SELECT * FROM $tbl_lp
  8876. WHERE c_id = $course_id $session_condition
  8877. ORDER BY display_order ";
  8878. $rs = Database::query($sql);
  8879. $return = '';
  8880. $return .= '<select name="prerequisites" class="form-control">';
  8881. $return .= '<option value="0">'.get_lang('none').'</option>';
  8882. if (Database::num_rows($rs) > 0) {
  8883. while ($row = Database::fetch_array($rs)) {
  8884. if ($row['id'] == $lp_id) {
  8885. continue;
  8886. }
  8887. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  8888. }
  8889. }
  8890. $return .= '</select>';
  8891. return $return;
  8892. }
  8893. /**
  8894. * Creates a list with all the documents in it.
  8895. *
  8896. * @param bool $showInvisibleFiles
  8897. *
  8898. * @throws Exception
  8899. * @throws HTML_QuickForm_Error
  8900. *
  8901. * @return string
  8902. */
  8903. public function get_documents($showInvisibleFiles = false)
  8904. {
  8905. $course_info = api_get_course_info();
  8906. $sessionId = api_get_session_id();
  8907. $documentTree = DocumentManager::get_document_preview(
  8908. $course_info,
  8909. $this->lp_id,
  8910. null,
  8911. $sessionId,
  8912. true,
  8913. null,
  8914. null,
  8915. $showInvisibleFiles,
  8916. true
  8917. );
  8918. $headers = [
  8919. get_lang('Files'),
  8920. get_lang('Create a new document'),
  8921. get_lang('Create read-out text'),
  8922. get_lang('Upload'),
  8923. ];
  8924. $form = new FormValidator(
  8925. 'form_upload',
  8926. 'POST',
  8927. $this->getCurrentBuildingModeURL(),
  8928. '',
  8929. ['enctype' => 'multipart/form-data']
  8930. );
  8931. $folders = DocumentManager::get_all_document_folders(
  8932. api_get_course_info(),
  8933. 0,
  8934. true
  8935. );
  8936. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  8937. DocumentManager::build_directory_selector(
  8938. $folders,
  8939. $lpPathInfo['id'],
  8940. [],
  8941. true,
  8942. $form,
  8943. 'directory_parent_id'
  8944. );
  8945. $group = [
  8946. $form->createElement(
  8947. 'radio',
  8948. 'if_exists',
  8949. get_lang('If file exists:'),
  8950. get_lang('Do nothing'),
  8951. 'nothing'
  8952. ),
  8953. $form->createElement(
  8954. 'radio',
  8955. 'if_exists',
  8956. null,
  8957. get_lang('Overwrite the existing file'),
  8958. 'overwrite'
  8959. ),
  8960. $form->createElement(
  8961. 'radio',
  8962. 'if_exists',
  8963. null,
  8964. get_lang('Rename the uploaded file if it exists'),
  8965. 'rename'
  8966. ),
  8967. ];
  8968. $form->addGroup($group, null, get_lang('If file exists:'));
  8969. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  8970. $defaultFileExistsOption = 'rename';
  8971. if (!empty($fileExistsOption)) {
  8972. $defaultFileExistsOption = $fileExistsOption;
  8973. }
  8974. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  8975. // Check box options
  8976. $form->addElement(
  8977. 'checkbox',
  8978. 'unzip',
  8979. get_lang('Options'),
  8980. get_lang('Uncompress zip')
  8981. );
  8982. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  8983. $form->addMultipleUpload($url);
  8984. $new = $this->display_document_form('add', 0);
  8985. $frmReadOutText = $this->displayFrmReadOutText('add');
  8986. $tabs = Display::tabs(
  8987. $headers,
  8988. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  8989. 'subtab'
  8990. );
  8991. return $tabs;
  8992. }
  8993. /**
  8994. * Creates a list with all the exercises (quiz) in it.
  8995. *
  8996. * @return string
  8997. */
  8998. public function get_exercises()
  8999. {
  9000. $course_id = api_get_course_int_id();
  9001. $session_id = api_get_session_id();
  9002. $userInfo = api_get_user_info();
  9003. // New for hotpotatoes.
  9004. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9005. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9006. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9007. $condition_session = api_get_session_condition($session_id, true, true);
  9008. $setting = api_get_setting('lp.show_invisible_exercise_in_lp_toc') === 'true';
  9009. $activeCondition = ' active <> -1 ';
  9010. if ($setting) {
  9011. $activeCondition = ' active = 1 ';
  9012. }
  9013. $categoryCondition = '';
  9014. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9015. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9016. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9017. }
  9018. $keywordCondition = '';
  9019. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9020. if (!empty($keyword)) {
  9021. $keyword = Database::escape_string($keyword);
  9022. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9023. }
  9024. $sql_quiz = "SELECT * FROM $tbl_quiz
  9025. WHERE
  9026. c_id = $course_id AND
  9027. $activeCondition
  9028. $condition_session
  9029. $categoryCondition
  9030. $keywordCondition
  9031. ORDER BY title ASC";
  9032. $sql_hot = "SELECT * FROM $tbl_doc
  9033. WHERE
  9034. c_id = $course_id AND
  9035. path LIKE '".$uploadPath."/%/%htm%'
  9036. $condition_session
  9037. ORDER BY id ASC";
  9038. $res_quiz = Database::query($sql_quiz);
  9039. $res_hot = Database::query($sql_hot);
  9040. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9041. // Create a search-box
  9042. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9043. $form->addHidden('action', 'add_item');
  9044. $form->addHidden('type', 'step');
  9045. $form->addHidden('lp_id', $this->lp_id);
  9046. $form->addHidden('lp_build_selected', '2');
  9047. $form->addCourseHiddenParams();
  9048. $form->addText(
  9049. 'keyword',
  9050. get_lang('Search'),
  9051. false,
  9052. [
  9053. 'aria-label' => get_lang('Search'),
  9054. ]
  9055. );
  9056. if (api_get_configuration_value('allow_exercise_categories')) {
  9057. $manager = new ExerciseCategoryManager();
  9058. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9059. if (!empty($options)) {
  9060. $form->addSelect(
  9061. 'category_id',
  9062. get_lang('Category'),
  9063. $options,
  9064. ['placeholder' => get_lang('Please select an option')]
  9065. );
  9066. }
  9067. }
  9068. $form->addButtonSearch(get_lang('Search'));
  9069. $return = $form->returnForm();
  9070. $return .= '<ul class="lp_resource">';
  9071. $return .= '<li class="lp_resource_element">';
  9072. $return .= Display::return_icon('new_exercice.png');
  9073. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9074. get_lang('New test').'</a>';
  9075. $return .= '</li>';
  9076. $previewIcon = Display::return_icon(
  9077. 'preview_view.png',
  9078. get_lang('Preview')
  9079. );
  9080. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9081. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9082. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9083. // Display hotpotatoes
  9084. while ($row_hot = Database::fetch_array($res_hot)) {
  9085. $link = Display::url(
  9086. $previewIcon,
  9087. $exerciseUrl.'&file='.$row_hot['path'],
  9088. ['target' => '_blank']
  9089. );
  9090. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9091. $return .= '<a class="moved" href="#">';
  9092. $return .= Display::return_icon(
  9093. 'move_everywhere.png',
  9094. get_lang('Move'),
  9095. [],
  9096. ICON_SIZE_TINY
  9097. );
  9098. $return .= '</a> ';
  9099. $return .= Display::return_icon('hotpotatoes_s.png');
  9100. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9101. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9102. $return .= '</li>';
  9103. }
  9104. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9105. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9106. $title = strip_tags(
  9107. api_html_entity_decode($row_quiz['title'])
  9108. );
  9109. $visibility = api_get_item_visibility(
  9110. ['real_id' => $course_id],
  9111. TOOL_QUIZ,
  9112. $row_quiz['iid'],
  9113. $session_id
  9114. );
  9115. $link = Display::url(
  9116. $previewIcon,
  9117. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9118. ['target' => '_blank']
  9119. );
  9120. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9121. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9122. $return .= $quizIcon;
  9123. $sessionStar = api_get_session_image(
  9124. $row_quiz['session_id'],
  9125. $userInfo['status']
  9126. );
  9127. $return .= Display::url(
  9128. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9129. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9130. [
  9131. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9132. ]
  9133. );
  9134. $return .= '</li>';
  9135. }
  9136. $return .= '</ul>';
  9137. return $return;
  9138. }
  9139. /**
  9140. * Creates a list with all the links in it.
  9141. *
  9142. * @return string
  9143. */
  9144. public function get_links()
  9145. {
  9146. $selfUrl = api_get_self();
  9147. $courseIdReq = api_get_cidreq();
  9148. $course = api_get_course_info();
  9149. $userInfo = api_get_user_info();
  9150. $course_id = $course['real_id'];
  9151. $tbl_link = Database::get_course_table(TABLE_LINK);
  9152. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9153. $moveEverywhereIcon = Display::return_icon(
  9154. 'move_everywhere.png',
  9155. get_lang('Move'),
  9156. [],
  9157. ICON_SIZE_TINY
  9158. );
  9159. $session_id = api_get_session_id();
  9160. $condition_session = api_get_session_condition(
  9161. $session_id,
  9162. true,
  9163. true,
  9164. 'link.session_id'
  9165. );
  9166. $sql = "SELECT
  9167. link.id as link_id,
  9168. link.title as link_title,
  9169. link.session_id as link_session_id,
  9170. link.category_id as category_id,
  9171. link_category.category_title as category_title
  9172. FROM $tbl_link as link
  9173. LEFT JOIN $linkCategoryTable as link_category
  9174. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9175. WHERE link.c_id = $course_id $condition_session
  9176. ORDER BY link_category.category_title ASC, link.title ASC";
  9177. $result = Database::query($sql);
  9178. $categorizedLinks = [];
  9179. $categories = [];
  9180. while ($link = Database::fetch_array($result)) {
  9181. if (!$link['category_id']) {
  9182. $link['category_title'] = get_lang('Uncategorized');
  9183. }
  9184. $categories[$link['category_id']] = $link['category_title'];
  9185. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9186. }
  9187. $linksHtmlCode =
  9188. '<script>
  9189. function toggle_tool(tool, id) {
  9190. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9191. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9192. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9193. } else {
  9194. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9195. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.png').'";
  9196. }
  9197. }
  9198. </script>
  9199. <ul class="lp_resource">
  9200. <li class="lp_resource_element">
  9201. '.Display::return_icon('linksnew.gif').'
  9202. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('Add a link').'">'.
  9203. get_lang('Add a link').'
  9204. </a>
  9205. </li>';
  9206. foreach ($categorizedLinks as $categoryId => $links) {
  9207. $linkNodes = null;
  9208. foreach ($links as $key => $linkInfo) {
  9209. $title = $linkInfo['link_title'];
  9210. $linkSessionId = $linkInfo['link_session_id'];
  9211. $link = Display::url(
  9212. Display::return_icon('preview_view.png', get_lang('Preview')),
  9213. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9214. ['target' => '_blank']
  9215. );
  9216. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9217. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9218. $linkNodes .=
  9219. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9220. <a class="moved" href="#">'.
  9221. $moveEverywhereIcon.
  9222. '</a>
  9223. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9224. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9225. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9226. Security::remove_XSS($title).$sessionStar.$link.
  9227. '</a>
  9228. </li>';
  9229. }
  9230. }
  9231. $linksHtmlCode .=
  9232. '<li>
  9233. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9234. <img src="'.Display::returnIconPath('add.png').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9235. align="absbottom" />
  9236. </a>
  9237. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9238. </li>
  9239. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9240. }
  9241. $linksHtmlCode .= '</ul>';
  9242. return $linksHtmlCode;
  9243. }
  9244. /**
  9245. * Creates a list with all the student publications in it.
  9246. *
  9247. * @return string
  9248. */
  9249. public function get_student_publications()
  9250. {
  9251. $return = '<ul class="lp_resource">';
  9252. $return .= '<li class="lp_resource_element">';
  9253. $return .= Display::return_icon('works_new.gif');
  9254. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9255. get_lang('Add the Assignments tool to the course').'</a>';
  9256. $return .= '</li>';
  9257. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9258. $works = getWorkListTeacher(0, 100, null, null, null);
  9259. if (!empty($works)) {
  9260. foreach ($works as $work) {
  9261. $link = Display::url(
  9262. Display::return_icon('preview_view.png', get_lang('Preview')),
  9263. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9264. ['target' => '_blank']
  9265. );
  9266. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9267. $return .= '<a class="moved" href="#">';
  9268. $return .= Display::return_icon(
  9269. 'move_everywhere.png',
  9270. get_lang('Move'),
  9271. [],
  9272. ICON_SIZE_TINY
  9273. );
  9274. $return .= '</a> ';
  9275. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9276. $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.'">'.
  9277. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9278. </a>';
  9279. $return .= '</li>';
  9280. }
  9281. }
  9282. $return .= '</ul>';
  9283. return $return;
  9284. }
  9285. /**
  9286. * Creates a list with all the forums in it.
  9287. *
  9288. * @return string
  9289. */
  9290. public function get_forums()
  9291. {
  9292. require_once '../forum/forumfunction.inc.php';
  9293. $forumCategories = get_forum_categories();
  9294. $forumsInNoCategory = get_forums_in_category(0);
  9295. if (!empty($forumsInNoCategory)) {
  9296. $forumCategories = array_merge(
  9297. $forumCategories,
  9298. [
  9299. [
  9300. 'cat_id' => 0,
  9301. 'session_id' => 0,
  9302. 'visibility' => 1,
  9303. 'cat_comment' => null,
  9304. ],
  9305. ]
  9306. );
  9307. }
  9308. $forumList = get_forums();
  9309. $a_forums = [];
  9310. foreach ($forumCategories as $forumCategory) {
  9311. // The forums in this category.
  9312. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9313. if (!empty($forumsInCategory)) {
  9314. foreach ($forumList as $forum) {
  9315. if (isset($forum['forum_category']) &&
  9316. $forum['forum_category'] == $forumCategory['cat_id']
  9317. ) {
  9318. $a_forums[] = $forum;
  9319. }
  9320. }
  9321. }
  9322. }
  9323. $return = '<ul class="lp_resource">';
  9324. // First add link
  9325. $return .= '<li class="lp_resource_element">';
  9326. $return .= Display::return_icon('new_forum.png');
  9327. $return .= Display::url(
  9328. get_lang('Create a new forum'),
  9329. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9330. 'action' => 'add',
  9331. 'content' => 'forum',
  9332. 'lp_id' => $this->lp_id,
  9333. ]),
  9334. ['title' => get_lang('Create a new forum')]
  9335. );
  9336. $return .= '</li>';
  9337. $return .= '<script>
  9338. function toggle_forum(forum_id) {
  9339. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9340. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9341. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9342. } else {
  9343. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9344. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.png').'";
  9345. }
  9346. }
  9347. </script>';
  9348. foreach ($a_forums as $forum) {
  9349. if (!empty($forum['forum_id'])) {
  9350. $link = Display::url(
  9351. Display::return_icon('preview_view.png', get_lang('Preview')),
  9352. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9353. ['target' => '_blank']
  9354. );
  9355. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9356. $return .= '<a class="moved" href="#">';
  9357. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9358. $return .= ' </a>';
  9359. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9360. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9361. <img src="'.Display::returnIconPath('add.png').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9362. </a>
  9363. <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">'.
  9364. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9365. $return .= '</li>';
  9366. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9367. $a_threads = get_threads($forum['forum_id']);
  9368. if (is_array($a_threads)) {
  9369. foreach ($a_threads as $thread) {
  9370. $link = Display::url(
  9371. Display::return_icon('preview_view.png', get_lang('Preview')),
  9372. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9373. ['target' => '_blank']
  9374. );
  9375. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9376. $return .= '&nbsp;<a class="moved" href="#">';
  9377. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9378. $return .= ' </a>';
  9379. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9380. $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.'">'.
  9381. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9382. $return .= '</li>';
  9383. }
  9384. }
  9385. $return .= '</div>';
  9386. }
  9387. }
  9388. $return .= '</ul>';
  9389. return $return;
  9390. }
  9391. /**
  9392. * // TODO: The output encoding should be equal to the system encoding.
  9393. *
  9394. * Exports the learning path as a SCORM package. This is the main function that
  9395. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9396. * whole thing and returns the zip.
  9397. *
  9398. * This method needs to be called in PHP5, as it will fail with non-adequate
  9399. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9400. * you need to call it on a learnpath object.
  9401. *
  9402. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9403. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9404. * path has been modified, it should use the generic method here below.
  9405. *
  9406. * @return string Returns the zip package string, or null if error
  9407. */
  9408. public function scormExport()
  9409. {
  9410. api_set_more_memory_and_time_limits();
  9411. $_course = api_get_course_info();
  9412. $course_id = $_course['real_id'];
  9413. // Create the zip handler (this will remain available throughout the method).
  9414. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9415. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9416. $temp_dir_short = uniqid('scorm_export', true);
  9417. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9418. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9419. $zip_folder = new PclZip($temp_zip_file);
  9420. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9421. $root_path = $main_path = api_get_path(SYS_PATH);
  9422. $files_cleanup = [];
  9423. // Place to temporarily stash the zip file.
  9424. // create the temp dir if it doesn't exist
  9425. // or do a cleanup before creating the zip file.
  9426. if (!is_dir($temp_zip_dir)) {
  9427. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9428. } else {
  9429. // Cleanup: Check the temp dir for old files and delete them.
  9430. $handle = opendir($temp_zip_dir);
  9431. while (false !== ($file = readdir($handle))) {
  9432. if ($file != '.' && $file != '..') {
  9433. unlink("$temp_zip_dir/$file");
  9434. }
  9435. }
  9436. closedir($handle);
  9437. }
  9438. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9439. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9440. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9441. ) {
  9442. // Remove the possible . at the end of the path.
  9443. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9444. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9445. mkdir(
  9446. $dest_path_to_scorm_folder,
  9447. api_get_permissions_for_new_directories(),
  9448. true
  9449. );
  9450. copyr(
  9451. $current_course_path.'/scorm/'.$this->path,
  9452. $dest_path_to_scorm_folder,
  9453. ['imsmanifest'],
  9454. $zip_files
  9455. );
  9456. }
  9457. // Build a dummy imsmanifest structure.
  9458. // Do not add to the zip yet (we still need it).
  9459. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9460. // Aggregation Model official document, section "2.3 Content Packaging".
  9461. // We are going to build a UTF-8 encoded manifest.
  9462. // Later we will recode it to the desired (and supported) encoding.
  9463. $xmldoc = new DOMDocument('1.0');
  9464. $root = $xmldoc->createElement('manifest');
  9465. $root->setAttribute('identifier', 'SingleCourseManifest');
  9466. $root->setAttribute('version', '1.1');
  9467. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9468. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9469. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9470. $root->setAttribute(
  9471. 'xsi:schemaLocation',
  9472. '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'
  9473. );
  9474. // Build mandatory sub-root container elements.
  9475. $metadata = $xmldoc->createElement('metadata');
  9476. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9477. $metadata->appendChild($md_schema);
  9478. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9479. $metadata->appendChild($md_schemaversion);
  9480. $root->appendChild($metadata);
  9481. $organizations = $xmldoc->createElement('organizations');
  9482. $resources = $xmldoc->createElement('resources');
  9483. // Build the only organization we will use in building our learnpaths.
  9484. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9485. $organization = $xmldoc->createElement('organization');
  9486. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9487. // To set the title of the SCORM entity (=organization), we take the name given
  9488. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9489. // learning path charset) as it is the encoding that defines how it is stored
  9490. // in the database. Then we convert it to HTML entities again as the "&" character
  9491. // alone is not authorized in XML (must be &amp;).
  9492. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9493. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9494. $organization->appendChild($org_title);
  9495. $folder_name = 'document';
  9496. // Removes the learning_path/scorm_folder path when exporting see #4841
  9497. $path_to_remove = '';
  9498. $path_to_replace = '';
  9499. $result = $this->generate_lp_folder($_course);
  9500. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9501. $path_to_remove = 'document'.$result['dir'];
  9502. $path_to_replace = $folder_name.'/';
  9503. }
  9504. // Fixes chamilo scorm exports
  9505. if ($this->ref === 'chamilo_scorm_export') {
  9506. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9507. }
  9508. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9509. $link_updates = [];
  9510. $links_to_create = [];
  9511. foreach ($this->ordered_items as $index => $itemId) {
  9512. /** @var learnpathItem $item */
  9513. $item = $this->items[$itemId];
  9514. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9515. // Get included documents from this item.
  9516. if ($item->type === 'sco') {
  9517. $inc_docs = $item->get_resources_from_source(
  9518. null,
  9519. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  9520. );
  9521. } else {
  9522. $inc_docs = $item->get_resources_from_source();
  9523. }
  9524. // Give a child element <item> to the <organization> element.
  9525. $my_item_id = $item->get_id();
  9526. $my_item = $xmldoc->createElement('item');
  9527. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9528. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9529. $my_item->setAttribute('isvisible', 'true');
  9530. // Give a child element <title> to the <item> element.
  9531. $my_title = $xmldoc->createElement(
  9532. 'title',
  9533. htmlspecialchars(
  9534. api_utf8_encode($item->get_title()),
  9535. ENT_QUOTES,
  9536. 'UTF-8'
  9537. )
  9538. );
  9539. $my_item->appendChild($my_title);
  9540. // Give a child element <adlcp:prerequisites> to the <item> element.
  9541. $my_prereqs = $xmldoc->createElement(
  9542. 'adlcp:prerequisites',
  9543. $this->get_scorm_prereq_string($my_item_id)
  9544. );
  9545. $my_prereqs->setAttribute('type', 'aicc_script');
  9546. $my_item->appendChild($my_prereqs);
  9547. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9548. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9549. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9550. //$xmldoc->createElement('adlcp:timelimitaction','');
  9551. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9552. //$xmldoc->createElement('adlcp:datafromlms','');
  9553. // Give a child element <adlcp:masteryscore> to the <item> element.
  9554. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9555. $my_item->appendChild($my_masteryscore);
  9556. // Attach this item to the organization element or hits parent if there is one.
  9557. if (!empty($item->parent) && $item->parent != 0) {
  9558. $children = $organization->childNodes;
  9559. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9560. if (is_object($possible_parent)) {
  9561. $possible_parent->appendChild($my_item);
  9562. } else {
  9563. if ($this->debug > 0) {
  9564. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9565. }
  9566. }
  9567. } else {
  9568. if ($this->debug > 0) {
  9569. error_log('No parent');
  9570. }
  9571. $organization->appendChild($my_item);
  9572. }
  9573. // Get the path of the file(s) from the course directory root.
  9574. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9575. $my_xml_file_path = $my_file_path;
  9576. if (!empty($path_to_remove)) {
  9577. // From docs
  9578. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9579. // From quiz
  9580. if ($this->ref === 'chamilo_scorm_export') {
  9581. $path_to_remove = 'scorm/'.$this->path.'/';
  9582. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9583. }
  9584. }
  9585. $my_sub_dir = dirname($my_file_path);
  9586. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9587. $my_xml_sub_dir = $my_sub_dir;
  9588. // Give a <resource> child to the <resources> element
  9589. $my_resource = $xmldoc->createElement('resource');
  9590. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9591. $my_resource->setAttribute('type', 'webcontent');
  9592. $my_resource->setAttribute('href', $my_xml_file_path);
  9593. // adlcp:scormtype can be either 'sco' or 'asset'.
  9594. if ($item->type === 'sco') {
  9595. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9596. } else {
  9597. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9598. }
  9599. // xml:base is the base directory to find the files declared in this resource.
  9600. $my_resource->setAttribute('xml:base', '');
  9601. // Give a <file> child to the <resource> element.
  9602. $my_file = $xmldoc->createElement('file');
  9603. $my_file->setAttribute('href', $my_xml_file_path);
  9604. $my_resource->appendChild($my_file);
  9605. // Dependency to other files - not yet supported.
  9606. $i = 1;
  9607. if ($inc_docs) {
  9608. foreach ($inc_docs as $doc_info) {
  9609. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9610. continue;
  9611. }
  9612. $my_dep = $xmldoc->createElement('resource');
  9613. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9614. $my_dep->setAttribute('identifier', $res_id);
  9615. $my_dep->setAttribute('type', 'webcontent');
  9616. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9617. $my_dep_file = $xmldoc->createElement('file');
  9618. // Check type of URL.
  9619. if ($doc_info[1] == 'remote') {
  9620. // Remote file. Save url as is.
  9621. $my_dep_file->setAttribute('href', $doc_info[0]);
  9622. $my_dep->setAttribute('xml:base', '');
  9623. } elseif ($doc_info[1] === 'local') {
  9624. switch ($doc_info[2]) {
  9625. case 'url':
  9626. // Local URL - save path as url for now, don't zip file.
  9627. $abs_path = api_get_path(SYS_PATH).
  9628. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9629. $current_dir = dirname($abs_path);
  9630. $current_dir = str_replace('\\', '/', $current_dir);
  9631. $file_path = realpath($abs_path);
  9632. $file_path = str_replace('\\', '/', $file_path);
  9633. $my_dep_file->setAttribute('href', $file_path);
  9634. $my_dep->setAttribute('xml:base', '');
  9635. if (strstr($file_path, $main_path) !== false) {
  9636. // The calculated real path is really inside Chamilo's root path.
  9637. // Reduce file path to what's under the DocumentRoot.
  9638. $replace = $file_path;
  9639. $file_path = substr($file_path, strlen($root_path) - 1);
  9640. $destinationFile = $file_path;
  9641. if (strstr($file_path, 'upload/users') !== false) {
  9642. $pos = strpos($file_path, 'my_files/');
  9643. if ($pos !== false) {
  9644. $onlyDirectory = str_replace(
  9645. 'upload/users/',
  9646. '',
  9647. substr($file_path, $pos, strlen($file_path))
  9648. );
  9649. }
  9650. $replace = $onlyDirectory;
  9651. $destinationFile = $replace;
  9652. }
  9653. $zip_files_abs[] = $file_path;
  9654. $link_updates[$my_file_path][] = [
  9655. 'orig' => $doc_info[0],
  9656. 'dest' => $destinationFile,
  9657. 'replace' => $replace,
  9658. ];
  9659. $my_dep_file->setAttribute('href', $file_path);
  9660. $my_dep->setAttribute('xml:base', '');
  9661. } elseif (empty($file_path)) {
  9662. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9663. $file_path = str_replace('//', '/', $file_path);
  9664. if (file_exists($file_path)) {
  9665. // We get the relative path.
  9666. $file_path = substr($file_path, strlen($current_dir));
  9667. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9668. $link_updates[$my_file_path][] = [
  9669. 'orig' => $doc_info[0],
  9670. 'dest' => $file_path,
  9671. ];
  9672. $my_dep_file->setAttribute('href', $file_path);
  9673. $my_dep->setAttribute('xml:base', '');
  9674. }
  9675. }
  9676. break;
  9677. case 'abs':
  9678. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9679. $my_dep_file->setAttribute('href', $doc_info[0]);
  9680. $my_dep->setAttribute('xml:base', '');
  9681. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9682. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9683. $abs_img_path_without_subdir = $doc_info[0];
  9684. $relp = api_get_path(REL_PATH); // The url-append config param.
  9685. $pos = strpos($abs_img_path_without_subdir, $relp);
  9686. if ($pos === 0) {
  9687. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  9688. }
  9689. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9690. $file_path = str_replace(['\\', '//'], '/', $file_path);
  9691. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9692. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9693. // Check if the current document is in that path.
  9694. if (strstr($file_path, $cur_path) !== false) {
  9695. $destinationFile = substr($file_path, strlen($cur_path));
  9696. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  9697. $fileToTest = $cur_path.$my_file_path;
  9698. if (!empty($path_to_remove)) {
  9699. $fileToTest = str_replace(
  9700. $path_to_remove.'/',
  9701. $path_to_replace,
  9702. $cur_path.$my_file_path
  9703. );
  9704. }
  9705. $relative_path = api_get_relative_path($fileToTest, $file_path);
  9706. // Put the current document in the zip (this array is the array
  9707. // that will manage documents already in the course folder - relative).
  9708. $zip_files[] = $filePathNoCoursePart;
  9709. // Update the links to the current document in the
  9710. // containing document (make them relative).
  9711. $link_updates[$my_file_path][] = [
  9712. 'orig' => $doc_info[0],
  9713. 'dest' => $destinationFile,
  9714. 'replace' => $relative_path,
  9715. ];
  9716. $my_dep_file->setAttribute('href', $file_path);
  9717. $my_dep->setAttribute('xml:base', '');
  9718. } elseif (strstr($file_path, $main_path) !== false) {
  9719. // The calculated real path is really inside Chamilo's root path.
  9720. // Reduce file path to what's under the DocumentRoot.
  9721. $file_path = substr($file_path, strlen($root_path));
  9722. $zip_files_abs[] = $file_path;
  9723. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9724. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9725. $my_dep->setAttribute('xml:base', '');
  9726. } elseif (empty($file_path)) {
  9727. // Probably this is an image inside "/main" directory
  9728. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  9729. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9730. if (file_exists($file_path)) {
  9731. if (strstr($file_path, 'main/default_course_document') !== false) {
  9732. // We get the relative path.
  9733. $pos = strpos($file_path, 'main/default_course_document/');
  9734. if ($pos !== false) {
  9735. $onlyDirectory = str_replace(
  9736. 'main/default_course_document/',
  9737. '',
  9738. substr($file_path, $pos, strlen($file_path))
  9739. );
  9740. }
  9741. $destinationFile = 'default_course_document/'.$onlyDirectory;
  9742. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  9743. $zip_files_abs[] = $fileAbs;
  9744. $link_updates[$my_file_path][] = [
  9745. 'orig' => $doc_info[0],
  9746. 'dest' => $destinationFile,
  9747. ];
  9748. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9749. $my_dep->setAttribute('xml:base', '');
  9750. }
  9751. }
  9752. }
  9753. break;
  9754. case 'rel':
  9755. // Path relative to the current document.
  9756. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9757. if (substr($doc_info[0], 0, 2) === '..') {
  9758. // Relative path going up.
  9759. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9760. $current_dir = str_replace('\\', '/', $current_dir);
  9761. $file_path = realpath($current_dir.$doc_info[0]);
  9762. $file_path = str_replace('\\', '/', $file_path);
  9763. if (strstr($file_path, $main_path) !== false) {
  9764. // The calculated real path is really inside Chamilo's root path.
  9765. // Reduce file path to what's under the DocumentRoot.
  9766. $file_path = substr($file_path, strlen($root_path));
  9767. $zip_files_abs[] = $file_path;
  9768. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9769. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9770. $my_dep->setAttribute('xml:base', '');
  9771. }
  9772. } else {
  9773. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9774. $my_dep_file->setAttribute('href', $doc_info[0]);
  9775. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9776. }
  9777. break;
  9778. default:
  9779. $my_dep_file->setAttribute('href', $doc_info[0]);
  9780. $my_dep->setAttribute('xml:base', '');
  9781. break;
  9782. }
  9783. }
  9784. $my_dep->appendChild($my_dep_file);
  9785. $resources->appendChild($my_dep);
  9786. $dependency = $xmldoc->createElement('dependency');
  9787. $dependency->setAttribute('identifierref', $res_id);
  9788. $my_resource->appendChild($dependency);
  9789. $i++;
  9790. }
  9791. }
  9792. $resources->appendChild($my_resource);
  9793. $zip_files[] = $my_file_path;
  9794. } else {
  9795. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9796. switch ($item->type) {
  9797. case TOOL_LINK:
  9798. $my_item = $xmldoc->createElement('item');
  9799. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9800. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9801. $my_item->setAttribute('isvisible', 'true');
  9802. // Give a child element <title> to the <item> element.
  9803. $my_title = $xmldoc->createElement(
  9804. 'title',
  9805. htmlspecialchars(
  9806. api_utf8_encode($item->get_title()),
  9807. ENT_QUOTES,
  9808. 'UTF-8'
  9809. )
  9810. );
  9811. $my_item->appendChild($my_title);
  9812. // Give a child element <adlcp:prerequisites> to the <item> element.
  9813. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9814. $my_prereqs->setAttribute('type', 'aicc_script');
  9815. $my_item->appendChild($my_prereqs);
  9816. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9817. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9818. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9819. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9820. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9821. //$xmldoc->createElement('adlcp:datafromlms', '');
  9822. // Give a child element <adlcp:masteryscore> to the <item> element.
  9823. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9824. $my_item->appendChild($my_masteryscore);
  9825. // Attach this item to the organization element or its parent if there is one.
  9826. if (!empty($item->parent) && $item->parent != 0) {
  9827. $children = $organization->childNodes;
  9828. for ($i = 0; $i < $children->length; $i++) {
  9829. $item_temp = $children->item($i);
  9830. if ($item_temp->nodeName == 'item') {
  9831. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9832. $item_temp->appendChild($my_item);
  9833. }
  9834. }
  9835. }
  9836. } else {
  9837. $organization->appendChild($my_item);
  9838. }
  9839. $my_file_path = 'link_'.$item->get_id().'.html';
  9840. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9841. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  9842. $rs = Database::query($sql);
  9843. if ($link = Database::fetch_array($rs)) {
  9844. $url = $link['url'];
  9845. $title = stripslashes($link['title']);
  9846. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9847. $my_xml_file_path = $my_file_path;
  9848. $my_sub_dir = dirname($my_file_path);
  9849. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9850. $my_xml_sub_dir = $my_sub_dir;
  9851. // Give a <resource> child to the <resources> element.
  9852. $my_resource = $xmldoc->createElement('resource');
  9853. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9854. $my_resource->setAttribute('type', 'webcontent');
  9855. $my_resource->setAttribute('href', $my_xml_file_path);
  9856. // adlcp:scormtype can be either 'sco' or 'asset'.
  9857. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9858. // xml:base is the base directory to find the files declared in this resource.
  9859. $my_resource->setAttribute('xml:base', '');
  9860. // give a <file> child to the <resource> element.
  9861. $my_file = $xmldoc->createElement('file');
  9862. $my_file->setAttribute('href', $my_xml_file_path);
  9863. $my_resource->appendChild($my_file);
  9864. $resources->appendChild($my_resource);
  9865. }
  9866. break;
  9867. case TOOL_QUIZ:
  9868. $exe_id = $item->path;
  9869. // Should be using ref when everything will be cleaned up in this regard.
  9870. $exe = new Exercise();
  9871. $exe->read($exe_id);
  9872. $my_item = $xmldoc->createElement('item');
  9873. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9874. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9875. $my_item->setAttribute('isvisible', 'true');
  9876. // Give a child element <title> to the <item> element.
  9877. $my_title = $xmldoc->createElement(
  9878. 'title',
  9879. htmlspecialchars(
  9880. api_utf8_encode($item->get_title()),
  9881. ENT_QUOTES,
  9882. 'UTF-8'
  9883. )
  9884. );
  9885. $my_item->appendChild($my_title);
  9886. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  9887. $my_item->appendChild($my_max_score);
  9888. // Give a child element <adlcp:prerequisites> to the <item> element.
  9889. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9890. $my_prereqs->setAttribute('type', 'aicc_script');
  9891. $my_item->appendChild($my_prereqs);
  9892. // Give a child element <adlcp:masteryscore> to the <item> element.
  9893. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9894. $my_item->appendChild($my_masteryscore);
  9895. // Attach this item to the organization element or hits parent if there is one.
  9896. if (!empty($item->parent) && $item->parent != 0) {
  9897. $children = $organization->childNodes;
  9898. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9899. if ($possible_parent) {
  9900. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  9901. $possible_parent->appendChild($my_item);
  9902. }
  9903. }
  9904. } else {
  9905. $organization->appendChild($my_item);
  9906. }
  9907. // Get the path of the file(s) from the course directory root
  9908. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9909. $my_file_path = 'quiz_'.$item->get_id().'.html';
  9910. // Write the contents of the exported exercise into a (big) html file
  9911. // to later pack it into the exported SCORM. The file will be removed afterwards.
  9912. $scormExercise = new ScormExercise($exe, true);
  9913. $contents = $scormExercise->export();
  9914. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  9915. $res = file_put_contents($tmp_file_path, $contents);
  9916. if ($res === false) {
  9917. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  9918. }
  9919. $files_cleanup[] = $tmp_file_path;
  9920. $my_xml_file_path = $my_file_path;
  9921. $my_sub_dir = dirname($my_file_path);
  9922. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9923. $my_xml_sub_dir = $my_sub_dir;
  9924. // Give a <resource> child to the <resources> element.
  9925. $my_resource = $xmldoc->createElement('resource');
  9926. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9927. $my_resource->setAttribute('type', 'webcontent');
  9928. $my_resource->setAttribute('href', $my_xml_file_path);
  9929. // adlcp:scormtype can be either 'sco' or 'asset'.
  9930. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9931. // xml:base is the base directory to find the files declared in this resource.
  9932. $my_resource->setAttribute('xml:base', '');
  9933. // Give a <file> child to the <resource> element.
  9934. $my_file = $xmldoc->createElement('file');
  9935. $my_file->setAttribute('href', $my_xml_file_path);
  9936. $my_resource->appendChild($my_file);
  9937. // Get included docs.
  9938. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  9939. // Dependency to other files - not yet supported.
  9940. $i = 1;
  9941. foreach ($inc_docs as $doc_info) {
  9942. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9943. continue;
  9944. }
  9945. $my_dep = $xmldoc->createElement('resource');
  9946. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9947. $my_dep->setAttribute('identifier', $res_id);
  9948. $my_dep->setAttribute('type', 'webcontent');
  9949. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9950. $my_dep_file = $xmldoc->createElement('file');
  9951. // Check type of URL.
  9952. if ($doc_info[1] == 'remote') {
  9953. // Remote file. Save url as is.
  9954. $my_dep_file->setAttribute('href', $doc_info[0]);
  9955. $my_dep->setAttribute('xml:base', '');
  9956. } elseif ($doc_info[1] == 'local') {
  9957. switch ($doc_info[2]) {
  9958. case 'url': // Local URL - save path as url for now, don't zip file.
  9959. // Save file but as local file (retrieve from URL).
  9960. $abs_path = api_get_path(SYS_PATH).
  9961. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9962. $current_dir = dirname($abs_path);
  9963. $current_dir = str_replace('\\', '/', $current_dir);
  9964. $file_path = realpath($abs_path);
  9965. $file_path = str_replace('\\', '/', $file_path);
  9966. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9967. $my_dep->setAttribute('xml:base', '');
  9968. if (strstr($file_path, $main_path) !== false) {
  9969. // The calculated real path is really inside the chamilo root path.
  9970. // Reduce file path to what's under the DocumentRoot.
  9971. $file_path = substr($file_path, strlen($root_path));
  9972. $zip_files_abs[] = $file_path;
  9973. $link_updates[$my_file_path][] = [
  9974. 'orig' => $doc_info[0],
  9975. 'dest' => 'document/'.$file_path,
  9976. ];
  9977. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9978. $my_dep->setAttribute('xml:base', '');
  9979. } elseif (empty($file_path)) {
  9980. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9981. $file_path = str_replace('//', '/', $file_path);
  9982. if (file_exists($file_path)) {
  9983. $file_path = substr($file_path, strlen($current_dir));
  9984. // We get the relative path.
  9985. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9986. $link_updates[$my_file_path][] = [
  9987. 'orig' => $doc_info[0],
  9988. 'dest' => 'document/'.$file_path,
  9989. ];
  9990. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9991. $my_dep->setAttribute('xml:base', '');
  9992. }
  9993. }
  9994. break;
  9995. case 'abs':
  9996. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9997. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9998. $current_dir = str_replace('\\', '/', $current_dir);
  9999. $file_path = realpath($doc_info[0]);
  10000. $file_path = str_replace('\\', '/', $file_path);
  10001. $my_dep_file->setAttribute('href', $file_path);
  10002. $my_dep->setAttribute('xml:base', '');
  10003. if (strstr($file_path, $main_path) !== false) {
  10004. // The calculated real path is really inside the chamilo root path.
  10005. // Reduce file path to what's under the DocumentRoot.
  10006. $file_path = substr($file_path, strlen($root_path));
  10007. $zip_files_abs[] = $file_path;
  10008. $link_updates[$my_file_path][] = [
  10009. 'orig' => $doc_info[0],
  10010. 'dest' => $file_path,
  10011. ];
  10012. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10013. $my_dep->setAttribute('xml:base', '');
  10014. } elseif (empty($file_path)) {
  10015. $docSysPartPath = str_replace(
  10016. api_get_path(REL_COURSE_PATH),
  10017. '',
  10018. $doc_info[0]
  10019. );
  10020. $docSysPartPathNoCourseCode = str_replace(
  10021. $_course['directory'].'/',
  10022. '',
  10023. $docSysPartPath
  10024. );
  10025. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10026. if (file_exists($docSysPath)) {
  10027. $file_path = $docSysPartPathNoCourseCode;
  10028. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10029. $link_updates[$my_file_path][] = [
  10030. 'orig' => $doc_info[0],
  10031. 'dest' => $file_path,
  10032. ];
  10033. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10034. $my_dep->setAttribute('xml:base', '');
  10035. }
  10036. }
  10037. break;
  10038. case 'rel':
  10039. // Path relative to the current document. Save xml:base as current document's
  10040. // directory and save file in zip as subdir.file_path
  10041. if (substr($doc_info[0], 0, 2) === '..') {
  10042. // Relative path going up.
  10043. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10044. $current_dir = str_replace('\\', '/', $current_dir);
  10045. $file_path = realpath($current_dir.$doc_info[0]);
  10046. $file_path = str_replace('\\', '/', $file_path);
  10047. if (strstr($file_path, $main_path) !== false) {
  10048. // The calculated real path is really inside Chamilo's root path.
  10049. // Reduce file path to what's under the DocumentRoot.
  10050. $file_path = substr($file_path, strlen($root_path));
  10051. $file_path_dest = $file_path;
  10052. // File path is courses/CHAMILO/document/....
  10053. $info_file_path = explode('/', $file_path);
  10054. if ($info_file_path[0] == 'courses') {
  10055. // Add character "/" in file path.
  10056. $file_path_dest = 'document/'.$file_path;
  10057. }
  10058. $zip_files_abs[] = $file_path;
  10059. $link_updates[$my_file_path][] = [
  10060. 'orig' => $doc_info[0],
  10061. 'dest' => $file_path_dest,
  10062. ];
  10063. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10064. $my_dep->setAttribute('xml:base', '');
  10065. }
  10066. } else {
  10067. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10068. $my_dep_file->setAttribute('href', $doc_info[0]);
  10069. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10070. }
  10071. break;
  10072. default:
  10073. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10074. $my_dep->setAttribute('xml:base', '');
  10075. break;
  10076. }
  10077. }
  10078. $my_dep->appendChild($my_dep_file);
  10079. $resources->appendChild($my_dep);
  10080. $dependency = $xmldoc->createElement('dependency');
  10081. $dependency->setAttribute('identifierref', $res_id);
  10082. $my_resource->appendChild($dependency);
  10083. $i++;
  10084. }
  10085. $resources->appendChild($my_resource);
  10086. $zip_files[] = $my_file_path;
  10087. break;
  10088. default:
  10089. // Get the path of the file(s) from the course directory root
  10090. $my_file_path = 'non_exportable.html';
  10091. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10092. $my_xml_file_path = $my_file_path;
  10093. $my_sub_dir = dirname($my_file_path);
  10094. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10095. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10096. $my_xml_sub_dir = $my_sub_dir;
  10097. // Give a <resource> child to the <resources> element.
  10098. $my_resource = $xmldoc->createElement('resource');
  10099. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10100. $my_resource->setAttribute('type', 'webcontent');
  10101. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10102. // adlcp:scormtype can be either 'sco' or 'asset'.
  10103. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10104. // xml:base is the base directory to find the files declared in this resource.
  10105. $my_resource->setAttribute('xml:base', '');
  10106. // Give a <file> child to the <resource> element.
  10107. $my_file = $xmldoc->createElement('file');
  10108. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10109. $my_resource->appendChild($my_file);
  10110. $resources->appendChild($my_resource);
  10111. break;
  10112. }
  10113. }
  10114. }
  10115. $organizations->appendChild($organization);
  10116. $root->appendChild($organizations);
  10117. $root->appendChild($resources);
  10118. $xmldoc->appendChild($root);
  10119. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10120. // then add the file to the zip, then destroy the file (this is done automatically).
  10121. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10122. foreach ($zip_files as $file_path) {
  10123. if (empty($file_path)) {
  10124. continue;
  10125. }
  10126. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10127. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10128. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10129. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10130. }
  10131. $this->create_path($dest_file);
  10132. @copy($filePath, $dest_file);
  10133. // Check if the file needs a link update.
  10134. if (in_array($file_path, array_keys($link_updates))) {
  10135. $string = file_get_contents($dest_file);
  10136. unlink($dest_file);
  10137. foreach ($link_updates[$file_path] as $old_new) {
  10138. // This is an ugly hack that allows .flv files to be found by the flv player that
  10139. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10140. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10141. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10142. if (substr($old_new['dest'], -3) === 'flv' &&
  10143. substr($old_new['dest'], 0, 5) === 'main/'
  10144. ) {
  10145. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10146. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10147. substr($old_new['dest'], 0, 6) === 'video/'
  10148. ) {
  10149. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10150. }
  10151. // Fix to avoid problems with default_course_document
  10152. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10153. $newDestination = $old_new['dest'];
  10154. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10155. $newDestination = $old_new['replace'];
  10156. }
  10157. } else {
  10158. $newDestination = str_replace('document/', '', $old_new['dest']);
  10159. }
  10160. $string = str_replace($old_new['orig'], $newDestination, $string);
  10161. // Add files inside the HTMLs
  10162. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10163. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10164. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10165. copy(
  10166. $sys_course_path.$new_path,
  10167. $destinationFile
  10168. );
  10169. }
  10170. }
  10171. file_put_contents($dest_file, $string);
  10172. }
  10173. if (file_exists($filePath) && $copyAll) {
  10174. $extension = $this->get_extension($filePath);
  10175. if (in_array($extension, ['html', 'html'])) {
  10176. $containerOrigin = dirname($filePath);
  10177. $containerDestination = dirname($dest_file);
  10178. $finder = new Finder();
  10179. $finder->files()->in($containerOrigin)
  10180. ->notName('*_DELETED_*')
  10181. ->exclude('share_folder')
  10182. ->exclude('chat_files')
  10183. ->exclude('certificates')
  10184. ;
  10185. if (is_dir($containerOrigin) &&
  10186. is_dir($containerDestination)
  10187. ) {
  10188. $fs = new Filesystem();
  10189. $fs->mirror(
  10190. $containerOrigin,
  10191. $containerDestination,
  10192. $finder
  10193. );
  10194. }
  10195. }
  10196. }
  10197. }
  10198. foreach ($zip_files_abs as $file_path) {
  10199. if (empty($file_path)) {
  10200. continue;
  10201. }
  10202. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10203. continue;
  10204. }
  10205. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10206. if (strstr($file_path, 'upload/users') !== false) {
  10207. $pos = strpos($file_path, 'my_files/');
  10208. if ($pos !== false) {
  10209. $onlyDirectory = str_replace(
  10210. 'upload/users/',
  10211. '',
  10212. substr($file_path, $pos, strlen($file_path))
  10213. );
  10214. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10215. }
  10216. }
  10217. if (strstr($file_path, 'default_course_document/') !== false) {
  10218. $replace = str_replace('/main', '', $file_path);
  10219. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10220. }
  10221. if (empty($dest_file)) {
  10222. continue;
  10223. }
  10224. $this->create_path($dest_file);
  10225. copy($main_path.$file_path, $dest_file);
  10226. // Check if the file needs a link update.
  10227. if (in_array($file_path, array_keys($link_updates))) {
  10228. $string = file_get_contents($dest_file);
  10229. unlink($dest_file);
  10230. foreach ($link_updates[$file_path] as $old_new) {
  10231. // This is an ugly hack that allows .flv files to be found by the flv player that
  10232. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10233. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10234. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10235. if (substr($old_new['dest'], -3) == 'flv' &&
  10236. substr($old_new['dest'], 0, 5) == 'main/'
  10237. ) {
  10238. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10239. }
  10240. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10241. }
  10242. file_put_contents($dest_file, $string);
  10243. }
  10244. }
  10245. if (is_array($links_to_create)) {
  10246. foreach ($links_to_create as $file => $link) {
  10247. $content = '<!DOCTYPE html><head>
  10248. <meta charset="'.api_get_language_isocode().'" />
  10249. <title>'.$link['title'].'</title>
  10250. </head>
  10251. <body dir="'.api_get_text_direction().'">
  10252. <div style="text-align:center">
  10253. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10254. </body>
  10255. </html>';
  10256. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10257. }
  10258. }
  10259. // Add non exportable message explanation.
  10260. $lang_not_exportable = get_lang('This learning object or activity is not SCORM compliant. That\'s why it is not exportable.');
  10261. $file_content = '<!DOCTYPE html><head>
  10262. <meta charset="'.api_get_language_isocode().'" />
  10263. <title>'.$lang_not_exportable.'</title>
  10264. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10265. </head>
  10266. <body dir="'.api_get_text_direction().'">';
  10267. $file_content .=
  10268. <<<EOD
  10269. <style>
  10270. .error-message {
  10271. font-family: arial, verdana, helvetica, sans-serif;
  10272. border-width: 1px;
  10273. border-style: solid;
  10274. left: 50%;
  10275. margin: 10px auto;
  10276. min-height: 30px;
  10277. padding: 5px;
  10278. right: 50%;
  10279. width: 500px;
  10280. background-color: #FFD1D1;
  10281. border-color: #FF0000;
  10282. color: #000;
  10283. }
  10284. </style>
  10285. <body>
  10286. <div class="error-message">
  10287. $lang_not_exportable
  10288. </div>
  10289. </body>
  10290. </html>
  10291. EOD;
  10292. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10293. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10294. }
  10295. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10296. // Add the extra files that go along with a SCORM package.
  10297. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10298. $fs = new Filesystem();
  10299. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10300. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10301. $manifest = @$xmldoc->saveXML();
  10302. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10303. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10304. $zip_folder->add(
  10305. $archivePath.'/'.$temp_dir_short,
  10306. PCLZIP_OPT_REMOVE_PATH,
  10307. $archivePath.'/'.$temp_dir_short.'/'
  10308. );
  10309. // Clean possible temporary files.
  10310. foreach ($files_cleanup as $file) {
  10311. $res = unlink($file);
  10312. if ($res === false) {
  10313. error_log(
  10314. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10315. 0
  10316. );
  10317. }
  10318. }
  10319. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10320. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10321. }
  10322. /**
  10323. * @param int $lp_id
  10324. *
  10325. * @return bool
  10326. */
  10327. public function scorm_export_to_pdf($lp_id)
  10328. {
  10329. $lp_id = (int) $lp_id;
  10330. $files_to_export = [];
  10331. $sessionId = api_get_session_id();
  10332. $course_data = api_get_course_info($this->cc);
  10333. if (!empty($course_data)) {
  10334. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10335. $list = self::get_flat_ordered_items_list($lp_id);
  10336. if (!empty($list)) {
  10337. foreach ($list as $item_id) {
  10338. $item = $this->items[$item_id];
  10339. switch ($item->type) {
  10340. case 'document':
  10341. // Getting documents from a LP with chamilo documents
  10342. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10343. // Try loading document from the base course.
  10344. if (empty($file_data) && !empty($sessionId)) {
  10345. $file_data = DocumentManager::get_document_data_by_id(
  10346. $item->path,
  10347. $this->cc,
  10348. false,
  10349. 0
  10350. );
  10351. }
  10352. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10353. if (file_exists($file_path)) {
  10354. $files_to_export[] = [
  10355. 'title' => $item->get_title(),
  10356. 'path' => $file_path,
  10357. ];
  10358. }
  10359. break;
  10360. case 'asset': //commes from a scorm package generated by chamilo
  10361. case 'sco':
  10362. $file_path = $scorm_path.'/'.$item->path;
  10363. if (file_exists($file_path)) {
  10364. $files_to_export[] = [
  10365. 'title' => $item->get_title(),
  10366. 'path' => $file_path,
  10367. ];
  10368. }
  10369. break;
  10370. case 'dir':
  10371. $files_to_export[] = [
  10372. 'title' => $item->get_title(),
  10373. 'path' => null,
  10374. ];
  10375. break;
  10376. }
  10377. }
  10378. }
  10379. $pdf = new PDF();
  10380. $result = $pdf->html_to_pdf(
  10381. $files_to_export,
  10382. $this->name,
  10383. $this->cc,
  10384. true,
  10385. true,
  10386. true,
  10387. $this->get_name()
  10388. );
  10389. return $result;
  10390. }
  10391. return false;
  10392. }
  10393. /**
  10394. * Temp function to be moved in main_api or the best place around for this.
  10395. * Creates a file path if it doesn't exist.
  10396. *
  10397. * @param string $path
  10398. */
  10399. public function create_path($path)
  10400. {
  10401. $path_bits = explode('/', dirname($path));
  10402. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10403. $path_built = IS_WINDOWS_OS ? '' : '/';
  10404. foreach ($path_bits as $bit) {
  10405. if (!empty($bit)) {
  10406. $new_path = $path_built.$bit;
  10407. if (is_dir($new_path)) {
  10408. $path_built = $new_path.'/';
  10409. } else {
  10410. mkdir($new_path, api_get_permissions_for_new_directories());
  10411. $path_built = $new_path.'/';
  10412. }
  10413. }
  10414. }
  10415. }
  10416. /**
  10417. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10418. *
  10419. * @return bool The results of the unlink function, or false if there was no image to start with
  10420. */
  10421. public function delete_lp_image()
  10422. {
  10423. $img = $this->get_preview_image();
  10424. if ($img != '') {
  10425. $del_file = $this->get_preview_image_path(null, 'sys');
  10426. if (isset($del_file) && file_exists($del_file)) {
  10427. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10428. if (file_exists($del_file_2)) {
  10429. unlink($del_file_2);
  10430. }
  10431. $this->set_preview_image('');
  10432. return @unlink($del_file);
  10433. }
  10434. }
  10435. return false;
  10436. }
  10437. /**
  10438. * Uploads an author image to the upload/learning_path/images directory.
  10439. *
  10440. * @param array The image array, coming from the $_FILES superglobal
  10441. *
  10442. * @return bool True on success, false on error
  10443. */
  10444. public function upload_image($image_array)
  10445. {
  10446. if (!empty($image_array['name'])) {
  10447. $upload_ok = process_uploaded_file($image_array);
  10448. $has_attachment = true;
  10449. }
  10450. if ($upload_ok && $has_attachment) {
  10451. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10452. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10453. $updir = $sys_course_path.$courseDir;
  10454. // Try to add an extension to the file if it hasn't one.
  10455. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10456. if (filter_extension($new_file_name)) {
  10457. $file_extension = explode('.', $image_array['name']);
  10458. $file_extension = strtolower($file_extension[count($file_extension) - 1]);
  10459. $filename = uniqid('');
  10460. $new_file_name = $filename.'.'.$file_extension;
  10461. $new_path = $updir.'/'.$new_file_name;
  10462. // Resize the image.
  10463. $temp = new Image($image_array['tmp_name']);
  10464. $temp->resize(104);
  10465. $result = $temp->send_image($new_path);
  10466. // Storing the image filename.
  10467. if ($result) {
  10468. $this->set_preview_image($new_file_name);
  10469. //Resize to 64px to use on course homepage
  10470. $temp->resize(64);
  10471. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10472. return true;
  10473. }
  10474. }
  10475. }
  10476. return false;
  10477. }
  10478. /**
  10479. * @param int $lp_id
  10480. * @param string $status
  10481. */
  10482. public function set_autolaunch($lp_id, $status)
  10483. {
  10484. $course_id = api_get_course_int_id();
  10485. $lp_id = (int) $lp_id;
  10486. $status = (int) $status;
  10487. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10488. // Setting everything to autolaunch = 0
  10489. $attributes['autolaunch'] = 0;
  10490. $where = [
  10491. 'session_id = ? AND c_id = ? ' => [
  10492. api_get_session_id(),
  10493. $course_id,
  10494. ],
  10495. ];
  10496. Database::update($lp_table, $attributes, $where);
  10497. if ($status == 1) {
  10498. //Setting my lp_id to autolaunch = 1
  10499. $attributes['autolaunch'] = 1;
  10500. $where = [
  10501. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10502. $lp_id,
  10503. api_get_session_id(),
  10504. $course_id,
  10505. ],
  10506. ];
  10507. Database::update($lp_table, $attributes, $where);
  10508. }
  10509. }
  10510. /**
  10511. * Gets previous_item_id for the next element of the lp_item table.
  10512. *
  10513. * @author Isaac flores paz
  10514. *
  10515. * @return int Previous item ID
  10516. */
  10517. public function select_previous_item_id()
  10518. {
  10519. $course_id = api_get_course_int_id();
  10520. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10521. // Get the max order of the items
  10522. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10523. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10524. $rs_max_order = Database::query($sql);
  10525. $row_max_order = Database::fetch_object($rs_max_order);
  10526. $max_order = $row_max_order->display_order;
  10527. // Get the previous item ID
  10528. $sql = "SELECT iid as previous FROM $table_lp_item
  10529. WHERE
  10530. c_id = $course_id AND
  10531. lp_id = ".$this->lp_id." AND
  10532. display_order = '$max_order' ";
  10533. $rs_max = Database::query($sql);
  10534. $row_max = Database::fetch_object($rs_max);
  10535. // Return the previous item ID
  10536. return $row_max->previous;
  10537. }
  10538. /**
  10539. * Copies an LP.
  10540. */
  10541. public function copy()
  10542. {
  10543. // Course builder
  10544. $cb = new CourseBuilder();
  10545. //Setting tools that will be copied
  10546. $cb->set_tools_to_build(['learnpaths']);
  10547. //Setting elements that will be copied
  10548. $cb->set_tools_specific_id_list(
  10549. ['learnpaths' => [$this->lp_id]]
  10550. );
  10551. $course = $cb->build();
  10552. //Course restorer
  10553. $course_restorer = new CourseRestorer($course);
  10554. $course_restorer->set_add_text_in_items(true);
  10555. $course_restorer->set_tool_copy_settings(
  10556. ['learnpaths' => ['reset_dates' => true]]
  10557. );
  10558. $course_restorer->restore(
  10559. api_get_course_id(),
  10560. api_get_session_id(),
  10561. false,
  10562. false
  10563. );
  10564. }
  10565. /**
  10566. * Verify document size.
  10567. *
  10568. * @param string $s
  10569. *
  10570. * @return bool
  10571. */
  10572. public static function verify_document_size($s)
  10573. {
  10574. $post_max = ini_get('post_max_size');
  10575. if (substr($post_max, -1, 1) == 'M') {
  10576. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10577. } elseif (substr($post_max, -1, 1) == 'G') {
  10578. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10579. }
  10580. $upl_max = ini_get('upload_max_filesize');
  10581. if (substr($upl_max, -1, 1) == 'M') {
  10582. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10583. } elseif (substr($upl_max, -1, 1) == 'G') {
  10584. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10585. }
  10586. $repo = Container::getDocumentRepository();
  10587. $documents_total_space = $repo->getTotalSpace(api_get_course_int_id());
  10588. $course_max_space = DocumentManager::get_course_quota();
  10589. $total_size = filesize($s) + $documents_total_space;
  10590. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10591. return true;
  10592. }
  10593. return false;
  10594. }
  10595. /**
  10596. * Clear LP prerequisites.
  10597. */
  10598. public function clear_prerequisites()
  10599. {
  10600. $course_id = $this->get_course_int_id();
  10601. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10602. $lp_id = $this->get_id();
  10603. // Cleaning prerequisites
  10604. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10605. WHERE c_id = $course_id AND lp_id = $lp_id";
  10606. Database::query($sql);
  10607. // Cleaning mastery score for exercises
  10608. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10609. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10610. Database::query($sql);
  10611. }
  10612. public function set_previous_step_as_prerequisite_for_all_items()
  10613. {
  10614. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10615. $course_id = $this->get_course_int_id();
  10616. $lp_id = $this->get_id();
  10617. if (!empty($this->items)) {
  10618. $previous_item_id = null;
  10619. $previous_item_max = 0;
  10620. $previous_item_type = null;
  10621. $last_item_not_dir = null;
  10622. $last_item_not_dir_type = null;
  10623. $last_item_not_dir_max = null;
  10624. foreach ($this->ordered_items as $itemId) {
  10625. $item = $this->getItem($itemId);
  10626. // if there was a previous item... (otherwise jump to set it)
  10627. if (!empty($previous_item_id)) {
  10628. $current_item_id = $item->get_id(); //save current id
  10629. if ($item->get_type() != 'dir') {
  10630. // Current item is not a folder, so it qualifies to get a prerequisites
  10631. if ($last_item_not_dir_type == 'quiz') {
  10632. // if previous is quiz, mark its max score as default score to be achieved
  10633. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10634. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10635. Database::query($sql);
  10636. }
  10637. // now simply update the prerequisite to set it to the last non-chapter item
  10638. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10639. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10640. Database::query($sql);
  10641. // record item as 'non-chapter' reference
  10642. $last_item_not_dir = $item->get_id();
  10643. $last_item_not_dir_type = $item->get_type();
  10644. $last_item_not_dir_max = $item->get_max();
  10645. }
  10646. } else {
  10647. if ($item->get_type() != 'dir') {
  10648. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10649. $last_item_not_dir = $item->get_id();
  10650. $last_item_not_dir_type = $item->get_type();
  10651. $last_item_not_dir_max = $item->get_max();
  10652. }
  10653. }
  10654. // Saving the item as "previous item" for the next loop
  10655. $previous_item_id = $item->get_id();
  10656. $previous_item_max = $item->get_max();
  10657. $previous_item_type = $item->get_type();
  10658. }
  10659. }
  10660. }
  10661. /**
  10662. * @param array $params
  10663. *
  10664. * @throws \Doctrine\ORM\OptimisticLockException
  10665. *
  10666. * @return int
  10667. */
  10668. public static function createCategory($params)
  10669. {
  10670. $em = Database::getManager();
  10671. $item = new CLpCategory();
  10672. $item->setName($params['name']);
  10673. $item->setCId($params['c_id']);
  10674. $em->persist($item);
  10675. $em->flush();
  10676. api_item_property_update(
  10677. api_get_course_info(),
  10678. TOOL_LEARNPATH_CATEGORY,
  10679. $item->getId(),
  10680. 'visible',
  10681. api_get_user_id()
  10682. );
  10683. return $item->getId();
  10684. }
  10685. /**
  10686. * @param array $params
  10687. *
  10688. * @throws \Doctrine\ORM\ORMException
  10689. * @throws \Doctrine\ORM\OptimisticLockException
  10690. * @throws \Doctrine\ORM\TransactionRequiredException
  10691. */
  10692. public static function updateCategory($params)
  10693. {
  10694. $em = Database::getManager();
  10695. /** @var CLpCategory $item */
  10696. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10697. if ($item) {
  10698. $item->setName($params['name']);
  10699. $em->merge($item);
  10700. $em->flush();
  10701. }
  10702. }
  10703. /**
  10704. * @param int $id
  10705. *
  10706. * @throws \Doctrine\ORM\ORMException
  10707. * @throws \Doctrine\ORM\OptimisticLockException
  10708. * @throws \Doctrine\ORM\TransactionRequiredException
  10709. */
  10710. public static function moveUpCategory($id)
  10711. {
  10712. $id = (int) $id;
  10713. $em = Database::getManager();
  10714. /** @var CLpCategory $item */
  10715. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10716. if ($item) {
  10717. $position = $item->getPosition() - 1;
  10718. $item->setPosition($position);
  10719. $em->persist($item);
  10720. $em->flush();
  10721. }
  10722. }
  10723. /**
  10724. * @param int $id
  10725. *
  10726. * @throws \Doctrine\ORM\ORMException
  10727. * @throws \Doctrine\ORM\OptimisticLockException
  10728. * @throws \Doctrine\ORM\TransactionRequiredException
  10729. */
  10730. public static function moveDownCategory($id)
  10731. {
  10732. $id = (int) $id;
  10733. $em = Database::getManager();
  10734. /** @var CLpCategory $item */
  10735. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10736. if ($item) {
  10737. $position = $item->getPosition() + 1;
  10738. $item->setPosition($position);
  10739. $em->persist($item);
  10740. $em->flush();
  10741. }
  10742. }
  10743. /**
  10744. * @param int $courseId
  10745. *
  10746. * @throws \Doctrine\ORM\Query\QueryException
  10747. *
  10748. * @return int|mixed
  10749. */
  10750. public static function getCountCategories($courseId)
  10751. {
  10752. if (empty($courseId)) {
  10753. return 0;
  10754. }
  10755. $em = Database::getManager();
  10756. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10757. $query->setParameter('id', $courseId);
  10758. return $query->getSingleScalarResult();
  10759. }
  10760. /**
  10761. * @param int $courseId
  10762. *
  10763. * @return mixed
  10764. */
  10765. public static function getCategories($courseId)
  10766. {
  10767. $em = Database::getManager();
  10768. // Using doctrine extensions
  10769. /** @var SortableRepository $repo */
  10770. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10771. $items = $repo
  10772. ->getBySortableGroupsQuery(['cId' => $courseId])
  10773. ->getResult();
  10774. return $items;
  10775. }
  10776. /**
  10777. * @param int $id
  10778. *
  10779. * @throws \Doctrine\ORM\ORMException
  10780. * @throws \Doctrine\ORM\OptimisticLockException
  10781. * @throws \Doctrine\ORM\TransactionRequiredException
  10782. *
  10783. * @return CLpCategory
  10784. */
  10785. public static function getCategory($id)
  10786. {
  10787. $id = (int) $id;
  10788. $em = Database::getManager();
  10789. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10790. return $item;
  10791. }
  10792. /**
  10793. * @param int $courseId
  10794. *
  10795. * @return array
  10796. */
  10797. public static function getCategoryByCourse($courseId)
  10798. {
  10799. $em = Database::getManager();
  10800. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10801. ['cId' => $courseId]
  10802. );
  10803. return $items;
  10804. }
  10805. /**
  10806. * @param int $id
  10807. *
  10808. * @throws \Doctrine\ORM\ORMException
  10809. * @throws \Doctrine\ORM\OptimisticLockException
  10810. * @throws \Doctrine\ORM\TransactionRequiredException
  10811. *
  10812. * @return mixed
  10813. */
  10814. public static function deleteCategory($id)
  10815. {
  10816. $em = Database::getManager();
  10817. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10818. if ($item) {
  10819. $courseId = $item->getCId();
  10820. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10821. $query->setParameter('id', $courseId);
  10822. $query->setParameter('catId', $item->getId());
  10823. $lps = $query->getResult();
  10824. // Setting category = 0.
  10825. if ($lps) {
  10826. foreach ($lps as $lpItem) {
  10827. $lpItem->setCategoryId(0);
  10828. }
  10829. }
  10830. // Removing category.
  10831. $em->remove($item);
  10832. $em->flush();
  10833. $courseInfo = api_get_course_info_by_id($courseId);
  10834. $sessionId = api_get_session_id();
  10835. // Delete link tool
  10836. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10837. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10838. // Delete tools
  10839. $sql = "DELETE FROM $tbl_tool
  10840. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10841. Database::query($sql);
  10842. return true;
  10843. }
  10844. return false;
  10845. }
  10846. /**
  10847. * @param int $courseId
  10848. * @param bool $addSelectOption
  10849. *
  10850. * @return mixed
  10851. */
  10852. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10853. {
  10854. $items = self::getCategoryByCourse($courseId);
  10855. $cats = [];
  10856. if ($addSelectOption) {
  10857. $cats = [get_lang('Select a category')];
  10858. }
  10859. if (!empty($items)) {
  10860. foreach ($items as $cat) {
  10861. $cats[$cat->getId()] = $cat->getName();
  10862. }
  10863. }
  10864. return $cats;
  10865. }
  10866. /**
  10867. * @param string $courseCode
  10868. * @param int $lpId
  10869. * @param int $user_id
  10870. *
  10871. * @return learnpath
  10872. */
  10873. public static function getLpFromSession($courseCode, $lpId, $user_id)
  10874. {
  10875. $debug = 0;
  10876. $learnPath = null;
  10877. $lpObject = Session::read('lpobject');
  10878. if ($lpObject !== null) {
  10879. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  10880. if ($debug) {
  10881. error_log('getLpFromSession: unserialize');
  10882. error_log('------getLpFromSession------');
  10883. error_log('------unserialize------');
  10884. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  10885. error_log("api_get_sessionid: ".api_get_session_id());
  10886. }
  10887. }
  10888. if (!is_object($learnPath)) {
  10889. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  10890. if ($debug) {
  10891. error_log('------getLpFromSession------');
  10892. error_log('getLpFromSession: create new learnpath');
  10893. error_log("create new LP with $courseCode - $lpId - $user_id");
  10894. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  10895. error_log("api_get_sessionid: ".api_get_session_id());
  10896. }
  10897. }
  10898. return $learnPath;
  10899. }
  10900. /**
  10901. * @param int $itemId
  10902. *
  10903. * @return learnpathItem|false
  10904. */
  10905. public function getItem($itemId)
  10906. {
  10907. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  10908. return $this->items[$itemId];
  10909. }
  10910. return false;
  10911. }
  10912. /**
  10913. * @return int
  10914. */
  10915. public function getCurrentAttempt()
  10916. {
  10917. $attempt = $this->getItem($this->get_current_item_id());
  10918. if ($attempt) {
  10919. $attemptId = $attempt->get_attempt_id();
  10920. return $attemptId;
  10921. }
  10922. return 0;
  10923. }
  10924. /**
  10925. * @return int
  10926. */
  10927. public function getCategoryId()
  10928. {
  10929. return (int) $this->categoryId;
  10930. }
  10931. /**
  10932. * @param int $categoryId
  10933. *
  10934. * @return bool
  10935. */
  10936. public function setCategoryId($categoryId)
  10937. {
  10938. $this->categoryId = (int) $categoryId;
  10939. $table = Database::get_course_table(TABLE_LP_MAIN);
  10940. $lp_id = $this->get_id();
  10941. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  10942. WHERE iid = $lp_id";
  10943. Database::query($sql);
  10944. return true;
  10945. }
  10946. /**
  10947. * Get whether this is a learning path with the possibility to subscribe
  10948. * users or not.
  10949. *
  10950. * @return int
  10951. */
  10952. public function getSubscribeUsers()
  10953. {
  10954. return $this->subscribeUsers;
  10955. }
  10956. /**
  10957. * Set whether this is a learning path with the possibility to subscribe
  10958. * users or not.
  10959. *
  10960. * @param int $value (0 = false, 1 = true)
  10961. *
  10962. * @return bool
  10963. */
  10964. public function setSubscribeUsers($value)
  10965. {
  10966. $this->subscribeUsers = (int) $value;
  10967. $table = Database::get_course_table(TABLE_LP_MAIN);
  10968. $lp_id = $this->get_id();
  10969. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  10970. WHERE iid = $lp_id";
  10971. Database::query($sql);
  10972. return true;
  10973. }
  10974. /**
  10975. * Calculate the count of stars for a user in this LP
  10976. * This calculation is based on the following rules:
  10977. * - the student gets one star when he gets to 50% of the learning path
  10978. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  10979. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  10980. * - the student gets the final star when the score for the *last* test is >= 80%.
  10981. *
  10982. * @param int $sessionId Optional. The session ID
  10983. *
  10984. * @return int The count of stars
  10985. */
  10986. public function getCalculateStars($sessionId = 0)
  10987. {
  10988. $stars = 0;
  10989. $progress = self::getProgress(
  10990. $this->lp_id,
  10991. $this->user_id,
  10992. $this->course_int_id,
  10993. $sessionId
  10994. );
  10995. if ($progress >= 50) {
  10996. $stars++;
  10997. }
  10998. // Calculate stars chapters evaluation
  10999. $exercisesItems = $this->getExercisesItems();
  11000. if (!empty($exercisesItems)) {
  11001. $totalResult = 0;
  11002. foreach ($exercisesItems as $exerciseItem) {
  11003. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11004. $this->user_id,
  11005. $exerciseItem->path,
  11006. $this->course_int_id,
  11007. $sessionId,
  11008. $this->lp_id,
  11009. $exerciseItem->db_id
  11010. );
  11011. $exerciseResultInfo = end($exerciseResultInfo);
  11012. if (!$exerciseResultInfo) {
  11013. continue;
  11014. }
  11015. if (!empty($exerciseResultInfo['max_score'])) {
  11016. $exerciseResult = $exerciseResultInfo['score'] * 100 / $exerciseResultInfo['max_score'];
  11017. } else {
  11018. $exerciseResult = 0;
  11019. }
  11020. $totalResult += $exerciseResult;
  11021. }
  11022. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11023. if ($totalExerciseAverage >= 50) {
  11024. $stars++;
  11025. }
  11026. if ($totalExerciseAverage >= 80) {
  11027. $stars++;
  11028. }
  11029. }
  11030. // Calculate star for final evaluation
  11031. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11032. if (!empty($finalEvaluationItem)) {
  11033. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11034. $this->user_id,
  11035. $finalEvaluationItem->path,
  11036. $this->course_int_id,
  11037. $sessionId,
  11038. $this->lp_id,
  11039. $finalEvaluationItem->db_id
  11040. );
  11041. $evaluationResultInfo = end($evaluationResultInfo);
  11042. if ($evaluationResultInfo) {
  11043. $evaluationResult = $evaluationResultInfo['score'] * 100 / $evaluationResultInfo['max_score'];
  11044. if ($evaluationResult >= 80) {
  11045. $stars++;
  11046. }
  11047. }
  11048. }
  11049. return $stars;
  11050. }
  11051. /**
  11052. * Get the items of exercise type.
  11053. *
  11054. * @return array The items. Otherwise return false
  11055. */
  11056. public function getExercisesItems()
  11057. {
  11058. $exercises = [];
  11059. foreach ($this->items as $item) {
  11060. if ($item->type != 'quiz') {
  11061. continue;
  11062. }
  11063. $exercises[] = $item;
  11064. }
  11065. array_pop($exercises);
  11066. return $exercises;
  11067. }
  11068. /**
  11069. * Get the item of exercise type (evaluation type).
  11070. *
  11071. * @return array The final evaluation. Otherwise return false
  11072. */
  11073. public function getFinalEvaluationItem()
  11074. {
  11075. $exercises = [];
  11076. foreach ($this->items as $item) {
  11077. if ($item->type != 'quiz') {
  11078. continue;
  11079. }
  11080. $exercises[] = $item;
  11081. }
  11082. return array_pop($exercises);
  11083. }
  11084. /**
  11085. * Calculate the total points achieved for the current user in this learning path.
  11086. *
  11087. * @param int $sessionId Optional. The session Id
  11088. *
  11089. * @return int
  11090. */
  11091. public function getCalculateScore($sessionId = 0)
  11092. {
  11093. // Calculate stars chapters evaluation
  11094. $exercisesItems = $this->getExercisesItems();
  11095. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11096. $totalExercisesResult = 0;
  11097. $totalEvaluationResult = 0;
  11098. if ($exercisesItems !== false) {
  11099. foreach ($exercisesItems as $exerciseItem) {
  11100. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11101. $this->user_id,
  11102. $exerciseItem->path,
  11103. $this->course_int_id,
  11104. $sessionId,
  11105. $this->lp_id,
  11106. $exerciseItem->db_id
  11107. );
  11108. $exerciseResultInfo = end($exerciseResultInfo);
  11109. if (!$exerciseResultInfo) {
  11110. continue;
  11111. }
  11112. $totalExercisesResult += $exerciseResultInfo['score'];
  11113. }
  11114. }
  11115. if (!empty($finalEvaluationItem)) {
  11116. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11117. $this->user_id,
  11118. $finalEvaluationItem->path,
  11119. $this->course_int_id,
  11120. $sessionId,
  11121. $this->lp_id,
  11122. $finalEvaluationItem->db_id
  11123. );
  11124. $evaluationResultInfo = end($evaluationResultInfo);
  11125. if ($evaluationResultInfo) {
  11126. $totalEvaluationResult += $evaluationResultInfo['score'];
  11127. }
  11128. }
  11129. return $totalExercisesResult + $totalEvaluationResult;
  11130. }
  11131. /**
  11132. * Check if URL is not allowed to be show in a iframe.
  11133. *
  11134. * @param string $src
  11135. *
  11136. * @return string
  11137. */
  11138. public function fixBlockedLinks($src)
  11139. {
  11140. $urlInfo = parse_url($src);
  11141. $platformProtocol = 'https';
  11142. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11143. $platformProtocol = 'http';
  11144. }
  11145. $protocolFixApplied = false;
  11146. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11147. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11148. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11149. if ($platformProtocol != $scheme) {
  11150. Session::write('x_frame_source', $src);
  11151. $src = 'blank.php?error=x_frames_options';
  11152. $protocolFixApplied = true;
  11153. }
  11154. if ($protocolFixApplied == false) {
  11155. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11156. // Check X-Frame-Options
  11157. $ch = curl_init();
  11158. $options = [
  11159. CURLOPT_URL => $src,
  11160. CURLOPT_RETURNTRANSFER => true,
  11161. CURLOPT_HEADER => true,
  11162. CURLOPT_FOLLOWLOCATION => true,
  11163. CURLOPT_ENCODING => "",
  11164. CURLOPT_AUTOREFERER => true,
  11165. CURLOPT_CONNECTTIMEOUT => 120,
  11166. CURLOPT_TIMEOUT => 120,
  11167. CURLOPT_MAXREDIRS => 10,
  11168. ];
  11169. $proxySettings = api_get_configuration_value('proxy_settings');
  11170. if (!empty($proxySettings) &&
  11171. isset($proxySettings['curl_setopt_array'])
  11172. ) {
  11173. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11174. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11175. }
  11176. curl_setopt_array($ch, $options);
  11177. $response = curl_exec($ch);
  11178. $httpCode = curl_getinfo($ch);
  11179. $headers = substr($response, 0, $httpCode['header_size']);
  11180. $error = false;
  11181. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11182. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11183. ) {
  11184. $error = true;
  11185. }
  11186. if ($error) {
  11187. Session::write('x_frame_source', $src);
  11188. $src = 'blank.php?error=x_frames_options';
  11189. }
  11190. }
  11191. }
  11192. return $src;
  11193. }
  11194. /**
  11195. * Check if this LP has a created forum in the basis course.
  11196. *
  11197. * @return bool
  11198. */
  11199. public function lpHasForum()
  11200. {
  11201. $forumTable = Database::get_course_table(TABLE_FORUM);
  11202. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11203. $fakeFrom = "
  11204. $forumTable f
  11205. INNER JOIN $itemProperty ip
  11206. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11207. ";
  11208. $resultData = Database::select(
  11209. 'COUNT(f.iid) AS qty',
  11210. $fakeFrom,
  11211. [
  11212. 'where' => [
  11213. 'ip.visibility != ? AND ' => 2,
  11214. 'ip.tool = ? AND ' => TOOL_FORUM,
  11215. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11216. 'f.lp_id = ?' => intval($this->lp_id),
  11217. ],
  11218. ],
  11219. 'first'
  11220. );
  11221. return $resultData['qty'] > 0;
  11222. }
  11223. /**
  11224. * Get the forum for this learning path.
  11225. *
  11226. * @param int $sessionId
  11227. *
  11228. * @return bool
  11229. */
  11230. public function getForum($sessionId = 0)
  11231. {
  11232. $forumTable = Database::get_course_table(TABLE_FORUM);
  11233. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11234. $fakeFrom = "$forumTable f
  11235. INNER JOIN $itemProperty ip ";
  11236. if ($this->lp_session_id == 0) {
  11237. $fakeFrom .= "
  11238. ON (
  11239. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11240. f.session_id = ip.session_id OR ip.session_id IS NULL
  11241. )
  11242. )
  11243. ";
  11244. } else {
  11245. $fakeFrom .= "
  11246. ON (
  11247. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11248. )
  11249. ";
  11250. }
  11251. $resultData = Database::select(
  11252. 'f.*',
  11253. $fakeFrom,
  11254. [
  11255. 'where' => [
  11256. 'ip.visibility != ? AND ' => 2,
  11257. 'ip.tool = ? AND ' => TOOL_FORUM,
  11258. 'f.session_id = ? AND ' => $sessionId,
  11259. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11260. 'f.lp_id = ?' => intval($this->lp_id),
  11261. ],
  11262. ],
  11263. 'first'
  11264. );
  11265. if (empty($resultData)) {
  11266. return false;
  11267. }
  11268. return $resultData;
  11269. }
  11270. /**
  11271. * Create a forum for this learning path.
  11272. *
  11273. * @param int $forumCategoryId
  11274. *
  11275. * @return int The forum ID if was created. Otherwise return false
  11276. */
  11277. public function createForum($forumCategoryId)
  11278. {
  11279. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11280. $forumId = store_forum(
  11281. [
  11282. 'lp_id' => $this->lp_id,
  11283. 'forum_title' => $this->name,
  11284. 'forum_comment' => null,
  11285. 'forum_category' => (int) $forumCategoryId,
  11286. 'students_can_edit_group' => ['students_can_edit' => 0],
  11287. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11288. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11289. 'group_forum' => 0,
  11290. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11291. ],
  11292. [],
  11293. true
  11294. );
  11295. return $forumId;
  11296. }
  11297. /**
  11298. * Get the LP Final Item form.
  11299. *
  11300. * @throws Exception
  11301. * @throws HTML_QuickForm_Error
  11302. *
  11303. * @return string
  11304. */
  11305. public function getFinalItemForm()
  11306. {
  11307. $finalItem = $this->getFinalItem();
  11308. $title = '';
  11309. if ($finalItem) {
  11310. $title = $finalItem->get_title();
  11311. $buttonText = get_lang('Save');
  11312. $content = $this->getSavedFinalItem();
  11313. } else {
  11314. $buttonText = get_lang('Add this document to the course');
  11315. $content = $this->getFinalItemTemplate();
  11316. }
  11317. $courseInfo = api_get_course_info();
  11318. $result = $this->generate_lp_folder($courseInfo);
  11319. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11320. $relative_prefix = '../../';
  11321. $editorConfig = [
  11322. 'ToolbarSet' => 'LearningPathDocuments',
  11323. 'Width' => '100%',
  11324. 'Height' => '500',
  11325. 'FullPage' => true,
  11326. 'CreateDocumentDir' => $relative_prefix,
  11327. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11328. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11329. ];
  11330. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11331. 'type' => 'document',
  11332. 'lp_id' => $this->lp_id,
  11333. ]);
  11334. $form = new FormValidator('final_item', 'POST', $url);
  11335. $form->addText('title', get_lang('Title'));
  11336. $form->addButtonSave($buttonText);
  11337. $form->addHtml(
  11338. Display::return_message(
  11339. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11340. 'normal',
  11341. false
  11342. )
  11343. );
  11344. $renderer = $form->defaultRenderer();
  11345. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11346. $form->addHtmlEditor(
  11347. 'content_lp_certificate',
  11348. null,
  11349. true,
  11350. false,
  11351. $editorConfig,
  11352. true
  11353. );
  11354. $form->addHidden('action', 'add_final_item');
  11355. $form->addHidden('path', Session::read('pathItem'));
  11356. $form->addHidden('previous', $this->get_last());
  11357. $form->setDefaults(
  11358. ['title' => $title, 'content_lp_certificate' => $content]
  11359. );
  11360. if ($form->validate()) {
  11361. $values = $form->exportValues();
  11362. $lastItemId = $this->getLastInFirstLevel();
  11363. if (!$finalItem) {
  11364. $documentId = $this->create_document(
  11365. $this->course_info,
  11366. $values['content_lp_certificate'],
  11367. $values['title']
  11368. );
  11369. $this->add_item(
  11370. 0,
  11371. $lastItemId,
  11372. 'final_item',
  11373. $documentId,
  11374. $values['title'],
  11375. ''
  11376. );
  11377. Display::addFlash(
  11378. Display::return_message(get_lang('Added'))
  11379. );
  11380. } else {
  11381. $this->edit_document($this->course_info);
  11382. }
  11383. }
  11384. return $form->returnForm();
  11385. }
  11386. /**
  11387. * Check if the current lp item is first, both, last or none from lp list.
  11388. *
  11389. * @param int $currentItemId
  11390. *
  11391. * @return string
  11392. */
  11393. public function isFirstOrLastItem($currentItemId)
  11394. {
  11395. $lpItemId = [];
  11396. $typeListNotToVerify = self::getChapterTypes();
  11397. // Using get_toc() function instead $this->items because returns the correct order of the items
  11398. foreach ($this->get_toc() as $item) {
  11399. if (!in_array($item['type'], $typeListNotToVerify)) {
  11400. $lpItemId[] = $item['id'];
  11401. }
  11402. }
  11403. $lastLpItemIndex = count($lpItemId) - 1;
  11404. $position = array_search($currentItemId, $lpItemId);
  11405. switch ($position) {
  11406. case 0:
  11407. if (!$lastLpItemIndex) {
  11408. $answer = 'both';
  11409. break;
  11410. }
  11411. $answer = 'first';
  11412. break;
  11413. case $lastLpItemIndex:
  11414. $answer = 'last';
  11415. break;
  11416. default:
  11417. $answer = 'none';
  11418. }
  11419. return $answer;
  11420. }
  11421. /**
  11422. * Get whether this is a learning path with the accumulated SCORM time or not.
  11423. *
  11424. * @return int
  11425. */
  11426. public function getAccumulateScormTime()
  11427. {
  11428. return $this->accumulateScormTime;
  11429. }
  11430. /**
  11431. * Set whether this is a learning path with the accumulated SCORM time or not.
  11432. *
  11433. * @param int $value (0 = false, 1 = true)
  11434. *
  11435. * @return bool Always returns true
  11436. */
  11437. public function setAccumulateScormTime($value)
  11438. {
  11439. $this->accumulateScormTime = (int) $value;
  11440. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11441. $lp_id = $this->get_id();
  11442. $sql = "UPDATE $lp_table
  11443. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11444. WHERE iid = $lp_id";
  11445. Database::query($sql);
  11446. return true;
  11447. }
  11448. /**
  11449. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11450. * the new learning path tool.
  11451. *
  11452. * The function is a big switch on tool type.
  11453. * In each case, we query the corresponding table for information and build the link
  11454. * with that information.
  11455. *
  11456. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11457. * previous work (display_addedresource_link_in_learnpath())
  11458. *
  11459. * @param int $course_id Course code
  11460. * @param int $learningPathId The learning path ID (in lp table)
  11461. * @param int $id_in_path the unique index in the items table
  11462. * @param int $lpViewId
  11463. *
  11464. * @return string
  11465. */
  11466. public static function rl_get_resource_link_for_learnpath(
  11467. $course_id,
  11468. $learningPathId,
  11469. $id_in_path,
  11470. $lpViewId
  11471. ) {
  11472. $session_id = api_get_session_id();
  11473. $course_info = api_get_course_info_by_id($course_id);
  11474. $learningPathId = (int) $learningPathId;
  11475. $id_in_path = (int) $id_in_path;
  11476. $lpViewId = (int) $lpViewId;
  11477. $em = Database::getManager();
  11478. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11479. /** @var CLpItem $rowItem */
  11480. $rowItem = $lpItemRepo->findOneBy([
  11481. 'cId' => $course_id,
  11482. 'lpId' => $learningPathId,
  11483. 'iid' => $id_in_path,
  11484. ]);
  11485. if (!$rowItem) {
  11486. // Try one more time with "id"
  11487. /** @var CLpItem $rowItem */
  11488. $rowItem = $lpItemRepo->findOneBy([
  11489. 'cId' => $course_id,
  11490. 'lpId' => $learningPathId,
  11491. 'id' => $id_in_path,
  11492. ]);
  11493. if (!$rowItem) {
  11494. return -1;
  11495. }
  11496. }
  11497. $course_code = $course_info['code'];
  11498. $type = $rowItem->getItemType();
  11499. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11500. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11501. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11502. $link = '';
  11503. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11504. switch ($type) {
  11505. case 'dir':
  11506. return $main_dir_path.'lp/blank.php';
  11507. case TOOL_CALENDAR_EVENT:
  11508. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11509. case TOOL_ANNOUNCEMENT:
  11510. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11511. case TOOL_LINK:
  11512. $linkInfo = Link::getLinkInfo($id);
  11513. if (isset($linkInfo['url'])) {
  11514. return $linkInfo['url'];
  11515. }
  11516. return '';
  11517. case TOOL_QUIZ:
  11518. if (empty($id)) {
  11519. return '';
  11520. }
  11521. // Get the lp_item_view with the highest view_count.
  11522. $learnpathItemViewResult = $em
  11523. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11524. ->findBy(
  11525. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11526. ['viewCount' => 'DESC'],
  11527. 1
  11528. );
  11529. /** @var CLpItemView $learnpathItemViewData */
  11530. $learnpathItemViewData = current($learnpathItemViewResult);
  11531. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11532. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11533. .http_build_query([
  11534. 'lp_init' => 1,
  11535. 'learnpath_item_view_id' => $learnpathItemViewId,
  11536. 'learnpath_id' => $learningPathId,
  11537. 'learnpath_item_id' => $id_in_path,
  11538. 'exerciseId' => $id,
  11539. ]);
  11540. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11541. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11542. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11543. $myrow = Database::fetch_array($result);
  11544. $path = $myrow['path'];
  11545. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11546. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11547. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11548. case TOOL_FORUM:
  11549. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11550. case TOOL_THREAD:
  11551. // forum post
  11552. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11553. if (empty($id)) {
  11554. return '';
  11555. }
  11556. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11557. $result = Database::query($sql);
  11558. $myrow = Database::fetch_array($result);
  11559. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11560. .$extraParams;
  11561. case TOOL_POST:
  11562. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11563. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11564. $myrow = Database::fetch_array($result);
  11565. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11566. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11567. case TOOL_READOUT_TEXT:
  11568. return api_get_path(WEB_CODE_PATH).
  11569. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  11570. case TOOL_DOCUMENT:
  11571. $document = $em
  11572. ->getRepository('ChamiloCourseBundle:CDocument')
  11573. ->findOneBy(['course' => $course_id, 'iid' => $id]);
  11574. if (empty($document)) {
  11575. // Try with normal id
  11576. $document = $em
  11577. ->getRepository('ChamiloCourseBundle:CDocument')
  11578. ->findOneBy(['course' => $course_id, 'id' => $id]);
  11579. if (empty($document)) {
  11580. return '';
  11581. }
  11582. }
  11583. $documentPathInfo = pathinfo($document->getPath());
  11584. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  11585. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11586. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  11587. $openmethod = 2;
  11588. $officedoc = false;
  11589. Session::write('openmethod', $openmethod);
  11590. Session::write('officedoc', $officedoc);
  11591. if ($showDirectUrl) {
  11592. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11593. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  11594. if (Link::isPdfLink($file)) {
  11595. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  11596. return $pdfUrl;
  11597. }
  11598. }
  11599. return $file;
  11600. }
  11601. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11602. case TOOL_LP_FINAL_ITEM:
  11603. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11604. .$extraParams;
  11605. case 'assignments':
  11606. return $main_dir_path.'work/work.php?'.$extraParams;
  11607. case TOOL_DROPBOX:
  11608. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11609. case 'introduction_text': //DEPRECATED
  11610. return '';
  11611. case TOOL_COURSE_DESCRIPTION:
  11612. return $main_dir_path.'course_description?'.$extraParams;
  11613. case TOOL_GROUP:
  11614. return $main_dir_path.'group/group.php?'.$extraParams;
  11615. case TOOL_USER:
  11616. return $main_dir_path.'user/user.php?'.$extraParams;
  11617. case TOOL_STUDENTPUBLICATION:
  11618. if (!empty($rowItem->getPath())) {
  11619. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11620. }
  11621. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11622. }
  11623. return $link;
  11624. }
  11625. /**
  11626. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11627. *
  11628. * @author Yannick Warnier <ywarnier@beeznest.org>
  11629. *
  11630. * @param string $course_code Course code
  11631. * @param int $learningPathId
  11632. * @param int $id_in_path The resource ID
  11633. *
  11634. * @return string
  11635. */
  11636. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11637. {
  11638. $_course = api_get_course_info($course_code);
  11639. if (empty($_course)) {
  11640. return '';
  11641. }
  11642. $course_id = $_course['real_id'];
  11643. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11644. $learningPathId = (int) $learningPathId;
  11645. $id_in_path = (int) $id_in_path;
  11646. $sql = "SELECT item_type, title, ref
  11647. FROM $tbl_lp_item
  11648. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11649. $res_item = Database::query($sql);
  11650. if (Database::num_rows($res_item) < 1) {
  11651. return '';
  11652. }
  11653. $row_item = Database::fetch_array($res_item);
  11654. $type = strtolower($row_item['item_type']);
  11655. $id = $row_item['ref'];
  11656. $output = '';
  11657. switch ($type) {
  11658. case TOOL_CALENDAR_EVENT:
  11659. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11660. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11661. $myrow = Database::fetch_array($result);
  11662. $output = $myrow['title'];
  11663. break;
  11664. case TOOL_ANNOUNCEMENT:
  11665. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11666. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11667. $myrow = Database::fetch_array($result);
  11668. $output = $myrow['title'];
  11669. break;
  11670. case TOOL_LINK:
  11671. // Doesn't take $target into account.
  11672. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11673. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11674. $myrow = Database::fetch_array($result);
  11675. $output = $myrow['title'];
  11676. break;
  11677. case TOOL_QUIZ:
  11678. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11679. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  11680. $myrow = Database::fetch_array($result);
  11681. $output = $myrow['title'];
  11682. break;
  11683. case TOOL_FORUM:
  11684. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11685. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  11686. $myrow = Database::fetch_array($result);
  11687. $output = $myrow['forum_name'];
  11688. break;
  11689. case TOOL_THREAD:
  11690. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11691. // Grabbing the title of the post.
  11692. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11693. $result_title = Database::query($sql_title);
  11694. $myrow_title = Database::fetch_array($result_title);
  11695. $output = $myrow_title['post_title'];
  11696. break;
  11697. case TOOL_POST:
  11698. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11699. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11700. $result = Database::query($sql);
  11701. $post = Database::fetch_array($result);
  11702. $output = $post['post_title'];
  11703. break;
  11704. case 'dir':
  11705. case TOOL_DOCUMENT:
  11706. $title = $row_item['title'];
  11707. $output = '-';
  11708. if (!empty($title)) {
  11709. $output = $title;
  11710. }
  11711. break;
  11712. case 'hotpotatoes':
  11713. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11714. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11715. $myrow = Database::fetch_array($result);
  11716. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11717. $last = count($pathname) - 1; // Making a correct name for the link.
  11718. $filename = $pathname[$last]; // Making a correct name for the link.
  11719. $myrow['path'] = rawurlencode($myrow['path']);
  11720. $output = $filename;
  11721. break;
  11722. }
  11723. return stripslashes($output);
  11724. }
  11725. /**
  11726. * Get the parent names for the current item.
  11727. *
  11728. * @param int $newItemId Optional. The item ID
  11729. *
  11730. * @return array
  11731. */
  11732. public function getCurrentItemParentNames($newItemId = 0)
  11733. {
  11734. $newItemId = $newItemId ?: $this->get_current_item_id();
  11735. $return = [];
  11736. $item = $this->getItem($newItemId);
  11737. $parent = $this->getItem($item->get_parent());
  11738. while ($parent) {
  11739. $return[] = $parent->get_title();
  11740. $parent = $this->getItem($parent->get_parent());
  11741. }
  11742. return array_reverse($return);
  11743. }
  11744. /**
  11745. * Reads and process "lp_subscription_settings" setting.
  11746. *
  11747. * @return array
  11748. */
  11749. public static function getSubscriptionSettings()
  11750. {
  11751. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11752. if (empty($subscriptionSettings)) {
  11753. // By default allow both settings
  11754. $subscriptionSettings = [
  11755. 'allow_add_users_to_lp' => true,
  11756. 'allow_add_users_to_lp_category' => true,
  11757. ];
  11758. } else {
  11759. $subscriptionSettings = $subscriptionSettings['options'];
  11760. }
  11761. return $subscriptionSettings;
  11762. }
  11763. /**
  11764. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  11765. */
  11766. public function exportToCourseBuildFormat()
  11767. {
  11768. if (!api_is_allowed_to_edit()) {
  11769. return false;
  11770. }
  11771. $courseBuilder = new CourseBuilder();
  11772. $itemList = [];
  11773. /** @var learnpathItem $item */
  11774. foreach ($this->items as $item) {
  11775. $itemList[$item->get_type()][] = $item->get_path();
  11776. }
  11777. if (empty($itemList)) {
  11778. return false;
  11779. }
  11780. if (isset($itemList['document'])) {
  11781. // Get parents
  11782. foreach ($itemList['document'] as $documentId) {
  11783. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  11784. if (!empty($documentInfo['parents'])) {
  11785. foreach ($documentInfo['parents'] as $parentInfo) {
  11786. if (in_array($parentInfo['iid'], $itemList['document'])) {
  11787. continue;
  11788. }
  11789. $itemList['document'][] = $parentInfo['iid'];
  11790. }
  11791. }
  11792. }
  11793. $courseInfo = api_get_course_info();
  11794. foreach ($itemList['document'] as $documentId) {
  11795. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  11796. $items = DocumentManager::get_resources_from_source_html(
  11797. $documentInfo['absolute_path'],
  11798. true,
  11799. TOOL_DOCUMENT
  11800. );
  11801. if (!empty($items)) {
  11802. foreach ($items as $item) {
  11803. // Get information about source url
  11804. $url = $item[0]; // url
  11805. $scope = $item[1]; // scope (local, remote)
  11806. $type = $item[2]; // type (rel, abs, url)
  11807. $origParseUrl = parse_url($url);
  11808. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  11809. if ($scope == 'local') {
  11810. if ($type == 'abs' || $type == 'rel') {
  11811. $documentFile = strstr($realOrigPath, 'document');
  11812. if (strpos($realOrigPath, $documentFile) !== false) {
  11813. $documentFile = str_replace('document', '', $documentFile);
  11814. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  11815. // Document found! Add it to the list
  11816. if ($itemDocumentId) {
  11817. $itemList['document'][] = $itemDocumentId;
  11818. }
  11819. }
  11820. }
  11821. }
  11822. }
  11823. }
  11824. }
  11825. $courseBuilder->build_documents(
  11826. api_get_session_id(),
  11827. $this->get_course_int_id(),
  11828. true,
  11829. $itemList['document']
  11830. );
  11831. }
  11832. if (isset($itemList['quiz'])) {
  11833. $courseBuilder->build_quizzes(
  11834. api_get_session_id(),
  11835. $this->get_course_int_id(),
  11836. true,
  11837. $itemList['quiz']
  11838. );
  11839. }
  11840. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  11841. /*if (!empty($itemList['thread'])) {
  11842. $postList = [];
  11843. foreach ($itemList['thread'] as $postId) {
  11844. $post = get_post_information($postId);
  11845. if ($post) {
  11846. if (!isset($itemList['forum'])) {
  11847. $itemList['forum'] = [];
  11848. }
  11849. $itemList['forum'][] = $post['forum_id'];
  11850. $postList[] = $postId;
  11851. }
  11852. }
  11853. if (!empty($postList)) {
  11854. $courseBuilder->build_forum_posts(
  11855. $this->get_course_int_id(),
  11856. null,
  11857. null,
  11858. $postList
  11859. );
  11860. }
  11861. }*/
  11862. if (!empty($itemList['thread'])) {
  11863. $threadList = [];
  11864. $em = Database::getManager();
  11865. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  11866. foreach ($itemList['thread'] as $threadId) {
  11867. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  11868. $thread = $repo->find($threadId);
  11869. if ($thread) {
  11870. $itemList['forum'][] = $thread->getForum() ? $thread->getForum()->getIid() : 0;
  11871. $threadList[] = $thread->getIid();
  11872. }
  11873. }
  11874. if (!empty($threadList)) {
  11875. $courseBuilder->build_forum_topics(
  11876. api_get_session_id(),
  11877. $this->get_course_int_id(),
  11878. null,
  11879. $threadList
  11880. );
  11881. }
  11882. }
  11883. $forumCategoryList = [];
  11884. if (isset($itemList['forum'])) {
  11885. foreach ($itemList['forum'] as $forumId) {
  11886. $forumInfo = get_forums($forumId);
  11887. $forumCategoryList[] = $forumInfo['forum_category'];
  11888. }
  11889. }
  11890. if (!empty($forumCategoryList)) {
  11891. $courseBuilder->build_forum_category(
  11892. api_get_session_id(),
  11893. $this->get_course_int_id(),
  11894. true,
  11895. $forumCategoryList
  11896. );
  11897. }
  11898. if (!empty($itemList['forum'])) {
  11899. $courseBuilder->build_forums(
  11900. api_get_session_id(),
  11901. $this->get_course_int_id(),
  11902. true,
  11903. $itemList['forum']
  11904. );
  11905. }
  11906. if (isset($itemList['link'])) {
  11907. $courseBuilder->build_links(
  11908. api_get_session_id(),
  11909. $this->get_course_int_id(),
  11910. true,
  11911. $itemList['link']
  11912. );
  11913. }
  11914. if (!empty($itemList['student_publication'])) {
  11915. $courseBuilder->build_works(
  11916. api_get_session_id(),
  11917. $this->get_course_int_id(),
  11918. true,
  11919. $itemList['student_publication']
  11920. );
  11921. }
  11922. $courseBuilder->build_learnpaths(
  11923. api_get_session_id(),
  11924. $this->get_course_int_id(),
  11925. true,
  11926. [$this->get_id()],
  11927. false
  11928. );
  11929. $courseBuilder->restoreDocumentsFromList();
  11930. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  11931. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  11932. $result = DocumentManager::file_send_for_download(
  11933. $zipPath,
  11934. true,
  11935. $this->get_name().'.zip'
  11936. );
  11937. if ($result) {
  11938. api_not_allowed();
  11939. }
  11940. return true;
  11941. }
  11942. /**
  11943. * Get whether this is a learning path with the accumulated work time or not.
  11944. *
  11945. * @return int
  11946. */
  11947. public function getAccumulateWorkTime()
  11948. {
  11949. return (int) $this->accumulateWorkTime;
  11950. }
  11951. /**
  11952. * Get whether this is a learning path with the accumulated work time or not.
  11953. *
  11954. * @return int
  11955. */
  11956. public function getAccumulateWorkTimeTotalCourse()
  11957. {
  11958. $table = Database::get_course_table(TABLE_LP_MAIN);
  11959. $sql = "SELECT SUM(accumulate_work_time) AS total
  11960. FROM $table
  11961. WHERE c_id = ".$this->course_int_id;
  11962. $result = Database::query($sql);
  11963. $row = Database::fetch_array($result);
  11964. return (int) $row['total'];
  11965. }
  11966. /**
  11967. * Set whether this is a learning path with the accumulated work time or not.
  11968. *
  11969. * @param int $value (0 = false, 1 = true)
  11970. *
  11971. * @return bool
  11972. */
  11973. public function setAccumulateWorkTime($value)
  11974. {
  11975. if (!api_get_configuration_value('lp_minimum_time')) {
  11976. return false;
  11977. }
  11978. $this->accumulateWorkTime = (int) $value;
  11979. $table = Database::get_course_table(TABLE_LP_MAIN);
  11980. $lp_id = $this->get_id();
  11981. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  11982. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  11983. Database::query($sql);
  11984. return true;
  11985. }
  11986. /**
  11987. * @param int $lpId
  11988. * @param int $courseId
  11989. *
  11990. * @return mixed
  11991. */
  11992. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  11993. {
  11994. $lpId = (int) $lpId;
  11995. $courseId = (int) $courseId;
  11996. $table = Database::get_course_table(TABLE_LP_MAIN);
  11997. $sql = "SELECT accumulate_work_time
  11998. FROM $table
  11999. WHERE c_id = $courseId AND id = $lpId";
  12000. $result = Database::query($sql);
  12001. $row = Database::fetch_array($result);
  12002. return $row['accumulate_work_time'];
  12003. }
  12004. /**
  12005. * @param int $courseId
  12006. *
  12007. * @return int
  12008. */
  12009. public static function getAccumulateWorkTimeTotal($courseId)
  12010. {
  12011. $table = Database::get_course_table(TABLE_LP_MAIN);
  12012. $courseId = (int) $courseId;
  12013. $sql = "SELECT SUM(accumulate_work_time) AS total
  12014. FROM $table
  12015. WHERE c_id = $courseId";
  12016. $result = Database::query($sql);
  12017. $row = Database::fetch_array($result);
  12018. return (int) $row['total'];
  12019. }
  12020. /**
  12021. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12022. * and put the images in.
  12023. *
  12024. * @return array
  12025. */
  12026. public static function getIconSelect()
  12027. {
  12028. $theme = api_get_visual_theme();
  12029. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12030. $icons = ['' => get_lang('Please select an option')];
  12031. if (is_dir($path)) {
  12032. $finder = new Finder();
  12033. $finder->files()->in($path);
  12034. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12035. /** @var SplFileInfo $file */
  12036. foreach ($finder as $file) {
  12037. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12038. $icons[$file->getFilename()] = $file->getFilename();
  12039. }
  12040. }
  12041. }
  12042. return $icons;
  12043. }
  12044. /**
  12045. * @param int $lpId
  12046. *
  12047. * @return string
  12048. */
  12049. public static function getSelectedIcon($lpId)
  12050. {
  12051. $extraFieldValue = new ExtraFieldValue('lp');
  12052. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12053. $icon = '';
  12054. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12055. $icon = $lpIcon['value'];
  12056. }
  12057. return $icon;
  12058. }
  12059. /**
  12060. * @param int $lpId
  12061. *
  12062. * @return string
  12063. */
  12064. public static function getSelectedIconHtml($lpId)
  12065. {
  12066. $icon = self::getSelectedIcon($lpId);
  12067. if (empty($icon)) {
  12068. return '';
  12069. }
  12070. $theme = api_get_visual_theme();
  12071. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12072. return Display::img($path);
  12073. }
  12074. /**
  12075. * @param string $value
  12076. *
  12077. * @return string
  12078. */
  12079. public function cleanItemTitle($value)
  12080. {
  12081. $value = Security::remove_XSS(strip_tags($value));
  12082. return $value;
  12083. }
  12084. /**
  12085. * @param FormValidator $form
  12086. */
  12087. public function setItemTitle(FormValidator $form)
  12088. {
  12089. if (api_get_configuration_value('save_titles_as_html')) {
  12090. $form->addHtmlEditor(
  12091. 'title',
  12092. get_lang('Title'),
  12093. true,
  12094. false,
  12095. ['ToolbarSet' => 'TitleAsHtml', 'id' => uniqid('editor')]
  12096. );
  12097. } else {
  12098. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
  12099. $form->applyFilter('title', 'trim');
  12100. $form->applyFilter('title', 'html_filter');
  12101. }
  12102. }
  12103. /**
  12104. * @return array
  12105. */
  12106. public function getItemsForForm($addParentCondition = false)
  12107. {
  12108. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12109. $course_id = api_get_course_int_id();
  12110. $sql = "SELECT * FROM $tbl_lp_item
  12111. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  12112. if ($addParentCondition) {
  12113. $sql .= ' AND parent_item_id = 0 ';
  12114. }
  12115. $sql .= ' ORDER BY display_order ASC';
  12116. $result = Database::query($sql);
  12117. $arrLP = [];
  12118. while ($row = Database::fetch_array($result)) {
  12119. $arrLP[] = [
  12120. 'iid' => $row['iid'],
  12121. 'id' => $row['iid'],
  12122. 'item_type' => $row['item_type'],
  12123. 'title' => $this->cleanItemTitle($row['title']),
  12124. 'title_raw' => $row['title'],
  12125. 'path' => $row['path'],
  12126. 'description' => Security::remove_XSS($row['description']),
  12127. 'parent_item_id' => $row['parent_item_id'],
  12128. 'previous_item_id' => $row['previous_item_id'],
  12129. 'next_item_id' => $row['next_item_id'],
  12130. 'display_order' => $row['display_order'],
  12131. 'max_score' => $row['max_score'],
  12132. 'min_score' => $row['min_score'],
  12133. 'mastery_score' => $row['mastery_score'],
  12134. 'prerequisite' => $row['prerequisite'],
  12135. 'max_time_allowed' => $row['max_time_allowed'],
  12136. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  12137. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  12138. ];
  12139. }
  12140. return $arrLP;
  12141. }
  12142. /**
  12143. * Get the depth level of LP item.
  12144. *
  12145. * @param array $items
  12146. * @param int $currentItemId
  12147. *
  12148. * @return int
  12149. */
  12150. private static function get_level_for_item($items, $currentItemId)
  12151. {
  12152. $parentItemId = 0;
  12153. if (isset($items[$currentItemId])) {
  12154. $parentItemId = $items[$currentItemId]->parent;
  12155. }
  12156. if ($parentItemId == 0) {
  12157. return 0;
  12158. } else {
  12159. return self::get_level_for_item($items, $parentItemId) + 1;
  12160. }
  12161. }
  12162. /**
  12163. * Generate the link for a learnpath category as course tool.
  12164. *
  12165. * @param int $categoryId
  12166. *
  12167. * @return string
  12168. */
  12169. private static function getCategoryLinkForTool($categoryId)
  12170. {
  12171. $categoryId = (int) $categoryId;
  12172. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12173. .http_build_query(
  12174. [
  12175. 'action' => 'view_category',
  12176. 'id' => $categoryId,
  12177. ]
  12178. );
  12179. return $link;
  12180. }
  12181. /**
  12182. * Return the scorm item type object with spaces replaced with _
  12183. * The return result is use to build a css classname like scorm_type_$return.
  12184. *
  12185. * @param $in_type
  12186. *
  12187. * @return mixed
  12188. */
  12189. private static function format_scorm_type_item($in_type)
  12190. {
  12191. return str_replace(' ', '_', $in_type);
  12192. }
  12193. /**
  12194. * Check and obtain the lp final item if exist.
  12195. *
  12196. * @return learnpathItem
  12197. */
  12198. private function getFinalItem()
  12199. {
  12200. if (empty($this->items)) {
  12201. return null;
  12202. }
  12203. foreach ($this->items as $item) {
  12204. if ($item->type !== 'final_item') {
  12205. continue;
  12206. }
  12207. return $item;
  12208. }
  12209. }
  12210. /**
  12211. * Get the LP Final Item Template.
  12212. *
  12213. * @return string
  12214. */
  12215. private function getFinalItemTemplate()
  12216. {
  12217. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12218. }
  12219. /**
  12220. * Get the LP Final Item Url.
  12221. *
  12222. * @return string
  12223. */
  12224. private function getSavedFinalItem()
  12225. {
  12226. $finalItem = $this->getFinalItem();
  12227. $doc = DocumentManager::get_document_data_by_id(
  12228. $finalItem->path,
  12229. $this->cc
  12230. );
  12231. if ($doc && file_exists($doc['absolute_path'])) {
  12232. return file_get_contents($doc['absolute_path']);
  12233. }
  12234. return '';
  12235. }
  12236. }