learnpath.class.php 494 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CourseBundle\Entity\CLpCategory;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  8. use Symfony\Component\Filesystem\Filesystem;
  9. use Symfony\Component\Finder\Finder;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CTool;
  12. use Chamilo\UserBundle\Entity\User;
  13. use Chamilo\CourseBundle\Entity\CLpItem;
  14. use Chamilo\CourseBundle\Entity\CLpItemView;
  15. use Chamilo\CourseBundle\Entity\CItemProperty;
  16. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  17. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  18. /**
  19. * Class learnpath
  20. * This class defines the parent attributes and methods for Chamilo learnpaths
  21. * and SCORM learnpaths. It is used by the scorm class.
  22. * @todo decouple class
  23. * @package chamilo.learnpath
  24. * @author Yannick Warnier <ywarnier@beeznest.org>
  25. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  26. */
  27. class learnpath
  28. {
  29. public $attempt = 0; // The number for the current ID view.
  30. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  31. public $current; // Id of the current item the user is viewing.
  32. public $current_score; // The score of the current item.
  33. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  34. public $current_time_stop; // The time the user closed this resource.
  35. public $default_status = 'not attempted';
  36. public $encoding = 'UTF-8';
  37. public $error = '';
  38. public $extra_information = ''; // This string can be used by proprietary SCORM contents to store data about the current learnpath.
  39. public $force_commit = false; // For SCORM only - if set to true, will send a scorm LMSCommit() request on each LMSSetValue().
  40. public $index; // The index of the active learnpath_item in $ordered_items array.
  41. public $items = [];
  42. public $last; // item_id of last item viewed in the learning path.
  43. public $last_item_seen = 0; // In case we have already come in this learnpath, reuse the last item seen if authorized.
  44. public $license; // Which license this course has been given - not used yet on 20060522.
  45. public $lp_id; // DB iid for this learnpath.
  46. public $lp_view_id; // DB ID for lp_view
  47. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  48. public $message = '';
  49. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  50. public $name; // Learnpath name (they generally have one).
  51. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  52. public $path = ''; // Path inside the scorm directory (if scorm).
  53. public $theme; // The current theme of the learning path.
  54. public $preview_image; // The current image of the learning path.
  55. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  56. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  57. public $prevent_reinit = 1;
  58. // Describes the mode of progress bar display.
  59. public $seriousgame_mode = 0;
  60. public $progress_bar_mode = '%';
  61. // Percentage progress as saved in the db.
  62. public $progress_db = 0;
  63. public $proximity; // Wether the content is distant or local or unknown.
  64. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  65. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  66. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  67. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  68. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  69. public $user_id; //ID of the user that is viewing/using the course
  70. public $update_queue = [];
  71. public $scorm_debug = 0;
  72. public $arrMenu = []; // Array for the menu items.
  73. public $debug = 0; // Logging level.
  74. public $lp_session_id = 0;
  75. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  76. public $prerequisite = 0;
  77. public $use_max_score = 1; // 1 or 0
  78. public $subscribeUsers = 0; // Subscribe users or not
  79. public $created_on = '';
  80. public $modified_on = '';
  81. public $publicated_on = '';
  82. public $expired_on = '';
  83. public $ref = null;
  84. public $course_int_id;
  85. public $course_info = [];
  86. public $categoryId;
  87. /**
  88. * Constructor.
  89. * Needs a database handler, a course code and a learnpath id from the database.
  90. * Also builds the list of items into $this->items.
  91. * @param string $course Course code
  92. * @param integer $lp_id
  93. * @param integer $user_id
  94. */
  95. public function __construct($course, $lp_id, $user_id)
  96. {
  97. $this->encoding = api_get_system_encoding();
  98. if ($this->debug > 0) {
  99. error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0);
  100. }
  101. if (empty($course)) {
  102. $course = api_get_course_id();
  103. }
  104. $course_info = api_get_course_info($course);
  105. if (!empty($course_info)) {
  106. $this->cc = $course_info['code'];
  107. $this->course_info = $course_info;
  108. $course_id = $course_info['real_id'];
  109. } else {
  110. $this->error = 'Course code does not exist in database.';
  111. }
  112. $lp_id = (int) $lp_id;
  113. $course_id = (int) $course_id;
  114. $this->set_course_int_id($course_id);
  115. // Check learnpath ID.
  116. if (empty($lp_id) || empty($course_id)) {
  117. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  118. } else {
  119. // TODO: Make it flexible to use any course_code (still using env course code here).
  120. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  121. $sql = "SELECT * FROM $lp_table
  122. WHERE iid = $lp_id";
  123. if ($this->debug > 2) {
  124. error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  125. }
  126. $res = Database::query($sql);
  127. if (Database::num_rows($res) > 0) {
  128. $this->lp_id = $lp_id;
  129. $row = Database::fetch_array($res);
  130. $this->type = $row['lp_type'];
  131. $this->name = stripslashes($row['name']);
  132. $this->proximity = $row['content_local'];
  133. $this->theme = $row['theme'];
  134. $this->maker = $row['content_maker'];
  135. $this->prevent_reinit = $row['prevent_reinit'];
  136. $this->seriousgame_mode = $row['seriousgame_mode'];
  137. $this->license = $row['content_license'];
  138. $this->scorm_debug = $row['debug'];
  139. $this->js_lib = $row['js_lib'];
  140. $this->path = $row['path'];
  141. $this->preview_image = $row['preview_image'];
  142. $this->author = $row['author'];
  143. $this->hide_toc_frame = $row['hide_toc_frame'];
  144. $this->lp_session_id = $row['session_id'];
  145. $this->use_max_score = $row['use_max_score'];
  146. $this->subscribeUsers = $row['subscribe_users'];
  147. $this->created_on = $row['created_on'];
  148. $this->modified_on = $row['modified_on'];
  149. $this->ref = $row['ref'];
  150. $this->categoryId = $row['category_id'];
  151. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  152. if (!empty($row['publicated_on'])) {
  153. $this->publicated_on = $row['publicated_on'];
  154. }
  155. if (!empty($row['expired_on'])) {
  156. $this->expired_on = $row['expired_on'];
  157. }
  158. if ($this->type == 2) {
  159. if ($row['force_commit'] == 1) {
  160. $this->force_commit = true;
  161. }
  162. }
  163. $this->mode = $row['default_view_mod'];
  164. // Check user ID.
  165. if (empty($user_id)) {
  166. $this->error = 'User ID is empty';
  167. } else {
  168. $user_info = api_get_user_info($user_id);
  169. if (!empty($user_info)) {
  170. $this->user_id = $user_info['user_id'];
  171. } else {
  172. $this->error = 'User ID does not exist in database ('.$sql.')';
  173. }
  174. }
  175. // End of variables checking.
  176. $session_id = api_get_session_id();
  177. // Get the session condition for learning paths of the base + session.
  178. $session = api_get_session_condition($session_id);
  179. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  180. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  181. // Selecting by view_count descending allows to get the highest view_count first.
  182. $sql = "SELECT * FROM $lp_table
  183. WHERE
  184. c_id = $course_id AND
  185. lp_id = $lp_id AND
  186. user_id = $user_id
  187. $session
  188. ORDER BY view_count DESC";
  189. $res = Database::query($sql);
  190. if ($this->debug > 2) {
  191. error_log('New LP - learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  192. }
  193. if (Database::num_rows($res) > 0) {
  194. if ($this->debug > 2) {
  195. error_log('New LP - learnpath::__construct() '.__LINE__.' - Found previous view');
  196. }
  197. $row = Database::fetch_array($res);
  198. $this->attempt = $row['view_count'];
  199. $this->lp_view_id = $row['id'];
  200. $this->last_item_seen = $row['last_item'];
  201. $this->progress_db = $row['progress'];
  202. $this->lp_view_session_id = $row['session_id'];
  203. } elseif (!api_is_invitee()) {
  204. if ($this->debug > 2) {
  205. error_log('New LP - learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  206. }
  207. $this->attempt = 1;
  208. $params = [
  209. 'c_id' => $course_id,
  210. 'lp_id' => $lp_id,
  211. 'user_id' => $user_id,
  212. 'view_count' => 1,
  213. 'session_id' => $session_id,
  214. 'last_item' => 0
  215. ];
  216. $this->lp_view_id = Database::insert($lp_table, $params);
  217. if (!empty($this->lp_view_id)) {
  218. $sql = "UPDATE $lp_table SET id = iid
  219. WHERE iid = ".$this->lp_view_id;
  220. Database::query($sql);
  221. }
  222. }
  223. // Initialise items.
  224. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  225. $sql = "SELECT * FROM $lp_item_table
  226. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  227. ORDER BY parent_item_id, display_order";
  228. $res = Database::query($sql);
  229. if ($this->debug > 2) {
  230. error_log('New LP - learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  231. error_log('-- Start while--');
  232. }
  233. $lp_item_id_list = [];
  234. while ($row = Database::fetch_array($res)) {
  235. $lp_item_id_list[] = $row['iid'];
  236. switch ($this->type) {
  237. case 3: //aicc
  238. $oItem = new aiccItem('db', $row['iid'], $course_id);
  239. if (is_object($oItem)) {
  240. $my_item_id = $oItem->get_id();
  241. $oItem->set_lp_view($this->lp_view_id, $course_id);
  242. $oItem->set_prevent_reinit($this->prevent_reinit);
  243. // Don't use reference here as the next loop will make the pointed object change.
  244. $this->items[$my_item_id] = $oItem;
  245. $this->refs_list[$oItem->ref] = $my_item_id;
  246. if ($this->debug > 2) {
  247. error_log(
  248. 'New LP - learnpath::__construct() - '.
  249. 'aicc object with id '.$my_item_id.
  250. ' set in items[]',
  251. 0
  252. );
  253. }
  254. }
  255. break;
  256. case 2:
  257. $oItem = new scormItem('db', $row['iid'], $course_id);
  258. if (is_object($oItem)) {
  259. $my_item_id = $oItem->get_id();
  260. $oItem->set_lp_view($this->lp_view_id, $course_id);
  261. $oItem->set_prevent_reinit($this->prevent_reinit);
  262. // Don't use reference here as the next loop will make the pointed object change.
  263. $this->items[$my_item_id] = $oItem;
  264. $this->refs_list[$oItem->ref] = $my_item_id;
  265. if ($this->debug > 2) {
  266. error_log('New LP - object with id '.$my_item_id.' set in items[]', 0);
  267. }
  268. }
  269. break;
  270. case 1:
  271. default:
  272. if ($this->debug > 2) {
  273. error_log('New LP - learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  274. }
  275. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  276. if ($this->debug > 2) {
  277. error_log('New LP - learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  278. }
  279. if (is_object($oItem)) {
  280. $my_item_id = $oItem->get_id();
  281. // Moved down to when we are sure the item_view exists.
  282. //$oItem->set_lp_view($this->lp_view_id);
  283. $oItem->set_prevent_reinit($this->prevent_reinit);
  284. // Don't use reference here as the next loop will make the pointed object change.
  285. $this->items[$my_item_id] = $oItem;
  286. $this->refs_list[$my_item_id] = $my_item_id;
  287. if ($this->debug > 2) {
  288. error_log(
  289. 'New LP - learnpath::__construct() '.__LINE__.
  290. ' - object with id '.$my_item_id.' set in items[]'
  291. );
  292. }
  293. }
  294. break;
  295. }
  296. // Setting the object level with variable $this->items[$i][parent]
  297. foreach ($this->items as $itemLPObject) {
  298. $level = self::get_level_for_item(
  299. $this->items,
  300. $itemLPObject->db_id
  301. );
  302. $itemLPObject->level = $level;
  303. }
  304. // Setting the view in the item object.
  305. if (is_object($this->items[$row['iid']])) {
  306. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  307. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  308. $this->items[$row['iid']]->current_start_time = 0;
  309. $this->items[$row['iid']]->current_stop_time = 0;
  310. }
  311. }
  312. }
  313. if ($this->debug > 2) {
  314. error_log('New LP - learnpath::__construct() '.__LINE__.' ----- end while ----');
  315. }
  316. if (!empty($lp_item_id_list)) {
  317. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  318. if (!empty($lp_item_id_list_to_string)) {
  319. // Get last viewing vars.
  320. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  321. // This query should only return one or zero result.
  322. $sql = "SELECT lp_item_id, status
  323. FROM $itemViewTable
  324. WHERE
  325. c_id = $course_id AND
  326. lp_view_id = ".$this->lp_view_id." AND
  327. lp_item_id IN ('".$lp_item_id_list_to_string."')
  328. ORDER BY view_count DESC ";
  329. if ($this->debug > 2) {
  330. error_log(
  331. 'New LP - learnpath::__construct() - Selecting item_views: '.$sql,
  332. 0
  333. );
  334. }
  335. $status_list = [];
  336. $res = Database::query($sql);
  337. while ($row = Database:: fetch_array($res)) {
  338. $status_list[$row['lp_item_id']] = $row['status'];
  339. }
  340. foreach ($lp_item_id_list as $item_id) {
  341. if (isset($status_list[$item_id])) {
  342. $status = $status_list[$item_id];
  343. if (is_object($this->items[$item_id])) {
  344. $this->items[$item_id]->set_status($status);
  345. if (empty($status)) {
  346. $this->items[$item_id]->set_status(
  347. $this->default_status
  348. );
  349. }
  350. }
  351. } else {
  352. if (!api_is_invitee()) {
  353. if (is_object($this->items[$item_id])) {
  354. $this->items[$item_id]->set_status(
  355. $this->default_status
  356. );
  357. }
  358. if (!empty($this->lp_view_id)) {
  359. // Add that row to the lp_item_view table so that
  360. // we have something to show in the stats page.
  361. $params = [
  362. 'c_id' => $course_id,
  363. 'lp_item_id' => $item_id,
  364. 'lp_view_id' => $this->lp_view_id,
  365. 'view_count' => 1,
  366. 'status' => 'not attempted',
  367. 'start_time' => time(),
  368. 'total_time' => 0,
  369. 'score' => 0
  370. ];
  371. $insertId = Database::insert($itemViewTable, $params);
  372. if ($insertId) {
  373. $sql = "UPDATE $itemViewTable SET id = iid
  374. WHERE iid = $insertId";
  375. Database::query($sql);
  376. }
  377. $this->items[$item_id]->set_lp_view(
  378. $this->lp_view_id,
  379. $course_id
  380. );
  381. }
  382. }
  383. }
  384. }
  385. }
  386. }
  387. $this->ordered_items = self::get_flat_ordered_items_list(
  388. $this->get_id(),
  389. 0,
  390. $course_id
  391. );
  392. $this->max_ordered_items = 0;
  393. foreach ($this->ordered_items as $index => $dummy) {
  394. if ($index > $this->max_ordered_items && !empty($dummy)) {
  395. $this->max_ordered_items = $index;
  396. }
  397. }
  398. // TODO: Define the current item better.
  399. $this->first();
  400. if ($this->debug > 2) {
  401. error_log('New LP - learnpath::__construct() '.__LINE__.' - End of learnpath constructor for learnpath '.$this->get_id(), 0);
  402. }
  403. } else {
  404. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  405. }
  406. }
  407. }
  408. /**
  409. * @return string
  410. */
  411. public function getCourseCode()
  412. {
  413. return $this->cc;
  414. }
  415. /**
  416. * @return int
  417. */
  418. public function get_course_int_id()
  419. {
  420. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  421. }
  422. /**
  423. * @param $course_id
  424. * @return int
  425. */
  426. public function set_course_int_id($course_id)
  427. {
  428. return $this->course_int_id = (int) $course_id;
  429. }
  430. /**
  431. * Get the depth level of LP item
  432. * @param array $items
  433. * @param int $currentItemId
  434. * @return int
  435. */
  436. private static function get_level_for_item($items, $currentItemId)
  437. {
  438. $parentItemId = $items[$currentItemId]->parent;
  439. if ($parentItemId == 0) {
  440. return 0;
  441. } else {
  442. return self::get_level_for_item($items, $parentItemId) + 1;
  443. }
  444. }
  445. /**
  446. * Function rewritten based on old_add_item() from Yannick Warnier.
  447. * Due the fact that users can decide where the item should come, I had to overlook this function and
  448. * I found it better to rewrite it. Old function is still available.
  449. * Added also the possibility to add a description.
  450. *
  451. * @param int $parent
  452. * @param int $previous
  453. * @param string $type
  454. * @param int $id resource ID (ref)
  455. * @param string $title
  456. * @param string $description
  457. * @param int $prerequisites
  458. * @param int $max_time_allowed
  459. * @param int $userId
  460. *
  461. * @return int
  462. */
  463. public function add_item(
  464. $parent,
  465. $previous,
  466. $type = 'dir',
  467. $id,
  468. $title,
  469. $description,
  470. $prerequisites = 0,
  471. $max_time_allowed = 0,
  472. $userId = 0
  473. ) {
  474. $course_id = $this->course_info['real_id'];
  475. if ($this->debug > 0) {
  476. error_log('New LP - In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  477. }
  478. if (empty($course_id)) {
  479. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  480. $this->course_info = api_get_course_info($this->cc);
  481. $course_id = $this->course_info['real_id'];
  482. }
  483. $userId = empty($userId) ? api_get_user_id() : $userId;
  484. $sessionId = api_get_session_id();
  485. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  486. $_course = $this->course_info;
  487. $parent = intval($parent);
  488. $previous = intval($previous);
  489. $id = intval($id);
  490. $max_time_allowed = htmlentities($max_time_allowed);
  491. if (empty($max_time_allowed)) {
  492. $max_time_allowed = 0;
  493. }
  494. $sql = "SELECT COUNT(iid) AS num
  495. FROM $tbl_lp_item
  496. WHERE
  497. c_id = $course_id AND
  498. lp_id = ".$this->get_id()." AND
  499. parent_item_id = ".$parent;
  500. $res_count = Database::query($sql);
  501. $row = Database::fetch_array($res_count);
  502. $num = $row['num'];
  503. if ($num > 0) {
  504. if (empty($previous)) {
  505. $sql = "SELECT iid, next_item_id, display_order
  506. FROM $tbl_lp_item
  507. WHERE
  508. c_id = $course_id AND
  509. lp_id = ".$this->get_id()." AND
  510. parent_item_id = $parent AND
  511. previous_item_id = 0 OR
  512. previous_item_id = $parent";
  513. $result = Database::query($sql);
  514. $row = Database::fetch_array($result);
  515. $tmp_previous = 0;
  516. $next = $row['iid'];
  517. $display_order = 0;
  518. } else {
  519. $previous = (int) $previous;
  520. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  521. FROM $tbl_lp_item
  522. WHERE
  523. c_id = $course_id AND
  524. lp_id = ".$this->get_id()." AND
  525. id = $previous";
  526. $result = Database::query($sql);
  527. $row = Database:: fetch_array($result);
  528. $tmp_previous = $row['iid'];
  529. $next = $row['next_item_id'];
  530. $display_order = $row['display_order'];
  531. }
  532. } else {
  533. $tmp_previous = 0;
  534. $next = 0;
  535. $display_order = 0;
  536. }
  537. $id = intval($id);
  538. $typeCleaned = Database::escape_string($type);
  539. if ($type == 'quiz') {
  540. $sql = 'SELECT SUM(ponderation)
  541. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  542. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  543. ON
  544. quiz_question.id = quiz_rel_question.question_id AND
  545. quiz_question.c_id = quiz_rel_question.c_id
  546. WHERE
  547. quiz_rel_question.exercice_id = '.$id." AND
  548. quiz_question.c_id = $course_id AND
  549. quiz_rel_question.c_id = $course_id ";
  550. $rsQuiz = Database::query($sql);
  551. $max_score = Database::result($rsQuiz, 0, 0);
  552. // Disabling the exercise if we add it inside a LP
  553. $exercise = new Exercise($course_id);
  554. $exercise->read($id);
  555. $exercise->disable();
  556. $exercise->save();
  557. } else {
  558. $max_score = 100;
  559. }
  560. $params = [
  561. "c_id" => $course_id,
  562. "lp_id" => $this->get_id(),
  563. "item_type" => $typeCleaned,
  564. "ref" => '',
  565. "title" => $title,
  566. "description" => $description,
  567. "path" => $id,
  568. "max_score" => $max_score,
  569. "parent_item_id" => $parent,
  570. "previous_item_id" => $previous,
  571. "next_item_id" => intval($next),
  572. "display_order" => $display_order + 1,
  573. "prerequisite" => $prerequisites,
  574. "max_time_allowed" => $max_time_allowed,
  575. 'min_score' => 0,
  576. 'launch_data' => ''
  577. ];
  578. if ($prerequisites != 0) {
  579. $params['prerequisite'] = $prerequisites;
  580. }
  581. $new_item_id = Database::insert($tbl_lp_item, $params);
  582. if ($this->debug > 2) {
  583. error_log('New LP - Inserting dir/chapter: '.$new_item_id, 0);
  584. }
  585. if ($new_item_id) {
  586. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  587. Database::query($sql);
  588. $sql = "UPDATE $tbl_lp_item
  589. SET previous_item_id = $new_item_id
  590. WHERE c_id = $course_id AND id = $next";
  591. Database::query($sql);
  592. // Update the item that should be before the new item.
  593. $sql = "UPDATE $tbl_lp_item
  594. SET next_item_id = $new_item_id
  595. WHERE c_id = $course_id AND id = $tmp_previous";
  596. Database::query($sql);
  597. // Update all the items after the new item.
  598. $sql = "UPDATE $tbl_lp_item
  599. SET display_order = display_order + 1
  600. WHERE
  601. c_id = $course_id AND
  602. lp_id = ".$this->get_id()." AND
  603. iid <> $new_item_id AND
  604. parent_item_id = $parent AND
  605. display_order > $display_order";
  606. Database::query($sql);
  607. // Update the item that should come after the new item.
  608. $sql = "UPDATE $tbl_lp_item
  609. SET ref = $new_item_id
  610. WHERE c_id = $course_id AND iid = $new_item_id";
  611. Database::query($sql);
  612. // Upload audio.
  613. if (!empty($_FILES['mp3']['name'])) {
  614. // Create the audio folder if it does not exist yet.
  615. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  616. if (!is_dir($filepath.'audio')) {
  617. mkdir(
  618. $filepath.'audio',
  619. api_get_permissions_for_new_directories()
  620. );
  621. $audio_id = add_document(
  622. $_course,
  623. '/audio',
  624. 'folder',
  625. 0,
  626. 'audio',
  627. '',
  628. 0,
  629. true,
  630. null,
  631. $sessionId,
  632. $userId
  633. );
  634. api_item_property_update(
  635. $_course,
  636. TOOL_DOCUMENT,
  637. $audio_id,
  638. 'FolderCreated',
  639. $userId,
  640. null,
  641. null,
  642. null,
  643. null,
  644. $sessionId
  645. );
  646. api_item_property_update(
  647. $_course,
  648. TOOL_DOCUMENT,
  649. $audio_id,
  650. 'invisible',
  651. $userId,
  652. null,
  653. null,
  654. null,
  655. null,
  656. $sessionId
  657. );
  658. }
  659. $file_path = handle_uploaded_document(
  660. $_course,
  661. $_FILES['mp3'],
  662. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  663. '/audio',
  664. $userId,
  665. '',
  666. '',
  667. '',
  668. '',
  669. false
  670. );
  671. // Getting the filename only.
  672. $file_components = explode('/', $file_path);
  673. $file = $file_components[count($file_components) - 1];
  674. // Store the mp3 file in the lp_item table.
  675. $sql = "UPDATE $tbl_lp_item SET
  676. audio = '".Database::escape_string($file)."'
  677. WHERE iid = '" . intval($new_item_id)."'";
  678. Database::query($sql);
  679. }
  680. }
  681. return $new_item_id;
  682. }
  683. /**
  684. * Static admin function allowing addition of a learnpath to a course.
  685. * @param string Course code
  686. * @param string Learnpath name
  687. * @param string Learnpath description string, if provided
  688. * @param string Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  689. * @param string Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  690. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  691. * @param string $publicated_on
  692. * @param string $expired_on
  693. * @param int $categoryId
  694. * @param int $userId
  695. * @return integer The new learnpath ID on success, 0 on failure
  696. */
  697. public static function add_lp(
  698. $courseCode,
  699. $name,
  700. $description = '',
  701. $learnpath = 'guess',
  702. $origin = 'zip',
  703. $zipname = '',
  704. $publicated_on = '',
  705. $expired_on = '',
  706. $categoryId = 0,
  707. $userId = 0
  708. ) {
  709. global $charset;
  710. if (!empty($courseCode)) {
  711. $courseInfo = api_get_course_info($courseCode);
  712. $course_id = $courseInfo['real_id'];
  713. } else {
  714. $course_id = api_get_course_int_id();
  715. $courseInfo = api_get_course_info();
  716. }
  717. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  718. // Check course code exists.
  719. // Check lp_name doesn't exist, otherwise append something.
  720. $i = 0;
  721. $name = Database::escape_string($name);
  722. $categoryId = intval($categoryId);
  723. // Session id.
  724. $session_id = api_get_session_id();
  725. $userId = empty($userId) ? api_get_user_id() : $userId;
  726. $check_name = "SELECT * FROM $tbl_lp
  727. WHERE c_id = $course_id AND name = '$name'";
  728. $res_name = Database::query($check_name);
  729. if (empty($publicated_on)) {
  730. $publicated_on = null;
  731. } else {
  732. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  733. }
  734. if (empty($expired_on)) {
  735. $expired_on = null;
  736. } else {
  737. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  738. }
  739. while (Database::num_rows($res_name)) {
  740. // There is already one such name, update the current one a bit.
  741. $i++;
  742. $name = $name.' - '.$i;
  743. $check_name = "SELECT * FROM $tbl_lp
  744. WHERE c_id = $course_id AND name = '$name'";
  745. $res_name = Database::query($check_name);
  746. }
  747. // New name does not exist yet; keep it.
  748. // Escape description.
  749. // Kevin: added htmlentities().
  750. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  751. $type = 1;
  752. switch ($learnpath) {
  753. case 'guess':
  754. break;
  755. case 'dokeos':
  756. case 'chamilo':
  757. $type = 1;
  758. break;
  759. case 'aicc':
  760. break;
  761. }
  762. switch ($origin) {
  763. case 'zip':
  764. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  765. break;
  766. case 'manual':
  767. default:
  768. $get_max = "SELECT MAX(display_order)
  769. FROM $tbl_lp WHERE c_id = $course_id";
  770. $res_max = Database::query($get_max);
  771. if (Database::num_rows($res_max) < 1) {
  772. $dsp = 1;
  773. } else {
  774. $row = Database::fetch_array($res_max);
  775. $dsp = $row[0] + 1;
  776. }
  777. $params = [
  778. 'c_id' => $course_id,
  779. 'lp_type' => $type,
  780. 'name' => $name,
  781. 'description' => $description,
  782. 'path' => '',
  783. 'default_view_mod' => 'embedded',
  784. 'default_encoding' => 'UTF-8',
  785. 'display_order' => $dsp,
  786. 'content_maker' => 'Chamilo',
  787. 'content_local' => 'local',
  788. 'js_lib' => '',
  789. 'session_id' => $session_id,
  790. 'created_on' => api_get_utc_datetime(),
  791. 'modified_on' => api_get_utc_datetime(),
  792. 'publicated_on' => $publicated_on,
  793. 'expired_on' => $expired_on,
  794. 'category_id' => $categoryId,
  795. 'force_commit' => 0,
  796. 'content_license' => '',
  797. 'debug' => 0,
  798. 'theme' => '',
  799. 'preview_image' => '',
  800. 'author' => '',
  801. 'prerequisite' => 0,
  802. 'hide_toc_frame' => 0,
  803. 'seriousgame_mode' => 0,
  804. 'autolaunch' => 0,
  805. 'max_attempts' => 0,
  806. 'subscribe_users' => 0,
  807. 'accumulate_scorm_time' => 1
  808. ];
  809. $id = Database::insert($tbl_lp, $params);
  810. if ($id > 0) {
  811. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  812. Database::query($sql);
  813. // Insert into item_property.
  814. api_item_property_update(
  815. $courseInfo,
  816. TOOL_LEARNPATH,
  817. $id,
  818. 'LearnpathAdded',
  819. $userId
  820. );
  821. api_set_default_visibility(
  822. $id,
  823. TOOL_LEARNPATH,
  824. 0,
  825. $courseInfo,
  826. $session_id,
  827. $userId
  828. );
  829. return $id;
  830. }
  831. break;
  832. }
  833. }
  834. /**
  835. * Auto completes the parents of an item in case it's been completed or passed
  836. * @param int $item Optional ID of the item from which to look for parents
  837. */
  838. public function autocomplete_parents($item)
  839. {
  840. $debug = $this->debug;
  841. if ($debug) {
  842. error_log('Learnpath::autocomplete_parents()');
  843. }
  844. if (empty($item)) {
  845. $item = $this->current;
  846. }
  847. $currentItem = $this->getItem($item);
  848. if ($currentItem) {
  849. $parent_id = $currentItem->get_parent();
  850. $parent = $this->getItem($parent_id);
  851. if ($parent) {
  852. // if $item points to an object and there is a parent.
  853. if ($debug) {
  854. error_log(
  855. 'Autocompleting parent of item '.$item.' "'.$currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  856. 0
  857. );
  858. }
  859. // New experiment including failed and browsed in completed status.
  860. //$current_status = $currentItem->get_status();
  861. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  862. // Fixes chapter auto complete
  863. if (true) {
  864. // If the current item is completed or passes or succeeded.
  865. $updateParentStatus = true;
  866. if ($debug) {
  867. error_log('Status of current item is alright');
  868. }
  869. foreach ($parent->get_children() as $childItemId) {
  870. $childItem = $this->getItem($childItemId);
  871. // If children was not set try to get the info
  872. if (empty($childItem->db_item_view_id)) {
  873. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  874. }
  875. // Check all his brothers (parent's children) for completion status.
  876. if ($childItemId != $item) {
  877. if ($debug) {
  878. error_log(
  879. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  880. 0
  881. );
  882. }
  883. // Trying completing parents of failed and browsed items as well.
  884. if ($childItem->status_is(
  885. [
  886. 'completed',
  887. 'passed',
  888. 'succeeded',
  889. 'browsed',
  890. 'failed'
  891. ]
  892. )
  893. ) {
  894. // Keep completion status to true.
  895. continue;
  896. } else {
  897. if ($debug > 2) {
  898. error_log(
  899. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
  900. 0
  901. );
  902. }
  903. $updateParentStatus = false;
  904. break;
  905. }
  906. }
  907. }
  908. if ($updateParentStatus) {
  909. // If all the children were completed:
  910. $parent->set_status('completed');
  911. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  912. // Force the status to "completed"
  913. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  914. $this->update_queue[$parent->get_id()] = 'completed';
  915. if ($debug) {
  916. error_log(
  917. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  918. print_r($this->update_queue, 1),
  919. 0
  920. );
  921. }
  922. // Recursive call.
  923. $this->autocomplete_parents($parent->get_id());
  924. }
  925. }
  926. } else {
  927. if ($debug) {
  928. error_log("Parent #$parent_id does not exists");
  929. }
  930. }
  931. } else {
  932. if ($debug) {
  933. error_log("#$item is an item that doesn't have parents");
  934. }
  935. }
  936. }
  937. /**
  938. * Auto saves the current results into the database for the whole learnpath
  939. * @todo: Add save operations for the learnpath itself.
  940. */
  941. public function autosave()
  942. {
  943. if ($this->debug > 0) {
  944. error_log('New LP - In learnpath::autosave()', 0);
  945. }
  946. }
  947. /**
  948. * Closes the current resource
  949. *
  950. * Stops the timer
  951. * Saves into the database if required
  952. * Clears the current resource data from this object
  953. * @return boolean True on success, false on failure
  954. */
  955. public function close()
  956. {
  957. if ($this->debug > 0) {
  958. error_log('New LP - In learnpath::close()', 0);
  959. }
  960. if (empty($this->lp_id)) {
  961. $this->error = 'Trying to close this learnpath but no ID is set';
  962. return false;
  963. }
  964. $this->current_time_stop = time();
  965. $this->ordered_items = [];
  966. $this->index = 0;
  967. unset($this->lp_id);
  968. //unset other stuff
  969. return true;
  970. }
  971. /**
  972. * Static admin function allowing removal of a learnpath
  973. * @param array $courseInfo
  974. * @param integer $id Learnpath ID
  975. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  976. * @return boolean True on success, false on failure (might change that to return number of elements deleted)
  977. */
  978. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  979. {
  980. $course_id = api_get_course_int_id();
  981. if (!empty($courseInfo)) {
  982. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  983. }
  984. // TODO: Implement a way of getting this to work when the current object is not set.
  985. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  986. // If an ID is specifically given and the current LP is not the same, prevent delete.
  987. if (!empty($id) && ($id != $this->lp_id)) {
  988. return false;
  989. }
  990. $lp = Database::get_course_table(TABLE_LP_MAIN);
  991. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  992. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  993. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  994. // Delete lp item id.
  995. foreach ($this->items as $id => $dummy) {
  996. $sql = "DELETE FROM $lp_item_view
  997. WHERE c_id = $course_id AND lp_item_id = '".$id."'";
  998. Database::query($sql);
  999. }
  1000. // Proposed by Christophe (nickname: clefevre)
  1001. $sql = "DELETE FROM $lp_item
  1002. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1003. Database::query($sql);
  1004. $sql = "DELETE FROM $lp_view
  1005. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1006. Database::query($sql);
  1007. self::toggle_publish($this->lp_id, 'i');
  1008. if ($this->type == 2 || $this->type == 3) {
  1009. // This is a scorm learning path, delete the files as well.
  1010. $sql = "SELECT path FROM $lp
  1011. WHERE iid = ".$this->lp_id;
  1012. $res = Database::query($sql);
  1013. if (Database::num_rows($res) > 0) {
  1014. $row = Database::fetch_array($res);
  1015. $path = $row['path'];
  1016. $sql = "SELECT id FROM $lp
  1017. WHERE
  1018. c_id = $course_id AND
  1019. path = '$path' AND
  1020. iid != ".$this->lp_id;
  1021. $res = Database::query($sql);
  1022. if (Database::num_rows($res) > 0) {
  1023. // Another learning path uses this directory, so don't delete it.
  1024. if ($this->debug > 2) {
  1025. error_log('New LP - In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1026. }
  1027. } else {
  1028. // No other LP uses that directory, delete it.
  1029. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1030. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir; // The absolute system path for this course.
  1031. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1032. if ($this->debug > 2) {
  1033. error_log('New LP - In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1034. }
  1035. // Proposed by Christophe (clefevre).
  1036. if (strcmp(substr($path, -2), "/.") == 0) {
  1037. $path = substr($path, 0, -1); // Remove "." at the end.
  1038. }
  1039. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1040. rmdirr($course_scorm_dir.$path);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1046. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1047. // Delete tools
  1048. $sql = "DELETE FROM $tbl_tool
  1049. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1050. Database::query($sql);
  1051. $sql = "DELETE FROM $lp
  1052. WHERE iid = ".$this->lp_id;
  1053. Database::query($sql);
  1054. // Updates the display order of all lps.
  1055. $this->update_display_order();
  1056. api_item_property_update(
  1057. api_get_course_info(),
  1058. TOOL_LEARNPATH,
  1059. $this->lp_id,
  1060. 'delete',
  1061. api_get_user_id()
  1062. );
  1063. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1064. api_get_course_id(),
  1065. 4,
  1066. $id,
  1067. api_get_session_id()
  1068. );
  1069. if ($link_info !== false) {
  1070. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1071. }
  1072. if (api_get_setting('search_enabled') == 'true') {
  1073. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1074. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1075. }
  1076. }
  1077. /**
  1078. * Removes all the children of one item - dangerous!
  1079. * @param integer $id Element ID of which children have to be removed
  1080. * @return integer Total number of children removed
  1081. */
  1082. public function delete_children_items($id)
  1083. {
  1084. $course_id = $this->course_info['real_id'];
  1085. if ($this->debug > 0) {
  1086. error_log('New LP - In learnpath::delete_children_items('.$id.')', 0);
  1087. }
  1088. $num = 0;
  1089. if (empty($id) || $id != strval(intval($id))) {
  1090. return false;
  1091. }
  1092. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1093. $sql = "SELECT * FROM $lp_item
  1094. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1095. $res = Database::query($sql);
  1096. while ($row = Database::fetch_array($res)) {
  1097. $num += $this->delete_children_items($row['iid']);
  1098. $sql = "DELETE FROM $lp_item
  1099. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1100. Database::query($sql);
  1101. $num++;
  1102. }
  1103. return $num;
  1104. }
  1105. /**
  1106. * Removes an item from the current learnpath
  1107. * @param integer $id Elem ID (0 if first)
  1108. * @param integer $remove Whether to remove the resource/data from the
  1109. * system or leave it (default: 'keep', others 'remove')
  1110. * @return integer Number of elements moved
  1111. * @todo implement resource removal
  1112. */
  1113. public function delete_item($id, $remove = 'keep')
  1114. {
  1115. $course_id = api_get_course_int_id();
  1116. if ($this->debug > 0) {
  1117. error_log('New LP - In learnpath::delete_item()', 0);
  1118. }
  1119. // TODO: Implement the resource removal.
  1120. if (empty($id) || $id != strval(intval($id))) {
  1121. return false;
  1122. }
  1123. // First select item to get previous, next, and display order.
  1124. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1125. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1126. $res_sel = Database::query($sql_sel);
  1127. if (Database::num_rows($res_sel) < 1) {
  1128. return false;
  1129. }
  1130. $row = Database::fetch_array($res_sel);
  1131. $previous = $row['previous_item_id'];
  1132. $next = $row['next_item_id'];
  1133. $display = $row['display_order'];
  1134. $parent = $row['parent_item_id'];
  1135. $lp = $row['lp_id'];
  1136. // Delete children items.
  1137. $num = $this->delete_children_items($id);
  1138. if ($this->debug > 2) {
  1139. error_log('New LP - learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1140. }
  1141. // Now delete the item.
  1142. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1143. if ($this->debug > 2) {
  1144. error_log('New LP - Deleting item: '.$sql_del, 0);
  1145. }
  1146. Database::query($sql_del);
  1147. // Now update surrounding items.
  1148. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1149. WHERE iid = $previous";
  1150. Database::query($sql_upd);
  1151. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1152. WHERE iid = $next";
  1153. Database::query($sql_upd);
  1154. // Now update all following items with new display order.
  1155. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1156. WHERE
  1157. c_id = $course_id AND
  1158. lp_id = $lp AND
  1159. parent_item_id = $parent AND
  1160. display_order > $display";
  1161. Database::query($sql_all);
  1162. //Removing prerequisites since the item will not longer exist
  1163. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1164. WHERE c_id = $course_id AND prerequisite = $id";
  1165. Database::query($sql_all);
  1166. // Remove from search engine if enabled.
  1167. if (api_get_setting('search_enabled') == 'true') {
  1168. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1169. $sql = 'SELECT * FROM %s
  1170. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1171. LIMIT 1';
  1172. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1173. $res = Database::query($sql);
  1174. if (Database::num_rows($res) > 0) {
  1175. $row2 = Database::fetch_array($res);
  1176. $di = new ChamiloIndexer();
  1177. $di->remove_document($row2['search_did']);
  1178. }
  1179. $sql = 'DELETE FROM %s
  1180. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1181. LIMIT 1';
  1182. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1183. Database::query($sql);
  1184. }
  1185. }
  1186. /**
  1187. * Updates an item's content in place
  1188. * @param integer $id Element ID
  1189. * @param integer $parent Parent item ID
  1190. * @param integer $previous Previous item ID
  1191. * @param string $title Item title
  1192. * @param string $description Item description
  1193. * @param string $prerequisites Prerequisites (optional)
  1194. * @param array $audio The array resulting of the $_FILES[mp3] element
  1195. * @param int $max_time_allowed
  1196. * @param string $url
  1197. * @return boolean True on success, false on error
  1198. */
  1199. public function edit_item(
  1200. $id,
  1201. $parent,
  1202. $previous,
  1203. $title,
  1204. $description,
  1205. $prerequisites = '0',
  1206. $audio = [],
  1207. $max_time_allowed = 0,
  1208. $url = ''
  1209. ) {
  1210. $course_id = api_get_course_int_id();
  1211. $_course = api_get_course_info();
  1212. if ($this->debug > 0) {
  1213. error_log('New LP - In learnpath::edit_item()', 0);
  1214. }
  1215. if (empty($max_time_allowed)) {
  1216. $max_time_allowed = 0;
  1217. }
  1218. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1219. return false;
  1220. }
  1221. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1222. $sql = "SELECT * FROM $tbl_lp_item
  1223. WHERE iid = $id";
  1224. $res_select = Database::query($sql);
  1225. $row_select = Database::fetch_array($res_select);
  1226. $audio_update_sql = '';
  1227. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1228. // Create the audio folder if it does not exist yet.
  1229. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1230. if (!is_dir($filepath.'audio')) {
  1231. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1232. $audio_id = add_document(
  1233. $_course,
  1234. '/audio',
  1235. 'folder',
  1236. 0,
  1237. 'audio'
  1238. );
  1239. api_item_property_update(
  1240. $_course,
  1241. TOOL_DOCUMENT,
  1242. $audio_id,
  1243. 'FolderCreated',
  1244. api_get_user_id(),
  1245. null,
  1246. null,
  1247. null,
  1248. null,
  1249. api_get_session_id()
  1250. );
  1251. api_item_property_update(
  1252. $_course,
  1253. TOOL_DOCUMENT,
  1254. $audio_id,
  1255. 'invisible',
  1256. api_get_user_id(),
  1257. null,
  1258. null,
  1259. null,
  1260. null,
  1261. api_get_session_id()
  1262. );
  1263. }
  1264. // Upload file in documents.
  1265. $pi = pathinfo($audio['name']);
  1266. if ($pi['extension'] == 'mp3') {
  1267. $c_det = api_get_course_info($this->cc);
  1268. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1269. $path = handle_uploaded_document(
  1270. $c_det,
  1271. $audio,
  1272. $bp,
  1273. '/audio',
  1274. api_get_user_id(),
  1275. 0,
  1276. null,
  1277. 0,
  1278. 'rename',
  1279. false,
  1280. 0
  1281. );
  1282. $path = substr($path, 7);
  1283. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1284. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1285. }
  1286. }
  1287. $same_parent = ($row_select['parent_item_id'] == $parent) ? true : false;
  1288. $same_previous = ($row_select['previous_item_id'] == $previous) ? true : false;
  1289. // TODO: htmlspecialchars to be checked for encoding related problems.
  1290. if ($same_parent && $same_previous) {
  1291. // Only update title and description.
  1292. $sql = "UPDATE $tbl_lp_item
  1293. SET title = '" . Database::escape_string($title)."',
  1294. prerequisite = '".$prerequisites."',
  1295. description = '".Database::escape_string($description)."'
  1296. ".$audio_update_sql.",
  1297. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1298. WHERE iid = $id";
  1299. Database::query($sql);
  1300. } else {
  1301. $old_parent = $row_select['parent_item_id'];
  1302. $old_previous = $row_select['previous_item_id'];
  1303. $old_next = $row_select['next_item_id'];
  1304. $old_order = $row_select['display_order'];
  1305. $old_prerequisite = $row_select['prerequisite'];
  1306. $old_max_time_allowed = $row_select['max_time_allowed'];
  1307. /* BEGIN -- virtually remove the current item id */
  1308. /* for the next and previous item it is like the current item doesn't exist anymore */
  1309. if ($old_previous != 0) {
  1310. // Next
  1311. $sql = "UPDATE $tbl_lp_item
  1312. SET next_item_id = $old_next
  1313. WHERE iid = $old_previous";
  1314. Database::query($sql);
  1315. }
  1316. if ($old_next != 0) {
  1317. // Previous
  1318. $sql = "UPDATE $tbl_lp_item
  1319. SET previous_item_id = $old_previous
  1320. WHERE iid = $old_next";
  1321. Database::query($sql);
  1322. }
  1323. // display_order - 1 for every item with a display_order
  1324. // bigger then the display_order of the current item.
  1325. $sql = "UPDATE $tbl_lp_item
  1326. SET display_order = display_order - 1
  1327. WHERE
  1328. c_id = $course_id AND
  1329. display_order > $old_order AND
  1330. lp_id = ".$this->lp_id." AND
  1331. parent_item_id = $old_parent";
  1332. Database::query($sql);
  1333. /* END -- virtually remove the current item id */
  1334. /* BEGIN -- update the current item id to his new location */
  1335. if ($previous == 0) {
  1336. // Select the data of the item that should come after the current item.
  1337. $sql = "SELECT id, display_order
  1338. FROM $tbl_lp_item
  1339. WHERE
  1340. c_id = $course_id AND
  1341. lp_id = ".$this->lp_id." AND
  1342. parent_item_id = $parent AND
  1343. previous_item_id = $previous";
  1344. $res_select_old = Database::query($sql);
  1345. $row_select_old = Database::fetch_array($res_select_old);
  1346. // If the new parent didn't have children before.
  1347. if (Database::num_rows($res_select_old) == 0) {
  1348. $new_next = 0;
  1349. $new_order = 1;
  1350. } else {
  1351. $new_next = $row_select_old['id'];
  1352. $new_order = $row_select_old['display_order'];
  1353. }
  1354. } else {
  1355. // Select the data of the item that should come before the current item.
  1356. $sql = "SELECT next_item_id, display_order
  1357. FROM $tbl_lp_item
  1358. WHERE iid = $previous";
  1359. $res_select_old = Database::query($sql);
  1360. $row_select_old = Database::fetch_array($res_select_old);
  1361. $new_next = $row_select_old['next_item_id'];
  1362. $new_order = $row_select_old['display_order'] + 1;
  1363. }
  1364. // TODO: htmlspecialchars to be checked for encoding related problems.
  1365. // Update the current item with the new data.
  1366. $sql = "UPDATE $tbl_lp_item
  1367. SET
  1368. title = '".Database::escape_string($title)."',
  1369. description = '".Database::escape_string($description)."',
  1370. parent_item_id = $parent,
  1371. previous_item_id = $previous,
  1372. next_item_id = $new_next,
  1373. display_order = $new_order
  1374. $audio_update_sql
  1375. WHERE iid = $id";
  1376. Database::query($sql);
  1377. if ($previous != 0) {
  1378. // Update the previous item's next_item_id.
  1379. $sql = "UPDATE $tbl_lp_item
  1380. SET next_item_id = $id
  1381. WHERE iid = $previous";
  1382. Database::query($sql);
  1383. }
  1384. if ($new_next != 0) {
  1385. // Update the next item's previous_item_id.
  1386. $sql = "UPDATE $tbl_lp_item
  1387. SET previous_item_id = $id
  1388. WHERE iid = $new_next";
  1389. Database::query($sql);
  1390. }
  1391. if ($old_prerequisite != $prerequisites) {
  1392. $sql = "UPDATE $tbl_lp_item
  1393. SET prerequisite = '$prerequisites'
  1394. WHERE iid = $id";
  1395. Database::query($sql);
  1396. }
  1397. if ($old_max_time_allowed != $max_time_allowed) {
  1398. // update max time allowed
  1399. $sql = "UPDATE $tbl_lp_item
  1400. SET max_time_allowed = $max_time_allowed
  1401. WHERE iid = $id";
  1402. Database::query($sql);
  1403. }
  1404. // Update all the items with the same or a bigger display_order than the current item.
  1405. $sql = "UPDATE $tbl_lp_item
  1406. SET display_order = display_order + 1
  1407. WHERE
  1408. c_id = $course_id AND
  1409. lp_id = ".$this->get_id()." AND
  1410. iid <> $id AND
  1411. parent_item_id = $parent AND
  1412. display_order >= $new_order";
  1413. Database::query($sql);
  1414. }
  1415. if ($row_select['item_type'] == 'link') {
  1416. $link = new Link();
  1417. $linkId = $row_select['path'];
  1418. $link->updateLink($linkId, $url);
  1419. }
  1420. }
  1421. /**
  1422. * Updates an item's prereq in place
  1423. * @param integer $id Element ID
  1424. * @param string $prerequisite_id Prerequisite Element ID
  1425. * @param int $mastery_score Prerequisite min score
  1426. * @param int $max_score Prerequisite max score
  1427. *
  1428. * @return boolean True on success, false on error
  1429. */
  1430. public function edit_item_prereq(
  1431. $id,
  1432. $prerequisite_id,
  1433. $mastery_score = 0,
  1434. $max_score = 100
  1435. ) {
  1436. $course_id = api_get_course_int_id();
  1437. if ($this->debug > 0) {
  1438. error_log('New LP - In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','.$max_score.')', 0);
  1439. }
  1440. if (empty($id) || ($id != strval(intval($id))) || empty($prerequisite_id)) {
  1441. return false;
  1442. }
  1443. $prerequisite_id = intval($prerequisite_id);
  1444. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1445. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1446. $mastery_score = 0;
  1447. }
  1448. if (!is_numeric($max_score) || $max_score < 0) {
  1449. $max_score = 100;
  1450. }
  1451. /*if ($mastery_score > $max_score) {
  1452. $max_score = $mastery_score;
  1453. }*/
  1454. if (!is_numeric($prerequisite_id)) {
  1455. $prerequisite_id = 'NULL';
  1456. }
  1457. $mastery_score = floatval($mastery_score);
  1458. $max_score = floatval($max_score);
  1459. $sql = " UPDATE $tbl_lp_item
  1460. SET
  1461. prerequisite = $prerequisite_id ,
  1462. prerequisite_min_score = $mastery_score ,
  1463. prerequisite_max_score = $max_score
  1464. WHERE iid = $id";
  1465. Database::query($sql);
  1466. // TODO: Update the item object (can be ignored for now because refreshed).
  1467. return true;
  1468. }
  1469. /**
  1470. * Gets all the chapters belonging to the same parent as the item/chapter given
  1471. * Can also be called as abstract method
  1472. * @param integer $id Item ID
  1473. * @return array A list of all the "brother items" (or an empty array on failure)
  1474. */
  1475. public function getSiblingDirectories($id)
  1476. {
  1477. $course_id = api_get_course_int_id();
  1478. if ($this->debug > 0) {
  1479. error_log('New LP - In learnpath::getSiblingDirectories()', 0);
  1480. }
  1481. if (empty($id) || $id != strval(intval($id))) {
  1482. return [];
  1483. }
  1484. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1485. $sql_parent = "SELECT * FROM $lp_item
  1486. WHERE iid = $id AND item_type='dir'";
  1487. $res_parent = Database::query($sql_parent);
  1488. if (Database::num_rows($res_parent) > 0) {
  1489. $row_parent = Database::fetch_array($res_parent);
  1490. $parent = $row_parent['parent_item_id'];
  1491. $sql = "SELECT * FROM $lp_item
  1492. WHERE
  1493. parent_item_id = $parent AND
  1494. iid = $id AND
  1495. item_type='dir'
  1496. ORDER BY display_order";
  1497. $res_bros = Database::query($sql);
  1498. $list = [];
  1499. while ($row_bro = Database::fetch_array($res_bros)) {
  1500. $list[] = $row_bro;
  1501. }
  1502. return $list;
  1503. }
  1504. return [];
  1505. }
  1506. /**
  1507. * Gets all the items belonging to the same parent as the item given
  1508. * Can also be called as abstract method
  1509. * @param integer $id Item ID
  1510. * @return array A list of all the "brother items" (or an empty array on failure)
  1511. */
  1512. public function get_brother_items($id)
  1513. {
  1514. $course_id = api_get_course_int_id();
  1515. if ($this->debug > 0) {
  1516. error_log('New LP - In learnpath::get_brother_items('.$id.')', 0);
  1517. }
  1518. if (empty($id) || $id != strval(intval($id))) {
  1519. return [];
  1520. }
  1521. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1522. $sql_parent = "SELECT * FROM $lp_item
  1523. WHERE iid = $id";
  1524. $res_parent = Database::query($sql_parent);
  1525. if (Database::num_rows($res_parent) > 0) {
  1526. $row_parent = Database::fetch_array($res_parent);
  1527. $parent = $row_parent['parent_item_id'];
  1528. $sql = "SELECT * FROM $lp_item
  1529. WHERE c_id = $course_id AND parent_item_id = $parent
  1530. ORDER BY display_order";
  1531. $res_bros = Database::query($sql);
  1532. $list = [];
  1533. while ($row_bro = Database::fetch_array($res_bros)) {
  1534. $list[] = $row_bro;
  1535. }
  1536. return $list;
  1537. }
  1538. return [];
  1539. }
  1540. /**
  1541. * Get the specific prefix index terms of this learning path
  1542. * @param string $prefix
  1543. * @return array Array of terms
  1544. */
  1545. public function get_common_index_terms_by_prefix($prefix)
  1546. {
  1547. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1548. $terms = get_specific_field_values_list_by_prefix(
  1549. $prefix,
  1550. $this->cc,
  1551. TOOL_LEARNPATH,
  1552. $this->lp_id
  1553. );
  1554. $prefix_terms = [];
  1555. if (!empty($terms)) {
  1556. foreach ($terms as $term) {
  1557. $prefix_terms[] = $term['value'];
  1558. }
  1559. }
  1560. return $prefix_terms;
  1561. }
  1562. /**
  1563. * Gets the number of items currently completed
  1564. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1565. * @return integer The number of items currently completed
  1566. */
  1567. public function get_complete_items_count($failedStatusException = false)
  1568. {
  1569. if ($this->debug > 0) {
  1570. error_log('New LP - In learnpath::get_complete_items_count()', 0);
  1571. }
  1572. $i = 0;
  1573. $completedStatusList = [
  1574. 'completed',
  1575. 'passed',
  1576. 'succeeded',
  1577. 'browsed'
  1578. ];
  1579. if (!$failedStatusException) {
  1580. $completedStatusList[] = 'failed';
  1581. }
  1582. foreach ($this->items as $id => $dummy) {
  1583. // Trying failed and browsed considered "progressed" as well.
  1584. if ($this->items[$id]->status_is($completedStatusList) &&
  1585. $this->items[$id]->get_type() != 'dir'
  1586. ) {
  1587. $i++;
  1588. }
  1589. }
  1590. return $i;
  1591. }
  1592. /**
  1593. * Gets the current item ID
  1594. * @return integer The current learnpath item id
  1595. */
  1596. public function get_current_item_id()
  1597. {
  1598. $current = 0;
  1599. if ($this->debug > 0) {
  1600. error_log('New LP - In learnpath::get_current_item_id()', 0);
  1601. }
  1602. if (!empty($this->current)) {
  1603. $current = $this->current;
  1604. }
  1605. if ($this->debug > 2) {
  1606. error_log('New LP - In learnpath::get_current_item_id() - Returning '.$current, 0);
  1607. }
  1608. return $current;
  1609. }
  1610. /**
  1611. * Force to get the first learnpath item id
  1612. * @return integer The current learnpath item id
  1613. */
  1614. public function get_first_item_id()
  1615. {
  1616. $current = 0;
  1617. if (is_array($this->ordered_items)) {
  1618. $current = $this->ordered_items[0];
  1619. }
  1620. return $current;
  1621. }
  1622. /**
  1623. * Gets the total number of items available for viewing in this SCORM
  1624. * @return integer The total number of items
  1625. */
  1626. public function get_total_items_count()
  1627. {
  1628. if ($this->debug > 0) {
  1629. error_log('New LP - In learnpath::get_total_items_count()', 0);
  1630. }
  1631. return count($this->items);
  1632. }
  1633. /**
  1634. * Gets the total number of items available for viewing in this SCORM but without chapters
  1635. * @return integer The total no-chapters number of items
  1636. */
  1637. public function getTotalItemsCountWithoutDirs()
  1638. {
  1639. if ($this->debug > 0) {
  1640. error_log('New LP - In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1641. }
  1642. $total = 0;
  1643. $typeListNotToCount = self::getChapterTypes();
  1644. foreach ($this->items as $temp2) {
  1645. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1646. $total++;
  1647. }
  1648. }
  1649. return $total;
  1650. }
  1651. /**
  1652. * Sets the first element URL.
  1653. */
  1654. public function first()
  1655. {
  1656. if ($this->debug > 0) {
  1657. error_log('New LP - In learnpath::first()', 0);
  1658. error_log('$this->last_item_seen '.$this->last_item_seen);
  1659. }
  1660. // Test if the last_item_seen exists and is not a dir.
  1661. if (count($this->ordered_items) == 0) {
  1662. $this->index = 0;
  1663. }
  1664. if ($this->debug > 0) {
  1665. if (isset($this->items[$this->last_item_seen])) {
  1666. $status = $this->items[$this->last_item_seen]->get_status();
  1667. }
  1668. }
  1669. if (!empty($this->last_item_seen) &&
  1670. !empty($this->items[$this->last_item_seen]) &&
  1671. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1672. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1673. //&& !$this->items[$this->last_item_seen]->is_done()
  1674. ) {
  1675. if ($this->debug > 2) {
  1676. error_log('New LP - In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.$this->items[$this->last_item_seen]->get_type(), 0);
  1677. }
  1678. $index = -1;
  1679. foreach ($this->ordered_items as $myindex => $item_id) {
  1680. if ($item_id == $this->last_item_seen) {
  1681. $index = $myindex;
  1682. break;
  1683. }
  1684. }
  1685. if ($index == -1) {
  1686. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1687. if ($this->debug > 2) {
  1688. error_log('New LP - Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1689. }
  1690. return false;
  1691. } else {
  1692. $this->last = $this->last_item_seen;
  1693. $this->current = $this->last_item_seen;
  1694. $this->index = $index;
  1695. }
  1696. } else {
  1697. if ($this->debug > 2) {
  1698. error_log('New LP - In learnpath::first() - No last item seen', 0);
  1699. }
  1700. $index = 0;
  1701. // Loop through all ordered items and stop at the first item that is
  1702. // not a directory *and* that has not been completed yet.
  1703. while (!empty($this->ordered_items[$index]) &&
  1704. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1705. (
  1706. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1707. $this->items[$this->ordered_items[$index]]->is_done() === true
  1708. ) && $index < $this->max_ordered_items) {
  1709. $index++;
  1710. }
  1711. $this->last = $this->current;
  1712. // current is
  1713. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1714. $this->index = $index;
  1715. if ($this->debug > 2) {
  1716. error_log('$index '.$index);
  1717. error_log('New LP - In learnpath::first() - No last item seen. New last = '.$this->last.'('.$this->ordered_items[$index].')', 0);
  1718. }
  1719. }
  1720. if ($this->debug > 2) {
  1721. error_log('New LP - In learnpath::first() - First item is '.$this->get_current_item_id());
  1722. }
  1723. }
  1724. /**
  1725. * Gets the information about an item in a format usable as JavaScript to update
  1726. * the JS API by just printing this content into the <head> section of the message frame
  1727. * @param int $item_id
  1728. * @return string
  1729. */
  1730. public function get_js_info($item_id = 0)
  1731. {
  1732. if ($this->debug > 0) {
  1733. error_log('New LP - In learnpath::get_js_info('.$item_id.')', 0);
  1734. }
  1735. $info = '';
  1736. $item_id = intval($item_id);
  1737. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1738. //if item is defined, return values from DB
  1739. $oItem = $this->items[$item_id];
  1740. $info .= '<script language="javascript">';
  1741. $info .= "top.set_score(".$oItem->get_score().");\n";
  1742. $info .= "top.set_max(".$oItem->get_max().");\n";
  1743. $info .= "top.set_min(".$oItem->get_min().");\n";
  1744. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1745. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1746. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1747. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1748. $info .= "top.set_flag_synchronized();";
  1749. $info .= '</script>';
  1750. if ($this->debug > 2) {
  1751. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1752. }
  1753. return $info;
  1754. } else {
  1755. // If item_id is empty, just update to default SCORM data.
  1756. $info .= '<script language="javascript">';
  1757. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1758. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1759. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1760. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1761. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1762. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1763. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1764. $info .= "top.set_flag_synchronized();";
  1765. $info .= '</script>';
  1766. if ($this->debug > 2) {
  1767. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1768. }
  1769. return $info;
  1770. }
  1771. }
  1772. /**
  1773. * Gets the js library from the database
  1774. * @return string The name of the javascript library to be used
  1775. */
  1776. public function get_js_lib()
  1777. {
  1778. $lib = '';
  1779. if (!empty($this->js_lib)) {
  1780. $lib = $this->js_lib;
  1781. }
  1782. return $lib;
  1783. }
  1784. /**
  1785. * Gets the learnpath database ID
  1786. * @return integer Learnpath ID in the lp table
  1787. */
  1788. public function get_id()
  1789. {
  1790. if (!empty($this->lp_id)) {
  1791. return $this->lp_id;
  1792. } else {
  1793. return 0;
  1794. }
  1795. }
  1796. /**
  1797. * Gets the last element URL.
  1798. * @return string URL to load into the viewer
  1799. */
  1800. public function get_last()
  1801. {
  1802. if ($this->debug > 0) {
  1803. error_log('New LP - In learnpath::get_last()', 0);
  1804. }
  1805. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1806. if (count($this->ordered_items) > 0) {
  1807. $this->index = count($this->ordered_items) - 1;
  1808. return $this->ordered_items[$this->index];
  1809. }
  1810. return false;
  1811. }
  1812. /**
  1813. * Gets the navigation bar for the learnpath display screen
  1814. * @return string The HTML string to use as a navigation bar
  1815. */
  1816. public function get_navigation_bar($idBar = null, $display = null)
  1817. {
  1818. if ($this->debug > 0) {
  1819. error_log('New LP - In learnpath::get_navigation_bar()', 0);
  1820. }
  1821. if (empty($idBar)) {
  1822. $idBar = 'control-top';
  1823. }
  1824. $navbar = null;
  1825. $lp_id = $this->lp_id;
  1826. $mycurrentitemid = $this->get_current_item_id();
  1827. $reportingText = get_lang('Reporting');
  1828. $previousText = get_lang('ScormPrevious');
  1829. $nextText = get_lang('ScormNext');
  1830. $fullScreenText = get_lang('ScormExitFullScreen');
  1831. if ($this->mode == 'fullscreen') {
  1832. $navbar = '
  1833. <span id="'.$idBar.'" class="buttons">
  1834. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1835. <span class="fa fa-info"></span><span class="sr-only">' . $reportingText.'</span>
  1836. </a>
  1837. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1838. <span class="fa fa-chevron-left"></span><span class="sr-only">' . $previousText.'</span>
  1839. </a>
  1840. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1841. <span class="fa fa-chevron-right"></span><span class="sr-only">' . $nextText.'</span>
  1842. </a>
  1843. <a class="icon-toolbar" id="view-embedded" href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1844. <span class="fa fa-columns"></span><span class="sr-only">' . $fullScreenText.'</span>
  1845. </a>
  1846. </span>';
  1847. } else {
  1848. $navbar = '
  1849. <span id="'.$idBar.'" class="buttons text-right">
  1850. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id.'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1851. <span class="fa fa-info"></span><span class="sr-only">' . $reportingText.'</span>
  1852. </a>
  1853. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item(' . $mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1854. <span class="fa fa-chevron-left"></span><span class="sr-only">' . $previousText.'</span>
  1855. </a>
  1856. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item(' . $mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1857. <span class="fa fa-chevron-right"></span><span class="sr-only">' . $nextText.'</span>
  1858. </a>
  1859. </span>';
  1860. }
  1861. return $navbar;
  1862. }
  1863. /**
  1864. * Gets the next resource in queue (url).
  1865. * @return string URL to load into the viewer
  1866. */
  1867. public function get_next_index()
  1868. {
  1869. if ($this->debug > 0) {
  1870. error_log('New LP - In learnpath::get_next_index()', 0);
  1871. }
  1872. // TODO
  1873. $index = $this->index;
  1874. $index++;
  1875. if ($this->debug > 2) {
  1876. error_log('New LP - Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1877. }
  1878. while (
  1879. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1880. $index < $this->max_ordered_items
  1881. ) {
  1882. $index++;
  1883. if ($index == $this->max_ordered_items) {
  1884. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1885. return $this->index;
  1886. } else {
  1887. return $index;
  1888. }
  1889. }
  1890. }
  1891. if (empty($this->ordered_items[$index])) {
  1892. return $this->index;
  1893. }
  1894. if ($this->debug > 2) {
  1895. error_log('New LP - index is now '.$index, 0);
  1896. }
  1897. return $index;
  1898. }
  1899. /**
  1900. * Gets item_id for the next element
  1901. * @return integer Next item (DB) ID
  1902. */
  1903. public function get_next_item_id()
  1904. {
  1905. if ($this->debug > 0) {
  1906. error_log('New LP - In learnpath::get_next_item_id()', 0);
  1907. }
  1908. $new_index = $this->get_next_index();
  1909. if (!empty($new_index)) {
  1910. if (isset($this->ordered_items[$new_index])) {
  1911. if ($this->debug > 2) {
  1912. error_log('New LP - In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1913. }
  1914. return $this->ordered_items[$new_index];
  1915. }
  1916. }
  1917. if ($this->debug > 2) {
  1918. error_log('New LP - In learnpath::get_next_index() - Problem - Returning 0', 0);
  1919. }
  1920. return 0;
  1921. }
  1922. /**
  1923. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...)
  1924. *
  1925. * Generally, the package provided is in the form of a zip file, so the function
  1926. * has been written to test a zip file. If not a zip, the function will return the
  1927. * default return value: ''
  1928. * @param string the path to the file
  1929. * @param string the original name of the file
  1930. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1931. */
  1932. public static function get_package_type($file_path, $file_name)
  1933. {
  1934. // Get name of the zip file without the extension.
  1935. $file_info = pathinfo($file_name);
  1936. $filename = $file_info['basename']; // Name including extension.
  1937. $extension = $file_info['extension']; // Extension only.
  1938. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1939. 'dll',
  1940. 'exe'
  1941. ])) {
  1942. return 'oogie';
  1943. }
  1944. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1945. 'dll',
  1946. 'exe'
  1947. ])) {
  1948. return 'woogie';
  1949. }
  1950. $zipFile = new PclZip($file_path);
  1951. // Check the zip content (real size and file extension).
  1952. $zipContentArray = $zipFile->listContent();
  1953. $package_type = '';
  1954. $at_root = false;
  1955. $manifest = '';
  1956. $aicc_match_crs = 0;
  1957. $aicc_match_au = 0;
  1958. $aicc_match_des = 0;
  1959. $aicc_match_cst = 0;
  1960. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1961. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1962. foreach ($zipContentArray as $thisContent) {
  1963. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1964. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1965. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1966. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1967. $package_type = 'scorm';
  1968. break; // Exit the foreach loop.
  1969. } elseif (
  1970. preg_match('/aicc\//i', $thisContent['filename']) ||
  1971. in_array(
  1972. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1973. ['crs', 'au', 'des', 'cst']
  1974. )
  1975. ) {
  1976. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  1977. switch ($ext) {
  1978. case 'crs':
  1979. $aicc_match_crs = 1;
  1980. break;
  1981. case 'au':
  1982. $aicc_match_au = 1;
  1983. break;
  1984. case 'des':
  1985. $aicc_match_des = 1;
  1986. break;
  1987. case 'cst':
  1988. $aicc_match_cst = 1;
  1989. break;
  1990. default:
  1991. break;
  1992. }
  1993. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  1994. } else {
  1995. $package_type = '';
  1996. }
  1997. }
  1998. }
  1999. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2000. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2001. $package_type = 'aicc';
  2002. }
  2003. return $package_type;
  2004. }
  2005. /**
  2006. * Gets the previous resource in queue (url). Also initialises time values for this viewing
  2007. * @return string URL to load into the viewer
  2008. */
  2009. public function get_previous_index()
  2010. {
  2011. if ($this->debug > 0) {
  2012. error_log('New LP - In learnpath::get_previous_index()', 0);
  2013. }
  2014. $index = $this->index;
  2015. if (isset($this->ordered_items[$index - 1])) {
  2016. $index--;
  2017. while (isset($this->ordered_items[$index]) &&
  2018. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2019. ) {
  2020. $index--;
  2021. if ($index < 0) {
  2022. return $this->index;
  2023. }
  2024. }
  2025. } else {
  2026. if ($this->debug > 2) {
  2027. error_log('New LP - get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2028. }
  2029. // There is no previous item.
  2030. }
  2031. return $index;
  2032. }
  2033. /**
  2034. * Gets item_id for the next element
  2035. * @return integer Previous item (DB) ID
  2036. */
  2037. public function get_previous_item_id()
  2038. {
  2039. if ($this->debug > 0) {
  2040. error_log('New LP - In learnpath::get_previous_item_id()', 0);
  2041. }
  2042. $new_index = $this->get_previous_index();
  2043. return $this->ordered_items[$new_index];
  2044. }
  2045. /**
  2046. * Gets the progress value from the progress_db attribute
  2047. * @return integer Current progress value
  2048. * @deprecated This method does not seem to be used as of 20170514
  2049. */
  2050. public function get_progress()
  2051. {
  2052. if ($this->debug > 0) {
  2053. error_log('New LP - In learnpath::get_progress()', 0);
  2054. }
  2055. if (!empty($this->progress_db)) {
  2056. return $this->progress_db;
  2057. }
  2058. return 0;
  2059. }
  2060. /**
  2061. * Returns the HTML necessary to print a mediaplayer block inside a page
  2062. * @param int $lpItemId
  2063. * @param string $autostart
  2064. * @return string The mediaplayer HTML
  2065. */
  2066. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2067. {
  2068. $course_id = api_get_course_int_id();
  2069. $_course = api_get_course_info();
  2070. if (empty($_course)) {
  2071. return '';
  2072. }
  2073. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2074. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2075. // Getting all the information about the item.
  2076. $sql = "SELECT * FROM $tbl_lp_item as lpi
  2077. INNER JOIN $tbl_lp_item_view as lp_view
  2078. ON (lpi.iid = lp_view.lp_item_id)
  2079. WHERE
  2080. lpi.iid = $lpItemId AND
  2081. lp_view.c_id = $course_id";
  2082. $result = Database::query($sql);
  2083. $row = Database::fetch_assoc($result);
  2084. $output = '';
  2085. if (!empty($row['audio'])) {
  2086. $list = $_SESSION['oLP']->get_toc();
  2087. $type_quiz = false;
  2088. foreach ($list as $toc) {
  2089. if ($toc['id'] == $_SESSION['oLP']->current && ($toc['type'] == 'quiz')) {
  2090. $type_quiz = true;
  2091. }
  2092. }
  2093. if ($type_quiz) {
  2094. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2095. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2096. } else {
  2097. $autostart_audio = $autostart;
  2098. }
  2099. } else {
  2100. $autostart_audio = 'true';
  2101. }
  2102. $courseInfo = api_get_course_info();
  2103. $audio = $row['audio'];
  2104. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2105. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2106. if (!file_exists($file)) {
  2107. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2108. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2109. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2110. }
  2111. $player = Display::getMediaPlayer(
  2112. $file,
  2113. [
  2114. 'id' => 'lp_audio_media_player',
  2115. 'url' => $url,
  2116. 'autoplay' => $autostart_audio,
  2117. 'width' => '100%'
  2118. ]
  2119. );
  2120. // The mp3 player.
  2121. $output = '<div id="container">';
  2122. $output .= $player;
  2123. $output .= '</div>';
  2124. }
  2125. return $output;
  2126. }
  2127. /**
  2128. * @param int $studentId
  2129. * @param int $prerequisite
  2130. * @param array $courseInfo
  2131. * @param int $sessionId
  2132. *
  2133. * @return bool
  2134. *
  2135. */
  2136. public static function isBlockedByPrerequisite(
  2137. $studentId,
  2138. $prerequisite,
  2139. $courseInfo,
  2140. $sessionId
  2141. ) {
  2142. $isBlocked = false;
  2143. if (!empty($prerequisite)) {
  2144. $progress = self::getProgress(
  2145. $prerequisite,
  2146. $studentId,
  2147. $courseInfo['real_id'],
  2148. $sessionId
  2149. );
  2150. if ($progress < 100) {
  2151. $isBlocked = true;
  2152. }
  2153. }
  2154. return $isBlocked;
  2155. }
  2156. /**
  2157. * Checks if the learning path is visible for student after the progress
  2158. * of its prerequisite is completed, considering the time availability and
  2159. * the LP visibility.
  2160. * @param int $lp_id
  2161. * @param int $student_id
  2162. * @param string Course code (optional)
  2163. * @param int $sessionId
  2164. * @return bool
  2165. */
  2166. public static function is_lp_visible_for_student(
  2167. $lp_id,
  2168. $student_id,
  2169. $courseCode = null,
  2170. $sessionId = 0
  2171. ) {
  2172. $courseInfo = api_get_course_info($courseCode);
  2173. $lp_id = (int) $lp_id;
  2174. $sessionId = (int) $sessionId;
  2175. if (empty($courseInfo)) {
  2176. return false;
  2177. }
  2178. if (empty($sessionId)) {
  2179. $sessionId = api_get_session_id();
  2180. }
  2181. $itemInfo = api_get_item_property_info(
  2182. $courseInfo['real_id'],
  2183. TOOL_LEARNPATH,
  2184. $lp_id,
  2185. $sessionId
  2186. );
  2187. // If the item was deleted.
  2188. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2189. return false;
  2190. }
  2191. // @todo remove this query and load the row info as a parameter
  2192. $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
  2193. // Get current prerequisite
  2194. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2195. FROM $tbl_learnpath
  2196. WHERE iid = $lp_id";
  2197. $rs = Database::query($sql);
  2198. $now = time();
  2199. if (Database::num_rows($rs) > 0) {
  2200. $row = Database::fetch_array($rs, 'ASSOC');
  2201. $prerequisite = $row['prerequisite'];
  2202. $is_visible = true;
  2203. $isBlocked = self::isBlockedByPrerequisite(
  2204. $student_id,
  2205. $prerequisite,
  2206. $courseInfo,
  2207. $sessionId
  2208. );
  2209. if ($isBlocked) {
  2210. $is_visible = false;
  2211. }
  2212. // Also check the time availability of the LP
  2213. if ($is_visible) {
  2214. // Adding visibility restrictions
  2215. if (!empty($row['publicated_on'])) {
  2216. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2217. $is_visible = false;
  2218. }
  2219. }
  2220. // Blocking empty start times see BT#2800
  2221. global $_custom;
  2222. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2223. $_custom['lps_hidden_when_no_start_date']
  2224. ) {
  2225. if (empty($row['publicated_on'])) {
  2226. $is_visible = false;
  2227. }
  2228. }
  2229. if (!empty($row['expired_on'])) {
  2230. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2231. $is_visible = false;
  2232. }
  2233. }
  2234. }
  2235. // Check if the subscription users/group to a LP is ON
  2236. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1) {
  2237. // Try group
  2238. $is_visible = false;
  2239. // Checking only the user visibility
  2240. $userVisibility = api_get_item_visibility(
  2241. $courseInfo,
  2242. 'learnpath',
  2243. $row['id'],
  2244. $sessionId,
  2245. $student_id,
  2246. 'LearnpathSubscription'
  2247. );
  2248. if ($userVisibility == 1) {
  2249. $is_visible = true;
  2250. } else {
  2251. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2252. if (!empty($userGroups)) {
  2253. foreach ($userGroups as $groupInfo) {
  2254. $groupId = $groupInfo['iid'];
  2255. $userVisibility = api_get_item_visibility(
  2256. $courseInfo,
  2257. 'learnpath',
  2258. $row['id'],
  2259. $sessionId,
  2260. null,
  2261. 'LearnpathSubscription',
  2262. $groupId
  2263. );
  2264. if ($userVisibility == 1) {
  2265. $is_visible = true;
  2266. break;
  2267. }
  2268. }
  2269. }
  2270. }
  2271. }
  2272. return $is_visible;
  2273. }
  2274. return false;
  2275. }
  2276. /**
  2277. * @param int $lpId
  2278. * @param int $userId
  2279. * @param int $courseId
  2280. * @param int $sessionId
  2281. * @return int
  2282. */
  2283. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2284. {
  2285. $lpId = intval($lpId);
  2286. $userId = intval($userId);
  2287. $courseId = intval($courseId);
  2288. $sessionId = intval($sessionId);
  2289. $progress = 0;
  2290. $sessionCondition = api_get_session_condition($sessionId);
  2291. $table = Database::get_course_table(TABLE_LP_VIEW);
  2292. $sql = "SELECT * FROM $table
  2293. WHERE
  2294. c_id = $courseId AND
  2295. lp_id = $lpId AND
  2296. user_id = $userId $sessionCondition ";
  2297. $res = Database::query($sql);
  2298. if (Database::num_rows($res) > 0) {
  2299. $row = Database:: fetch_array($res);
  2300. $progress = $row['progress'];
  2301. }
  2302. return (int) $progress;
  2303. }
  2304. /**
  2305. * Displays a progress bar
  2306. * completed so far.
  2307. * @param integer $percentage Progress value to display
  2308. * @param string $text_add Text to display near the progress value
  2309. * @return string HTML string containing the progress bar
  2310. */
  2311. public static function get_progress_bar($percentage = -1, $text_add = '')
  2312. {
  2313. $text = $percentage.$text_add;
  2314. $output = '<div class="progress">
  2315. <div id="progress_bar_value"
  2316. class="progress-bar progress-bar-success" role="progressbar"
  2317. aria-valuenow="' .$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2318. '. $text.'
  2319. </div>
  2320. </div>';
  2321. return $output;
  2322. }
  2323. /**
  2324. * @param string $mode can be '%' or 'abs'
  2325. * otherwise this value will be used $this->progress_bar_mode
  2326. * @return string
  2327. */
  2328. public function getProgressBar($mode = null)
  2329. {
  2330. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2331. return self::get_progress_bar($percentage, $text_add);
  2332. }
  2333. /**
  2334. * Gets the progress bar info to display inside the progress bar.
  2335. * Also used by scorm_api.php
  2336. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2337. * we display a number of completed elements per total elements
  2338. * @param integer $add Additional steps to fake as completed
  2339. * @return array Percentage or number and symbol (% or /xx)
  2340. */
  2341. public function get_progress_bar_text($mode = '', $add = 0)
  2342. {
  2343. if ($this->debug > 0) {
  2344. error_log('New LP - In learnpath::get_progress_bar_text()', 0);
  2345. }
  2346. if (empty($mode)) {
  2347. $mode = $this->progress_bar_mode;
  2348. }
  2349. $total_items = $this->getTotalItemsCountWithoutDirs();
  2350. if ($this->debug > 2) {
  2351. error_log('New LP - Total items available in this learnpath: '.$total_items, 0);
  2352. }
  2353. $completeItems = $this->get_complete_items_count();
  2354. if ($this->debug > 2) {
  2355. error_log('New LP - Items completed so far: '.$completeItems, 0);
  2356. }
  2357. if ($add != 0) {
  2358. $completeItems += $add;
  2359. if ($this->debug > 2) {
  2360. error_log('New LP - Items completed so far (+modifier): '.$completeItems, 0);
  2361. }
  2362. }
  2363. $text = '';
  2364. if ($completeItems > $total_items) {
  2365. $completeItems = $total_items;
  2366. }
  2367. $percentage = 0;
  2368. if ($mode == '%') {
  2369. if ($total_items > 0) {
  2370. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2371. } else {
  2372. $percentage = 0;
  2373. }
  2374. $percentage = number_format($percentage, 0);
  2375. $text = '%';
  2376. } elseif ($mode == 'abs') {
  2377. $percentage = $completeItems;
  2378. $text = '/'.$total_items;
  2379. }
  2380. return [
  2381. $percentage,
  2382. $text
  2383. ];
  2384. }
  2385. /**
  2386. * Gets the progress bar mode
  2387. * @return string The progress bar mode attribute
  2388. */
  2389. public function get_progress_bar_mode()
  2390. {
  2391. if ($this->debug > 0) {
  2392. error_log('New LP - In learnpath::get_progress_bar_mode()', 0);
  2393. }
  2394. if (!empty($this->progress_bar_mode)) {
  2395. return $this->progress_bar_mode;
  2396. } else {
  2397. return '%';
  2398. }
  2399. }
  2400. /**
  2401. * Gets the learnpath proximity (remote or local)
  2402. * @return string Learnpath proximity
  2403. */
  2404. public function get_proximity()
  2405. {
  2406. if ($this->debug > 0) {
  2407. error_log('New LP - In learnpath::get_proximity()', 0);
  2408. }
  2409. if (!empty($this->proximity)) {
  2410. return $this->proximity;
  2411. } else {
  2412. return '';
  2413. }
  2414. }
  2415. /**
  2416. * Gets the learnpath theme (remote or local)
  2417. * @return string Learnpath theme
  2418. */
  2419. public function get_theme()
  2420. {
  2421. if ($this->debug > 0) {
  2422. error_log('New LP - In learnpath::get_theme()', 0);
  2423. }
  2424. if (!empty($this->theme)) {
  2425. return $this->theme;
  2426. } else {
  2427. return '';
  2428. }
  2429. }
  2430. /**
  2431. * Gets the learnpath session id
  2432. * @return int
  2433. */
  2434. public function get_lp_session_id()
  2435. {
  2436. if ($this->debug > 0) {
  2437. error_log('New LP - In learnpath::get_lp_session_id()', 0);
  2438. }
  2439. if (!empty($this->lp_session_id)) {
  2440. return (int) $this->lp_session_id;
  2441. } else {
  2442. return 0;
  2443. }
  2444. }
  2445. /**
  2446. * Gets the learnpath image
  2447. * @return string Web URL of the LP image
  2448. */
  2449. public function get_preview_image()
  2450. {
  2451. if ($this->debug > 0) {
  2452. error_log('New LP - In learnpath::get_preview_image()', 0);
  2453. }
  2454. if (!empty($this->preview_image)) {
  2455. return $this->preview_image;
  2456. } else {
  2457. return '';
  2458. }
  2459. }
  2460. /**
  2461. * @param string $size
  2462. * @param string $path_type
  2463. * @return bool|string
  2464. */
  2465. public function get_preview_image_path($size = null, $path_type = 'web')
  2466. {
  2467. $preview_image = $this->get_preview_image();
  2468. if (isset($preview_image) && !empty($preview_image)) {
  2469. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2470. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2471. if (isset($size)) {
  2472. $info = pathinfo($preview_image);
  2473. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2474. if (file_exists($image_sys_path.$image_custom_size)) {
  2475. if ($path_type == 'web') {
  2476. return $image_path.$image_custom_size;
  2477. } else {
  2478. return $image_sys_path.$image_custom_size;
  2479. }
  2480. }
  2481. } else {
  2482. if ($path_type == 'web') {
  2483. return $image_path.$preview_image;
  2484. } else {
  2485. return $image_sys_path.$preview_image;
  2486. }
  2487. }
  2488. }
  2489. return false;
  2490. }
  2491. /**
  2492. * Gets the learnpath author
  2493. * @return string LP's author
  2494. */
  2495. public function get_author()
  2496. {
  2497. if ($this->debug > 0) {
  2498. error_log('New LP - In learnpath::get_author()', 0);
  2499. }
  2500. if (!empty($this->author)) {
  2501. return $this->author;
  2502. } else {
  2503. return '';
  2504. }
  2505. }
  2506. /**
  2507. * Gets hide table of contents
  2508. * @return int
  2509. */
  2510. public function getHideTableOfContents()
  2511. {
  2512. return (int) $this->hide_toc_frame;
  2513. }
  2514. /**
  2515. * Generate a new prerequisites string for a given item. If this item was a sco and
  2516. * its prerequisites were strings (instead of IDs), then transform those strings into
  2517. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2518. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2519. * same rule as the scorm_export() method
  2520. * @param integer Item ID
  2521. * @return string Prerequisites string ready for the export as SCORM
  2522. */
  2523. public function get_scorm_prereq_string($item_id)
  2524. {
  2525. if ($this->debug > 0) {
  2526. error_log('New LP - In learnpath::get_scorm_prereq_string()');
  2527. }
  2528. if (!is_object($this->items[$item_id])) {
  2529. return false;
  2530. }
  2531. /** @var learnpathItem $oItem */
  2532. $oItem = $this->items[$item_id];
  2533. $prereq = $oItem->get_prereq_string();
  2534. if (empty($prereq)) {
  2535. return '';
  2536. }
  2537. if (preg_match('/^\d+$/', $prereq) && is_object($this->items[$prereq])) {
  2538. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2539. // then simply return it (with the ITEM_ prefix).
  2540. //return 'ITEM_' . $prereq;
  2541. return $this->items[$prereq]->ref;
  2542. } else {
  2543. if (isset($this->refs_list[$prereq])) {
  2544. // It's a simple string item from which the ID can be found in the refs list,
  2545. // so we can transform it directly to an ID for export.
  2546. return $this->items[$this->refs_list[$prereq]]->ref;
  2547. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2548. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2549. } else {
  2550. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2551. // and replace them, one by one, by the internal IDs (chamilo db)
  2552. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2553. // by a space as well.
  2554. $find = [
  2555. '&',
  2556. '|',
  2557. '~',
  2558. '=',
  2559. '<>',
  2560. '{',
  2561. '}',
  2562. '*',
  2563. '(',
  2564. ')'
  2565. ];
  2566. $replace = [
  2567. ' ',
  2568. ' ',
  2569. ' ',
  2570. ' ',
  2571. ' ',
  2572. ' ',
  2573. ' ',
  2574. ' ',
  2575. ' ',
  2576. ' '
  2577. ];
  2578. $prereq_mod = str_replace($find, $replace, $prereq);
  2579. $ids = explode(' ', $prereq_mod);
  2580. foreach ($ids as $id) {
  2581. $id = trim($id);
  2582. if (isset($this->refs_list[$id])) {
  2583. $prereq = preg_replace(
  2584. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2585. 'ITEM_'.$this->refs_list[$id],
  2586. $prereq
  2587. );
  2588. }
  2589. }
  2590. return $prereq;
  2591. }
  2592. }
  2593. }
  2594. /**
  2595. * Returns the XML DOM document's node
  2596. * @param resource Reference to a list of objects to search for the given ITEM_*
  2597. * @param string The identifier to look for
  2598. * @return mixed The reference to the element found with that identifier. False if not found
  2599. */
  2600. public function get_scorm_xml_node(& $children, $id)
  2601. {
  2602. for ($i = 0; $i < $children->length; $i++) {
  2603. $item_temp = $children->item($i);
  2604. if ($item_temp->nodeName == 'item') {
  2605. if ($item_temp->getAttribute('identifier') == $id) {
  2606. return $item_temp;
  2607. }
  2608. }
  2609. $subchildren = $item_temp->childNodes;
  2610. if ($subchildren && $subchildren->length > 0) {
  2611. $val = $this->get_scorm_xml_node($subchildren, $id);
  2612. if (is_object($val)) {
  2613. return $val;
  2614. }
  2615. }
  2616. }
  2617. return false;
  2618. }
  2619. /**
  2620. * Gets the status list for all LP's items
  2621. * @return array Array of [index] => [item ID => current status]
  2622. */
  2623. public function get_items_status_list()
  2624. {
  2625. if ($this->debug > 0) {
  2626. error_log('New LP - In learnpath::get_items_status_list()', 0);
  2627. }
  2628. $list = [];
  2629. foreach ($this->ordered_items as $item_id) {
  2630. $list[] = [
  2631. $item_id => $this->items[$item_id]->get_status()
  2632. ];
  2633. }
  2634. return $list;
  2635. }
  2636. /**
  2637. * Return the number of interactions for the given learnpath Item View ID.
  2638. * This method can be used as static.
  2639. * @param integer Item View ID
  2640. * @param integer course id
  2641. * @return integer Number of interactions
  2642. */
  2643. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2644. {
  2645. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2646. $lp_iv_id = intval($lp_iv_id);
  2647. $course_id = intval($course_id);
  2648. $sql = "SELECT count(*) FROM $table
  2649. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2650. $res = Database::query($sql);
  2651. $num = 0;
  2652. if (Database::num_rows($res)) {
  2653. $row = Database::fetch_array($res);
  2654. $num = $row[0];
  2655. }
  2656. return $num;
  2657. }
  2658. /**
  2659. * Return the interactions as an array for the given lp_iv_id.
  2660. * This method can be used as static.
  2661. * @param integer Learnpath Item View ID
  2662. * @return array
  2663. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2664. */
  2665. public static function get_iv_interactions_array($lp_iv_id)
  2666. {
  2667. $course_id = api_get_course_int_id();
  2668. $list = [];
  2669. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2670. if (empty($lp_iv_id)) {
  2671. return [];
  2672. }
  2673. $sql = "SELECT * FROM $table
  2674. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2675. ORDER BY order_id ASC";
  2676. $res = Database::query($sql);
  2677. $num = Database::num_rows($res);
  2678. if ($num > 0) {
  2679. $list[] = [
  2680. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2681. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2682. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2683. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2684. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2685. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2686. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2687. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES)
  2688. ];
  2689. while ($row = Database::fetch_array($res)) {
  2690. $list[] = [
  2691. 'order_id' => ($row['order_id'] + 1),
  2692. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2693. 'type' => $row['interaction_type'],
  2694. 'time' => $row['completion_time'],
  2695. //'correct_responses' => $row['correct_responses'],
  2696. 'correct_responses' => '', // Hide correct responses from students.
  2697. 'student_response' => $row['student_response'],
  2698. 'result' => $row['result'],
  2699. 'latency' => $row['latency']
  2700. ];
  2701. }
  2702. }
  2703. return $list;
  2704. }
  2705. /**
  2706. * Return the number of objectives for the given learnpath Item View ID.
  2707. * This method can be used as static.
  2708. * @param integer Item View ID
  2709. * @return integer Number of objectives
  2710. */
  2711. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2712. {
  2713. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2714. $course_id = intval($course_id);
  2715. $lp_iv_id = intval($lp_iv_id);
  2716. $sql = "SELECT count(*) FROM $table
  2717. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2718. //@todo seems that this always returns 0
  2719. $res = Database::query($sql);
  2720. $num = 0;
  2721. if (Database::num_rows($res)) {
  2722. $row = Database::fetch_array($res);
  2723. $num = $row[0];
  2724. }
  2725. return $num;
  2726. }
  2727. /**
  2728. * Return the objectives as an array for the given lp_iv_id.
  2729. * This method can be used as static.
  2730. * @param integer Learnpath Item View ID
  2731. * @return array
  2732. * @todo Translate labels
  2733. */
  2734. public static function get_iv_objectives_array($lp_iv_id = 0)
  2735. {
  2736. $course_id = api_get_course_int_id();
  2737. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2738. $sql = "SELECT * FROM $table
  2739. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id
  2740. ORDER BY order_id ASC";
  2741. $res = Database::query($sql);
  2742. $num = Database::num_rows($res);
  2743. $list = [];
  2744. if ($num > 0) {
  2745. $list[] = [
  2746. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2747. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2748. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2749. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2750. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2751. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES)
  2752. ];
  2753. while ($row = Database::fetch_array($res)) {
  2754. $list[] = [
  2755. 'order_id' => ($row['order_id'] + 1),
  2756. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2757. 'score_raw' => $row['score_raw'],
  2758. 'score_max' => $row['score_max'],
  2759. 'score_min' => $row['score_min'],
  2760. 'status' => $row['status']
  2761. ];
  2762. }
  2763. }
  2764. return $list;
  2765. }
  2766. /**
  2767. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2768. * used by get_html_toc() to be ready to display
  2769. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2770. */
  2771. public function get_toc()
  2772. {
  2773. if ($this->debug > 0) {
  2774. error_log('learnpath::get_toc()', 0);
  2775. }
  2776. $toc = [];
  2777. foreach ($this->ordered_items as $item_id) {
  2778. if ($this->debug > 2) {
  2779. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2780. }
  2781. // TODO: Change this link generation and use new function instead.
  2782. $toc[] = [
  2783. 'id' => $item_id,
  2784. 'title' => $this->items[$item_id]->get_title(),
  2785. 'status' => $this->items[$item_id]->get_status(),
  2786. 'level' => $this->items[$item_id]->get_level(),
  2787. 'type' => $this->items[$item_id]->get_type(),
  2788. 'description' => $this->items[$item_id]->get_description(),
  2789. 'path' => $this->items[$item_id]->get_path(),
  2790. 'parent' => $this->items[$item_id]->get_parent(),
  2791. ];
  2792. }
  2793. if ($this->debug > 2) {
  2794. error_log('New LP - In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2795. }
  2796. return $toc;
  2797. }
  2798. /**
  2799. * Generate and return the table of contents for this learnpath. The JS
  2800. * table returned is used inside of scorm_api.php
  2801. * @param string $varname
  2802. * @return string A JS array vairiable construction
  2803. */
  2804. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2805. {
  2806. if ($this->debug > 0) {
  2807. error_log('New LP - In learnpath::get_items_details_as_js()', 0);
  2808. }
  2809. $toc = $varname.' = new Array();';
  2810. foreach ($this->ordered_items as $item_id) {
  2811. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2812. }
  2813. if ($this->debug > 2) {
  2814. error_log('New LP - In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2815. }
  2816. return $toc;
  2817. }
  2818. /**
  2819. * Gets the learning path type
  2820. * @param boolean Return the name? If false, return the ID. Default is false.
  2821. * @return mixed Type ID or name, depending on the parameter
  2822. */
  2823. public function get_type($get_name = false)
  2824. {
  2825. $res = false;
  2826. if ($this->debug > 0) {
  2827. error_log('New LP - In learnpath::get_type()', 0);
  2828. }
  2829. if (!empty($this->type) && (!$get_name)) {
  2830. $res = $this->type;
  2831. }
  2832. if ($this->debug > 2) {
  2833. error_log('New LP - In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2834. }
  2835. return $res;
  2836. }
  2837. /**
  2838. * Gets the learning path type as static method
  2839. * @param int $lp_id
  2840. * @return mixed Type ID or name, depending on the parameter
  2841. */
  2842. public static function get_type_static($lp_id = 0)
  2843. {
  2844. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2845. $lp_id = intval($lp_id);
  2846. $sql = "SELECT lp_type FROM $tbl_lp
  2847. WHERE iid = $lp_id";
  2848. $res = Database::query($sql);
  2849. if ($res === false) {
  2850. return null;
  2851. }
  2852. if (Database::num_rows($res) <= 0) {
  2853. return null;
  2854. }
  2855. $row = Database::fetch_array($res);
  2856. return $row['lp_type'];
  2857. }
  2858. /**
  2859. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2860. * This method can be used as abstract and is recursive
  2861. * @param integer Learnpath ID
  2862. * @param integer Parent ID of the items to look for
  2863. * @return array Ordered list of item IDs (empty array on error)
  2864. */
  2865. public static function get_flat_ordered_items_list($lp, $parent = 0, $course_id = 0)
  2866. {
  2867. if (empty($course_id)) {
  2868. $course_id = api_get_course_int_id();
  2869. } else {
  2870. $course_id = intval($course_id);
  2871. }
  2872. $list = [];
  2873. if (empty($lp)) {
  2874. return $list;
  2875. }
  2876. $lp = intval($lp);
  2877. $parent = intval($parent);
  2878. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2879. $sql = "SELECT iid FROM $tbl_lp_item
  2880. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2881. ORDER BY display_order";
  2882. $res = Database::query($sql);
  2883. while ($row = Database::fetch_array($res)) {
  2884. $sublist = self::get_flat_ordered_items_list(
  2885. $lp,
  2886. $row['iid'],
  2887. $course_id
  2888. );
  2889. $list[] = $row['iid'];
  2890. foreach ($sublist as $item) {
  2891. $list[] = $item;
  2892. }
  2893. }
  2894. return $list;
  2895. }
  2896. /**
  2897. * @return array
  2898. */
  2899. public static function getChapterTypes()
  2900. {
  2901. return [
  2902. 'dir'
  2903. ];
  2904. }
  2905. /**
  2906. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display
  2907. * @return string HTML TOC ready to display
  2908. */
  2909. public function getParentToc($tree)
  2910. {
  2911. if ($this->debug > 0) {
  2912. error_log('In learnpath::get_html_toc()', 0);
  2913. }
  2914. if (empty($tree)) {
  2915. $tree = $this->get_toc();
  2916. }
  2917. $dirTypes = self::getChapterTypes();
  2918. $myCurrentId = $this->get_current_item_id();
  2919. $listParent = [];
  2920. $listChildren = [];
  2921. $listNotParent = [];
  2922. $list = [];
  2923. foreach ($tree as $subtree) {
  2924. if (in_array($subtree['type'], $dirTypes)) {
  2925. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2926. $subtree['children'] = $listChildren;
  2927. if (!empty($subtree['children'])) {
  2928. foreach ($subtree['children'] as $subItem) {
  2929. if ($subItem['id'] == $this->current) {
  2930. $subtree['parent_current'] = 'in';
  2931. $subtree['current'] = 'on';
  2932. }
  2933. }
  2934. }
  2935. $listParent[] = $subtree;
  2936. }
  2937. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2938. $classStatus = [
  2939. 'not attempted' => 'scorm_not_attempted',
  2940. 'incomplete' => 'scorm_not_attempted',
  2941. 'failed' => 'scorm_failed',
  2942. 'completed' => 'scorm_completed',
  2943. 'passed' => 'scorm_completed',
  2944. 'succeeded' => 'scorm_completed',
  2945. 'browsed' => 'scorm_completed',
  2946. ];
  2947. if (isset($classStatus[$subtree['status']])) {
  2948. $cssStatus = $classStatus[$subtree['status']];
  2949. }
  2950. $title = Security::remove_XSS($subtree['title']);
  2951. unset($subtree['title']);
  2952. if (empty($title)) {
  2953. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2954. }
  2955. $classStyle = null;
  2956. if ($subtree['id'] == $this->current) {
  2957. $classStyle = 'scorm_item_normal '. $classStyle . 'scorm_highlight';
  2958. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2959. $classStyle = 'scorm_item_normal '. $classStyle . ' ';
  2960. }
  2961. $subtree['title'] = $title;
  2962. $subtree['class'] = $cssStatus . ' ' .$classStyle;
  2963. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2964. $subtree['current_id'] = $myCurrentId;
  2965. $listNotParent[] = $subtree;
  2966. }
  2967. }
  2968. $list['are_parents'] = $listParent;
  2969. $list['not_parents'] = $listNotParent;
  2970. return $list;
  2971. }
  2972. /**
  2973. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display
  2974. * @return string HTML TOC ready to display
  2975. */
  2976. public function getChildrenToc($tree, $id, $parent = true)
  2977. {
  2978. if ($this->debug > 0) {
  2979. error_log('In learnpath::get_html_toc()', 0);
  2980. }
  2981. if (empty($tree)) {
  2982. $tree = $this->get_toc();
  2983. }
  2984. $dirTypes = self::getChapterTypes();
  2985. $mycurrentitemid = $this->get_current_item_id();
  2986. $list = [];
  2987. $classStatus = [
  2988. 'not attempted' => 'scorm_not_attempted',
  2989. 'incomplete' => 'scorm_not_attempted',
  2990. 'failed' => 'scorm_failed',
  2991. 'completed' => 'scorm_completed',
  2992. 'passed' => 'scorm_completed',
  2993. 'succeeded' => 'scorm_completed',
  2994. 'browsed' => 'scorm_completed',
  2995. ];
  2996. foreach ($tree as $subtree) {
  2997. $subtree['tree'] = null;
  2998. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  2999. if ($subtree['id'] == $this->current) {
  3000. $subtree['current'] = 'active';
  3001. } else {
  3002. $subtree['current'] = null;
  3003. }
  3004. if (isset($classStatus[$subtree['status']])) {
  3005. $cssStatus = $classStatus[$subtree['status']];
  3006. }
  3007. $title = Security::remove_XSS($subtree['title']);
  3008. unset($subtree['title']);
  3009. if (empty($title)) {
  3010. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3011. }
  3012. $classStyle = null;
  3013. if ($subtree['id'] == $this->current) {
  3014. $classStyle = 'scorm_item_normal '. $classStyle . 'scorm_highlight';
  3015. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3016. $classStyle = 'scorm_item_normal '. $classStyle . ' ';
  3017. }
  3018. if (in_array($subtree['type'], $dirTypes)) {
  3019. $subtree['title'] = stripslashes($title);
  3020. } else {
  3021. $subtree['title'] = $title;
  3022. $subtree['class'] = $cssStatus . ' ' .$classStyle;
  3023. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3024. $subtree['current_id'] = $mycurrentitemid;
  3025. }
  3026. $list[] = $subtree;
  3027. }
  3028. }
  3029. return $list;
  3030. }
  3031. /**
  3032. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display
  3033. * @param array $toc_list
  3034. * @return string HTML TOC ready to display
  3035. */
  3036. public function getListArrayToc($toc_list = [])
  3037. {
  3038. if ($this->debug > 0) {
  3039. error_log('In learnpath::get_html_toc()', 0);
  3040. }
  3041. if (empty($toc_list)) {
  3042. $toc_list = $this->get_toc();
  3043. }
  3044. // Temporary variables.
  3045. $mycurrentitemid = $this->get_current_item_id();
  3046. $list = [];
  3047. $arrayList = [];
  3048. $classStatus = [
  3049. 'not attempted' => 'scorm_not_attempted',
  3050. 'incomplete' => 'scorm_not_attempted',
  3051. 'failed' => 'scorm_failed',
  3052. 'completed' => 'scorm_completed',
  3053. 'passed' => 'scorm_completed',
  3054. 'succeeded' => 'scorm_completed',
  3055. 'browsed' => 'scorm_completed',
  3056. ];
  3057. foreach ($toc_list as $item) {
  3058. $list['id'] = $item['id'];
  3059. $list['status'] = $item['status'];
  3060. $cssStatus = null;
  3061. if (isset($classStatus[$item['status']])) {
  3062. $cssStatus = $classStatus[$item['status']];
  3063. }
  3064. $classStyle = ' ';
  3065. $dirTypes = self::getChapterTypes();
  3066. if (in_array($item['type'], $dirTypes)) {
  3067. $classStyle = 'scorm_item_section ';
  3068. }
  3069. if ($item['id'] == $this->current) {
  3070. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3071. } elseif (!in_array($item['type'], $dirTypes)) {
  3072. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3073. }
  3074. $title = $item['title'];
  3075. if (empty($title)) {
  3076. $title = self::rl_get_resource_name(
  3077. api_get_course_id(),
  3078. $this->get_id(),
  3079. $item['id']
  3080. );
  3081. }
  3082. $title = Security::remove_XSS($item['title']);
  3083. if (empty($item['description'])) {
  3084. $list['description'] = $title;
  3085. } else {
  3086. $list['description'] = $item['description'];
  3087. }
  3088. $list['class'] = $classStyle.' '.$cssStatus;
  3089. $list['level'] = $item['level'];
  3090. $list['type'] = $item['type'];
  3091. if (in_array($item['type'], $dirTypes)) {
  3092. $list['css_level'] = 'level_'.$item['level'];
  3093. } else {
  3094. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.learnpath::format_scorm_type_item($item['type']);
  3095. }
  3096. if (in_array($item['type'], $dirTypes)) {
  3097. $list['title'] = stripslashes($title);
  3098. } else {
  3099. $list['title'] = stripslashes($title);
  3100. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3101. $list['current_id'] = $mycurrentitemid;
  3102. }
  3103. $arrayList[] = $list;
  3104. }
  3105. return $arrayList;
  3106. }
  3107. /**
  3108. * Returns an HTML-formatted string ready to display with teacher buttons
  3109. * in LP view menu
  3110. * @return string HTML TOC ready to display
  3111. */
  3112. public function get_teacher_toc_buttons()
  3113. {
  3114. $is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
  3115. $hide_teacher_icons_lp = api_get_configuration_value('hide_teacher_icons_lp');
  3116. $html = '';
  3117. if ($is_allowed_to_edit && $hide_teacher_icons_lp == false) {
  3118. if ($this->get_lp_session_id() == api_get_session_id()) {
  3119. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3120. $html .= '<div class="btn-group">';
  3121. $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'>".
  3122. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3123. $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'>".
  3124. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3125. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3126. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3127. $html .= '</div>';
  3128. $html .= '</div>';
  3129. }
  3130. }
  3131. return $html;
  3132. }
  3133. /**
  3134. * Gets the learnpath maker name - generally the editor's name
  3135. * @return string Learnpath maker name
  3136. */
  3137. public function get_maker()
  3138. {
  3139. if ($this->debug > 0) {
  3140. error_log('New LP - In learnpath::get_maker()', 0);
  3141. }
  3142. if (!empty($this->maker)) {
  3143. return $this->maker;
  3144. } else {
  3145. return '';
  3146. }
  3147. }
  3148. /**
  3149. * Gets the learnpath name/title
  3150. * @return string Learnpath name/title
  3151. */
  3152. public function get_name()
  3153. {
  3154. if ($this->debug > 0) {
  3155. error_log('New LP - In learnpath::get_name()', 0);
  3156. }
  3157. if (!empty($this->name)) {
  3158. return $this->name;
  3159. } else {
  3160. return 'N/A';
  3161. }
  3162. }
  3163. /**
  3164. * Gets a link to the resource from the present location, depending on item ID.
  3165. * @param string $type Type of link expected
  3166. * @param integer $item_id Learnpath item ID
  3167. * @return string $provided_toc Link to the lp_item resource
  3168. */
  3169. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3170. {
  3171. $course_id = $this->get_course_int_id();
  3172. if ($this->debug > 0) {
  3173. error_log('New LP - In learnpath::get_link('.$type.','.$item_id.')', 0);
  3174. }
  3175. if (empty($item_id)) {
  3176. if ($this->debug > 2) {
  3177. error_log('New LP - In learnpath::get_link() - no item id given in learnpath::get_link(), using current: '.$this->get_current_item_id(), 0);
  3178. }
  3179. $item_id = $this->get_current_item_id();
  3180. }
  3181. if (empty($item_id)) {
  3182. if ($this->debug > 2) {
  3183. error_log('New LP - In learnpath::get_link() - no current item id found in learnpath object', 0);
  3184. }
  3185. //still empty, this means there was no item_id given and we are not in an object context or
  3186. //the object property is empty, return empty link
  3187. $item_id = $this->first();
  3188. return '';
  3189. }
  3190. $file = '';
  3191. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3192. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3193. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3194. $item_id = intval($item_id);
  3195. $sql = "SELECT
  3196. l.lp_type as ltype,
  3197. l.path as lpath,
  3198. li.item_type as litype,
  3199. li.path as lipath,
  3200. li.parameters as liparams
  3201. FROM $lp_table l
  3202. INNER JOIN $lp_item_table li
  3203. ON (li.lp_id = l.iid)
  3204. WHERE
  3205. li.iid = $item_id
  3206. ";
  3207. if ($this->debug > 2) {
  3208. error_log('New LP - In learnpath::get_link() - selecting item '.$sql, 0);
  3209. }
  3210. $res = Database::query($sql);
  3211. if (Database::num_rows($res) > 0) {
  3212. $row = Database::fetch_array($res);
  3213. $lp_type = $row['ltype'];
  3214. $lp_path = $row['lpath'];
  3215. $lp_item_type = $row['litype'];
  3216. $lp_item_path = $row['lipath'];
  3217. $lp_item_params = $row['liparams'];
  3218. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3219. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3220. }
  3221. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3222. if ($type == 'http') {
  3223. //web path
  3224. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3225. } else {
  3226. $course_path = $sys_course_path; //system path
  3227. }
  3228. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3229. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3230. if (in_array(
  3231. $lp_item_type,
  3232. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3233. )
  3234. ) {
  3235. $lp_type = 1;
  3236. }
  3237. if ($this->debug > 2) {
  3238. error_log('New LP - In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3239. error_log('New LP - In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3240. }
  3241. // Now go through the specific cases to get the end of the path
  3242. // @todo Use constants instead of int values.
  3243. switch ($lp_type) {
  3244. case 1:
  3245. $file = self::rl_get_resource_link_for_learnpath(
  3246. $course_id,
  3247. $this->get_id(),
  3248. $item_id,
  3249. $this->get_view_id()
  3250. );
  3251. if ($this->debug > 0) {
  3252. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3253. }
  3254. switch ($lp_item_type) {
  3255. case 'dir':
  3256. $file = 'lp_content.php?type=dir';
  3257. break;
  3258. case 'link':
  3259. if (Link::is_youtube_link($file)) {
  3260. $src = Link::get_youtube_video_id($file);
  3261. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3262. } elseif (Link::isVimeoLink($file)) {
  3263. $src = Link::getVimeoLinkId($file);
  3264. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3265. } else {
  3266. // If the current site is HTTPS and the link is
  3267. // HTTP, browsers will refuse opening the link
  3268. $urlId = api_get_current_access_url_id();
  3269. $url = api_get_access_url($urlId, false);
  3270. $protocol = substr($url['url'], 0, 5);
  3271. if ($protocol === 'https') {
  3272. $linkProtocol = substr($file, 0, 5);
  3273. if ($linkProtocol === 'http:') {
  3274. //this is the special intervention case
  3275. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3276. }
  3277. }
  3278. }
  3279. break;
  3280. case 'quiz':
  3281. // Check how much attempts of a exercise exits in lp
  3282. $lp_item_id = $this->get_current_item_id();
  3283. $lp_view_id = $this->get_view_id();
  3284. $prevent_reinit = null;
  3285. if (isset($this->items[$this->current])) {
  3286. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3287. }
  3288. if (empty($provided_toc)) {
  3289. if ($this->debug > 0) {
  3290. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3291. }
  3292. $list = $this->get_toc();
  3293. } else {
  3294. if ($this->debug > 0) {
  3295. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3296. }
  3297. $list = $provided_toc;
  3298. }
  3299. $type_quiz = false;
  3300. foreach ($list as $toc) {
  3301. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3302. $type_quiz = true;
  3303. }
  3304. }
  3305. if ($type_quiz) {
  3306. $lp_item_id = intval($lp_item_id);
  3307. $lp_view_id = intval($lp_view_id);
  3308. $sql = "SELECT count(*) FROM $lp_item_view_table
  3309. WHERE
  3310. c_id = $course_id AND
  3311. lp_item_id='".$lp_item_id."' AND
  3312. lp_view_id ='".$lp_view_id."' AND
  3313. status='completed'";
  3314. $result = Database::query($sql);
  3315. $row_count = Database:: fetch_row($result);
  3316. $count_item_view = (int) $row_count[0];
  3317. $not_multiple_attempt = 0;
  3318. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3319. $not_multiple_attempt = 1;
  3320. }
  3321. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3322. }
  3323. break;
  3324. }
  3325. $tmp_array = explode('/', $file);
  3326. $document_name = $tmp_array[count($tmp_array) - 1];
  3327. if (strpos($document_name, '_DELETED_')) {
  3328. $file = 'blank.php?error=document_deleted';
  3329. }
  3330. break;
  3331. case 2:
  3332. if ($this->debug > 2) {
  3333. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3334. }
  3335. if ($lp_item_type != 'dir') {
  3336. // Quite complex here:
  3337. // We want to make sure 'http://' (and similar) links can
  3338. // be loaded as is (withouth the Chamilo path in front) but
  3339. // some contents use this form: resource.htm?resource=http://blablabla
  3340. // which means we have to find a protocol at the path's start, otherwise
  3341. // it should not be considered as an external URL.
  3342. // if ($this->prerequisites_match($item_id)) {
  3343. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3344. if ($this->debug > 2) {
  3345. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3346. }
  3347. // Distant url, return as is.
  3348. $file = $lp_item_path;
  3349. } else {
  3350. if ($this->debug > 2) {
  3351. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3352. }
  3353. // Prevent getting untranslatable urls.
  3354. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3355. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3356. // Prepare the path.
  3357. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3358. // TODO: Fix this for urls with protocol header.
  3359. $file = str_replace('//', '/', $file);
  3360. $file = str_replace(':/', '://', $file);
  3361. if (substr($lp_path, -1) == '/') {
  3362. $lp_path = substr($lp_path, 0, -1);
  3363. }
  3364. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3365. // if file not found.
  3366. $decoded = html_entity_decode($lp_item_path);
  3367. list($decoded) = explode('?', $decoded);
  3368. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3369. $file = self::rl_get_resource_link_for_learnpath(
  3370. $course_id,
  3371. $this->get_id(),
  3372. $item_id,
  3373. $this->get_view_id()
  3374. );
  3375. if (empty($file)) {
  3376. $file = 'blank.php?error=document_not_found';
  3377. } else {
  3378. $tmp_array = explode('/', $file);
  3379. $document_name = $tmp_array[count($tmp_array) - 1];
  3380. if (strpos($document_name, '_DELETED_')) {
  3381. $file = 'blank.php?error=document_deleted';
  3382. } else {
  3383. $file = 'blank.php?error=document_not_found';
  3384. }
  3385. }
  3386. } else {
  3387. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3388. }
  3389. }
  3390. }
  3391. // We want to use parameters if they were defined in the imsmanifest
  3392. if (strpos($file, 'blank.php') === false) {
  3393. $lp_item_params = ltrim($lp_item_params, '?');
  3394. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3395. }
  3396. } else {
  3397. $file = 'lp_content.php?type=dir';
  3398. }
  3399. break;
  3400. case 3:
  3401. if ($this->debug > 2) {
  3402. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3403. }
  3404. // Formatting AICC HACP append URL.
  3405. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3406. if (!empty($lp_item_params)) {
  3407. $aicc_append .= $lp_item_params.'&';
  3408. }
  3409. if ($lp_item_type != 'dir') {
  3410. // Quite complex here:
  3411. // We want to make sure 'http://' (and similar) links can
  3412. // be loaded as is (withouth the Chamilo path in front) but
  3413. // some contents use this form: resource.htm?resource=http://blablabla
  3414. // which means we have to find a protocol at the path's start, otherwise
  3415. // it should not be considered as an external URL.
  3416. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3417. if ($this->debug > 2) {
  3418. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3419. }
  3420. // Distant url, return as is.
  3421. $file = $lp_item_path;
  3422. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3423. /*
  3424. if (stristr($file,'<servername>') !== false) {
  3425. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3426. }
  3427. */
  3428. if (stripos($file, '<servername>') !== false) {
  3429. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3430. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3431. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3432. }
  3433. //
  3434. $file .= $aicc_append;
  3435. } else {
  3436. if ($this->debug > 2) {
  3437. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3438. }
  3439. // Prevent getting untranslatable urls.
  3440. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3441. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3442. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3443. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3444. // TODO: Fix this for urls with protocol header.
  3445. $file = str_replace('//', '/', $file);
  3446. $file = str_replace(':/', '://', $file);
  3447. $file .= $aicc_append;
  3448. }
  3449. } else {
  3450. $file = 'lp_content.php?type=dir';
  3451. }
  3452. break;
  3453. case 4:
  3454. break;
  3455. default:
  3456. break;
  3457. }
  3458. // Replace &amp; by & because &amp; will break URL with params
  3459. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3460. }
  3461. if ($this->debug > 2) {
  3462. error_log('New LP - In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3463. }
  3464. return $file;
  3465. }
  3466. /**
  3467. * Gets the latest usable view or generate a new one
  3468. * @param integer Optional attempt number. If none given, takes the highest from the lp_view table
  3469. * @return integer DB lp_view id
  3470. */
  3471. public function get_view($attempt_num = 0)
  3472. {
  3473. if ($this->debug > 0) {
  3474. error_log('New LP - In learnpath::get_view()', 0);
  3475. }
  3476. $search = '';
  3477. // Use $attempt_num to enable multi-views management (disabled so far).
  3478. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3479. $search = 'AND view_count = '.$attempt_num;
  3480. }
  3481. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3482. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3483. $course_id = api_get_course_int_id();
  3484. $sessionId = api_get_session_id();
  3485. $sql = "SELECT iid, view_count FROM $lp_view_table
  3486. WHERE
  3487. c_id = $course_id AND
  3488. lp_id = " . $this->get_id()." AND
  3489. user_id = " . $this->get_user_id()." AND
  3490. session_id = $sessionId
  3491. $search
  3492. ORDER BY view_count DESC";
  3493. $res = Database::query($sql);
  3494. if (Database::num_rows($res) > 0) {
  3495. $row = Database::fetch_array($res);
  3496. $this->lp_view_id = $row['iid'];
  3497. } elseif (!api_is_invitee()) {
  3498. // There is no database record, create one.
  3499. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3500. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3501. Database::query($sql);
  3502. $id = Database::insert_id();
  3503. $this->lp_view_id = $id;
  3504. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3505. Database::query($sql);
  3506. }
  3507. return $this->lp_view_id;
  3508. }
  3509. /**
  3510. * Gets the current view id
  3511. * @return integer View ID (from lp_view)
  3512. */
  3513. public function get_view_id()
  3514. {
  3515. if ($this->debug > 0) {
  3516. error_log('New LP - In learnpath::get_view_id()', 0);
  3517. }
  3518. if (!empty($this->lp_view_id)) {
  3519. return $this->lp_view_id;
  3520. } else {
  3521. return 0;
  3522. }
  3523. }
  3524. /**
  3525. * Gets the update queue
  3526. * @return array Array containing IDs of items to be updated by JavaScript
  3527. */
  3528. public function get_update_queue()
  3529. {
  3530. if ($this->debug > 0) {
  3531. error_log('New LP - In learnpath::get_update_queue()', 0);
  3532. }
  3533. return $this->update_queue;
  3534. }
  3535. /**
  3536. * Gets the user ID
  3537. * @return integer User ID
  3538. */
  3539. public function get_user_id()
  3540. {
  3541. if ($this->debug > 0) {
  3542. error_log('New LP - In learnpath::get_user_id()', 0);
  3543. }
  3544. if (!empty($this->user_id)) {
  3545. return $this->user_id;
  3546. } else {
  3547. return false;
  3548. }
  3549. }
  3550. /**
  3551. * Checks if any of the items has an audio element attached
  3552. * @return bool True or false
  3553. */
  3554. public function has_audio()
  3555. {
  3556. if ($this->debug > 1) {
  3557. error_log('New LP - In learnpath::has_audio()', 0);
  3558. }
  3559. $has = false;
  3560. foreach ($this->items as $i => $item) {
  3561. if (!empty($this->items[$i]->audio)) {
  3562. $has = true;
  3563. break;
  3564. }
  3565. }
  3566. return $has;
  3567. }
  3568. /**
  3569. * Moves an item up and down at its level
  3570. * @param integer Item to move up and down
  3571. * @param string Direction 'up' or 'down'
  3572. * @return integer New display order, or false on error
  3573. */
  3574. public function move_item($id, $direction)
  3575. {
  3576. $course_id = api_get_course_int_id();
  3577. if ($this->debug > 0) {
  3578. error_log('New LP - In learnpath::move_item('.$id.','.$direction.')', 0);
  3579. }
  3580. if (empty($id) || empty($direction)) {
  3581. return false;
  3582. }
  3583. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3584. $sql_sel = "SELECT *
  3585. FROM $tbl_lp_item
  3586. WHERE
  3587. iid = $id
  3588. ";
  3589. $res_sel = Database::query($sql_sel);
  3590. // Check if elem exists.
  3591. if (Database::num_rows($res_sel) < 1) {
  3592. return false;
  3593. }
  3594. // Gather data.
  3595. $row = Database::fetch_array($res_sel);
  3596. $previous = $row['previous_item_id'];
  3597. $next = $row['next_item_id'];
  3598. $display = $row['display_order'];
  3599. $parent = $row['parent_item_id'];
  3600. $lp = $row['lp_id'];
  3601. // Update the item (switch with previous/next one).
  3602. switch ($direction) {
  3603. case 'up':
  3604. if ($this->debug > 2) {
  3605. error_log('Movement up detected', 0);
  3606. }
  3607. if ($display > 1) {
  3608. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3609. WHERE iid = $previous";
  3610. if ($this->debug > 2) {
  3611. error_log('Selecting previous: '.$sql_sel2, 0);
  3612. }
  3613. $res_sel2 = Database::query($sql_sel2);
  3614. if (Database::num_rows($res_sel2) < 1) {
  3615. $previous_previous = 0;
  3616. }
  3617. // Gather data.
  3618. $row2 = Database::fetch_array($res_sel2);
  3619. $previous_previous = $row2['previous_item_id'];
  3620. // Update previous_previous item (switch "next" with current).
  3621. if ($previous_previous != 0) {
  3622. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3623. next_item_id = $id
  3624. WHERE iid = $previous_previous";
  3625. if ($this->debug > 2) {
  3626. error_log($sql_upd2, 0);
  3627. }
  3628. Database::query($sql_upd2);
  3629. }
  3630. // Update previous item (switch with current).
  3631. if ($previous != 0) {
  3632. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3633. next_item_id = $next,
  3634. previous_item_id = $id,
  3635. display_order = display_order +1
  3636. WHERE iid = $previous";
  3637. if ($this->debug > 2) {
  3638. error_log($sql_upd2, 0);
  3639. }
  3640. Database::query($sql_upd2);
  3641. }
  3642. // Update current item (switch with previous).
  3643. if ($id != 0) {
  3644. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3645. next_item_id = $previous,
  3646. previous_item_id = $previous_previous,
  3647. display_order = display_order-1
  3648. WHERE c_id = ".$course_id." AND id = $id";
  3649. if ($this->debug > 2) {
  3650. error_log($sql_upd2, 0);
  3651. }
  3652. Database::query($sql_upd2);
  3653. }
  3654. // Update next item (new previous item).
  3655. if ($next != 0) {
  3656. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3657. WHERE iid = $next";
  3658. if ($this->debug > 2) {
  3659. error_log($sql_upd2, 0);
  3660. }
  3661. Database::query($sql_upd2);
  3662. }
  3663. $display = $display - 1;
  3664. }
  3665. break;
  3666. case 'down':
  3667. if ($this->debug > 2) {
  3668. error_log('Movement down detected', 0);
  3669. }
  3670. if ($next != 0) {
  3671. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3672. WHERE iid = $next";
  3673. if ($this->debug > 2) {
  3674. error_log('Selecting next: '.$sql_sel2, 0);
  3675. }
  3676. $res_sel2 = Database::query($sql_sel2);
  3677. if (Database::num_rows($res_sel2) < 1) {
  3678. $next_next = 0;
  3679. }
  3680. // Gather data.
  3681. $row2 = Database::fetch_array($res_sel2);
  3682. $next_next = $row2['next_item_id'];
  3683. // Update previous item (switch with current).
  3684. if ($previous != 0) {
  3685. $sql_upd2 = "UPDATE $tbl_lp_item
  3686. SET next_item_id = $next
  3687. WHERE iid = $previous";
  3688. Database::query($sql_upd2);
  3689. }
  3690. // Update current item (switch with previous).
  3691. if ($id != 0) {
  3692. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3693. previous_item_id = $next,
  3694. next_item_id = $next_next,
  3695. display_order = display_order + 1
  3696. WHERE iid = $id";
  3697. Database::query($sql_upd2);
  3698. }
  3699. // Update next item (new previous item).
  3700. if ($next != 0) {
  3701. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3702. previous_item_id = $previous,
  3703. next_item_id = $id,
  3704. display_order = display_order-1
  3705. WHERE iid = $next";
  3706. Database::query($sql_upd2);
  3707. }
  3708. // Update next_next item (switch "previous" with current).
  3709. if ($next_next != 0) {
  3710. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3711. previous_item_id = $id
  3712. WHERE iid = $next_next";
  3713. Database::query($sql_upd2);
  3714. }
  3715. $display = $display + 1;
  3716. }
  3717. break;
  3718. default:
  3719. return false;
  3720. }
  3721. return $display;
  3722. }
  3723. /**
  3724. * Move a LP up (display_order)
  3725. * @param int $lp_id Learnpath ID
  3726. * @param int $categoryId
  3727. * @return bool
  3728. */
  3729. public static function move_up($lp_id, $categoryId = 0)
  3730. {
  3731. $courseId = api_get_course_int_id();
  3732. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3733. $categoryCondition = '';
  3734. if (!empty($categoryId)) {
  3735. $categoryId = (int) $categoryId;
  3736. $categoryCondition = " AND category_id = $categoryId";
  3737. }
  3738. $sql = "SELECT * FROM $lp_table
  3739. WHERE c_id = $courseId
  3740. $categoryCondition
  3741. ORDER BY display_order";
  3742. $res = Database::query($sql);
  3743. if ($res === false) {
  3744. return false;
  3745. }
  3746. $lps = [];
  3747. $lp_order = [];
  3748. $num = Database::num_rows($res);
  3749. // First check the order is correct, globally (might be wrong because
  3750. // of versions < 1.8.4)
  3751. if ($num > 0) {
  3752. $i = 1;
  3753. while ($row = Database::fetch_array($res)) {
  3754. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3755. $sql = "UPDATE $lp_table SET display_order = $i
  3756. WHERE iid = ".$row['iid'];
  3757. Database::query($sql);
  3758. }
  3759. $row['display_order'] = $i;
  3760. $lps[$row['iid']] = $row;
  3761. $lp_order[$i] = $row['iid'];
  3762. $i++;
  3763. }
  3764. }
  3765. if ($num > 1) { // If there's only one element, no need to sort.
  3766. $order = $lps[$lp_id]['display_order'];
  3767. if ($order > 1) { // If it's the first element, no need to move up.
  3768. $sql = "UPDATE $lp_table SET display_order = $order
  3769. WHERE iid = ".$lp_order[$order - 1];
  3770. Database::query($sql);
  3771. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3772. WHERE iid = $lp_id";
  3773. Database::query($sql);
  3774. }
  3775. }
  3776. return true;
  3777. }
  3778. /**
  3779. * Move a learnpath down (display_order)
  3780. * @param int $lp_id Learnpath ID
  3781. * @param int $categoryId
  3782. * @return bool
  3783. */
  3784. public static function move_down($lp_id, $categoryId = 0)
  3785. {
  3786. $courseId = api_get_course_int_id();
  3787. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3788. $categoryCondition = '';
  3789. if (!empty($categoryId)) {
  3790. $categoryId = (int) $categoryId;
  3791. $categoryCondition = " AND category_id = $categoryId";
  3792. }
  3793. $sql = "SELECT * FROM $lp_table
  3794. WHERE c_id = $courseId
  3795. $categoryCondition
  3796. ORDER BY display_order";
  3797. $res = Database::query($sql);
  3798. if ($res === false) {
  3799. return false;
  3800. }
  3801. $lps = [];
  3802. $lp_order = [];
  3803. $num = Database::num_rows($res);
  3804. $max = 0;
  3805. // First check the order is correct, globally (might be wrong because
  3806. // of versions < 1.8.4).
  3807. if ($num > 0) {
  3808. $i = 1;
  3809. while ($row = Database::fetch_array($res)) {
  3810. $max = $i;
  3811. if ($row['display_order'] != $i) {
  3812. // If we find a gap in the order, we need to fix it.
  3813. $sql = "UPDATE $lp_table SET display_order = $i
  3814. WHERE iid = ".$row['iid'];
  3815. Database::query($sql);
  3816. }
  3817. $row['display_order'] = $i;
  3818. $lps[$row['iid']] = $row;
  3819. $lp_order[$i] = $row['iid'];
  3820. $i++;
  3821. }
  3822. }
  3823. if ($num > 1) { // If there's only one element, no need to sort.
  3824. $order = $lps[$lp_id]['display_order'];
  3825. if ($order < $max) { // If it's the first element, no need to move up.
  3826. $sql = "UPDATE $lp_table SET display_order = $order
  3827. WHERE iid = ".$lp_order[$order + 1];
  3828. Database::query($sql);
  3829. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3830. WHERE iid = $lp_id";
  3831. Database::query($sql);
  3832. }
  3833. }
  3834. return true;
  3835. }
  3836. /**
  3837. * Updates learnpath attributes to point to the next element
  3838. * The last part is similar to set_current_item but processing the other way around
  3839. */
  3840. public function next()
  3841. {
  3842. if ($this->debug > 0) {
  3843. error_log('New LP - In learnpath::next()', 0);
  3844. }
  3845. $this->last = $this->get_current_item_id();
  3846. $this->items[$this->last]->save(
  3847. false,
  3848. $this->prerequisites_match($this->last)
  3849. );
  3850. $this->autocomplete_parents($this->last);
  3851. $new_index = $this->get_next_index();
  3852. if ($this->debug > 2) {
  3853. error_log('New LP - New index: '.$new_index, 0);
  3854. }
  3855. $this->index = $new_index;
  3856. if ($this->debug > 2) {
  3857. error_log('New LP - Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3858. }
  3859. $this->current = $this->ordered_items[$new_index];
  3860. if ($this->debug > 2) {
  3861. error_log('New LP - new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3862. }
  3863. }
  3864. /**
  3865. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3866. * class, this might be redefined to allow several behaviours depending on the document type.
  3867. * @param integer Resource ID
  3868. */
  3869. public function open($id)
  3870. {
  3871. if ($this->debug > 0) {
  3872. error_log('New LP - In learnpath::open()', 0);
  3873. }
  3874. // TODO:
  3875. // set the current resource attribute to this resource
  3876. // switch on element type (redefine in child class?)
  3877. // set status for this item to "opened"
  3878. // start timer
  3879. // initialise score
  3880. $this->index = 0; //or = the last item seen (see $this->last)
  3881. }
  3882. /**
  3883. * Check that all prerequisites are fulfilled. Returns true and an
  3884. * empty string on success, returns false
  3885. * and the prerequisite string on error.
  3886. * This function is based on the rules for aicc_script language as
  3887. * described in the SCORM 1.2 CAM documentation page 108.
  3888. * @param integer $itemId Optional item ID. If none given, uses the current open item.
  3889. * @return boolean True if prerequisites are matched, false otherwise -
  3890. * Empty string if true returned, prerequisites string otherwise.
  3891. */
  3892. public function prerequisites_match($itemId = null)
  3893. {
  3894. $debug = $this->debug;
  3895. if ($debug > 0) {
  3896. error_log('In learnpath::prerequisites_match()', 0);
  3897. }
  3898. if (empty($itemId)) {
  3899. $itemId = $this->current;
  3900. }
  3901. $currentItem = $this->getItem($itemId);
  3902. if ($currentItem) {
  3903. if ($this->type == 2) {
  3904. // Getting prereq from scorm
  3905. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3906. } else {
  3907. $prereq_string = $currentItem->get_prereq_string();
  3908. }
  3909. if (empty($prereq_string)) {
  3910. if ($debug > 0) {
  3911. error_log('Found prereq_string is empty return true');
  3912. }
  3913. return true;
  3914. }
  3915. // Clean spaces.
  3916. $prereq_string = str_replace(' ', '', $prereq_string);
  3917. if ($debug > 0) {
  3918. error_log('Found prereq_string: '.$prereq_string, 0);
  3919. }
  3920. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3921. $result = $currentItem->parse_prereq(
  3922. $prereq_string,
  3923. $this->items,
  3924. $this->refs_list,
  3925. $this->get_user_id()
  3926. );
  3927. if ($result === false) {
  3928. $this->set_error_msg($currentItem->prereq_alert);
  3929. }
  3930. } else {
  3931. $result = true;
  3932. if ($debug > 1) {
  3933. error_log('$this->items['.$itemId.'] was not an object', 0);
  3934. }
  3935. }
  3936. if ($debug > 1) {
  3937. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3938. }
  3939. return $result;
  3940. }
  3941. /**
  3942. * Updates learnpath attributes to point to the previous element
  3943. * The last part is similar to set_current_item but processing the other way around
  3944. */
  3945. public function previous()
  3946. {
  3947. if ($this->debug > 0) {
  3948. error_log('New LP - In learnpath::previous()', 0);
  3949. }
  3950. $this->last = $this->get_current_item_id();
  3951. $this->items[$this->last]->save(
  3952. false,
  3953. $this->prerequisites_match($this->last)
  3954. );
  3955. $this->autocomplete_parents($this->last);
  3956. $new_index = $this->get_previous_index();
  3957. $this->index = $new_index;
  3958. $this->current = $this->ordered_items[$new_index];
  3959. }
  3960. /**
  3961. * Publishes a learnpath. This basically means show or hide the learnpath
  3962. * to normal users.
  3963. * Can be used as abstract
  3964. * @param integer Learnpath ID
  3965. * @param int New visibility
  3966. * @return bool
  3967. */
  3968. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3969. {
  3970. $action = 'visible';
  3971. if ($set_visibility != 1) {
  3972. $action = 'invisible';
  3973. self::toggle_publish($lp_id, 'i');
  3974. }
  3975. return api_item_property_update(
  3976. api_get_course_info(),
  3977. TOOL_LEARNPATH,
  3978. $lp_id,
  3979. $action,
  3980. api_get_user_id()
  3981. );
  3982. }
  3983. /**
  3984. * Publishes a learnpath category.
  3985. * This basically means show or hide the learnpath category to normal users.
  3986. * @param int $id
  3987. * @param int $visibility
  3988. * @return bool
  3989. */
  3990. public static function toggleCategoryVisibility($id, $visibility = 1)
  3991. {
  3992. $action = 'visible';
  3993. if ($visibility != 1) {
  3994. $action = 'invisible';
  3995. $list = new LearnpathList(
  3996. api_get_user_id(),
  3997. null,
  3998. null,
  3999. null,
  4000. false,
  4001. $id
  4002. );
  4003. $lpList = $list->get_flat_list();
  4004. foreach ($lpList as $lp) {
  4005. learnpath::toggle_visibility($lp['iid'], 0);
  4006. }
  4007. learnpath::toggleCategoryPublish($id, 0);
  4008. }
  4009. return api_item_property_update(
  4010. api_get_course_info(),
  4011. TOOL_LEARNPATH_CATEGORY,
  4012. $id,
  4013. $action,
  4014. api_get_user_id()
  4015. );
  4016. }
  4017. /**
  4018. * Publishes a learnpath. This basically means show or hide the learnpath
  4019. * on the course homepage
  4020. * Can be used as abstract
  4021. * @param integer $lp_id Learnpath id
  4022. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4023. * @return bool
  4024. */
  4025. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4026. {
  4027. $course_id = api_get_course_int_id();
  4028. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4029. $lp_id = (int) $lp_id;
  4030. $sql = "SELECT * FROM $tbl_lp
  4031. WHERE iid = $lp_id";
  4032. $result = Database::query($sql);
  4033. if (Database::num_rows($result)) {
  4034. $row = Database::fetch_array($result);
  4035. $name = Database::escape_string($row['name']);
  4036. if ($set_visibility == 'i') {
  4037. $v = 0;
  4038. }
  4039. if ($set_visibility == 'v') {
  4040. $v = 1;
  4041. }
  4042. $session_id = api_get_session_id();
  4043. $session_condition = api_get_session_condition($session_id);
  4044. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4045. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4046. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4047. $sql = "SELECT * FROM $tbl_tool
  4048. WHERE
  4049. c_id = $course_id AND
  4050. (link = '$link' OR link = '$oldLink') AND
  4051. image = 'scormbuilder.gif' AND
  4052. (
  4053. link LIKE '$link%' OR
  4054. link LIKE '$oldLink%'
  4055. )
  4056. $session_condition
  4057. ";
  4058. $result = Database::query($sql);
  4059. $num = Database::num_rows($result);
  4060. if ($set_visibility == 'i' && $num > 0) {
  4061. $sql = "DELETE FROM $tbl_tool
  4062. WHERE
  4063. c_id = $course_id AND
  4064. (link = '$link' OR link = '$oldLink') AND
  4065. image='scormbuilder.gif'
  4066. $session_condition";
  4067. Database::query($sql);
  4068. } elseif ($set_visibility == 'v' && $num == 0) {
  4069. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4070. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4071. Database::query($sql);
  4072. $insertId = Database::insert_id();
  4073. if ($insertId) {
  4074. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4075. Database::query($sql);
  4076. }
  4077. } elseif ($set_visibility == 'v' && $num > 0) {
  4078. $sql = "UPDATE $tbl_tool SET
  4079. c_id = $course_id,
  4080. name = '$name',
  4081. link = '$link',
  4082. image = 'scormbuilder.gif',
  4083. visibility = '$v',
  4084. admin = '0',
  4085. address = 'pastillegris.gif',
  4086. added_tool = 0,
  4087. session_id = $session_id
  4088. WHERE
  4089. c_id = ".$course_id." AND
  4090. (link = '$link' OR link = '$oldLink') AND
  4091. image='scormbuilder.gif'
  4092. $session_condition
  4093. ";
  4094. Database::query($sql);
  4095. } else {
  4096. // Parameter and database incompatible, do nothing, exit.
  4097. return false;
  4098. }
  4099. } else {
  4100. return false;
  4101. }
  4102. }
  4103. /**
  4104. * Generate the link for a learnpath category as course tool
  4105. * @param int $categoryId
  4106. * @return string
  4107. */
  4108. private static function getCategoryLinkForTool($categoryId)
  4109. {
  4110. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  4111. .http_build_query(
  4112. [
  4113. 'action' => 'view_category',
  4114. 'id' => $categoryId
  4115. ]
  4116. );
  4117. return $link;
  4118. }
  4119. /**
  4120. * Publishes a learnpath.
  4121. * Show or hide the learnpath category on the course homepage
  4122. * @param int $id
  4123. * @param int $setVisibility
  4124. * @return bool
  4125. */
  4126. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4127. {
  4128. $courseId = api_get_course_int_id();
  4129. $sessionId = api_get_session_id();
  4130. $sessionCondition = api_get_session_condition(
  4131. $sessionId,
  4132. true,
  4133. false,
  4134. 't.sessionId'
  4135. );
  4136. $em = Database::getManager();
  4137. /** @var CLpCategory $category */
  4138. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4139. if (!$category) {
  4140. return false;
  4141. }
  4142. $link = self::getCategoryLinkForTool($id);
  4143. /** @var CTool $tool */
  4144. $tool = $em->createQuery("
  4145. SELECT t FROM ChamiloCourseBundle:CTool t
  4146. WHERE
  4147. t.cId = :course AND
  4148. t.link = :link1 AND
  4149. t.image = 'lp_category.gif' AND
  4150. t.link LIKE :link2
  4151. $sessionCondition
  4152. ")
  4153. ->setParameters([
  4154. 'course' => (int) $courseId,
  4155. 'link1' => $link,
  4156. 'link2' => "$link%"
  4157. ])
  4158. ->getOneOrNullResult();
  4159. if ($setVisibility == 0 && $tool) {
  4160. $em->remove($tool);
  4161. $em->flush();
  4162. return true;
  4163. }
  4164. if ($setVisibility == 1 && !$tool) {
  4165. $tool = new CTool();
  4166. $tool
  4167. ->setCategory('authoring')
  4168. ->setCId($courseId)
  4169. ->setName(strip_tags($category->getName()))
  4170. ->setLink($link)
  4171. ->setImage('lp_category.gif')
  4172. ->setVisibility(1)
  4173. ->setAdmin(0)
  4174. ->setAddress('pastillegris.gif')
  4175. ->setAddedTool(0)
  4176. ->setSessionId($sessionId)
  4177. ->setTarget('_self');
  4178. $em->persist($tool);
  4179. $em->flush();
  4180. $tool->setId($tool->getIid());
  4181. $em->persist($tool);
  4182. $em->flush();
  4183. return true;
  4184. }
  4185. if ($setVisibility == 1 && $tool) {
  4186. $tool
  4187. ->setName(strip_tags($category->getName()))
  4188. ->setVisibility(1);
  4189. $em->persist($tool);
  4190. $em->flush();
  4191. return true;
  4192. }
  4193. return false;
  4194. }
  4195. /**
  4196. * Check if the learnpath category is visible for a user
  4197. * @param CLpCategory $category
  4198. * @param User $user
  4199. * @return bool
  4200. */
  4201. public static function categoryIsVisibleForStudent(
  4202. CLpCategory $category,
  4203. User $user
  4204. ) {
  4205. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4206. if ($isAllowedToEdit) {
  4207. return true;
  4208. }
  4209. $users = $category->getUsers();
  4210. if (empty($users) || !$users->count()) {
  4211. return true;
  4212. }
  4213. if ($category->hasUserAdded($user)) {
  4214. return true;
  4215. }
  4216. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4217. if (!empty($groups)) {
  4218. $em = Database::getManager();
  4219. /** @var ItemPropertyRepository $itemRepo */
  4220. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4221. /** @var CourseRepository $courseRepo */
  4222. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4223. $sessionId = api_get_session_id();
  4224. $session = null;
  4225. if (!empty($sessionId)) {
  4226. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4227. }
  4228. $course = $courseRepo->find(api_get_course_int_id());
  4229. // Subscribed groups to a LP
  4230. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4231. TOOL_LEARNPATH_CATEGORY,
  4232. $category->getId(),
  4233. $course,
  4234. $session
  4235. );
  4236. if (!empty($subscribedGroupsInLp)) {
  4237. $groups = array_column($groups, 'iid');
  4238. /** @var CItemProperty $item */
  4239. foreach ($subscribedGroupsInLp as $item) {
  4240. if ($item->getGroup() &&
  4241. in_array($item->getGroup()->getId(), $groups)
  4242. ) {
  4243. return true;
  4244. }
  4245. }
  4246. }
  4247. }
  4248. return false;
  4249. }
  4250. /**
  4251. * Check if a learnpath category is published as course tool
  4252. * @param CLpCategory $category
  4253. * @param int $courseId
  4254. * @return bool
  4255. */
  4256. public static function categoryIsPublished(
  4257. CLpCategory $category,
  4258. $courseId
  4259. ) {
  4260. $link = self::getCategoryLinkForTool($category->getId());
  4261. $em = Database::getManager();
  4262. $tools = $em
  4263. ->createQuery("
  4264. SELECT t FROM ChamiloCourseBundle:CTool t
  4265. WHERE t.cId = :course AND
  4266. t.name = :name AND
  4267. t.image = 'lp_category.gif' AND
  4268. t.link LIKE :link
  4269. ")
  4270. ->setParameters([
  4271. 'course' => $courseId,
  4272. 'name' => strip_tags($category->getName()),
  4273. 'link' => "$link%"
  4274. ])
  4275. ->getResult();
  4276. /** @var CTool $tool */
  4277. $tool = current($tools);
  4278. return $tool ? $tool->getVisibility() : false;
  4279. }
  4280. /**
  4281. * Restart the whole learnpath. Return the URL of the first element.
  4282. * Make sure the results are saved with anoter method. This method should probably be
  4283. * redefined in children classes.
  4284. * To use a similar method statically, use the create_new_attempt() method
  4285. * @return bool
  4286. */
  4287. public function restart()
  4288. {
  4289. if ($this->debug > 0) {
  4290. error_log('New LP - In learnpath::restart()', 0);
  4291. }
  4292. // TODO
  4293. // Call autosave method to save the current progress.
  4294. //$this->index = 0;
  4295. if (api_is_invitee()) {
  4296. return false;
  4297. }
  4298. $session_id = api_get_session_id();
  4299. $course_id = api_get_course_int_id();
  4300. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4301. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4302. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4303. if ($this->debug > 2) {
  4304. error_log('New LP - Inserting new lp_view for restart: '.$sql, 0);
  4305. }
  4306. Database::query($sql);
  4307. $view_id = Database::insert_id();
  4308. if ($view_id) {
  4309. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4310. Database::query($sql);
  4311. $this->lp_view_id = $view_id;
  4312. $this->attempt = $this->attempt + 1;
  4313. } else {
  4314. $this->error = 'Could not insert into item_view table...';
  4315. return false;
  4316. }
  4317. $this->autocomplete_parents($this->current);
  4318. foreach ($this->items as $index => $dummy) {
  4319. $this->items[$index]->restart();
  4320. $this->items[$index]->set_lp_view($this->lp_view_id);
  4321. }
  4322. $this->first();
  4323. return true;
  4324. }
  4325. /**
  4326. * Saves the current item
  4327. * @return boolean
  4328. */
  4329. public function save_current()
  4330. {
  4331. $debug = $this->debug;
  4332. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4333. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4334. if ($debug) {
  4335. error_log('New LP - save_current() saving item '.$this->current, 0);
  4336. error_log(''.print_r($this->items, true), 0);
  4337. }
  4338. if (isset($this->items[$this->current]) &&
  4339. is_object($this->items[$this->current])
  4340. ) {
  4341. if ($debug) {
  4342. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->last_scorm_session_time);
  4343. }
  4344. $res = $this->items[$this->current]->save(
  4345. false,
  4346. $this->prerequisites_match($this->current)
  4347. );
  4348. $this->autocomplete_parents($this->current);
  4349. $status = $this->items[$this->current]->get_status();
  4350. $this->update_queue[$this->current] = $status;
  4351. if ($debug) {
  4352. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->last_scorm_session_time);
  4353. }
  4354. return $res;
  4355. }
  4356. return false;
  4357. }
  4358. /**
  4359. * Saves the given item
  4360. * @param integer $item_id Optional (will take from $_REQUEST if null)
  4361. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4362. * @return bool
  4363. */
  4364. public function save_item($item_id = null, $from_outside = true)
  4365. {
  4366. $debug = $this->debug;
  4367. if ($debug) {
  4368. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4369. }
  4370. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4371. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4372. if (empty($item_id)) {
  4373. $item_id = intval($_REQUEST['id']);
  4374. }
  4375. if (empty($item_id)) {
  4376. $item_id = $this->get_current_item_id();
  4377. }
  4378. if (isset($this->items[$item_id]) &&
  4379. is_object($this->items[$item_id])
  4380. ) {
  4381. if ($debug) {
  4382. error_log('Object exists');
  4383. }
  4384. // Saving the item.
  4385. $res = $this->items[$item_id]->save(
  4386. $from_outside,
  4387. $this->prerequisites_match($item_id)
  4388. );
  4389. if ($debug) {
  4390. error_log('update_queue before:');
  4391. error_log(print_r($this->update_queue, 1));
  4392. }
  4393. $this->autocomplete_parents($item_id);
  4394. $status = $this->items[$item_id]->get_status();
  4395. $this->update_queue[$item_id] = $status;
  4396. if ($debug) {
  4397. error_log('get_status(): '.$status);
  4398. error_log('update_queue after:');
  4399. error_log(print_r($this->update_queue, 1));
  4400. }
  4401. return $res;
  4402. }
  4403. return false;
  4404. }
  4405. /**
  4406. * Saves the last item seen's ID only in case
  4407. */
  4408. public function save_last()
  4409. {
  4410. $course_id = api_get_course_int_id();
  4411. if ($this->debug > 0) {
  4412. error_log('New LP - In learnpath::save_last()', 0);
  4413. }
  4414. $session_condition = api_get_session_condition(
  4415. api_get_session_id(),
  4416. true,
  4417. false
  4418. );
  4419. $table = Database::get_course_table(TABLE_LP_VIEW);
  4420. if (isset($this->current) && !api_is_invitee()) {
  4421. if ($this->debug > 2) {
  4422. error_log('New LP - Saving current item ('.$this->current.') for later review', 0);
  4423. }
  4424. $sql = "UPDATE $table SET
  4425. last_item = ".intval($this->get_current_item_id())."
  4426. WHERE
  4427. c_id = $course_id AND
  4428. lp_id = ".$this->get_id()." AND
  4429. user_id = ".$this->get_user_id()." ".$session_condition;
  4430. if ($this->debug > 2) {
  4431. error_log('New LP - Saving last item seen : '.$sql, 0);
  4432. }
  4433. Database::query($sql);
  4434. }
  4435. if (!api_is_invitee()) {
  4436. // Save progress.
  4437. list($progress, ) = $this->get_progress_bar_text('%');
  4438. if ($progress >= 0 && $progress <= 100) {
  4439. $progress = (int) $progress;
  4440. $sql = "UPDATE $table SET
  4441. progress = $progress
  4442. WHERE
  4443. c_id = $course_id AND
  4444. lp_id = " . $this->get_id()." AND
  4445. user_id = " . $this->get_user_id()." ".$session_condition;
  4446. // Ignore errors as some tables might not have the progress field just yet.
  4447. Database::query($sql);
  4448. $this->progress_db = $progress;
  4449. }
  4450. }
  4451. }
  4452. /**
  4453. * Sets the current item ID (checks if valid and authorized first)
  4454. * @param integer $item_id New item ID. If not given or not authorized, defaults to current
  4455. */
  4456. public function set_current_item($item_id = null)
  4457. {
  4458. if ($this->debug > 0) {
  4459. error_log('New LP - In learnpath::set_current_item('.$item_id.')', 0);
  4460. }
  4461. if (empty($item_id)) {
  4462. if ($this->debug > 2) {
  4463. error_log('New LP - No new current item given, ignore...', 0);
  4464. }
  4465. // Do nothing.
  4466. } else {
  4467. if ($this->debug > 2) {
  4468. error_log('New LP - New current item given is '.$item_id.'...', 0);
  4469. }
  4470. if (is_numeric($item_id)) {
  4471. $item_id = intval($item_id);
  4472. // TODO: Check in database here.
  4473. $this->last = $this->current;
  4474. $this->current = $item_id;
  4475. // TODO: Update $this->index as well.
  4476. foreach ($this->ordered_items as $index => $item) {
  4477. if ($item == $this->current) {
  4478. $this->index = $index;
  4479. break;
  4480. }
  4481. }
  4482. if ($this->debug > 2) {
  4483. error_log('New LP - set_current_item('.$item_id.') done. Index is now : '.$this->index, 0);
  4484. }
  4485. } else {
  4486. error_log('New LP - set_current_item('.$item_id.') failed. Not a numeric value: ', 0);
  4487. }
  4488. }
  4489. }
  4490. /**
  4491. * Sets the encoding
  4492. * @param string New encoding
  4493. * @return bool
  4494. * TODO (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4495. */
  4496. public function set_encoding($enc = 'UTF-8')
  4497. {
  4498. if ($this->debug > 0) {
  4499. error_log('New LP - In learnpath::set_encoding()', 0);
  4500. }
  4501. $enc = api_refine_encoding_id($enc);
  4502. if (empty($enc)) {
  4503. $enc = api_get_system_encoding();
  4504. }
  4505. if (api_is_encoding_supported($enc)) {
  4506. $lp = $this->get_id();
  4507. if ($lp != 0) {
  4508. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4509. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4510. WHERE iid = ".$lp;
  4511. $res = Database::query($sql);
  4512. return $res;
  4513. }
  4514. }
  4515. return false;
  4516. }
  4517. /**
  4518. * Sets the JS lib setting in the database directly.
  4519. * This is the JavaScript library file this lp needs to load on startup
  4520. * @param string Proximity setting
  4521. * @return boolean True on update success. False otherwise.
  4522. */
  4523. public function set_jslib($lib = '')
  4524. {
  4525. if ($this->debug > 0) {
  4526. error_log('New LP - In learnpath::set_jslib()', 0);
  4527. }
  4528. $lp = $this->get_id();
  4529. $course_id = api_get_course_int_id();
  4530. if ($lp != 0) {
  4531. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4532. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4533. WHERE iid = $lp";
  4534. $res = Database::query($sql);
  4535. return $res;
  4536. } else {
  4537. return false;
  4538. }
  4539. }
  4540. /**
  4541. * Sets the name of the LP maker (publisher) (and save)
  4542. * @param string Optional string giving the new content_maker of this learnpath
  4543. * @return boolean True
  4544. */
  4545. public function set_maker($name = '')
  4546. {
  4547. if ($this->debug > 0) {
  4548. error_log('New LP - In learnpath::set_maker()', 0);
  4549. }
  4550. if (empty($name)) {
  4551. return false;
  4552. }
  4553. $this->maker = $name;
  4554. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4555. $lp_id = $this->get_id();
  4556. $sql = "UPDATE $lp_table SET
  4557. content_maker = '".Database::escape_string($this->maker)."'
  4558. WHERE iid = $lp_id";
  4559. if ($this->debug > 2) {
  4560. error_log('New LP - lp updated with new content_maker : '.$this->maker, 0);
  4561. }
  4562. Database::query($sql);
  4563. return true;
  4564. }
  4565. /**
  4566. * Sets the name of the current learnpath (and save)
  4567. * @param string $name Optional string giving the new name of this learnpath
  4568. * @return boolean True/False
  4569. */
  4570. public function set_name($name = null)
  4571. {
  4572. if ($this->debug > 0) {
  4573. error_log('New LP - In learnpath::set_name()', 0);
  4574. }
  4575. if (empty($name)) {
  4576. return false;
  4577. }
  4578. $this->name = Database::escape_string($name);
  4579. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4580. $lp_id = $this->get_id();
  4581. $course_id = $this->course_info['real_id'];
  4582. $sql = "UPDATE $lp_table SET
  4583. name = '".Database::escape_string($this->name)."'
  4584. WHERE iid = $lp_id";
  4585. if ($this->debug > 2) {
  4586. error_log('New LP - lp updated with new name : '.$this->name, 0);
  4587. }
  4588. $result = Database::query($sql);
  4589. // If the lp is visible on the homepage, change his name there.
  4590. if (Database::affected_rows($result)) {
  4591. $session_id = api_get_session_id();
  4592. $session_condition = api_get_session_condition($session_id);
  4593. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4594. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4595. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4596. WHERE
  4597. c_id = $course_id AND
  4598. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4599. Database::query($sql);
  4600. return true;
  4601. } else {
  4602. return false;
  4603. }
  4604. }
  4605. /**
  4606. * Set index specified prefix terms for all items in this path
  4607. * @param string Comma-separated list of terms
  4608. * @param string Xapian term prefix
  4609. * @return boolean False on error, true otherwise
  4610. */
  4611. public function set_terms_by_prefix($terms_string, $prefix)
  4612. {
  4613. $course_id = api_get_course_int_id();
  4614. if (api_get_setting('search_enabled') !== 'true') {
  4615. return false;
  4616. }
  4617. if (!extension_loaded('xapian')) {
  4618. return false;
  4619. }
  4620. $terms_string = trim($terms_string);
  4621. $terms = explode(',', $terms_string);
  4622. array_walk($terms, 'trim_value');
  4623. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4624. // Don't do anything if no change, verify only at DB, not the search engine.
  4625. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4626. return false;
  4627. }
  4628. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4629. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4630. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4631. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4632. $lp_id = intval($_POST['lp_id']);
  4633. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4634. $result = Database::query($sql);
  4635. $di = new ChamiloIndexer();
  4636. while ($lp_item = Database::fetch_array($result)) {
  4637. // Get search_did.
  4638. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4639. $sql = 'SELECT * FROM %s
  4640. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4641. LIMIT 1';
  4642. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4643. //echo $sql; echo '<br>';
  4644. $res = Database::query($sql);
  4645. if (Database::num_rows($res) > 0) {
  4646. $se_ref = Database::fetch_array($res);
  4647. // Compare terms.
  4648. $doc = $di->get_document($se_ref['search_did']);
  4649. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4650. $xterms = [];
  4651. foreach ($xapian_terms as $xapian_term) {
  4652. $xterms[] = substr($xapian_term['name'], 1);
  4653. }
  4654. $dterms = $terms;
  4655. $missing_terms = array_diff($dterms, $xterms);
  4656. $deprecated_terms = array_diff($xterms, $dterms);
  4657. // Save it to search engine.
  4658. foreach ($missing_terms as $term) {
  4659. $doc->add_term($prefix.$term, 1);
  4660. }
  4661. foreach ($deprecated_terms as $term) {
  4662. $doc->remove_term($prefix.$term);
  4663. }
  4664. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4665. $di->getDb()->flush();
  4666. }
  4667. }
  4668. return true;
  4669. }
  4670. /**
  4671. * Sets the theme of the LP (local/remote) (and save)
  4672. * @param string Optional string giving the new theme of this learnpath
  4673. * @return bool Returns true if theme name is not empty
  4674. */
  4675. public function set_theme($name = '')
  4676. {
  4677. if ($this->debug > 0) {
  4678. error_log('New LP - In learnpath::set_theme()', 0);
  4679. }
  4680. $this->theme = $name;
  4681. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4682. $lp_id = $this->get_id();
  4683. $sql = "UPDATE $lp_table SET theme = '".Database::escape_string($this->theme)."'
  4684. WHERE iid = $lp_id";
  4685. if ($this->debug > 2) {
  4686. error_log('New LP - lp updated with new theme : '.$this->theme, 0);
  4687. }
  4688. Database::query($sql);
  4689. return true;
  4690. }
  4691. /**
  4692. * Sets the image of an LP (and save)
  4693. * @param string Optional string giving the new image of this learnpath
  4694. * @return bool Returns true if theme name is not empty
  4695. */
  4696. public function set_preview_image($name = '')
  4697. {
  4698. if ($this->debug > 0) {
  4699. error_log('New LP - In learnpath::set_preview_image()', 0);
  4700. }
  4701. $this->preview_image = $name;
  4702. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4703. $lp_id = $this->get_id();
  4704. $sql = "UPDATE $lp_table SET
  4705. preview_image = '".Database::escape_string($this->preview_image)."'
  4706. WHERE iid = $lp_id";
  4707. if ($this->debug > 2) {
  4708. error_log('New LP - lp updated with new preview image : '.$this->preview_image, 0);
  4709. }
  4710. Database::query($sql);
  4711. return true;
  4712. }
  4713. /**
  4714. * Sets the author of a LP (and save)
  4715. * @param string Optional string giving the new author of this learnpath
  4716. * @return bool Returns true if author's name is not empty
  4717. */
  4718. public function set_author($name = '')
  4719. {
  4720. if ($this->debug > 0) {
  4721. error_log('New LP - In learnpath::set_author()', 0);
  4722. }
  4723. $this->author = $name;
  4724. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4725. $lp_id = $this->get_id();
  4726. $sql = "UPDATE $lp_table SET author = '".Database::escape_string($name)."'
  4727. WHERE iid = $lp_id";
  4728. if ($this->debug > 2) {
  4729. error_log('New LP - lp updated with new preview author : '.$this->author, 0);
  4730. }
  4731. Database::query($sql);
  4732. return true;
  4733. }
  4734. /**
  4735. * Sets the hide_toc_frame parameter of a LP (and save)
  4736. * @param int 1 if frame is hidden 0 then else
  4737. * @return bool Returns true if author's name is not empty
  4738. */
  4739. public function set_hide_toc_frame($hide)
  4740. {
  4741. if ($this->debug > 0) {
  4742. error_log('New LP - In learnpath::set_hide_toc_frame()', 0);
  4743. }
  4744. if (intval($hide) == $hide) {
  4745. $this->hide_toc_frame = $hide;
  4746. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4747. $lp_id = $this->get_id();
  4748. $sql = "UPDATE $lp_table SET
  4749. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4750. WHERE iid = $lp_id";
  4751. if ($this->debug > 2) {
  4752. error_log('New LP - lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4753. }
  4754. Database::query($sql);
  4755. return true;
  4756. } else {
  4757. return false;
  4758. }
  4759. }
  4760. /**
  4761. * Sets the prerequisite of a LP (and save)
  4762. * @param int integer giving the new prerequisite of this learnpath
  4763. * @return bool returns true if prerequisite is not empty
  4764. */
  4765. public function set_prerequisite($prerequisite)
  4766. {
  4767. if ($this->debug > 0) {
  4768. error_log('New LP - In learnpath::set_prerequisite()', 0);
  4769. }
  4770. $this->prerequisite = intval($prerequisite);
  4771. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4772. $lp_id = $this->get_id();
  4773. $sql = "UPDATE $lp_table SET prerequisite = '".$this->prerequisite."'
  4774. WHERE iid = $lp_id";
  4775. if ($this->debug > 2) {
  4776. error_log('New LP - lp updated with new preview requisite : '.$this->requisite, 0);
  4777. }
  4778. Database::query($sql);
  4779. return true;
  4780. }
  4781. /**
  4782. * Sets the location/proximity of the LP (local/remote) (and save)
  4783. * @param string Optional string giving the new location of this learnpath
  4784. * @return boolean True on success / False on error
  4785. */
  4786. public function set_proximity($name = '')
  4787. {
  4788. if ($this->debug > 0) {
  4789. error_log('New LP - In learnpath::set_proximity()', 0);
  4790. }
  4791. if (empty($name)) {
  4792. return false;
  4793. }
  4794. $this->proximity = $name;
  4795. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4796. $lp_id = $this->get_id();
  4797. $sql = "UPDATE $lp_table SET
  4798. content_local = '".Database::escape_string($name)."'
  4799. WHERE iid = $lp_id";
  4800. if ($this->debug > 2) {
  4801. error_log('New LP - lp updated with new proximity : '.$this->proximity, 0);
  4802. }
  4803. Database::query($sql);
  4804. return true;
  4805. }
  4806. /**
  4807. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item
  4808. * @param integer DB ID of the item
  4809. */
  4810. public function set_previous_item($id)
  4811. {
  4812. if ($this->debug > 0) {
  4813. error_log('New LP - In learnpath::set_previous_item()', 0);
  4814. }
  4815. $this->last = $id;
  4816. }
  4817. /**
  4818. * Sets use_max_score
  4819. * @param int $use_max_score Optional string giving the new location of this learnpath
  4820. * @return boolean True on success / False on error
  4821. */
  4822. public function set_use_max_score($use_max_score = 1)
  4823. {
  4824. if ($this->debug > 0) {
  4825. error_log('New LP - In learnpath::set_use_max_score()', 0);
  4826. }
  4827. $use_max_score = intval($use_max_score);
  4828. $this->use_max_score = $use_max_score;
  4829. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4830. $lp_id = $this->get_id();
  4831. $sql = "UPDATE $lp_table SET
  4832. use_max_score = '".$this->use_max_score."'
  4833. WHERE iid = $lp_id";
  4834. if ($this->debug > 2) {
  4835. error_log('New LP - lp updated with new use_max_score : '.$this->use_max_score, 0);
  4836. }
  4837. Database::query($sql);
  4838. return true;
  4839. }
  4840. /**
  4841. * Sets and saves the expired_on date
  4842. * @param string $expired_on Optional string giving the new author of this learnpath
  4843. * @return bool Returns true if author's name is not empty
  4844. */
  4845. public function set_expired_on($expired_on)
  4846. {
  4847. if ($this->debug > 0) {
  4848. error_log('New LP - In learnpath::set_expired_on()', 0);
  4849. }
  4850. $em = Database::getManager();
  4851. /** @var CLp $lp */
  4852. $lp = $em
  4853. ->getRepository('ChamiloCourseBundle:CLp')
  4854. ->findOneBy(
  4855. [
  4856. 'iid' => $this->get_id()
  4857. ]
  4858. );
  4859. if (!$lp) {
  4860. return false;
  4861. }
  4862. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4863. $lp->setExpiredOn($this->expired_on);
  4864. $em->persist($lp);
  4865. $em->flush();
  4866. if ($this->debug > 2) {
  4867. error_log('New LP - lp updated with new expired_on : '.$this->expired_on, 0);
  4868. }
  4869. return true;
  4870. }
  4871. /**
  4872. * Sets and saves the publicated_on date
  4873. * @param string $publicated_on Optional string giving the new author of this learnpath
  4874. * @return bool Returns true if author's name is not empty
  4875. */
  4876. public function set_publicated_on($publicated_on)
  4877. {
  4878. if ($this->debug > 0) {
  4879. error_log('New LP - In learnpath::set_expired_on()', 0);
  4880. }
  4881. $em = Database::getManager();
  4882. /** @var CLp $lp */
  4883. $lp = $em
  4884. ->getRepository('ChamiloCourseBundle:CLp')
  4885. ->findOneBy(
  4886. [
  4887. 'iid' => $this->get_id()
  4888. ]
  4889. );
  4890. if (!$lp) {
  4891. return false;
  4892. }
  4893. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4894. $lp->setPublicatedOn($this->publicated_on);
  4895. $em->persist($lp);
  4896. $em->flush();
  4897. if ($this->debug > 2) {
  4898. error_log('New LP - lp updated with new publicated_on : '.$this->publicated_on, 0);
  4899. }
  4900. return true;
  4901. }
  4902. /**
  4903. * Sets and saves the expired_on date
  4904. * @return bool Returns true if author's name is not empty
  4905. */
  4906. public function set_modified_on()
  4907. {
  4908. if ($this->debug > 0) {
  4909. error_log('New LP - In learnpath::set_expired_on()', 0);
  4910. }
  4911. $this->modified_on = api_get_utc_datetime();
  4912. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4913. $lp_id = $this->get_id();
  4914. $sql = "UPDATE $lp_table SET modified_on = '".$this->modified_on."'
  4915. WHERE iid = $lp_id";
  4916. if ($this->debug > 2) {
  4917. error_log('New LP - lp updated with new expired_on : '.$this->modified_on, 0);
  4918. }
  4919. Database::query($sql);
  4920. return true;
  4921. }
  4922. /**
  4923. * Sets the object's error message
  4924. * @param string Error message. If empty, reinits the error string
  4925. * @return void
  4926. */
  4927. public function set_error_msg($error = '')
  4928. {
  4929. if ($this->debug > 0) {
  4930. error_log('New LP - In learnpath::set_error_msg()', 0);
  4931. }
  4932. if (empty($error)) {
  4933. $this->error = '';
  4934. } else {
  4935. $this->error .= $error;
  4936. }
  4937. }
  4938. /**
  4939. * Launches the current item if not 'sco'
  4940. * (starts timer and make sure there is a record ready in the DB)
  4941. * @param boolean $allow_new_attempt Whether to allow a new attempt or not
  4942. * @return boolean
  4943. */
  4944. public function start_current_item($allow_new_attempt = false)
  4945. {
  4946. if ($this->debug > 0) {
  4947. error_log('New LP - In learnpath::start_current_item()', 0);
  4948. }
  4949. if ($this->current != 0 && is_object($this->items[$this->current])) {
  4950. $type = $this->get_type();
  4951. $item_type = $this->items[$this->current]->get_type();
  4952. if (($type == 2 && $item_type != 'sco') ||
  4953. ($type == 3 && $item_type != 'au') ||
  4954. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4955. ) {
  4956. $this->items[$this->current]->open($allow_new_attempt);
  4957. $this->autocomplete_parents($this->current);
  4958. $prereq_check = $this->prerequisites_match($this->current);
  4959. $this->items[$this->current]->save(false, $prereq_check);
  4960. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  4961. }
  4962. // If sco, then it is supposed to have been updated by some other call.
  4963. if ($item_type == 'sco') {
  4964. $this->items[$this->current]->restart();
  4965. }
  4966. }
  4967. if ($this->debug > 0) {
  4968. error_log('New LP - End of learnpath::start_current_item()', 0);
  4969. }
  4970. return true;
  4971. }
  4972. /**
  4973. * Stops the processing and counters for the old item (as held in $this->last)
  4974. * @return boolean True/False
  4975. */
  4976. public function stop_previous_item()
  4977. {
  4978. if ($this->debug > 0) {
  4979. error_log('New LP - In learnpath::stop_previous_item()', 0);
  4980. }
  4981. if ($this->last != 0 && $this->last != $this->current && is_object($this->items[$this->last])) {
  4982. if ($this->debug > 2) {
  4983. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' is object', 0);
  4984. }
  4985. switch ($this->get_type()) {
  4986. case '3':
  4987. if ($this->items[$this->last]->get_type() != 'au') {
  4988. if ($this->debug > 2) {
  4989. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au', 0);
  4990. }
  4991. $this->items[$this->last]->close();
  4992. //$this->autocomplete_parents($this->last);
  4993. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  4994. } else {
  4995. if ($this->debug > 2) {
  4996. error_log('New LP - In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals', 0);
  4997. }
  4998. }
  4999. break;
  5000. case '2':
  5001. if ($this->items[$this->last]->get_type() != 'sco') {
  5002. if ($this->debug > 2) {
  5003. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco', 0);
  5004. }
  5005. $this->items[$this->last]->close();
  5006. //$this->autocomplete_parents($this->last);
  5007. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  5008. } else {
  5009. if ($this->debug > 2) {
  5010. error_log('New LP - In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals', 0);
  5011. }
  5012. }
  5013. break;
  5014. case '1':
  5015. default:
  5016. if ($this->debug > 2) {
  5017. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset', 0);
  5018. }
  5019. $this->items[$this->last]->close();
  5020. break;
  5021. }
  5022. } else {
  5023. if ($this->debug > 2) {
  5024. error_log('New LP - In learnpath::stop_previous_item() - No previous element found, ignoring...', 0);
  5025. }
  5026. return false;
  5027. }
  5028. return true;
  5029. }
  5030. /**
  5031. * Updates the default view mode from fullscreen to embedded and inversely
  5032. * @return string The current default view mode ('fullscreen' or 'embedded')
  5033. */
  5034. public function update_default_view_mode()
  5035. {
  5036. if ($this->debug > 0) {
  5037. error_log('New LP - In learnpath::update_default_view_mode()', 0);
  5038. }
  5039. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5040. $sql = "SELECT * FROM $lp_table
  5041. WHERE iid = ".$this->get_id();
  5042. $res = Database::query($sql);
  5043. if (Database::num_rows($res) > 0) {
  5044. $row = Database::fetch_array($res);
  5045. $default_view_mode = $row['default_view_mod'];
  5046. $view_mode = $default_view_mode;
  5047. switch ($default_view_mode) {
  5048. case 'fullscreen': // default with popup
  5049. $view_mode = 'embedded';
  5050. break;
  5051. case 'embedded': // default view with left menu
  5052. $view_mode = 'embedframe';
  5053. break;
  5054. case 'embedframe': //folded menu
  5055. $view_mode = 'impress';
  5056. break;
  5057. case 'impress':
  5058. $view_mode = 'fullscreen';
  5059. break;
  5060. }
  5061. $sql = "UPDATE $lp_table SET default_view_mod = '$view_mode'
  5062. WHERE iid = ".$this->get_id();
  5063. Database::query($sql);
  5064. $this->mode = $view_mode;
  5065. return $view_mode;
  5066. } else {
  5067. if ($this->debug > 2) {
  5068. error_log('New LP - Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5069. }
  5070. }
  5071. return -1;
  5072. }
  5073. /**
  5074. * Updates the default behaviour about auto-commiting SCORM updates
  5075. * @return boolean True if auto-commit has been set to 'on', false otherwise
  5076. */
  5077. public function update_default_scorm_commit()
  5078. {
  5079. if ($this->debug > 0) {
  5080. error_log('New LP - In learnpath::update_default_scorm_commit()', 0);
  5081. }
  5082. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5083. $sql = "SELECT * FROM $lp_table
  5084. WHERE iid = ".$this->get_id();
  5085. $res = Database::query($sql);
  5086. if (Database::num_rows($res) > 0) {
  5087. $row = Database::fetch_array($res);
  5088. $force = $row['force_commit'];
  5089. if ($force == 1) {
  5090. $force = 0;
  5091. $force_return = false;
  5092. } elseif ($force == 0) {
  5093. $force = 1;
  5094. $force_return = true;
  5095. }
  5096. $sql = "UPDATE $lp_table SET force_commit = $force
  5097. WHERE iid = ".$this->get_id();
  5098. Database::query($sql);
  5099. $this->force_commit = $force_return;
  5100. return $force_return;
  5101. } else {
  5102. if ($this->debug > 2) {
  5103. error_log('New LP - Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5104. }
  5105. }
  5106. return -1;
  5107. }
  5108. /**
  5109. * Updates the order of learning paths (goes through all of them by order and fills the gaps)
  5110. * @return bool True on success, false on failure
  5111. */
  5112. public function update_display_order()
  5113. {
  5114. $course_id = api_get_course_int_id();
  5115. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5116. $sql = "SELECT * FROM $lp_table WHERE c_id = $course_id ORDER BY display_order";
  5117. $res = Database::query($sql);
  5118. if ($res === false) {
  5119. return false;
  5120. }
  5121. $num = Database::num_rows($res);
  5122. // First check the order is correct, globally (might be wrong because
  5123. // of versions < 1.8.4).
  5124. if ($num > 0) {
  5125. $i = 1;
  5126. while ($row = Database::fetch_array($res)) {
  5127. if ($row['display_order'] != $i) {
  5128. // If we find a gap in the order, we need to fix it.
  5129. $sql = "UPDATE $lp_table SET display_order = $i
  5130. WHERE iid = ".$row['iid'];
  5131. Database::query($sql);
  5132. }
  5133. $i++;
  5134. }
  5135. }
  5136. return true;
  5137. }
  5138. /**
  5139. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view
  5140. * @return boolean True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5141. */
  5142. public function update_reinit()
  5143. {
  5144. $course_id = api_get_course_int_id();
  5145. if ($this->debug > 0) {
  5146. error_log('New LP - In learnpath::update_reinit()', 0);
  5147. }
  5148. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5149. $sql = "SELECT * FROM $lp_table
  5150. WHERE iid = ".$this->get_id();
  5151. $res = Database::query($sql);
  5152. if (Database::num_rows($res) > 0) {
  5153. $row = Database::fetch_array($res);
  5154. $force = $row['prevent_reinit'];
  5155. if ($force == 1) {
  5156. $force = 0;
  5157. } elseif ($force == 0) {
  5158. $force = 1;
  5159. }
  5160. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5161. WHERE iid = ".$this->get_id();
  5162. Database::query($sql);
  5163. $this->prevent_reinit = $force;
  5164. return $force;
  5165. } else {
  5166. if ($this->debug > 2) {
  5167. error_log('New LP - Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5168. }
  5169. }
  5170. return -1;
  5171. }
  5172. /**
  5173. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag
  5174. *
  5175. * @return string 'single', 'multi' or 'seriousgame'
  5176. * @author ndiechburg <noel@cblue.be>
  5177. **/
  5178. public function get_attempt_mode()
  5179. {
  5180. //Set default value for seriousgame_mode
  5181. if (!isset($this->seriousgame_mode)) {
  5182. $this->seriousgame_mode = 0;
  5183. }
  5184. // Set default value for prevent_reinit
  5185. if (!isset($this->prevent_reinit)) {
  5186. $this->prevent_reinit = 1;
  5187. }
  5188. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5189. return 'seriousgame';
  5190. }
  5191. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5192. return 'single';
  5193. }
  5194. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5195. return 'multiple';
  5196. }
  5197. return 'single';
  5198. }
  5199. /**
  5200. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags
  5201. *
  5202. * @param string 'seriousgame', 'single' or 'multiple'
  5203. * @return boolean
  5204. * @author ndiechburg <noel@cblue.be>
  5205. **/
  5206. public function set_attempt_mode($mode)
  5207. {
  5208. switch ($mode) {
  5209. case 'seriousgame':
  5210. $sg_mode = 1;
  5211. $prevent_reinit = 1;
  5212. break;
  5213. case 'single':
  5214. $sg_mode = 0;
  5215. $prevent_reinit = 1;
  5216. break;
  5217. case 'multiple':
  5218. $sg_mode = 0;
  5219. $prevent_reinit = 0;
  5220. break;
  5221. default:
  5222. $sg_mode = 0;
  5223. $prevent_reinit = 0;
  5224. break;
  5225. }
  5226. $this->prevent_reinit = $prevent_reinit;
  5227. $this->seriousgame_mode = $sg_mode;
  5228. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5229. $sql = "UPDATE $lp_table SET
  5230. prevent_reinit = $prevent_reinit ,
  5231. seriousgame_mode = $sg_mode
  5232. WHERE iid = ".$this->get_id();
  5233. $res = Database::query($sql);
  5234. if ($res) {
  5235. return true;
  5236. } else {
  5237. return false;
  5238. }
  5239. }
  5240. /**
  5241. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm)
  5242. *
  5243. * @author ndiechburg <noel@cblue.be>
  5244. **/
  5245. public function switch_attempt_mode()
  5246. {
  5247. if ($this->debug > 0) {
  5248. error_log('New LP - In learnpath::switch_attempt_mode()', 0);
  5249. }
  5250. $mode = $this->get_attempt_mode();
  5251. switch ($mode) {
  5252. case 'single':
  5253. $next_mode = 'multiple';
  5254. break;
  5255. case 'multiple':
  5256. $next_mode = 'seriousgame';
  5257. break;
  5258. case 'seriousgame':
  5259. $next_mode = 'single';
  5260. break;
  5261. default:
  5262. $next_mode = 'single';
  5263. break;
  5264. }
  5265. $this->set_attempt_mode($next_mode);
  5266. }
  5267. /**
  5268. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5269. * but possibility to do again a completed item.
  5270. *
  5271. * @return boolean true if seriousgame_mode has been set to 1, false otherwise
  5272. * @author ndiechburg <noel@cblue.be>
  5273. **/
  5274. public function set_seriousgame_mode()
  5275. {
  5276. if ($this->debug > 0) {
  5277. error_log('New LP - In learnpath::set_seriousgame_mode()', 0);
  5278. }
  5279. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5280. $sql = "SELECT * FROM $lp_table
  5281. WHERE iid = ".$this->get_id();
  5282. $res = Database::query($sql);
  5283. if (Database::num_rows($res) > 0) {
  5284. $row = Database::fetch_array($res);
  5285. $force = $row['seriousgame_mode'];
  5286. if ($force == 1) {
  5287. $force = 0;
  5288. } elseif ($force == 0) {
  5289. $force = 1;
  5290. }
  5291. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5292. WHERE iid = ".$this->get_id();
  5293. Database::query($sql);
  5294. $this->seriousgame_mode = $force;
  5295. return $force;
  5296. } else {
  5297. if ($this->debug > 2) {
  5298. error_log('New LP - Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5299. }
  5300. }
  5301. return -1;
  5302. }
  5303. /**
  5304. * Updates the "scorm_debug" value that shows or hide the debug window
  5305. * @return boolean True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5306. */
  5307. public function update_scorm_debug()
  5308. {
  5309. if ($this->debug > 0) {
  5310. error_log('New LP - In learnpath::update_scorm_debug()', 0);
  5311. }
  5312. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5313. $sql = "SELECT * FROM $lp_table
  5314. WHERE iid = ".$this->get_id();
  5315. $res = Database::query($sql);
  5316. if (Database::num_rows($res) > 0) {
  5317. $row = Database::fetch_array($res);
  5318. $force = $row['debug'];
  5319. if ($force == 1) {
  5320. $force = 0;
  5321. } elseif ($force == 0) {
  5322. $force = 1;
  5323. }
  5324. $sql = "UPDATE $lp_table SET debug = $force
  5325. WHERE iid = ".$this->get_id();
  5326. Database::query($sql);
  5327. $this->scorm_debug = $force;
  5328. return $force;
  5329. } else {
  5330. if ($this->debug > 2) {
  5331. error_log('New LP - Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5332. }
  5333. }
  5334. return -1;
  5335. }
  5336. /**
  5337. * Function that makes a call to the function sort_tree_array and create_tree_array
  5338. * @author Kevin Van Den Haute
  5339. * @param array
  5340. */
  5341. public function tree_array($array)
  5342. {
  5343. if ($this->debug > 1) {
  5344. error_log('New LP - In learnpath::tree_array()', 0);
  5345. }
  5346. $array = $this->sort_tree_array($array);
  5347. $this->create_tree_array($array);
  5348. }
  5349. /**
  5350. * Creates an array with the elements of the learning path tree in it
  5351. *
  5352. * @author Kevin Van Den Haute
  5353. * @param array $array
  5354. * @param int $parent
  5355. * @param int $depth
  5356. * @param array $tmp
  5357. */
  5358. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5359. {
  5360. if ($this->debug > 1) {
  5361. error_log('New LP - In learnpath::create_tree_array())', 0);
  5362. }
  5363. if (is_array($array)) {
  5364. for ($i = 0; $i < count($array); $i++) {
  5365. if ($array[$i]['parent_item_id'] == $parent) {
  5366. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5367. $tmp[] = $array[$i]['parent_item_id'];
  5368. $depth++;
  5369. }
  5370. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5371. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5372. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5373. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5374. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5375. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5376. $this->arrMenu[] = [
  5377. 'id' => $array[$i]['id'],
  5378. 'ref' => $ref,
  5379. 'item_type' => $array[$i]['item_type'],
  5380. 'title' => $array[$i]['title'],
  5381. 'path' => $path,
  5382. 'description' => $array[$i]['description'],
  5383. 'parent_item_id' => $array[$i]['parent_item_id'],
  5384. 'previous_item_id' => $array[$i]['previous_item_id'],
  5385. 'next_item_id' => $array[$i]['next_item_id'],
  5386. 'min_score' => $array[$i]['min_score'],
  5387. 'max_score' => $array[$i]['max_score'],
  5388. 'mastery_score' => $array[$i]['mastery_score'],
  5389. 'display_order' => $array[$i]['display_order'],
  5390. 'prerequisite' => $preq,
  5391. 'depth' => $depth,
  5392. 'audio' => $audio,
  5393. 'prerequisite_min_score' => $prerequisiteMinScore,
  5394. 'prerequisite_max_score' => $prerequisiteMaxScore
  5395. ];
  5396. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5397. }
  5398. }
  5399. }
  5400. }
  5401. /**
  5402. * Sorts a multi dimensional array by parent id and display order
  5403. * @author Kevin Van Den Haute
  5404. *
  5405. * @param array $array (array with al the learning path items in it)
  5406. *
  5407. * @return array
  5408. */
  5409. public function sort_tree_array($array)
  5410. {
  5411. foreach ($array as $key => $row) {
  5412. $parent[$key] = $row['parent_item_id'];
  5413. $position[$key] = $row['display_order'];
  5414. }
  5415. if (count($array) > 0) {
  5416. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5417. }
  5418. return $array;
  5419. }
  5420. /**
  5421. * Function that creates a html list of learning path items so that we can add audio files to them
  5422. * @author Kevin Van Den Haute
  5423. * @return string
  5424. */
  5425. public function overview()
  5426. {
  5427. if ($this->debug > 0) {
  5428. error_log('New LP - In learnpath::overview()', 0);
  5429. }
  5430. $return = '';
  5431. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5432. // we need to start a form when we want to update all the mp3 files
  5433. if ($update_audio == 'true') {
  5434. $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">';
  5435. }
  5436. $return .= '<div id="message"></div>';
  5437. if (count($this->items) == 0) {
  5438. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5439. } else {
  5440. $return_audio = '<table class="data_table">';
  5441. $return_audio .= '<tr>';
  5442. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5443. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5444. $return_audio .= '</tr>';
  5445. if ($update_audio != 'true') {
  5446. $return .= '<div class="col-md-12">';
  5447. $return .= self::return_new_tree($update_audio);
  5448. $return .= '</div>';
  5449. $return .= Display::div(
  5450. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5451. ['style' => 'float:left; margin-top:15px;width:100%']
  5452. );
  5453. } else {
  5454. $return_audio .= self::return_new_tree($update_audio);
  5455. $return .= $return_audio.'</table>';
  5456. }
  5457. // We need to close the form when we are updating the mp3 files.
  5458. if ($update_audio == 'true') {
  5459. $return .= '<div class="footer-audio">';
  5460. $return .= Display::button(
  5461. 'save_audio',
  5462. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5463. ['class' => 'btn btn-primary', 'type' => 'submit']
  5464. );
  5465. $return .= '</div>';
  5466. }
  5467. }
  5468. // We need to close the form when we are updating the mp3 files.
  5469. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5470. $return .= '</form>';
  5471. }
  5472. return $return;
  5473. }
  5474. /**
  5475. * @param string string $update_audio
  5476. * @param bool $drop_element_here
  5477. * @return string
  5478. */
  5479. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5480. {
  5481. $return = '';
  5482. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5483. $course_id = api_get_course_int_id();
  5484. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  5485. $sql = "SELECT * FROM $tbl_lp_item
  5486. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5487. $result = Database::query($sql);
  5488. $arrLP = [];
  5489. while ($row = Database::fetch_array($result)) {
  5490. $arrLP[] = [
  5491. 'id' => $row['id'],
  5492. 'item_type' => $row['item_type'],
  5493. 'title' => Security::remove_XSS($row['title']),
  5494. 'path' => $row['path'],
  5495. 'description' => Security::remove_XSS($row['description']),
  5496. 'parent_item_id' => $row['parent_item_id'],
  5497. 'previous_item_id' => $row['previous_item_id'],
  5498. 'next_item_id' => $row['next_item_id'],
  5499. 'max_score' => $row['max_score'],
  5500. 'min_score' => $row['min_score'],
  5501. 'mastery_score' => $row['mastery_score'],
  5502. 'prerequisite' => $row['prerequisite'],
  5503. 'display_order' => $row['display_order'],
  5504. 'audio' => $row['audio'],
  5505. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5506. 'prerequisite_min_score' => $row['prerequisite_min_score']
  5507. ];
  5508. }
  5509. $this->tree_array($arrLP);
  5510. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  5511. unset($this->arrMenu);
  5512. $default_data = null;
  5513. $default_content = null;
  5514. $elements = [];
  5515. $return_audio = null;
  5516. for ($i = 0; $i < count($arrLP); $i++) {
  5517. $title = $arrLP[$i]['title'];
  5518. $title_cut = cut($arrLP[$i]['title'], 25);
  5519. // Link for the documents
  5520. if ($arrLP[$i]['item_type'] == 'document') {
  5521. $url = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5522. $title_cut = Display::url(
  5523. $title_cut,
  5524. $url,
  5525. [
  5526. 'class' => 'ajax moved',
  5527. 'data-title' => $title,
  5528. 'title' => $title
  5529. ]
  5530. );
  5531. }
  5532. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5533. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5534. Session::write('pathItem', $arrLP[$i]['path']);
  5535. }
  5536. if (($i % 2) == 0) {
  5537. $oddClass = 'row_odd';
  5538. } else {
  5539. $oddClass = 'row_even';
  5540. }
  5541. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5542. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5543. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  5544. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5545. } else {
  5546. if (file_exists('../img/lp_'.$icon_name.'.gif')) {
  5547. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5548. } else {
  5549. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5550. $icon = Display::return_icon('certificate.png');
  5551. } else {
  5552. $icon = Display::return_icon('folder_document.gif');
  5553. }
  5554. }
  5555. }
  5556. // The audio column.
  5557. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5558. $audio = '';
  5559. if (!$update_audio || $update_audio <> 'true') {
  5560. if (empty($arrLP[$i]['audio'])) {
  5561. $audio .= '';
  5562. }
  5563. } else {
  5564. $types = self::getChapterTypes();
  5565. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5566. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5567. if (!empty($arrLP[$i]['audio'])) {
  5568. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5569. <input type="checkbox" name="removemp3' . $arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5570. }
  5571. }
  5572. }
  5573. $return_audio .= Display::span($icon.' '.$title).
  5574. Display::tag(
  5575. 'td',
  5576. $audio,
  5577. ['style' => '']
  5578. );
  5579. $return_audio .= '</td>';
  5580. $move_icon = '';
  5581. $move_item_icon = '';
  5582. $edit_icon = '';
  5583. $delete_icon = '';
  5584. $audio_icon = '';
  5585. $prerequisities_icon = '';
  5586. $forumIcon = '';
  5587. $previewIcon = '';
  5588. if ($is_allowed_to_edit) {
  5589. if (!$update_audio || $update_audio <> 'true') {
  5590. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5591. $move_icon .= '<a class="moved" href="#">';
  5592. $move_icon .= Display::return_icon(
  5593. 'move_everywhere.png',
  5594. get_lang('Move'),
  5595. [],
  5596. ICON_SIZE_TINY
  5597. );
  5598. $move_icon .= '</a>';
  5599. }
  5600. }
  5601. // No edit for this item types
  5602. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5603. if ($arrLP[$i]['item_type'] != 'dir') {
  5604. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5605. $edit_icon .= Display::return_icon(
  5606. 'edit.png',
  5607. get_lang('LearnpathEditModule'),
  5608. [],
  5609. ICON_SIZE_TINY
  5610. );
  5611. $edit_icon .= '</a>';
  5612. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5613. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5614. $this->course_int_id,
  5615. $this->lp_session_id
  5616. );
  5617. if ($forumThread) {
  5618. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5619. 'action' => 'dissociate_forum',
  5620. 'id' => $arrLP[$i]['id'],
  5621. 'lp_id' => $this->lp_id
  5622. ]);
  5623. $forumIcon = Display::url(
  5624. Display::return_icon('forum.png', get_lang('DissociateForumToLPItem'), [], ICON_SIZE_TINY),
  5625. $forumIconUrl,
  5626. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5627. );
  5628. } else {
  5629. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5630. 'action' => 'create_forum',
  5631. 'id' => $arrLP[$i]['id'],
  5632. 'lp_id' => $this->lp_id
  5633. ]);
  5634. $forumIcon = Display::url(
  5635. Display::return_icon('forum.png', get_lang('AssociateForumToLPItem'), [], ICON_SIZE_TINY),
  5636. $forumIconUrl,
  5637. ['class' => "btn btn-default lp-btn-associate-forum"]
  5638. );
  5639. }
  5640. }
  5641. } else {
  5642. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5643. $edit_icon .= Display::return_icon(
  5644. 'edit.png',
  5645. get_lang('LearnpathEditModule'),
  5646. [],
  5647. ICON_SIZE_TINY
  5648. );
  5649. $edit_icon .= '</a>';
  5650. }
  5651. } else {
  5652. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5653. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5654. $edit_icon .= Display::return_icon(
  5655. 'edit.png',
  5656. get_lang('Edit'),
  5657. [],
  5658. ICON_SIZE_TINY
  5659. );
  5660. $edit_icon .= '</a>';
  5661. }
  5662. }
  5663. $delete_icon .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" onclick="return confirmation(\''.addslashes($title).'\');" class="btn btn-default">';
  5664. $delete_icon .= Display::return_icon(
  5665. 'delete.png',
  5666. get_lang('LearnpathDeleteModule'),
  5667. [],
  5668. ICON_SIZE_TINY
  5669. );
  5670. $delete_icon .= '</a>';
  5671. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5672. $previewImage = Display::return_icon(
  5673. 'preview_view.png',
  5674. get_lang('Preview'),
  5675. [],
  5676. ICON_SIZE_TINY
  5677. );
  5678. switch ($arrLP[$i]['item_type']) {
  5679. case TOOL_DOCUMENT:
  5680. case TOOL_LP_FINAL_ITEM:
  5681. $urlPreviewLink = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5682. $previewIcon = Display::url(
  5683. $previewImage,
  5684. $urlPreviewLink,
  5685. [
  5686. 'target' => '_blank',
  5687. 'class' => 'btn btn-default',
  5688. 'data-title' => $arrLP[$i]['title'],
  5689. 'title' => $arrLP[$i]['title']
  5690. ]
  5691. );
  5692. break;
  5693. case TOOL_THREAD:
  5694. case TOOL_FORUM:
  5695. case TOOL_QUIZ:
  5696. case TOOL_STUDENTPUBLICATION:
  5697. case TOOL_LP_FINAL_ITEM:
  5698. case TOOL_LINK:
  5699. //$target = '';
  5700. //$class = 'btn btn-default ajax';
  5701. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5702. $class = 'btn btn-default';
  5703. $target = '_blank';
  5704. //}
  5705. $link = self::rl_get_resource_link_for_learnpath(
  5706. $this->course_int_id,
  5707. $this->lp_id,
  5708. $arrLP[$i]['id'],
  5709. 0,
  5710. ''
  5711. );
  5712. $previewIcon = Display::url(
  5713. $previewImage,
  5714. $link,
  5715. [
  5716. 'class' => $class,
  5717. 'data-title' => $arrLP[$i]['title'],
  5718. 'title' => $arrLP[$i]['title'],
  5719. 'target' => $target
  5720. ]
  5721. );
  5722. break;
  5723. default:
  5724. $previewIcon = Display::url(
  5725. $previewImage,
  5726. $url.'&action=view_item',
  5727. ['class' => 'btn btn-default', 'target' => '_blank']
  5728. );
  5729. break;
  5730. }
  5731. if ($arrLP[$i]['item_type'] != 'dir') {
  5732. $prerequisities_icon = Display::url(
  5733. Display::return_icon(
  5734. 'accept.png',
  5735. get_lang('LearnpathPrerequisites'),
  5736. [],
  5737. ICON_SIZE_TINY
  5738. ),
  5739. $url.'&action=edit_item_prereq',
  5740. ['class' => 'btn btn-default']
  5741. );
  5742. if ($arrLP[$i]['item_type'] != 'final_item') {
  5743. $move_item_icon = Display::url(
  5744. Display::return_icon(
  5745. 'move.png',
  5746. get_lang('Move'),
  5747. [],
  5748. ICON_SIZE_TINY
  5749. ),
  5750. $url.'&action=move_item',
  5751. ['class' => 'btn btn-default']
  5752. );
  5753. }
  5754. $audio_icon = Display::url(
  5755. Display::return_icon(
  5756. 'audio.png',
  5757. get_lang('UplUpload'),
  5758. [],
  5759. ICON_SIZE_TINY
  5760. ),
  5761. $url.'&action=add_audio',
  5762. ['class' => 'btn btn-default']
  5763. );
  5764. }
  5765. }
  5766. if ($update_audio != 'true') {
  5767. $row = $move_icon.' '.$icon.
  5768. Display::span($title_cut).
  5769. Display::tag(
  5770. 'div',
  5771. "<div class=\"btn-group btn-group-xs\">$previewIcon $audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
  5772. ['class'=>'btn-toolbar button_actions']
  5773. );
  5774. } else {
  5775. $row = Display::span($title.$icon).Display::span($audio, ['class'=>'button_actions']);
  5776. }
  5777. $parent_id = $arrLP[$i]['parent_item_id'];
  5778. $default_data[$arrLP[$i]['id']] = $row;
  5779. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5780. if (empty($parent_id)) {
  5781. $elements[$arrLP[$i]['id']]['data'] = $row;
  5782. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5783. } else {
  5784. $parent_arrays = [];
  5785. if ($arrLP[$i]['depth'] > 1) {
  5786. //Getting list of parents
  5787. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5788. foreach ($arrLP as $item) {
  5789. if ($item['id'] == $parent_id) {
  5790. if ($item['parent_item_id'] == 0) {
  5791. $parent_id = $item['id'];
  5792. break;
  5793. } else {
  5794. $parent_id = $item['parent_item_id'];
  5795. if (empty($parent_arrays)) {
  5796. $parent_arrays[] = intval($item['id']);
  5797. }
  5798. $parent_arrays[] = $parent_id;
  5799. break;
  5800. }
  5801. }
  5802. }
  5803. }
  5804. }
  5805. if (!empty($parent_arrays)) {
  5806. $parent_arrays = array_reverse($parent_arrays);
  5807. $val = '$elements';
  5808. $x = 0;
  5809. foreach ($parent_arrays as $item) {
  5810. if ($x != count($parent_arrays) - 1) {
  5811. $val .= '["'.$item.'"]["children"]';
  5812. } else {
  5813. $val .= '["'.$item.'"]["children"]';
  5814. }
  5815. $x++;
  5816. }
  5817. $val .= "";
  5818. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5819. eval($code_str);
  5820. } else {
  5821. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5822. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5823. }
  5824. }
  5825. }
  5826. $list = '<ul id="lp_item_list">';
  5827. $tree = self::print_recursive(
  5828. $elements,
  5829. $default_data,
  5830. $default_content
  5831. );
  5832. if (!empty($tree)) {
  5833. $list .= $tree;
  5834. } else {
  5835. if ($drop_element_here) {
  5836. $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
  5837. }
  5838. }
  5839. $list .= '</ul>';
  5840. $return .= Display::panelCollapse(
  5841. $this->name,
  5842. $list,
  5843. 'scorm-list',
  5844. null,
  5845. 'scorm-list-accordion',
  5846. 'scorm-list-collapse'
  5847. );
  5848. if ($update_audio == 'true') {
  5849. $return = $return_audio;
  5850. }
  5851. return $return;
  5852. }
  5853. /**
  5854. * @param array $elements
  5855. * @param array $default_data
  5856. * @param array $default_content
  5857. * @return string
  5858. */
  5859. public function print_recursive($elements, $default_data, $default_content)
  5860. {
  5861. $return = '';
  5862. foreach ($elements as $key => $item) {
  5863. if (isset($item['load_data']) || empty($item['data'])) {
  5864. $item['data'] = $default_data[$item['load_data']];
  5865. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5866. }
  5867. $sub_list = '';
  5868. if (isset($item['type']) && $item['type'] == 'dir') {
  5869. $sub_list = Display::tag('li', '', ['class'=>'sub_item empty']); // empty value
  5870. }
  5871. if (empty($item['children'])) {
  5872. $sub_list = Display::tag('ul', $sub_list, ['id'=>'UL_'.$key, 'class'=>'record li_container']);
  5873. $active = null;
  5874. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5875. $active = 'active';
  5876. }
  5877. $return .= Display::tag(
  5878. 'li',
  5879. Display::div($item['data'], ['class'=>"item_data $active"]).$sub_list,
  5880. ['id'=>$key, 'class'=>'record li_container']
  5881. );
  5882. } else {
  5883. // Sections
  5884. if (isset($item['children'])) {
  5885. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5886. }
  5887. $sub_list = Display::tag('ul', $sub_list.$data, ['id'=>'UL_'.$key, 'class'=>'record li_container']);
  5888. $return .= Display::tag(
  5889. 'li',
  5890. Display::div($item['data'], ['class'=>'item_data']).$sub_list,
  5891. ['id'=>$key, 'class'=>'record li_container']
  5892. );
  5893. }
  5894. }
  5895. return $return;
  5896. }
  5897. /**
  5898. * This function builds the action menu
  5899. * @param bool $returnContent Optional
  5900. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5901. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5902. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5903. * @return string
  5904. */
  5905. public function build_action_menu(
  5906. $returnContent = false,
  5907. $showRequirementButtons = true,
  5908. $isConfigPage = false,
  5909. $allowExpand = true
  5910. ) {
  5911. $actionsLeft = '';
  5912. $actionsRight = '';
  5913. $actionsLeft .= Display::url(
  5914. Display::return_icon(
  5915. 'preview_view.png',
  5916. get_lang('Preview'),
  5917. '',
  5918. ICON_SIZE_MEDIUM
  5919. ),
  5920. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5921. 'action' => 'view',
  5922. 'lp_id' => $this->lp_id,
  5923. 'isStudentView' => 'true'
  5924. ])
  5925. );
  5926. $actionsLeft .= Display::url(
  5927. Display::return_icon(
  5928. 'upload_audio.png',
  5929. get_lang('UpdateAllAudioFragments'),
  5930. '',
  5931. ICON_SIZE_MEDIUM
  5932. ),
  5933. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5934. 'action' => 'admin_view',
  5935. 'lp_id' => $this->lp_id,
  5936. 'updateaudio' => 'true'
  5937. ])
  5938. );
  5939. if (!$isConfigPage) {
  5940. $actionsLeft .= Display::url(
  5941. Display::return_icon(
  5942. 'settings.png',
  5943. get_lang('CourseSettings'),
  5944. '',
  5945. ICON_SIZE_MEDIUM
  5946. ),
  5947. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5948. 'action' => 'edit',
  5949. 'lp_id' => $this->lp_id
  5950. ])
  5951. );
  5952. } else {
  5953. $actionsLeft .= Display::url(
  5954. Display::return_icon(
  5955. 'edit.png',
  5956. get_lang('Edit'),
  5957. '',
  5958. ICON_SIZE_MEDIUM
  5959. ),
  5960. 'lp_controller.php?'.http_build_query([
  5961. 'action' => 'build',
  5962. 'lp_id' => $this->lp_id
  5963. ]).'&'.api_get_cidreq()
  5964. );
  5965. }
  5966. if ($allowExpand) {
  5967. $actionsLeft .= Display::url(
  5968. Display::return_icon(
  5969. 'expand.png',
  5970. get_lang('Expand'),
  5971. ['id' => 'expand'],
  5972. ICON_SIZE_MEDIUM
  5973. ).
  5974. Display::return_icon(
  5975. 'contract.png',
  5976. get_lang('Collapse'),
  5977. ['id' => 'contract', 'class' => 'hide'],
  5978. ICON_SIZE_MEDIUM
  5979. ),
  5980. '#',
  5981. ['role' => 'button', 'id' => 'hide_bar_template']
  5982. );
  5983. }
  5984. if ($showRequirementButtons) {
  5985. $buttons = [
  5986. [
  5987. 'title' => get_lang('SetPrerequisiteForEachItem'),
  5988. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5989. 'action' => 'set_previous_step_as_prerequisite',
  5990. 'lp_id' => $this->lp_id
  5991. ])
  5992. ],
  5993. [
  5994. 'title' => get_lang('ClearAllPrerequisites'),
  5995. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5996. 'action' => 'clear_prerequisites',
  5997. 'lp_id' => $this->lp_id
  5998. ])
  5999. ],
  6000. ];
  6001. $actionsRight = Display::groupButtonWithDropDown(
  6002. get_lang('PrerequisitesOptions'),
  6003. $buttons,
  6004. true
  6005. );
  6006. }
  6007. $toolbar = Display::toolbarAction(
  6008. 'actions-lp-controller',
  6009. [$actionsLeft, $actionsRight]
  6010. );
  6011. if ($returnContent) {
  6012. return $toolbar;
  6013. }
  6014. echo $toolbar;
  6015. }
  6016. /**
  6017. * Creates the default learning path folder
  6018. * @param array $course
  6019. * @param int $creatorId
  6020. *
  6021. * @return bool
  6022. */
  6023. public static function generate_learning_path_folder($course, $creatorId = 0)
  6024. {
  6025. // Creating learning_path folder
  6026. $dir = '/learning_path';
  6027. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6028. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6029. $folder = false;
  6030. if (!is_dir($filepath.'/'.$dir)) {
  6031. $folderData = create_unexisting_directory(
  6032. $course,
  6033. $creatorId,
  6034. 0,
  6035. 0,
  6036. 0,
  6037. $filepath,
  6038. $dir,
  6039. get_lang('LearningPaths'),
  6040. 0
  6041. );
  6042. if (!empty($folderData)) {
  6043. $folder = true;
  6044. }
  6045. } else {
  6046. $folder = true;
  6047. }
  6048. return $folder;
  6049. }
  6050. /**
  6051. * @param array $course
  6052. * @param string $lp_name
  6053. * @param int $creatorId
  6054. *
  6055. * @return array
  6056. */
  6057. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6058. {
  6059. $filepath = '';
  6060. $dir = '/learning_path/';
  6061. if (empty($lp_name)) {
  6062. $lp_name = $this->name;
  6063. }
  6064. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6065. $folder = self::generate_learning_path_folder($course, $creatorId);
  6066. // Limits title size
  6067. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6068. $dir = $dir.$title;
  6069. // Creating LP folder
  6070. $documentId = null;
  6071. if ($folder) {
  6072. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6073. if (!is_dir($filepath.'/'.$dir)) {
  6074. $folderData = create_unexisting_directory(
  6075. $course,
  6076. $creatorId,
  6077. 0,
  6078. 0,
  6079. 0,
  6080. $filepath,
  6081. $dir,
  6082. $lp_name
  6083. );
  6084. if (!empty($folderData)) {
  6085. $folder = true;
  6086. }
  6087. $documentId = $folderData['id'];
  6088. } else {
  6089. $folder = true;
  6090. }
  6091. $dir = $dir.'/';
  6092. if ($folder) {
  6093. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6094. }
  6095. }
  6096. if (empty($documentId)) {
  6097. $dir = api_remove_trailing_slash($dir);
  6098. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6099. }
  6100. $array = [
  6101. 'dir' => $dir,
  6102. 'filepath' => $filepath,
  6103. 'folder' => $folder,
  6104. 'id' => $documentId
  6105. ];
  6106. return $array;
  6107. }
  6108. /**
  6109. * Create a new document //still needs some finetuning
  6110. * @param array $courseInfo
  6111. * @param string $content
  6112. * @param string $title
  6113. * @param string $extension
  6114. * @param int $parentId
  6115. * @param int $creatorId creator id
  6116. *
  6117. * @return int
  6118. */
  6119. public function create_document(
  6120. $courseInfo,
  6121. $content = '',
  6122. $title = '',
  6123. $extension = 'html',
  6124. $parentId = 0,
  6125. $creatorId = 0
  6126. ) {
  6127. if (!empty($courseInfo)) {
  6128. $course_id = $courseInfo['real_id'];
  6129. } else {
  6130. $course_id = api_get_course_int_id();
  6131. }
  6132. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6133. $sessionId = api_get_session_id();
  6134. // Generates folder
  6135. $result = $this->generate_lp_folder($courseInfo);
  6136. $dir = $result['dir'];
  6137. if (empty($parentId) || $parentId == '/') {
  6138. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6139. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6140. if ($parentId === '/') {
  6141. $dir = '/';
  6142. }
  6143. // Please, do not modify this dirname formatting.
  6144. if (strstr($dir, '..')) {
  6145. $dir = '/';
  6146. }
  6147. if (!empty($dir[0]) && $dir[0] == '.') {
  6148. $dir = substr($dir, 1);
  6149. }
  6150. if (!empty($dir[0]) && $dir[0] != '/') {
  6151. $dir = '/'.$dir;
  6152. }
  6153. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6154. $dir .= '/';
  6155. }
  6156. } else {
  6157. $parentInfo = DocumentManager::get_document_data_by_id(
  6158. $parentId,
  6159. $courseInfo['code']
  6160. );
  6161. if (!empty($parentInfo)) {
  6162. $dir = $parentInfo['path'].'/';
  6163. }
  6164. }
  6165. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6166. if (!is_dir($filepath)) {
  6167. $dir = '/';
  6168. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6169. }
  6170. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6171. // is already escaped twice when it gets here.
  6172. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6173. if (!empty($title)) {
  6174. $title = api_replace_dangerous_char(stripslashes($title));
  6175. } else {
  6176. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6177. }
  6178. $title = disable_dangerous_file($title);
  6179. $filename = $title;
  6180. $content = !empty($content) ? $content : $_POST['content_lp'];
  6181. $tmp_filename = $filename;
  6182. $i = 0;
  6183. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6184. $tmp_filename = $filename.'_'.++ $i;
  6185. }
  6186. $filename = $tmp_filename.'.'.$extension;
  6187. if ($extension == 'html') {
  6188. $content = stripslashes($content);
  6189. $content = str_replace(
  6190. api_get_path(WEB_COURSE_PATH),
  6191. api_get_path(REL_PATH).'courses/',
  6192. $content
  6193. );
  6194. // Change the path of mp3 to absolute.
  6195. // The first regexp deals with :// urls.
  6196. $content = preg_replace(
  6197. "|(flashvars=\"file=)([^:/]+)/|",
  6198. "$1".api_get_path(
  6199. REL_COURSE_PATH
  6200. ).$courseInfo['path'].'/document/',
  6201. $content
  6202. );
  6203. // The second regexp deals with audio/ urls.
  6204. $content = preg_replace(
  6205. "|(flashvars=\"file=)([^/]+)/|",
  6206. "$1".api_get_path(
  6207. REL_COURSE_PATH
  6208. ).$courseInfo['path'].'/document/$2/',
  6209. $content
  6210. );
  6211. // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
  6212. $content = str_replace(
  6213. '</body>',
  6214. '<style type="text/css">body{}</style></body>',
  6215. $content
  6216. );
  6217. }
  6218. if (!file_exists($filepath.$filename)) {
  6219. if ($fp = @ fopen($filepath.$filename, 'w')) {
  6220. fputs($fp, $content);
  6221. fclose($fp);
  6222. $file_size = filesize($filepath.$filename);
  6223. $save_file_path = $dir.$filename;
  6224. $document_id = add_document(
  6225. $courseInfo,
  6226. $save_file_path,
  6227. 'file',
  6228. $file_size,
  6229. $tmp_filename,
  6230. '',
  6231. 0, //readonly
  6232. true,
  6233. null,
  6234. $sessionId,
  6235. $creatorId
  6236. );
  6237. if ($document_id) {
  6238. api_item_property_update(
  6239. $courseInfo,
  6240. TOOL_DOCUMENT,
  6241. $document_id,
  6242. 'DocumentAdded',
  6243. $creatorId,
  6244. null,
  6245. null,
  6246. null,
  6247. null,
  6248. $sessionId
  6249. );
  6250. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6251. $new_title = $originalTitle;
  6252. if ($new_comment || $new_title) {
  6253. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6254. $ct = '';
  6255. if ($new_comment) {
  6256. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6257. }
  6258. if ($new_title) {
  6259. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6260. }
  6261. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6262. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6263. Database::query($sql);
  6264. }
  6265. }
  6266. return $document_id;
  6267. }
  6268. }
  6269. }
  6270. /**
  6271. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'
  6272. * @param array $_course array
  6273. * @return void
  6274. */
  6275. public function edit_document($_course)
  6276. {
  6277. $course_id = api_get_course_int_id();
  6278. $urlAppend = api_get_configuration_value('url_append');
  6279. // Please, do not modify this dirname formatting.
  6280. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6281. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6282. if (strstr($dir, '..')) {
  6283. $dir = '/';
  6284. }
  6285. if (isset($dir[0]) && $dir[0] == '.') {
  6286. $dir = substr($dir, 1);
  6287. }
  6288. if (isset($dir[0]) && $dir[0] != '/') {
  6289. $dir = '/'.$dir;
  6290. }
  6291. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6292. $dir .= '/';
  6293. }
  6294. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6295. if (!is_dir($filepath)) {
  6296. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6297. }
  6298. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6299. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6300. $document_id = intval($_POST['path']);
  6301. $sql = "SELECT path FROM ".$table_doc."
  6302. WHERE c_id = $course_id AND id = ".$document_id;
  6303. $res = Database::query($sql);
  6304. $row = Database::fetch_array($res);
  6305. $content = stripslashes($_POST['content_lp']);
  6306. $file = $filepath.$row['path'];
  6307. if ($fp = @fopen($file, 'w')) {
  6308. $content = str_replace(
  6309. api_get_path(WEB_COURSE_PATH),
  6310. $urlAppend.api_get_path(REL_COURSE_PATH),
  6311. $content
  6312. );
  6313. // Change the path of mp3 to absolute.
  6314. // The first regexp deals with :// urls.
  6315. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/', $content);
  6316. // The second regexp deals with audio/ urls.
  6317. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|", "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/', $content);
  6318. fputs($fp, $content);
  6319. fclose($fp);
  6320. $sql = "UPDATE ".$table_doc." SET
  6321. title='".Database::escape_string($_POST['title'])."'
  6322. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6323. Database::query($sql);
  6324. }
  6325. }
  6326. }
  6327. /**
  6328. * Displays the selected item, with a panel for manipulating the item
  6329. * @param int $item_id
  6330. * @param string $msg
  6331. * @param bool $show_actions
  6332. * @return string
  6333. */
  6334. public function display_item($item_id, $msg = null, $show_actions = true)
  6335. {
  6336. $course_id = api_get_course_int_id();
  6337. $return = '';
  6338. if (is_numeric($item_id)) {
  6339. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6340. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6341. WHERE lp.iid = ".intval($item_id);
  6342. $result = Database::query($sql);
  6343. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6344. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6345. // Prevents wrong parent selection for document, see Bug#1251.
  6346. if ($row['item_type'] != 'dir') {
  6347. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6348. }
  6349. if ($show_actions) {
  6350. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6351. }
  6352. $return .= '<div style="padding:10px;">';
  6353. if ($msg != '') {
  6354. $return .= $msg;
  6355. }
  6356. $return .= '<h3>'.$row['title'].'</h3>';
  6357. switch ($row['item_type']) {
  6358. case TOOL_THREAD:
  6359. $link = $this->rl_get_resource_link_for_learnpath(
  6360. $course_id,
  6361. $row['lp_id'],
  6362. $item_id,
  6363. 0
  6364. );
  6365. $return .= Display::url(
  6366. get_lang('GoToThread'),
  6367. $link,
  6368. ['class' => 'btn btn-primary']
  6369. );
  6370. break;
  6371. case TOOL_FORUM:
  6372. $return .= Display::url(
  6373. get_lang('GoToForum'),
  6374. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6375. ['class' => 'btn btn-primary']
  6376. );
  6377. break;
  6378. case TOOL_QUIZ:
  6379. if (!empty($row['path'])) {
  6380. $exercise = new Exercise();
  6381. $exercise->read($row['path']);
  6382. $return .= $exercise->description.'<br />';
  6383. $return .= Display::url(
  6384. get_lang('GoToExercise'),
  6385. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6386. ['class' => 'btn btn-primary']
  6387. );
  6388. }
  6389. break;
  6390. case TOOL_LP_FINAL_ITEM:
  6391. $return .= $this->getSavedFinalItem();
  6392. break;
  6393. case TOOL_DOCUMENT:
  6394. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6395. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6396. WHERE c_id = ".$course_id." AND iid = ".intval($row['path']);
  6397. $result = Database::query($sql_doc);
  6398. $path_file = Database::result($result, 0, 0);
  6399. $path_parts = pathinfo($path_file);
  6400. // TODO: Correct the following naive comparisons.
  6401. if (in_array($path_parts['extension'], [
  6402. 'html',
  6403. 'txt',
  6404. 'png',
  6405. 'jpg',
  6406. 'JPG',
  6407. 'jpeg',
  6408. 'JPEG',
  6409. 'gif',
  6410. 'swf',
  6411. 'pdf',
  6412. 'htm'
  6413. ])) {
  6414. $return .= $this->display_document($row['path'], true, true);
  6415. }
  6416. break;
  6417. case TOOL_HOTPOTATOES:
  6418. $return .= $this->display_document($row['path'], false, true);
  6419. break;
  6420. }
  6421. $return .= '</div>';
  6422. }
  6423. }
  6424. return $return;
  6425. }
  6426. /**
  6427. * Shows the needed forms for editing a specific item
  6428. * @param int $item_id
  6429. * @return string
  6430. */
  6431. public function display_edit_item($item_id)
  6432. {
  6433. $course_id = api_get_course_int_id();
  6434. $return = '';
  6435. if (is_numeric($item_id)) {
  6436. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6437. $sql = "SELECT * FROM $tbl_lp_item
  6438. WHERE iid = ".intval($item_id);
  6439. $res = Database::query($sql);
  6440. $row = Database::fetch_array($res);
  6441. switch ($row['item_type']) {
  6442. case 'dir':
  6443. case 'asset':
  6444. case 'sco':
  6445. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6446. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6447. $return .= $this->display_item_form(
  6448. $row['item_type'],
  6449. get_lang('EditCurrentChapter').' :',
  6450. 'edit',
  6451. $item_id,
  6452. $row
  6453. );
  6454. } else {
  6455. $return .= $this->display_item_small_form(
  6456. $row['item_type'],
  6457. get_lang('EditCurrentChapter').' :',
  6458. $row
  6459. );
  6460. }
  6461. break;
  6462. case TOOL_DOCUMENT:
  6463. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6464. $sql = "SELECT lp.*, doc.path as dir
  6465. FROM $tbl_lp_item as lp
  6466. LEFT JOIN $tbl_doc as doc
  6467. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6468. WHERE
  6469. doc.c_id = $course_id AND
  6470. lp.iid = ".intval($item_id);
  6471. $res_step = Database::query($sql);
  6472. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6473. $return .= $this->display_manipulate(
  6474. $item_id,
  6475. $row['item_type']
  6476. );
  6477. $return .= $this->display_document_form(
  6478. 'edit',
  6479. $item_id,
  6480. $row_step
  6481. );
  6482. break;
  6483. case TOOL_LINK:
  6484. $link_id = (string) $row['path'];
  6485. if (ctype_digit($link_id)) {
  6486. $tbl_link = Database::get_course_table(TABLE_LINK);
  6487. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6488. WHERE c_id = '.$course_id.' AND iid = '.intval($link_id);
  6489. $res_link = Database::query($sql_select);
  6490. $row_link = Database::fetch_array($res_link);
  6491. if (is_array($row_link)) {
  6492. $row['url'] = $row_link['url'];
  6493. }
  6494. }
  6495. $return .= $this->display_manipulate(
  6496. $item_id,
  6497. $row['item_type']
  6498. );
  6499. $return .= $this->display_link_form('edit', $item_id, $row);
  6500. break;
  6501. case TOOL_LP_FINAL_ITEM:
  6502. Session::write('finalItem', true);
  6503. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6504. $sql = "SELECT lp.*, doc.path as dir
  6505. FROM $tbl_lp_item as lp
  6506. LEFT JOIN $tbl_doc as doc
  6507. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6508. WHERE
  6509. doc.c_id = $course_id AND
  6510. lp.iid = ".intval($item_id);
  6511. $res_step = Database::query($sql);
  6512. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6513. $return .= $this->display_manipulate(
  6514. $item_id,
  6515. $row['item_type']
  6516. );
  6517. $return .= $this->display_document_form(
  6518. 'edit',
  6519. $item_id,
  6520. $row_step
  6521. );
  6522. break;
  6523. case TOOL_QUIZ:
  6524. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6525. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6526. break;
  6527. case TOOL_HOTPOTATOES:
  6528. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6529. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6530. break;
  6531. case TOOL_STUDENTPUBLICATION:
  6532. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6533. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6534. break;
  6535. case TOOL_FORUM:
  6536. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6537. $return .= $this->display_forum_form('edit', $item_id, $row);
  6538. break;
  6539. case TOOL_THREAD:
  6540. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6541. $return .= $this->display_thread_form('edit', $item_id, $row);
  6542. break;
  6543. }
  6544. }
  6545. return $return;
  6546. }
  6547. /**
  6548. * Function that displays a list with al the resources that
  6549. * could be added to the learning path
  6550. * @return bool
  6551. */
  6552. public function display_resources()
  6553. {
  6554. $course_code = api_get_course_id();
  6555. // Get all the docs.
  6556. $documents = $this->get_documents(true);
  6557. // Get all the exercises.
  6558. $exercises = $this->get_exercises();
  6559. // Get all the links.
  6560. $links = $this->get_links();
  6561. // Get all the student publications.
  6562. $works = $this->get_student_publications();
  6563. // Get all the forums.
  6564. $forums = $this->get_forums(null, $course_code);
  6565. // Get the final item form (see BT#11048) .
  6566. $finish = $this->getFinalItemForm();
  6567. $headers = [
  6568. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6569. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6570. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6571. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6572. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6573. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6574. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6575. ];
  6576. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6577. $dir = $_SESSION['oLP']->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6578. echo Display::tabs(
  6579. $headers,
  6580. [
  6581. $documents,
  6582. $exercises,
  6583. $links,
  6584. $works,
  6585. $forums,
  6586. $dir,
  6587. $finish,
  6588. ],
  6589. 'resource_tab'
  6590. );
  6591. return true;
  6592. }
  6593. /**
  6594. * Returns the extension of a document
  6595. * @param string $filename
  6596. * @return string Extension (part after the last dot)
  6597. */
  6598. public function get_extension($filename)
  6599. {
  6600. $explode = explode('.', $filename);
  6601. return $explode[count($explode) - 1];
  6602. }
  6603. /**
  6604. * Displays a document by id
  6605. *
  6606. * @param int $id
  6607. * @return string
  6608. */
  6609. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6610. {
  6611. $_course = api_get_course_info();
  6612. $course_id = api_get_course_int_id();
  6613. $return = '';
  6614. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6615. $sql_doc = "SELECT * FROM ".$tbl_doc."
  6616. WHERE c_id = $course_id AND iid = $id";
  6617. $res_doc = Database::query($sql_doc);
  6618. $row_doc = Database::fetch_array($res_doc);
  6619. // TODO: Add a path filter.
  6620. if ($iframe) {
  6621. $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>';
  6622. } else {
  6623. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6624. }
  6625. return $return;
  6626. }
  6627. /**
  6628. * Return HTML form to add/edit a quiz
  6629. * @param string $action Action (add/edit)
  6630. * @param integer $id Item ID if already exists
  6631. * @param mixed $extra_info Extra information (quiz ID if integer)
  6632. * @return string HTML form
  6633. */
  6634. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6635. {
  6636. $course_id = api_get_course_int_id();
  6637. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6638. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6639. if ($id != 0 && is_array($extra_info)) {
  6640. $item_title = $extra_info['title'];
  6641. $item_description = $extra_info['description'];
  6642. } elseif (is_numeric($extra_info)) {
  6643. $sql = "SELECT title, description
  6644. FROM $tbl_quiz
  6645. WHERE c_id = $course_id AND iid = ".$extra_info;
  6646. $result = Database::query($sql);
  6647. $row = Database::fetch_array($result);
  6648. $item_title = $row['title'];
  6649. $item_description = $row['description'];
  6650. } else {
  6651. $item_title = '';
  6652. $item_description = '';
  6653. }
  6654. $item_title = Security::remove_XSS($item_title);
  6655. $item_description = Security::remove_XSS($item_description);
  6656. if ($id != 0 && is_array($extra_info)) {
  6657. $parent = $extra_info['parent_item_id'];
  6658. } else {
  6659. $parent = 0;
  6660. }
  6661. $sql = "SELECT * FROM $tbl_lp_item
  6662. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6663. $result = Database::query($sql);
  6664. $arrLP = [];
  6665. while ($row = Database::fetch_array($result)) {
  6666. $arrLP[] = [
  6667. 'id' => $row['id'],
  6668. 'item_type' => $row['item_type'],
  6669. 'title' => $row['title'],
  6670. 'path' => $row['path'],
  6671. 'description' => $row['description'],
  6672. 'parent_item_id' => $row['parent_item_id'],
  6673. 'previous_item_id' => $row['previous_item_id'],
  6674. 'next_item_id' => $row['next_item_id'],
  6675. 'display_order' => $row['display_order'],
  6676. 'max_score' => $row['max_score'],
  6677. 'min_score' => $row['min_score'],
  6678. 'mastery_score' => $row['mastery_score'],
  6679. 'prerequisite' => $row['prerequisite'],
  6680. 'max_time_allowed' => $row['max_time_allowed']
  6681. ];
  6682. }
  6683. $this->tree_array($arrLP);
  6684. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  6685. unset($this->arrMenu);
  6686. $form = new FormValidator(
  6687. 'quiz_form',
  6688. 'POST',
  6689. $this->getCurrentBuildingModeURL()
  6690. );
  6691. $defaults = [];
  6692. if ($action == 'add') {
  6693. $legend = get_lang('CreateTheExercise');
  6694. } elseif ($action == 'move') {
  6695. $legend = get_lang('MoveTheCurrentExercise');
  6696. } else {
  6697. $legend = get_lang('EditCurrentExecice');
  6698. }
  6699. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6700. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6701. }
  6702. $form->addHeader($legend);
  6703. if ($action != 'move') {
  6704. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  6705. $defaults['title'] = $item_title;
  6706. }
  6707. // Select for Parent item, root or chapter
  6708. $selectParent = $form->addSelect(
  6709. 'parent',
  6710. get_lang('Parent'),
  6711. [],
  6712. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6713. );
  6714. $selectParent->addOption($this->name, 0);
  6715. $arrHide = [
  6716. $id
  6717. ];
  6718. for ($i = 0; $i < count($arrLP); $i++) {
  6719. if ($action != 'add') {
  6720. if (
  6721. ($arrLP[$i]['item_type'] == 'dir') &&
  6722. !in_array($arrLP[$i]['id'], $arrHide) &&
  6723. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6724. ) {
  6725. $selectParent->addOption(
  6726. $arrLP[$i]['title'],
  6727. $arrLP[$i]['id'],
  6728. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6729. );
  6730. if ($parent == $arrLP[$i]['id']) {
  6731. $selectParent->setSelected($arrLP[$i]['id']);
  6732. }
  6733. } else {
  6734. $arrHide[] = $arrLP[$i]['id'];
  6735. }
  6736. } else {
  6737. if ($arrLP[$i]['item_type'] == 'dir') {
  6738. $selectParent->addOption(
  6739. $arrLP[$i]['title'],
  6740. $arrLP[$i]['id'],
  6741. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6742. );
  6743. if ($parent == $arrLP[$i]['id']) {
  6744. $selectParent->setSelected($arrLP[$i]['id']);
  6745. }
  6746. }
  6747. }
  6748. }
  6749. if (is_array($arrLP)) {
  6750. reset($arrLP);
  6751. }
  6752. $selectPrevious = $form->addSelect(
  6753. 'previous',
  6754. get_lang('Position'),
  6755. [],
  6756. ['id' => 'previous']
  6757. );
  6758. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6759. for ($i = 0; $i < count($arrLP); $i++) {
  6760. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6761. $arrLP[$i]['id'] != $id
  6762. ) {
  6763. $selectPrevious->addOption(
  6764. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6765. $arrLP[$i]['id']
  6766. );
  6767. if (is_array($extra_info)) {
  6768. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6769. $selectPrevious->setSelected($arrLP[$i]['id']);
  6770. }
  6771. } elseif ($action == 'add') {
  6772. $selectPrevious->setSelected($arrLP[$i]['id']);
  6773. }
  6774. }
  6775. }
  6776. if ($action != 'move') {
  6777. $id_prerequisite = 0;
  6778. if (is_array($arrLP)) {
  6779. foreach ($arrLP as $key => $value) {
  6780. if ($value['id'] == $id) {
  6781. $id_prerequisite = $value['prerequisite'];
  6782. break;
  6783. }
  6784. }
  6785. }
  6786. $arrHide = [];
  6787. for ($i = 0; $i < count($arrLP); $i++) {
  6788. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6789. if (is_array($extra_info)) {
  6790. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6791. $s_selected_position = $arrLP[$i]['id'];
  6792. }
  6793. } elseif ($action == 'add') {
  6794. $s_selected_position = 0;
  6795. }
  6796. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6797. }
  6798. }
  6799. }
  6800. if ($action == 'add') {
  6801. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6802. } else {
  6803. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6804. }
  6805. if ($action == 'move') {
  6806. $form->addHidden('title', $item_title);
  6807. $form->addHidden('description', $item_description);
  6808. }
  6809. if (is_numeric($extra_info)) {
  6810. $form->addHidden('path', $extra_info);
  6811. } elseif (is_array($extra_info)) {
  6812. $form->addHidden('path', $extra_info['path']);
  6813. }
  6814. $form->addHidden('type', TOOL_QUIZ);
  6815. $form->addHidden('post_time', time());
  6816. $form->setDefaults($defaults);
  6817. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6818. }
  6819. /**
  6820. * Addition of Hotpotatoes tests
  6821. * @param string Action
  6822. * @param integer Internal ID of the item
  6823. * @param mixed Extra information - can be an array with title and description indexes
  6824. * @return string HTML structure to display the hotpotatoes addition formular
  6825. */
  6826. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6827. {
  6828. $course_id = api_get_course_int_id();
  6829. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  6830. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6831. if ($id != 0 && is_array($extra_info)) {
  6832. $item_title = stripslashes($extra_info['title']);
  6833. $item_description = stripslashes($extra_info['description']);
  6834. } elseif (is_numeric($extra_info)) {
  6835. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6836. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  6837. WHERE
  6838. c_id = ".$course_id." AND
  6839. path LIKE '" . $uploadPath."/%/%htm%' AND
  6840. iid = " . (int) $extra_info."
  6841. ORDER BY iid ASC";
  6842. $res_hot = Database::query($sql);
  6843. $row = Database::fetch_array($res_hot);
  6844. $item_title = $row['title'];
  6845. $item_description = $row['description'];
  6846. if (!empty($row['comment'])) {
  6847. $item_title = $row['comment'];
  6848. }
  6849. } else {
  6850. $item_title = '';
  6851. $item_description = '';
  6852. }
  6853. if ($id != 0 && is_array($extra_info)) {
  6854. $parent = $extra_info['parent_item_id'];
  6855. } else {
  6856. $parent = 0;
  6857. }
  6858. $sql = "SELECT * FROM $tbl_lp_item
  6859. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6860. $result = Database::query($sql);
  6861. $arrLP = [];
  6862. while ($row = Database::fetch_array($result)) {
  6863. $arrLP[] = [
  6864. 'id' => $row['id'],
  6865. 'item_type' => $row['item_type'],
  6866. 'title' => $row['title'],
  6867. 'path' => $row['path'],
  6868. 'description' => $row['description'],
  6869. 'parent_item_id' => $row['parent_item_id'],
  6870. 'previous_item_id' => $row['previous_item_id'],
  6871. 'next_item_id' => $row['next_item_id'],
  6872. 'display_order' => $row['display_order'],
  6873. 'max_score' => $row['max_score'],
  6874. 'min_score' => $row['min_score'],
  6875. 'mastery_score' => $row['mastery_score'],
  6876. 'prerequisite' => $row['prerequisite'],
  6877. 'max_time_allowed' => $row['max_time_allowed']
  6878. ];
  6879. }
  6880. $legend = '<legend>';
  6881. if ($action == 'add') {
  6882. $legend .= get_lang('CreateTheExercise');
  6883. } elseif ($action == 'move') {
  6884. $legend .= get_lang('MoveTheCurrentExercise');
  6885. } else {
  6886. $legend .= get_lang('EditCurrentExecice');
  6887. }
  6888. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6889. $legend .= Display:: return_message(
  6890. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6891. );
  6892. }
  6893. $legend .= '</legend>';
  6894. $return = '<form method="POST">';
  6895. $return .= $legend;
  6896. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6897. $return .= '<tr>';
  6898. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6899. $return .= '<td class="input">';
  6900. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6901. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6902. $arrHide = [
  6903. $id
  6904. ];
  6905. if (count($arrLP) > 0) {
  6906. for ($i = 0; $i < count($arrLP); $i++) {
  6907. if ($action != 'add') {
  6908. if ($arrLP[$i]['item_type'] == 'dir' &&
  6909. !in_array($arrLP[$i]['id'], $arrHide) &&
  6910. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6911. ) {
  6912. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6913. } else {
  6914. $arrHide[] = $arrLP[$i]['id'];
  6915. }
  6916. } else {
  6917. if ($arrLP[$i]['item_type'] == 'dir') {
  6918. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6919. }
  6920. }
  6921. }
  6922. reset($arrLP);
  6923. }
  6924. $return .= '</select>';
  6925. $return .= '</td>';
  6926. $return .= '</tr>';
  6927. $return .= '<tr>';
  6928. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6929. $return .= '<td class="input">';
  6930. $return .= '<select id="previous" name="previous" size="1">';
  6931. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6932. for ($i = 0; $i < count($arrLP); $i++) {
  6933. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6934. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6935. $selected = 'selected="selected" ';
  6936. } elseif ($action == 'add') {
  6937. $selected = 'selected="selected" ';
  6938. } else {
  6939. $selected = '';
  6940. }
  6941. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  6942. }
  6943. }
  6944. $return .= '</select>';
  6945. $return .= '</td>';
  6946. $return .= '</tr>';
  6947. if ($action != 'move') {
  6948. $return .= '<tr>';
  6949. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  6950. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  6951. $return .= '</tr>';
  6952. $id_prerequisite = 0;
  6953. if (is_array($arrLP) && count($arrLP) > 0) {
  6954. foreach ($arrLP as $key => $value) {
  6955. if ($value['id'] == $id) {
  6956. $id_prerequisite = $value['prerequisite'];
  6957. break;
  6958. }
  6959. }
  6960. $arrHide = [];
  6961. for ($i = 0; $i < count($arrLP); $i++) {
  6962. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6963. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6964. $s_selected_position = $arrLP[$i]['id'];
  6965. } elseif ($action == 'add') {
  6966. $s_selected_position = 0;
  6967. }
  6968. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6969. }
  6970. }
  6971. }
  6972. }
  6973. $return .= '<tr>';
  6974. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.get_lang('SaveHotpotatoes').'</button></td>';
  6975. $return .= '</tr>';
  6976. $return .= '</table>';
  6977. if ($action == 'move') {
  6978. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  6979. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  6980. }
  6981. if (is_numeric($extra_info)) {
  6982. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  6983. } elseif (is_array($extra_info)) {
  6984. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  6985. }
  6986. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  6987. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  6988. $return .= '</form>';
  6989. return $return;
  6990. }
  6991. /**
  6992. * Return the form to display the forum edit/add option
  6993. * @param string Action (add/edit)
  6994. * @param integer ID of the lp_item if already exists
  6995. * @param mixed Forum ID or title
  6996. * @return string HTML form
  6997. */
  6998. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  6999. {
  7000. $course_id = api_get_course_int_id();
  7001. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7002. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7003. if ($id != 0 && is_array($extra_info)) {
  7004. $item_title = stripslashes($extra_info['title']);
  7005. } elseif (is_numeric($extra_info)) {
  7006. $sql = "SELECT forum_title as title, forum_comment as comment
  7007. FROM " . $tbl_forum."
  7008. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7009. $result = Database::query($sql);
  7010. $row = Database::fetch_array($result);
  7011. $item_title = $row['title'];
  7012. $item_description = $row['comment'];
  7013. } else {
  7014. $item_title = '';
  7015. $item_description = '';
  7016. }
  7017. if ($id != 0 && is_array($extra_info)) {
  7018. $parent = $extra_info['parent_item_id'];
  7019. } else {
  7020. $parent = 0;
  7021. }
  7022. $sql = "SELECT * FROM $tbl_lp_item
  7023. WHERE
  7024. c_id = $course_id AND
  7025. lp_id = " . $this->lp_id;
  7026. $result = Database::query($sql);
  7027. $arrLP = [];
  7028. while ($row = Database::fetch_array($result)) {
  7029. $arrLP[] = [
  7030. 'id' => $row['iid'],
  7031. 'item_type' => $row['item_type'],
  7032. 'title' => $row['title'],
  7033. 'path' => $row['path'],
  7034. 'description' => $row['description'],
  7035. 'parent_item_id' => $row['parent_item_id'],
  7036. 'previous_item_id' => $row['previous_item_id'],
  7037. 'next_item_id' => $row['next_item_id'],
  7038. 'display_order' => $row['display_order'],
  7039. 'max_score' => $row['max_score'],
  7040. 'min_score' => $row['min_score'],
  7041. 'mastery_score' => $row['mastery_score'],
  7042. 'prerequisite' => $row['prerequisite']
  7043. ];
  7044. }
  7045. $this->tree_array($arrLP);
  7046. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7047. unset($this->arrMenu);
  7048. if ($action == 'add') {
  7049. $legend = get_lang('CreateTheForum');
  7050. } elseif ($action == 'move') {
  7051. $legend = get_lang('MoveTheCurrentForum');
  7052. } else {
  7053. $legend = get_lang('EditCurrentForum');
  7054. }
  7055. $form = new FormValidator(
  7056. 'forum_form',
  7057. 'POST',
  7058. $this->getCurrentBuildingModeURL()
  7059. );
  7060. $defaults = [];
  7061. $form->addHeader($legend);
  7062. if ($action != 'move') {
  7063. $form->addText(
  7064. 'title',
  7065. get_lang('Title'),
  7066. true,
  7067. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7068. );
  7069. $defaults['title'] = $item_title;
  7070. }
  7071. $selectParent = $form->addSelect(
  7072. 'parent',
  7073. get_lang('Parent'),
  7074. [],
  7075. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7076. );
  7077. $selectParent->addOption($this->name, 0);
  7078. $arrHide = [
  7079. $id
  7080. ];
  7081. //$parent_item_id = $_SESSION['parent_item_id'];
  7082. for ($i = 0; $i < count($arrLP); $i++) {
  7083. if ($action != 'add') {
  7084. if ($arrLP[$i]['item_type'] == 'dir' &&
  7085. !in_array($arrLP[$i]['id'], $arrHide) &&
  7086. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7087. ) {
  7088. $selectParent->addOption(
  7089. $arrLP[$i]['title'],
  7090. $arrLP[$i]['id'],
  7091. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7092. );
  7093. if ($parent == $arrLP[$i]['id']) {
  7094. $selectParent->setSelected($arrLP[$i]['id']);
  7095. }
  7096. } else {
  7097. $arrHide[] = $arrLP[$i]['id'];
  7098. }
  7099. } else {
  7100. if ($arrLP[$i]['item_type'] == 'dir') {
  7101. $selectParent->addOption(
  7102. $arrLP[$i]['title'],
  7103. $arrLP[$i]['id'],
  7104. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7105. );
  7106. if ($parent == $arrLP[$i]['id']) {
  7107. $selectParent->setSelected($arrLP[$i]['id']);
  7108. }
  7109. }
  7110. }
  7111. }
  7112. if (is_array($arrLP)) {
  7113. reset($arrLP);
  7114. }
  7115. $selectPrevious = $form->addSelect(
  7116. 'previous',
  7117. get_lang('Position'),
  7118. [],
  7119. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7120. );
  7121. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7122. for ($i = 0; $i < count($arrLP); $i++) {
  7123. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7124. $arrLP[$i]['id'] != $id
  7125. ) {
  7126. $selectPrevious->addOption(
  7127. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7128. $arrLP[$i]['id']
  7129. );
  7130. if (isset($extra_info['previous_item_id']) &&
  7131. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7132. ) {
  7133. $selectPrevious->setSelected($arrLP[$i]['id']);
  7134. } elseif ($action == 'add') {
  7135. $selectPrevious->setSelected($arrLP[$i]['id']);
  7136. }
  7137. }
  7138. }
  7139. if ($action != 'move') {
  7140. $id_prerequisite = 0;
  7141. if (is_array($arrLP)) {
  7142. foreach ($arrLP as $key => $value) {
  7143. if ($value['id'] == $id) {
  7144. $id_prerequisite = $value['prerequisite'];
  7145. break;
  7146. }
  7147. }
  7148. }
  7149. $arrHide = [];
  7150. for ($i = 0; $i < count($arrLP); $i++) {
  7151. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7152. if (isset($extra_info['previous_item_id']) &&
  7153. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7154. ) {
  7155. $s_selected_position = $arrLP[$i]['id'];
  7156. } elseif ($action == 'add') {
  7157. $s_selected_position = 0;
  7158. }
  7159. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7160. }
  7161. }
  7162. }
  7163. if ($action == 'add') {
  7164. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7165. } else {
  7166. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7167. }
  7168. if ($action == 'move') {
  7169. $form->addHidden('title', $item_title);
  7170. $form->addHidden('description', $item_description);
  7171. }
  7172. if (is_numeric($extra_info)) {
  7173. $form->addHidden('path', $extra_info);
  7174. } elseif (is_array($extra_info)) {
  7175. $form->addHidden('path', $extra_info['path']);
  7176. }
  7177. $form->addHidden('type', TOOL_FORUM);
  7178. $form->addHidden('post_time', time());
  7179. $form->setDefaults($defaults);
  7180. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7181. }
  7182. /**
  7183. * Return HTML form to add/edit forum threads
  7184. * @param string Action (add/edit)
  7185. * @param integer Item ID if already exists in learning path
  7186. * @param mixed Extra information (thread ID if integer)
  7187. * @return string HTML form
  7188. */
  7189. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7190. {
  7191. $course_id = api_get_course_int_id();
  7192. if (empty($course_id)) {
  7193. return null;
  7194. }
  7195. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7196. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7197. if ($id != 0 && is_array($extra_info)) {
  7198. $item_title = stripslashes($extra_info['title']);
  7199. } elseif (is_numeric($extra_info)) {
  7200. $sql = "SELECT thread_title as title FROM $tbl_forum
  7201. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7202. $result = Database::query($sql);
  7203. $row = Database::fetch_array($result);
  7204. $item_title = $row['title'];
  7205. $item_description = '';
  7206. } else {
  7207. $item_title = '';
  7208. $item_description = '';
  7209. }
  7210. if ($id != 0 && is_array($extra_info)) {
  7211. $parent = $extra_info['parent_item_id'];
  7212. } else {
  7213. $parent = 0;
  7214. }
  7215. $sql = "SELECT * FROM $tbl_lp_item
  7216. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7217. $result = Database::query($sql);
  7218. $arrLP = [];
  7219. while ($row = Database::fetch_array($result)) {
  7220. $arrLP[] = [
  7221. 'id' => $row['iid'],
  7222. 'item_type' => $row['item_type'],
  7223. 'title' => $row['title'],
  7224. 'path' => $row['path'],
  7225. 'description' => $row['description'],
  7226. 'parent_item_id' => $row['parent_item_id'],
  7227. 'previous_item_id' => $row['previous_item_id'],
  7228. 'next_item_id' => $row['next_item_id'],
  7229. 'display_order' => $row['display_order'],
  7230. 'max_score' => $row['max_score'],
  7231. 'min_score' => $row['min_score'],
  7232. 'mastery_score' => $row['mastery_score'],
  7233. 'prerequisite' => $row['prerequisite']
  7234. ];
  7235. }
  7236. $this->tree_array($arrLP);
  7237. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7238. unset($this->arrMenu);
  7239. $form = new FormValidator(
  7240. 'thread_form',
  7241. 'POST',
  7242. $this->getCurrentBuildingModeURL()
  7243. );
  7244. $defaults = [];
  7245. if ($action == 'add') {
  7246. $legend = get_lang('CreateTheForum');
  7247. } elseif ($action == 'move') {
  7248. $legend = get_lang('MoveTheCurrentForum');
  7249. } else {
  7250. $legend = get_lang('EditCurrentForum');
  7251. }
  7252. $form->addHeader($legend);
  7253. $selectParent = $form->addSelect(
  7254. 'parent',
  7255. get_lang('Parent'),
  7256. [],
  7257. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7258. );
  7259. $selectParent->addOption($this->name, 0);
  7260. $arrHide = [
  7261. $id
  7262. ];
  7263. for ($i = 0; $i < count($arrLP); $i++) {
  7264. if ($action != 'add') {
  7265. if (
  7266. ($arrLP[$i]['item_type'] == 'dir') &&
  7267. !in_array($arrLP[$i]['id'], $arrHide) &&
  7268. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7269. ) {
  7270. $selectParent->addOption(
  7271. $arrLP[$i]['title'],
  7272. $arrLP[$i]['id'],
  7273. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7274. );
  7275. if ($parent == $arrLP[$i]['id']) {
  7276. $selectParent->setSelected($arrLP[$i]['id']);
  7277. }
  7278. } else {
  7279. $arrHide[] = $arrLP[$i]['id'];
  7280. }
  7281. } else {
  7282. if ($arrLP[$i]['item_type'] == 'dir') {
  7283. $selectParent->addOption(
  7284. $arrLP[$i]['title'],
  7285. $arrLP[$i]['id'],
  7286. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7287. );
  7288. if ($parent == $arrLP[$i]['id']) {
  7289. $selectParent->setSelected($arrLP[$i]['id']);
  7290. }
  7291. }
  7292. }
  7293. }
  7294. if ($arrLP != null) {
  7295. reset($arrLP);
  7296. }
  7297. $selectPrevious = $form->addSelect(
  7298. 'previous',
  7299. get_lang('Position'),
  7300. [],
  7301. ['id' => 'previous']
  7302. );
  7303. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7304. for ($i = 0; $i < count($arrLP); $i++) {
  7305. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7306. $selectPrevious->addOption(
  7307. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7308. $arrLP[$i]['id']
  7309. );
  7310. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7311. $selectPrevious->setSelected($arrLP[$i]['id']);
  7312. } elseif ($action == 'add') {
  7313. $selectPrevious->setSelected($arrLP[$i]['id']);
  7314. }
  7315. }
  7316. }
  7317. if ($action != 'move') {
  7318. $form->addText(
  7319. 'title',
  7320. get_lang('Title'),
  7321. true,
  7322. ['id' => 'idTitle']
  7323. );
  7324. $defaults['title'] = $item_title;
  7325. $id_prerequisite = 0;
  7326. if ($arrLP != null) {
  7327. foreach ($arrLP as $key => $value) {
  7328. if ($value['id'] == $id) {
  7329. $id_prerequisite = $value['prerequisite'];
  7330. break;
  7331. }
  7332. }
  7333. }
  7334. $arrHide = [];
  7335. $s_selected_position = 0;
  7336. for ($i = 0; $i < count($arrLP); $i++) {
  7337. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7338. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7339. $s_selected_position = $arrLP[$i]['id'];
  7340. } elseif ($action == 'add') {
  7341. $s_selected_position = 0;
  7342. }
  7343. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7344. }
  7345. }
  7346. $selectPrerequisites = $form->addSelect(
  7347. 'prerequisites',
  7348. get_lang('LearnpathPrerequisites'),
  7349. [],
  7350. ['id' => 'prerequisites']
  7351. );
  7352. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7353. foreach ($arrHide as $key => $value) {
  7354. $selectPrerequisites->addOption($value['value'], $key);
  7355. if ($key == $s_selected_position && $action == 'add') {
  7356. $selectPrerequisites->setSelected($key);
  7357. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7358. $selectPrerequisites->setSelected($key);
  7359. }
  7360. }
  7361. }
  7362. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7363. if ($action == 'move') {
  7364. $form->addHidden('title', $item_title);
  7365. $form->addHidden('description', $item_description);
  7366. }
  7367. if (is_numeric($extra_info)) {
  7368. $form->addHidden('path', $extra_info);
  7369. } elseif (is_array($extra_info)) {
  7370. $form->addHidden('path', $extra_info['path']);
  7371. }
  7372. $form->addHidden('type', TOOL_THREAD);
  7373. $form->addHidden('post_time', time());
  7374. $form->setDefaults($defaults);
  7375. return $form->returnForm();
  7376. }
  7377. /**
  7378. * Return the HTML form to display an item (generally a dir item)
  7379. * @param string Item type (dir)
  7380. * @param string Title (optional, only when creating)
  7381. * @param string Action ('add'/'edit')
  7382. * @param integer lp_item ID
  7383. * @param mixed Extra info
  7384. * @return string HTML form
  7385. */
  7386. public function display_item_form(
  7387. $item_type,
  7388. $title = '',
  7389. $action = 'add_item',
  7390. $id = 0,
  7391. $extra_info = 'new'
  7392. ) {
  7393. $course_id = api_get_course_int_id();
  7394. $_course = api_get_course_info();
  7395. global $charset;
  7396. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7397. if ($id != 0 && is_array($extra_info)) {
  7398. $item_title = $extra_info['title'];
  7399. $item_description = $extra_info['description'];
  7400. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7401. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7402. } else {
  7403. $item_title = '';
  7404. $item_description = '';
  7405. $item_path_fck = '';
  7406. }
  7407. if ($id != 0 && is_array($extra_info)) {
  7408. $parent = $extra_info['parent_item_id'];
  7409. } else {
  7410. $parent = 0;
  7411. }
  7412. $id = intval($id);
  7413. $sql = "SELECT * FROM $tbl_lp_item
  7414. WHERE
  7415. lp_id = " . $this->lp_id." AND
  7416. iid != $id";
  7417. if ($item_type == 'dir') {
  7418. $sql .= " AND parent_item_id = 0";
  7419. }
  7420. $result = Database::query($sql);
  7421. $arrLP = [];
  7422. while ($row = Database::fetch_array($result)) {
  7423. $arrLP[] = [
  7424. 'id' => $row['iid'],
  7425. 'item_type' => $row['item_type'],
  7426. 'title' => $row['title'],
  7427. 'path' => $row['path'],
  7428. 'description' => $row['description'],
  7429. 'parent_item_id' => $row['parent_item_id'],
  7430. 'previous_item_id' => $row['previous_item_id'],
  7431. 'next_item_id' => $row['next_item_id'],
  7432. 'max_score' => $row['max_score'],
  7433. 'min_score' => $row['min_score'],
  7434. 'mastery_score' => $row['mastery_score'],
  7435. 'prerequisite' => $row['prerequisite'],
  7436. 'display_order' => $row['display_order']
  7437. ];
  7438. }
  7439. $this->tree_array($arrLP);
  7440. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7441. unset($this->arrMenu);
  7442. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7443. $form = new FormValidator('form', 'POST', $url);
  7444. $defaults['title'] = api_html_entity_decode(
  7445. $item_title,
  7446. ENT_QUOTES,
  7447. $charset
  7448. );
  7449. $defaults['description'] = $item_description;
  7450. $form->addElement('header', $title);
  7451. //$arrHide = array($id);
  7452. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7453. $arrHide[0]['padding'] = 20;
  7454. $charset = api_get_system_encoding();
  7455. for ($i = 0; $i < count($arrLP); $i++) {
  7456. if ($action != 'add') {
  7457. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7458. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7459. ) {
  7460. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7461. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7462. if ($parent == $arrLP[$i]['id']) {
  7463. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7464. }
  7465. }
  7466. } else {
  7467. if ($arrLP[$i]['item_type'] == 'dir') {
  7468. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7469. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7470. if ($parent == $arrLP[$i]['id']) {
  7471. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7472. }
  7473. }
  7474. }
  7475. }
  7476. if ($action != 'move') {
  7477. $form->addElement('text', 'title', get_lang('Title'));
  7478. $form->applyFilter('title', 'html_filter');
  7479. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7480. } else {
  7481. $form->addElement('hidden', 'title');
  7482. }
  7483. $parent_select = $form->addElement(
  7484. 'select',
  7485. 'parent',
  7486. get_lang('Parent'),
  7487. '',
  7488. [
  7489. 'id' => 'idParent',
  7490. 'onchange' => "javascript: load_cbo(this.value);",
  7491. ]
  7492. );
  7493. foreach ($arrHide as $key => $value) {
  7494. $parent_select->addOption(
  7495. $value['value'],
  7496. $key,
  7497. 'style="padding-left:'.$value['padding'].'px;"'
  7498. );
  7499. }
  7500. if (!empty($s_selected_parent)) {
  7501. $parent_select->setSelected($s_selected_parent);
  7502. }
  7503. if (is_array($arrLP)) {
  7504. reset($arrLP);
  7505. }
  7506. $arrHide = [];
  7507. // POSITION
  7508. for ($i = 0; $i < count($arrLP); $i++) {
  7509. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7510. //this is the same!
  7511. if (isset($extra_info['previous_item_id']) &&
  7512. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7513. ) {
  7514. $s_selected_position = $arrLP[$i]['id'];
  7515. } elseif ($action == 'add') {
  7516. $s_selected_position = $arrLP[$i]['id'];
  7517. }
  7518. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7519. }
  7520. }
  7521. $position = $form->addElement(
  7522. 'select',
  7523. 'previous',
  7524. get_lang('Position'),
  7525. '',
  7526. ['id' => 'previous']
  7527. );
  7528. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7529. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7530. foreach ($arrHide as $key => $value) {
  7531. $position->addOption($value['value'].'"', $key, 'style="padding-left:'.$padding.'px;"');
  7532. }
  7533. if (!empty($s_selected_position)) {
  7534. $position->setSelected($s_selected_position);
  7535. }
  7536. if (is_array($arrLP)) {
  7537. reset($arrLP);
  7538. }
  7539. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7540. //fix in order to use the tab
  7541. if ($item_type == 'dir') {
  7542. $form->addElement('hidden', 'type', 'dir');
  7543. }
  7544. $extension = null;
  7545. if (!empty($item_path)) {
  7546. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7547. }
  7548. //assets can't be modified
  7549. //$item_type == 'asset' ||
  7550. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7551. if ($item_type == 'sco') {
  7552. $form->addElement(
  7553. 'html',
  7554. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7555. );
  7556. }
  7557. $renderer = $form->defaultRenderer();
  7558. $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}', 'content_lp');
  7559. $relative_prefix = '';
  7560. $editor_config = [
  7561. 'ToolbarSet' => 'LearningPathDocuments',
  7562. 'Width' => '100%',
  7563. 'Height' => '500',
  7564. 'FullPage' => true,
  7565. 'CreateDocumentDir' => $relative_prefix,
  7566. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7567. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck
  7568. ];
  7569. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7570. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7571. $defaults['content_lp'] = file_get_contents($content_path);
  7572. }
  7573. $form->addElement('hidden', 'type', $item_type);
  7574. $form->addElement('hidden', 'post_time', time());
  7575. $form->setDefaults($defaults);
  7576. return $form->returnForm();
  7577. }
  7578. /**
  7579. * @return string
  7580. */
  7581. public function getCurrentBuildingModeURL()
  7582. {
  7583. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7584. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7585. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7586. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7587. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7588. return $currentUrl;
  7589. }
  7590. /**
  7591. * Returns the form to update or create a document
  7592. * @param string $action (add/edit)
  7593. * @param integer $id ID of the lp_item (if already exists)
  7594. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7595. * @return string HTML form
  7596. */
  7597. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7598. {
  7599. $course_id = api_get_course_int_id();
  7600. $_course = api_get_course_info();
  7601. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7602. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7603. $no_display_edit_textarea = false;
  7604. $item_description = '';
  7605. //If action==edit document
  7606. //We don't display the document form if it's not an editable document (html or txt file)
  7607. if ($action == 'edit') {
  7608. if (is_array($extra_info)) {
  7609. $path_parts = pathinfo($extra_info['dir']);
  7610. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7611. $no_display_edit_textarea = true;
  7612. }
  7613. }
  7614. }
  7615. $no_display_add = false;
  7616. // If action==add an existing document
  7617. // We don't display the document form if it's not an editable document (html or txt file).
  7618. if ($action == 'add') {
  7619. if (is_numeric($extra_info)) {
  7620. $sql_doc = "SELECT path FROM $tbl_doc
  7621. WHERE c_id = $course_id AND iid = ".intval($extra_info);
  7622. $result = Database::query($sql_doc);
  7623. $path_file = Database::result($result, 0, 0);
  7624. $path_parts = pathinfo($path_file);
  7625. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7626. $no_display_add = true;
  7627. }
  7628. }
  7629. }
  7630. if ($id != 0 && is_array($extra_info)) {
  7631. $item_title = stripslashes($extra_info['title']);
  7632. $item_description = stripslashes($extra_info['description']);
  7633. $item_terms = stripslashes($extra_info['terms']);
  7634. if (empty($item_title)) {
  7635. $path_parts = pathinfo($extra_info['path']);
  7636. $item_title = stripslashes($path_parts['filename']);
  7637. }
  7638. } elseif (is_numeric($extra_info)) {
  7639. $sql = "SELECT path, title FROM $tbl_doc
  7640. WHERE
  7641. c_id = ".$course_id." AND
  7642. iid = " . intval($extra_info);
  7643. $result = Database::query($sql);
  7644. $row = Database::fetch_array($result);
  7645. $item_title = $row['title'];
  7646. $item_title = str_replace('_', ' ', $item_title);
  7647. if (empty($item_title)) {
  7648. $path_parts = pathinfo($row['path']);
  7649. $item_title = stripslashes($path_parts['filename']);
  7650. }
  7651. } else {
  7652. $item_title = '';
  7653. $item_description = '';
  7654. }
  7655. $return = '<legend>';
  7656. if ($id != 0 && is_array($extra_info)) {
  7657. $parent = $extra_info['parent_item_id'];
  7658. } else {
  7659. $parent = 0;
  7660. }
  7661. $sql = "SELECT * FROM $tbl_lp_item
  7662. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7663. $result = Database::query($sql);
  7664. $arrLP = [];
  7665. while ($row = Database::fetch_array($result)) {
  7666. $arrLP[] = [
  7667. 'id' => $row['id'],
  7668. 'item_type' => $row['item_type'],
  7669. 'title' => $row['title'],
  7670. 'path' => $row['path'],
  7671. 'description' => $row['description'],
  7672. 'parent_item_id' => $row['parent_item_id'],
  7673. 'previous_item_id' => $row['previous_item_id'],
  7674. 'next_item_id' => $row['next_item_id'],
  7675. 'display_order' => $row['display_order'],
  7676. 'max_score' => $row['max_score'],
  7677. 'min_score' => $row['min_score'],
  7678. 'mastery_score' => $row['mastery_score'],
  7679. 'prerequisite' => $row['prerequisite']
  7680. ];
  7681. }
  7682. $this->tree_array($arrLP);
  7683. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7684. unset($this->arrMenu);
  7685. if ($action == 'add') {
  7686. $return .= get_lang('CreateTheDocument');
  7687. } elseif ($action == 'move') {
  7688. $return .= get_lang('MoveTheCurrentDocument');
  7689. } else {
  7690. $return .= get_lang('EditTheCurrentDocument');
  7691. }
  7692. $return .= '</legend>';
  7693. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7694. $return .= Display::return_message(
  7695. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7696. false
  7697. );
  7698. }
  7699. $form = new FormValidator(
  7700. 'form',
  7701. 'POST',
  7702. $this->getCurrentBuildingModeURL(),
  7703. '',
  7704. ['enctype' => 'multipart/form-data']
  7705. );
  7706. $defaults['title'] = Security::remove_XSS($item_title);
  7707. if (empty($item_title)) {
  7708. $defaults['title'] = Security::remove_XSS($item_title);
  7709. }
  7710. $defaults['description'] = $item_description;
  7711. $form->addElement('html', $return);
  7712. if ($action != 'move') {
  7713. $data = $this->generate_lp_folder($_course);
  7714. if ($action != 'edit') {
  7715. $folders = DocumentManager::get_all_document_folders(
  7716. $_course,
  7717. 0,
  7718. true
  7719. );
  7720. DocumentManager::build_directory_selector(
  7721. $folders,
  7722. '',
  7723. [],
  7724. true,
  7725. $form,
  7726. 'directory_parent_id'
  7727. );
  7728. }
  7729. if (isset($data['id'])) {
  7730. $defaults['directory_parent_id'] = $data['id'];
  7731. }
  7732. $form->addElement(
  7733. 'text',
  7734. 'title',
  7735. get_lang('Title'),
  7736. ['id' => 'idTitle', 'class' => 'col-md-4']
  7737. );
  7738. $form->applyFilter('title', 'html_filter');
  7739. }
  7740. $arrHide[0]['value'] = $this->name;
  7741. $arrHide[0]['padding'] = 20;
  7742. for ($i = 0; $i < count($arrLP); $i++) {
  7743. if ($action != 'add') {
  7744. if ($arrLP[$i]['item_type'] == 'dir' &&
  7745. !in_array($arrLP[$i]['id'], $arrHide) &&
  7746. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7747. ) {
  7748. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7749. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7750. if ($parent == $arrLP[$i]['id']) {
  7751. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7752. }
  7753. }
  7754. } else {
  7755. if ($arrLP[$i]['item_type'] == 'dir') {
  7756. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7757. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7758. if ($parent == $arrLP[$i]['id']) {
  7759. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7760. }
  7761. }
  7762. }
  7763. }
  7764. $parent_select = $form->addSelect(
  7765. 'parent',
  7766. get_lang('Parent'),
  7767. [],
  7768. [
  7769. 'id' => 'idParent',
  7770. 'onchange' => 'javascript: load_cbo(this.value);',
  7771. ]
  7772. );
  7773. $my_count = 0;
  7774. foreach ($arrHide as $key => $value) {
  7775. if ($my_count != 0) {
  7776. // The LP name is also the first section and is not in the same charset like the other sections.
  7777. $value['value'] = Security::remove_XSS($value['value']);
  7778. $parent_select->addOption(
  7779. $value['value'],
  7780. $key,
  7781. 'style="padding-left:'.$value['padding'].'px;"'
  7782. );
  7783. } else {
  7784. $value['value'] = Security::remove_XSS($value['value']);
  7785. $parent_select->addOption(
  7786. $value['value'],
  7787. $key,
  7788. 'style="padding-left:'.$value['padding'].'px;"'
  7789. );
  7790. }
  7791. $my_count++;
  7792. }
  7793. if (!empty($id)) {
  7794. $parent_select->setSelected($parent);
  7795. } else {
  7796. $parent_item_id = Session::read('parent_item_id', 0);
  7797. $parent_select->setSelected($parent_item_id);
  7798. }
  7799. if (is_array($arrLP)) {
  7800. reset($arrLP);
  7801. }
  7802. $arrHide = [];
  7803. $s_selected_position = null;
  7804. // POSITION
  7805. $lastPosition = null;
  7806. for ($i = 0; $i < count($arrLP); $i++) {
  7807. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7808. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7809. ) {
  7810. if ((isset($extra_info['previous_item_id']) &&
  7811. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  7812. ) {
  7813. $s_selected_position = $arrLP[$i]['id'];
  7814. }
  7815. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7816. }
  7817. $lastPosition = $arrLP[$i]['id'];
  7818. }
  7819. if (empty($s_selected_position)) {
  7820. $s_selected_position = $lastPosition;
  7821. }
  7822. $position = $form->addSelect(
  7823. 'previous',
  7824. get_lang('Position'),
  7825. [],
  7826. ['id' => 'previous']
  7827. );
  7828. $position->addOption(get_lang('FirstPosition'), 0);
  7829. foreach ($arrHide as $key => $value) {
  7830. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7831. $position->addOption(
  7832. $value['value'],
  7833. $key,
  7834. 'style="padding-left:'.$padding.'px;"'
  7835. );
  7836. }
  7837. $position->setSelected($s_selected_position);
  7838. if (is_array($arrLP)) {
  7839. reset($arrLP);
  7840. }
  7841. if ($action != 'move') {
  7842. $id_prerequisite = 0;
  7843. if (is_array($arrLP)) {
  7844. foreach ($arrLP as $key => $value) {
  7845. if ($value['id'] == $id) {
  7846. $id_prerequisite = $value['prerequisite'];
  7847. break;
  7848. }
  7849. }
  7850. }
  7851. $arrHide = [];
  7852. for ($i = 0; $i < count($arrLP); $i++) {
  7853. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7854. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7855. ) {
  7856. if (isset($extra_info['previous_item_id']) &&
  7857. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7858. ) {
  7859. $s_selected_position = $arrLP[$i]['id'];
  7860. } elseif ($action == 'add') {
  7861. $s_selected_position = $arrLP[$i]['id'];
  7862. }
  7863. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7864. }
  7865. }
  7866. if (!$no_display_add) {
  7867. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7868. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7869. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  7870. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  7871. ) {
  7872. if (isset($_POST['content'])) {
  7873. $content = stripslashes($_POST['content']);
  7874. } elseif (is_array($extra_info)) {
  7875. //If it's an html document or a text file
  7876. if (!$no_display_edit_textarea) {
  7877. $content = $this->display_document(
  7878. $extra_info['path'],
  7879. false,
  7880. false
  7881. );
  7882. }
  7883. } elseif (is_numeric($extra_info)) {
  7884. $content = $this->display_document(
  7885. $extra_info,
  7886. false,
  7887. false
  7888. );
  7889. } else {
  7890. $content = '';
  7891. }
  7892. if (!$no_display_edit_textarea) {
  7893. // We need to calculate here some specific settings for the online editor.
  7894. // The calculated settings work for documents in the Documents tool
  7895. // (on the root or in subfolders).
  7896. // For documents in native scorm packages it is unclear whether the
  7897. // online editor should be activated or not.
  7898. // A new document, it is in the root of the repository.
  7899. $relative_path = '';
  7900. $relative_prefix = '';
  7901. if (is_array($extra_info) && $extra_info != 'new') {
  7902. // The document already exists. Whe have to determine its relative path towards the repository root.
  7903. $relative_path = explode('/', $extra_info['dir']);
  7904. $cnt = count($relative_path) - 2;
  7905. if ($cnt < 0) {
  7906. $cnt = 0;
  7907. }
  7908. $relative_prefix = str_repeat('../', $cnt);
  7909. $relative_path = array_slice($relative_path, 1, $cnt);
  7910. $relative_path = implode('/', $relative_path);
  7911. if (strlen($relative_path) > 0) {
  7912. $relative_path = $relative_path.'/';
  7913. }
  7914. } else {
  7915. $result = $this->generate_lp_folder($_course);
  7916. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7917. $relative_prefix = '../../';
  7918. }
  7919. $editor_config = [
  7920. 'ToolbarSet' => 'LearningPathDocuments',
  7921. 'Width' => '100%',
  7922. 'Height' => '500',
  7923. 'FullPage' => true,
  7924. 'CreateDocumentDir' => $relative_prefix,
  7925. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7926. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path
  7927. ];
  7928. if ($_GET['action'] == 'add_item') {
  7929. $class = 'add';
  7930. $text = get_lang('LPCreateDocument');
  7931. } else {
  7932. if ($_GET['action'] == 'edit_item') {
  7933. $class = 'save';
  7934. $text = get_lang('SaveDocument');
  7935. }
  7936. }
  7937. $form->addButtonSave($text, 'submit_button');
  7938. $renderer = $form->defaultRenderer();
  7939. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7940. $form->addElement('html', '<div class="editor-lp">');
  7941. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7942. $form->addElement('html', '</div>');
  7943. $defaults['content_lp'] = $content;
  7944. }
  7945. } elseif (is_numeric($extra_info)) {
  7946. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7947. $return = $this->display_document($extra_info, true, true, true);
  7948. $form->addElement('html', $return);
  7949. }
  7950. }
  7951. }
  7952. if (isset($extra_info['item_type']) &&
  7953. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7954. ) {
  7955. $parent_select->freeze();
  7956. $position->freeze();
  7957. }
  7958. if ($action == 'move') {
  7959. $form->addElement('hidden', 'title', $item_title);
  7960. $form->addElement('hidden', 'description', $item_description);
  7961. }
  7962. if (is_numeric($extra_info)) {
  7963. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7964. $form->addElement('hidden', 'path', $extra_info);
  7965. } elseif (is_array($extra_info)) {
  7966. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7967. $form->addElement('hidden', 'path', $extra_info['path']);
  7968. }
  7969. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7970. $form->addElement('hidden', 'post_time', time());
  7971. $form->setDefaults($defaults);
  7972. return $form->returnForm();
  7973. }
  7974. /**
  7975. * Return HTML form to add/edit a link item
  7976. * @param string $action (add/edit)
  7977. * @param integer $id Item ID if exists
  7978. * @param mixed $extra_info
  7979. * @return string HTML form
  7980. */
  7981. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  7982. {
  7983. $course_id = api_get_course_int_id();
  7984. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7985. $tbl_link = Database::get_course_table(TABLE_LINK);
  7986. if ($id != 0 && is_array($extra_info)) {
  7987. $item_title = stripslashes($extra_info['title']);
  7988. $item_description = stripslashes($extra_info['description']);
  7989. $item_url = stripslashes($extra_info['url']);
  7990. } elseif (is_numeric($extra_info)) {
  7991. $extra_info = intval($extra_info);
  7992. $sql = "SELECT title, description, url FROM ".$tbl_link."
  7993. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  7994. $result = Database::query($sql);
  7995. $row = Database::fetch_array($result);
  7996. $item_title = $row['title'];
  7997. $item_description = $row['description'];
  7998. $item_url = $row['url'];
  7999. } else {
  8000. $item_title = '';
  8001. $item_description = '';
  8002. $item_url = '';
  8003. }
  8004. $form = new FormValidator(
  8005. 'edit_link',
  8006. 'POST',
  8007. $this->getCurrentBuildingModeURL()
  8008. );
  8009. $defaults = [];
  8010. if ($id != 0 && is_array($extra_info)) {
  8011. $parent = $extra_info['parent_item_id'];
  8012. } else {
  8013. $parent = 0;
  8014. }
  8015. $sql = "SELECT * FROM $tbl_lp_item
  8016. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8017. $result = Database::query($sql);
  8018. $arrLP = [];
  8019. while ($row = Database::fetch_array($result)) {
  8020. $arrLP[] = [
  8021. 'id' => $row['id'],
  8022. 'item_type' => $row['item_type'],
  8023. 'title' => $row['title'],
  8024. 'path' => $row['path'],
  8025. 'description' => $row['description'],
  8026. 'parent_item_id' => $row['parent_item_id'],
  8027. 'previous_item_id' => $row['previous_item_id'],
  8028. 'next_item_id' => $row['next_item_id'],
  8029. 'display_order' => $row['display_order'],
  8030. 'max_score' => $row['max_score'],
  8031. 'min_score' => $row['min_score'],
  8032. 'mastery_score' => $row['mastery_score'],
  8033. 'prerequisite' => $row['prerequisite']
  8034. ];
  8035. }
  8036. $this->tree_array($arrLP);
  8037. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8038. unset($this->arrMenu);
  8039. if ($action == 'add') {
  8040. $legend = get_lang('CreateTheLink');
  8041. } elseif ($action == 'move') {
  8042. $legend = get_lang('MoveCurrentLink');
  8043. } else {
  8044. $legend = get_lang('EditCurrentLink');
  8045. }
  8046. $form->addHeader($legend);
  8047. if ($action != 'move') {
  8048. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8049. $defaults['title'] = $item_title;
  8050. }
  8051. $selectParent = $form->addSelect(
  8052. 'parent',
  8053. get_lang('Parent'),
  8054. [],
  8055. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8056. );
  8057. $selectParent->addOption($this->name, 0);
  8058. $arrHide = [
  8059. $id
  8060. ];
  8061. $parent_item_id = Session::read('parent_item_id', 0);
  8062. for ($i = 0; $i < count($arrLP); $i++) {
  8063. if ($action != 'add') {
  8064. if (
  8065. ($arrLP[$i]['item_type'] == 'dir') &&
  8066. !in_array($arrLP[$i]['id'], $arrHide) &&
  8067. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8068. ) {
  8069. $selectParent->addOption(
  8070. $arrLP[$i]['title'],
  8071. $arrLP[$i]['id'],
  8072. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8073. );
  8074. if ($parent == $arrLP[$i]['id']) {
  8075. $selectParent->setSelected($arrLP[$i]['id']);
  8076. }
  8077. } else {
  8078. $arrHide[] = $arrLP[$i]['id'];
  8079. }
  8080. } else {
  8081. if ($arrLP[$i]['item_type'] == 'dir') {
  8082. $selectParent->addOption(
  8083. $arrLP[$i]['title'],
  8084. $arrLP[$i]['id'],
  8085. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8086. );
  8087. if ($parent_item_id == $arrLP[$i]['id']) {
  8088. $selectParent->setSelected($arrLP[$i]['id']);
  8089. }
  8090. }
  8091. }
  8092. }
  8093. if (is_array($arrLP)) {
  8094. reset($arrLP);
  8095. }
  8096. $selectPrevious = $form->addSelect(
  8097. 'previous',
  8098. get_lang('Position'),
  8099. [],
  8100. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8101. );
  8102. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8103. for ($i = 0; $i < count($arrLP); $i++) {
  8104. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8105. $selectPrevious->addOption(
  8106. $arrLP[$i]['title'],
  8107. $arrLP[$i]['id']
  8108. );
  8109. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8110. $selectPrevious->setSelected($arrLP[$i]['id']);
  8111. } elseif ($action == 'add') {
  8112. $selectPrevious->setSelected($arrLP[$i]['id']);
  8113. }
  8114. }
  8115. }
  8116. if ($action != 'move') {
  8117. $urlAttributes = ['class' => 'learnpath_item_form'];
  8118. if (is_numeric($extra_info)) {
  8119. $urlAttributes['disabled'] = 'disabled';
  8120. }
  8121. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8122. $defaults['url'] = $item_url;
  8123. $id_prerequisite = 0;
  8124. if (is_array($arrLP)) {
  8125. foreach ($arrLP as $key => $value) {
  8126. if ($value['id'] == $id) {
  8127. $id_prerequisite = $value['prerequisite'];
  8128. break;
  8129. }
  8130. }
  8131. }
  8132. $arrHide = [];
  8133. for ($i = 0; $i < count($arrLP); $i++) {
  8134. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8135. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8136. $s_selected_position = $arrLP[$i]['id'];
  8137. } elseif ($action == 'add') {
  8138. $s_selected_position = 0;
  8139. }
  8140. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8141. }
  8142. }
  8143. }
  8144. if ($action == 'add') {
  8145. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8146. } else {
  8147. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8148. }
  8149. if ($action == 'move') {
  8150. $form->addHidden('title', $item_title);
  8151. $form->addHidden('description', $item_description);
  8152. }
  8153. if (is_numeric($extra_info)) {
  8154. $form->addHidden('path', $extra_info);
  8155. } elseif (is_array($extra_info)) {
  8156. $form->addHidden('path', $extra_info['path']);
  8157. }
  8158. $form->addHidden('type', TOOL_LINK);
  8159. $form->addHidden('post_time', time());
  8160. $form->setDefaults($defaults);
  8161. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8162. }
  8163. /**
  8164. * Return HTML form to add/edit a student publication (work)
  8165. * @param string Action (add/edit)
  8166. * @param integer Item ID if already exists
  8167. * @param mixed Extra info (work ID if integer)
  8168. * @return string HTML form
  8169. */
  8170. public function display_student_publication_form(
  8171. $action = 'add',
  8172. $id = 0,
  8173. $extra_info = ''
  8174. ) {
  8175. $course_id = api_get_course_int_id();
  8176. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8177. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8178. if ($id != 0 && is_array($extra_info)) {
  8179. $item_title = stripslashes($extra_info['title']);
  8180. $item_description = stripslashes($extra_info['description']);
  8181. } elseif (is_numeric($extra_info)) {
  8182. $extra_info = intval($extra_info);
  8183. $sql = "SELECT title, description
  8184. FROM $tbl_publication
  8185. WHERE c_id = $course_id AND id = ".$extra_info;
  8186. $result = Database::query($sql);
  8187. $row = Database::fetch_array($result);
  8188. $item_title = $row['title'];
  8189. } else {
  8190. $item_title = get_lang('Student_publication');
  8191. }
  8192. if ($id != 0 && is_array($extra_info)) {
  8193. $parent = $extra_info['parent_item_id'];
  8194. } else {
  8195. $parent = 0;
  8196. }
  8197. $sql = "SELECT * FROM $tbl_lp_item
  8198. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8199. $result = Database::query($sql);
  8200. $arrLP = [];
  8201. while ($row = Database::fetch_array($result)) {
  8202. $arrLP[] = [
  8203. 'id' => $row['iid'],
  8204. 'item_type' => $row['item_type'],
  8205. 'title' => $row['title'],
  8206. 'path' => $row['path'],
  8207. 'description' => $row['description'],
  8208. 'parent_item_id' => $row['parent_item_id'],
  8209. 'previous_item_id' => $row['previous_item_id'],
  8210. 'next_item_id' => $row['next_item_id'],
  8211. 'display_order' => $row['display_order'],
  8212. 'max_score' => $row['max_score'],
  8213. 'min_score' => $row['min_score'],
  8214. 'mastery_score' => $row['mastery_score'],
  8215. 'prerequisite' => $row['prerequisite']
  8216. ];
  8217. }
  8218. $this->tree_array($arrLP);
  8219. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8220. unset($this->arrMenu);
  8221. $form = new FormValidator('frm_student_publication', 'post', '#');
  8222. if ($action == 'add') {
  8223. $form->addHeader(get_lang('Student_publication'));
  8224. } elseif ($action == 'move') {
  8225. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8226. } else {
  8227. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8228. }
  8229. if ($action != 'move') {
  8230. $form->addText(
  8231. 'title',
  8232. get_lang('Title'),
  8233. true,
  8234. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8235. );
  8236. }
  8237. $parentSelect = $form->addSelect(
  8238. 'parent',
  8239. get_lang('Parent'),
  8240. ['0' => $this->name],
  8241. [
  8242. 'onchange' => 'javascript: load_cbo(this.value);',
  8243. 'class' => 'learnpath_item_form',
  8244. 'id' => 'idParent'
  8245. ]
  8246. );
  8247. $arrHide = [$id];
  8248. for ($i = 0; $i < count($arrLP); $i++) {
  8249. if ($action != 'add') {
  8250. if (
  8251. ($arrLP[$i]['item_type'] == 'dir') &&
  8252. !in_array($arrLP[$i]['id'], $arrHide) &&
  8253. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8254. ) {
  8255. $parentSelect->addOption(
  8256. $arrLP[$i]['title'],
  8257. $arrLP[$i]['id'],
  8258. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8259. );
  8260. if ($parent == $arrLP[$i]['id']) {
  8261. $parentSelect->setSelected($arrLP[$i]['id']);
  8262. }
  8263. } else {
  8264. $arrHide[] = $arrLP[$i]['id'];
  8265. }
  8266. } else {
  8267. if ($arrLP[$i]['item_type'] == 'dir') {
  8268. $parentSelect->addOption(
  8269. $arrLP[$i]['title'],
  8270. $arrLP[$i]['id'],
  8271. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8272. );
  8273. if ($parent == $arrLP[$i]['id']) {
  8274. $parentSelect->setSelected($arrLP[$i]['id']);
  8275. }
  8276. }
  8277. }
  8278. }
  8279. if (is_array($arrLP)) {
  8280. reset($arrLP);
  8281. }
  8282. $previousSelect = $form->addSelect(
  8283. 'previous',
  8284. get_lang('Position'),
  8285. ['0' => get_lang('FirstPosition')],
  8286. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8287. );
  8288. for ($i = 0; $i < count($arrLP); $i++) {
  8289. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8290. $previousSelect->addOption(
  8291. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8292. $arrLP[$i]['id']
  8293. );
  8294. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8295. $previousSelect->setSelected($arrLP[$i]['id']);
  8296. } elseif ($action == 'add') {
  8297. $previousSelect->setSelected($arrLP[$i]['id']);
  8298. }
  8299. }
  8300. }
  8301. if ($action != 'move') {
  8302. $id_prerequisite = 0;
  8303. if (is_array($arrLP)) {
  8304. foreach ($arrLP as $key => $value) {
  8305. if ($value['id'] == $id) {
  8306. $id_prerequisite = $value['prerequisite'];
  8307. break;
  8308. }
  8309. }
  8310. }
  8311. $arrHide = [];
  8312. for ($i = 0; $i < count($arrLP); $i++) {
  8313. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8314. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8315. $s_selected_position = $arrLP[$i]['id'];
  8316. } elseif ($action == 'add') {
  8317. $s_selected_position = 0;
  8318. }
  8319. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8320. }
  8321. }
  8322. }
  8323. if ($action == 'add') {
  8324. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8325. } else {
  8326. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8327. }
  8328. if ($action == 'move') {
  8329. $form->addHidden('title', $item_title);
  8330. $form->addHidden('description', $item_description);
  8331. }
  8332. if (is_numeric($extra_info)) {
  8333. $form->addHidden('path', $extra_info);
  8334. } elseif (is_array($extra_info)) {
  8335. $form->addHidden('path', $extra_info['path']);
  8336. }
  8337. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8338. $form->addHidden('post_time', time());
  8339. $form->setDefaults(['title' => $item_title]);
  8340. $return = '<div class="sectioncomment">';
  8341. $return .= $form->returnForm();
  8342. $return .= '</div>';
  8343. return $return;
  8344. }
  8345. /**
  8346. * Displays the menu for manipulating a step
  8347. *
  8348. * @param $item_id
  8349. * @param string $item_type
  8350. * @return string
  8351. */
  8352. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8353. {
  8354. $_course = api_get_course_info();
  8355. $course_id = api_get_course_int_id();
  8356. $course_code = api_get_course_id();
  8357. $return = '<div class="actions">';
  8358. switch ($item_type) {
  8359. case 'dir':
  8360. // Commented the message cause should not show it.
  8361. //$lang = get_lang('TitleManipulateChapter');
  8362. break;
  8363. case TOOL_LP_FINAL_ITEM:
  8364. case TOOL_DOCUMENT:
  8365. // Commented the message cause should not show it.
  8366. //$lang = get_lang('TitleManipulateDocument');
  8367. break;
  8368. case TOOL_LINK:
  8369. case 'link':
  8370. // Commented the message cause should not show it.
  8371. //$lang = get_lang('TitleManipulateLink');
  8372. break;
  8373. case TOOL_QUIZ:
  8374. // Commented the message cause should not show it.
  8375. //$lang = get_lang('TitleManipulateQuiz');
  8376. break;
  8377. case TOOL_STUDENTPUBLICATION:
  8378. // Commented the message cause should not show it.
  8379. //$lang = get_lang('TitleManipulateStudentPublication');
  8380. break;
  8381. }
  8382. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8383. $item_id = intval($item_id);
  8384. $sql = "SELECT * FROM $tbl_lp_item
  8385. WHERE iid = ".$item_id;
  8386. $result = Database::query($sql);
  8387. $row = Database::fetch_assoc($result);
  8388. $audio_player = null;
  8389. // We display an audio player if needed.
  8390. if (!empty($row['audio'])) {
  8391. $audio_player .= '<div class="lp_mediaplayer" id="container">
  8392. <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
  8393. </div>';
  8394. $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
  8395. $audio_player .= '<script>
  8396. var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
  8397. s1.addParam("allowscriptaccess","always");
  8398. s1.addParam("flashvars","file=../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'].'&autostart=true");
  8399. s1.write("container");
  8400. </script>';
  8401. }
  8402. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8403. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8404. $return .= Display::url(
  8405. Display::return_icon(
  8406. 'edit.png',
  8407. get_lang('Edit'),
  8408. [],
  8409. ICON_SIZE_SMALL
  8410. ),
  8411. $url.'&action=edit_item&path_item='.$row['path']
  8412. );
  8413. $return .= Display::url(
  8414. Display::return_icon(
  8415. 'move.png',
  8416. get_lang('Move'),
  8417. [],
  8418. ICON_SIZE_SMALL
  8419. ),
  8420. $url.'&action=move_item'
  8421. );
  8422. }
  8423. // Commented for now as prerequisites cannot be added to chapters.
  8424. if ($item_type != 'dir') {
  8425. $return .= Display::url(
  8426. Display::return_icon(
  8427. 'accept.png',
  8428. get_lang('LearnpathPrerequisites'),
  8429. [],
  8430. ICON_SIZE_SMALL
  8431. ),
  8432. $url.'&action=edit_item_prereq'
  8433. );
  8434. }
  8435. $return .= Display::url(
  8436. Display::return_icon(
  8437. 'delete.png',
  8438. get_lang('Delete'),
  8439. [],
  8440. ICON_SIZE_SMALL
  8441. ),
  8442. $url.'&action=delete_item'
  8443. );
  8444. if ($item_type == TOOL_HOTPOTATOES) {
  8445. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8446. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8447. }
  8448. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  8449. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8450. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8451. }
  8452. $return .= '</div>';
  8453. if (!empty($audio_player)) {
  8454. $return .= '<br />'.$audio_player;
  8455. }
  8456. return $return;
  8457. }
  8458. /**
  8459. * Creates the javascript needed for filling up the checkboxes without page reload
  8460. * @return string
  8461. */
  8462. public function get_js_dropdown_array()
  8463. {
  8464. $course_id = api_get_course_int_id();
  8465. $return = 'var child_name = new Array();'."\n";
  8466. $return .= 'var child_value = new Array();'."\n\n";
  8467. $return .= 'child_name[0] = new Array();'."\n";
  8468. $return .= 'child_value[0] = new Array();'."\n\n";
  8469. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8470. $sql = "SELECT * FROM ".$tbl_lp_item."
  8471. WHERE
  8472. c_id = $course_id AND
  8473. lp_id = ".$this->lp_id." AND
  8474. parent_item_id = 0
  8475. ORDER BY display_order ASC";
  8476. $res_zero = Database::query($sql);
  8477. $i = 0;
  8478. while ($row_zero = Database::fetch_array($res_zero)) {
  8479. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8480. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8481. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8482. }
  8483. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8484. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8485. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8486. }
  8487. }
  8488. $return .= "\n";
  8489. $sql = "SELECT * FROM $tbl_lp_item
  8490. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8491. $res = Database::query($sql);
  8492. while ($row = Database::fetch_array($res)) {
  8493. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8494. WHERE
  8495. c_id = ".$course_id." AND
  8496. parent_item_id = " . $row['iid']."
  8497. ORDER BY display_order ASC";
  8498. $res_parent = Database::query($sql_parent);
  8499. $i = 0;
  8500. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8501. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8502. while ($row_parent = Database::fetch_array($res_parent)) {
  8503. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  8504. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8505. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8506. }
  8507. $return .= "\n";
  8508. }
  8509. return $return;
  8510. }
  8511. /**
  8512. * Display the form to allow moving an item
  8513. * @param integer $item_id Item ID
  8514. * @return string HTML form
  8515. */
  8516. public function display_move_item($item_id)
  8517. {
  8518. $course_id = api_get_course_int_id();
  8519. $return = '';
  8520. if (is_numeric($item_id)) {
  8521. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8522. $sql = "SELECT * FROM $tbl_lp_item
  8523. WHERE iid = $item_id";
  8524. $res = Database::query($sql);
  8525. $row = Database::fetch_array($res);
  8526. switch ($row['item_type']) {
  8527. case 'dir':
  8528. case 'asset':
  8529. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8530. $return .= $this->display_item_form(
  8531. $row['item_type'],
  8532. get_lang('MoveCurrentChapter'),
  8533. 'move',
  8534. $item_id,
  8535. $row
  8536. );
  8537. break;
  8538. case TOOL_DOCUMENT:
  8539. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8540. $return .= $this->display_document_form('move', $item_id, $row);
  8541. break;
  8542. case TOOL_LINK:
  8543. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8544. $return .= $this->display_link_form('move', $item_id, $row);
  8545. break;
  8546. case TOOL_HOTPOTATOES:
  8547. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8548. $return .= $this->display_link_form('move', $item_id, $row);
  8549. break;
  8550. case TOOL_QUIZ:
  8551. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8552. $return .= $this->display_quiz_form('move', $item_id, $row);
  8553. break;
  8554. case TOOL_STUDENTPUBLICATION:
  8555. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8556. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8557. break;
  8558. case TOOL_FORUM:
  8559. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8560. $return .= $this->display_forum_form('move', $item_id, $row);
  8561. break;
  8562. case TOOL_THREAD:
  8563. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8564. $return .= $this->display_forum_form('move', $item_id, $row);
  8565. break;
  8566. }
  8567. }
  8568. return $return;
  8569. }
  8570. /**
  8571. * Displays a basic form on the overview page for changing the item title and the item description.
  8572. * @param string $item_type
  8573. * @param string $title
  8574. * @param array $data
  8575. * @return string
  8576. */
  8577. public function display_item_small_form($item_type, $title = '', $data = [])
  8578. {
  8579. $url = api_get_self().'?'.api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
  8580. $form = new FormValidator('small_form', 'post', $url);
  8581. $form->addElement('header', $title);
  8582. $form->addElement('text', 'title', get_lang('Title'));
  8583. $form->addButtonSave(get_lang('Save'), 'submit_button');
  8584. $form->addElement('hidden', 'id', $data['id']);
  8585. $form->addElement('hidden', 'parent', $data['parent_item_id']);
  8586. $form->addElement('hidden', 'previous', $data['previous_item_id']);
  8587. $form->setDefaults(['title' => $data['title']]);
  8588. return $form->toHtml();
  8589. }
  8590. /**
  8591. * Return HTML form to allow prerequisites selection
  8592. * @todo use FormValidator
  8593. * @param integer Item ID
  8594. * @return string HTML form
  8595. */
  8596. public function display_item_prerequisites_form($item_id)
  8597. {
  8598. $course_id = api_get_course_int_id();
  8599. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8600. $item_id = intval($item_id);
  8601. /* Current prerequisite */
  8602. $sql = "SELECT * FROM $tbl_lp_item
  8603. WHERE iid = $item_id";
  8604. $result = Database::query($sql);
  8605. $row = Database::fetch_array($result);
  8606. $prerequisiteId = $row['prerequisite'];
  8607. $return = '<legend>';
  8608. $return .= get_lang('AddEditPrerequisites');
  8609. $return .= '</legend>';
  8610. $return .= '<form method="POST">';
  8611. $return .= '<div class="table-responsive">';
  8612. $return .= '<table class="table table-hover">';
  8613. $return .= '<thead>';
  8614. $return .= '<tr>';
  8615. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8616. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8617. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8618. $return .= '</tr>';
  8619. $return .= '</thead>';
  8620. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8621. $return .= '<tbody>';
  8622. $return .= '<tr>';
  8623. $return .= '<td colspan="3">';
  8624. $return .= '<div class="radio learnpath"><label for="idNone">';
  8625. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8626. $return .= get_lang('None').'</label>';
  8627. $return .= '</div>';
  8628. $return .= '</tr>';
  8629. $sql = "SELECT * FROM $tbl_lp_item
  8630. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8631. $result = Database::query($sql);
  8632. $arrLP = [];
  8633. $selectedMinScore = [];
  8634. $selectedMaxScore = [];
  8635. while ($row = Database::fetch_array($result)) {
  8636. if ($row['id'] == $item_id) {
  8637. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8638. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8639. }
  8640. $arrLP[] = [
  8641. 'id' => $row['iid'],
  8642. 'item_type' => $row['item_type'],
  8643. 'title' => $row['title'],
  8644. 'ref' => $row['ref'],
  8645. 'description' => $row['description'],
  8646. 'parent_item_id' => $row['parent_item_id'],
  8647. 'previous_item_id' => $row['previous_item_id'],
  8648. 'next_item_id' => $row['next_item_id'],
  8649. 'max_score' => $row['max_score'],
  8650. 'min_score' => $row['min_score'],
  8651. 'mastery_score' => $row['mastery_score'],
  8652. 'prerequisite' => $row['prerequisite'],
  8653. 'next_item_id' => $row['next_item_id'],
  8654. 'display_order' => $row['display_order'],
  8655. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  8656. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  8657. ];
  8658. }
  8659. $this->tree_array($arrLP);
  8660. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8661. unset($this->arrMenu);
  8662. for ($i = 0; $i < count($arrLP); $i++) {
  8663. $item = $arrLP[$i];
  8664. if ($item['id'] == $item_id) {
  8665. break;
  8666. }
  8667. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8668. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8669. $return .= '<tr>';
  8670. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8671. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8672. $return .= '<label for="id'.$item['id'].'">';
  8673. $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'].'" />';
  8674. $icon_name = str_replace(' ', '', $item['item_type']);
  8675. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8676. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8677. } else {
  8678. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8679. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8680. } else {
  8681. $return .= Display::return_icon('folder_document.png');
  8682. }
  8683. }
  8684. $return .= $item['title'].'</label>';
  8685. $return .= '</div>';
  8686. $return .= '</td>';
  8687. if ($item['item_type'] == TOOL_QUIZ) {
  8688. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8689. $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
  8690. $tmp_obj_exercice = new Exercise($course_id);
  8691. $tmp_obj_exercice->read($tmp_obj_lp_item->path);
  8692. $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
  8693. $tmp_obj_lp_item->update();
  8694. $item['max_score'] = $tmp_obj_lp_item->max_score;
  8695. $return .= '<td>';
  8696. $return .= '<input class="form-control" size="4" maxlength="3" name="min_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue.'" />';
  8697. $return .= '</td>';
  8698. $return .= '<td>';
  8699. $return .= '<input class="form-control" size="4" maxlength="3" readonly name="max_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue.'" />';
  8700. $return .= '</td>';
  8701. }
  8702. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8703. $return .= '<td>';
  8704. $return .= '<input size="4" maxlength="3" name="min_'.$item['id'].'" type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue.'" />';
  8705. $return .= '</td>';
  8706. $return .= '<td>';
  8707. $return .= '<input size="4" maxlength="3" name="max_'.$item['id'].'" readonly type="number" min="0" step="1" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue.'" />';
  8708. $return .= '</td>';
  8709. }
  8710. $return .= '</tr>';
  8711. }
  8712. $return .= '<tr>';
  8713. $return .= '</tr>';
  8714. $return .= '</tbody>';
  8715. $return .= '</table>';
  8716. $return .= '</div>';
  8717. $return .= '<div class="form-group">';
  8718. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.get_lang('ModifyPrerequisites').'</button>';
  8719. $return .= '</form>';
  8720. return $return;
  8721. }
  8722. /**
  8723. * Return HTML list to allow prerequisites selection for lp
  8724. * @param integer Item ID
  8725. * @return string HTML form
  8726. */
  8727. public function display_lp_prerequisites_list()
  8728. {
  8729. $course_id = api_get_course_int_id();
  8730. $lp_id = $this->lp_id;
  8731. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  8732. // get current prerequisite
  8733. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  8734. $result = Database::query($sql);
  8735. $row = Database::fetch_array($result);
  8736. $prerequisiteId = $row['prerequisite'];
  8737. $session_id = api_get_session_id();
  8738. $session_condition = api_get_session_condition($session_id, true, true);
  8739. $sql = "SELECT * FROM $tbl_lp
  8740. WHERE c_id = $course_id $session_condition
  8741. ORDER BY display_order ";
  8742. $rs = Database::query($sql);
  8743. $return = '';
  8744. $return .= '<select name="prerequisites" class="form-control">';
  8745. $return .= '<option value="0">'.get_lang('None').'</option>';
  8746. if (Database::num_rows($rs) > 0) {
  8747. while ($row = Database::fetch_array($rs)) {
  8748. if ($row['id'] == $lp_id) {
  8749. continue;
  8750. }
  8751. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  8752. }
  8753. }
  8754. $return .= '</select>';
  8755. return $return;
  8756. }
  8757. /**
  8758. * Creates a list with all the documents in it
  8759. * @param bool $showInvisibleFiles
  8760. * @return string
  8761. */
  8762. public function get_documents($showInvisibleFiles = false)
  8763. {
  8764. $course_info = api_get_course_info();
  8765. $sessionId = api_get_session_id();
  8766. $documentTree = DocumentManager::get_document_preview(
  8767. $course_info,
  8768. $this->lp_id,
  8769. null,
  8770. $sessionId,
  8771. true,
  8772. null,
  8773. null,
  8774. $showInvisibleFiles,
  8775. true
  8776. );
  8777. $headers = [
  8778. get_lang('Files'),
  8779. get_lang('CreateTheDocument'),
  8780. get_lang('Upload')
  8781. ];
  8782. $form = new FormValidator(
  8783. 'form_upload',
  8784. 'POST',
  8785. $this->getCurrentBuildingModeURL(),
  8786. '',
  8787. ['enctype' => 'multipart/form-data']
  8788. );
  8789. $folders = DocumentManager::get_all_document_folders(
  8790. api_get_course_info(),
  8791. 0,
  8792. true
  8793. );
  8794. DocumentManager::build_directory_selector(
  8795. $folders,
  8796. '',
  8797. [],
  8798. true,
  8799. $form,
  8800. 'directory_parent_id'
  8801. );
  8802. $group = [
  8803. $form->createElement(
  8804. 'radio',
  8805. 'if_exists',
  8806. get_lang("UplWhatIfFileExists"),
  8807. get_lang('UplDoNothing'),
  8808. 'nothing'
  8809. ),
  8810. $form->createElement(
  8811. 'radio',
  8812. 'if_exists',
  8813. null,
  8814. get_lang('UplOverwriteLong'),
  8815. 'overwrite'
  8816. ),
  8817. $form->createElement(
  8818. 'radio',
  8819. 'if_exists',
  8820. null,
  8821. get_lang('UplRenameLong'),
  8822. 'rename'
  8823. )
  8824. ];
  8825. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  8826. $form->setDefaults(['if_exists' => 'rename']);
  8827. // Check box options
  8828. $form->addElement(
  8829. 'checkbox',
  8830. 'unzip',
  8831. get_lang('Options'),
  8832. get_lang('Uncompress')
  8833. );
  8834. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  8835. $form->addMultipleUpload($url);
  8836. $new = $this->display_document_form('add', 0);
  8837. $tabs = Display::tabs(
  8838. $headers,
  8839. [$documentTree, $new, $form->returnForm()],
  8840. 'subtab'
  8841. );
  8842. return $tabs;
  8843. }
  8844. /**
  8845. * Creates a list with all the exercises (quiz) in it
  8846. * @return string
  8847. */
  8848. public function get_exercises()
  8849. {
  8850. $course_id = api_get_course_int_id();
  8851. $session_id = api_get_session_id();
  8852. $userInfo = api_get_user_info();
  8853. // New for hotpotatoes.
  8854. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  8855. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8856. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  8857. $condition_session = api_get_session_condition($session_id, true, true);
  8858. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  8859. $activeCondition = ' active <> -1 ';
  8860. if ($setting) {
  8861. $activeCondition = ' active = 1 ';
  8862. }
  8863. $sql_quiz = "SELECT * FROM $tbl_quiz
  8864. WHERE c_id = $course_id AND $activeCondition $condition_session
  8865. ORDER BY title ASC";
  8866. $sql_hot = "SELECT * FROM $tbl_doc
  8867. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  8868. ORDER BY id ASC";
  8869. $res_quiz = Database::query($sql_quiz);
  8870. $res_hot = Database::query($sql_hot);
  8871. $return = '<ul class="lp_resource">';
  8872. $return .= '<li class="lp_resource_element">';
  8873. $return .= Display::return_icon('new_exercice.png');
  8874. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  8875. get_lang('NewExercise').'</a>';
  8876. $return .= '</li>';
  8877. $previewIcon = Display::return_icon(
  8878. 'preview_view.png',
  8879. get_lang('Preview')
  8880. );
  8881. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  8882. // Display hotpotatoes
  8883. while ($row_hot = Database::fetch_array($res_hot)) {
  8884. $link = Display::url(
  8885. $previewIcon,
  8886. $exerciseUrl.'&file='.$row_hot['path'],
  8887. ['target' => '_blank']
  8888. );
  8889. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  8890. $return .= '<a class="moved" href="#">';
  8891. $return .= Display::return_icon(
  8892. 'move_everywhere.png',
  8893. get_lang('Move'),
  8894. [],
  8895. ICON_SIZE_TINY
  8896. );
  8897. $return .= '</a> ';
  8898. $return .= Display::return_icon('hotpotatoes_s.png');
  8899. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  8900. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  8901. $return .= '</li>';
  8902. }
  8903. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  8904. while ($row_quiz = Database::fetch_array($res_quiz)) {
  8905. $title = strip_tags(
  8906. api_html_entity_decode($row_quiz['title'])
  8907. );
  8908. $link = Display::url(
  8909. $previewIcon,
  8910. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  8911. ['target' => '_blank']
  8912. );
  8913. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  8914. $return .= '<a class="moved" href="#">';
  8915. $return .= Display::return_icon(
  8916. 'move_everywhere.png',
  8917. get_lang('Move'),
  8918. [],
  8919. ICON_SIZE_TINY
  8920. );
  8921. $return .= '</a> ';
  8922. $return .= Display::return_icon(
  8923. 'quizz_small.gif',
  8924. '',
  8925. [],
  8926. ICON_SIZE_TINY
  8927. );
  8928. $sessionStar = api_get_session_image(
  8929. $row_quiz['session_id'],
  8930. $userInfo['status']
  8931. );
  8932. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id.'">'.
  8933. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  8934. '</a>';
  8935. $return .= '</li>';
  8936. }
  8937. $return .= '</ul>';
  8938. return $return;
  8939. }
  8940. /**
  8941. * Creates a list with all the links in it
  8942. * @return string
  8943. */
  8944. public function get_links()
  8945. {
  8946. $selfUrl = api_get_self();
  8947. $courseIdReq = api_get_cidreq();
  8948. $course = api_get_course_info();
  8949. $userInfo = api_get_user_info();
  8950. $course_id = $course['real_id'];
  8951. $tbl_link = Database::get_course_table(TABLE_LINK);
  8952. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  8953. $moveEverywhereIcon = Display::return_icon(
  8954. 'move_everywhere.png',
  8955. get_lang('Move'),
  8956. [],
  8957. ICON_SIZE_TINY
  8958. );
  8959. $session_id = api_get_session_id();
  8960. $condition_session = api_get_session_condition(
  8961. $session_id,
  8962. true,
  8963. true,
  8964. "link.session_id"
  8965. );
  8966. $sql = "SELECT
  8967. link.id as link_id,
  8968. link.title as link_title,
  8969. link.session_id as link_session_id,
  8970. link.category_id as category_id,
  8971. link_category.category_title as category_title
  8972. FROM $tbl_link as link
  8973. LEFT JOIN $linkCategoryTable as link_category
  8974. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  8975. WHERE link.c_id = ".$course_id." $condition_session
  8976. ORDER BY link_category.category_title ASC, link.title ASC";
  8977. $result = Database::query($sql);
  8978. $categorizedLinks = [];
  8979. $categories = [];
  8980. while ($link = Database::fetch_array($result)) {
  8981. if (!$link['category_id']) {
  8982. $link['category_title'] = get_lang('Uncategorized');
  8983. }
  8984. $categories[$link['category_id']] = $link['category_title'];
  8985. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  8986. }
  8987. $linksHtmlCode =
  8988. '<script>
  8989. function toggle_tool(tool, id) {
  8990. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  8991. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  8992. document.getElementById(tool+"_"+id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
  8993. } else {
  8994. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  8995. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  8996. }
  8997. }
  8998. </script>
  8999. <ul class="lp_resource">
  9000. <li class="lp_resource_element">
  9001. '.Display::return_icon('linksnew.gif').'
  9002. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9003. get_lang('LinkAdd').'
  9004. </a>
  9005. </li>';
  9006. foreach ($categorizedLinks as $categoryId => $links) {
  9007. $linkNodes = null;
  9008. foreach ($links as $key => $linkInfo) {
  9009. $title = $linkInfo['link_title'];
  9010. $linkSessionId = $linkInfo['link_session_id'];
  9011. $link = Display::url(
  9012. Display::return_icon('preview_view.png', get_lang('Preview')),
  9013. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9014. ['target' => '_blank']
  9015. );
  9016. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9017. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9018. $linkNodes .=
  9019. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9020. <a class="moved" href="#">'.
  9021. $moveEverywhereIcon.
  9022. '</a>
  9023. '.Display::return_icon('lp_link.png').'
  9024. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9025. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9026. Security::remove_XSS($title).$sessionStar.$link.
  9027. '</a>
  9028. </li>';
  9029. }
  9030. }
  9031. $linksHtmlCode .=
  9032. '<li>
  9033. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9034. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9035. align="absbottom" />
  9036. </a>
  9037. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9038. </li>
  9039. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9040. }
  9041. $linksHtmlCode .= '</ul>';
  9042. return $linksHtmlCode;
  9043. }
  9044. /**
  9045. * Creates a list with all the student publications in it
  9046. * @return string
  9047. */
  9048. public function get_student_publications()
  9049. {
  9050. $return = '<ul class="lp_resource">';
  9051. $return .= '<li class="lp_resource_element">';
  9052. $return .= Display::return_icon('works_new.gif');
  9053. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9054. get_lang('AddAssignmentPage').'</a>';
  9055. $return .= '</li>';
  9056. $sessionId = api_get_session_id();
  9057. if (empty($sessionId)) {
  9058. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9059. $works = getWorkListTeacher(0, 100, null, null, null);
  9060. if (!empty($works)) {
  9061. foreach ($works as $work) {
  9062. $link = Display::url(
  9063. Display::return_icon('preview_view.png', get_lang('Preview')),
  9064. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9065. ['target' => '_blank']
  9066. );
  9067. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9068. $return .= '<a class="moved" href="#">';
  9069. $return .= Display::return_icon(
  9070. 'move_everywhere.png',
  9071. get_lang('Move'),
  9072. [],
  9073. ICON_SIZE_TINY
  9074. );
  9075. $return .= '</a> ';
  9076. $return .= Display::return_icon('works.gif');
  9077. $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.'">'.
  9078. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9079. </a>';
  9080. $return .= '</li>';
  9081. }
  9082. }
  9083. }
  9084. $return .= '</ul>';
  9085. return $return;
  9086. }
  9087. /**
  9088. * Creates a list with all the forums in it
  9089. * @return string
  9090. */
  9091. public function get_forums()
  9092. {
  9093. require_once '../forum/forumfunction.inc.php';
  9094. require_once '../forum/forumconfig.inc.php';
  9095. $forumCategories = get_forum_categories();
  9096. $forumsInNoCategory = get_forums_in_category(0);
  9097. if (!empty($forumsInNoCategory)) {
  9098. $forumCategories = array_merge(
  9099. $forumCategories,
  9100. [
  9101. [
  9102. 'cat_id' => 0,
  9103. 'session_id' => 0,
  9104. 'visibility' => 1,
  9105. 'cat_comment' => null,
  9106. ],
  9107. ]
  9108. );
  9109. }
  9110. $forumList = get_forums();
  9111. $a_forums = [];
  9112. foreach ($forumCategories as $forumCategory) {
  9113. // The forums in this category.
  9114. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9115. if (!empty($forumsInCategory)) {
  9116. foreach ($forumList as $forum) {
  9117. if (isset($forum['forum_category']) &&
  9118. $forum['forum_category'] == $forumCategory['cat_id']
  9119. ) {
  9120. $a_forums[] = $forum;
  9121. }
  9122. }
  9123. }
  9124. }
  9125. $return = '<ul class="lp_resource">';
  9126. // First add link
  9127. $return .= '<li class="lp_resource_element">';
  9128. $return .= Display::return_icon('new_forum.png');
  9129. $return .= Display::url(
  9130. get_lang('CreateANewForum'),
  9131. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9132. 'action' => 'add',
  9133. 'content' => 'forum',
  9134. 'lp_id' => $this->lp_id
  9135. ]),
  9136. ['title' => get_lang('CreateANewForum')]
  9137. );
  9138. $return .= '</li>';
  9139. $return .= '<script>
  9140. function toggle_forum(forum_id) {
  9141. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9142. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9143. document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('remove.gif').'";
  9144. } else {
  9145. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9146. document.getElementById("forum_"+forum_id+"_opener").src = "' . Display::returnIconPath('add.gif').'";
  9147. }
  9148. }
  9149. </script>';
  9150. foreach ($a_forums as $forum) {
  9151. if (!empty($forum['forum_id'])) {
  9152. $link = Display::url(
  9153. Display::return_icon('preview_view.png', get_lang('Preview')),
  9154. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9155. ['target' => '_blank']
  9156. );
  9157. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9158. $return .= '<a class="moved" href="#">';
  9159. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9160. $return .= ' </a>';
  9161. $return .= Display::return_icon('lp_forum.png', '', [], ICON_SIZE_TINY);
  9162. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9163. <img src="' . Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9164. </a>
  9165. <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">'.
  9166. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9167. $return .= '</li>';
  9168. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9169. $a_threads = get_threads($forum['forum_id']);
  9170. if (is_array($a_threads)) {
  9171. foreach ($a_threads as $thread) {
  9172. $link = Display::url(
  9173. Display::return_icon('preview_view.png', get_lang('Preview')),
  9174. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9175. ['target' => '_blank']
  9176. );
  9177. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9178. $return .= '&nbsp;<a class="moved" href="#">';
  9179. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9180. $return .= ' </a>';
  9181. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9182. $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.'">'.
  9183. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9184. $return .= '</li>';
  9185. }
  9186. }
  9187. $return .= '</div>';
  9188. }
  9189. }
  9190. $return .= '</ul>';
  9191. return $return;
  9192. }
  9193. /**
  9194. * // TODO: The output encoding should be equal to the system encoding.
  9195. *
  9196. * Exports the learning path as a SCORM package. This is the main function that
  9197. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9198. * whole thing and returns the zip.
  9199. *
  9200. * This method needs to be called in PHP5, as it will fail with non-adequate
  9201. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9202. * you need to call it on a learnpath object.
  9203. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9204. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9205. * path has been modified, it should use the generic method here below.
  9206. * @param string Optional name of zip file. If none, title of learnpath is
  9207. * domesticated and trailed with ".zip"
  9208. * @return string Returns the zip package string, or null if error
  9209. */
  9210. public function scorm_export()
  9211. {
  9212. $_course = api_get_course_info();
  9213. $course_id = $_course['real_id'];
  9214. // Remove memory and time limits as much as possible as this might be a long process...
  9215. if (function_exists('ini_set')) {
  9216. api_set_memory_limit('256M');
  9217. ini_set('max_execution_time', 600);
  9218. }
  9219. // Create the zip handler (this will remain available throughout the method).
  9220. $archive_path = api_get_path(SYS_ARCHIVE_PATH);
  9221. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9222. $temp_dir_short = uniqid();
  9223. $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
  9224. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9225. $zip_folder = new PclZip($temp_zip_file);
  9226. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9227. $root_path = $main_path = api_get_path(SYS_PATH);
  9228. $files_cleanup = [];
  9229. // Place to temporarily stash the zip file.
  9230. // create the temp dir if it doesn't exist
  9231. // or do a cleanup before creating the zip file.
  9232. if (!is_dir($temp_zip_dir)) {
  9233. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9234. } else {
  9235. // Cleanup: Check the temp dir for old files and delete them.
  9236. $handle = opendir($temp_zip_dir);
  9237. while (false !== ($file = readdir($handle))) {
  9238. if ($file != '.' && $file != '..') {
  9239. unlink("$temp_zip_dir/$file");
  9240. }
  9241. }
  9242. closedir($handle);
  9243. }
  9244. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9245. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9246. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9247. ) {
  9248. // Remove the possible . at the end of the path.
  9249. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9250. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9251. mkdir(
  9252. $dest_path_to_scorm_folder,
  9253. api_get_permissions_for_new_directories(),
  9254. true
  9255. );
  9256. copyr(
  9257. $current_course_path.'/scorm/'.$this->path,
  9258. $dest_path_to_scorm_folder,
  9259. ['imsmanifest'],
  9260. $zip_files
  9261. );
  9262. }
  9263. // Build a dummy imsmanifest structure.
  9264. // Do not add to the zip yet (we still need it).
  9265. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9266. // Aggregation Model official document, section "2.3 Content Packaging".
  9267. // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
  9268. $xmldoc = new DOMDocument('1.0');
  9269. $root = $xmldoc->createElement('manifest');
  9270. $root->setAttribute('identifier', 'SingleCourseManifest');
  9271. $root->setAttribute('version', '1.1');
  9272. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9273. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9274. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9275. $root->setAttribute('xsi:schemaLocation', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd');
  9276. // Build mandatory sub-root container elements.
  9277. $metadata = $xmldoc->createElement('metadata');
  9278. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9279. $metadata->appendChild($md_schema);
  9280. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9281. $metadata->appendChild($md_schemaversion);
  9282. $root->appendChild($metadata);
  9283. $organizations = $xmldoc->createElement('organizations');
  9284. $resources = $xmldoc->createElement('resources');
  9285. // Build the only organization we will use in building our learnpaths.
  9286. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9287. $organization = $xmldoc->createElement('organization');
  9288. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9289. // To set the title of the SCORM entity (=organization), we take the name given
  9290. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9291. // learning path charset) as it is the encoding that defines how it is stored
  9292. // in the database. Then we convert it to HTML entities again as the "&" character
  9293. // alone is not authorized in XML (must be &amp;).
  9294. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9295. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9296. $organization->appendChild($org_title);
  9297. $folder_name = 'document';
  9298. // Removes the learning_path/scorm_folder path when exporting see #4841
  9299. $path_to_remove = null;
  9300. $result = $this->generate_lp_folder($_course);
  9301. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9302. $path_to_remove = 'document'.$result['dir'];
  9303. $path_to_replace = $folder_name.'/';
  9304. }
  9305. // Fixes chamilo scorm exports
  9306. if ($this->ref === 'chamilo_scorm_export') {
  9307. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9308. }
  9309. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9310. // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
  9311. $link_updates = [];
  9312. $links_to_create = [];
  9313. //foreach ($this->items as $index => $item) {
  9314. foreach ($this->ordered_items as $index => $itemId) {
  9315. $item = $this->items[$itemId];
  9316. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9317. // Get included documents from this item.
  9318. if ($item->type === 'sco') {
  9319. $inc_docs = $item->get_resources_from_source(
  9320. null,
  9321. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.'scorm/'.$this->path.'/'.$item->get_path()
  9322. );
  9323. } else {
  9324. $inc_docs = $item->get_resources_from_source();
  9325. }
  9326. // Give a child element <item> to the <organization> element.
  9327. $my_item_id = $item->get_id();
  9328. $my_item = $xmldoc->createElement('item');
  9329. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9330. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9331. $my_item->setAttribute('isvisible', 'true');
  9332. // Give a child element <title> to the <item> element.
  9333. $my_title = $xmldoc->createElement(
  9334. 'title',
  9335. htmlspecialchars(
  9336. api_utf8_encode($item->get_title()),
  9337. ENT_QUOTES,
  9338. 'UTF-8'
  9339. )
  9340. );
  9341. $my_item->appendChild($my_title);
  9342. // Give a child element <adlcp:prerequisites> to the <item> element.
  9343. $my_prereqs = $xmldoc->createElement(
  9344. 'adlcp:prerequisites',
  9345. $this->get_scorm_prereq_string($my_item_id)
  9346. );
  9347. $my_prereqs->setAttribute('type', 'aicc_script');
  9348. $my_item->appendChild($my_prereqs);
  9349. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9350. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9351. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9352. //$xmldoc->createElement('adlcp:timelimitaction','');
  9353. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9354. //$xmldoc->createElement('adlcp:datafromlms','');
  9355. // Give a child element <adlcp:masteryscore> to the <item> element.
  9356. $my_masteryscore = $xmldoc->createElement(
  9357. 'adlcp:masteryscore',
  9358. $item->get_mastery_score()
  9359. );
  9360. $my_item->appendChild($my_masteryscore);
  9361. // Attach this item to the organization element or hits parent if there is one.
  9362. if (!empty($item->parent) && $item->parent != 0) {
  9363. $children = $organization->childNodes;
  9364. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9365. if (is_object($possible_parent)) {
  9366. $possible_parent->appendChild($my_item);
  9367. } else {
  9368. if ($this->debug > 0) {
  9369. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9370. }
  9371. }
  9372. } else {
  9373. if ($this->debug > 0) {
  9374. error_log('No parent');
  9375. }
  9376. $organization->appendChild($my_item);
  9377. }
  9378. // Get the path of the file(s) from the course directory root.
  9379. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9380. if (!empty($path_to_remove)) {
  9381. //From docs
  9382. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9383. //From quiz
  9384. if ($this->ref === 'chamilo_scorm_export') {
  9385. $path_to_remove = 'scorm/'.$this->path.'/';
  9386. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9387. }
  9388. } else {
  9389. $my_xml_file_path = $my_file_path;
  9390. }
  9391. $my_sub_dir = dirname($my_file_path);
  9392. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9393. $my_xml_sub_dir = $my_sub_dir;
  9394. // Give a <resource> child to the <resources> element
  9395. $my_resource = $xmldoc->createElement('resource');
  9396. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9397. $my_resource->setAttribute('type', 'webcontent');
  9398. $my_resource->setAttribute('href', $my_xml_file_path);
  9399. // adlcp:scormtype can be either 'sco' or 'asset'.
  9400. if ($item->type === 'sco') {
  9401. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9402. } else {
  9403. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9404. }
  9405. // xml:base is the base directory to find the files declared in this resource.
  9406. $my_resource->setAttribute('xml:base', '');
  9407. // Give a <file> child to the <resource> element.
  9408. $my_file = $xmldoc->createElement('file');
  9409. $my_file->setAttribute('href', $my_xml_file_path);
  9410. $my_resource->appendChild($my_file);
  9411. // Dependency to other files - not yet supported.
  9412. $i = 1;
  9413. if ($inc_docs) {
  9414. foreach ($inc_docs as $doc_info) {
  9415. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9416. continue;
  9417. }
  9418. $my_dep = $xmldoc->createElement('resource');
  9419. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9420. $my_dep->setAttribute('identifier', $res_id);
  9421. $my_dep->setAttribute('type', 'webcontent');
  9422. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9423. $my_dep_file = $xmldoc->createElement('file');
  9424. // Check type of URL.
  9425. if ($doc_info[1] == 'remote') {
  9426. // Remote file. Save url as is.
  9427. $my_dep_file->setAttribute('href', $doc_info[0]);
  9428. $my_dep->setAttribute('xml:base', '');
  9429. } elseif ($doc_info[1] === 'local') {
  9430. switch ($doc_info[2]) {
  9431. case 'url': // Local URL - save path as url for now, don't zip file.
  9432. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9433. $current_dir = dirname($abs_path);
  9434. $current_dir = str_replace('\\', '/', $current_dir);
  9435. $file_path = realpath($abs_path);
  9436. $file_path = str_replace('\\', '/', $file_path);
  9437. $my_dep_file->setAttribute('href', $file_path);
  9438. $my_dep->setAttribute('xml:base', '');
  9439. if (strstr($file_path, $main_path) !== false) {
  9440. // The calculated real path is really inside Chamilo's root path.
  9441. // Reduce file path to what's under the DocumentRoot.
  9442. $file_path = substr($file_path, strlen($root_path) - 1);
  9443. //echo $file_path;echo '<br /><br />';
  9444. //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
  9445. $zip_files_abs[] = $file_path;
  9446. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9447. $my_dep_file->setAttribute('href', $file_path);
  9448. $my_dep->setAttribute('xml:base', '');
  9449. } elseif (empty($file_path)) {
  9450. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9451. if (strpos($document_root, -1) == '/') {
  9452. $document_root = substr(0, -1, $document_root);
  9453. }*/
  9454. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9455. $file_path = str_replace('//', '/', $file_path);
  9456. if (file_exists($file_path)) {
  9457. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9458. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9459. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9460. $my_dep_file->setAttribute('href', $file_path);
  9461. $my_dep->setAttribute('xml:base', '');
  9462. }
  9463. }
  9464. break;
  9465. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9466. $my_dep_file->setAttribute('href', $doc_info[0]);
  9467. $my_dep->setAttribute('xml:base', '');
  9468. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9469. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9470. $abs_img_path_without_subdir = $doc_info[0];
  9471. $relp = api_get_path(REL_PATH); // The url-append config param.
  9472. $pos = strpos($abs_img_path_without_subdir, $relp);
  9473. if ($pos === 0) {
  9474. $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir, strlen($relp));
  9475. }
  9476. //$file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
  9477. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9478. $file_path = str_replace('\\', '/', $file_path);
  9479. $file_path = str_replace('//', '/', $file_path);
  9480. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9481. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9482. // Check if the current document is in that path.
  9483. if (strstr($file_path, $cur_path) !== false) {
  9484. // The document is in that path, now get the relative path
  9485. // to the containing document.
  9486. $orig_file_path = dirname($cur_path.$my_file_path).'/';
  9487. $orig_file_path = str_replace('\\', '/', $orig_file_path);
  9488. $relative_path = '';
  9489. if (strstr($file_path, $cur_path) !== false) {
  9490. //$relative_path = substr($file_path, strlen($orig_file_path));
  9491. $relative_path = str_replace($cur_path, '', $file_path);
  9492. $file_path = substr($file_path, strlen($cur_path));
  9493. } else {
  9494. // This case is still a problem as it's difficult to calculate a relative path easily
  9495. // might still generate wrong links.
  9496. //$file_path = substr($file_path,strlen($cur_path));
  9497. // Calculate the directory path to the current file (without trailing slash).
  9498. $my_relative_path = dirname($file_path);
  9499. $my_relative_path = str_replace('\\', '/', $my_relative_path);
  9500. $my_relative_file = basename($file_path);
  9501. // Calculate the directory path to the containing file (without trailing slash).
  9502. $my_orig_file_path = substr($orig_file_path, 0, -1);
  9503. $dotdot = '';
  9504. $subdir = '';
  9505. while (strstr($my_relative_path, $my_orig_file_path) === false && (strlen($my_orig_file_path) > 1) && (strlen($my_relative_path) > 1)) {
  9506. $my_relative_path2 = dirname($my_relative_path);
  9507. $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
  9508. $my_orig_file_path = dirname($my_orig_file_path);
  9509. $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
  9510. $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'.$subdir;
  9511. $dotdot += '../';
  9512. $my_relative_path = $my_relative_path2;
  9513. }
  9514. $relative_path = $dotdot.$subdir.$my_relative_file;
  9515. }
  9516. // Put the current document in the zip (this array is the array
  9517. // that will manage documents already in the course folder - relative).
  9518. $zip_files[] = $file_path;
  9519. // Update the links to the current document in the containing document (make them relative).
  9520. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $relative_path];
  9521. $my_dep_file->setAttribute('href', $file_path);
  9522. $my_dep->setAttribute('xml:base', '');
  9523. } elseif (strstr($file_path, $main_path) !== false) {
  9524. // The calculated real path is really inside Chamilo's root path.
  9525. // Reduce file path to what's under the DocumentRoot.
  9526. $file_path = substr($file_path, strlen($root_path));
  9527. //echo $file_path;echo '<br /><br />';
  9528. //error_log('Reduced path: '.$file_path, 0);
  9529. $zip_files_abs[] = $file_path;
  9530. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9531. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9532. $my_dep->setAttribute('xml:base', '');
  9533. } elseif (empty($file_path)) {
  9534. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9535. if(strpos($document_root,-1) == '/') {
  9536. $document_root = substr(0, -1, $document_root);
  9537. }*/
  9538. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9539. $file_path = str_replace('//', '/', $file_path);
  9540. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9541. $current_dir = dirname($abs_path);
  9542. $current_dir = str_replace('\\', '/', $current_dir);
  9543. if (file_exists($file_path)) {
  9544. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9545. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9546. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9547. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9548. $my_dep->setAttribute('xml:base', '');
  9549. }
  9550. }
  9551. break;
  9552. case 'rel':
  9553. // Path relative to the current document.
  9554. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9555. if (substr($doc_info[0], 0, 2) == '..') {
  9556. // Relative path going up.
  9557. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9558. $current_dir = str_replace('\\', '/', $current_dir);
  9559. $file_path = realpath($current_dir.$doc_info[0]);
  9560. $file_path = str_replace('\\', '/', $file_path);
  9561. if (strstr($file_path, $main_path) !== false) {
  9562. // The calculated real path is really inside Chamilo's root path.
  9563. // Reduce file path to what's under the DocumentRoot.
  9564. $file_path = substr($file_path, strlen($root_path));
  9565. $zip_files_abs[] = $file_path;
  9566. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9567. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9568. $my_dep->setAttribute('xml:base', '');
  9569. }
  9570. } else {
  9571. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9572. $my_dep_file->setAttribute('href', $doc_info[0]);
  9573. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9574. }
  9575. break;
  9576. default:
  9577. $my_dep_file->setAttribute('href', $doc_info[0]);
  9578. $my_dep->setAttribute('xml:base', '');
  9579. break;
  9580. }
  9581. }
  9582. $my_dep->appendChild($my_dep_file);
  9583. $resources->appendChild($my_dep);
  9584. $dependency = $xmldoc->createElement('dependency');
  9585. $dependency->setAttribute('identifierref', $res_id);
  9586. $my_resource->appendChild($dependency);
  9587. $i++;
  9588. }
  9589. }
  9590. $resources->appendChild($my_resource);
  9591. $zip_files[] = $my_file_path;
  9592. } else {
  9593. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9594. switch ($item->type) {
  9595. case TOOL_LINK:
  9596. $my_item = $xmldoc->createElement('item');
  9597. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9598. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9599. $my_item->setAttribute('isvisible', 'true');
  9600. // Give a child element <title> to the <item> element.
  9601. $my_title = $xmldoc->createElement(
  9602. 'title',
  9603. htmlspecialchars(
  9604. api_utf8_encode($item->get_title()),
  9605. ENT_QUOTES,
  9606. 'UTF-8'
  9607. )
  9608. );
  9609. $my_item->appendChild($my_title);
  9610. // Give a child element <adlcp:prerequisites> to the <item> element.
  9611. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9612. $my_prereqs->setAttribute('type', 'aicc_script');
  9613. $my_item->appendChild($my_prereqs);
  9614. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9615. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9616. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9617. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9618. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9619. //$xmldoc->createElement('adlcp:datafromlms', '');
  9620. // Give a child element <adlcp:masteryscore> to the <item> element.
  9621. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9622. $my_item->appendChild($my_masteryscore);
  9623. // Attach this item to the organization element or its parent if there is one.
  9624. if (!empty($item->parent) && $item->parent != 0) {
  9625. $children = $organization->childNodes;
  9626. for ($i = 0; $i < $children->length; $i++) {
  9627. $item_temp = $children->item($i);
  9628. if ($item_temp -> nodeName == 'item') {
  9629. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9630. $item_temp -> appendChild($my_item);
  9631. }
  9632. }
  9633. }
  9634. } else {
  9635. $organization->appendChild($my_item);
  9636. }
  9637. $my_file_path = 'link_'.$item->get_id().'.html';
  9638. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9639. WHERE c_id = '.$course_id.' AND id='.$item->path;
  9640. $rs = Database::query($sql);
  9641. if ($link = Database::fetch_array($rs)) {
  9642. $url = $link['url'];
  9643. $title = stripslashes($link['title']);
  9644. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9645. $my_xml_file_path = $my_file_path;
  9646. $my_sub_dir = dirname($my_file_path);
  9647. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9648. $my_xml_sub_dir = $my_sub_dir;
  9649. // Give a <resource> child to the <resources> element.
  9650. $my_resource = $xmldoc->createElement('resource');
  9651. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9652. $my_resource->setAttribute('type', 'webcontent');
  9653. $my_resource->setAttribute('href', $my_xml_file_path);
  9654. // adlcp:scormtype can be either 'sco' or 'asset'.
  9655. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9656. // xml:base is the base directory to find the files declared in this resource.
  9657. $my_resource->setAttribute('xml:base', '');
  9658. // give a <file> child to the <resource> element.
  9659. $my_file = $xmldoc->createElement('file');
  9660. $my_file->setAttribute('href', $my_xml_file_path);
  9661. $my_resource->appendChild($my_file);
  9662. $resources->appendChild($my_resource);
  9663. }
  9664. break;
  9665. case TOOL_QUIZ:
  9666. $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
  9667. $exe = new Exercise();
  9668. $exe->read($exe_id);
  9669. $my_item = $xmldoc->createElement('item');
  9670. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9671. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9672. $my_item->setAttribute('isvisible', 'true');
  9673. // Give a child element <title> to the <item> element.
  9674. $my_title = $xmldoc->createElement(
  9675. 'title',
  9676. htmlspecialchars(
  9677. api_utf8_encode($item->get_title()),
  9678. ENT_QUOTES,
  9679. 'UTF-8'
  9680. )
  9681. );
  9682. $my_item->appendChild($my_title);
  9683. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  9684. //$my_item->appendChild($my_max_score);
  9685. // Give a child element <adlcp:prerequisites> to the <item> element.
  9686. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9687. $my_prereqs->setAttribute('type', 'aicc_script');
  9688. $my_item->appendChild($my_prereqs);
  9689. // Give a child element <adlcp:masteryscore> to the <item> element.
  9690. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9691. $my_item->appendChild($my_masteryscore);
  9692. // Attach this item to the organization element or hits parent if there is one.
  9693. if (!empty($item->parent) && $item->parent != 0) {
  9694. $children = $organization->childNodes;
  9695. /*for ($i = 0; $i < $children->length; $i++) {
  9696. $item_temp = $children->item($i);
  9697. if ($exe_id == 81) {
  9698. error_log($item_temp->nodeName );
  9699. error_log($item_temp->getAttribute('identifier'));
  9700. }
  9701. if ($item_temp->nodeName == 'item') {
  9702. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9703. $item_temp->appendChild($my_item);
  9704. }
  9705. }
  9706. }*/
  9707. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9708. if ($possible_parent) {
  9709. if ($possible_parent->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9710. $possible_parent->appendChild($my_item);
  9711. }
  9712. }
  9713. } else {
  9714. $organization->appendChild($my_item);
  9715. }
  9716. // Get the path of the file(s) from the course directory root
  9717. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9718. $my_file_path = 'quiz_'.$item->get_id().'.html';
  9719. // Write the contents of the exported exercise into a (big) html file
  9720. // to later pack it into the exported SCORM. The file will be removed afterwards.
  9721. $contents = ScormSection::export_exercise_to_scorm(
  9722. $exe,
  9723. true
  9724. );
  9725. $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
  9726. $res = file_put_contents($tmp_file_path, $contents);
  9727. if ($res === false) {
  9728. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  9729. }
  9730. $files_cleanup[] = $tmp_file_path;
  9731. $my_xml_file_path = $my_file_path;
  9732. $my_sub_dir = dirname($my_file_path);
  9733. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9734. $my_xml_sub_dir = $my_sub_dir;
  9735. // Give a <resource> child to the <resources> element.
  9736. $my_resource = $xmldoc->createElement('resource');
  9737. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9738. $my_resource->setAttribute('type', 'webcontent');
  9739. $my_resource->setAttribute('href', $my_xml_file_path);
  9740. // adlcp:scormtype can be either 'sco' or 'asset'.
  9741. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9742. // xml:base is the base directory to find the files declared in this resource.
  9743. $my_resource->setAttribute('xml:base', '');
  9744. // Give a <file> child to the <resource> element.
  9745. $my_file = $xmldoc->createElement('file');
  9746. $my_file->setAttribute('href', $my_xml_file_path);
  9747. $my_resource->appendChild($my_file);
  9748. // Get included docs.
  9749. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  9750. // Dependency to other files - not yet supported.
  9751. $i = 1;
  9752. foreach ($inc_docs as $doc_info) {
  9753. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9754. continue;
  9755. }
  9756. $my_dep = $xmldoc->createElement('resource');
  9757. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9758. $my_dep->setAttribute('identifier', $res_id);
  9759. $my_dep->setAttribute('type', 'webcontent');
  9760. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9761. $my_dep_file = $xmldoc->createElement('file');
  9762. // Check type of URL.
  9763. if ($doc_info[1] == 'remote') {
  9764. // Remote file. Save url as is.
  9765. $my_dep_file->setAttribute('href', $doc_info[0]);
  9766. $my_dep->setAttribute('xml:base', '');
  9767. } elseif ($doc_info[1] == 'local') {
  9768. switch ($doc_info[2]) {
  9769. case 'url': // Local URL - save path as url for now, don't zip file.
  9770. // Save file but as local file (retrieve from URL).
  9771. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9772. $current_dir = dirname($abs_path);
  9773. $current_dir = str_replace('\\', '/', $current_dir);
  9774. $file_path = realpath($abs_path);
  9775. $file_path = str_replace('\\', '/', $file_path);
  9776. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9777. $my_dep->setAttribute('xml:base', '');
  9778. if (strstr($file_path, $main_path) !== false) {
  9779. // The calculated real path is really inside the chamilo root path.
  9780. // Reduce file path to what's under the DocumentRoot.
  9781. $file_path = substr($file_path, strlen($root_path));
  9782. $zip_files_abs[] = $file_path;
  9783. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => 'document/'.$file_path];
  9784. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9785. $my_dep->setAttribute('xml:base', '');
  9786. } elseif (empty($file_path)) {
  9787. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
  9788. if (strpos($document_root,-1) == '/') {
  9789. $document_root = substr(0, -1, $document_root);
  9790. }*/
  9791. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9792. $file_path = str_replace('//', '/', $file_path);
  9793. if (file_exists($file_path)) {
  9794. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9795. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9796. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => 'document/'.$file_path];
  9797. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9798. $my_dep->setAttribute('xml:base', '');
  9799. }
  9800. }
  9801. break;
  9802. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9803. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9804. $current_dir = str_replace('\\', '/', $current_dir);
  9805. $file_path = realpath($doc_info[0]);
  9806. $file_path = str_replace('\\', '/', $file_path);
  9807. $my_dep_file->setAttribute('href', $file_path);
  9808. $my_dep->setAttribute('xml:base', '');
  9809. if (strstr($file_path, $main_path) !== false) {
  9810. // The calculated real path is really inside the chamilo root path.
  9811. // Reduce file path to what's under the DocumentRoot.
  9812. $file_path = substr($file_path, strlen($root_path));
  9813. //echo $file_path;echo '<br /><br />';
  9814. //error_log('Reduced path: '.$file_path, 0);
  9815. $zip_files_abs[] = $file_path;
  9816. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9817. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9818. $my_dep->setAttribute('xml:base', '');
  9819. } elseif (empty($file_path)) {
  9820. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9821. if (strpos($document_root,-1) == '/') {
  9822. $document_root = substr(0, -1, $document_root);
  9823. }*/
  9824. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9825. $file_path = str_replace('//', '/', $file_path);
  9826. if (file_exists($file_path)) {
  9827. $file_path = substr($file_path, strlen($current_dir)); // We get the relative path.
  9828. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9829. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9830. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9831. $my_dep->setAttribute('xml:base', '');
  9832. }
  9833. }
  9834. break;
  9835. case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
  9836. if (substr($doc_info[0], 0, 2) == '..') {
  9837. // Relative path going up.
  9838. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9839. $current_dir = str_replace('\\', '/', $current_dir);
  9840. $file_path = realpath($current_dir.$doc_info[0]);
  9841. $file_path = str_replace('\\', '/', $file_path);
  9842. //error_log($file_path.' <-> '.$main_path, 0);
  9843. if (strstr($file_path, $main_path) !== false) {
  9844. // The calculated real path is really inside Chamilo's root path.
  9845. // Reduce file path to what's under the DocumentRoot.
  9846. $file_path = substr($file_path, strlen($root_path));
  9847. $file_path_dest = $file_path;
  9848. // File path is courses/CHAMILO/document/....
  9849. $info_file_path = explode('/', $file_path);
  9850. if ($info_file_path[0] == 'courses') { // Add character "/" in file path.
  9851. $file_path_dest = 'document/'.$file_path;
  9852. }
  9853. //error_log('Reduced path: '.$file_path, 0);
  9854. $zip_files_abs[] = $file_path;
  9855. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path_dest];
  9856. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9857. $my_dep->setAttribute('xml:base', '');
  9858. }
  9859. } else {
  9860. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9861. $my_dep_file->setAttribute('href', $doc_info[0]);
  9862. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9863. }
  9864. break;
  9865. default:
  9866. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  9867. $my_dep->setAttribute('xml:base', '');
  9868. break;
  9869. }
  9870. }
  9871. $my_dep->appendChild($my_dep_file);
  9872. $resources->appendChild($my_dep);
  9873. $dependency = $xmldoc->createElement('dependency');
  9874. $dependency->setAttribute('identifierref', $res_id);
  9875. $my_resource->appendChild($dependency);
  9876. $i++;
  9877. }
  9878. $resources->appendChild($my_resource);
  9879. $zip_files[] = $my_file_path;
  9880. break;
  9881. default:
  9882. // Get the path of the file(s) from the course directory root
  9883. $my_file_path = 'non_exportable.html';
  9884. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  9885. $my_xml_file_path = $my_file_path;
  9886. $my_sub_dir = dirname($my_file_path);
  9887. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9888. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  9889. $my_xml_sub_dir = $my_sub_dir;
  9890. // Give a <resource> child to the <resources> element.
  9891. $my_resource = $xmldoc->createElement('resource');
  9892. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9893. $my_resource->setAttribute('type', 'webcontent');
  9894. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  9895. // adlcp:scormtype can be either 'sco' or 'asset'.
  9896. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9897. // xml:base is the base directory to find the files declared in this resource.
  9898. $my_resource->setAttribute('xml:base', '');
  9899. // Give a <file> child to the <resource> element.
  9900. $my_file = $xmldoc->createElement('file');
  9901. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  9902. $my_resource->appendChild($my_file);
  9903. $resources->appendChild($my_resource);
  9904. break;
  9905. }
  9906. }
  9907. }
  9908. $organizations->appendChild($organization);
  9909. $root->appendChild($organizations);
  9910. $root->appendChild($resources);
  9911. $xmldoc->appendChild($root);
  9912. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  9913. // TODO: Add a readme file here, with a short description and a link to the Reload player
  9914. // then add the file to the zip, then destroy the file (this is done automatically).
  9915. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  9916. foreach ($zip_files as $file_path) {
  9917. if (empty($file_path)) {
  9918. continue;
  9919. }
  9920. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  9921. $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
  9922. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  9923. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  9924. }
  9925. $this->create_path($dest_file);
  9926. @copy($filePath, $dest_file);
  9927. // Check if the file needs a link update.
  9928. if (in_array($file_path, array_keys($link_updates))) {
  9929. $string = file_get_contents($dest_file);
  9930. unlink($dest_file);
  9931. foreach ($link_updates[$file_path] as $old_new) {
  9932. // This is an ugly hack that allows .flv files to be found by the flv player that
  9933. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  9934. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  9935. // ../../.. to return from inc/lib/flv_player to the document/main path.
  9936. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  9937. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  9938. } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
  9939. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  9940. }
  9941. //Fix to avoid problems with default_course_document
  9942. if (strpos("main/default_course_document", $old_new['dest'] === false)) {
  9943. //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
  9944. $newDestination = $old_new['dest'];
  9945. } else {
  9946. $newDestination = str_replace('document/', '', $old_new['dest']);
  9947. }
  9948. $string = str_replace($old_new['orig'], $newDestination, $string);
  9949. // Add files inside the HTMLs
  9950. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  9951. $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
  9952. if (file_exists($sys_course_path.$new_path)) {
  9953. copy($sys_course_path.$new_path, $destinationFile);
  9954. }
  9955. }
  9956. file_put_contents($dest_file, $string);
  9957. }
  9958. if (file_exists($filePath) && $copyAll) {
  9959. $extension = $this->get_extension($filePath);
  9960. if (in_array($extension, ['html', 'html'])) {
  9961. $containerOrigin = dirname($filePath);
  9962. $containerDestination = dirname($dest_file);
  9963. $finder = new Finder();
  9964. $finder->files()->in($containerOrigin)
  9965. ->notName('*_DELETED_*')
  9966. ->exclude('share_folder')
  9967. ->exclude('chat_files')
  9968. ->exclude('certificates')
  9969. ;
  9970. if (is_dir($containerOrigin) &&
  9971. is_dir($containerDestination)
  9972. ) {
  9973. $fs = new Filesystem();
  9974. $fs->mirror(
  9975. $containerOrigin,
  9976. $containerDestination,
  9977. $finder
  9978. );
  9979. }
  9980. }
  9981. }
  9982. }
  9983. foreach ($zip_files_abs as $file_path) {
  9984. if (empty($file_path)) {
  9985. continue;
  9986. }
  9987. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  9988. continue;
  9989. }
  9990. $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
  9991. $this->create_path($dest_file);
  9992. copy($main_path.$file_path, $dest_file);
  9993. // Check if the file needs a link update.
  9994. if (in_array($file_path, array_keys($link_updates))) {
  9995. $string = file_get_contents($dest_file);
  9996. unlink($dest_file);
  9997. foreach ($link_updates[$file_path] as $old_new) {
  9998. // This is an ugly hack that allows .flv files to be found by the flv player that
  9999. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10000. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10001. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10002. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  10003. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10004. }
  10005. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10006. }
  10007. file_put_contents($dest_file, $string);
  10008. }
  10009. }
  10010. if (is_array($links_to_create)) {
  10011. foreach ($links_to_create as $file => $link) {
  10012. $file_content = '<!DOCTYPE html><head>
  10013. <meta charset="'.api_get_language_isocode().'" />
  10014. <title>'.$link['title'].'</title>
  10015. </head>
  10016. <body dir="'.api_get_text_direction().'">
  10017. <div style="text-align:center">
  10018. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10019. </body>
  10020. </html>';
  10021. file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
  10022. }
  10023. }
  10024. // Add non exportable message explanation.
  10025. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10026. $file_content = '<!DOCTYPE html><head>
  10027. <meta charset="'.api_get_language_isocode().'" />
  10028. <title>'.$lang_not_exportable.'</title>
  10029. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10030. </head>
  10031. <body dir="'.api_get_text_direction().'">';
  10032. $file_content .=
  10033. <<<EOD
  10034. <style>
  10035. .error-message {
  10036. font-family: arial, verdana, helvetica, sans-serif;
  10037. border-width: 1px;
  10038. border-style: solid;
  10039. left: 50%;
  10040. margin: 10px auto;
  10041. min-height: 30px;
  10042. padding: 5px;
  10043. right: 50%;
  10044. width: 500px;
  10045. background-color: #FFD1D1;
  10046. border-color: #FF0000;
  10047. color: #000;
  10048. }
  10049. </style>
  10050. <body>
  10051. <div class="error-message">
  10052. $lang_not_exportable
  10053. </div>
  10054. </body>
  10055. </html>
  10056. EOD;
  10057. if (!is_dir($archive_path.$temp_dir_short.'/document')) {
  10058. @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10059. }
  10060. file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10061. // Add the extra files that go along with a SCORM package.
  10062. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10063. $fs = new Filesystem();
  10064. $fs->mirror($main_code_path, $archive_path.$temp_dir_short);
  10065. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10066. $manifest = @$xmldoc->saveXML();
  10067. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10068. file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10069. $zip_folder->add(
  10070. $archive_path.'/'.$temp_dir_short,
  10071. PCLZIP_OPT_REMOVE_PATH,
  10072. $archive_path.'/'.$temp_dir_short.'/'
  10073. );
  10074. // Clean possible temporary files.
  10075. foreach ($files_cleanup as $file) {
  10076. $res = unlink($file);
  10077. if ($res === false) {
  10078. error_log(
  10079. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10080. 0
  10081. );
  10082. }
  10083. }
  10084. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10085. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10086. }
  10087. /**
  10088. * @param int $lp_id
  10089. * @return bool
  10090. */
  10091. public function scorm_export_to_pdf($lp_id)
  10092. {
  10093. $lp_id = intval($lp_id);
  10094. $files_to_export = [];
  10095. $course_data = api_get_course_info($this->cc);
  10096. if (!empty($course_data)) {
  10097. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10098. $list = self::get_flat_ordered_items_list($lp_id);
  10099. if (!empty($list)) {
  10100. foreach ($list as $item_id) {
  10101. $item = $this->items[$item_id];
  10102. switch ($item->type) {
  10103. case 'document':
  10104. //Getting documents from a LP with chamilo documents
  10105. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10106. // Try loading document from the base course.
  10107. if (empty($file_data) && !empty($sessionId)) {
  10108. $file_data = DocumentManager::get_document_data_by_id(
  10109. $item->path,
  10110. $this->cc,
  10111. false,
  10112. 0
  10113. );
  10114. }
  10115. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10116. if (file_exists($file_path)) {
  10117. $files_to_export[] = [
  10118. 'title' => $item->get_title(),
  10119. 'path' => $file_path
  10120. ];
  10121. }
  10122. break;
  10123. case 'asset': //commes from a scorm package generated by chamilo
  10124. case 'sco':
  10125. $file_path = $scorm_path.'/'.$item->path;
  10126. if (file_exists($file_path)) {
  10127. $files_to_export[] = [
  10128. 'title' => $item->get_title(),
  10129. 'path' => $file_path
  10130. ];
  10131. }
  10132. break;
  10133. case 'dir':
  10134. $files_to_export[] = [
  10135. 'title' => $item->get_title(),
  10136. 'path' => null
  10137. ];
  10138. break;
  10139. }
  10140. }
  10141. }
  10142. $pdf = new PDF();
  10143. $result = $pdf->html_to_pdf(
  10144. $files_to_export,
  10145. $this->name,
  10146. $this->cc,
  10147. true
  10148. );
  10149. return $result;
  10150. }
  10151. return false;
  10152. }
  10153. /**
  10154. * Temp function to be moved in main_api or the best place around for this.
  10155. * Creates a file path if it doesn't exist
  10156. * @param string $path
  10157. */
  10158. public function create_path($path)
  10159. {
  10160. $path_bits = explode('/', dirname($path));
  10161. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10162. $path_built = IS_WINDOWS_OS ? '' : '/';
  10163. foreach ($path_bits as $bit) {
  10164. if (!empty($bit)) {
  10165. $new_path = $path_built.$bit;
  10166. if (is_dir($new_path)) {
  10167. $path_built = $new_path.'/';
  10168. } else {
  10169. mkdir($new_path, api_get_permissions_for_new_directories());
  10170. $path_built = $new_path.'/';
  10171. }
  10172. }
  10173. }
  10174. }
  10175. /**
  10176. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10177. * @return boolean The results of the unlink function, or false if there was no image to start with
  10178. */
  10179. public function delete_lp_image()
  10180. {
  10181. $img = $this->get_preview_image();
  10182. if ($img != '') {
  10183. $del_file = $this->get_preview_image_path(null, 'sys');
  10184. if (isset($del_file) && file_exists($del_file)) {
  10185. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10186. if (file_exists($del_file_2)) {
  10187. unlink($del_file_2);
  10188. }
  10189. $this->set_preview_image('');
  10190. return @unlink($del_file);
  10191. }
  10192. }
  10193. return false;
  10194. }
  10195. /**
  10196. * Uploads an author image to the upload/learning_path/images directory
  10197. * @param array The image array, coming from the $_FILES superglobal
  10198. * @return boolean True on success, false on error
  10199. */
  10200. public function upload_image($image_array)
  10201. {
  10202. if (!empty($image_array['name'])) {
  10203. $upload_ok = process_uploaded_file($image_array);
  10204. $has_attachment = true;
  10205. }
  10206. if ($upload_ok && $has_attachment) {
  10207. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10208. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10209. $updir = $sys_course_path.$courseDir;
  10210. // Try to add an extension to the file if it hasn't one.
  10211. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10212. if (filter_extension($new_file_name)) {
  10213. $file_extension = explode('.', $image_array['name']);
  10214. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10215. $filename = uniqid('');
  10216. $new_file_name = $filename.'.'.$file_extension;
  10217. $new_path = $updir.'/'.$new_file_name;
  10218. // Resize the image.
  10219. $temp = new Image($image_array['tmp_name']);
  10220. $temp->resize(104);
  10221. $result = $temp->send_image($new_path);
  10222. // Storing the image filename.
  10223. if ($result) {
  10224. $this->set_preview_image($new_file_name);
  10225. //Resize to 64px to use on course homepage
  10226. $temp->resize(64);
  10227. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10228. return true;
  10229. }
  10230. }
  10231. }
  10232. return false;
  10233. }
  10234. /**
  10235. * @param int $lp_id
  10236. * @param string $status
  10237. */
  10238. public function set_autolaunch($lp_id, $status)
  10239. {
  10240. $course_id = api_get_course_int_id();
  10241. $lp_id = intval($lp_id);
  10242. $status = intval($status);
  10243. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10244. // Setting everything to autolaunch = 0
  10245. $attributes['autolaunch'] = 0;
  10246. $where = [
  10247. 'session_id = ? AND c_id = ? ' => [
  10248. api_get_session_id(),
  10249. $course_id
  10250. ]
  10251. ];
  10252. Database::update($lp_table, $attributes, $where);
  10253. if ($status == 1) {
  10254. //Setting my lp_id to autolaunch = 1
  10255. $attributes['autolaunch'] = 1;
  10256. $where = [
  10257. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10258. $lp_id,
  10259. api_get_session_id(),
  10260. $course_id
  10261. ]
  10262. ];
  10263. Database::update($lp_table, $attributes, $where);
  10264. }
  10265. }
  10266. /**
  10267. * Gets previous_item_id for the next element of the lp_item table
  10268. * @author Isaac flores paz
  10269. * @return integer Previous item ID
  10270. */
  10271. public function select_previous_item_id()
  10272. {
  10273. $course_id = api_get_course_int_id();
  10274. if ($this->debug > 0) {
  10275. error_log('New LP - In learnpath::select_previous_item_id()', 0);
  10276. }
  10277. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10278. // Get the max order of the items
  10279. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10280. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10281. $rs_max_order = Database::query($sql);
  10282. $row_max_order = Database::fetch_object($rs_max_order);
  10283. $max_order = $row_max_order->display_order;
  10284. // Get the previous item ID
  10285. $sql = "SELECT iid as previous FROM $table_lp_item
  10286. WHERE
  10287. c_id = $course_id AND
  10288. lp_id = ".$this->lp_id." AND
  10289. display_order = '$max_order' ";
  10290. $rs_max = Database::query($sql);
  10291. $row_max = Database::fetch_object($rs_max);
  10292. // Return the previous item ID
  10293. return $row_max->previous;
  10294. }
  10295. /**
  10296. * Copies an LP
  10297. */
  10298. public function copy()
  10299. {
  10300. // Course builder
  10301. $cb = new CourseBuilder();
  10302. //Setting tools that will be copied
  10303. $cb->set_tools_to_build(['learnpaths']);
  10304. //Setting elements that will be copied
  10305. $cb->set_tools_specific_id_list(
  10306. ['learnpaths' => [$this->lp_id]]
  10307. );
  10308. $course = $cb->build();
  10309. //Course restorer
  10310. $course_restorer = new CourseRestorer($course);
  10311. $course_restorer->set_add_text_in_items(true);
  10312. $course_restorer->set_tool_copy_settings(
  10313. ['learnpaths' => ['reset_dates' => true]]
  10314. );
  10315. $course_restorer->restore(
  10316. api_get_course_id(),
  10317. api_get_session_id(),
  10318. false,
  10319. false
  10320. );
  10321. }
  10322. /**
  10323. * Verify document size
  10324. * @param string $s
  10325. * @return bool
  10326. */
  10327. public static function verify_document_size($s)
  10328. {
  10329. $post_max = ini_get('post_max_size');
  10330. if (substr($post_max, -1, 1) == 'M') {
  10331. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10332. } elseif (substr($post_max, -1, 1) == 'G') {
  10333. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10334. }
  10335. $upl_max = ini_get('upload_max_filesize');
  10336. if (substr($upl_max, -1, 1) == 'M') {
  10337. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10338. } elseif (substr($upl_max, -1, 1) == 'G') {
  10339. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10340. }
  10341. $documents_total_space = DocumentManager::documents_total_space();
  10342. $course_max_space = DocumentManager::get_course_quota();
  10343. $total_size = filesize($s) + $documents_total_space;
  10344. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10345. return true;
  10346. } else {
  10347. return false;
  10348. }
  10349. }
  10350. /**
  10351. * Clear LP prerequisites
  10352. */
  10353. public function clear_prerequisites()
  10354. {
  10355. $course_id = $this->get_course_int_id();
  10356. if ($this->debug > 0) {
  10357. error_log('New LP - In learnpath::clear_prerequisites()', 0);
  10358. }
  10359. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10360. $lp_id = $this->get_id();
  10361. //Cleaning prerequisites
  10362. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10363. WHERE c_id = $course_id AND lp_id = $lp_id";
  10364. Database::query($sql);
  10365. //Cleaning mastery score for exercises
  10366. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10367. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10368. Database::query($sql);
  10369. }
  10370. public function set_previous_step_as_prerequisite_for_all_items()
  10371. {
  10372. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10373. $course_id = $this->get_course_int_id();
  10374. $lp_id = $this->get_id();
  10375. if (!empty($this->items)) {
  10376. $previous_item_id = null;
  10377. $previous_item_max = 0;
  10378. $previous_item_type = null;
  10379. $last_item_not_dir = null;
  10380. $last_item_not_dir_type = null;
  10381. $last_item_not_dir_max = null;
  10382. foreach ($this->ordered_items as $itemId) {
  10383. $item = $this->getItem($itemId);
  10384. // if there was a previous item... (otherwise jump to set it)
  10385. if (!empty($previous_item_id)) {
  10386. $current_item_id = $item->get_id(); //save current id
  10387. if ($item->get_type() != 'dir') {
  10388. // Current item is not a folder, so it qualifies to get a prerequisites
  10389. if ($last_item_not_dir_type == 'quiz') {
  10390. // if previous is quiz, mark its max score as default score to be achieved
  10391. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10392. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10393. Database::query($sql);
  10394. }
  10395. // now simply update the prerequisite to set it to the last non-chapter item
  10396. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10397. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10398. Database::query($sql);
  10399. // record item as 'non-chapter' reference
  10400. $last_item_not_dir = $item->get_id();
  10401. $last_item_not_dir_type = $item->get_type();
  10402. $last_item_not_dir_max = $item->get_max();
  10403. }
  10404. } else {
  10405. if ($item->get_type() != 'dir') {
  10406. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10407. $last_item_not_dir = $item->get_id();
  10408. $last_item_not_dir_type = $item->get_type();
  10409. $last_item_not_dir_max = $item->get_max();
  10410. }
  10411. }
  10412. // Saving the item as "previous item" for the next loop
  10413. $previous_item_id = $item->get_id();
  10414. $previous_item_max = $item->get_max();
  10415. $previous_item_type = $item->get_type();
  10416. }
  10417. }
  10418. }
  10419. /**
  10420. * @param array $params
  10421. */
  10422. public static function createCategory($params)
  10423. {
  10424. $em = Database::getManager();
  10425. $item = new CLpCategory();
  10426. $item->setName($params['name']);
  10427. $item->setCId($params['c_id']);
  10428. $em->persist($item);
  10429. $em->flush();
  10430. }
  10431. /**
  10432. * @param array $params
  10433. */
  10434. public static function updateCategory($params)
  10435. {
  10436. $em = Database::getManager();
  10437. /** @var CLpCategory $item */
  10438. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10439. if ($item) {
  10440. $item->setName($params['name']);
  10441. $em->merge($item);
  10442. $em->flush();
  10443. }
  10444. }
  10445. /**
  10446. * @param int $id
  10447. */
  10448. public static function moveUpCategory($id)
  10449. {
  10450. $id = (int) $id;
  10451. $em = Database::getManager();
  10452. /** @var CLpCategory $item */
  10453. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10454. if ($item) {
  10455. $position = $item->getPosition() - 1;
  10456. $item->setPosition($position);
  10457. $em->persist($item);
  10458. $em->flush();
  10459. }
  10460. }
  10461. /**
  10462. * @param int $id
  10463. */
  10464. public static function moveDownCategory($id)
  10465. {
  10466. $id = (int) $id;
  10467. $em = Database::getManager();
  10468. /** @var CLpCategory $item */
  10469. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10470. if ($item) {
  10471. $position = $item->getPosition() + 1;
  10472. $item->setPosition($position);
  10473. $em->persist($item);
  10474. $em->flush();
  10475. }
  10476. }
  10477. /**
  10478. * @param int $courseId
  10479. * @return int|mixed
  10480. */
  10481. public static function getCountCategories($courseId)
  10482. {
  10483. if (empty($course_id)) {
  10484. return 0;
  10485. }
  10486. $em = Database::getManager();
  10487. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10488. $query->setParameter('id', $courseId);
  10489. return $query->getSingleScalarResult();
  10490. }
  10491. /**
  10492. * @param int $courseId
  10493. *
  10494. * @return mixed
  10495. */
  10496. public static function getCategories($courseId)
  10497. {
  10498. $em = Database::getManager();
  10499. //Default behaviour
  10500. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10501. array('cId' => $course_id),
  10502. array('name' => 'ASC')
  10503. );*/
  10504. // Using doctrine extensions
  10505. /** @var SortableRepository $repo */
  10506. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10507. $items = $repo
  10508. ->getBySortableGroupsQuery(['cId' => $courseId])
  10509. ->getResult();
  10510. return $items;
  10511. }
  10512. /**
  10513. * @param int $id
  10514. *
  10515. * @return CLpCategory
  10516. */
  10517. public static function getCategory($id)
  10518. {
  10519. $id = (int) $id;
  10520. $em = Database::getManager();
  10521. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10522. return $item;
  10523. }
  10524. /**
  10525. * @param int $courseId
  10526. * @return array
  10527. */
  10528. public static function getCategoryByCourse($courseId)
  10529. {
  10530. $em = Database::getManager();
  10531. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10532. ['cId' => $courseId]
  10533. );
  10534. return $items;
  10535. }
  10536. /**
  10537. * @param int $id
  10538. *
  10539. * @return mixed
  10540. */
  10541. public static function deleteCategory($id)
  10542. {
  10543. $em = Database::getManager();
  10544. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10545. if ($item) {
  10546. $courseId = $item->getCId();
  10547. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10548. $query->setParameter('id', $courseId);
  10549. $query->setParameter('catId', $item->getId());
  10550. $lps = $query->getResult();
  10551. // Setting category = 0.
  10552. if ($lps) {
  10553. foreach ($lps as $lpItem) {
  10554. $lpItem->setCategoryId(0);
  10555. }
  10556. }
  10557. // Removing category.
  10558. $em->remove($item);
  10559. $em->flush();
  10560. $courseInfo = api_get_course_info_by_id($courseId);
  10561. $sessionId = api_get_session_id();
  10562. // Delete link tool
  10563. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10564. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10565. // Delete tools
  10566. $sql = "DELETE FROM $tbl_tool
  10567. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10568. Database::query($sql);
  10569. }
  10570. }
  10571. /**
  10572. * @param int $courseId
  10573. * @param bool $addSelectOption
  10574. *
  10575. * @return mixed
  10576. */
  10577. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10578. {
  10579. $items = self::getCategoryByCourse($courseId);
  10580. $cats = [];
  10581. if ($addSelectOption) {
  10582. $cats = [get_lang('SelectACategory')];
  10583. }
  10584. if (!empty($items)) {
  10585. foreach ($items as $cat) {
  10586. $cats[$cat->getId()] = $cat->getName();
  10587. }
  10588. }
  10589. return $cats;
  10590. }
  10591. /**
  10592. * Return the scorm item type object with spaces replaced with _
  10593. * The return result is use to build a css classname like scorm_type_$return
  10594. * @param $in_type
  10595. * @return mixed
  10596. */
  10597. private static function format_scorm_type_item($in_type)
  10598. {
  10599. return str_replace(' ', '_', $in_type);
  10600. }
  10601. /**
  10602. * @param string $courseCode
  10603. * @param int $lp_id
  10604. * @param int $user_id
  10605. *
  10606. * @return learnpath
  10607. */
  10608. public static function getLpFromSession($courseCode, $lp_id, $user_id)
  10609. {
  10610. $learnPath = null;
  10611. $lpObject = Session::read('lpobject');
  10612. if ($lpObject !== null) {
  10613. $learnPath = unserialize($lpObject);
  10614. }
  10615. if (!is_object($learnPath)) {
  10616. $learnPath = new learnpath($courseCode, $lp_id, $user_id);
  10617. }
  10618. return $learnPath;
  10619. }
  10620. /**
  10621. * @param int $itemId
  10622. * @return learnpathItem|false
  10623. */
  10624. public function getItem($itemId)
  10625. {
  10626. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  10627. return $this->items[$itemId];
  10628. }
  10629. return false;
  10630. }
  10631. /**
  10632. * @return int
  10633. */
  10634. public function getCategoryId()
  10635. {
  10636. return $this->categoryId;
  10637. }
  10638. /**
  10639. * @param int $categoryId
  10640. * @return bool
  10641. */
  10642. public function setCategoryId($categoryId)
  10643. {
  10644. $this->categoryId = intval($categoryId);
  10645. $courseId = api_get_course_int_id();
  10646. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10647. $lp_id = $this->get_id();
  10648. $sql = "UPDATE $lp_table SET category_id = ".$this->categoryId."
  10649. WHERE iid = $lp_id";
  10650. Database::query($sql);
  10651. return true;
  10652. }
  10653. /**
  10654. * Get whether this is a learning path with the possibility to subscribe
  10655. * users or not
  10656. * @return int
  10657. */
  10658. public function getSubscribeUsers()
  10659. {
  10660. return $this->subscribeUsers;
  10661. }
  10662. /**
  10663. * Set whether this is a learning path with the possibility to subscribe
  10664. * users or not
  10665. * @param int $value (0 = false, 1 = true)
  10666. * @return bool
  10667. */
  10668. public function setSubscribeUsers($value)
  10669. {
  10670. if ($this->debug > 0) {
  10671. error_log('New LP - In learnpath::set_subscribe_users()', 0);
  10672. }
  10673. $this->subscribeUsers = (int) $value;
  10674. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10675. $lp_id = $this->get_id();
  10676. $sql = "UPDATE $lp_table SET subscribe_users = ".$this->subscribeUsers."
  10677. WHERE iid = $lp_id";
  10678. Database::query($sql);
  10679. return true;
  10680. }
  10681. /**
  10682. * Calculate the count of stars for a user in this LP
  10683. * This calculation is based on the following rules:
  10684. * - the student gets one star when he gets to 50% of the learning path
  10685. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  10686. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  10687. * - the student gets the final star when the score for the *last* test is >= 80%
  10688. * @param int $sessionId Optional. The session ID
  10689. * @return int The count of stars
  10690. */
  10691. public function getCalculateStars($sessionId = 0)
  10692. {
  10693. $stars = 0;
  10694. $progress = self::getProgress(
  10695. $this->lp_id,
  10696. $this->user_id,
  10697. $this->course_int_id,
  10698. $sessionId
  10699. );
  10700. if ($progress >= 50) {
  10701. $stars++;
  10702. }
  10703. // Calculate stars chapters evaluation
  10704. $exercisesItems = $this->getExercisesItems();
  10705. if (!empty($exercisesItems)) {
  10706. $totalResult = 0;
  10707. foreach ($exercisesItems as $exerciseItem) {
  10708. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10709. $this->user_id,
  10710. $exerciseItem->path,
  10711. $this->course_int_id,
  10712. $sessionId,
  10713. $this->lp_id,
  10714. $exerciseItem->db_id
  10715. );
  10716. $exerciseResultInfo = end($exerciseResultInfo);
  10717. if (!$exerciseResultInfo) {
  10718. continue;
  10719. }
  10720. if (!empty($exerciseResultInfo['exe_weighting'])) {
  10721. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  10722. } else {
  10723. $exerciseResult = 0;
  10724. }
  10725. $totalResult += $exerciseResult;
  10726. }
  10727. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  10728. if ($totalExerciseAverage >= 50) {
  10729. $stars++;
  10730. }
  10731. if ($totalExerciseAverage >= 80) {
  10732. $stars++;
  10733. }
  10734. }
  10735. // Calculate star for final evaluation
  10736. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10737. if (!empty($finalEvaluationItem)) {
  10738. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10739. $this->user_id,
  10740. $finalEvaluationItem->path,
  10741. $this->course_int_id,
  10742. $sessionId,
  10743. $this->lp_id,
  10744. $finalEvaluationItem->db_id
  10745. );
  10746. $evaluationResultInfo = end($evaluationResultInfo);
  10747. if ($evaluationResultInfo) {
  10748. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  10749. if ($evaluationResult >= 80) {
  10750. $stars++;
  10751. }
  10752. }
  10753. }
  10754. return $stars;
  10755. }
  10756. /**
  10757. * Get the items of exercise type
  10758. * @return array The items. Otherwise return false
  10759. */
  10760. public function getExercisesItems()
  10761. {
  10762. $exercises = [];
  10763. foreach ($this->items as $item) {
  10764. if ($item->type != 'quiz') {
  10765. continue;
  10766. }
  10767. $exercises[] = $item;
  10768. }
  10769. array_pop($exercises);
  10770. return $exercises;
  10771. }
  10772. /**
  10773. * Get the item of exercise type (evaluation type)
  10774. * @return array The final evaluation. Otherwise return false
  10775. */
  10776. public function getFinalEvaluationItem()
  10777. {
  10778. $exercises = [];
  10779. foreach ($this->items as $item) {
  10780. if ($item->type != 'quiz') {
  10781. continue;
  10782. }
  10783. $exercises[] = $item;
  10784. }
  10785. return array_pop($exercises);
  10786. }
  10787. /**
  10788. * Calculate the total points achieved for the current user in this learning path
  10789. * @param int $sessionId Optional. The session Id
  10790. * @return int
  10791. */
  10792. public function getCalculateScore($sessionId = 0)
  10793. {
  10794. // Calculate stars chapters evaluation
  10795. $exercisesItems = $this->getExercisesItems();
  10796. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10797. $totalExercisesResult = 0;
  10798. $totalEvaluationResult = 0;
  10799. if ($exercisesItems !== false) {
  10800. foreach ($exercisesItems as $exerciseItem) {
  10801. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10802. $this->user_id,
  10803. $exerciseItem->path,
  10804. $this->course_int_id,
  10805. $sessionId,
  10806. $this->lp_id,
  10807. $exerciseItem->db_id
  10808. );
  10809. $exerciseResultInfo = end($exerciseResultInfo);
  10810. if (!$exerciseResultInfo) {
  10811. continue;
  10812. }
  10813. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  10814. }
  10815. }
  10816. if (!empty($finalEvaluationItem)) {
  10817. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10818. $this->user_id,
  10819. $finalEvaluationItem->path,
  10820. $this->course_int_id,
  10821. $sessionId,
  10822. $this->lp_id,
  10823. $finalEvaluationItem->db_id
  10824. );
  10825. $evaluationResultInfo = end($evaluationResultInfo);
  10826. if ($evaluationResultInfo) {
  10827. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  10828. }
  10829. }
  10830. return $totalExercisesResult + $totalEvaluationResult;
  10831. }
  10832. /**
  10833. * Check if URL is not allowed to be show in a iframe
  10834. * @param string $src
  10835. *
  10836. * @return string
  10837. */
  10838. public function fixBlockedLinks($src)
  10839. {
  10840. $urlInfo = parse_url($src);
  10841. $platformProtocol = 'https';
  10842. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  10843. $platformProtocol = 'http';
  10844. }
  10845. $protocolFixApplied = false;
  10846. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  10847. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  10848. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  10849. if ($platformProtocol != $scheme) {
  10850. Session::write('x_frame_source', $src);
  10851. $src = 'blank.php?error=x_frames_options';
  10852. $protocolFixApplied = true;
  10853. }
  10854. if ($protocolFixApplied == false) {
  10855. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  10856. // Check X-Frame-Options
  10857. $ch = curl_init();
  10858. $options = [
  10859. CURLOPT_URL => $src,
  10860. CURLOPT_RETURNTRANSFER => true,
  10861. CURLOPT_HEADER => true,
  10862. CURLOPT_FOLLOWLOCATION => true,
  10863. CURLOPT_ENCODING => "",
  10864. CURLOPT_AUTOREFERER => true,
  10865. CURLOPT_CONNECTTIMEOUT => 120,
  10866. CURLOPT_TIMEOUT => 120,
  10867. CURLOPT_MAXREDIRS => 10,
  10868. ];
  10869. curl_setopt_array($ch, $options);
  10870. $response = curl_exec($ch);
  10871. $httpCode = curl_getinfo($ch);
  10872. $headers = substr($response, 0, $httpCode['header_size']);
  10873. $error = false;
  10874. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  10875. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  10876. ) {
  10877. $error = true;
  10878. }
  10879. if ($error) {
  10880. Session::write('x_frame_source', $src);
  10881. $src = 'blank.php?error=x_frames_options';
  10882. }
  10883. }
  10884. }
  10885. return $src;
  10886. }
  10887. /**
  10888. * Check if this LP has a created forum in the basis course
  10889. * @return boolean
  10890. */
  10891. public function lpHasForum()
  10892. {
  10893. $forumTable = Database::get_course_table(TABLE_FORUM);
  10894. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10895. $fakeFrom = "
  10896. $forumTable f
  10897. INNER JOIN $itemProperty ip
  10898. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  10899. ";
  10900. $resultData = Database::select(
  10901. 'COUNT(f.iid) AS qty',
  10902. $fakeFrom,
  10903. [
  10904. 'where' => [
  10905. 'ip.visibility != ? AND ' => 2,
  10906. 'ip.tool = ? AND ' => TOOL_FORUM,
  10907. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10908. 'f.lp_id = ?' => intval($this->lp_id)
  10909. ]
  10910. ],
  10911. 'first'
  10912. );
  10913. return $resultData['qty'] > 0;
  10914. }
  10915. /**
  10916. * Get the forum for this learning path
  10917. * @param int $sessionId
  10918. * @return boolean
  10919. */
  10920. public function getForum($sessionId = 0)
  10921. {
  10922. $forumTable = Database::get_course_table(TABLE_FORUM);
  10923. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10924. $fakeFrom = "$forumTable f
  10925. INNER JOIN $itemProperty ip ";
  10926. if ($this->lp_session_id == 0) {
  10927. $fakeFrom .= "
  10928. ON (
  10929. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  10930. f.session_id = ip.session_id OR ip.session_id IS NULL
  10931. )
  10932. )
  10933. ";
  10934. } else {
  10935. $fakeFrom .= "
  10936. ON (
  10937. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  10938. )
  10939. ";
  10940. }
  10941. $resultData = Database::select(
  10942. 'f.*',
  10943. $fakeFrom,
  10944. [
  10945. 'where' => [
  10946. 'ip.visibility != ? AND ' => 2,
  10947. 'ip.tool = ? AND ' => TOOL_FORUM,
  10948. 'f.session_id = ? AND ' => $sessionId,
  10949. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10950. 'f.lp_id = ?' => intval($this->lp_id)
  10951. ]
  10952. ],
  10953. 'first'
  10954. );
  10955. if (empty($resultData)) {
  10956. return false;
  10957. }
  10958. return $resultData;
  10959. }
  10960. /**
  10961. * Create a forum for this learning path
  10962. * @param int $forumCategoryId
  10963. * @return int The forum ID if was created. Otherwise return false
  10964. */
  10965. public function createForum($forumCategoryId)
  10966. {
  10967. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  10968. $forumId = store_forum(
  10969. [
  10970. 'lp_id' => $this->lp_id,
  10971. 'forum_title' => $this->name,
  10972. 'forum_comment' => null,
  10973. 'forum_category' => intval($forumCategoryId),
  10974. 'students_can_edit_group' => ['students_can_edit' => 0],
  10975. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  10976. 'default_view_type_group' => ['default_view_type' => 'flat'],
  10977. 'group_forum' => 0,
  10978. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public']
  10979. ],
  10980. [],
  10981. true
  10982. );
  10983. return $forumId;
  10984. }
  10985. /**
  10986. * Check and obtain the lp final item if exist
  10987. *
  10988. * @return learnpathItem
  10989. */
  10990. private function getFinalItem()
  10991. {
  10992. if (empty($this->items)) {
  10993. return null;
  10994. }
  10995. foreach ($this->items as $item) {
  10996. if ($item->type !== 'final_item') {
  10997. continue;
  10998. }
  10999. return $item;
  11000. }
  11001. }
  11002. /**
  11003. * Get the LP Final Item Template
  11004. *
  11005. * @return string
  11006. */
  11007. private function getFinalItemTemplate()
  11008. {
  11009. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  11010. }
  11011. /**
  11012. * Get the LP Final Item Url
  11013. *
  11014. * @return string
  11015. */
  11016. private function getSavedFinalItem()
  11017. {
  11018. $finalItem = $this->getFinalItem();
  11019. $doc = DocumentManager::get_document_data_by_id(
  11020. $finalItem->path,
  11021. $this->cc
  11022. );
  11023. if ($doc && file_exists($doc['absolute_path'])) {
  11024. return file_get_contents($doc['absolute_path']);
  11025. }
  11026. return '';
  11027. }
  11028. /**
  11029. * Get the LP Final Item form
  11030. *
  11031. * @return string
  11032. */
  11033. public function getFinalItemForm()
  11034. {
  11035. $finalItem = $this->getFinalItem();
  11036. $title = '';
  11037. if ($finalItem) {
  11038. $title = $finalItem->get_title();
  11039. $buttonText = get_lang('Save');
  11040. $content = $this->getSavedFinalItem();
  11041. } else {
  11042. $buttonText = get_lang('LPCreateDocument');
  11043. $content = $this->getFinalItemTemplate();
  11044. }
  11045. $courseInfo = api_get_course_info();
  11046. $result = $this->generate_lp_folder($courseInfo);
  11047. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11048. $relative_prefix = '../../';
  11049. $editorConfig = [
  11050. 'ToolbarSet' => 'LearningPathDocuments',
  11051. 'Width' => '100%',
  11052. 'Height' => '500',
  11053. 'FullPage' => true,
  11054. 'CreateDocumentDir' => $relative_prefix,
  11055. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11056. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path
  11057. ];
  11058. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11059. 'type' => 'document',
  11060. 'lp_id' => $this->lp_id
  11061. ]);
  11062. $form = new FormValidator('final_item', 'POST', $url);
  11063. $form->addText('title', get_lang('Title'));
  11064. $form->addButtonSave($buttonText);
  11065. $form->addHtml(
  11066. Display::return_message(
  11067. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11068. 'normal',
  11069. false
  11070. )
  11071. );
  11072. $renderer = $form->defaultRenderer();
  11073. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11074. $form->addHtmlEditor(
  11075. 'content_lp_certificate',
  11076. null,
  11077. true,
  11078. false,
  11079. $editorConfig,
  11080. true
  11081. );
  11082. $form->addHidden('action', 'add_final_item');
  11083. $form->addHidden('path', Session::read('pathItem'));
  11084. $form->addHidden('previous', $this->get_last());
  11085. $form->setDefaults(
  11086. ['title' => $title, 'content_lp_certificate' => $content]
  11087. );
  11088. if ($form->validate()) {
  11089. $values = $form->exportValues();
  11090. $lastItemId = $this->get_last();
  11091. if (!$finalItem) {
  11092. $documentId = $this->create_document(
  11093. $this->course_info,
  11094. $values['content_lp_certificate'],
  11095. $values['title']
  11096. );
  11097. $this->add_item(
  11098. 0,
  11099. $lastItemId,
  11100. 'final_item',
  11101. $documentId,
  11102. $values['title'],
  11103. ''
  11104. );
  11105. Display::addFlash(
  11106. Display::return_message(get_lang('Added'))
  11107. );
  11108. } else {
  11109. $this->edit_document($this->course_info);
  11110. }
  11111. }
  11112. return $form->returnForm();
  11113. }
  11114. /**
  11115. * Check if the current lp item is first, both, last or none from lp list
  11116. *
  11117. * @param int $currentItemId
  11118. * @return string
  11119. */
  11120. public function isFirstOrLastItem($currentItemId)
  11121. {
  11122. if ($this->debug > 0) {
  11123. error_log('New LP - In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11124. }
  11125. $lpItemId = [];
  11126. $typeListNotToVerify = self::getChapterTypes();
  11127. // Using get_toc() function instead $this->items because returns the correct order of the items
  11128. foreach ($this->get_toc() as $item) {
  11129. if (!in_array($item['type'], $typeListNotToVerify)) {
  11130. $lpItemId[] = $item['id'];
  11131. }
  11132. }
  11133. $lastLpItemIndex = count($lpItemId) - 1;
  11134. $position = array_search($currentItemId, $lpItemId);
  11135. switch ($position) {
  11136. case 0:
  11137. if (!$lastLpItemIndex) {
  11138. $answer = 'both';
  11139. break;
  11140. }
  11141. $answer = 'first';
  11142. break;
  11143. case $lastLpItemIndex:
  11144. $answer = 'last';
  11145. break;
  11146. default:
  11147. $answer = 'none';
  11148. }
  11149. return $answer;
  11150. }
  11151. /**
  11152. * Get whether this is a learning path with the accumulated SCORM time or not
  11153. * @return int
  11154. */
  11155. public function getAccumulateScormTime()
  11156. {
  11157. return $this->accumulateScormTime;
  11158. }
  11159. /**
  11160. * Set whether this is a learning path with the accumulated SCORM time or not
  11161. * @param int $value (0 = false, 1 = true)
  11162. * @return bool Always returns true
  11163. */
  11164. public function setAccumulateScormTime($value)
  11165. {
  11166. if ($this->debug > 0) {
  11167. error_log('New LP - In learnpath::setAccumulateScormTime()', 0);
  11168. }
  11169. $this->accumulateScormTime = intval($value);
  11170. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11171. $lp_id = $this->get_id();
  11172. $sql = "UPDATE $lp_table
  11173. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11174. WHERE iid = $lp_id";
  11175. Database::query($sql);
  11176. return true;
  11177. }
  11178. /**
  11179. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11180. * the new learning path tool.
  11181. *
  11182. * The function is a big switch on tool type.
  11183. * In each case, we query the corresponding table for information and build the link
  11184. * with that information.
  11185. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11186. * previous work (display_addedresource_link_in_learnpath())
  11187. * @param int $course_id Course code
  11188. * @param int $learningPathId The learning path ID (in lp table)
  11189. * @param int $id_in_path the unique index in the items table
  11190. * @param int $lpViewId
  11191. * @param string $origin
  11192. * @return string
  11193. */
  11194. public static function rl_get_resource_link_for_learnpath(
  11195. $course_id,
  11196. $learningPathId,
  11197. $id_in_path,
  11198. $lpViewId,
  11199. $origin = 'learnpath'
  11200. ) {
  11201. $session_id = api_get_session_id();
  11202. $course_info = api_get_course_info_by_id($course_id);
  11203. $learningPathId = intval($learningPathId);
  11204. $id_in_path = intval($id_in_path);
  11205. $lpViewId = intval($lpViewId);
  11206. $em = Database::getManager();
  11207. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11208. /** @var CLpItem $rowItem */
  11209. $rowItem = $lpItemRepo->findOneBy([
  11210. 'cId' => $course_id,
  11211. 'lpId' => $learningPathId,
  11212. 'id' => $id_in_path
  11213. ]);
  11214. if (!$rowItem) {
  11215. return -1;
  11216. }
  11217. $course_code = $course_info['code'];
  11218. $type = $rowItem->getItemType();
  11219. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11220. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11221. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11222. $link = '';
  11223. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11224. switch ($type) {
  11225. case 'dir':
  11226. return $main_dir_path.'lp/blank.php';
  11227. case TOOL_CALENDAR_EVENT:
  11228. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11229. case TOOL_ANNOUNCEMENT:
  11230. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11231. case TOOL_LINK:
  11232. $linkInfo = Link::getLinkInfo($id);
  11233. if (isset($linkInfo['url'])) {
  11234. return $linkInfo['url'];
  11235. }
  11236. return '';
  11237. case TOOL_QUIZ:
  11238. if (empty($id)) {
  11239. return '';
  11240. }
  11241. // Get the lp_item_view with the highest view_count.
  11242. $learnpathItemViewResult = $em
  11243. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11244. ->findBy(
  11245. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11246. ['viewCount' => 'DESC'],
  11247. 1
  11248. );
  11249. /** @var CLpItemView $learnpathItemViewData */
  11250. $learnpathItemViewData = current($learnpathItemViewResult);
  11251. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11252. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11253. .http_build_query([
  11254. 'lp_init' => 1,
  11255. 'learnpath_item_view_id' => $learnpathItemViewId,
  11256. 'learnpath_id' => $learningPathId,
  11257. 'learnpath_item_id' => $id_in_path,
  11258. 'exerciseId' => $id
  11259. ]);
  11260. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11261. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11262. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11263. $myrow = Database::fetch_array($result);
  11264. $path = $myrow['path'];
  11265. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11266. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11267. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11268. case TOOL_FORUM:
  11269. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11270. case TOOL_THREAD: //forum post
  11271. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11272. if (empty($id)) {
  11273. return '';
  11274. }
  11275. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11276. $result = Database::query($sql);
  11277. $myrow = Database::fetch_array($result);
  11278. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11279. .$extraParams;
  11280. case TOOL_POST:
  11281. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11282. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11283. $myrow = Database::fetch_array($result);
  11284. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11285. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11286. case TOOL_DOCUMENT:
  11287. $document = $em
  11288. ->getRepository('ChamiloCourseBundle:CDocument')
  11289. ->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11290. if (!$document) {
  11291. return '';
  11292. }
  11293. $documentPathInfo = pathinfo($document->getPath());
  11294. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  11295. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11296. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  11297. $openmethod = 2;
  11298. $officedoc = false;
  11299. Session::write('openmethod', $openmethod);
  11300. Session::write('officedoc', $officedoc);
  11301. if ($showDirectUrl) {
  11302. return $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11303. }
  11304. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11305. case TOOL_LP_FINAL_ITEM:
  11306. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11307. .$extraParams;
  11308. case 'assignments':
  11309. return $main_dir_path.'work/work.php?'.$extraParams;
  11310. case TOOL_DROPBOX:
  11311. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11312. case 'introduction_text': //DEPRECATED
  11313. return '';
  11314. case TOOL_COURSE_DESCRIPTION:
  11315. return $main_dir_path.'course_description?'.$extraParams;
  11316. case TOOL_GROUP:
  11317. return $main_dir_path.'group/group.php?'.$extraParams;
  11318. case TOOL_USER:
  11319. return $main_dir_path.'user/user.php?'.$extraParams;
  11320. case TOOL_STUDENTPUBLICATION:
  11321. if (!empty($rowItem->getPath())) {
  11322. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11323. }
  11324. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11325. } //end switch
  11326. return $link;
  11327. }
  11328. /**
  11329. * Gets the name of a resource (generally used in learnpath when no name is provided)
  11330. *
  11331. * @author Yannick Warnier <ywarnier@beeznest.org>
  11332. * @param string Course code
  11333. * @param string The tool type (using constants declared in main_api.lib.php)
  11334. * @param integer The resource ID
  11335. * @return string
  11336. */
  11337. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11338. {
  11339. $_course = api_get_course_info($course_code);
  11340. $course_id = $_course['real_id'];
  11341. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11342. $learningPathId = intval($learningPathId);
  11343. $id_in_path = intval($id_in_path);
  11344. $sql_item = "SELECT item_type, title, ref FROM $tbl_lp_item
  11345. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11346. $res_item = Database::query($sql_item);
  11347. if (Database::num_rows($res_item) < 1) {
  11348. return '';
  11349. }
  11350. $row_item = Database::fetch_array($res_item);
  11351. $type = strtolower($row_item['item_type']);
  11352. $id = $row_item['ref'];
  11353. $output = '';
  11354. switch ($type) {
  11355. case TOOL_CALENDAR_EVENT:
  11356. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11357. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11358. $myrow = Database::fetch_array($result);
  11359. $output = $myrow['title'];
  11360. break;
  11361. case TOOL_ANNOUNCEMENT:
  11362. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11363. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11364. $myrow = Database::fetch_array($result);
  11365. $output = $myrow['title'];
  11366. break;
  11367. case TOOL_LINK:
  11368. // Doesn't take $target into account.
  11369. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11370. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11371. $myrow = Database::fetch_array($result);
  11372. $output = $myrow['title'];
  11373. break;
  11374. case TOOL_QUIZ:
  11375. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11376. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
  11377. $myrow = Database::fetch_array($result);
  11378. $output = $myrow['title'];
  11379. break;
  11380. case TOOL_FORUM:
  11381. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11382. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
  11383. $myrow = Database::fetch_array($result);
  11384. $output = $myrow['forum_name'];
  11385. break;
  11386. case TOOL_THREAD: //=topics
  11387. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11388. // Grabbing the title of the post.
  11389. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11390. $result_title = Database::query($sql_title);
  11391. $myrow_title = Database::fetch_array($result_title);
  11392. $output = $myrow_title['post_title'];
  11393. break;
  11394. case TOOL_POST:
  11395. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11396. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  11397. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11398. $result = Database::query($sql);
  11399. $post = Database::fetch_array($result);
  11400. $output = $post['post_title'];
  11401. break;
  11402. case 'dir':
  11403. $title = $row_item['title'];
  11404. if (!empty($title)) {
  11405. $output = $title;
  11406. } else {
  11407. $output = '-';
  11408. }
  11409. break;
  11410. case TOOL_DOCUMENT:
  11411. $title = $row_item['title'];
  11412. if (!empty($title)) {
  11413. $output = $title;
  11414. } else {
  11415. $output = '-';
  11416. }
  11417. break;
  11418. case 'hotpotatoes':
  11419. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11420. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11421. $myrow = Database::fetch_array($result);
  11422. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11423. $last = count($pathname) - 1; // Making a correct name for the link.
  11424. $filename = $pathname[$last]; // Making a correct name for the link.
  11425. $ext = explode('.', $filename);
  11426. $ext = strtolower($ext[sizeof($ext) - 1]);
  11427. $myrow['path'] = rawurlencode($myrow['path']);
  11428. $output = $filename;
  11429. break;
  11430. }
  11431. return stripslashes($output);
  11432. }
  11433. /**
  11434. * Get the parent names for the current item
  11435. * @param int $newItemId Optional. The item ID
  11436. * @return array
  11437. */
  11438. public function getCurrentItemParentNames($newItemId = 0)
  11439. {
  11440. $newItemId = $newItemId ?: $this->get_current_item_id();
  11441. $return = [];
  11442. $item = $this->getItem($newItemId);
  11443. $parent = $this->getItem($item->get_parent());
  11444. while ($parent) {
  11445. $return[] = $parent->get_title();
  11446. $parent = $this->getItem($parent->get_parent());
  11447. }
  11448. return array_reverse($return);
  11449. }
  11450. /**
  11451. * Reads and process "lp_subscription_settings" setting
  11452. * @return array
  11453. */
  11454. public static function getSubscriptionSettings()
  11455. {
  11456. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11457. if (empty($subscriptionSettings)) {
  11458. // By default allow both settings
  11459. $subscriptionSettings = [
  11460. 'allow_add_users_to_lp' => true,
  11461. 'allow_add_users_to_lp_category' => true,
  11462. ];
  11463. } else {
  11464. $subscriptionSettings = $subscriptionSettings['options'];
  11465. }
  11466. return $subscriptionSettings;
  11467. }
  11468. }