learnpath.class.php 513 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. $lp_item_id_list = [];
  241. while ($row = Database::fetch_array($res)) {
  242. $lp_item_id_list[] = $row['iid'];
  243. switch ($this->type) {
  244. case 3: //aicc
  245. $oItem = new aiccItem('db', $row['iid'], $course_id);
  246. if (is_object($oItem)) {
  247. $my_item_id = $oItem->get_id();
  248. $oItem->set_lp_view($this->lp_view_id, $course_id);
  249. $oItem->set_prevent_reinit($this->prevent_reinit);
  250. // Don't use reference here as the next loop will make the pointed object change.
  251. $this->items[$my_item_id] = $oItem;
  252. $this->refs_list[$oItem->ref] = $my_item_id;
  253. if ($debug) {
  254. error_log(
  255. 'learnpath::__construct() - '.
  256. 'aicc object with id '.$my_item_id.
  257. ' set in items[]',
  258. 0
  259. );
  260. }
  261. }
  262. break;
  263. case 2:
  264. $oItem = new scormItem('db', $row['iid'], $course_id);
  265. if (is_object($oItem)) {
  266. $my_item_id = $oItem->get_id();
  267. $oItem->set_lp_view($this->lp_view_id, $course_id);
  268. $oItem->set_prevent_reinit($this->prevent_reinit);
  269. // Don't use reference here as the next loop will make the pointed object change.
  270. $this->items[$my_item_id] = $oItem;
  271. $this->refs_list[$oItem->ref] = $my_item_id;
  272. if ($debug) {
  273. error_log('object with id '.$my_item_id.' set in items[]');
  274. }
  275. }
  276. break;
  277. case 1:
  278. default:
  279. if ($debug) {
  280. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  281. }
  282. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  285. }
  286. if (is_object($oItem)) {
  287. $my_item_id = $oItem->get_id();
  288. // Moved down to when we are sure the item_view exists.
  289. //$oItem->set_lp_view($this->lp_view_id);
  290. $oItem->set_prevent_reinit($this->prevent_reinit);
  291. // Don't use reference here as the next loop will make the pointed object change.
  292. $this->items[$my_item_id] = $oItem;
  293. $this->refs_list[$my_item_id] = $my_item_id;
  294. if ($debug) {
  295. error_log(
  296. 'learnpath::__construct() '.__LINE__.
  297. ' - object with id '.$my_item_id.' set in items[]'
  298. );
  299. }
  300. }
  301. break;
  302. }
  303. // Setting the object level with variable $this->items[$i][parent]
  304. foreach ($this->items as $itemLPObject) {
  305. $level = self::get_level_for_item(
  306. $this->items,
  307. $itemLPObject->db_id
  308. );
  309. $itemLPObject->level = $level;
  310. }
  311. // Setting the view in the item object.
  312. if (is_object($this->items[$row['iid']])) {
  313. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  314. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  315. $this->items[$row['iid']]->current_start_time = 0;
  316. $this->items[$row['iid']]->current_stop_time = 0;
  317. }
  318. }
  319. }
  320. if (!empty($lp_item_id_list)) {
  321. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  322. if (!empty($lp_item_id_list_to_string)) {
  323. // Get last viewing vars.
  324. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  325. // This query should only return one or zero result.
  326. $sql = "SELECT lp_item_id, status
  327. FROM $itemViewTable
  328. WHERE
  329. c_id = $course_id AND
  330. lp_view_id = ".$this->get_view_id()." AND
  331. lp_item_id IN ('".$lp_item_id_list_to_string."')
  332. ORDER BY view_count DESC ";
  333. $status_list = [];
  334. $res = Database::query($sql);
  335. while ($row = Database:: fetch_array($res)) {
  336. $status_list[$row['lp_item_id']] = $row['status'];
  337. }
  338. foreach ($lp_item_id_list as $item_id) {
  339. if (isset($status_list[$item_id])) {
  340. $status = $status_list[$item_id];
  341. if (is_object($this->items[$item_id])) {
  342. $this->items[$item_id]->set_status($status);
  343. if (empty($status)) {
  344. $this->items[$item_id]->set_status(
  345. $this->default_status
  346. );
  347. }
  348. }
  349. } else {
  350. if (!api_is_invitee()) {
  351. if (is_object($this->items[$item_id])) {
  352. $this->items[$item_id]->set_status(
  353. $this->default_status
  354. );
  355. }
  356. if (!empty($this->lp_view_id)) {
  357. // Add that row to the lp_item_view table so that
  358. // we have something to show in the stats page.
  359. $params = [
  360. 'c_id' => $course_id,
  361. 'lp_item_id' => $item_id,
  362. 'lp_view_id' => $this->lp_view_id,
  363. 'view_count' => 1,
  364. 'status' => 'not attempted',
  365. 'start_time' => time(),
  366. 'total_time' => 0,
  367. 'score' => 0,
  368. ];
  369. $insertId = Database::insert($itemViewTable, $params);
  370. if ($insertId) {
  371. $sql = "UPDATE $itemViewTable SET id = iid
  372. WHERE iid = $insertId";
  373. Database::query($sql);
  374. }
  375. $this->items[$item_id]->set_lp_view(
  376. $this->lp_view_id,
  377. $course_id
  378. );
  379. }
  380. }
  381. }
  382. }
  383. }
  384. }
  385. $this->ordered_items = self::get_flat_ordered_items_list(
  386. $this->get_id(),
  387. 0,
  388. $course_id
  389. );
  390. $this->max_ordered_items = 0;
  391. foreach ($this->ordered_items as $index => $dummy) {
  392. if ($index > $this->max_ordered_items && !empty($dummy)) {
  393. $this->max_ordered_items = $index;
  394. }
  395. }
  396. // TODO: Define the current item better.
  397. $this->first();
  398. if ($debug) {
  399. error_log('lp_view_session_id '.$this->lp_view_session_id);
  400. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  401. }
  402. } else {
  403. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  404. }
  405. }
  406. }
  407. /**
  408. * @return string
  409. */
  410. public function getCourseCode()
  411. {
  412. return $this->cc;
  413. }
  414. /**
  415. * @return int
  416. */
  417. public function get_course_int_id()
  418. {
  419. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  420. }
  421. /**
  422. * @param $course_id
  423. *
  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. * Function rewritten based on old_add_item() from Yannick Warnier.
  432. * Due the fact that users can decide where the item should come, I had to overlook this function and
  433. * I found it better to rewrite it. Old function is still available.
  434. * Added also the possibility to add a description.
  435. *
  436. * @param int $parent
  437. * @param int $previous
  438. * @param string $type
  439. * @param int $id resource ID (ref)
  440. * @param string $title
  441. * @param string $description
  442. * @param int $prerequisites
  443. * @param int $max_time_allowed
  444. * @param int $userId
  445. *
  446. * @return int
  447. */
  448. public function add_item(
  449. $parent,
  450. $previous,
  451. $type = 'dir',
  452. $id,
  453. $title,
  454. $description,
  455. $prerequisites = 0,
  456. $max_time_allowed = 0,
  457. $userId = 0
  458. ) {
  459. $course_id = $this->course_info['real_id'];
  460. if (empty($course_id)) {
  461. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  462. $this->course_info = api_get_course_info($this->cc);
  463. $course_id = $this->course_info['real_id'];
  464. }
  465. $userId = empty($userId) ? api_get_user_id() : $userId;
  466. $sessionId = api_get_session_id();
  467. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  468. $_course = $this->course_info;
  469. $parent = (int) $parent;
  470. $previous = (int) $previous;
  471. $id = (int) $id;
  472. $max_time_allowed = htmlentities($max_time_allowed);
  473. if (empty($max_time_allowed)) {
  474. $max_time_allowed = 0;
  475. }
  476. $sql = "SELECT COUNT(iid) AS num
  477. FROM $tbl_lp_item
  478. WHERE
  479. c_id = $course_id AND
  480. lp_id = ".$this->get_id()." AND
  481. parent_item_id = $parent ";
  482. $res_count = Database::query($sql);
  483. $row = Database::fetch_array($res_count);
  484. $num = $row['num'];
  485. $tmp_previous = 0;
  486. $display_order = 0;
  487. $next = 0;
  488. if ($num > 0) {
  489. if (empty($previous)) {
  490. $sql = "SELECT iid, next_item_id, display_order
  491. FROM $tbl_lp_item
  492. WHERE
  493. c_id = $course_id AND
  494. lp_id = ".$this->get_id()." AND
  495. parent_item_id = $parent AND
  496. previous_item_id = 0 OR
  497. previous_item_id = $parent";
  498. $result = Database::query($sql);
  499. $row = Database::fetch_array($result);
  500. if ($row) {
  501. $next = $row['iid'];
  502. }
  503. } else {
  504. $previous = (int) $previous;
  505. $sql = "SELECT iid, previous_item_id, 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. id = $previous";
  511. $result = Database::query($sql);
  512. $row = Database::fetch_array($result);
  513. if ($row) {
  514. $tmp_previous = $row['iid'];
  515. $next = $row['next_item_id'];
  516. $display_order = $row['display_order'];
  517. }
  518. }
  519. }
  520. $id = (int) $id;
  521. $typeCleaned = Database::escape_string($type);
  522. $max_score = 100;
  523. if ($type === 'quiz') {
  524. $sql = 'SELECT SUM(ponderation)
  525. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  526. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  527. ON
  528. quiz_question.id = quiz_rel_question.question_id AND
  529. quiz_question.c_id = quiz_rel_question.c_id
  530. WHERE
  531. quiz_rel_question.exercice_id = '.$id." AND
  532. quiz_question.c_id = $course_id AND
  533. quiz_rel_question.c_id = $course_id ";
  534. $rsQuiz = Database::query($sql);
  535. $max_score = Database::result($rsQuiz, 0, 0);
  536. // Disabling the exercise if we add it inside a LP
  537. $exercise = new Exercise($course_id);
  538. $exercise->read($id);
  539. $exercise->disable();
  540. $exercise->save();
  541. }
  542. $params = [
  543. 'c_id' => $course_id,
  544. 'lp_id' => $this->get_id(),
  545. 'item_type' => $typeCleaned,
  546. 'ref' => '',
  547. 'title' => $title,
  548. 'description' => $description,
  549. 'path' => $id,
  550. 'max_score' => $max_score,
  551. 'parent_item_id' => $parent,
  552. 'previous_item_id' => $previous,
  553. 'next_item_id' => (int) $next,
  554. 'display_order' => $display_order + 1,
  555. 'prerequisite' => $prerequisites,
  556. 'max_time_allowed' => $max_time_allowed,
  557. 'min_score' => 0,
  558. 'launch_data' => '',
  559. ];
  560. if ($prerequisites != 0) {
  561. $params['prerequisite'] = $prerequisites;
  562. }
  563. $new_item_id = Database::insert($tbl_lp_item, $params);
  564. if ($new_item_id) {
  565. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  566. Database::query($sql);
  567. if (!empty($next)) {
  568. $sql = "UPDATE $tbl_lp_item
  569. SET previous_item_id = $new_item_id
  570. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  571. Database::query($sql);
  572. }
  573. // Update the item that should be before the new item.
  574. if (!empty($tmp_previous)) {
  575. $sql = "UPDATE $tbl_lp_item
  576. SET next_item_id = $new_item_id
  577. WHERE c_id = $course_id AND id = $tmp_previous";
  578. Database::query($sql);
  579. }
  580. // Update all the items after the new item.
  581. $sql = "UPDATE $tbl_lp_item
  582. SET display_order = display_order + 1
  583. WHERE
  584. c_id = $course_id AND
  585. lp_id = ".$this->get_id()." AND
  586. iid <> $new_item_id AND
  587. parent_item_id = $parent AND
  588. display_order > $display_order";
  589. Database::query($sql);
  590. // Update the item that should come after the new item.
  591. $sql = "UPDATE $tbl_lp_item
  592. SET ref = $new_item_id
  593. WHERE c_id = $course_id AND iid = $new_item_id";
  594. Database::query($sql);
  595. $sql = "UPDATE $tbl_lp_item
  596. SET previous_item_id = ".$this->getLastInFirstLevel()."
  597. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  598. Database::query($sql);
  599. // Upload audio.
  600. if (!empty($_FILES['mp3']['name'])) {
  601. // Create the audio folder if it does not exist yet.
  602. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  603. if (!is_dir($filepath.'audio')) {
  604. mkdir(
  605. $filepath.'audio',
  606. api_get_permissions_for_new_directories()
  607. );
  608. $audio_id = add_document(
  609. $_course,
  610. '/audio',
  611. 'folder',
  612. 0,
  613. 'audio',
  614. '',
  615. 0,
  616. true,
  617. null,
  618. $sessionId,
  619. $userId
  620. );
  621. api_item_property_update(
  622. $_course,
  623. TOOL_DOCUMENT,
  624. $audio_id,
  625. 'FolderCreated',
  626. $userId,
  627. null,
  628. null,
  629. null,
  630. null,
  631. $sessionId
  632. );
  633. api_item_property_update(
  634. $_course,
  635. TOOL_DOCUMENT,
  636. $audio_id,
  637. 'invisible',
  638. $userId,
  639. null,
  640. null,
  641. null,
  642. null,
  643. $sessionId
  644. );
  645. }
  646. $file_path = handle_uploaded_document(
  647. $_course,
  648. $_FILES['mp3'],
  649. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  650. '/audio',
  651. $userId,
  652. '',
  653. '',
  654. '',
  655. '',
  656. false
  657. );
  658. // Getting the filename only.
  659. $file_components = explode('/', $file_path);
  660. $file = $file_components[count($file_components) - 1];
  661. // Store the mp3 file in the lp_item table.
  662. $sql = "UPDATE $tbl_lp_item SET
  663. audio = '".Database::escape_string($file)."'
  664. WHERE iid = '".intval($new_item_id)."'";
  665. Database::query($sql);
  666. }
  667. }
  668. return $new_item_id;
  669. }
  670. /**
  671. * Static admin function allowing addition of a learnpath to a course.
  672. *
  673. * @param string $courseCode
  674. * @param string $name
  675. * @param string $description
  676. * @param string $learnpath
  677. * @param string $origin
  678. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  679. * @param string $publicated_on
  680. * @param string $expired_on
  681. * @param int $categoryId
  682. * @param int $userId
  683. *
  684. * @return int The new learnpath ID on success, 0 on failure
  685. */
  686. public static function add_lp(
  687. $courseCode,
  688. $name,
  689. $description = '',
  690. $learnpath = 'guess',
  691. $origin = 'zip',
  692. $zipname = '',
  693. $publicated_on = '',
  694. $expired_on = '',
  695. $categoryId = 0,
  696. $userId = 0
  697. ) {
  698. global $charset;
  699. if (!empty($courseCode)) {
  700. $courseInfo = api_get_course_info($courseCode);
  701. $course_id = $courseInfo['real_id'];
  702. } else {
  703. $course_id = api_get_course_int_id();
  704. $courseInfo = api_get_course_info();
  705. }
  706. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  707. // Check course code exists.
  708. // Check lp_name doesn't exist, otherwise append something.
  709. $i = 0;
  710. $name = Database::escape_string($name);
  711. $categoryId = (int) $categoryId;
  712. // Session id.
  713. $session_id = api_get_session_id();
  714. $userId = empty($userId) ? api_get_user_id() : $userId;
  715. $check_name = "SELECT * FROM $tbl_lp
  716. WHERE c_id = $course_id AND name = '$name'";
  717. $res_name = Database::query($check_name);
  718. if (empty($publicated_on)) {
  719. $publicated_on = null;
  720. } else {
  721. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  722. }
  723. if (empty($expired_on)) {
  724. $expired_on = null;
  725. } else {
  726. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  727. }
  728. while (Database::num_rows($res_name)) {
  729. // There is already one such name, update the current one a bit.
  730. $i++;
  731. $name = $name.' - '.$i;
  732. $check_name = "SELECT * FROM $tbl_lp
  733. WHERE c_id = $course_id AND name = '$name'";
  734. $res_name = Database::query($check_name);
  735. }
  736. // New name does not exist yet; keep it.
  737. // Escape description.
  738. // Kevin: added htmlentities().
  739. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  740. $type = 1;
  741. switch ($learnpath) {
  742. case 'guess':
  743. break;
  744. case 'dokeos':
  745. case 'chamilo':
  746. $type = 1;
  747. break;
  748. case 'aicc':
  749. break;
  750. }
  751. switch ($origin) {
  752. case 'zip':
  753. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  754. break;
  755. case 'manual':
  756. default:
  757. $get_max = "SELECT MAX(display_order)
  758. FROM $tbl_lp WHERE c_id = $course_id";
  759. $res_max = Database::query($get_max);
  760. if (Database::num_rows($res_max) < 1) {
  761. $dsp = 1;
  762. } else {
  763. $row = Database::fetch_array($res_max);
  764. $dsp = $row[0] + 1;
  765. }
  766. $params = [
  767. 'c_id' => $course_id,
  768. 'lp_type' => $type,
  769. 'name' => $name,
  770. 'description' => $description,
  771. 'path' => '',
  772. 'default_view_mod' => 'embedded',
  773. 'default_encoding' => 'UTF-8',
  774. 'display_order' => $dsp,
  775. 'content_maker' => 'Chamilo',
  776. 'content_local' => 'local',
  777. 'js_lib' => '',
  778. 'session_id' => $session_id,
  779. 'created_on' => api_get_utc_datetime(),
  780. 'modified_on' => api_get_utc_datetime(),
  781. 'publicated_on' => $publicated_on,
  782. 'expired_on' => $expired_on,
  783. 'category_id' => $categoryId,
  784. 'force_commit' => 0,
  785. 'content_license' => '',
  786. 'debug' => 0,
  787. 'theme' => '',
  788. 'preview_image' => '',
  789. 'author' => '',
  790. 'prerequisite' => 0,
  791. 'hide_toc_frame' => 0,
  792. 'seriousgame_mode' => 0,
  793. 'autolaunch' => 0,
  794. 'max_attempts' => 0,
  795. 'subscribe_users' => 0,
  796. 'accumulate_scorm_time' => 1,
  797. ];
  798. $id = Database::insert($tbl_lp, $params);
  799. if ($id > 0) {
  800. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  801. Database::query($sql);
  802. // Insert into item_property.
  803. api_item_property_update(
  804. $courseInfo,
  805. TOOL_LEARNPATH,
  806. $id,
  807. 'LearnpathAdded',
  808. $userId
  809. );
  810. api_set_default_visibility(
  811. $id,
  812. TOOL_LEARNPATH,
  813. 0,
  814. $courseInfo,
  815. $session_id,
  816. $userId
  817. );
  818. return $id;
  819. }
  820. break;
  821. }
  822. }
  823. /**
  824. * Auto completes the parents of an item in case it's been completed or passed.
  825. *
  826. * @param int $item Optional ID of the item from which to look for parents
  827. */
  828. public function autocomplete_parents($item)
  829. {
  830. $debug = $this->debug;
  831. if (empty($item)) {
  832. $item = $this->current;
  833. }
  834. $currentItem = $this->getItem($item);
  835. if ($currentItem) {
  836. $parent_id = $currentItem->get_parent();
  837. $parent = $this->getItem($parent_id);
  838. if ($parent) {
  839. // if $item points to an object and there is a parent.
  840. if ($debug) {
  841. error_log(
  842. 'Autocompleting parent of item '.$item.' '.
  843. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  844. 0
  845. );
  846. }
  847. // New experiment including failed and browsed in completed status.
  848. //$current_status = $currentItem->get_status();
  849. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  850. // Fixes chapter auto complete
  851. if (true) {
  852. // If the current item is completed or passes or succeeded.
  853. $updateParentStatus = true;
  854. if ($debug) {
  855. error_log('Status of current item is alright');
  856. }
  857. foreach ($parent->get_children() as $childItemId) {
  858. $childItem = $this->getItem($childItemId);
  859. // If children was not set try to get the info
  860. if (empty($childItem->db_item_view_id)) {
  861. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  862. }
  863. // Check all his brothers (parent's children) for completion status.
  864. if ($childItemId != $item) {
  865. if ($debug) {
  866. error_log(
  867. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  868. 0
  869. );
  870. }
  871. // Trying completing parents of failed and browsed items as well.
  872. if ($childItem->status_is(
  873. [
  874. 'completed',
  875. 'passed',
  876. 'succeeded',
  877. 'browsed',
  878. 'failed',
  879. ]
  880. )
  881. ) {
  882. // Keep completion status to true.
  883. continue;
  884. } else {
  885. if ($debug > 2) {
  886. error_log(
  887. '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,
  888. 0
  889. );
  890. }
  891. $updateParentStatus = false;
  892. break;
  893. }
  894. }
  895. }
  896. if ($updateParentStatus) {
  897. // If all the children were completed:
  898. $parent->set_status('completed');
  899. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  900. // Force the status to "completed"
  901. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  902. $this->update_queue[$parent->get_id()] = 'completed';
  903. if ($debug) {
  904. error_log(
  905. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  906. print_r($this->update_queue, 1),
  907. 0
  908. );
  909. }
  910. // Recursive call.
  911. $this->autocomplete_parents($parent->get_id());
  912. }
  913. }
  914. } else {
  915. if ($debug) {
  916. error_log("Parent #$parent_id does not exists");
  917. }
  918. }
  919. } else {
  920. if ($debug) {
  921. error_log("#$item is an item that doesn't have parents");
  922. }
  923. }
  924. }
  925. /**
  926. * Closes the current resource.
  927. *
  928. * Stops the timer
  929. * Saves into the database if required
  930. * Clears the current resource data from this object
  931. *
  932. * @return bool True on success, false on failure
  933. */
  934. public function close()
  935. {
  936. if (empty($this->lp_id)) {
  937. $this->error = 'Trying to close this learnpath but no ID is set';
  938. return false;
  939. }
  940. $this->current_time_stop = time();
  941. $this->ordered_items = [];
  942. $this->index = 0;
  943. unset($this->lp_id);
  944. //unset other stuff
  945. return true;
  946. }
  947. /**
  948. * Static admin function allowing removal of a learnpath.
  949. *
  950. * @param array $courseInfo
  951. * @param int $id Learnpath ID
  952. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  953. *
  954. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  955. */
  956. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  957. {
  958. $course_id = api_get_course_int_id();
  959. if (!empty($courseInfo)) {
  960. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  961. }
  962. // TODO: Implement a way of getting this to work when the current object is not set.
  963. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  964. // If an ID is specifically given and the current LP is not the same, prevent delete.
  965. if (!empty($id) && ($id != $this->lp_id)) {
  966. return false;
  967. }
  968. $lp = Database::get_course_table(TABLE_LP_MAIN);
  969. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  970. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  971. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  972. // Delete lp item id.
  973. foreach ($this->items as $lpItemId => $dummy) {
  974. $sql = "DELETE FROM $lp_item_view
  975. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  976. Database::query($sql);
  977. }
  978. // Proposed by Christophe (nickname: clefevre)
  979. $sql = "DELETE FROM $lp_item
  980. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  981. Database::query($sql);
  982. $sql = "DELETE FROM $lp_view
  983. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  984. Database::query($sql);
  985. self::toggle_publish($this->lp_id, 'i');
  986. if ($this->type == 2 || $this->type == 3) {
  987. // This is a scorm learning path, delete the files as well.
  988. $sql = "SELECT path FROM $lp
  989. WHERE iid = ".$this->lp_id;
  990. $res = Database::query($sql);
  991. if (Database::num_rows($res) > 0) {
  992. $row = Database::fetch_array($res);
  993. $path = $row['path'];
  994. $sql = "SELECT id FROM $lp
  995. WHERE
  996. c_id = $course_id AND
  997. path = '$path' AND
  998. iid != ".$this->lp_id;
  999. $res = Database::query($sql);
  1000. if (Database::num_rows($res) > 0) {
  1001. // Another learning path uses this directory, so don't delete it.
  1002. if ($this->debug > 2) {
  1003. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1004. }
  1005. } else {
  1006. // No other LP uses that directory, delete it.
  1007. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1008. // The absolute system path for this course.
  1009. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1010. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1011. if ($this->debug > 2) {
  1012. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1013. }
  1014. // Proposed by Christophe (clefevre).
  1015. if (strcmp(substr($path, -2), "/.") == 0) {
  1016. $path = substr($path, 0, -1); // Remove "." at the end.
  1017. }
  1018. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1019. rmdirr($course_scorm_dir.$path);
  1020. }
  1021. }
  1022. }
  1023. }
  1024. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1025. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1026. // Delete tools
  1027. $sql = "DELETE FROM $tbl_tool
  1028. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1029. Database::query($sql);
  1030. $sql = "DELETE FROM $lp
  1031. WHERE iid = ".$this->lp_id;
  1032. Database::query($sql);
  1033. // Updates the display order of all lps.
  1034. $this->update_display_order();
  1035. api_item_property_update(
  1036. api_get_course_info(),
  1037. TOOL_LEARNPATH,
  1038. $this->lp_id,
  1039. 'delete',
  1040. api_get_user_id()
  1041. );
  1042. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1043. api_get_course_id(),
  1044. 4,
  1045. $id,
  1046. api_get_session_id()
  1047. );
  1048. if ($link_info !== false) {
  1049. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1050. }
  1051. if (api_get_setting('search_enabled') == 'true') {
  1052. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1053. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1054. }
  1055. }
  1056. /**
  1057. * Removes all the children of one item - dangerous!
  1058. *
  1059. * @param int $id Element ID of which children have to be removed
  1060. *
  1061. * @return int Total number of children removed
  1062. */
  1063. public function delete_children_items($id)
  1064. {
  1065. $course_id = $this->course_info['real_id'];
  1066. $num = 0;
  1067. $id = (int) $id;
  1068. if (empty($id) || empty($course_id)) {
  1069. return false;
  1070. }
  1071. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1072. $sql = "SELECT * FROM $lp_item
  1073. WHERE c_id = $course_id AND parent_item_id = $id";
  1074. $res = Database::query($sql);
  1075. while ($row = Database::fetch_array($res)) {
  1076. $num += $this->delete_children_items($row['iid']);
  1077. $sql = "DELETE FROM $lp_item
  1078. WHERE c_id = $course_id AND iid = ".$row['iid'];
  1079. Database::query($sql);
  1080. $num++;
  1081. }
  1082. return $num;
  1083. }
  1084. /**
  1085. * Removes an item from the current learnpath.
  1086. *
  1087. * @param int $id Elem ID (0 if first)
  1088. *
  1089. * @return int Number of elements moved
  1090. *
  1091. * @todo implement resource removal
  1092. */
  1093. public function delete_item($id)
  1094. {
  1095. $course_id = api_get_course_int_id();
  1096. $id = (int) $id;
  1097. // TODO: Implement the resource removal.
  1098. if (empty($id) || empty($course_id)) {
  1099. return false;
  1100. }
  1101. // First select item to get previous, next, and display order.
  1102. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1103. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1104. $res_sel = Database::query($sql_sel);
  1105. if (Database::num_rows($res_sel) < 1) {
  1106. return false;
  1107. }
  1108. $row = Database::fetch_array($res_sel);
  1109. $previous = $row['previous_item_id'];
  1110. $next = $row['next_item_id'];
  1111. $display = $row['display_order'];
  1112. $parent = $row['parent_item_id'];
  1113. $lp = $row['lp_id'];
  1114. // Delete children items.
  1115. $this->delete_children_items($id);
  1116. // Now delete the item.
  1117. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1118. Database::query($sql_del);
  1119. // Now update surrounding items.
  1120. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1121. WHERE iid = $previous";
  1122. Database::query($sql_upd);
  1123. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1124. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1125. Database::query($sql_upd);
  1126. // Now update all following items with new display order.
  1127. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1128. WHERE
  1129. c_id = $course_id AND
  1130. lp_id = $lp AND
  1131. parent_item_id = $parent AND
  1132. display_order > $display";
  1133. Database::query($sql_all);
  1134. //Removing prerequisites since the item will not longer exist
  1135. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1136. WHERE c_id = $course_id AND prerequisite = $id";
  1137. Database::query($sql_all);
  1138. $sql = "UPDATE $lp_item
  1139. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1140. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1141. Database::query($sql);
  1142. // Remove from search engine if enabled.
  1143. if (api_get_setting('search_enabled') === 'true') {
  1144. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1145. $sql = 'SELECT * FROM %s
  1146. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1147. LIMIT 1';
  1148. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1149. $res = Database::query($sql);
  1150. if (Database::num_rows($res) > 0) {
  1151. $row2 = Database::fetch_array($res);
  1152. $di = new ChamiloIndexer();
  1153. $di->remove_document($row2['search_did']);
  1154. }
  1155. $sql = 'DELETE FROM %s
  1156. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1157. LIMIT 1';
  1158. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1159. Database::query($sql);
  1160. }
  1161. }
  1162. /**
  1163. * Updates an item's content in place.
  1164. *
  1165. * @param int $id Element ID
  1166. * @param int $parent Parent item ID
  1167. * @param int $previous Previous item ID
  1168. * @param string $title Item title
  1169. * @param string $description Item description
  1170. * @param string $prerequisites Prerequisites (optional)
  1171. * @param array $audio The array resulting of the $_FILES[mp3] element
  1172. * @param int $max_time_allowed
  1173. * @param string $url
  1174. *
  1175. * @return bool True on success, false on error
  1176. */
  1177. public function edit_item(
  1178. $id,
  1179. $parent,
  1180. $previous,
  1181. $title,
  1182. $description,
  1183. $prerequisites = '0',
  1184. $audio = [],
  1185. $max_time_allowed = 0,
  1186. $url = ''
  1187. ) {
  1188. $course_id = api_get_course_int_id();
  1189. $_course = api_get_course_info();
  1190. $id = (int) $id;
  1191. if (empty($max_time_allowed)) {
  1192. $max_time_allowed = 0;
  1193. }
  1194. if (empty($id) || empty($_course)) {
  1195. return false;
  1196. }
  1197. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1198. $sql = "SELECT * FROM $tbl_lp_item
  1199. WHERE iid = $id";
  1200. $res_select = Database::query($sql);
  1201. $row_select = Database::fetch_array($res_select);
  1202. $audio_update_sql = '';
  1203. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1204. // Create the audio folder if it does not exist yet.
  1205. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1206. if (!is_dir($filepath.'audio')) {
  1207. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1208. $audio_id = add_document(
  1209. $_course,
  1210. '/audio',
  1211. 'folder',
  1212. 0,
  1213. 'audio'
  1214. );
  1215. api_item_property_update(
  1216. $_course,
  1217. TOOL_DOCUMENT,
  1218. $audio_id,
  1219. 'FolderCreated',
  1220. api_get_user_id(),
  1221. null,
  1222. null,
  1223. null,
  1224. null,
  1225. api_get_session_id()
  1226. );
  1227. api_item_property_update(
  1228. $_course,
  1229. TOOL_DOCUMENT,
  1230. $audio_id,
  1231. 'invisible',
  1232. api_get_user_id(),
  1233. null,
  1234. null,
  1235. null,
  1236. null,
  1237. api_get_session_id()
  1238. );
  1239. }
  1240. // Upload file in documents.
  1241. $pi = pathinfo($audio['name']);
  1242. if ($pi['extension'] === 'mp3') {
  1243. $c_det = api_get_course_info($this->cc);
  1244. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1245. $path = handle_uploaded_document(
  1246. $c_det,
  1247. $audio,
  1248. $bp,
  1249. '/audio',
  1250. api_get_user_id(),
  1251. 0,
  1252. null,
  1253. 0,
  1254. 'rename',
  1255. false,
  1256. 0
  1257. );
  1258. $path = substr($path, 7);
  1259. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1260. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1261. }
  1262. }
  1263. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1264. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1265. // TODO: htmlspecialchars to be checked for encoding related problems.
  1266. if ($same_parent && $same_previous) {
  1267. // Only update title and description.
  1268. $sql = "UPDATE $tbl_lp_item
  1269. SET title = '".Database::escape_string($title)."',
  1270. prerequisite = '".$prerequisites."',
  1271. description = '".Database::escape_string($description)."'
  1272. ".$audio_update_sql.",
  1273. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1274. WHERE iid = $id";
  1275. Database::query($sql);
  1276. } else {
  1277. $old_parent = $row_select['parent_item_id'];
  1278. $old_previous = $row_select['previous_item_id'];
  1279. $old_next = $row_select['next_item_id'];
  1280. $old_order = $row_select['display_order'];
  1281. $old_prerequisite = $row_select['prerequisite'];
  1282. $old_max_time_allowed = $row_select['max_time_allowed'];
  1283. /* BEGIN -- virtually remove the current item id */
  1284. /* for the next and previous item it is like the current item doesn't exist anymore */
  1285. if ($old_previous != 0) {
  1286. // Next
  1287. $sql = "UPDATE $tbl_lp_item
  1288. SET next_item_id = $old_next
  1289. WHERE iid = $old_previous";
  1290. Database::query($sql);
  1291. }
  1292. if (!empty($old_next)) {
  1293. // Previous
  1294. $sql = "UPDATE $tbl_lp_item
  1295. SET previous_item_id = $old_previous
  1296. WHERE iid = $old_next";
  1297. Database::query($sql);
  1298. }
  1299. // display_order - 1 for every item with a display_order
  1300. // bigger then the display_order of the current item.
  1301. $sql = "UPDATE $tbl_lp_item
  1302. SET display_order = display_order - 1
  1303. WHERE
  1304. c_id = $course_id AND
  1305. display_order > $old_order AND
  1306. lp_id = ".$this->lp_id." AND
  1307. parent_item_id = $old_parent";
  1308. Database::query($sql);
  1309. /* END -- virtually remove the current item id */
  1310. /* BEGIN -- update the current item id to his new location */
  1311. if ($previous == 0) {
  1312. // Select the data of the item that should come after the current item.
  1313. $sql = "SELECT id, display_order
  1314. FROM $tbl_lp_item
  1315. WHERE
  1316. c_id = $course_id AND
  1317. lp_id = ".$this->lp_id." AND
  1318. parent_item_id = $parent AND
  1319. previous_item_id = $previous";
  1320. $res_select_old = Database::query($sql);
  1321. $row_select_old = Database::fetch_array($res_select_old);
  1322. // If the new parent didn't have children before.
  1323. if (Database::num_rows($res_select_old) == 0) {
  1324. $new_next = 0;
  1325. $new_order = 1;
  1326. } else {
  1327. $new_next = $row_select_old['id'];
  1328. $new_order = $row_select_old['display_order'];
  1329. }
  1330. } else {
  1331. // Select the data of the item that should come before the current item.
  1332. $sql = "SELECT next_item_id, display_order
  1333. FROM $tbl_lp_item
  1334. WHERE iid = $previous";
  1335. $res_select_old = Database::query($sql);
  1336. $row_select_old = Database::fetch_array($res_select_old);
  1337. $new_next = $row_select_old['next_item_id'];
  1338. $new_order = $row_select_old['display_order'] + 1;
  1339. }
  1340. // TODO: htmlspecialchars to be checked for encoding related problems.
  1341. // Update the current item with the new data.
  1342. $sql = "UPDATE $tbl_lp_item
  1343. SET
  1344. title = '".Database::escape_string($title)."',
  1345. description = '".Database::escape_string($description)."',
  1346. parent_item_id = $parent,
  1347. previous_item_id = $previous,
  1348. next_item_id = $new_next,
  1349. display_order = $new_order
  1350. $audio_update_sql
  1351. WHERE iid = $id";
  1352. Database::query($sql);
  1353. if ($previous != 0) {
  1354. // Update the previous item's next_item_id.
  1355. $sql = "UPDATE $tbl_lp_item
  1356. SET next_item_id = $id
  1357. WHERE iid = $previous";
  1358. Database::query($sql);
  1359. }
  1360. if (!empty($new_next)) {
  1361. // Update the next item's previous_item_id.
  1362. $sql = "UPDATE $tbl_lp_item
  1363. SET previous_item_id = $id
  1364. WHERE iid = $new_next";
  1365. Database::query($sql);
  1366. }
  1367. if ($old_prerequisite != $prerequisites) {
  1368. $sql = "UPDATE $tbl_lp_item
  1369. SET prerequisite = '$prerequisites'
  1370. WHERE iid = $id";
  1371. Database::query($sql);
  1372. }
  1373. if ($old_max_time_allowed != $max_time_allowed) {
  1374. // update max time allowed
  1375. $sql = "UPDATE $tbl_lp_item
  1376. SET max_time_allowed = $max_time_allowed
  1377. WHERE iid = $id";
  1378. Database::query($sql);
  1379. }
  1380. // Update all the items with the same or a bigger display_order than the current item.
  1381. $sql = "UPDATE $tbl_lp_item
  1382. SET display_order = display_order + 1
  1383. WHERE
  1384. c_id = $course_id AND
  1385. lp_id = ".$this->get_id()." AND
  1386. iid <> $id AND
  1387. parent_item_id = $parent AND
  1388. display_order >= $new_order";
  1389. Database::query($sql);
  1390. }
  1391. if ($row_select['item_type'] == 'link') {
  1392. $link = new Link();
  1393. $linkId = $row_select['path'];
  1394. $link->updateLink($linkId, $url);
  1395. }
  1396. }
  1397. /**
  1398. * Updates an item's prereq in place.
  1399. *
  1400. * @param int $id Element ID
  1401. * @param string $prerequisite_id Prerequisite Element ID
  1402. * @param int $minScore Prerequisite min score
  1403. * @param int $maxScore Prerequisite max score
  1404. *
  1405. * @return bool True on success, false on error
  1406. */
  1407. public function edit_item_prereq(
  1408. $id,
  1409. $prerequisite_id,
  1410. $minScore = 0,
  1411. $maxScore = 100
  1412. ) {
  1413. $id = (int) $id;
  1414. $prerequisite_id = (int) $prerequisite_id;
  1415. if (empty($id)) {
  1416. return false;
  1417. }
  1418. if (empty($minScore) || $minScore < 0) {
  1419. $minScore = 0;
  1420. }
  1421. if (empty($maxScore) || $maxScore < 0) {
  1422. $maxScore = 100;
  1423. }
  1424. $minScore = floatval($minScore);
  1425. $maxScore = floatval($maxScore);
  1426. if (empty($prerequisite_id)) {
  1427. $prerequisite_id = 'NULL';
  1428. $minScore = 0;
  1429. $maxScore = 100;
  1430. }
  1431. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1432. $sql = " UPDATE $tbl_lp_item
  1433. SET
  1434. prerequisite = $prerequisite_id ,
  1435. prerequisite_min_score = $minScore ,
  1436. prerequisite_max_score = $maxScore
  1437. WHERE iid = $id";
  1438. Database::query($sql);
  1439. return true;
  1440. }
  1441. /**
  1442. * Gets all the chapters belonging to the same parent as the item/chapter given
  1443. * Can also be called as abstract method.
  1444. *
  1445. * @deprecated not used
  1446. *
  1447. * @param int $id Item ID
  1448. *
  1449. * @return array A list of all the "brother items" (or an empty array on failure)
  1450. */
  1451. public function getSiblingDirectories($id)
  1452. {
  1453. $course_id = api_get_course_int_id();
  1454. if (empty($id) || $id != strval(intval($id))) {
  1455. return [];
  1456. }
  1457. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1458. $sql_parent = "SELECT * FROM $lp_item
  1459. WHERE iid = $id AND item_type='dir'";
  1460. $res_parent = Database::query($sql_parent);
  1461. if (Database::num_rows($res_parent) > 0) {
  1462. $row_parent = Database::fetch_array($res_parent);
  1463. $parent = $row_parent['parent_item_id'];
  1464. $sql = "SELECT * FROM $lp_item
  1465. WHERE
  1466. parent_item_id = $parent AND
  1467. iid = $id AND
  1468. item_type='dir'
  1469. ORDER BY display_order";
  1470. $res_bros = Database::query($sql);
  1471. $list = [];
  1472. while ($row_bro = Database::fetch_array($res_bros)) {
  1473. $list[] = $row_bro;
  1474. }
  1475. return $list;
  1476. }
  1477. return [];
  1478. }
  1479. /**
  1480. * Gets all the items belonging to the same parent as the item given
  1481. * Can also be called as abstract method.
  1482. *
  1483. * @deprecated not used
  1484. *
  1485. * @param int $id Item ID
  1486. *
  1487. * @return array A list of all the "brother items" (or an empty array on failure)
  1488. */
  1489. public function get_brother_items($id)
  1490. {
  1491. $course_id = api_get_course_int_id();
  1492. if (empty($id) || $id != strval(intval($id))) {
  1493. return [];
  1494. }
  1495. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1496. $sql_parent = "SELECT * FROM $lp_item
  1497. WHERE iid = $id";
  1498. $res_parent = Database::query($sql_parent);
  1499. if (Database::num_rows($res_parent) > 0) {
  1500. $row_parent = Database::fetch_array($res_parent);
  1501. $parent = $row_parent['parent_item_id'];
  1502. $sql = "SELECT * FROM $lp_item
  1503. WHERE c_id = $course_id AND parent_item_id = $parent
  1504. ORDER BY display_order";
  1505. $res_bros = Database::query($sql);
  1506. $list = [];
  1507. while ($row_bro = Database::fetch_array($res_bros)) {
  1508. $list[] = $row_bro;
  1509. }
  1510. return $list;
  1511. }
  1512. return [];
  1513. }
  1514. /**
  1515. * Get the specific prefix index terms of this learning path.
  1516. *
  1517. * @param string $prefix
  1518. *
  1519. * @return array Array of terms
  1520. */
  1521. public function get_common_index_terms_by_prefix($prefix)
  1522. {
  1523. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1524. $terms = get_specific_field_values_list_by_prefix(
  1525. $prefix,
  1526. $this->cc,
  1527. TOOL_LEARNPATH,
  1528. $this->lp_id
  1529. );
  1530. $prefix_terms = [];
  1531. if (!empty($terms)) {
  1532. foreach ($terms as $term) {
  1533. $prefix_terms[] = $term['value'];
  1534. }
  1535. }
  1536. return $prefix_terms;
  1537. }
  1538. /**
  1539. * Gets the number of items currently completed.
  1540. *
  1541. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1542. *
  1543. * @return int The number of items currently completed
  1544. */
  1545. public function get_complete_items_count($failedStatusException = false)
  1546. {
  1547. $i = 0;
  1548. $completedStatusList = [
  1549. 'completed',
  1550. 'passed',
  1551. 'succeeded',
  1552. 'browsed',
  1553. ];
  1554. if (!$failedStatusException) {
  1555. $completedStatusList[] = 'failed';
  1556. }
  1557. foreach ($this->items as $id => $dummy) {
  1558. // Trying failed and browsed considered "progressed" as well.
  1559. if ($this->items[$id]->status_is($completedStatusList) &&
  1560. $this->items[$id]->get_type() != 'dir'
  1561. ) {
  1562. $i++;
  1563. }
  1564. }
  1565. return $i;
  1566. }
  1567. /**
  1568. * Gets the current item ID.
  1569. *
  1570. * @return int The current learnpath item id
  1571. */
  1572. public function get_current_item_id()
  1573. {
  1574. $current = 0;
  1575. if (!empty($this->current)) {
  1576. $current = (int) $this->current;
  1577. }
  1578. return $current;
  1579. }
  1580. /**
  1581. * Force to get the first learnpath item id.
  1582. *
  1583. * @return int The current learnpath item id
  1584. */
  1585. public function get_first_item_id()
  1586. {
  1587. $current = 0;
  1588. if (is_array($this->ordered_items)) {
  1589. $current = $this->ordered_items[0];
  1590. }
  1591. return $current;
  1592. }
  1593. /**
  1594. * Gets the total number of items available for viewing in this SCORM.
  1595. *
  1596. * @return int The total number of items
  1597. */
  1598. public function get_total_items_count()
  1599. {
  1600. return count($this->items);
  1601. }
  1602. /**
  1603. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1604. *
  1605. * @return int The total no-chapters number of items
  1606. */
  1607. public function getTotalItemsCountWithoutDirs()
  1608. {
  1609. $total = 0;
  1610. $typeListNotToCount = self::getChapterTypes();
  1611. foreach ($this->items as $temp2) {
  1612. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1613. $total++;
  1614. }
  1615. }
  1616. return $total;
  1617. }
  1618. /**
  1619. * Sets the first element URL.
  1620. */
  1621. public function first()
  1622. {
  1623. if ($this->debug > 0) {
  1624. error_log('In learnpath::first()', 0);
  1625. error_log('$this->last_item_seen '.$this->last_item_seen);
  1626. }
  1627. // Test if the last_item_seen exists and is not a dir.
  1628. if (count($this->ordered_items) == 0) {
  1629. $this->index = 0;
  1630. }
  1631. if (!empty($this->last_item_seen) &&
  1632. !empty($this->items[$this->last_item_seen]) &&
  1633. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1634. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1635. //&& !$this->items[$this->last_item_seen]->is_done()
  1636. ) {
  1637. if ($this->debug > 2) {
  1638. error_log(
  1639. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1640. $this->items[$this->last_item_seen]->get_type()
  1641. );
  1642. }
  1643. $index = -1;
  1644. foreach ($this->ordered_items as $myindex => $item_id) {
  1645. if ($item_id == $this->last_item_seen) {
  1646. $index = $myindex;
  1647. break;
  1648. }
  1649. }
  1650. if ($index == -1) {
  1651. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1652. if ($this->debug > 2) {
  1653. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1654. }
  1655. return false;
  1656. } else {
  1657. $this->last = $this->last_item_seen;
  1658. $this->current = $this->last_item_seen;
  1659. $this->index = $index;
  1660. }
  1661. } else {
  1662. if ($this->debug > 2) {
  1663. error_log('In learnpath::first() - No last item seen', 0);
  1664. }
  1665. $index = 0;
  1666. // Loop through all ordered items and stop at the first item that is
  1667. // not a directory *and* that has not been completed yet.
  1668. while (!empty($this->ordered_items[$index]) &&
  1669. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1670. (
  1671. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1672. $this->items[$this->ordered_items[$index]]->is_done() === true
  1673. ) && $index < $this->max_ordered_items) {
  1674. $index++;
  1675. }
  1676. $this->last = $this->current;
  1677. // current is
  1678. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1679. $this->index = $index;
  1680. if ($this->debug > 2) {
  1681. error_log('$index '.$index);
  1682. error_log('In learnpath::first() - No last item seen');
  1683. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1684. }
  1685. }
  1686. if ($this->debug > 2) {
  1687. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1688. }
  1689. }
  1690. /**
  1691. * Gets the js library from the database.
  1692. *
  1693. * @return string The name of the javascript library to be used
  1694. */
  1695. public function get_js_lib()
  1696. {
  1697. $lib = '';
  1698. if (!empty($this->js_lib)) {
  1699. $lib = $this->js_lib;
  1700. }
  1701. return $lib;
  1702. }
  1703. /**
  1704. * Gets the learnpath database ID.
  1705. *
  1706. * @return int Learnpath ID in the lp table
  1707. */
  1708. public function get_id()
  1709. {
  1710. if (!empty($this->lp_id)) {
  1711. return (int) $this->lp_id;
  1712. }
  1713. return 0;
  1714. }
  1715. /**
  1716. * Gets the last element URL.
  1717. *
  1718. * @return string URL to load into the viewer
  1719. */
  1720. public function get_last()
  1721. {
  1722. // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1723. if (count($this->ordered_items) > 0) {
  1724. $this->index = count($this->ordered_items) - 1;
  1725. return $this->ordered_items[$this->index];
  1726. }
  1727. return false;
  1728. }
  1729. /**
  1730. * Get the last element in the first level.
  1731. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1732. *
  1733. * @return mixed
  1734. */
  1735. public function getLastInFirstLevel()
  1736. {
  1737. try {
  1738. $lastId = Database::getManager()
  1739. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1740. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1741. ->setMaxResults(1)
  1742. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1743. ->getSingleScalarResult();
  1744. return $lastId;
  1745. } catch (Exception $exception) {
  1746. return 0;
  1747. }
  1748. }
  1749. /**
  1750. * Gets the navigation bar for the learnpath display screen.
  1751. *
  1752. * @param string $barId
  1753. *
  1754. * @return string The HTML string to use as a navigation bar
  1755. */
  1756. public function get_navigation_bar($barId = '')
  1757. {
  1758. if (empty($barId)) {
  1759. $barId = 'control-top';
  1760. }
  1761. $lpId = $this->lp_id;
  1762. $mycurrentitemid = $this->get_current_item_id();
  1763. $reportingText = get_lang('Reporting');
  1764. $previousText = get_lang('ScormPrevious');
  1765. $nextText = get_lang('ScormNext');
  1766. $fullScreenText = get_lang('ScormExitFullScreen');
  1767. $settings = api_get_configuration_value('lp_view_settings');
  1768. $display = isset($settings['display']) ? $settings['display'] : false;
  1769. $reportingIcon = '
  1770. <a class="icon-toolbar"
  1771. id="stats_link"
  1772. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1773. onclick="window.parent.API.save_asset(); return true;"
  1774. target="content_name" title="'.$reportingText.'">
  1775. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1776. </a>';
  1777. if (!empty($display)) {
  1778. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1779. if ($showReporting === false) {
  1780. $reportingIcon = '';
  1781. }
  1782. }
  1783. $hideArrows = false;
  1784. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1785. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1786. }
  1787. $previousIcon = '';
  1788. $nextIcon = '';
  1789. if ($hideArrows === false) {
  1790. $previousIcon = '
  1791. <a class="icon-toolbar" id="scorm-previous" href="#"
  1792. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1793. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1794. </a>';
  1795. $nextIcon = '
  1796. <a class="icon-toolbar" id="scorm-next" href="#"
  1797. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1798. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1799. </a>';
  1800. }
  1801. if ($this->mode === 'fullscreen') {
  1802. $navbar = '
  1803. <span id="'.$barId.'" class="buttons">
  1804. '.$reportingIcon.'
  1805. '.$previousIcon.'
  1806. '.$nextIcon.'
  1807. <a class="icon-toolbar" id="view-embedded"
  1808. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1809. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1810. </a>
  1811. </span>';
  1812. } else {
  1813. $navbar = '
  1814. <span id="'.$barId.'" class="buttons text-right">
  1815. '.$reportingIcon.'
  1816. '.$previousIcon.'
  1817. '.$nextIcon.'
  1818. </span>';
  1819. }
  1820. return $navbar;
  1821. }
  1822. /**
  1823. * Gets the next resource in queue (url).
  1824. *
  1825. * @return string URL to load into the viewer
  1826. */
  1827. public function get_next_index()
  1828. {
  1829. // TODO
  1830. $index = $this->index;
  1831. $index++;
  1832. while (
  1833. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1834. $index < $this->max_ordered_items
  1835. ) {
  1836. $index++;
  1837. if ($index == $this->max_ordered_items) {
  1838. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1839. return $this->index;
  1840. }
  1841. return $index;
  1842. }
  1843. }
  1844. if (empty($this->ordered_items[$index])) {
  1845. return $this->index;
  1846. }
  1847. return $index;
  1848. }
  1849. /**
  1850. * Gets item_id for the next element.
  1851. *
  1852. * @return int Next item (DB) ID
  1853. */
  1854. public function get_next_item_id()
  1855. {
  1856. $new_index = $this->get_next_index();
  1857. if (!empty($new_index)) {
  1858. if (isset($this->ordered_items[$new_index])) {
  1859. return $this->ordered_items[$new_index];
  1860. }
  1861. }
  1862. return 0;
  1863. }
  1864. /**
  1865. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1866. *
  1867. * Generally, the package provided is in the form of a zip file, so the function
  1868. * has been written to test a zip file. If not a zip, the function will return the
  1869. * default return value: ''
  1870. *
  1871. * @param string $file_path the path to the file
  1872. * @param string $file_name the original name of the file
  1873. *
  1874. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1875. */
  1876. public static function get_package_type($file_path, $file_name)
  1877. {
  1878. // Get name of the zip file without the extension.
  1879. $file_info = pathinfo($file_name);
  1880. $extension = $file_info['extension']; // Extension only.
  1881. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1882. 'dll',
  1883. 'exe',
  1884. ])) {
  1885. return 'oogie';
  1886. }
  1887. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1888. 'dll',
  1889. 'exe',
  1890. ])) {
  1891. return 'woogie';
  1892. }
  1893. $zipFile = new PclZip($file_path);
  1894. // Check the zip content (real size and file extension).
  1895. $zipContentArray = $zipFile->listContent();
  1896. $package_type = '';
  1897. $manifest = '';
  1898. $aicc_match_crs = 0;
  1899. $aicc_match_au = 0;
  1900. $aicc_match_des = 0;
  1901. $aicc_match_cst = 0;
  1902. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1903. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1904. foreach ($zipContentArray as $thisContent) {
  1905. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1906. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1907. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1908. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1909. $package_type = 'scorm';
  1910. break; // Exit the foreach loop.
  1911. } elseif (
  1912. preg_match('/aicc\//i', $thisContent['filename']) ||
  1913. in_array(
  1914. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1915. ['crs', 'au', 'des', 'cst']
  1916. )
  1917. ) {
  1918. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  1919. switch ($ext) {
  1920. case 'crs':
  1921. $aicc_match_crs = 1;
  1922. break;
  1923. case 'au':
  1924. $aicc_match_au = 1;
  1925. break;
  1926. case 'des':
  1927. $aicc_match_des = 1;
  1928. break;
  1929. case 'cst':
  1930. $aicc_match_cst = 1;
  1931. break;
  1932. default:
  1933. break;
  1934. }
  1935. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  1936. } else {
  1937. $package_type = '';
  1938. }
  1939. }
  1940. }
  1941. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  1942. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  1943. $package_type = 'aicc';
  1944. }
  1945. // Try with chamilo course builder
  1946. if (empty($package_type)) {
  1947. $package_type = 'chamilo';
  1948. }
  1949. return $package_type;
  1950. }
  1951. /**
  1952. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  1953. *
  1954. * @return string URL to load into the viewer
  1955. */
  1956. public function get_previous_index()
  1957. {
  1958. $index = $this->index;
  1959. if (isset($this->ordered_items[$index - 1])) {
  1960. $index--;
  1961. while (isset($this->ordered_items[$index]) &&
  1962. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  1963. ) {
  1964. $index--;
  1965. if ($index < 0) {
  1966. return $this->index;
  1967. }
  1968. }
  1969. }
  1970. return $index;
  1971. }
  1972. /**
  1973. * Gets item_id for the next element.
  1974. *
  1975. * @return int Previous item (DB) ID
  1976. */
  1977. public function get_previous_item_id()
  1978. {
  1979. $index = $this->get_previous_index();
  1980. return $this->ordered_items[$index];
  1981. }
  1982. /**
  1983. * Returns the HTML necessary to print a mediaplayer block inside a page.
  1984. *
  1985. * @param int $lpItemId
  1986. * @param string $autostart
  1987. *
  1988. * @return string The mediaplayer HTML
  1989. */
  1990. public function get_mediaplayer($lpItemId, $autostart = 'true')
  1991. {
  1992. $course_id = api_get_course_int_id();
  1993. $_course = api_get_course_info();
  1994. if (empty($_course)) {
  1995. return '';
  1996. }
  1997. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1998. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1999. $lpItemId = (int) $lpItemId;
  2000. /** @var learnpathItem $item */
  2001. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2002. $itemViewId = 0;
  2003. if ($item) {
  2004. $itemViewId = (int) $item->db_item_view_id;
  2005. }
  2006. // Getting all the information about the item.
  2007. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2008. FROM $tbl_lp_item as lpi
  2009. INNER JOIN $tbl_lp_item_view as lp_view
  2010. ON (lpi.iid = lp_view.lp_item_id)
  2011. WHERE
  2012. lp_view.iid = $itemViewId AND
  2013. lpi.iid = $lpItemId AND
  2014. lp_view.c_id = $course_id";
  2015. $result = Database::query($sql);
  2016. $row = Database::fetch_assoc($result);
  2017. $output = '';
  2018. if (!empty($row['audio'])) {
  2019. $list = $_SESSION['oLP']->get_toc();
  2020. switch ($row['item_type']) {
  2021. case 'quiz':
  2022. $type_quiz = false;
  2023. foreach ($list as $toc) {
  2024. if ($toc['id'] == $_SESSION['oLP']->current) {
  2025. $type_quiz = true;
  2026. }
  2027. }
  2028. if ($type_quiz) {
  2029. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2030. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2031. } else {
  2032. $autostart_audio = $autostart;
  2033. }
  2034. }
  2035. break;
  2036. case TOOL_READOUT_TEXT:;
  2037. $autostart_audio = 'false';
  2038. break;
  2039. default:
  2040. $autostart_audio = 'true';
  2041. }
  2042. $courseInfo = api_get_course_info();
  2043. $audio = $row['audio'];
  2044. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2045. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2046. if (!file_exists($file)) {
  2047. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2048. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2049. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2050. }
  2051. $player = Display::getMediaPlayer(
  2052. $file,
  2053. [
  2054. 'id' => 'lp_audio_media_player',
  2055. 'url' => $url,
  2056. 'autoplay' => $autostart_audio,
  2057. 'width' => '100%',
  2058. ]
  2059. );
  2060. // The mp3 player.
  2061. $output = '<div id="container">';
  2062. $output .= $player;
  2063. $output .= '</div>';
  2064. }
  2065. return $output;
  2066. }
  2067. /**
  2068. * @param int $studentId
  2069. * @param int $prerequisite
  2070. * @param array $courseInfo
  2071. * @param int $sessionId
  2072. *
  2073. * @return bool
  2074. */
  2075. public static function isBlockedByPrerequisite(
  2076. $studentId,
  2077. $prerequisite,
  2078. $courseInfo,
  2079. $sessionId
  2080. ) {
  2081. if (empty($courseInfo)) {
  2082. return false;
  2083. }
  2084. $courseId = $courseInfo['real_id'];
  2085. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2086. if ($allow) {
  2087. if (api_is_allowed_to_edit() ||
  2088. api_is_platform_admin(true) ||
  2089. api_is_drh() ||
  2090. api_is_coach($sessionId, $courseId, false)
  2091. ) {
  2092. return false;
  2093. }
  2094. }
  2095. $isBlocked = false;
  2096. if (!empty($prerequisite)) {
  2097. $progress = self::getProgress(
  2098. $prerequisite,
  2099. $studentId,
  2100. $courseId,
  2101. $sessionId
  2102. );
  2103. if ($progress < 100) {
  2104. $isBlocked = true;
  2105. }
  2106. if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  2107. // Block if it does not exceed minimum time
  2108. // Minimum time (in minutes) to pass the learning path
  2109. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2110. if ($accumulateWorkTime > 0) {
  2111. // Total time in course (sum of times in learning paths from course)
  2112. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2113. // Connect with the plugin_licences_course_session table
  2114. // which indicates what percentage of the time applies
  2115. // Minimum connection percentage
  2116. $perc = 100;
  2117. // Time from the course
  2118. $tc = $accumulateWorkTimeTotal;
  2119. // Percentage of the learning paths
  2120. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2121. // Minimum time for each learning path
  2122. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2123. // Spent time (in seconds) so far in the learning path
  2124. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2125. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2126. if ($lpTime < ($accumulateWorkTime * 60)) {
  2127. $isBlocked = true;
  2128. }
  2129. }
  2130. }
  2131. }
  2132. return $isBlocked;
  2133. }
  2134. /**
  2135. * Checks if the learning path is visible for student after the progress
  2136. * of its prerequisite is completed, considering the time availability and
  2137. * the LP visibility.
  2138. *
  2139. * @param int $lp_id
  2140. * @param int $student_id
  2141. * @param array $courseInfo
  2142. * @param int $sessionId
  2143. *
  2144. * @return bool
  2145. */
  2146. public static function is_lp_visible_for_student(
  2147. $lp_id,
  2148. $student_id,
  2149. $courseInfo = [],
  2150. $sessionId = 0
  2151. ) {
  2152. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2153. $lp_id = (int) $lp_id;
  2154. $sessionId = (int) $sessionId;
  2155. if (empty($courseInfo)) {
  2156. return false;
  2157. }
  2158. if (empty($sessionId)) {
  2159. $sessionId = api_get_session_id();
  2160. }
  2161. $courseId = $courseInfo['real_id'];
  2162. $itemInfo = api_get_item_property_info(
  2163. $courseId,
  2164. TOOL_LEARNPATH,
  2165. $lp_id,
  2166. $sessionId
  2167. );
  2168. // If the item was deleted.
  2169. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2170. return false;
  2171. }
  2172. // @todo remove this query and load the row info as a parameter
  2173. $table = Database::get_course_table(TABLE_LP_MAIN);
  2174. // Get current prerequisite
  2175. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2176. FROM $table
  2177. WHERE iid = $lp_id";
  2178. $rs = Database::query($sql);
  2179. $now = time();
  2180. if (Database::num_rows($rs) > 0) {
  2181. $row = Database::fetch_array($rs, 'ASSOC');
  2182. $prerequisite = $row['prerequisite'];
  2183. $is_visible = true;
  2184. $isBlocked = self::isBlockedByPrerequisite(
  2185. $student_id,
  2186. $prerequisite,
  2187. $courseInfo,
  2188. $sessionId
  2189. );
  2190. if ($isBlocked) {
  2191. $is_visible = false;
  2192. }
  2193. // Also check the time availability of the LP
  2194. if ($is_visible) {
  2195. // Adding visibility restrictions
  2196. if (!empty($row['publicated_on'])) {
  2197. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2198. $is_visible = false;
  2199. }
  2200. }
  2201. // Blocking empty start times see BT#2800
  2202. global $_custom;
  2203. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2204. $_custom['lps_hidden_when_no_start_date']
  2205. ) {
  2206. if (empty($row['publicated_on'])) {
  2207. $is_visible = false;
  2208. }
  2209. }
  2210. if (!empty($row['expired_on'])) {
  2211. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2212. $is_visible = false;
  2213. }
  2214. }
  2215. }
  2216. if ($is_visible) {
  2217. $subscriptionSettings = self::getSubscriptionSettings();
  2218. // Check if the subscription users/group to a LP is ON
  2219. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2220. $subscriptionSettings['allow_add_users_to_lp'] === true
  2221. ) {
  2222. // Try group
  2223. $is_visible = false;
  2224. // Checking only the user visibility
  2225. $userVisibility = api_get_item_visibility(
  2226. $courseInfo,
  2227. 'learnpath',
  2228. $row['id'],
  2229. $sessionId,
  2230. $student_id,
  2231. 'LearnpathSubscription'
  2232. );
  2233. if ($userVisibility == 1) {
  2234. $is_visible = true;
  2235. } else {
  2236. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id, $courseId);
  2237. if (!empty($userGroups)) {
  2238. foreach ($userGroups as $groupInfo) {
  2239. $groupId = $groupInfo['iid'];
  2240. $userVisibility = api_get_item_visibility(
  2241. $courseInfo,
  2242. 'learnpath',
  2243. $row['id'],
  2244. $sessionId,
  2245. null,
  2246. 'LearnpathSubscription',
  2247. $groupId
  2248. );
  2249. if ($userVisibility == 1) {
  2250. $is_visible = true;
  2251. break;
  2252. }
  2253. }
  2254. }
  2255. }
  2256. }
  2257. }
  2258. return $is_visible;
  2259. }
  2260. return false;
  2261. }
  2262. /**
  2263. * @param int $lpId
  2264. * @param int $userId
  2265. * @param int $courseId
  2266. * @param int $sessionId
  2267. *
  2268. * @return int
  2269. */
  2270. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2271. {
  2272. $lpId = (int) $lpId;
  2273. $userId = (int) $userId;
  2274. $courseId = (int) $courseId;
  2275. $sessionId = (int) $sessionId;
  2276. $sessionCondition = api_get_session_condition($sessionId);
  2277. $table = Database::get_course_table(TABLE_LP_VIEW);
  2278. $sql = "SELECT progress FROM $table
  2279. WHERE
  2280. c_id = $courseId AND
  2281. lp_id = $lpId AND
  2282. user_id = $userId $sessionCondition ";
  2283. $res = Database::query($sql);
  2284. $progress = 0;
  2285. if (Database::num_rows($res) > 0) {
  2286. $row = Database::fetch_array($res);
  2287. $progress = (int) $row['progress'];
  2288. }
  2289. return $progress;
  2290. }
  2291. /**
  2292. * @param array $lpList
  2293. * @param int $userId
  2294. * @param int $courseId
  2295. * @param int $sessionId
  2296. *
  2297. * @return array
  2298. */
  2299. public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
  2300. {
  2301. $lpList = array_map('intval', $lpList);
  2302. if (empty($lpList)) {
  2303. return [];
  2304. }
  2305. $lpList = implode("','", $lpList);
  2306. $userId = (int) $userId;
  2307. $courseId = (int) $courseId;
  2308. $sessionId = (int) $sessionId;
  2309. $sessionCondition = api_get_session_condition($sessionId);
  2310. $table = Database::get_course_table(TABLE_LP_VIEW);
  2311. $sql = "SELECT lp_id, progress FROM $table
  2312. WHERE
  2313. c_id = $courseId AND
  2314. lp_id IN ('".$lpList."') AND
  2315. user_id = $userId $sessionCondition ";
  2316. $res = Database::query($sql);
  2317. if (Database::num_rows($res) > 0) {
  2318. $list = [];
  2319. while ($row = Database::fetch_array($res)) {
  2320. $list[$row['lp_id']] = $row['progress'];
  2321. }
  2322. return $list;
  2323. }
  2324. return [];
  2325. }
  2326. /**
  2327. * Displays a progress bar
  2328. * completed so far.
  2329. *
  2330. * @param int $percentage Progress value to display
  2331. * @param string $text_add Text to display near the progress value
  2332. *
  2333. * @return string HTML string containing the progress bar
  2334. */
  2335. public static function get_progress_bar($percentage = -1, $text_add = '')
  2336. {
  2337. $text = $percentage.$text_add;
  2338. $output = '<div class="progress">
  2339. <div id="progress_bar_value"
  2340. class="progress-bar progress-bar-success" role="progressbar"
  2341. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2342. '.$text.'
  2343. </div>
  2344. </div>';
  2345. return $output;
  2346. }
  2347. /**
  2348. * @param string $mode can be '%' or 'abs'
  2349. * otherwise this value will be used $this->progress_bar_mode
  2350. *
  2351. * @return string
  2352. */
  2353. public function getProgressBar($mode = null)
  2354. {
  2355. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2356. return self::get_progress_bar($percentage, $text_add);
  2357. }
  2358. /**
  2359. * Gets the progress bar info to display inside the progress bar.
  2360. * Also used by scorm_api.php.
  2361. *
  2362. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2363. * we display a number of completed elements per total elements
  2364. * @param int $add Additional steps to fake as completed
  2365. *
  2366. * @return array Percentage or number and symbol (% or /xx)
  2367. */
  2368. public function get_progress_bar_text($mode = '', $add = 0)
  2369. {
  2370. if (empty($mode)) {
  2371. $mode = $this->progress_bar_mode;
  2372. }
  2373. $total_items = $this->getTotalItemsCountWithoutDirs();
  2374. $completeItems = $this->get_complete_items_count();
  2375. if ($add != 0) {
  2376. $completeItems += $add;
  2377. }
  2378. $text = '';
  2379. if ($completeItems > $total_items) {
  2380. $completeItems = $total_items;
  2381. }
  2382. $percentage = 0;
  2383. if ($mode == '%') {
  2384. if ($total_items > 0) {
  2385. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2386. }
  2387. $percentage = number_format($percentage, 0);
  2388. $text = '%';
  2389. } elseif ($mode === 'abs') {
  2390. $percentage = $completeItems;
  2391. $text = '/'.$total_items;
  2392. }
  2393. return [
  2394. $percentage,
  2395. $text,
  2396. ];
  2397. }
  2398. /**
  2399. * Gets the progress bar mode.
  2400. *
  2401. * @return string The progress bar mode attribute
  2402. */
  2403. public function get_progress_bar_mode()
  2404. {
  2405. if (!empty($this->progress_bar_mode)) {
  2406. return $this->progress_bar_mode;
  2407. }
  2408. return '%';
  2409. }
  2410. /**
  2411. * Gets the learnpath theme (remote or local).
  2412. *
  2413. * @return string Learnpath theme
  2414. */
  2415. public function get_theme()
  2416. {
  2417. if (!empty($this->theme)) {
  2418. return $this->theme;
  2419. }
  2420. return '';
  2421. }
  2422. /**
  2423. * Gets the learnpath session id.
  2424. *
  2425. * @return int
  2426. */
  2427. public function get_lp_session_id()
  2428. {
  2429. if (!empty($this->lp_session_id)) {
  2430. return (int) $this->lp_session_id;
  2431. }
  2432. return 0;
  2433. }
  2434. /**
  2435. * Gets the learnpath image.
  2436. *
  2437. * @return string Web URL of the LP image
  2438. */
  2439. public function get_preview_image()
  2440. {
  2441. if (!empty($this->preview_image)) {
  2442. return $this->preview_image;
  2443. }
  2444. return '';
  2445. }
  2446. /**
  2447. * @param string $size
  2448. * @param string $path_type
  2449. *
  2450. * @return bool|string
  2451. */
  2452. public function get_preview_image_path($size = null, $path_type = 'web')
  2453. {
  2454. $preview_image = $this->get_preview_image();
  2455. if (isset($preview_image) && !empty($preview_image)) {
  2456. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2457. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2458. if (isset($size)) {
  2459. $info = pathinfo($preview_image);
  2460. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2461. if (file_exists($image_sys_path.$image_custom_size)) {
  2462. if ($path_type == 'web') {
  2463. return $image_path.$image_custom_size;
  2464. } else {
  2465. return $image_sys_path.$image_custom_size;
  2466. }
  2467. }
  2468. } else {
  2469. if ($path_type == 'web') {
  2470. return $image_path.$preview_image;
  2471. } else {
  2472. return $image_sys_path.$preview_image;
  2473. }
  2474. }
  2475. }
  2476. return false;
  2477. }
  2478. /**
  2479. * Gets the learnpath author.
  2480. *
  2481. * @return string LP's author
  2482. */
  2483. public function get_author()
  2484. {
  2485. if (!empty($this->author)) {
  2486. return $this->author;
  2487. }
  2488. return '';
  2489. }
  2490. /**
  2491. * Gets hide table of contents.
  2492. *
  2493. * @return int
  2494. */
  2495. public function getHideTableOfContents()
  2496. {
  2497. return (int) $this->hide_toc_frame;
  2498. }
  2499. /**
  2500. * Generate a new prerequisites string for a given item. If this item was a sco and
  2501. * its prerequisites were strings (instead of IDs), then transform those strings into
  2502. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2503. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2504. * same rule as the scormExport() method.
  2505. *
  2506. * @param int $item_id Item ID
  2507. *
  2508. * @return string Prerequisites string ready for the export as SCORM
  2509. */
  2510. public function get_scorm_prereq_string($item_id)
  2511. {
  2512. if ($this->debug > 0) {
  2513. error_log('In learnpath::get_scorm_prereq_string()');
  2514. }
  2515. if (!is_object($this->items[$item_id])) {
  2516. return false;
  2517. }
  2518. /** @var learnpathItem $oItem */
  2519. $oItem = $this->items[$item_id];
  2520. $prereq = $oItem->get_prereq_string();
  2521. if (empty($prereq)) {
  2522. return '';
  2523. }
  2524. if (preg_match('/^\d+$/', $prereq) &&
  2525. isset($this->items[$prereq]) &&
  2526. is_object($this->items[$prereq])
  2527. ) {
  2528. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2529. // then simply return it (with the ITEM_ prefix).
  2530. //return 'ITEM_' . $prereq;
  2531. return $this->items[$prereq]->ref;
  2532. } else {
  2533. if (isset($this->refs_list[$prereq])) {
  2534. // It's a simple string item from which the ID can be found in the refs list,
  2535. // so we can transform it directly to an ID for export.
  2536. return $this->items[$this->refs_list[$prereq]]->ref;
  2537. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2538. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2539. } else {
  2540. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2541. // and replace them, one by one, by the internal IDs (chamilo db)
  2542. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2543. // by a space as well.
  2544. $find = [
  2545. '&',
  2546. '|',
  2547. '~',
  2548. '=',
  2549. '<>',
  2550. '{',
  2551. '}',
  2552. '*',
  2553. '(',
  2554. ')',
  2555. ];
  2556. $replace = [
  2557. ' ',
  2558. ' ',
  2559. ' ',
  2560. ' ',
  2561. ' ',
  2562. ' ',
  2563. ' ',
  2564. ' ',
  2565. ' ',
  2566. ' ',
  2567. ];
  2568. $prereq_mod = str_replace($find, $replace, $prereq);
  2569. $ids = explode(' ', $prereq_mod);
  2570. foreach ($ids as $id) {
  2571. $id = trim($id);
  2572. if (isset($this->refs_list[$id])) {
  2573. $prereq = preg_replace(
  2574. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2575. 'ITEM_'.$this->refs_list[$id],
  2576. $prereq
  2577. );
  2578. }
  2579. }
  2580. return $prereq;
  2581. }
  2582. }
  2583. }
  2584. /**
  2585. * Returns the XML DOM document's node.
  2586. *
  2587. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2588. * @param string $id The identifier to look for
  2589. *
  2590. * @return mixed The reference to the element found with that identifier. False if not found
  2591. */
  2592. public function get_scorm_xml_node(&$children, $id)
  2593. {
  2594. for ($i = 0; $i < $children->length; $i++) {
  2595. $item_temp = $children->item($i);
  2596. if ($item_temp->nodeName == 'item') {
  2597. if ($item_temp->getAttribute('identifier') == $id) {
  2598. return $item_temp;
  2599. }
  2600. }
  2601. $subchildren = $item_temp->childNodes;
  2602. if ($subchildren && $subchildren->length > 0) {
  2603. $val = $this->get_scorm_xml_node($subchildren, $id);
  2604. if (is_object($val)) {
  2605. return $val;
  2606. }
  2607. }
  2608. }
  2609. return false;
  2610. }
  2611. /**
  2612. * Gets the status list for all LP's items.
  2613. *
  2614. * @return array Array of [index] => [item ID => current status]
  2615. */
  2616. public function get_items_status_list()
  2617. {
  2618. $list = [];
  2619. foreach ($this->ordered_items as $item_id) {
  2620. $list[] = [
  2621. $item_id => $this->items[$item_id]->get_status(),
  2622. ];
  2623. }
  2624. return $list;
  2625. }
  2626. /**
  2627. * Return the number of interactions for the given learnpath Item View ID.
  2628. * This method can be used as static.
  2629. *
  2630. * @param int $lp_iv_id Item View ID
  2631. * @param int $course_id course id
  2632. *
  2633. * @return int
  2634. */
  2635. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2636. {
  2637. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2638. $lp_iv_id = (int) $lp_iv_id;
  2639. $course_id = (int) $course_id;
  2640. $sql = "SELECT count(*) FROM $table
  2641. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2642. $res = Database::query($sql);
  2643. $num = 0;
  2644. if (Database::num_rows($res)) {
  2645. $row = Database::fetch_array($res);
  2646. $num = $row[0];
  2647. }
  2648. return $num;
  2649. }
  2650. /**
  2651. * Return the interactions as an array for the given lp_iv_id.
  2652. * This method can be used as static.
  2653. *
  2654. * @param int $lp_iv_id Learnpath Item View ID
  2655. *
  2656. * @return array
  2657. *
  2658. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2659. */
  2660. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2661. {
  2662. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2663. $list = [];
  2664. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2665. $lp_iv_id = (int) $lp_iv_id;
  2666. if (empty($lp_iv_id) || empty($course_id)) {
  2667. return [];
  2668. }
  2669. $sql = "SELECT * FROM $table
  2670. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2671. ORDER BY order_id ASC";
  2672. $res = Database::query($sql);
  2673. $num = Database::num_rows($res);
  2674. if ($num > 0) {
  2675. $list[] = [
  2676. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2677. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2678. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2679. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2680. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2681. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2682. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2683. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2684. 'student_response_formatted' => '',
  2685. ];
  2686. while ($row = Database::fetch_array($res)) {
  2687. $studentResponseFormatted = urldecode($row['student_response']);
  2688. $content_student_response = explode('__|', $studentResponseFormatted);
  2689. if (count($content_student_response) > 0) {
  2690. if (count($content_student_response) >= 3) {
  2691. // Pop the element off the end of array.
  2692. array_pop($content_student_response);
  2693. }
  2694. $studentResponseFormatted = implode(',', $content_student_response);
  2695. }
  2696. $list[] = [
  2697. 'order_id' => $row['order_id'] + 1,
  2698. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2699. 'type' => $row['interaction_type'],
  2700. 'time' => $row['completion_time'],
  2701. 'correct_responses' => '', // Hide correct responses from students.
  2702. 'student_response' => $row['student_response'],
  2703. 'result' => $row['result'],
  2704. 'latency' => $row['latency'],
  2705. 'student_response_formatted' => $studentResponseFormatted,
  2706. ];
  2707. }
  2708. }
  2709. return $list;
  2710. }
  2711. /**
  2712. * Return the number of objectives for the given learnpath Item View ID.
  2713. * This method can be used as static.
  2714. *
  2715. * @param int $lp_iv_id Item View ID
  2716. * @param int $course_id Course ID
  2717. *
  2718. * @return int Number of objectives
  2719. */
  2720. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2721. {
  2722. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2723. $course_id = (int) $course_id;
  2724. $lp_iv_id = (int) $lp_iv_id;
  2725. $sql = "SELECT count(*) FROM $table
  2726. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2727. //@todo seems that this always returns 0
  2728. $res = Database::query($sql);
  2729. $num = 0;
  2730. if (Database::num_rows($res)) {
  2731. $row = Database::fetch_array($res);
  2732. $num = $row[0];
  2733. }
  2734. return $num;
  2735. }
  2736. /**
  2737. * Return the objectives as an array for the given lp_iv_id.
  2738. * This method can be used as static.
  2739. *
  2740. * @param int $lpItemViewId Learnpath Item View ID
  2741. * @param int $course_id
  2742. *
  2743. * @return array
  2744. *
  2745. * @todo Translate labels
  2746. */
  2747. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2748. {
  2749. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2750. $lpItemViewId = (int) $lpItemViewId;
  2751. if (empty($course_id) || empty($lpItemViewId)) {
  2752. return [];
  2753. }
  2754. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2755. $sql = "SELECT * FROM $table
  2756. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2757. ORDER BY order_id ASC";
  2758. $res = Database::query($sql);
  2759. $num = Database::num_rows($res);
  2760. $list = [];
  2761. if ($num > 0) {
  2762. $list[] = [
  2763. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2764. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2765. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2766. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2767. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2768. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2769. ];
  2770. while ($row = Database::fetch_array($res)) {
  2771. $list[] = [
  2772. 'order_id' => $row['order_id'] + 1,
  2773. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2774. 'score_raw' => $row['score_raw'],
  2775. 'score_max' => $row['score_max'],
  2776. 'score_min' => $row['score_min'],
  2777. 'status' => $row['status'],
  2778. ];
  2779. }
  2780. }
  2781. return $list;
  2782. }
  2783. /**
  2784. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2785. * used by get_html_toc() to be ready to display.
  2786. *
  2787. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2788. */
  2789. public function get_toc()
  2790. {
  2791. $toc = [];
  2792. foreach ($this->ordered_items as $item_id) {
  2793. // TODO: Change this link generation and use new function instead.
  2794. $toc[] = [
  2795. 'id' => $item_id,
  2796. 'title' => $this->items[$item_id]->get_title(),
  2797. 'status' => $this->items[$item_id]->get_status(),
  2798. 'level' => $this->items[$item_id]->get_level(),
  2799. 'type' => $this->items[$item_id]->get_type(),
  2800. 'description' => $this->items[$item_id]->get_description(),
  2801. 'path' => $this->items[$item_id]->get_path(),
  2802. 'parent' => $this->items[$item_id]->get_parent(),
  2803. ];
  2804. }
  2805. return $toc;
  2806. }
  2807. /**
  2808. * Generate and return the table of contents for this learnpath. The JS
  2809. * table returned is used inside of scorm_api.php.
  2810. *
  2811. * @param string $varname
  2812. *
  2813. * @return string A JS array variable construction
  2814. */
  2815. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2816. {
  2817. $toc = $varname.' = new Array();';
  2818. foreach ($this->ordered_items as $item_id) {
  2819. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2820. }
  2821. return $toc;
  2822. }
  2823. /**
  2824. * Gets the learning path type.
  2825. *
  2826. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2827. *
  2828. * @return mixed Type ID or name, depending on the parameter
  2829. */
  2830. public function get_type($get_name = false)
  2831. {
  2832. $res = false;
  2833. if (!empty($this->type) && (!$get_name)) {
  2834. $res = $this->type;
  2835. }
  2836. return $res;
  2837. }
  2838. /**
  2839. * Gets the learning path type as static method.
  2840. *
  2841. * @param int $lp_id
  2842. *
  2843. * @return mixed Type ID or name, depending on the parameter
  2844. */
  2845. public static function get_type_static($lp_id = 0)
  2846. {
  2847. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2848. $lp_id = (int) $lp_id;
  2849. $sql = "SELECT lp_type FROM $tbl_lp
  2850. WHERE iid = $lp_id";
  2851. $res = Database::query($sql);
  2852. if ($res === false) {
  2853. return null;
  2854. }
  2855. if (Database::num_rows($res) <= 0) {
  2856. return null;
  2857. }
  2858. $row = Database::fetch_array($res);
  2859. return $row['lp_type'];
  2860. }
  2861. /**
  2862. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2863. * This method can be used as abstract and is recursive.
  2864. *
  2865. * @param int $lp Learnpath ID
  2866. * @param int $parent Parent ID of the items to look for
  2867. * @param int $course_id
  2868. *
  2869. * @return array Ordered list of item IDs (empty array on error)
  2870. */
  2871. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2872. {
  2873. if (empty($course_id)) {
  2874. $course_id = api_get_course_int_id();
  2875. } else {
  2876. $course_id = (int) $course_id;
  2877. }
  2878. $list = [];
  2879. if (empty($lp)) {
  2880. return $list;
  2881. }
  2882. $lp = (int) $lp;
  2883. $parent = (int) $parent;
  2884. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2885. $sql = "SELECT iid FROM $tbl_lp_item
  2886. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2887. ORDER BY display_order";
  2888. $res = Database::query($sql);
  2889. while ($row = Database::fetch_array($res)) {
  2890. $sublist = self::get_flat_ordered_items_list(
  2891. $lp,
  2892. $row['iid'],
  2893. $course_id
  2894. );
  2895. $list[] = $row['iid'];
  2896. foreach ($sublist as $item) {
  2897. $list[] = $item;
  2898. }
  2899. }
  2900. return $list;
  2901. }
  2902. /**
  2903. * @return array
  2904. */
  2905. public static function getChapterTypes()
  2906. {
  2907. return [
  2908. 'dir',
  2909. ];
  2910. }
  2911. /**
  2912. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2913. *
  2914. * @param $tree
  2915. *
  2916. * @return array HTML TOC ready to display
  2917. */
  2918. public function getParentToc($tree)
  2919. {
  2920. if (empty($tree)) {
  2921. $tree = $this->get_toc();
  2922. }
  2923. $dirTypes = self::getChapterTypes();
  2924. $myCurrentId = $this->get_current_item_id();
  2925. $listParent = [];
  2926. $listChildren = [];
  2927. $listNotParent = [];
  2928. $list = [];
  2929. foreach ($tree as $subtree) {
  2930. if (in_array($subtree['type'], $dirTypes)) {
  2931. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2932. $subtree['children'] = $listChildren;
  2933. if (!empty($subtree['children'])) {
  2934. foreach ($subtree['children'] as $subItem) {
  2935. if ($subItem['id'] == $this->current) {
  2936. $subtree['parent_current'] = 'in';
  2937. $subtree['current'] = 'on';
  2938. }
  2939. }
  2940. }
  2941. $listParent[] = $subtree;
  2942. }
  2943. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2944. $classStatus = [
  2945. 'not attempted' => 'scorm_not_attempted',
  2946. 'incomplete' => 'scorm_not_attempted',
  2947. 'failed' => 'scorm_failed',
  2948. 'completed' => 'scorm_completed',
  2949. 'passed' => 'scorm_completed',
  2950. 'succeeded' => 'scorm_completed',
  2951. 'browsed' => 'scorm_completed',
  2952. ];
  2953. if (isset($classStatus[$subtree['status']])) {
  2954. $cssStatus = $classStatus[$subtree['status']];
  2955. }
  2956. $title = Security::remove_XSS($subtree['title']);
  2957. unset($subtree['title']);
  2958. if (empty($title)) {
  2959. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2960. }
  2961. $classStyle = null;
  2962. if ($subtree['id'] == $this->current) {
  2963. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2964. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2965. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2966. }
  2967. $subtree['title'] = $title;
  2968. $subtree['class'] = $classStyle.' '.$cssStatus;
  2969. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2970. $subtree['current_id'] = $myCurrentId;
  2971. $listNotParent[] = $subtree;
  2972. }
  2973. }
  2974. $list['are_parents'] = $listParent;
  2975. $list['not_parents'] = $listNotParent;
  2976. return $list;
  2977. }
  2978. /**
  2979. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2980. *
  2981. * @param array $tree
  2982. * @param int $id
  2983. * @param bool $parent
  2984. *
  2985. * @return array HTML TOC ready to display
  2986. */
  2987. public function getChildrenToc($tree, $id, $parent = true)
  2988. {
  2989. if (empty($tree)) {
  2990. $tree = $this->get_toc();
  2991. }
  2992. $dirTypes = self::getChapterTypes();
  2993. $currentItemId = $this->get_current_item_id();
  2994. $list = [];
  2995. $classStatus = [
  2996. 'not attempted' => 'scorm_not_attempted',
  2997. 'incomplete' => 'scorm_not_attempted',
  2998. 'failed' => 'scorm_failed',
  2999. 'completed' => 'scorm_completed',
  3000. 'passed' => 'scorm_completed',
  3001. 'succeeded' => 'scorm_completed',
  3002. 'browsed' => 'scorm_completed',
  3003. ];
  3004. foreach ($tree as $subtree) {
  3005. $subtree['tree'] = null;
  3006. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3007. if ($subtree['id'] == $this->current) {
  3008. $subtree['current'] = 'active';
  3009. } else {
  3010. $subtree['current'] = null;
  3011. }
  3012. if (isset($classStatus[$subtree['status']])) {
  3013. $cssStatus = $classStatus[$subtree['status']];
  3014. }
  3015. $title = Security::remove_XSS($subtree['title']);
  3016. unset($subtree['title']);
  3017. if (empty($title)) {
  3018. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3019. }
  3020. $classStyle = null;
  3021. if ($subtree['id'] == $this->current) {
  3022. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3023. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3024. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3025. }
  3026. if (in_array($subtree['type'], $dirTypes)) {
  3027. $subtree['title'] = stripslashes($title);
  3028. } else {
  3029. $subtree['title'] = $title;
  3030. $subtree['class'] = $classStyle.' '.$cssStatus;
  3031. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3032. $subtree['current_id'] = $currentItemId;
  3033. }
  3034. $list[] = $subtree;
  3035. }
  3036. }
  3037. return $list;
  3038. }
  3039. /**
  3040. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3041. *
  3042. * @param array $toc_list
  3043. *
  3044. * @return array HTML TOC ready to display
  3045. */
  3046. public function getListArrayToc($toc_list = [])
  3047. {
  3048. if (empty($toc_list)) {
  3049. $toc_list = $this->get_toc();
  3050. }
  3051. // Temporary variables.
  3052. $currentItemId = $this->get_current_item_id();
  3053. $list = [];
  3054. $arrayList = [];
  3055. $classStatus = [
  3056. 'not attempted' => 'scorm_not_attempted',
  3057. 'incomplete' => 'scorm_not_attempted',
  3058. 'failed' => 'scorm_failed',
  3059. 'completed' => 'scorm_completed',
  3060. 'passed' => 'scorm_completed',
  3061. 'succeeded' => 'scorm_completed',
  3062. 'browsed' => 'scorm_completed',
  3063. ];
  3064. foreach ($toc_list as $item) {
  3065. $list['id'] = $item['id'];
  3066. $list['status'] = $item['status'];
  3067. $cssStatus = null;
  3068. if (isset($classStatus[$item['status']])) {
  3069. $cssStatus = $classStatus[$item['status']];
  3070. }
  3071. $classStyle = ' ';
  3072. $dirTypes = self::getChapterTypes();
  3073. if (in_array($item['type'], $dirTypes)) {
  3074. $classStyle = 'scorm_item_section ';
  3075. }
  3076. if ($item['id'] == $this->current) {
  3077. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3078. } elseif (!in_array($item['type'], $dirTypes)) {
  3079. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3080. }
  3081. $title = $item['title'];
  3082. if (empty($title)) {
  3083. $title = self::rl_get_resource_name(
  3084. api_get_course_id(),
  3085. $this->get_id(),
  3086. $item['id']
  3087. );
  3088. }
  3089. $title = Security::remove_XSS($item['title']);
  3090. if (empty($item['description'])) {
  3091. $list['description'] = $title;
  3092. } else {
  3093. $list['description'] = $item['description'];
  3094. }
  3095. $list['class'] = $classStyle.' '.$cssStatus;
  3096. $list['level'] = $item['level'];
  3097. $list['type'] = $item['type'];
  3098. if (in_array($item['type'], $dirTypes)) {
  3099. $list['css_level'] = 'level_'.$item['level'];
  3100. } else {
  3101. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3102. }
  3103. if (in_array($item['type'], $dirTypes)) {
  3104. $list['title'] = stripslashes($title);
  3105. } else {
  3106. $list['title'] = stripslashes($title);
  3107. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3108. $list['current_id'] = $currentItemId;
  3109. }
  3110. $arrayList[] = $list;
  3111. }
  3112. return $arrayList;
  3113. }
  3114. /**
  3115. * Returns an HTML-formatted string ready to display with teacher buttons
  3116. * in LP view menu.
  3117. *
  3118. * @return string HTML TOC ready to display
  3119. */
  3120. public function get_teacher_toc_buttons()
  3121. {
  3122. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3123. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3124. $html = '';
  3125. if ($isAllow && $hideIcons == false) {
  3126. if ($this->get_lp_session_id() == api_get_session_id()) {
  3127. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3128. $html .= '<div class="btn-group">';
  3129. $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'>".
  3130. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3131. $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'>".
  3132. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3133. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3134. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3135. $html .= '</div>';
  3136. $html .= '</div>';
  3137. }
  3138. }
  3139. return $html;
  3140. }
  3141. /**
  3142. * Gets the learnpath maker name - generally the editor's name.
  3143. *
  3144. * @return string Learnpath maker name
  3145. */
  3146. public function get_maker()
  3147. {
  3148. if (!empty($this->maker)) {
  3149. return $this->maker;
  3150. }
  3151. return '';
  3152. }
  3153. /**
  3154. * Gets the learnpath name/title.
  3155. *
  3156. * @return string Learnpath name/title
  3157. */
  3158. public function get_name()
  3159. {
  3160. if (!empty($this->name)) {
  3161. return $this->name;
  3162. }
  3163. return 'N/A';
  3164. }
  3165. /**
  3166. * @return string
  3167. */
  3168. public function getNameNoTags()
  3169. {
  3170. return strip_tags($this->get_name());
  3171. }
  3172. /**
  3173. * Gets a link to the resource from the present location, depending on item ID.
  3174. *
  3175. * @param string $type Type of link expected
  3176. * @param int $item_id Learnpath item ID
  3177. * @param bool $provided_toc
  3178. *
  3179. * @return string $provided_toc Link to the lp_item resource
  3180. */
  3181. public function get_link($type = 'http', $item_id = 0, $provided_toc = false)
  3182. {
  3183. $course_id = $this->get_course_int_id();
  3184. $item_id = (int) $item_id;
  3185. if (empty($item_id)) {
  3186. $item_id = $this->get_current_item_id();
  3187. if (empty($item_id)) {
  3188. //still empty, this means there was no item_id given and we are not in an object context or
  3189. //the object property is empty, return empty link
  3190. $this->first();
  3191. return '';
  3192. }
  3193. }
  3194. $file = '';
  3195. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3196. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3197. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3198. $sql = "SELECT
  3199. l.lp_type as ltype,
  3200. l.path as lpath,
  3201. li.item_type as litype,
  3202. li.path as lipath,
  3203. li.parameters as liparams
  3204. FROM $lp_table l
  3205. INNER JOIN $lp_item_table li
  3206. ON (li.lp_id = l.iid)
  3207. WHERE
  3208. li.iid = $item_id
  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. // Now go through the specific cases to get the end of the path
  3238. // @todo Use constants instead of int values.
  3239. switch ($lp_type) {
  3240. case 1:
  3241. $file = self::rl_get_resource_link_for_learnpath(
  3242. $course_id,
  3243. $this->get_id(),
  3244. $item_id,
  3245. $this->get_view_id()
  3246. );
  3247. switch ($lp_item_type) {
  3248. case 'document':
  3249. // Shows a button to download the file instead of just downloading the file directly.
  3250. $documentPathInfo = pathinfo($file);
  3251. if (isset($documentPathInfo['extension'])) {
  3252. $parsed = parse_url($documentPathInfo['extension']);
  3253. if (isset($parsed['path'])) {
  3254. $extension = $parsed['path'];
  3255. $extensionsToDownload = [
  3256. 'zip',
  3257. 'ppt',
  3258. 'pptx',
  3259. 'ods',
  3260. 'xlsx',
  3261. 'xls',
  3262. 'csv',
  3263. 'doc',
  3264. 'docx',
  3265. 'dot',
  3266. ];
  3267. if (in_array($extension, $extensionsToDownload)) {
  3268. $file = api_get_path(WEB_CODE_PATH).
  3269. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3270. }
  3271. }
  3272. }
  3273. break;
  3274. case 'dir':
  3275. $file = 'lp_content.php?type=dir';
  3276. break;
  3277. case 'link':
  3278. if (Link::is_youtube_link($file)) {
  3279. $src = Link::get_youtube_video_id($file);
  3280. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3281. } elseif (Link::isVimeoLink($file)) {
  3282. $src = Link::getVimeoLinkId($file);
  3283. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3284. } else {
  3285. // If the current site is HTTPS and the link is
  3286. // HTTP, browsers will refuse opening the link
  3287. $urlId = api_get_current_access_url_id();
  3288. $url = api_get_access_url($urlId, false);
  3289. $protocol = substr($url['url'], 0, 5);
  3290. if ($protocol === 'https') {
  3291. $linkProtocol = substr($file, 0, 5);
  3292. if ($linkProtocol === 'http:') {
  3293. //this is the special intervention case
  3294. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3295. }
  3296. }
  3297. }
  3298. break;
  3299. case 'quiz':
  3300. // Check how much attempts of a exercise exits in lp
  3301. $lp_item_id = $this->get_current_item_id();
  3302. $lp_view_id = $this->get_view_id();
  3303. $prevent_reinit = null;
  3304. if (isset($this->items[$this->current])) {
  3305. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3306. }
  3307. if (empty($provided_toc)) {
  3308. if ($this->debug > 0) {
  3309. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3310. }
  3311. $list = $this->get_toc();
  3312. } else {
  3313. if ($this->debug > 0) {
  3314. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3315. }
  3316. $list = $provided_toc;
  3317. }
  3318. $type_quiz = false;
  3319. foreach ($list as $toc) {
  3320. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3321. $type_quiz = true;
  3322. }
  3323. }
  3324. if ($type_quiz) {
  3325. $lp_item_id = (int) $lp_item_id;
  3326. $lp_view_id = (int) $lp_view_id;
  3327. $sql = "SELECT count(*) FROM $lp_item_view_table
  3328. WHERE
  3329. c_id = $course_id AND
  3330. lp_item_id='".$lp_item_id."' AND
  3331. lp_view_id ='".$lp_view_id."' AND
  3332. status='completed'";
  3333. $result = Database::query($sql);
  3334. $row_count = Database:: fetch_row($result);
  3335. $count_item_view = (int) $row_count[0];
  3336. $not_multiple_attempt = 0;
  3337. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3338. $not_multiple_attempt = 1;
  3339. }
  3340. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3341. }
  3342. break;
  3343. }
  3344. $tmp_array = explode('/', $file);
  3345. $document_name = $tmp_array[count($tmp_array) - 1];
  3346. if (strpos($document_name, '_DELETED_')) {
  3347. $file = 'blank.php?error=document_deleted';
  3348. }
  3349. break;
  3350. case 2:
  3351. if ($this->debug > 2) {
  3352. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3353. }
  3354. if ($lp_item_type != 'dir') {
  3355. // Quite complex here:
  3356. // We want to make sure 'http://' (and similar) links can
  3357. // be loaded as is (withouth the Chamilo path in front) but
  3358. // some contents use this form: resource.htm?resource=http://blablabla
  3359. // which means we have to find a protocol at the path's start, otherwise
  3360. // it should not be considered as an external URL.
  3361. // if ($this->prerequisites_match($item_id)) {
  3362. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3363. if ($this->debug > 2) {
  3364. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3365. }
  3366. // Distant url, return as is.
  3367. $file = $lp_item_path;
  3368. } else {
  3369. if ($this->debug > 2) {
  3370. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3371. }
  3372. // Prevent getting untranslatable urls.
  3373. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3374. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3375. // Prepare the path.
  3376. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3377. // TODO: Fix this for urls with protocol header.
  3378. $file = str_replace('//', '/', $file);
  3379. $file = str_replace(':/', '://', $file);
  3380. if (substr($lp_path, -1) == '/') {
  3381. $lp_path = substr($lp_path, 0, -1);
  3382. }
  3383. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3384. // if file not found.
  3385. $decoded = html_entity_decode($lp_item_path);
  3386. list($decoded) = explode('?', $decoded);
  3387. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3388. $file = self::rl_get_resource_link_for_learnpath(
  3389. $course_id,
  3390. $this->get_id(),
  3391. $item_id,
  3392. $this->get_view_id()
  3393. );
  3394. if (empty($file)) {
  3395. $file = 'blank.php?error=document_not_found';
  3396. } else {
  3397. $tmp_array = explode('/', $file);
  3398. $document_name = $tmp_array[count($tmp_array) - 1];
  3399. if (strpos($document_name, '_DELETED_')) {
  3400. $file = 'blank.php?error=document_deleted';
  3401. } else {
  3402. $file = 'blank.php?error=document_not_found';
  3403. }
  3404. }
  3405. } else {
  3406. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3407. }
  3408. }
  3409. }
  3410. // We want to use parameters if they were defined in the imsmanifest
  3411. if (strpos($file, 'blank.php') === false) {
  3412. $lp_item_params = ltrim($lp_item_params, '?');
  3413. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3414. }
  3415. } else {
  3416. $file = 'lp_content.php?type=dir';
  3417. }
  3418. break;
  3419. case 3:
  3420. if ($this->debug > 2) {
  3421. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3422. }
  3423. // Formatting AICC HACP append URL.
  3424. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3425. if (!empty($lp_item_params)) {
  3426. $aicc_append .= $lp_item_params.'&';
  3427. }
  3428. if ($lp_item_type != 'dir') {
  3429. // Quite complex here:
  3430. // We want to make sure 'http://' (and similar) links can
  3431. // be loaded as is (withouth the Chamilo path in front) but
  3432. // some contents use this form: resource.htm?resource=http://blablabla
  3433. // which means we have to find a protocol at the path's start, otherwise
  3434. // it should not be considered as an external URL.
  3435. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3436. if ($this->debug > 2) {
  3437. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3438. }
  3439. // Distant url, return as is.
  3440. $file = $lp_item_path;
  3441. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3442. /*
  3443. if (stristr($file,'<servername>') !== false) {
  3444. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3445. }
  3446. */
  3447. if (stripos($file, '<servername>') !== false) {
  3448. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3449. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3450. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3451. }
  3452. $file .= $aicc_append;
  3453. } else {
  3454. if ($this->debug > 2) {
  3455. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3456. }
  3457. // Prevent getting untranslatable urls.
  3458. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3459. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3460. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3461. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3462. // TODO: Fix this for urls with protocol header.
  3463. $file = str_replace('//', '/', $file);
  3464. $file = str_replace(':/', '://', $file);
  3465. $file .= $aicc_append;
  3466. }
  3467. } else {
  3468. $file = 'lp_content.php?type=dir';
  3469. }
  3470. break;
  3471. case 4:
  3472. break;
  3473. default:
  3474. break;
  3475. }
  3476. // Replace &amp; by & because &amp; will break URL with params
  3477. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3478. }
  3479. if ($this->debug > 2) {
  3480. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3481. }
  3482. return $file;
  3483. }
  3484. /**
  3485. * Gets the latest usable view or generate a new one.
  3486. *
  3487. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3488. *
  3489. * @return int DB lp_view id
  3490. */
  3491. public function get_view($attempt_num = 0)
  3492. {
  3493. $search = '';
  3494. // Use $attempt_num to enable multi-views management (disabled so far).
  3495. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3496. $search = 'AND view_count = '.$attempt_num;
  3497. }
  3498. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3499. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3500. $course_id = api_get_course_int_id();
  3501. $sessionId = api_get_session_id();
  3502. $sql = "SELECT iid, view_count FROM $lp_view_table
  3503. WHERE
  3504. c_id = $course_id AND
  3505. lp_id = ".$this->get_id()." AND
  3506. user_id = ".$this->get_user_id()." AND
  3507. session_id = $sessionId
  3508. $search
  3509. ORDER BY view_count DESC";
  3510. $res = Database::query($sql);
  3511. if (Database::num_rows($res) > 0) {
  3512. $row = Database::fetch_array($res);
  3513. $this->lp_view_id = $row['iid'];
  3514. } elseif (!api_is_invitee()) {
  3515. // There is no database record, create one.
  3516. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3517. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3518. Database::query($sql);
  3519. $id = Database::insert_id();
  3520. $this->lp_view_id = $id;
  3521. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3522. Database::query($sql);
  3523. }
  3524. return $this->lp_view_id;
  3525. }
  3526. /**
  3527. * Gets the current view id.
  3528. *
  3529. * @return int View ID (from lp_view)
  3530. */
  3531. public function get_view_id()
  3532. {
  3533. if (!empty($this->lp_view_id)) {
  3534. return (int) $this->lp_view_id;
  3535. }
  3536. return 0;
  3537. }
  3538. /**
  3539. * Gets the update queue.
  3540. *
  3541. * @return array Array containing IDs of items to be updated by JavaScript
  3542. */
  3543. public function get_update_queue()
  3544. {
  3545. return $this->update_queue;
  3546. }
  3547. /**
  3548. * Gets the user ID.
  3549. *
  3550. * @return int User ID
  3551. */
  3552. public function get_user_id()
  3553. {
  3554. if (!empty($this->user_id)) {
  3555. return (int) $this->user_id;
  3556. }
  3557. return false;
  3558. }
  3559. /**
  3560. * Checks if any of the items has an audio element attached.
  3561. *
  3562. * @return bool True or false
  3563. */
  3564. public function has_audio()
  3565. {
  3566. $has = false;
  3567. foreach ($this->items as $i => $item) {
  3568. if (!empty($this->items[$i]->audio)) {
  3569. $has = true;
  3570. break;
  3571. }
  3572. }
  3573. return $has;
  3574. }
  3575. /**
  3576. * Moves an item up and down at its level.
  3577. *
  3578. * @param int $id Item to move up and down
  3579. * @param string $direction Direction 'up' or 'down'
  3580. *
  3581. * @return bool|int
  3582. */
  3583. public function move_item($id, $direction)
  3584. {
  3585. $course_id = api_get_course_int_id();
  3586. if (empty($id) || empty($direction)) {
  3587. return false;
  3588. }
  3589. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3590. $sql_sel = "SELECT *
  3591. FROM $tbl_lp_item
  3592. WHERE
  3593. iid = $id
  3594. ";
  3595. $res_sel = Database::query($sql_sel);
  3596. // Check if elem exists.
  3597. if (Database::num_rows($res_sel) < 1) {
  3598. return false;
  3599. }
  3600. // Gather data.
  3601. $row = Database::fetch_array($res_sel);
  3602. $previous = $row['previous_item_id'];
  3603. $next = $row['next_item_id'];
  3604. $display = $row['display_order'];
  3605. $parent = $row['parent_item_id'];
  3606. $lp = $row['lp_id'];
  3607. // Update the item (switch with previous/next one).
  3608. switch ($direction) {
  3609. case 'up':
  3610. if ($display > 1) {
  3611. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3612. WHERE iid = $previous";
  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. Database::query($sql_upd2);
  3626. }
  3627. // Update previous item (switch with current).
  3628. if ($previous != 0) {
  3629. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3630. next_item_id = $next,
  3631. previous_item_id = $id,
  3632. display_order = display_order +1
  3633. WHERE iid = $previous";
  3634. Database::query($sql_upd2);
  3635. }
  3636. // Update current item (switch with previous).
  3637. if ($id != 0) {
  3638. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3639. next_item_id = $previous,
  3640. previous_item_id = $previous_previous,
  3641. display_order = display_order-1
  3642. WHERE c_id = ".$course_id." AND id = $id";
  3643. Database::query($sql_upd2);
  3644. }
  3645. // Update next item (new previous item).
  3646. if (!empty($next)) {
  3647. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3648. WHERE iid = $next";
  3649. Database::query($sql_upd2);
  3650. }
  3651. $display = $display - 1;
  3652. }
  3653. break;
  3654. case 'down':
  3655. if ($next != 0) {
  3656. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3657. WHERE iid = $next";
  3658. $res_sel2 = Database::query($sql_sel2);
  3659. if (Database::num_rows($res_sel2) < 1) {
  3660. $next_next = 0;
  3661. }
  3662. // Gather data.
  3663. $row2 = Database::fetch_array($res_sel2);
  3664. $next_next = $row2['next_item_id'];
  3665. // Update previous item (switch with current).
  3666. if ($previous != 0) {
  3667. $sql_upd2 = "UPDATE $tbl_lp_item
  3668. SET next_item_id = $next
  3669. WHERE iid = $previous";
  3670. Database::query($sql_upd2);
  3671. }
  3672. // Update current item (switch with previous).
  3673. if ($id != 0) {
  3674. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3675. previous_item_id = $next,
  3676. next_item_id = $next_next,
  3677. display_order = display_order + 1
  3678. WHERE iid = $id";
  3679. Database::query($sql_upd2);
  3680. }
  3681. // Update next item (new previous item).
  3682. if ($next != 0) {
  3683. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3684. previous_item_id = $previous,
  3685. next_item_id = $id,
  3686. display_order = display_order-1
  3687. WHERE iid = $next";
  3688. Database::query($sql_upd2);
  3689. }
  3690. // Update next_next item (switch "previous" with current).
  3691. if ($next_next != 0) {
  3692. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3693. previous_item_id = $id
  3694. WHERE iid = $next_next";
  3695. Database::query($sql_upd2);
  3696. }
  3697. $display = $display + 1;
  3698. }
  3699. break;
  3700. default:
  3701. return false;
  3702. }
  3703. return $display;
  3704. }
  3705. /**
  3706. * Move a LP up (display_order).
  3707. *
  3708. * @param int $lp_id Learnpath ID
  3709. * @param int $categoryId Category ID
  3710. *
  3711. * @return bool
  3712. */
  3713. public static function move_up($lp_id, $categoryId = 0)
  3714. {
  3715. $courseId = api_get_course_int_id();
  3716. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3717. $categoryCondition = '';
  3718. if (!empty($categoryId)) {
  3719. $categoryId = (int) $categoryId;
  3720. $categoryCondition = " AND category_id = $categoryId";
  3721. }
  3722. $sql = "SELECT * FROM $lp_table
  3723. WHERE c_id = $courseId
  3724. $categoryCondition
  3725. ORDER BY display_order";
  3726. $res = Database::query($sql);
  3727. if ($res === false) {
  3728. return false;
  3729. }
  3730. $lps = [];
  3731. $lp_order = [];
  3732. $num = Database::num_rows($res);
  3733. // First check the order is correct, globally (might be wrong because
  3734. // of versions < 1.8.4)
  3735. if ($num > 0) {
  3736. $i = 1;
  3737. while ($row = Database::fetch_array($res)) {
  3738. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3739. $sql = "UPDATE $lp_table SET display_order = $i
  3740. WHERE iid = ".$row['iid'];
  3741. Database::query($sql);
  3742. }
  3743. $row['display_order'] = $i;
  3744. $lps[$row['iid']] = $row;
  3745. $lp_order[$i] = $row['iid'];
  3746. $i++;
  3747. }
  3748. }
  3749. if ($num > 1) { // If there's only one element, no need to sort.
  3750. $order = $lps[$lp_id]['display_order'];
  3751. if ($order > 1) { // If it's the first element, no need to move up.
  3752. $sql = "UPDATE $lp_table SET display_order = $order
  3753. WHERE iid = ".$lp_order[$order - 1];
  3754. Database::query($sql);
  3755. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3756. WHERE iid = $lp_id";
  3757. Database::query($sql);
  3758. }
  3759. }
  3760. return true;
  3761. }
  3762. /**
  3763. * Move a learnpath down (display_order).
  3764. *
  3765. * @param int $lp_id Learnpath ID
  3766. * @param int $categoryId Category ID
  3767. *
  3768. * @return bool
  3769. */
  3770. public static function move_down($lp_id, $categoryId = 0)
  3771. {
  3772. $courseId = api_get_course_int_id();
  3773. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3774. $categoryCondition = '';
  3775. if (!empty($categoryId)) {
  3776. $categoryId = (int) $categoryId;
  3777. $categoryCondition = " AND category_id = $categoryId";
  3778. }
  3779. $sql = "SELECT * FROM $lp_table
  3780. WHERE c_id = $courseId
  3781. $categoryCondition
  3782. ORDER BY display_order";
  3783. $res = Database::query($sql);
  3784. if ($res === false) {
  3785. return false;
  3786. }
  3787. $lps = [];
  3788. $lp_order = [];
  3789. $num = Database::num_rows($res);
  3790. $max = 0;
  3791. // First check the order is correct, globally (might be wrong because
  3792. // of versions < 1.8.4).
  3793. if ($num > 0) {
  3794. $i = 1;
  3795. while ($row = Database::fetch_array($res)) {
  3796. $max = $i;
  3797. if ($row['display_order'] != $i) {
  3798. // If we find a gap in the order, we need to fix it.
  3799. $sql = "UPDATE $lp_table SET display_order = $i
  3800. WHERE iid = ".$row['iid'];
  3801. Database::query($sql);
  3802. }
  3803. $row['display_order'] = $i;
  3804. $lps[$row['iid']] = $row;
  3805. $lp_order[$i] = $row['iid'];
  3806. $i++;
  3807. }
  3808. }
  3809. if ($num > 1) { // If there's only one element, no need to sort.
  3810. $order = $lps[$lp_id]['display_order'];
  3811. if ($order < $max) { // If it's the first element, no need to move up.
  3812. $sql = "UPDATE $lp_table SET display_order = $order
  3813. WHERE iid = ".$lp_order[$order + 1];
  3814. Database::query($sql);
  3815. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3816. WHERE iid = $lp_id";
  3817. Database::query($sql);
  3818. }
  3819. }
  3820. return true;
  3821. }
  3822. /**
  3823. * Updates learnpath attributes to point to the next element
  3824. * The last part is similar to set_current_item but processing the other way around.
  3825. */
  3826. public function next()
  3827. {
  3828. if ($this->debug > 0) {
  3829. error_log('In learnpath::next()', 0);
  3830. }
  3831. $this->last = $this->get_current_item_id();
  3832. $this->items[$this->last]->save(
  3833. false,
  3834. $this->prerequisites_match($this->last)
  3835. );
  3836. $this->autocomplete_parents($this->last);
  3837. $new_index = $this->get_next_index();
  3838. if ($this->debug > 2) {
  3839. error_log('New index: '.$new_index, 0);
  3840. }
  3841. $this->index = $new_index;
  3842. if ($this->debug > 2) {
  3843. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3844. }
  3845. $this->current = $this->ordered_items[$new_index];
  3846. if ($this->debug > 2) {
  3847. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3848. }
  3849. }
  3850. /**
  3851. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3852. * class, this might be redefined to allow several behaviours depending on the document type.
  3853. *
  3854. * @param int $id Resource ID
  3855. */
  3856. public function open($id)
  3857. {
  3858. // TODO:
  3859. // set the current resource attribute to this resource
  3860. // switch on element type (redefine in child class?)
  3861. // set status for this item to "opened"
  3862. // start timer
  3863. // initialise score
  3864. $this->index = 0; //or = the last item seen (see $this->last)
  3865. }
  3866. /**
  3867. * Check that all prerequisites are fulfilled. Returns true and an
  3868. * empty string on success, returns false
  3869. * and the prerequisite string on error.
  3870. * This function is based on the rules for aicc_script language as
  3871. * described in the SCORM 1.2 CAM documentation page 108.
  3872. *
  3873. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3874. *
  3875. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  3876. * string otherwise
  3877. */
  3878. public function prerequisites_match($itemId = null)
  3879. {
  3880. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3881. if ($allow) {
  3882. if (api_is_allowed_to_edit() ||
  3883. api_is_platform_admin(true) ||
  3884. api_is_drh() ||
  3885. api_is_coach(api_get_session_id(), api_get_course_int_id())
  3886. ) {
  3887. return true;
  3888. }
  3889. }
  3890. $debug = $this->debug;
  3891. if ($debug > 0) {
  3892. error_log('In learnpath::prerequisites_match()');
  3893. }
  3894. if (empty($itemId)) {
  3895. $itemId = $this->current;
  3896. }
  3897. $currentItem = $this->getItem($itemId);
  3898. if ($currentItem) {
  3899. if ($this->type == 2) {
  3900. // Getting prereq from scorm
  3901. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3902. } else {
  3903. $prereq_string = $currentItem->get_prereq_string();
  3904. }
  3905. if (empty($prereq_string)) {
  3906. if ($debug > 0) {
  3907. error_log('Found prereq_string is empty return true');
  3908. }
  3909. return true;
  3910. }
  3911. // Clean spaces.
  3912. $prereq_string = str_replace(' ', '', $prereq_string);
  3913. if ($debug > 0) {
  3914. error_log('Found prereq_string: '.$prereq_string, 0);
  3915. }
  3916. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3917. $result = $currentItem->parse_prereq(
  3918. $prereq_string,
  3919. $this->items,
  3920. $this->refs_list,
  3921. $this->get_user_id()
  3922. );
  3923. if ($result === false) {
  3924. $this->set_error_msg($currentItem->prereq_alert);
  3925. }
  3926. } else {
  3927. $result = true;
  3928. if ($debug > 1) {
  3929. error_log('$this->items['.$itemId.'] was not an object', 0);
  3930. }
  3931. }
  3932. if ($debug > 1) {
  3933. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3934. }
  3935. return $result;
  3936. }
  3937. /**
  3938. * Updates learnpath attributes to point to the previous element
  3939. * The last part is similar to set_current_item but processing the other way around.
  3940. */
  3941. public function previous()
  3942. {
  3943. $this->last = $this->get_current_item_id();
  3944. $this->items[$this->last]->save(
  3945. false,
  3946. $this->prerequisites_match($this->last)
  3947. );
  3948. $this->autocomplete_parents($this->last);
  3949. $new_index = $this->get_previous_index();
  3950. $this->index = $new_index;
  3951. $this->current = $this->ordered_items[$new_index];
  3952. }
  3953. /**
  3954. * Publishes a learnpath. This basically means show or hide the learnpath
  3955. * to normal users.
  3956. * Can be used as abstract.
  3957. *
  3958. * @param int $lp_id Learnpath ID
  3959. * @param int $set_visibility New visibility
  3960. *
  3961. * @return bool
  3962. */
  3963. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3964. {
  3965. $action = 'visible';
  3966. if ($set_visibility != 1) {
  3967. $action = 'invisible';
  3968. self::toggle_publish($lp_id, 'i');
  3969. }
  3970. return api_item_property_update(
  3971. api_get_course_info(),
  3972. TOOL_LEARNPATH,
  3973. $lp_id,
  3974. $action,
  3975. api_get_user_id()
  3976. );
  3977. }
  3978. /**
  3979. * Publishes a learnpath category.
  3980. * This basically means show or hide the learnpath category to normal users.
  3981. *
  3982. * @param int $id
  3983. * @param int $visibility
  3984. *
  3985. * @throws \Doctrine\ORM\NonUniqueResultException
  3986. * @throws \Doctrine\ORM\ORMException
  3987. * @throws \Doctrine\ORM\OptimisticLockException
  3988. * @throws \Doctrine\ORM\TransactionRequiredException
  3989. *
  3990. * @return bool
  3991. */
  3992. public static function toggleCategoryVisibility($id, $visibility = 1)
  3993. {
  3994. $action = 'visible';
  3995. if ($visibility != 1) {
  3996. $action = 'invisible';
  3997. $list = new LearnpathList(
  3998. api_get_user_id(),
  3999. null,
  4000. null,
  4001. null,
  4002. false,
  4003. $id
  4004. );
  4005. $lpList = $list->get_flat_list();
  4006. foreach ($lpList as $lp) {
  4007. self::toggle_visibility($lp['iid'], 0);
  4008. }
  4009. self::toggleCategoryPublish($id, 0);
  4010. }
  4011. return api_item_property_update(
  4012. api_get_course_info(),
  4013. TOOL_LEARNPATH_CATEGORY,
  4014. $id,
  4015. $action,
  4016. api_get_user_id()
  4017. );
  4018. }
  4019. /**
  4020. * Publishes a learnpath. This basically means show or hide the learnpath
  4021. * on the course homepage
  4022. * Can be used as abstract.
  4023. *
  4024. * @param int $lp_id Learnpath id
  4025. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4026. *
  4027. * @return bool
  4028. */
  4029. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4030. {
  4031. $course_id = api_get_course_int_id();
  4032. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4033. $lp_id = (int) $lp_id;
  4034. $sql = "SELECT * FROM $tbl_lp
  4035. WHERE iid = $lp_id";
  4036. $result = Database::query($sql);
  4037. if (Database::num_rows($result)) {
  4038. $row = Database::fetch_array($result);
  4039. $name = Database::escape_string($row['name']);
  4040. if ($set_visibility == 'i') {
  4041. $v = 0;
  4042. }
  4043. if ($set_visibility == 'v') {
  4044. $v = 1;
  4045. }
  4046. $session_id = api_get_session_id();
  4047. $session_condition = api_get_session_condition($session_id);
  4048. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4049. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4050. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4051. $sql = "SELECT * FROM $tbl_tool
  4052. WHERE
  4053. c_id = $course_id AND
  4054. (link = '$link' OR link = '$oldLink') AND
  4055. image = 'scormbuilder.gif' AND
  4056. (
  4057. link LIKE '$link%' OR
  4058. link LIKE '$oldLink%'
  4059. )
  4060. $session_condition
  4061. ";
  4062. $result = Database::query($sql);
  4063. $num = Database::num_rows($result);
  4064. if ($set_visibility == 'i' && $num > 0) {
  4065. $sql = "DELETE FROM $tbl_tool
  4066. WHERE
  4067. c_id = $course_id AND
  4068. (link = '$link' OR link = '$oldLink') AND
  4069. image='scormbuilder.gif'
  4070. $session_condition";
  4071. Database::query($sql);
  4072. } elseif ($set_visibility == 'v' && $num == 0) {
  4073. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4074. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4075. Database::query($sql);
  4076. $insertId = Database::insert_id();
  4077. if ($insertId) {
  4078. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4079. Database::query($sql);
  4080. }
  4081. } elseif ($set_visibility == 'v' && $num > 0) {
  4082. $sql = "UPDATE $tbl_tool SET
  4083. c_id = $course_id,
  4084. name = '$name',
  4085. link = '$link',
  4086. image = 'scormbuilder.gif',
  4087. visibility = '$v',
  4088. admin = '0',
  4089. address = 'pastillegris.gif',
  4090. added_tool = 0,
  4091. session_id = $session_id
  4092. WHERE
  4093. c_id = ".$course_id." AND
  4094. (link = '$link' OR link = '$oldLink') AND
  4095. image='scormbuilder.gif'
  4096. $session_condition
  4097. ";
  4098. Database::query($sql);
  4099. } else {
  4100. // Parameter and database incompatible, do nothing, exit.
  4101. return false;
  4102. }
  4103. } else {
  4104. return false;
  4105. }
  4106. }
  4107. /**
  4108. * Publishes a learnpath.
  4109. * Show or hide the learnpath category on the course homepage.
  4110. *
  4111. * @param int $id
  4112. * @param int $setVisibility
  4113. *
  4114. * @throws \Doctrine\ORM\NonUniqueResultException
  4115. * @throws \Doctrine\ORM\ORMException
  4116. * @throws \Doctrine\ORM\OptimisticLockException
  4117. * @throws \Doctrine\ORM\TransactionRequiredException
  4118. *
  4119. * @return bool
  4120. */
  4121. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4122. {
  4123. $courseId = api_get_course_int_id();
  4124. $sessionId = api_get_session_id();
  4125. $sessionCondition = api_get_session_condition(
  4126. $sessionId,
  4127. true,
  4128. false,
  4129. 't.sessionId'
  4130. );
  4131. $em = Database::getManager();
  4132. /** @var CLpCategory $category */
  4133. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4134. if (!$category) {
  4135. return false;
  4136. }
  4137. if (empty($courseId)) {
  4138. return false;
  4139. }
  4140. $link = self::getCategoryLinkForTool($id);
  4141. /** @var CTool $tool */
  4142. $tool = $em->createQuery("
  4143. SELECT t FROM ChamiloCourseBundle:CTool t
  4144. WHERE
  4145. t.cId = :course AND
  4146. t.link = :link1 AND
  4147. t.image = 'lp_category.gif' AND
  4148. t.link LIKE :link2
  4149. $sessionCondition
  4150. ")
  4151. ->setParameters([
  4152. 'course' => (int) $courseId,
  4153. 'link1' => $link,
  4154. 'link2' => "$link%",
  4155. ])
  4156. ->getOneOrNullResult();
  4157. if ($setVisibility == 0 && $tool) {
  4158. $em->remove($tool);
  4159. $em->flush();
  4160. return true;
  4161. }
  4162. if ($setVisibility == 1 && !$tool) {
  4163. $tool = new CTool();
  4164. $tool
  4165. ->setCategory('authoring')
  4166. ->setCId($courseId)
  4167. ->setName(strip_tags($category->getName()))
  4168. ->setLink($link)
  4169. ->setImage('lp_category.gif')
  4170. ->setVisibility(1)
  4171. ->setAdmin(0)
  4172. ->setAddress('pastillegris.gif')
  4173. ->setAddedTool(0)
  4174. ->setSessionId($sessionId)
  4175. ->setTarget('_self');
  4176. $em->persist($tool);
  4177. $em->flush();
  4178. $tool->setId($tool->getIid());
  4179. $em->persist($tool);
  4180. $em->flush();
  4181. return true;
  4182. }
  4183. if ($setVisibility == 1 && $tool) {
  4184. $tool
  4185. ->setName(strip_tags($category->getName()))
  4186. ->setVisibility(1);
  4187. $em->persist($tool);
  4188. $em->flush();
  4189. return true;
  4190. }
  4191. return false;
  4192. }
  4193. /**
  4194. * Check if the learnpath category is visible for a user.
  4195. *
  4196. * @param CLpCategory $category
  4197. * @param User $user
  4198. * @param int
  4199. * @param int
  4200. *
  4201. * @return bool
  4202. */
  4203. public static function categoryIsVisibleForStudent(
  4204. CLpCategory $category,
  4205. User $user,
  4206. $courseId = 0,
  4207. $sessionId = 0
  4208. ) {
  4209. $subscriptionSettings = self::getSubscriptionSettings();
  4210. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4211. return true;
  4212. }
  4213. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4214. if ($isAllowedToEdit) {
  4215. return true;
  4216. }
  4217. if (empty($category)) {
  4218. return false;
  4219. }
  4220. $users = $category->getUsers();
  4221. if (empty($users) || !$users->count()) {
  4222. return true;
  4223. }
  4224. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4225. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4226. if ($category->hasUserAdded($user)) {
  4227. return true;
  4228. }
  4229. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4230. if (!empty($groups)) {
  4231. $em = Database::getManager();
  4232. /** @var ItemPropertyRepository $itemRepo */
  4233. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4234. /** @var CourseRepository $courseRepo */
  4235. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4236. $session = null;
  4237. if (!empty($sessionId)) {
  4238. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4239. }
  4240. $course = $courseRepo->find($courseId);
  4241. // Subscribed groups to a LP
  4242. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4243. TOOL_LEARNPATH_CATEGORY,
  4244. $category->getId(),
  4245. $course,
  4246. $session
  4247. );
  4248. if (!empty($subscribedGroupsInLp)) {
  4249. $groups = array_column($groups, 'iid');
  4250. /** @var CItemProperty $item */
  4251. foreach ($subscribedGroupsInLp as $item) {
  4252. if ($item->getGroup() &&
  4253. in_array($item->getGroup()->getId(), $groups)
  4254. ) {
  4255. return true;
  4256. }
  4257. }
  4258. }
  4259. }
  4260. return false;
  4261. }
  4262. /**
  4263. * Check if a learnpath category is published as course tool.
  4264. *
  4265. * @param CLpCategory $category
  4266. * @param int $courseId
  4267. *
  4268. * @return bool
  4269. */
  4270. public static function categoryIsPublished(
  4271. CLpCategory $category,
  4272. $courseId
  4273. ) {
  4274. $link = self::getCategoryLinkForTool($category->getId());
  4275. $em = Database::getManager();
  4276. $tools = $em
  4277. ->createQuery("
  4278. SELECT t FROM ChamiloCourseBundle:CTool t
  4279. WHERE t.cId = :course AND
  4280. t.name = :name AND
  4281. t.image = 'lp_category.gif' AND
  4282. t.link LIKE :link
  4283. ")
  4284. ->setParameters([
  4285. 'course' => $courseId,
  4286. 'name' => strip_tags($category->getName()),
  4287. 'link' => "$link%",
  4288. ])
  4289. ->getResult();
  4290. /** @var CTool $tool */
  4291. $tool = current($tools);
  4292. return $tool ? $tool->getVisibility() : false;
  4293. }
  4294. /**
  4295. * Restart the whole learnpath. Return the URL of the first element.
  4296. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4297. * To use a similar method statically, use the create_new_attempt() method.
  4298. *
  4299. * @return bool
  4300. */
  4301. public function restart()
  4302. {
  4303. if ($this->debug > 0) {
  4304. error_log('In learnpath::restart()', 0);
  4305. }
  4306. // TODO
  4307. // Call autosave method to save the current progress.
  4308. //$this->index = 0;
  4309. if (api_is_invitee()) {
  4310. return false;
  4311. }
  4312. $session_id = api_get_session_id();
  4313. $course_id = api_get_course_int_id();
  4314. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4315. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4316. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4317. if ($this->debug > 2) {
  4318. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4319. }
  4320. Database::query($sql);
  4321. $view_id = Database::insert_id();
  4322. if ($view_id) {
  4323. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4324. Database::query($sql);
  4325. $this->lp_view_id = $view_id;
  4326. $this->attempt = $this->attempt + 1;
  4327. } else {
  4328. $this->error = 'Could not insert into item_view table...';
  4329. return false;
  4330. }
  4331. $this->autocomplete_parents($this->current);
  4332. foreach ($this->items as $index => $dummy) {
  4333. $this->items[$index]->restart();
  4334. $this->items[$index]->set_lp_view($this->lp_view_id);
  4335. }
  4336. $this->first();
  4337. return true;
  4338. }
  4339. /**
  4340. * Saves the current item.
  4341. *
  4342. * @return bool
  4343. */
  4344. public function save_current()
  4345. {
  4346. $debug = $this->debug;
  4347. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4348. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4349. if ($debug) {
  4350. error_log('save_current() saving item '.$this->current, 0);
  4351. error_log(''.print_r($this->items, true), 0);
  4352. }
  4353. if (isset($this->items[$this->current]) &&
  4354. is_object($this->items[$this->current])
  4355. ) {
  4356. if ($debug) {
  4357. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4358. }
  4359. $res = $this->items[$this->current]->save(
  4360. false,
  4361. $this->prerequisites_match($this->current)
  4362. );
  4363. $this->autocomplete_parents($this->current);
  4364. $status = $this->items[$this->current]->get_status();
  4365. $this->update_queue[$this->current] = $status;
  4366. if ($debug) {
  4367. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4368. }
  4369. return $res;
  4370. }
  4371. return false;
  4372. }
  4373. /**
  4374. * Saves the given item.
  4375. *
  4376. * @param int $item_id Optional (will take from $_REQUEST if null)
  4377. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4378. *
  4379. * @return bool
  4380. */
  4381. public function save_item($item_id = null, $from_outside = true)
  4382. {
  4383. $debug = $this->debug;
  4384. if ($debug) {
  4385. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4386. }
  4387. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4388. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4389. if (empty($item_id)) {
  4390. $item_id = (int) $_REQUEST['id'];
  4391. }
  4392. if (empty($item_id)) {
  4393. $item_id = $this->get_current_item_id();
  4394. }
  4395. if (isset($this->items[$item_id]) &&
  4396. is_object($this->items[$item_id])
  4397. ) {
  4398. if ($debug) {
  4399. error_log('Object exists');
  4400. }
  4401. // Saving the item.
  4402. $res = $this->items[$item_id]->save(
  4403. $from_outside,
  4404. $this->prerequisites_match($item_id)
  4405. );
  4406. if ($debug) {
  4407. error_log('update_queue before:');
  4408. error_log(print_r($this->update_queue, 1));
  4409. }
  4410. $this->autocomplete_parents($item_id);
  4411. $status = $this->items[$item_id]->get_status();
  4412. $this->update_queue[$item_id] = $status;
  4413. if ($debug) {
  4414. error_log('get_status(): '.$status);
  4415. error_log('update_queue after:');
  4416. error_log(print_r($this->update_queue, 1));
  4417. }
  4418. return $res;
  4419. }
  4420. return false;
  4421. }
  4422. /**
  4423. * Saves the last item seen's ID only in case.
  4424. */
  4425. public function save_last()
  4426. {
  4427. $course_id = api_get_course_int_id();
  4428. $debug = $this->debug;
  4429. if ($debug) {
  4430. error_log('In learnpath::save_last()', 0);
  4431. }
  4432. $session_condition = api_get_session_condition(
  4433. api_get_session_id(),
  4434. true,
  4435. false
  4436. );
  4437. $table = Database::get_course_table(TABLE_LP_VIEW);
  4438. if (isset($this->current) && !api_is_invitee()) {
  4439. if ($debug) {
  4440. error_log('Saving current item ('.$this->current.') for later review', 0);
  4441. }
  4442. $sql = "UPDATE $table SET
  4443. last_item = ".$this->get_current_item_id()."
  4444. WHERE
  4445. c_id = $course_id AND
  4446. lp_id = ".$this->get_id()." AND
  4447. user_id = ".$this->get_user_id()." ".$session_condition;
  4448. if ($debug) {
  4449. error_log('Saving last item seen : '.$sql, 0);
  4450. }
  4451. Database::query($sql);
  4452. }
  4453. if (!api_is_invitee()) {
  4454. // Save progress.
  4455. list($progress) = $this->get_progress_bar_text('%');
  4456. if ($progress >= 0 && $progress <= 100) {
  4457. $progress = (int) $progress;
  4458. $sql = "UPDATE $table SET
  4459. progress = $progress
  4460. WHERE
  4461. c_id = $course_id AND
  4462. lp_id = ".$this->get_id()." AND
  4463. user_id = ".$this->get_user_id()." ".$session_condition;
  4464. // Ignore errors as some tables might not have the progress field just yet.
  4465. Database::query($sql);
  4466. $this->progress_db = $progress;
  4467. }
  4468. }
  4469. }
  4470. /**
  4471. * Sets the current item ID (checks if valid and authorized first).
  4472. *
  4473. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4474. */
  4475. public function set_current_item($item_id = null)
  4476. {
  4477. $debug = $this->debug;
  4478. if ($debug) {
  4479. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4480. }
  4481. if (empty($item_id)) {
  4482. if ($debug) {
  4483. error_log('No new current item given, ignore...', 0);
  4484. }
  4485. // Do nothing.
  4486. } else {
  4487. if ($debug) {
  4488. error_log('New current item given is '.$item_id.'...', 0);
  4489. }
  4490. if (is_numeric($item_id)) {
  4491. $item_id = (int) $item_id;
  4492. // TODO: Check in database here.
  4493. $this->last = $this->current;
  4494. $this->current = $item_id;
  4495. // TODO: Update $this->index as well.
  4496. foreach ($this->ordered_items as $index => $item) {
  4497. if ($item == $this->current) {
  4498. $this->index = $index;
  4499. break;
  4500. }
  4501. }
  4502. if ($debug) {
  4503. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4504. }
  4505. } else {
  4506. if ($debug) {
  4507. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4508. }
  4509. }
  4510. }
  4511. }
  4512. /**
  4513. * Sets the encoding.
  4514. *
  4515. * @param string $enc New encoding
  4516. *
  4517. * @return bool
  4518. *
  4519. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4520. */
  4521. public function set_encoding($enc = 'UTF-8')
  4522. {
  4523. $enc = api_refine_encoding_id($enc);
  4524. if (empty($enc)) {
  4525. $enc = api_get_system_encoding();
  4526. }
  4527. if (api_is_encoding_supported($enc)) {
  4528. $lp = $this->get_id();
  4529. if ($lp != 0) {
  4530. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4531. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4532. WHERE iid = ".$lp;
  4533. $res = Database::query($sql);
  4534. return $res;
  4535. }
  4536. }
  4537. return false;
  4538. }
  4539. /**
  4540. * Sets the JS lib setting in the database directly.
  4541. * This is the JavaScript library file this lp needs to load on startup.
  4542. *
  4543. * @param string $lib Proximity setting
  4544. *
  4545. * @return bool True on update success. False otherwise.
  4546. */
  4547. public function set_jslib($lib = '')
  4548. {
  4549. $lp = $this->get_id();
  4550. if ($lp != 0) {
  4551. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4552. $lib = Database::escape_string($lib);
  4553. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4554. WHERE iid = $lp";
  4555. $res = Database::query($sql);
  4556. return $res;
  4557. }
  4558. return false;
  4559. }
  4560. /**
  4561. * Sets the name of the LP maker (publisher) (and save).
  4562. *
  4563. * @param string $name Optional string giving the new content_maker of this learnpath
  4564. *
  4565. * @return bool True
  4566. */
  4567. public function set_maker($name = '')
  4568. {
  4569. if (empty($name)) {
  4570. return false;
  4571. }
  4572. $this->maker = $name;
  4573. $table = Database::get_course_table(TABLE_LP_MAIN);
  4574. $lp_id = $this->get_id();
  4575. $sql = "UPDATE $table SET
  4576. content_maker = '".Database::escape_string($this->maker)."'
  4577. WHERE iid = $lp_id";
  4578. Database::query($sql);
  4579. return true;
  4580. }
  4581. /**
  4582. * Sets the name of the current learnpath (and save).
  4583. *
  4584. * @param string $name Optional string giving the new name of this learnpath
  4585. *
  4586. * @return bool True/False
  4587. */
  4588. public function set_name($name = null)
  4589. {
  4590. if (empty($name)) {
  4591. return false;
  4592. }
  4593. $this->name = Database::escape_string($name);
  4594. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4595. $lp_id = $this->get_id();
  4596. $course_id = $this->course_info['real_id'];
  4597. $sql = "UPDATE $lp_table SET
  4598. name = '".Database::escape_string($this->name)."'
  4599. WHERE iid = $lp_id";
  4600. $result = Database::query($sql);
  4601. // If the lp is visible on the homepage, change his name there.
  4602. if (Database::affected_rows($result)) {
  4603. $session_id = api_get_session_id();
  4604. $session_condition = api_get_session_condition($session_id);
  4605. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4606. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4607. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4608. WHERE
  4609. c_id = $course_id AND
  4610. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4611. Database::query($sql);
  4612. return true;
  4613. }
  4614. return false;
  4615. }
  4616. /**
  4617. * Set index specified prefix terms for all items in this path.
  4618. *
  4619. * @param string $terms_string Comma-separated list of terms
  4620. * @param string $prefix Xapian term prefix
  4621. *
  4622. * @return bool False on error, true otherwise
  4623. */
  4624. public function set_terms_by_prefix($terms_string, $prefix)
  4625. {
  4626. $course_id = api_get_course_int_id();
  4627. if (api_get_setting('search_enabled') !== 'true') {
  4628. return false;
  4629. }
  4630. if (!extension_loaded('xapian')) {
  4631. return false;
  4632. }
  4633. $terms_string = trim($terms_string);
  4634. $terms = explode(',', $terms_string);
  4635. array_walk($terms, 'trim_value');
  4636. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4637. // Don't do anything if no change, verify only at DB, not the search engine.
  4638. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4639. return false;
  4640. }
  4641. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4642. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4643. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4644. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4645. $lp_id = (int) $_POST['lp_id'];
  4646. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4647. $result = Database::query($sql);
  4648. $di = new ChamiloIndexer();
  4649. while ($lp_item = Database::fetch_array($result)) {
  4650. // Get search_did.
  4651. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4652. $sql = 'SELECT * FROM %s
  4653. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4654. LIMIT 1';
  4655. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4656. //echo $sql; echo '<br>';
  4657. $res = Database::query($sql);
  4658. if (Database::num_rows($res) > 0) {
  4659. $se_ref = Database::fetch_array($res);
  4660. // Compare terms.
  4661. $doc = $di->get_document($se_ref['search_did']);
  4662. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4663. $xterms = [];
  4664. foreach ($xapian_terms as $xapian_term) {
  4665. $xterms[] = substr($xapian_term['name'], 1);
  4666. }
  4667. $dterms = $terms;
  4668. $missing_terms = array_diff($dterms, $xterms);
  4669. $deprecated_terms = array_diff($xterms, $dterms);
  4670. // Save it to search engine.
  4671. foreach ($missing_terms as $term) {
  4672. $doc->add_term($prefix.$term, 1);
  4673. }
  4674. foreach ($deprecated_terms as $term) {
  4675. $doc->remove_term($prefix.$term);
  4676. }
  4677. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4678. $di->getDb()->flush();
  4679. }
  4680. }
  4681. return true;
  4682. }
  4683. /**
  4684. * Sets the theme of the LP (local/remote) (and save).
  4685. *
  4686. * @param string $name Optional string giving the new theme of this learnpath
  4687. *
  4688. * @return bool Returns true if theme name is not empty
  4689. */
  4690. public function set_theme($name = '')
  4691. {
  4692. $this->theme = $name;
  4693. $table = Database::get_course_table(TABLE_LP_MAIN);
  4694. $lp_id = $this->get_id();
  4695. $sql = "UPDATE $table
  4696. SET theme = '".Database::escape_string($this->theme)."'
  4697. WHERE iid = $lp_id";
  4698. Database::query($sql);
  4699. return true;
  4700. }
  4701. /**
  4702. * Sets the image of an LP (and save).
  4703. *
  4704. * @param string $name Optional string giving the new image of this learnpath
  4705. *
  4706. * @return bool Returns true if theme name is not empty
  4707. */
  4708. public function set_preview_image($name = '')
  4709. {
  4710. $this->preview_image = $name;
  4711. $table = Database::get_course_table(TABLE_LP_MAIN);
  4712. $lp_id = $this->get_id();
  4713. $sql = "UPDATE $table SET
  4714. preview_image = '".Database::escape_string($this->preview_image)."'
  4715. WHERE iid = $lp_id";
  4716. Database::query($sql);
  4717. return true;
  4718. }
  4719. /**
  4720. * Sets the author of a LP (and save).
  4721. *
  4722. * @param string $name Optional string giving the new author of this learnpath
  4723. *
  4724. * @return bool Returns true if author's name is not empty
  4725. */
  4726. public function set_author($name = '')
  4727. {
  4728. $this->author = $name;
  4729. $table = Database::get_course_table(TABLE_LP_MAIN);
  4730. $lp_id = $this->get_id();
  4731. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4732. WHERE iid = $lp_id";
  4733. Database::query($sql);
  4734. return true;
  4735. }
  4736. /**
  4737. * Sets the hide_toc_frame parameter of a LP (and save).
  4738. *
  4739. * @param int $hide 1 if frame is hidden 0 then else
  4740. *
  4741. * @return bool Returns true if author's name is not empty
  4742. */
  4743. public function set_hide_toc_frame($hide)
  4744. {
  4745. if (intval($hide) == $hide) {
  4746. $this->hide_toc_frame = $hide;
  4747. $table = Database::get_course_table(TABLE_LP_MAIN);
  4748. $lp_id = $this->get_id();
  4749. $sql = "UPDATE $table SET
  4750. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4751. WHERE iid = $lp_id";
  4752. Database::query($sql);
  4753. return true;
  4754. }
  4755. return false;
  4756. }
  4757. /**
  4758. * Sets the prerequisite of a LP (and save).
  4759. *
  4760. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4761. *
  4762. * @return bool returns true if prerequisite is not empty
  4763. */
  4764. public function set_prerequisite($prerequisite)
  4765. {
  4766. $this->prerequisite = (int) $prerequisite;
  4767. $table = Database::get_course_table(TABLE_LP_MAIN);
  4768. $lp_id = $this->get_id();
  4769. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4770. WHERE iid = $lp_id";
  4771. Database::query($sql);
  4772. return true;
  4773. }
  4774. /**
  4775. * Sets the location/proximity of the LP (local/remote) (and save).
  4776. *
  4777. * @param string $name Optional string giving the new location of this learnpath
  4778. *
  4779. * @return bool True on success / False on error
  4780. */
  4781. public function set_proximity($name = '')
  4782. {
  4783. if (empty($name)) {
  4784. return false;
  4785. }
  4786. $this->proximity = $name;
  4787. $table = Database::get_course_table(TABLE_LP_MAIN);
  4788. $lp_id = $this->get_id();
  4789. $sql = "UPDATE $table SET
  4790. content_local = '".Database::escape_string($name)."'
  4791. WHERE iid = $lp_id";
  4792. Database::query($sql);
  4793. return true;
  4794. }
  4795. /**
  4796. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4797. *
  4798. * @param int $id DB ID of the item
  4799. */
  4800. public function set_previous_item($id)
  4801. {
  4802. if ($this->debug > 0) {
  4803. error_log('In learnpath::set_previous_item()', 0);
  4804. }
  4805. $this->last = $id;
  4806. }
  4807. /**
  4808. * Sets use_max_score.
  4809. *
  4810. * @param int $use_max_score Optional string giving the new location of this learnpath
  4811. *
  4812. * @return bool True on success / False on error
  4813. */
  4814. public function set_use_max_score($use_max_score = 1)
  4815. {
  4816. $use_max_score = (int) $use_max_score;
  4817. $this->use_max_score = $use_max_score;
  4818. $table = Database::get_course_table(TABLE_LP_MAIN);
  4819. $lp_id = $this->get_id();
  4820. $sql = "UPDATE $table SET
  4821. use_max_score = '".$this->use_max_score."'
  4822. WHERE iid = $lp_id";
  4823. Database::query($sql);
  4824. return true;
  4825. }
  4826. /**
  4827. * Sets and saves the expired_on date.
  4828. *
  4829. * @param string $expired_on Optional string giving the new author of this learnpath
  4830. *
  4831. * @throws \Doctrine\ORM\OptimisticLockException
  4832. *
  4833. * @return bool Returns true if author's name is not empty
  4834. */
  4835. public function set_expired_on($expired_on)
  4836. {
  4837. $em = Database::getManager();
  4838. /** @var CLp $lp */
  4839. $lp = $em
  4840. ->getRepository('ChamiloCourseBundle:CLp')
  4841. ->findOneBy(
  4842. [
  4843. 'iid' => $this->get_id(),
  4844. ]
  4845. );
  4846. if (!$lp) {
  4847. return false;
  4848. }
  4849. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4850. $lp->setExpiredOn($this->expired_on);
  4851. $em->persist($lp);
  4852. $em->flush();
  4853. return true;
  4854. }
  4855. /**
  4856. * Sets and saves the publicated_on date.
  4857. *
  4858. * @param string $publicated_on Optional string giving the new author of this learnpath
  4859. *
  4860. * @throws \Doctrine\ORM\OptimisticLockException
  4861. *
  4862. * @return bool Returns true if author's name is not empty
  4863. */
  4864. public function set_publicated_on($publicated_on)
  4865. {
  4866. $em = Database::getManager();
  4867. /** @var CLp $lp */
  4868. $lp = $em
  4869. ->getRepository('ChamiloCourseBundle:CLp')
  4870. ->findOneBy(
  4871. [
  4872. 'iid' => $this->get_id(),
  4873. ]
  4874. );
  4875. if (!$lp) {
  4876. return false;
  4877. }
  4878. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4879. $lp->setPublicatedOn($this->publicated_on);
  4880. $em->persist($lp);
  4881. $em->flush();
  4882. return true;
  4883. }
  4884. /**
  4885. * Sets and saves the expired_on date.
  4886. *
  4887. * @return bool Returns true if author's name is not empty
  4888. */
  4889. public function set_modified_on()
  4890. {
  4891. $this->modified_on = api_get_utc_datetime();
  4892. $table = Database::get_course_table(TABLE_LP_MAIN);
  4893. $lp_id = $this->get_id();
  4894. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  4895. WHERE iid = $lp_id";
  4896. Database::query($sql);
  4897. return true;
  4898. }
  4899. /**
  4900. * Sets the object's error message.
  4901. *
  4902. * @param string $error Error message. If empty, reinits the error string
  4903. */
  4904. public function set_error_msg($error = '')
  4905. {
  4906. if ($this->debug > 0) {
  4907. error_log('In learnpath::set_error_msg()', 0);
  4908. }
  4909. if (empty($error)) {
  4910. $this->error = '';
  4911. } else {
  4912. $this->error .= $error;
  4913. }
  4914. }
  4915. /**
  4916. * Launches the current item if not 'sco'
  4917. * (starts timer and make sure there is a record ready in the DB).
  4918. *
  4919. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  4920. *
  4921. * @return bool
  4922. */
  4923. public function start_current_item($allow_new_attempt = false)
  4924. {
  4925. $debug = $this->debug;
  4926. if ($debug) {
  4927. error_log('In learnpath::start_current_item()');
  4928. error_log('current: '.$this->current);
  4929. }
  4930. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  4931. $type = $this->get_type();
  4932. $item_type = $this->items[$this->current]->get_type();
  4933. if (($type == 2 && $item_type != 'sco') ||
  4934. ($type == 3 && $item_type != 'au') ||
  4935. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4936. ) {
  4937. if ($debug) {
  4938. error_log('item type: '.$item_type);
  4939. error_log('lp type: '.$type);
  4940. }
  4941. $this->items[$this->current]->open($allow_new_attempt);
  4942. $this->autocomplete_parents($this->current);
  4943. $prereq_check = $this->prerequisites_match($this->current);
  4944. if ($debug) {
  4945. error_log('start_current_item will save item with prereq: '.$prereq_check);
  4946. }
  4947. $this->items[$this->current]->save(false, $prereq_check);
  4948. }
  4949. // If sco, then it is supposed to have been updated by some other call.
  4950. if ($item_type == 'sco') {
  4951. $this->items[$this->current]->restart();
  4952. }
  4953. }
  4954. if ($debug) {
  4955. error_log('lp_view_session_id');
  4956. error_log($this->lp_view_session_id);
  4957. error_log('api session id');
  4958. error_log(api_get_session_id());
  4959. error_log('End of learnpath::start_current_item()');
  4960. }
  4961. return true;
  4962. }
  4963. /**
  4964. * Stops the processing and counters for the old item (as held in $this->last).
  4965. *
  4966. * @return bool True/False
  4967. */
  4968. public function stop_previous_item()
  4969. {
  4970. $debug = $this->debug;
  4971. if ($debug) {
  4972. error_log('In learnpath::stop_previous_item()', 0);
  4973. }
  4974. if ($this->last != 0 && $this->last != $this->current &&
  4975. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  4976. ) {
  4977. if ($debug) {
  4978. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  4979. }
  4980. switch ($this->get_type()) {
  4981. case '3':
  4982. if ($this->items[$this->last]->get_type() != 'au') {
  4983. if ($debug) {
  4984. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  4985. }
  4986. $this->items[$this->last]->close();
  4987. } else {
  4988. if ($debug) {
  4989. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  4990. }
  4991. }
  4992. break;
  4993. case '2':
  4994. if ($this->items[$this->last]->get_type() != 'sco') {
  4995. if ($debug) {
  4996. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  4997. }
  4998. $this->items[$this->last]->close();
  4999. } else {
  5000. if ($debug) {
  5001. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5002. }
  5003. }
  5004. break;
  5005. case '1':
  5006. default:
  5007. if ($debug) {
  5008. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5009. }
  5010. $this->items[$this->last]->close();
  5011. break;
  5012. }
  5013. } else {
  5014. if ($debug) {
  5015. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5016. }
  5017. return false;
  5018. }
  5019. return true;
  5020. }
  5021. /**
  5022. * Updates the default view mode from fullscreen to embedded and inversely.
  5023. *
  5024. * @return string The current default view mode ('fullscreen' or 'embedded')
  5025. */
  5026. public function update_default_view_mode()
  5027. {
  5028. $table = Database::get_course_table(TABLE_LP_MAIN);
  5029. $sql = "SELECT * FROM $table
  5030. WHERE iid = ".$this->get_id();
  5031. $res = Database::query($sql);
  5032. if (Database::num_rows($res) > 0) {
  5033. $row = Database::fetch_array($res);
  5034. $default_view_mode = $row['default_view_mod'];
  5035. $view_mode = $default_view_mode;
  5036. switch ($default_view_mode) {
  5037. case 'fullscreen': // default with popup
  5038. $view_mode = 'embedded';
  5039. break;
  5040. case 'embedded': // default view with left menu
  5041. $view_mode = 'embedframe';
  5042. break;
  5043. case 'embedframe': //folded menu
  5044. $view_mode = 'impress';
  5045. break;
  5046. case 'impress':
  5047. $view_mode = 'fullscreen';
  5048. break;
  5049. }
  5050. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5051. WHERE iid = ".$this->get_id();
  5052. Database::query($sql);
  5053. $this->mode = $view_mode;
  5054. return $view_mode;
  5055. }
  5056. return -1;
  5057. }
  5058. /**
  5059. * Updates the default behaviour about auto-commiting SCORM updates.
  5060. *
  5061. * @return bool True if auto-commit has been set to 'on', false otherwise
  5062. */
  5063. public function update_default_scorm_commit()
  5064. {
  5065. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5066. $sql = "SELECT * FROM $lp_table
  5067. WHERE iid = ".$this->get_id();
  5068. $res = Database::query($sql);
  5069. if (Database::num_rows($res) > 0) {
  5070. $row = Database::fetch_array($res);
  5071. $force = $row['force_commit'];
  5072. if ($force == 1) {
  5073. $force = 0;
  5074. $force_return = false;
  5075. } elseif ($force == 0) {
  5076. $force = 1;
  5077. $force_return = true;
  5078. }
  5079. $sql = "UPDATE $lp_table SET force_commit = $force
  5080. WHERE iid = ".$this->get_id();
  5081. Database::query($sql);
  5082. $this->force_commit = $force_return;
  5083. return $force_return;
  5084. }
  5085. return -1;
  5086. }
  5087. /**
  5088. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5089. *
  5090. * @return bool True on success, false on failure
  5091. */
  5092. public function update_display_order()
  5093. {
  5094. $course_id = api_get_course_int_id();
  5095. $table = Database::get_course_table(TABLE_LP_MAIN);
  5096. $sql = "SELECT * FROM $table
  5097. WHERE c_id = $course_id
  5098. ORDER BY display_order";
  5099. $res = Database::query($sql);
  5100. if ($res === false) {
  5101. return false;
  5102. }
  5103. $num = Database::num_rows($res);
  5104. // First check the order is correct, globally (might be wrong because
  5105. // of versions < 1.8.4).
  5106. if ($num > 0) {
  5107. $i = 1;
  5108. while ($row = Database::fetch_array($res)) {
  5109. if ($row['display_order'] != $i) {
  5110. // If we find a gap in the order, we need to fix it.
  5111. $sql = "UPDATE $table SET display_order = $i
  5112. WHERE iid = ".$row['iid'];
  5113. Database::query($sql);
  5114. }
  5115. $i++;
  5116. }
  5117. }
  5118. return true;
  5119. }
  5120. /**
  5121. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5122. *
  5123. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5124. */
  5125. public function update_reinit()
  5126. {
  5127. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5128. $sql = "SELECT * FROM $lp_table
  5129. WHERE iid = ".$this->get_id();
  5130. $res = Database::query($sql);
  5131. if (Database::num_rows($res) > 0) {
  5132. $row = Database::fetch_array($res);
  5133. $force = $row['prevent_reinit'];
  5134. if ($force == 1) {
  5135. $force = 0;
  5136. } elseif ($force == 0) {
  5137. $force = 1;
  5138. }
  5139. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5140. WHERE iid = ".$this->get_id();
  5141. Database::query($sql);
  5142. $this->prevent_reinit = $force;
  5143. return $force;
  5144. }
  5145. return -1;
  5146. }
  5147. /**
  5148. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5149. *
  5150. * @return string 'single', 'multi' or 'seriousgame'
  5151. *
  5152. * @author ndiechburg <noel@cblue.be>
  5153. */
  5154. public function get_attempt_mode()
  5155. {
  5156. //Set default value for seriousgame_mode
  5157. if (!isset($this->seriousgame_mode)) {
  5158. $this->seriousgame_mode = 0;
  5159. }
  5160. // Set default value for prevent_reinit
  5161. if (!isset($this->prevent_reinit)) {
  5162. $this->prevent_reinit = 1;
  5163. }
  5164. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5165. return 'seriousgame';
  5166. }
  5167. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5168. return 'single';
  5169. }
  5170. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5171. return 'multiple';
  5172. }
  5173. return 'single';
  5174. }
  5175. /**
  5176. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5177. *
  5178. * @param string 'seriousgame', 'single' or 'multiple'
  5179. *
  5180. * @return bool
  5181. *
  5182. * @author ndiechburg <noel@cblue.be>
  5183. */
  5184. public function set_attempt_mode($mode)
  5185. {
  5186. switch ($mode) {
  5187. case 'seriousgame':
  5188. $sg_mode = 1;
  5189. $prevent_reinit = 1;
  5190. break;
  5191. case 'single':
  5192. $sg_mode = 0;
  5193. $prevent_reinit = 1;
  5194. break;
  5195. case 'multiple':
  5196. $sg_mode = 0;
  5197. $prevent_reinit = 0;
  5198. break;
  5199. default:
  5200. $sg_mode = 0;
  5201. $prevent_reinit = 0;
  5202. break;
  5203. }
  5204. $this->prevent_reinit = $prevent_reinit;
  5205. $this->seriousgame_mode = $sg_mode;
  5206. $table = Database::get_course_table(TABLE_LP_MAIN);
  5207. $sql = "UPDATE $table SET
  5208. prevent_reinit = $prevent_reinit ,
  5209. seriousgame_mode = $sg_mode
  5210. WHERE iid = ".$this->get_id();
  5211. $res = Database::query($sql);
  5212. if ($res) {
  5213. return true;
  5214. } else {
  5215. return false;
  5216. }
  5217. }
  5218. /**
  5219. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5220. *
  5221. * @author ndiechburg <noel@cblue.be>
  5222. */
  5223. public function switch_attempt_mode()
  5224. {
  5225. $mode = $this->get_attempt_mode();
  5226. switch ($mode) {
  5227. case 'single':
  5228. $next_mode = 'multiple';
  5229. break;
  5230. case 'multiple':
  5231. $next_mode = 'seriousgame';
  5232. break;
  5233. case 'seriousgame':
  5234. default:
  5235. $next_mode = 'single';
  5236. break;
  5237. }
  5238. $this->set_attempt_mode($next_mode);
  5239. }
  5240. /**
  5241. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5242. * but possibility to do again a completed item.
  5243. *
  5244. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5245. *
  5246. * @author ndiechburg <noel@cblue.be>
  5247. */
  5248. public function set_seriousgame_mode()
  5249. {
  5250. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5251. $sql = "SELECT * FROM $lp_table
  5252. WHERE iid = ".$this->get_id();
  5253. $res = Database::query($sql);
  5254. if (Database::num_rows($res) > 0) {
  5255. $row = Database::fetch_array($res);
  5256. $force = $row['seriousgame_mode'];
  5257. if ($force == 1) {
  5258. $force = 0;
  5259. } elseif ($force == 0) {
  5260. $force = 1;
  5261. }
  5262. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5263. WHERE iid = ".$this->get_id();
  5264. Database::query($sql);
  5265. $this->seriousgame_mode = $force;
  5266. return $force;
  5267. }
  5268. return -1;
  5269. }
  5270. /**
  5271. * Updates the "scorm_debug" value that shows or hide the debug window.
  5272. *
  5273. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5274. */
  5275. public function update_scorm_debug()
  5276. {
  5277. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5278. $sql = "SELECT * FROM $lp_table
  5279. WHERE iid = ".$this->get_id();
  5280. $res = Database::query($sql);
  5281. if (Database::num_rows($res) > 0) {
  5282. $row = Database::fetch_array($res);
  5283. $force = $row['debug'];
  5284. if ($force == 1) {
  5285. $force = 0;
  5286. } elseif ($force == 0) {
  5287. $force = 1;
  5288. }
  5289. $sql = "UPDATE $lp_table SET debug = $force
  5290. WHERE iid = ".$this->get_id();
  5291. Database::query($sql);
  5292. $this->scorm_debug = $force;
  5293. return $force;
  5294. }
  5295. return -1;
  5296. }
  5297. /**
  5298. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5299. *
  5300. * @author Kevin Van Den Haute
  5301. *
  5302. * @param array
  5303. */
  5304. public function tree_array($array)
  5305. {
  5306. $array = $this->sort_tree_array($array);
  5307. $this->create_tree_array($array);
  5308. }
  5309. /**
  5310. * Creates an array with the elements of the learning path tree in it.
  5311. *
  5312. * @author Kevin Van Den Haute
  5313. *
  5314. * @param array $array
  5315. * @param int $parent
  5316. * @param int $depth
  5317. * @param array $tmp
  5318. */
  5319. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5320. {
  5321. if (is_array($array)) {
  5322. for ($i = 0; $i < count($array); $i++) {
  5323. if ($array[$i]['parent_item_id'] == $parent) {
  5324. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5325. $tmp[] = $array[$i]['parent_item_id'];
  5326. $depth++;
  5327. }
  5328. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5329. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5330. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5331. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5332. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5333. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5334. $this->arrMenu[] = [
  5335. 'id' => $array[$i]['id'],
  5336. 'ref' => $ref,
  5337. 'item_type' => $array[$i]['item_type'],
  5338. 'title' => $array[$i]['title'],
  5339. 'title_raw' => $array[$i]['title_raw'],
  5340. 'path' => $path,
  5341. 'description' => $array[$i]['description'],
  5342. 'parent_item_id' => $array[$i]['parent_item_id'],
  5343. 'previous_item_id' => $array[$i]['previous_item_id'],
  5344. 'next_item_id' => $array[$i]['next_item_id'],
  5345. 'min_score' => $array[$i]['min_score'],
  5346. 'max_score' => $array[$i]['max_score'],
  5347. 'mastery_score' => $array[$i]['mastery_score'],
  5348. 'display_order' => $array[$i]['display_order'],
  5349. 'prerequisite' => $preq,
  5350. 'depth' => $depth,
  5351. 'audio' => $audio,
  5352. 'prerequisite_min_score' => $prerequisiteMinScore,
  5353. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5354. ];
  5355. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5356. }
  5357. }
  5358. }
  5359. }
  5360. /**
  5361. * Sorts a multi dimensional array by parent id and display order.
  5362. *
  5363. * @author Kevin Van Den Haute
  5364. *
  5365. * @param array $array (array with al the learning path items in it)
  5366. *
  5367. * @return array
  5368. */
  5369. public function sort_tree_array($array)
  5370. {
  5371. foreach ($array as $key => $row) {
  5372. $parent[$key] = $row['parent_item_id'];
  5373. $position[$key] = $row['display_order'];
  5374. }
  5375. if (count($array) > 0) {
  5376. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5377. }
  5378. return $array;
  5379. }
  5380. /**
  5381. * Function that creates a html list of learning path items so that we can add audio files to them.
  5382. *
  5383. * @author Kevin Van Den Haute
  5384. *
  5385. * @return string
  5386. */
  5387. public function overview()
  5388. {
  5389. $return = '';
  5390. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5391. // we need to start a form when we want to update all the mp3 files
  5392. if ($update_audio == 'true') {
  5393. $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">';
  5394. }
  5395. $return .= '<div id="message"></div>';
  5396. if (count($this->items) == 0) {
  5397. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5398. } else {
  5399. $return_audio = '<table class="data_table">';
  5400. $return_audio .= '<tr>';
  5401. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5402. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5403. $return_audio .= '</tr>';
  5404. if ($update_audio != 'true') {
  5405. $return .= '<div class="col-md-12">';
  5406. $return .= self::return_new_tree($update_audio);
  5407. $return .= '</div>';
  5408. $return .= Display::div(
  5409. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5410. ['style' => 'float:left; margin-top:15px;width:100%']
  5411. );
  5412. } else {
  5413. $return_audio .= self::return_new_tree($update_audio);
  5414. $return .= $return_audio.'</table>';
  5415. }
  5416. // We need to close the form when we are updating the mp3 files.
  5417. if ($update_audio == 'true') {
  5418. $return .= '<div class="footer-audio">';
  5419. $return .= Display::button(
  5420. 'save_audio',
  5421. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5422. ['class' => 'btn btn-primary', 'type' => 'submit']
  5423. );
  5424. $return .= '</div>';
  5425. }
  5426. }
  5427. // We need to close the form when we are updating the mp3 files.
  5428. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5429. $return .= '</form>';
  5430. }
  5431. return $return;
  5432. }
  5433. /**
  5434. * @param string $update_audio
  5435. *
  5436. * @return array
  5437. */
  5438. public function processBuildMenuElements($update_audio = 'false')
  5439. {
  5440. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5441. $arrLP = $this->getItemsForForm();
  5442. $this->tree_array($arrLP);
  5443. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5444. unset($this->arrMenu);
  5445. $default_data = null;
  5446. $default_content = null;
  5447. $elements = [];
  5448. $return_audio = null;
  5449. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5450. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5451. $countItems = count($arrLP);
  5452. $upIcon = Display::return_icon(
  5453. 'up.png',
  5454. get_lang('Up'),
  5455. [],
  5456. ICON_SIZE_TINY
  5457. );
  5458. $disableUpIcon = Display::return_icon(
  5459. 'up_na.png',
  5460. get_lang('Up'),
  5461. [],
  5462. ICON_SIZE_TINY
  5463. );
  5464. $downIcon = Display::return_icon(
  5465. 'down.png',
  5466. get_lang('Down'),
  5467. [],
  5468. ICON_SIZE_TINY
  5469. );
  5470. $disableDownIcon = Display::return_icon(
  5471. 'down_na.png',
  5472. get_lang('Down'),
  5473. [],
  5474. ICON_SIZE_TINY
  5475. );
  5476. $show = api_get_configuration_value('show_full_lp_item_title_in_edition');
  5477. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5478. $plugin = null;
  5479. if ($pluginCalendar) {
  5480. $plugin = LearningCalendarPlugin::create();
  5481. }
  5482. for ($i = 0; $i < $countItems; $i++) {
  5483. $parent_id = $arrLP[$i]['parent_item_id'];
  5484. $title = $arrLP[$i]['title'];
  5485. $title_cut = $arrLP[$i]['title_raw'];
  5486. if ($show === false) {
  5487. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5488. }
  5489. // Link for the documents
  5490. if ($arrLP[$i]['item_type'] === 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5491. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5492. $title_cut = Display::url(
  5493. $title_cut,
  5494. $url,
  5495. [
  5496. 'class' => 'ajax moved',
  5497. 'data-title' => $title,
  5498. 'title' => $title,
  5499. ]
  5500. );
  5501. }
  5502. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5503. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5504. Session::write('pathItem', $arrLP[$i]['path']);
  5505. }
  5506. $oddClass = 'row_even';
  5507. if (($i % 2) == 0) {
  5508. $oddClass = 'row_odd';
  5509. }
  5510. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5511. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5512. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5513. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5514. } else {
  5515. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5516. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5517. } else {
  5518. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5519. $icon = Display::return_icon('certificate.png');
  5520. } else {
  5521. $icon = Display::return_icon('folder_document.gif');
  5522. }
  5523. }
  5524. }
  5525. // The audio column.
  5526. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5527. $audio = '';
  5528. if (!$update_audio || $update_audio != 'true') {
  5529. if (empty($arrLP[$i]['audio'])) {
  5530. $audio .= '';
  5531. }
  5532. } else {
  5533. $types = self::getChapterTypes();
  5534. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5535. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5536. if (!empty($arrLP[$i]['audio'])) {
  5537. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5538. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5539. }
  5540. }
  5541. }
  5542. $return_audio .= Display::span($icon.' '.$title).
  5543. Display::tag(
  5544. 'td',
  5545. $audio,
  5546. ['style' => '']
  5547. );
  5548. $return_audio .= '</td>';
  5549. $move_icon = '';
  5550. $move_item_icon = '';
  5551. $edit_icon = '';
  5552. $delete_icon = '';
  5553. $audio_icon = '';
  5554. $prerequisities_icon = '';
  5555. $forumIcon = '';
  5556. $previewIcon = '';
  5557. $pluginCalendarIcon = '';
  5558. $orderIcons = '';
  5559. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5560. if ($is_allowed_to_edit) {
  5561. if (!$update_audio || $update_audio != 'true') {
  5562. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5563. $move_icon .= '<a class="moved" href="#">';
  5564. $move_icon .= Display::return_icon(
  5565. 'move_everywhere.png',
  5566. get_lang('Move'),
  5567. [],
  5568. ICON_SIZE_TINY
  5569. );
  5570. $move_icon .= '</a>';
  5571. }
  5572. }
  5573. // No edit for this item types
  5574. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5575. if ($arrLP[$i]['item_type'] != 'dir') {
  5576. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5577. $edit_icon .= Display::return_icon(
  5578. 'edit.png',
  5579. get_lang('LearnpathEditModule'),
  5580. [],
  5581. ICON_SIZE_TINY
  5582. );
  5583. $edit_icon .= '</a>';
  5584. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5585. $forumThread = null;
  5586. if (isset($this->items[$arrLP[$i]['id']])) {
  5587. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5588. $this->course_int_id,
  5589. $this->lp_session_id
  5590. );
  5591. }
  5592. if ($forumThread) {
  5593. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5594. 'action' => 'dissociate_forum',
  5595. 'id' => $arrLP[$i]['id'],
  5596. 'lp_id' => $this->lp_id,
  5597. ]);
  5598. $forumIcon = Display::url(
  5599. Display::return_icon(
  5600. 'forum.png',
  5601. get_lang('DissociateForumToLPItem'),
  5602. [],
  5603. ICON_SIZE_TINY
  5604. ),
  5605. $forumIconUrl,
  5606. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5607. );
  5608. } else {
  5609. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5610. 'action' => 'create_forum',
  5611. 'id' => $arrLP[$i]['id'],
  5612. 'lp_id' => $this->lp_id,
  5613. ]);
  5614. $forumIcon = Display::url(
  5615. Display::return_icon(
  5616. 'forum.png',
  5617. get_lang('AssociateForumToLPItem'),
  5618. [],
  5619. ICON_SIZE_TINY
  5620. ),
  5621. $forumIconUrl,
  5622. ['class' => 'btn btn-default lp-btn-associate-forum']
  5623. );
  5624. }
  5625. }
  5626. } else {
  5627. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5628. $edit_icon .= Display::return_icon(
  5629. 'edit.png',
  5630. get_lang('LearnpathEditModule'),
  5631. [],
  5632. ICON_SIZE_TINY
  5633. );
  5634. $edit_icon .= '</a>';
  5635. }
  5636. } else {
  5637. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5638. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5639. $edit_icon .= Display::return_icon(
  5640. 'edit.png',
  5641. get_lang('Edit'),
  5642. [],
  5643. ICON_SIZE_TINY
  5644. );
  5645. $edit_icon .= '</a>';
  5646. }
  5647. }
  5648. if ($pluginCalendar) {
  5649. $pluginLink = $pluginUrl.
  5650. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5651. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5652. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5653. if ($itemInfo && $itemInfo['value'] == 1) {
  5654. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5655. }
  5656. $pluginCalendarIcon = Display::url(
  5657. $iconCalendar,
  5658. $pluginLink,
  5659. ['class' => 'btn btn-default']
  5660. );
  5661. }
  5662. if ($arrLP[$i]['item_type'] != 'final_item') {
  5663. $orderIcons = Display::url(
  5664. $upIcon,
  5665. 'javascript:void(0)',
  5666. ['class' => 'btn btn-default order_items', 'data-dir' => 'up', 'data-id' => $arrLP[$i]['id']]
  5667. );
  5668. $orderIcons .= Display::url(
  5669. $downIcon,
  5670. 'javascript:void(0)',
  5671. ['class' => 'btn btn-default order_items', 'data-dir' => 'down', 'data-id' => $arrLP[$i]['id']]
  5672. );
  5673. }
  5674. $delete_icon .= ' <a
  5675. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5676. onclick="return confirmation(\''.addslashes($title).'\');"
  5677. class="btn btn-default">';
  5678. $delete_icon .= Display::return_icon(
  5679. 'delete.png',
  5680. get_lang('LearnpathDeleteModule'),
  5681. [],
  5682. ICON_SIZE_TINY
  5683. );
  5684. $delete_icon .= '</a>';
  5685. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5686. $previewImage = Display::return_icon(
  5687. 'preview_view.png',
  5688. get_lang('Preview'),
  5689. [],
  5690. ICON_SIZE_TINY
  5691. );
  5692. switch ($arrLP[$i]['item_type']) {
  5693. case TOOL_DOCUMENT:
  5694. case TOOL_LP_FINAL_ITEM:
  5695. case TOOL_READOUT_TEXT:
  5696. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5697. $previewIcon = Display::url(
  5698. $previewImage,
  5699. $urlPreviewLink,
  5700. [
  5701. 'target' => '_blank',
  5702. 'class' => 'btn btn-default',
  5703. 'data-title' => $arrLP[$i]['title'],
  5704. 'title' => $arrLP[$i]['title'],
  5705. ]
  5706. );
  5707. break;
  5708. case TOOL_THREAD:
  5709. case TOOL_FORUM:
  5710. case TOOL_QUIZ:
  5711. case TOOL_STUDENTPUBLICATION:
  5712. case TOOL_LP_FINAL_ITEM:
  5713. case TOOL_LINK:
  5714. $class = 'btn btn-default';
  5715. $target = '_blank';
  5716. $link = self::rl_get_resource_link_for_learnpath(
  5717. $this->course_int_id,
  5718. $this->lp_id,
  5719. $arrLP[$i]['id'],
  5720. 0
  5721. );
  5722. $previewIcon = Display::url(
  5723. $previewImage,
  5724. $link,
  5725. [
  5726. 'class' => $class,
  5727. 'data-title' => $arrLP[$i]['title'],
  5728. 'title' => $arrLP[$i]['title'],
  5729. 'target' => $target,
  5730. ]
  5731. );
  5732. break;
  5733. default:
  5734. $previewIcon = Display::url(
  5735. $previewImage,
  5736. $url.'&action=view_item',
  5737. ['class' => 'btn btn-default', 'target' => '_blank']
  5738. );
  5739. break;
  5740. }
  5741. if ($arrLP[$i]['item_type'] != 'dir') {
  5742. $prerequisities_icon = Display::url(
  5743. Display::return_icon(
  5744. 'accept.png',
  5745. get_lang('LearnpathPrerequisites'),
  5746. [],
  5747. ICON_SIZE_TINY
  5748. ),
  5749. $url.'&action=edit_item_prereq',
  5750. ['class' => 'btn btn-default']
  5751. );
  5752. if ($arrLP[$i]['item_type'] != 'final_item') {
  5753. $move_item_icon = Display::url(
  5754. Display::return_icon(
  5755. 'move.png',
  5756. get_lang('Move'),
  5757. [],
  5758. ICON_SIZE_TINY
  5759. ),
  5760. $url.'&action=move_item',
  5761. ['class' => 'btn btn-default']
  5762. );
  5763. }
  5764. $audio_icon = Display::url(
  5765. Display::return_icon(
  5766. 'audio.png',
  5767. get_lang('UplUpload'),
  5768. [],
  5769. ICON_SIZE_TINY
  5770. ),
  5771. $url.'&action=add_audio',
  5772. ['class' => 'btn btn-default']
  5773. );
  5774. }
  5775. }
  5776. if ($update_audio != 'true') {
  5777. $row = $move_icon.' '.$icon.
  5778. Display::span($title_cut).
  5779. Display::tag(
  5780. 'div',
  5781. "<div class=\"btn-group btn-group-xs\">
  5782. $previewIcon
  5783. $audio
  5784. $edit_icon
  5785. $pluginCalendarIcon
  5786. $forumIcon
  5787. $prerequisities_icon
  5788. $move_item_icon
  5789. $audio_icon
  5790. $orderIcons
  5791. $delete_icon
  5792. </div>",
  5793. ['class' => 'btn-toolbar button_actions']
  5794. );
  5795. } else {
  5796. $row =
  5797. Display::span($title.$icon).
  5798. Display::span($audio, ['class' => 'button_actions']);
  5799. }
  5800. $default_data[$arrLP[$i]['id']] = $row;
  5801. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5802. if (empty($parent_id)) {
  5803. $elements[$arrLP[$i]['id']]['data'] = $row;
  5804. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5805. } else {
  5806. $parent_arrays = [];
  5807. if ($arrLP[$i]['depth'] > 1) {
  5808. // Getting list of parents
  5809. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5810. foreach ($arrLP as $item) {
  5811. if ($item['id'] == $parent_id) {
  5812. if ($item['parent_item_id'] == 0) {
  5813. $parent_id = $item['id'];
  5814. break;
  5815. } else {
  5816. $parent_id = $item['parent_item_id'];
  5817. if (empty($parent_arrays)) {
  5818. $parent_arrays[] = intval($item['id']);
  5819. }
  5820. $parent_arrays[] = $parent_id;
  5821. break;
  5822. }
  5823. }
  5824. }
  5825. }
  5826. }
  5827. if (!empty($parent_arrays)) {
  5828. $parent_arrays = array_reverse($parent_arrays);
  5829. $val = '$elements';
  5830. $x = 0;
  5831. foreach ($parent_arrays as $item) {
  5832. if ($x != count($parent_arrays) - 1) {
  5833. $val .= '["'.$item.'"]["children"]';
  5834. } else {
  5835. $val .= '["'.$item.'"]["children"]';
  5836. }
  5837. $x++;
  5838. }
  5839. $val .= "";
  5840. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5841. eval($code_str);
  5842. } else {
  5843. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5844. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5845. }
  5846. }
  5847. }
  5848. return [
  5849. 'elements' => $elements,
  5850. 'default_data' => $default_data,
  5851. 'default_content' => $default_content,
  5852. 'return_audio' => $return_audio,
  5853. ];
  5854. }
  5855. /**
  5856. * @param string $updateAudio true/false strings
  5857. *
  5858. * @return string
  5859. */
  5860. public function returnLpItemList($updateAudio)
  5861. {
  5862. $result = $this->processBuildMenuElements($updateAudio);
  5863. $html = self::print_recursive(
  5864. $result['elements'],
  5865. $result['default_data'],
  5866. $result['default_content']
  5867. );
  5868. if (!empty($html)) {
  5869. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5870. }
  5871. return $html;
  5872. }
  5873. /**
  5874. * @param string $update_audio
  5875. * @param bool $drop_element_here
  5876. *
  5877. * @return string
  5878. */
  5879. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5880. {
  5881. $result = $this->processBuildMenuElements($update_audio);
  5882. $list = '<ul id="lp_item_list">';
  5883. $tree = $this->print_recursive(
  5884. $result['elements'],
  5885. $result['default_data'],
  5886. $result['default_content']
  5887. );
  5888. if (!empty($tree)) {
  5889. $list .= $tree;
  5890. } else {
  5891. if ($drop_element_here) {
  5892. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5893. }
  5894. }
  5895. $list .= '</ul>';
  5896. $return = Display::panelCollapse(
  5897. $this->name,
  5898. $list,
  5899. 'scorm-list',
  5900. null,
  5901. 'scorm-list-accordion',
  5902. 'scorm-list-collapse'
  5903. );
  5904. if ($update_audio === 'true') {
  5905. $return = $result['return_audio'];
  5906. }
  5907. return $return;
  5908. }
  5909. /**
  5910. * @param array $elements
  5911. * @param array $default_data
  5912. * @param array $default_content
  5913. *
  5914. * @return string
  5915. */
  5916. public function print_recursive($elements, $default_data, $default_content)
  5917. {
  5918. $return = '';
  5919. foreach ($elements as $key => $item) {
  5920. if (isset($item['load_data']) || empty($item['data'])) {
  5921. $item['data'] = $default_data[$item['load_data']];
  5922. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5923. }
  5924. $sub_list = '';
  5925. if (isset($item['type']) && $item['type'] === 'dir') {
  5926. // empty value
  5927. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  5928. }
  5929. if (empty($item['children'])) {
  5930. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5931. $active = null;
  5932. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5933. $active = 'active';
  5934. }
  5935. $return .= Display::tag(
  5936. 'li',
  5937. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  5938. ['id' => $key, 'class' => 'record li_container']
  5939. );
  5940. } else {
  5941. // Sections
  5942. $data = '';
  5943. if (isset($item['children'])) {
  5944. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5945. }
  5946. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5947. $return .= Display::tag(
  5948. 'li',
  5949. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  5950. ['id' => $key, 'class' => 'record li_container']
  5951. );
  5952. }
  5953. }
  5954. return $return;
  5955. }
  5956. /**
  5957. * This function builds the action menu.
  5958. *
  5959. * @param bool $returnContent Optional
  5960. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5961. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5962. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5963. *
  5964. * @return string
  5965. */
  5966. public function build_action_menu(
  5967. $returnContent = false,
  5968. $showRequirementButtons = true,
  5969. $isConfigPage = false,
  5970. $allowExpand = true
  5971. ) {
  5972. $actionsLeft = '';
  5973. $actionsRight = '';
  5974. $actionsLeft .= Display::url(
  5975. Display::return_icon(
  5976. 'back.png',
  5977. get_lang('ReturnToLearningPaths'),
  5978. '',
  5979. ICON_SIZE_MEDIUM
  5980. ),
  5981. 'lp_controller.php?'.api_get_cidreq()
  5982. );
  5983. $actionsLeft .= Display::url(
  5984. Display::return_icon(
  5985. 'preview_view.png',
  5986. get_lang('Preview'),
  5987. '',
  5988. ICON_SIZE_MEDIUM
  5989. ),
  5990. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5991. 'action' => 'view',
  5992. 'lp_id' => $this->lp_id,
  5993. 'isStudentView' => 'true',
  5994. ])
  5995. );
  5996. $actionsLeft .= Display::url(
  5997. Display::return_icon(
  5998. 'upload_audio.png',
  5999. get_lang('UpdateAllAudioFragments'),
  6000. '',
  6001. ICON_SIZE_MEDIUM
  6002. ),
  6003. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6004. 'action' => 'admin_view',
  6005. 'lp_id' => $this->lp_id,
  6006. 'updateaudio' => 'true',
  6007. ])
  6008. );
  6009. if (!$isConfigPage) {
  6010. $actionsLeft .= Display::url(
  6011. Display::return_icon(
  6012. 'settings.png',
  6013. get_lang('CourseSettings'),
  6014. '',
  6015. ICON_SIZE_MEDIUM
  6016. ),
  6017. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6018. 'action' => 'edit',
  6019. 'lp_id' => $this->lp_id,
  6020. ])
  6021. );
  6022. } else {
  6023. $actionsLeft .= Display::url(
  6024. Display::return_icon(
  6025. 'edit.png',
  6026. get_lang('Edit'),
  6027. '',
  6028. ICON_SIZE_MEDIUM
  6029. ),
  6030. 'lp_controller.php?'.http_build_query([
  6031. 'action' => 'build',
  6032. 'lp_id' => $this->lp_id,
  6033. ]).'&'.api_get_cidreq()
  6034. );
  6035. }
  6036. if ($allowExpand) {
  6037. $actionsLeft .= Display::url(
  6038. Display::return_icon(
  6039. 'expand.png',
  6040. get_lang('Expand'),
  6041. ['id' => 'expand'],
  6042. ICON_SIZE_MEDIUM
  6043. ).
  6044. Display::return_icon(
  6045. 'contract.png',
  6046. get_lang('Collapse'),
  6047. ['id' => 'contract', 'class' => 'hide'],
  6048. ICON_SIZE_MEDIUM
  6049. ),
  6050. '#',
  6051. ['role' => 'button', 'id' => 'hide_bar_template']
  6052. );
  6053. }
  6054. if ($showRequirementButtons) {
  6055. $buttons = [
  6056. [
  6057. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6058. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6059. 'action' => 'set_previous_step_as_prerequisite',
  6060. 'lp_id' => $this->lp_id,
  6061. ]),
  6062. ],
  6063. [
  6064. 'title' => get_lang('ClearAllPrerequisites'),
  6065. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6066. 'action' => 'clear_prerequisites',
  6067. 'lp_id' => $this->lp_id,
  6068. ]),
  6069. ],
  6070. ];
  6071. $actionsRight = Display::groupButtonWithDropDown(
  6072. get_lang('PrerequisitesOptions'),
  6073. $buttons,
  6074. true
  6075. );
  6076. }
  6077. $toolbar = Display::toolbarAction(
  6078. 'actions-lp-controller',
  6079. [$actionsLeft, $actionsRight]
  6080. );
  6081. if ($returnContent) {
  6082. return $toolbar;
  6083. }
  6084. echo $toolbar;
  6085. }
  6086. /**
  6087. * Creates the default learning path folder.
  6088. *
  6089. * @param array $course
  6090. * @param int $creatorId
  6091. *
  6092. * @return bool
  6093. */
  6094. public static function generate_learning_path_folder($course, $creatorId = 0)
  6095. {
  6096. // Creating learning_path folder
  6097. $dir = '/learning_path';
  6098. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6099. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6100. $folder = false;
  6101. if (!is_dir($filepath.'/'.$dir)) {
  6102. $folderData = create_unexisting_directory(
  6103. $course,
  6104. $creatorId,
  6105. 0,
  6106. null,
  6107. 0,
  6108. $filepath,
  6109. $dir,
  6110. get_lang('LearningPaths'),
  6111. 0
  6112. );
  6113. if (!empty($folderData)) {
  6114. $folder = true;
  6115. }
  6116. } else {
  6117. $folder = true;
  6118. }
  6119. return $folder;
  6120. }
  6121. /**
  6122. * @param array $course
  6123. * @param string $lp_name
  6124. * @param int $creatorId
  6125. *
  6126. * @return array
  6127. */
  6128. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6129. {
  6130. $filepath = '';
  6131. $dir = '/learning_path/';
  6132. if (empty($lp_name)) {
  6133. $lp_name = $this->name;
  6134. }
  6135. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6136. $folder = self::generate_learning_path_folder($course, $creatorId);
  6137. // Limits title size
  6138. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6139. $dir = $dir.$title;
  6140. // Creating LP folder
  6141. $documentId = null;
  6142. if ($folder) {
  6143. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6144. if (!is_dir($filepath.'/'.$dir)) {
  6145. $folderData = create_unexisting_directory(
  6146. $course,
  6147. $creatorId,
  6148. 0,
  6149. 0,
  6150. 0,
  6151. $filepath,
  6152. $dir,
  6153. $lp_name
  6154. );
  6155. if (!empty($folderData)) {
  6156. $folder = true;
  6157. }
  6158. $documentId = $folderData['id'];
  6159. } else {
  6160. $folder = true;
  6161. }
  6162. $dir = $dir.'/';
  6163. if ($folder) {
  6164. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6165. }
  6166. }
  6167. if (empty($documentId)) {
  6168. $dir = api_remove_trailing_slash($dir);
  6169. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6170. }
  6171. $array = [
  6172. 'dir' => $dir,
  6173. 'filepath' => $filepath,
  6174. 'folder' => $folder,
  6175. 'id' => $documentId,
  6176. ];
  6177. return $array;
  6178. }
  6179. /**
  6180. * Create a new document //still needs some finetuning.
  6181. *
  6182. * @param array $courseInfo
  6183. * @param string $content
  6184. * @param string $title
  6185. * @param string $extension
  6186. * @param int $parentId
  6187. * @param int $creatorId creator id
  6188. *
  6189. * @return int
  6190. */
  6191. public function create_document(
  6192. $courseInfo,
  6193. $content = '',
  6194. $title = '',
  6195. $extension = 'html',
  6196. $parentId = 0,
  6197. $creatorId = 0
  6198. ) {
  6199. if (!empty($courseInfo)) {
  6200. $course_id = $courseInfo['real_id'];
  6201. } else {
  6202. $course_id = api_get_course_int_id();
  6203. }
  6204. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6205. $sessionId = api_get_session_id();
  6206. // Generates folder
  6207. $result = $this->generate_lp_folder($courseInfo);
  6208. $dir = $result['dir'];
  6209. if (empty($parentId) || $parentId == '/') {
  6210. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6211. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6212. if ($parentId === '/') {
  6213. $dir = '/';
  6214. }
  6215. // Please, do not modify this dirname formatting.
  6216. if (strstr($dir, '..')) {
  6217. $dir = '/';
  6218. }
  6219. if (!empty($dir[0]) && $dir[0] == '.') {
  6220. $dir = substr($dir, 1);
  6221. }
  6222. if (!empty($dir[0]) && $dir[0] != '/') {
  6223. $dir = '/'.$dir;
  6224. }
  6225. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6226. $dir .= '/';
  6227. }
  6228. } else {
  6229. $parentInfo = DocumentManager::get_document_data_by_id(
  6230. $parentId,
  6231. $courseInfo['code']
  6232. );
  6233. if (!empty($parentInfo)) {
  6234. $dir = $parentInfo['path'].'/';
  6235. }
  6236. }
  6237. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6238. if (!is_dir($filepath)) {
  6239. $dir = '/';
  6240. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6241. }
  6242. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6243. // is already escaped twice when it gets here.
  6244. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6245. if (!empty($title)) {
  6246. $title = api_replace_dangerous_char(stripslashes($title));
  6247. } else {
  6248. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6249. }
  6250. $title = disable_dangerous_file($title);
  6251. $filename = $title;
  6252. $content = !empty($content) ? $content : $_POST['content_lp'];
  6253. $tmp_filename = $filename;
  6254. $i = 0;
  6255. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6256. $tmp_filename = $filename.'_'.++$i;
  6257. }
  6258. $filename = $tmp_filename.'.'.$extension;
  6259. if ($extension == 'html') {
  6260. $content = stripslashes($content);
  6261. $content = str_replace(
  6262. api_get_path(WEB_COURSE_PATH),
  6263. api_get_path(REL_PATH).'courses/',
  6264. $content
  6265. );
  6266. // Change the path of mp3 to absolute.
  6267. // The first regexp deals with :// urls.
  6268. $content = preg_replace(
  6269. "|(flashvars=\"file=)([^:/]+)/|",
  6270. "$1".api_get_path(
  6271. REL_COURSE_PATH
  6272. ).$courseInfo['path'].'/document/',
  6273. $content
  6274. );
  6275. // The second regexp deals with audio/ urls.
  6276. $content = preg_replace(
  6277. "|(flashvars=\"file=)([^/]+)/|",
  6278. "$1".api_get_path(
  6279. REL_COURSE_PATH
  6280. ).$courseInfo['path'].'/document/$2/',
  6281. $content
  6282. );
  6283. // For flv player: To prevent edition problem with firefox,
  6284. // we have to use a strange tip (don't blame me please).
  6285. $content = str_replace(
  6286. '</body>',
  6287. '<style type="text/css">body{}</style></body>',
  6288. $content
  6289. );
  6290. }
  6291. if (!file_exists($filepath.$filename)) {
  6292. if ($fp = @fopen($filepath.$filename, 'w')) {
  6293. fputs($fp, $content);
  6294. fclose($fp);
  6295. $file_size = filesize($filepath.$filename);
  6296. $save_file_path = $dir.$filename;
  6297. $document_id = add_document(
  6298. $courseInfo,
  6299. $save_file_path,
  6300. 'file',
  6301. $file_size,
  6302. $tmp_filename,
  6303. '',
  6304. 0, //readonly
  6305. true,
  6306. null,
  6307. $sessionId,
  6308. $creatorId
  6309. );
  6310. if ($document_id) {
  6311. api_item_property_update(
  6312. $courseInfo,
  6313. TOOL_DOCUMENT,
  6314. $document_id,
  6315. 'DocumentAdded',
  6316. $creatorId,
  6317. null,
  6318. null,
  6319. null,
  6320. null,
  6321. $sessionId
  6322. );
  6323. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6324. $new_title = $originalTitle;
  6325. if ($new_comment || $new_title) {
  6326. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6327. $ct = '';
  6328. if ($new_comment) {
  6329. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6330. }
  6331. if ($new_title) {
  6332. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6333. }
  6334. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6335. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6336. Database::query($sql);
  6337. }
  6338. }
  6339. return $document_id;
  6340. }
  6341. }
  6342. }
  6343. /**
  6344. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6345. *
  6346. * @param array $_course array
  6347. */
  6348. public function edit_document($_course)
  6349. {
  6350. $course_id = api_get_course_int_id();
  6351. $urlAppend = api_get_configuration_value('url_append');
  6352. // Please, do not modify this dirname formatting.
  6353. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6354. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6355. if (strstr($dir, '..')) {
  6356. $dir = '/';
  6357. }
  6358. if (isset($dir[0]) && $dir[0] == '.') {
  6359. $dir = substr($dir, 1);
  6360. }
  6361. if (isset($dir[0]) && $dir[0] != '/') {
  6362. $dir = '/'.$dir;
  6363. }
  6364. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6365. $dir .= '/';
  6366. }
  6367. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6368. if (!is_dir($filepath)) {
  6369. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6370. }
  6371. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6372. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6373. $document_id = (int) $_POST['path'];
  6374. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6375. if (empty($documentInfo)) {
  6376. // Try with iid
  6377. $table = Database::get_course_table(TABLE_DOCUMENT);
  6378. $sql = "SELECT id, path FROM $table
  6379. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6380. $res_doc = Database::query($sql);
  6381. $row = Database::fetch_array($res_doc);
  6382. if ($row) {
  6383. $document_id = $row['id'];
  6384. $documentPath = $row['path'];
  6385. }
  6386. } else {
  6387. $documentPath = $documentInfo['path'];
  6388. }
  6389. $content = stripslashes($_POST['content_lp']);
  6390. $file = $filepath.$documentPath;
  6391. if (!file_exists($file)) {
  6392. return false;
  6393. }
  6394. if ($fp = @fopen($file, 'w')) {
  6395. $content = str_replace(
  6396. api_get_path(WEB_COURSE_PATH),
  6397. $urlAppend.api_get_path(REL_COURSE_PATH),
  6398. $content
  6399. );
  6400. // Change the path of mp3 to absolute.
  6401. // The first regexp deals with :// urls.
  6402. $content = preg_replace(
  6403. "|(flashvars=\"file=)([^:/]+)/|",
  6404. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6405. $content
  6406. );
  6407. // The second regexp deals with audio/ urls.
  6408. $content = preg_replace(
  6409. "|(flashvars=\"file=)([^:/]+)/|",
  6410. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6411. $content
  6412. );
  6413. fputs($fp, $content);
  6414. fclose($fp);
  6415. $sql = "UPDATE $table_doc SET
  6416. title='".Database::escape_string($_POST['title'])."'
  6417. WHERE c_id = $course_id AND id = ".$document_id;
  6418. Database::query($sql);
  6419. }
  6420. }
  6421. }
  6422. /**
  6423. * Displays the selected item, with a panel for manipulating the item.
  6424. *
  6425. * @param int $item_id
  6426. * @param string $msg
  6427. * @param bool $show_actions
  6428. *
  6429. * @return string
  6430. */
  6431. public function display_item($item_id, $msg = null, $show_actions = true)
  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 lp.* FROM $tbl_lp_item as lp
  6438. WHERE lp.iid = ".intval($item_id);
  6439. $result = Database::query($sql);
  6440. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6441. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6442. // Prevents wrong parent selection for document, see Bug#1251.
  6443. if ($row['item_type'] != 'dir') {
  6444. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6445. }
  6446. if ($show_actions) {
  6447. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6448. }
  6449. $return .= '<div style="padding:10px;">';
  6450. if ($msg != '') {
  6451. $return .= $msg;
  6452. }
  6453. $return .= '<h3>'.$row['title'].'</h3>';
  6454. switch ($row['item_type']) {
  6455. case TOOL_THREAD:
  6456. $link = $this->rl_get_resource_link_for_learnpath(
  6457. $course_id,
  6458. $row['lp_id'],
  6459. $item_id,
  6460. 0
  6461. );
  6462. $return .= Display::url(
  6463. get_lang('GoToThread'),
  6464. $link,
  6465. ['class' => 'btn btn-primary']
  6466. );
  6467. break;
  6468. case TOOL_FORUM:
  6469. $return .= Display::url(
  6470. get_lang('GoToForum'),
  6471. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6472. ['class' => 'btn btn-primary']
  6473. );
  6474. break;
  6475. case TOOL_QUIZ:
  6476. if (!empty($row['path'])) {
  6477. $exercise = new Exercise();
  6478. $exercise->read($row['path']);
  6479. $return .= $exercise->description.'<br />';
  6480. $return .= Display::url(
  6481. get_lang('GoToExercise'),
  6482. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6483. ['class' => 'btn btn-primary']
  6484. );
  6485. }
  6486. break;
  6487. case TOOL_LP_FINAL_ITEM:
  6488. $return .= $this->getSavedFinalItem();
  6489. break;
  6490. case TOOL_DOCUMENT:
  6491. case TOOL_READOUT_TEXT:
  6492. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6493. $sql_doc = "SELECT path FROM $tbl_doc
  6494. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6495. $result = Database::query($sql_doc);
  6496. $path_file = Database::result($result, 0, 0);
  6497. $path_parts = pathinfo($path_file);
  6498. // TODO: Correct the following naive comparisons.
  6499. if (in_array($path_parts['extension'], [
  6500. 'html',
  6501. 'txt',
  6502. 'png',
  6503. 'jpg',
  6504. 'JPG',
  6505. 'jpeg',
  6506. 'JPEG',
  6507. 'gif',
  6508. 'swf',
  6509. 'pdf',
  6510. 'htm',
  6511. ])) {
  6512. $return .= $this->display_document($row['path'], true, true);
  6513. }
  6514. break;
  6515. case TOOL_HOTPOTATOES:
  6516. $return .= $this->display_document($row['path'], false, true);
  6517. break;
  6518. }
  6519. $return .= '</div>';
  6520. }
  6521. }
  6522. return $return;
  6523. }
  6524. /**
  6525. * Shows the needed forms for editing a specific item.
  6526. *
  6527. * @param int $item_id
  6528. *
  6529. * @throws Exception
  6530. * @throws HTML_QuickForm_Error
  6531. *
  6532. * @return string
  6533. */
  6534. public function display_edit_item($item_id)
  6535. {
  6536. $course_id = api_get_course_int_id();
  6537. $return = '';
  6538. $item_id = (int) $item_id;
  6539. if (empty($item_id)) {
  6540. return '';
  6541. }
  6542. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6543. $sql = "SELECT * FROM $tbl_lp_item
  6544. WHERE iid = ".$item_id;
  6545. $res = Database::query($sql);
  6546. $row = Database::fetch_array($res);
  6547. switch ($row['item_type']) {
  6548. case 'dir':
  6549. case 'asset':
  6550. case 'sco':
  6551. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6552. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6553. $return .= $this->display_item_form(
  6554. $row['item_type'],
  6555. get_lang('EditCurrentChapter').' :',
  6556. 'edit',
  6557. $item_id,
  6558. $row
  6559. );
  6560. } else {
  6561. $return .= $this->display_item_form(
  6562. $row['item_type'],
  6563. get_lang('EditCurrentChapter').' :',
  6564. 'edit_item',
  6565. $item_id,
  6566. $row
  6567. );
  6568. }
  6569. break;
  6570. case TOOL_DOCUMENT:
  6571. case TOOL_READOUT_TEXT:
  6572. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6573. $sql = "SELECT lp.*, doc.path as dir
  6574. FROM $tbl_lp_item as lp
  6575. LEFT JOIN $tbl_doc as doc
  6576. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6577. WHERE
  6578. doc.c_id = $course_id AND
  6579. lp.iid = ".$item_id;
  6580. $res_step = Database::query($sql);
  6581. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6582. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6583. if ($row['item_type'] === TOOL_DOCUMENT) {
  6584. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6585. }
  6586. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6587. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6588. }
  6589. break;
  6590. case TOOL_LINK:
  6591. $linkId = (int) $row['path'];
  6592. if (!empty($linkId)) {
  6593. $table = Database::get_course_table(TABLE_LINK);
  6594. $sql = 'SELECT url FROM '.$table.'
  6595. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6596. $res_link = Database::query($sql);
  6597. $row_link = Database::fetch_array($res_link);
  6598. if (empty($row_link)) {
  6599. // Try with id
  6600. $sql = 'SELECT url FROM '.$table.'
  6601. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6602. $res_link = Database::query($sql);
  6603. $row_link = Database::fetch_array($res_link);
  6604. }
  6605. if (is_array($row_link)) {
  6606. $row['url'] = $row_link['url'];
  6607. }
  6608. }
  6609. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6610. $return .= $this->display_link_form('edit', $item_id, $row);
  6611. break;
  6612. case TOOL_LP_FINAL_ITEM:
  6613. Session::write('finalItem', true);
  6614. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6615. $sql = "SELECT lp.*, doc.path as dir
  6616. FROM $tbl_lp_item as lp
  6617. LEFT JOIN $tbl_doc as doc
  6618. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6619. WHERE
  6620. doc.c_id = $course_id AND
  6621. lp.iid = ".$item_id;
  6622. $res_step = Database::query($sql);
  6623. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6624. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6625. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6626. break;
  6627. case TOOL_QUIZ:
  6628. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6629. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6630. break;
  6631. case TOOL_HOTPOTATOES:
  6632. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6633. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6634. break;
  6635. case TOOL_STUDENTPUBLICATION:
  6636. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6637. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6638. break;
  6639. case TOOL_FORUM:
  6640. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6641. $return .= $this->display_forum_form('edit', $item_id, $row);
  6642. break;
  6643. case TOOL_THREAD:
  6644. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6645. $return .= $this->display_thread_form('edit', $item_id, $row);
  6646. break;
  6647. }
  6648. return $return;
  6649. }
  6650. /**
  6651. * Function that displays a list with al the resources that
  6652. * could be added to the learning path.
  6653. *
  6654. * @throws Exception
  6655. * @throws HTML_QuickForm_Error
  6656. *
  6657. * @return bool
  6658. */
  6659. public function display_resources()
  6660. {
  6661. $course_code = api_get_course_id();
  6662. // Get all the docs.
  6663. $documents = $this->get_documents(true);
  6664. // Get all the exercises.
  6665. $exercises = $this->get_exercises();
  6666. // Get all the links.
  6667. $links = $this->get_links();
  6668. // Get all the student publications.
  6669. $works = $this->get_student_publications();
  6670. // Get all the forums.
  6671. $forums = $this->get_forums(null, $course_code);
  6672. // Get the final item form (see BT#11048) .
  6673. $finish = $this->getFinalItemForm();
  6674. $headers = [
  6675. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6676. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6677. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6678. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6679. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6680. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6681. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6682. ];
  6683. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6684. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6685. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  6686. echo Display::tabs(
  6687. $headers,
  6688. [
  6689. $documents,
  6690. $exercises,
  6691. $links,
  6692. $works,
  6693. $forums,
  6694. $dir,
  6695. $finish,
  6696. ],
  6697. 'resource_tab',
  6698. [],
  6699. [],
  6700. $selected
  6701. );
  6702. return true;
  6703. }
  6704. /**
  6705. * Returns the extension of a document.
  6706. *
  6707. * @param string $filename
  6708. *
  6709. * @return string Extension (part after the last dot)
  6710. */
  6711. public function get_extension($filename)
  6712. {
  6713. $explode = explode('.', $filename);
  6714. return $explode[count($explode) - 1];
  6715. }
  6716. /**
  6717. * Displays a document by id.
  6718. *
  6719. * @param int $id
  6720. * @param bool $show_title
  6721. * @param bool $iframe
  6722. * @param bool $edit_link
  6723. *
  6724. * @return string
  6725. */
  6726. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6727. {
  6728. $_course = api_get_course_info();
  6729. $course_id = api_get_course_int_id();
  6730. $id = (int) $id;
  6731. $return = '';
  6732. $table = Database::get_course_table(TABLE_DOCUMENT);
  6733. $sql_doc = "SELECT * FROM $table
  6734. WHERE c_id = $course_id AND iid = $id";
  6735. $res_doc = Database::query($sql_doc);
  6736. $row_doc = Database::fetch_array($res_doc);
  6737. // TODO: Add a path filter.
  6738. if ($iframe) {
  6739. $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>';
  6740. } else {
  6741. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6742. }
  6743. return $return;
  6744. }
  6745. /**
  6746. * Return HTML form to add/edit a quiz.
  6747. *
  6748. * @param string $action Action (add/edit)
  6749. * @param int $id Item ID if already exists
  6750. * @param mixed $extra_info Extra information (quiz ID if integer)
  6751. *
  6752. * @throws Exception
  6753. *
  6754. * @return string HTML form
  6755. */
  6756. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6757. {
  6758. $course_id = api_get_course_int_id();
  6759. $id = (int) $id;
  6760. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6761. if ($id != 0 && is_array($extra_info)) {
  6762. $item_title = $extra_info['title'];
  6763. $item_description = $extra_info['description'];
  6764. } elseif (is_numeric($extra_info)) {
  6765. $sql = "SELECT title, description
  6766. FROM $tbl_quiz
  6767. WHERE c_id = $course_id AND iid = ".$extra_info;
  6768. $result = Database::query($sql);
  6769. $row = Database::fetch_array($result);
  6770. $item_title = $row['title'];
  6771. $item_description = $row['description'];
  6772. } else {
  6773. $item_title = '';
  6774. $item_description = '';
  6775. }
  6776. $item_title = Security::remove_XSS($item_title);
  6777. $item_description = Security::remove_XSS($item_description);
  6778. $parent = 0;
  6779. if ($id != 0 && is_array($extra_info)) {
  6780. $parent = $extra_info['parent_item_id'];
  6781. }
  6782. $arrLP = $this->getItemsForForm();
  6783. $this->tree_array($arrLP);
  6784. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6785. unset($this->arrMenu);
  6786. $form = new FormValidator(
  6787. 'quiz_form',
  6788. 'POST',
  6789. $this->getCurrentBuildingModeURL()
  6790. );
  6791. $defaults = [];
  6792. if ($action === 'add') {
  6793. $legend = get_lang('CreateTheExercise');
  6794. } elseif ($action === 'move') {
  6795. $legend = get_lang('MoveTheCurrentExercise');
  6796. } else {
  6797. $legend = get_lang('EditCurrentExecice');
  6798. }
  6799. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6800. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6801. }
  6802. $form->addHeader($legend);
  6803. if ($action != 'move') {
  6804. $this->setItemTitle($form);
  6805. $defaults['title'] = $item_title;
  6806. }
  6807. // Select for Parent item, root or chapter
  6808. $selectParent = $form->addSelect(
  6809. 'parent',
  6810. get_lang('Parent'),
  6811. [],
  6812. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6813. );
  6814. $selectParent->addOption($this->name, 0);
  6815. $arrHide = [
  6816. $id,
  6817. ];
  6818. for ($i = 0; $i < count($arrLP); $i++) {
  6819. if ($action != 'add') {
  6820. if (
  6821. ($arrLP[$i]['item_type'] == 'dir') &&
  6822. !in_array($arrLP[$i]['id'], $arrHide) &&
  6823. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6824. ) {
  6825. $selectParent->addOption(
  6826. $arrLP[$i]['title'],
  6827. $arrLP[$i]['id'],
  6828. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6829. );
  6830. if ($parent == $arrLP[$i]['id']) {
  6831. $selectParent->setSelected($arrLP[$i]['id']);
  6832. }
  6833. } else {
  6834. $arrHide[] = $arrLP[$i]['id'];
  6835. }
  6836. } else {
  6837. if ($arrLP[$i]['item_type'] == 'dir') {
  6838. $selectParent->addOption(
  6839. $arrLP[$i]['title'],
  6840. $arrLP[$i]['id'],
  6841. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6842. );
  6843. if ($parent == $arrLP[$i]['id']) {
  6844. $selectParent->setSelected($arrLP[$i]['id']);
  6845. }
  6846. }
  6847. }
  6848. }
  6849. if (is_array($arrLP)) {
  6850. reset($arrLP);
  6851. }
  6852. $selectPrevious = $form->addSelect(
  6853. 'previous',
  6854. get_lang('Position'),
  6855. [],
  6856. ['id' => 'previous']
  6857. );
  6858. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6859. for ($i = 0; $i < count($arrLP); $i++) {
  6860. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6861. $arrLP[$i]['id'] != $id
  6862. ) {
  6863. $selectPrevious->addOption(
  6864. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6865. $arrLP[$i]['id']
  6866. );
  6867. if (is_array($extra_info)) {
  6868. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6869. $selectPrevious->setSelected($arrLP[$i]['id']);
  6870. }
  6871. } elseif ($action == 'add') {
  6872. $selectPrevious->setSelected($arrLP[$i]['id']);
  6873. }
  6874. }
  6875. }
  6876. if ($action != 'move') {
  6877. $arrHide = [];
  6878. for ($i = 0; $i < count($arrLP); $i++) {
  6879. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6880. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6881. }
  6882. }
  6883. }
  6884. if ($action === 'add') {
  6885. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6886. } else {
  6887. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6888. }
  6889. if ($action === 'move') {
  6890. $form->addHidden('title', $item_title);
  6891. $form->addHidden('description', $item_description);
  6892. }
  6893. if (is_numeric($extra_info)) {
  6894. $form->addHidden('path', $extra_info);
  6895. } elseif (is_array($extra_info)) {
  6896. $form->addHidden('path', $extra_info['path']);
  6897. }
  6898. $form->addHidden('type', TOOL_QUIZ);
  6899. $form->addHidden('post_time', time());
  6900. $form->setDefaults($defaults);
  6901. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6902. }
  6903. /**
  6904. * Addition of Hotpotatoes tests.
  6905. *
  6906. * @param string $action
  6907. * @param int $id Internal ID of the item
  6908. * @param string $extra_info
  6909. *
  6910. * @return string HTML structure to display the hotpotatoes addition formular
  6911. */
  6912. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6913. {
  6914. $course_id = api_get_course_int_id();
  6915. $uploadPath = DIR_HOTPOTATOES;
  6916. if ($id != 0 && is_array($extra_info)) {
  6917. $item_title = stripslashes($extra_info['title']);
  6918. $item_description = stripslashes($extra_info['description']);
  6919. } elseif (is_numeric($extra_info)) {
  6920. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6921. $sql = "SELECT * FROM $TBL_DOCUMENT
  6922. WHERE
  6923. c_id = $course_id AND
  6924. path LIKE '".$uploadPath."/%/%htm%' AND
  6925. iid = ".(int) $extra_info."
  6926. ORDER BY iid ASC";
  6927. $res_hot = Database::query($sql);
  6928. $row = Database::fetch_array($res_hot);
  6929. $item_title = $row['title'];
  6930. $item_description = $row['description'];
  6931. if (!empty($row['comment'])) {
  6932. $item_title = $row['comment'];
  6933. }
  6934. } else {
  6935. $item_title = '';
  6936. $item_description = '';
  6937. }
  6938. $parent = 0;
  6939. if ($id != 0 && is_array($extra_info)) {
  6940. $parent = $extra_info['parent_item_id'];
  6941. }
  6942. $arrLP = $this->getItemsForForm();
  6943. $legend = '<legend>';
  6944. if ($action == 'add') {
  6945. $legend .= get_lang('CreateTheExercise');
  6946. } elseif ($action == 'move') {
  6947. $legend .= get_lang('MoveTheCurrentExercise');
  6948. } else {
  6949. $legend .= get_lang('EditCurrentExecice');
  6950. }
  6951. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6952. $legend .= Display:: return_message(
  6953. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6954. );
  6955. }
  6956. $legend .= '</legend>';
  6957. $return = '<form method="POST">';
  6958. $return .= $legend;
  6959. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6960. $return .= '<tr>';
  6961. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6962. $return .= '<td class="input">';
  6963. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6964. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6965. $arrHide = [$id];
  6966. if (count($arrLP) > 0) {
  6967. for ($i = 0; $i < count($arrLP); $i++) {
  6968. if ($action != 'add') {
  6969. if ($arrLP[$i]['item_type'] == 'dir' &&
  6970. !in_array($arrLP[$i]['id'], $arrHide) &&
  6971. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6972. ) {
  6973. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6974. } else {
  6975. $arrHide[] = $arrLP[$i]['id'];
  6976. }
  6977. } else {
  6978. if ($arrLP[$i]['item_type'] == 'dir') {
  6979. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6980. }
  6981. }
  6982. }
  6983. reset($arrLP);
  6984. }
  6985. $return .= '</select>';
  6986. $return .= '</td>';
  6987. $return .= '</tr>';
  6988. $return .= '<tr>';
  6989. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6990. $return .= '<td class="input">';
  6991. $return .= '<select id="previous" name="previous" size="1">';
  6992. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6993. for ($i = 0; $i < count($arrLP); $i++) {
  6994. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6995. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6996. $selected = 'selected="selected" ';
  6997. } elseif ($action == 'add') {
  6998. $selected = 'selected="selected" ';
  6999. } else {
  7000. $selected = '';
  7001. }
  7002. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.
  7003. get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7004. }
  7005. }
  7006. $return .= '</select>';
  7007. $return .= '</td>';
  7008. $return .= '</tr>';
  7009. if ($action != 'move') {
  7010. $return .= '<tr>';
  7011. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7012. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7013. $return .= '</tr>';
  7014. $id_prerequisite = 0;
  7015. if (is_array($arrLP) && count($arrLP) > 0) {
  7016. foreach ($arrLP as $key => $value) {
  7017. if ($value['id'] == $id) {
  7018. $id_prerequisite = $value['prerequisite'];
  7019. break;
  7020. }
  7021. }
  7022. $arrHide = [];
  7023. for ($i = 0; $i < count($arrLP); $i++) {
  7024. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7025. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7026. }
  7027. }
  7028. }
  7029. }
  7030. $return .= '<tr>';
  7031. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7032. get_lang('SaveHotpotatoes').'</button></td>';
  7033. $return .= '</tr>';
  7034. $return .= '</table>';
  7035. if ($action == 'move') {
  7036. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7037. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7038. }
  7039. if (is_numeric($extra_info)) {
  7040. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7041. } elseif (is_array($extra_info)) {
  7042. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7043. }
  7044. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7045. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7046. $return .= '</form>';
  7047. return $return;
  7048. }
  7049. /**
  7050. * Return the form to display the forum edit/add option.
  7051. *
  7052. * @param string $action
  7053. * @param int $id ID of the lp_item if already exists
  7054. * @param string $extra_info
  7055. *
  7056. * @throws Exception
  7057. *
  7058. * @return string HTML form
  7059. */
  7060. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7061. {
  7062. $course_id = api_get_course_int_id();
  7063. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7064. $item_title = '';
  7065. $item_description = '';
  7066. if ($id != 0 && is_array($extra_info)) {
  7067. $item_title = stripslashes($extra_info['title']);
  7068. } elseif (is_numeric($extra_info)) {
  7069. $sql = "SELECT forum_title as title, forum_comment as comment
  7070. FROM $tbl_forum
  7071. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7072. $result = Database::query($sql);
  7073. $row = Database::fetch_array($result);
  7074. $item_title = $row['title'];
  7075. $item_description = $row['comment'];
  7076. }
  7077. $parent = 0;
  7078. if ($id != 0 && is_array($extra_info)) {
  7079. $parent = $extra_info['parent_item_id'];
  7080. }
  7081. $arrLP = $this->getItemsForForm();
  7082. $this->tree_array($arrLP);
  7083. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7084. unset($this->arrMenu);
  7085. if ($action == 'add') {
  7086. $legend = get_lang('CreateTheForum');
  7087. } elseif ($action == 'move') {
  7088. $legend = get_lang('MoveTheCurrentForum');
  7089. } else {
  7090. $legend = get_lang('EditCurrentForum');
  7091. }
  7092. $form = new FormValidator(
  7093. 'forum_form',
  7094. 'POST',
  7095. $this->getCurrentBuildingModeURL()
  7096. );
  7097. $defaults = [];
  7098. $form->addHeader($legend);
  7099. if ($action != 'move') {
  7100. $this->setItemTitle($form);
  7101. $defaults['title'] = $item_title;
  7102. }
  7103. $selectParent = $form->addSelect(
  7104. 'parent',
  7105. get_lang('Parent'),
  7106. [],
  7107. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7108. );
  7109. $selectParent->addOption($this->name, 0);
  7110. $arrHide = [
  7111. $id,
  7112. ];
  7113. for ($i = 0; $i < count($arrLP); $i++) {
  7114. if ($action != 'add') {
  7115. if ($arrLP[$i]['item_type'] == 'dir' &&
  7116. !in_array($arrLP[$i]['id'], $arrHide) &&
  7117. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7118. ) {
  7119. $selectParent->addOption(
  7120. $arrLP[$i]['title'],
  7121. $arrLP[$i]['id'],
  7122. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7123. );
  7124. if ($parent == $arrLP[$i]['id']) {
  7125. $selectParent->setSelected($arrLP[$i]['id']);
  7126. }
  7127. } else {
  7128. $arrHide[] = $arrLP[$i]['id'];
  7129. }
  7130. } else {
  7131. if ($arrLP[$i]['item_type'] == 'dir') {
  7132. $selectParent->addOption(
  7133. $arrLP[$i]['title'],
  7134. $arrLP[$i]['id'],
  7135. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7136. );
  7137. if ($parent == $arrLP[$i]['id']) {
  7138. $selectParent->setSelected($arrLP[$i]['id']);
  7139. }
  7140. }
  7141. }
  7142. }
  7143. if (is_array($arrLP)) {
  7144. reset($arrLP);
  7145. }
  7146. $selectPrevious = $form->addSelect(
  7147. 'previous',
  7148. get_lang('Position'),
  7149. [],
  7150. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7151. );
  7152. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7153. for ($i = 0; $i < count($arrLP); $i++) {
  7154. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7155. $arrLP[$i]['id'] != $id
  7156. ) {
  7157. $selectPrevious->addOption(
  7158. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7159. $arrLP[$i]['id']
  7160. );
  7161. if (isset($extra_info['previous_item_id']) &&
  7162. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7163. ) {
  7164. $selectPrevious->setSelected($arrLP[$i]['id']);
  7165. } elseif ($action == 'add') {
  7166. $selectPrevious->setSelected($arrLP[$i]['id']);
  7167. }
  7168. }
  7169. }
  7170. if ($action != 'move') {
  7171. $id_prerequisite = 0;
  7172. if (is_array($arrLP)) {
  7173. foreach ($arrLP as $key => $value) {
  7174. if ($value['id'] == $id) {
  7175. $id_prerequisite = $value['prerequisite'];
  7176. break;
  7177. }
  7178. }
  7179. }
  7180. $arrHide = [];
  7181. for ($i = 0; $i < count($arrLP); $i++) {
  7182. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7183. if (isset($extra_info['previous_item_id']) &&
  7184. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7185. ) {
  7186. $s_selected_position = $arrLP[$i]['id'];
  7187. } elseif ($action == 'add') {
  7188. $s_selected_position = 0;
  7189. }
  7190. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7191. }
  7192. }
  7193. }
  7194. if ($action == 'add') {
  7195. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7196. } else {
  7197. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7198. }
  7199. if ($action == 'move') {
  7200. $form->addHidden('title', $item_title);
  7201. $form->addHidden('description', $item_description);
  7202. }
  7203. if (is_numeric($extra_info)) {
  7204. $form->addHidden('path', $extra_info);
  7205. } elseif (is_array($extra_info)) {
  7206. $form->addHidden('path', $extra_info['path']);
  7207. }
  7208. $form->addHidden('type', TOOL_FORUM);
  7209. $form->addHidden('post_time', time());
  7210. $form->setDefaults($defaults);
  7211. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7212. }
  7213. /**
  7214. * Return HTML form to add/edit forum threads.
  7215. *
  7216. * @param string $action
  7217. * @param int $id Item ID if already exists in learning path
  7218. * @param string $extra_info
  7219. *
  7220. * @throws Exception
  7221. *
  7222. * @return string HTML form
  7223. */
  7224. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7225. {
  7226. $course_id = api_get_course_int_id();
  7227. if (empty($course_id)) {
  7228. return null;
  7229. }
  7230. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7231. $item_title = '';
  7232. $item_description = '';
  7233. if ($id != 0 && is_array($extra_info)) {
  7234. $item_title = stripslashes($extra_info['title']);
  7235. } elseif (is_numeric($extra_info)) {
  7236. $sql = "SELECT thread_title as title FROM $tbl_forum
  7237. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7238. $result = Database::query($sql);
  7239. $row = Database::fetch_array($result);
  7240. $item_title = $row['title'];
  7241. $item_description = '';
  7242. }
  7243. $parent = 0;
  7244. if ($id != 0 && is_array($extra_info)) {
  7245. $parent = $extra_info['parent_item_id'];
  7246. }
  7247. $arrLP = $this->getItemsForForm();
  7248. $this->tree_array($arrLP);
  7249. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7250. unset($this->arrMenu);
  7251. $form = new FormValidator(
  7252. 'thread_form',
  7253. 'POST',
  7254. $this->getCurrentBuildingModeURL()
  7255. );
  7256. $defaults = [];
  7257. if ($action == 'add') {
  7258. $legend = get_lang('CreateTheForum');
  7259. } elseif ($action == 'move') {
  7260. $legend = get_lang('MoveTheCurrentForum');
  7261. } else {
  7262. $legend = get_lang('EditCurrentForum');
  7263. }
  7264. $form->addHeader($legend);
  7265. $selectParent = $form->addSelect(
  7266. 'parent',
  7267. get_lang('Parent'),
  7268. [],
  7269. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7270. );
  7271. $selectParent->addOption($this->name, 0);
  7272. $arrHide = [
  7273. $id,
  7274. ];
  7275. for ($i = 0; $i < count($arrLP); $i++) {
  7276. if ($action != 'add') {
  7277. if (
  7278. ($arrLP[$i]['item_type'] == 'dir') &&
  7279. !in_array($arrLP[$i]['id'], $arrHide) &&
  7280. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7281. ) {
  7282. $selectParent->addOption(
  7283. $arrLP[$i]['title'],
  7284. $arrLP[$i]['id'],
  7285. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7286. );
  7287. if ($parent == $arrLP[$i]['id']) {
  7288. $selectParent->setSelected($arrLP[$i]['id']);
  7289. }
  7290. } else {
  7291. $arrHide[] = $arrLP[$i]['id'];
  7292. }
  7293. } else {
  7294. if ($arrLP[$i]['item_type'] == 'dir') {
  7295. $selectParent->addOption(
  7296. $arrLP[$i]['title'],
  7297. $arrLP[$i]['id'],
  7298. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7299. );
  7300. if ($parent == $arrLP[$i]['id']) {
  7301. $selectParent->setSelected($arrLP[$i]['id']);
  7302. }
  7303. }
  7304. }
  7305. }
  7306. if ($arrLP != null) {
  7307. reset($arrLP);
  7308. }
  7309. $selectPrevious = $form->addSelect(
  7310. 'previous',
  7311. get_lang('Position'),
  7312. [],
  7313. ['id' => 'previous']
  7314. );
  7315. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7316. for ($i = 0; $i < count($arrLP); $i++) {
  7317. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7318. $selectPrevious->addOption(
  7319. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7320. $arrLP[$i]['id']
  7321. );
  7322. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7323. $selectPrevious->setSelected($arrLP[$i]['id']);
  7324. } elseif ($action == 'add') {
  7325. $selectPrevious->setSelected($arrLP[$i]['id']);
  7326. }
  7327. }
  7328. }
  7329. if ($action != 'move') {
  7330. $this->setItemTitle($form);
  7331. $defaults['title'] = $item_title;
  7332. $id_prerequisite = 0;
  7333. if ($arrLP != null) {
  7334. foreach ($arrLP as $key => $value) {
  7335. if ($value['id'] == $id) {
  7336. $id_prerequisite = $value['prerequisite'];
  7337. break;
  7338. }
  7339. }
  7340. }
  7341. $arrHide = [];
  7342. $s_selected_position = 0;
  7343. for ($i = 0; $i < count($arrLP); $i++) {
  7344. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7345. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7346. $s_selected_position = $arrLP[$i]['id'];
  7347. } elseif ($action == 'add') {
  7348. $s_selected_position = 0;
  7349. }
  7350. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7351. }
  7352. }
  7353. $selectPrerequisites = $form->addSelect(
  7354. 'prerequisites',
  7355. get_lang('LearnpathPrerequisites'),
  7356. [],
  7357. ['id' => 'prerequisites']
  7358. );
  7359. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7360. foreach ($arrHide as $key => $value) {
  7361. $selectPrerequisites->addOption($value['value'], $key);
  7362. if ($key == $s_selected_position && $action == 'add') {
  7363. $selectPrerequisites->setSelected($key);
  7364. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7365. $selectPrerequisites->setSelected($key);
  7366. }
  7367. }
  7368. }
  7369. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7370. if ($action == 'move') {
  7371. $form->addHidden('title', $item_title);
  7372. $form->addHidden('description', $item_description);
  7373. }
  7374. if (is_numeric($extra_info)) {
  7375. $form->addHidden('path', $extra_info);
  7376. } elseif (is_array($extra_info)) {
  7377. $form->addHidden('path', $extra_info['path']);
  7378. }
  7379. $form->addHidden('type', TOOL_THREAD);
  7380. $form->addHidden('post_time', time());
  7381. $form->setDefaults($defaults);
  7382. return $form->returnForm();
  7383. }
  7384. /**
  7385. * Return the HTML form to display an item (generally a dir item).
  7386. *
  7387. * @param string $item_type
  7388. * @param string $title
  7389. * @param string $action
  7390. * @param int $id
  7391. * @param string $extra_info
  7392. *
  7393. * @throws Exception
  7394. * @throws HTML_QuickForm_Error
  7395. *
  7396. * @return string HTML form
  7397. */
  7398. public function display_item_form(
  7399. $item_type,
  7400. $title = '',
  7401. $action = 'add_item',
  7402. $id = 0,
  7403. $extra_info = 'new'
  7404. ) {
  7405. $_course = api_get_course_info();
  7406. global $charset;
  7407. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7408. $item_title = '';
  7409. $item_description = '';
  7410. $item_path_fck = '';
  7411. if ($id != 0 && is_array($extra_info)) {
  7412. $item_title = $extra_info['title'];
  7413. $item_description = $extra_info['description'];
  7414. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7415. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7416. }
  7417. $parent = 0;
  7418. if ($id != 0 && is_array($extra_info)) {
  7419. $parent = $extra_info['parent_item_id'];
  7420. }
  7421. $id = (int) $id;
  7422. $sql = "SELECT * FROM $tbl_lp_item
  7423. WHERE
  7424. lp_id = ".$this->lp_id." AND
  7425. iid != $id";
  7426. if ($item_type == 'dir') {
  7427. $sql .= " AND parent_item_id = 0";
  7428. }
  7429. $result = Database::query($sql);
  7430. $arrLP = [];
  7431. while ($row = Database::fetch_array($result)) {
  7432. $arrLP[] = [
  7433. 'id' => $row['iid'],
  7434. 'item_type' => $row['item_type'],
  7435. 'title' => $this->cleanItemTitle($row['title']),
  7436. 'title_raw' => $row['title'],
  7437. 'path' => $row['path'],
  7438. 'description' => $row['description'],
  7439. 'parent_item_id' => $row['parent_item_id'],
  7440. 'previous_item_id' => $row['previous_item_id'],
  7441. 'next_item_id' => $row['next_item_id'],
  7442. 'max_score' => $row['max_score'],
  7443. 'min_score' => $row['min_score'],
  7444. 'mastery_score' => $row['mastery_score'],
  7445. 'prerequisite' => $row['prerequisite'],
  7446. 'display_order' => $row['display_order'],
  7447. ];
  7448. }
  7449. $this->tree_array($arrLP);
  7450. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7451. unset($this->arrMenu);
  7452. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7453. $form = new FormValidator('form_'.$item_type, 'POST', $url);
  7454. $defaults['title'] = api_html_entity_decode(
  7455. $item_title,
  7456. ENT_QUOTES,
  7457. $charset
  7458. );
  7459. $defaults['description'] = $item_description;
  7460. $form->addHeader($title);
  7461. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7462. $arrHide[0]['padding'] = 20;
  7463. $charset = api_get_system_encoding();
  7464. for ($i = 0; $i < count($arrLP); $i++) {
  7465. if ($action != 'add') {
  7466. if ($arrLP[$i]['item_type'] === 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7467. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7468. ) {
  7469. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7470. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7471. if ($parent == $arrLP[$i]['id']) {
  7472. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7473. }
  7474. }
  7475. } else {
  7476. if ($arrLP[$i]['item_type'] === 'dir') {
  7477. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7478. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7479. if ($parent == $arrLP[$i]['id']) {
  7480. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7481. }
  7482. }
  7483. }
  7484. }
  7485. if ($action != 'move') {
  7486. $this->setItemTitle($form);
  7487. } else {
  7488. $form->addElement('hidden', 'title');
  7489. }
  7490. $parentSelect = $form->addElement(
  7491. 'select',
  7492. 'parent',
  7493. get_lang('Parent'),
  7494. '',
  7495. [
  7496. 'id' => 'idParent',
  7497. 'onchange' => 'javascript: load_cbo(this.value);',
  7498. ]
  7499. );
  7500. foreach ($arrHide as $key => $value) {
  7501. $parentSelect->addOption(
  7502. $value['value'],
  7503. $key,
  7504. 'style="padding-left:'.$value['padding'].'px;"'
  7505. );
  7506. $lastPosition = $key;
  7507. }
  7508. if (!empty($s_selected_parent)) {
  7509. $parentSelect->setSelected($s_selected_parent);
  7510. }
  7511. if (is_array($arrLP)) {
  7512. reset($arrLP);
  7513. }
  7514. $arrHide = [];
  7515. // POSITION
  7516. for ($i = 0; $i < count($arrLP); $i++) {
  7517. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7518. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7519. //this is the same!
  7520. if (isset($extra_info['previous_item_id']) &&
  7521. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7522. ) {
  7523. $s_selected_position = $arrLP[$i]['id'];
  7524. } elseif ($action == 'add') {
  7525. $s_selected_position = $arrLP[$i]['id'];
  7526. }
  7527. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7528. }
  7529. }
  7530. $position = $form->addElement(
  7531. 'select',
  7532. 'previous',
  7533. get_lang('Position'),
  7534. '',
  7535. ['id' => 'previous']
  7536. );
  7537. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7538. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7539. $lastPosition = null;
  7540. foreach ($arrHide as $key => $value) {
  7541. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7542. $lastPosition = $key;
  7543. }
  7544. if (!empty($s_selected_position)) {
  7545. $position->setSelected($s_selected_position);
  7546. }
  7547. // When new chapter add at the end
  7548. if ($action === 'add_item') {
  7549. $position->setSelected($lastPosition);
  7550. }
  7551. if (is_array($arrLP)) {
  7552. reset($arrLP);
  7553. }
  7554. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7555. //fix in order to use the tab
  7556. if ($item_type === 'dir') {
  7557. $form->addElement('hidden', 'type', 'dir');
  7558. }
  7559. $extension = null;
  7560. if (!empty($item_path)) {
  7561. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7562. }
  7563. //assets can't be modified
  7564. //$item_type == 'asset' ||
  7565. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7566. if ($item_type == 'sco') {
  7567. $form->addElement(
  7568. 'html',
  7569. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7570. );
  7571. }
  7572. $renderer = $form->defaultRenderer();
  7573. $renderer->setElementTemplate(
  7574. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7575. 'content_lp'
  7576. );
  7577. $relative_prefix = '';
  7578. $editor_config = [
  7579. 'ToolbarSet' => 'LearningPathDocuments',
  7580. 'Width' => '100%',
  7581. 'Height' => '500',
  7582. 'FullPage' => true,
  7583. 'CreateDocumentDir' => $relative_prefix,
  7584. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7585. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7586. ];
  7587. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7588. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7589. $defaults['content_lp'] = file_get_contents($content_path);
  7590. }
  7591. if (!empty($id)) {
  7592. $form->addHidden('id', $id);
  7593. }
  7594. $form->addElement('hidden', 'type', $item_type);
  7595. $form->addElement('hidden', 'post_time', time());
  7596. $form->setDefaults($defaults);
  7597. return $form->returnForm();
  7598. }
  7599. /**
  7600. * @return string
  7601. */
  7602. public function getCurrentBuildingModeURL()
  7603. {
  7604. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7605. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7606. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7607. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7608. $currentUrl = api_get_self().'?'.api_get_cidreq().
  7609. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7610. return $currentUrl;
  7611. }
  7612. /**
  7613. * Returns the form to update or create a document.
  7614. *
  7615. * @param string $action (add/edit)
  7616. * @param int $id ID of the lp_item (if already exists)
  7617. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7618. *
  7619. * @throws Exception
  7620. * @throws HTML_QuickForm_Error
  7621. *
  7622. * @return string HTML form
  7623. */
  7624. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7625. {
  7626. $course_id = api_get_course_int_id();
  7627. $_course = api_get_course_info();
  7628. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7629. $no_display_edit_textarea = false;
  7630. $item_description = '';
  7631. //If action==edit document
  7632. //We don't display the document form if it's not an editable document (html or txt file)
  7633. if ($action === 'edit') {
  7634. if (is_array($extra_info)) {
  7635. $path_parts = pathinfo($extra_info['dir']);
  7636. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7637. $no_display_edit_textarea = true;
  7638. }
  7639. }
  7640. }
  7641. $no_display_add = false;
  7642. // If action==add an existing document
  7643. // We don't display the document form if it's not an editable document (html or txt file).
  7644. if ($action === 'add') {
  7645. if (is_numeric($extra_info)) {
  7646. $extra_info = (int) $extra_info;
  7647. $sql_doc = "SELECT path FROM $tbl_doc
  7648. WHERE c_id = $course_id AND iid = ".$extra_info;
  7649. $result = Database::query($sql_doc);
  7650. $path_file = Database::result($result, 0, 0);
  7651. $path_parts = pathinfo($path_file);
  7652. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7653. $no_display_add = true;
  7654. }
  7655. }
  7656. }
  7657. $item_title = '';
  7658. $item_description = '';
  7659. if ($id != 0 && is_array($extra_info)) {
  7660. $item_title = stripslashes($extra_info['title']);
  7661. $item_description = stripslashes($extra_info['description']);
  7662. if (empty($item_title)) {
  7663. $path_parts = pathinfo($extra_info['path']);
  7664. $item_title = stripslashes($path_parts['filename']);
  7665. }
  7666. } elseif (is_numeric($extra_info)) {
  7667. $sql = "SELECT path, title FROM $tbl_doc
  7668. WHERE
  7669. c_id = ".$course_id." AND
  7670. iid = ".intval($extra_info);
  7671. $result = Database::query($sql);
  7672. $row = Database::fetch_array($result);
  7673. $item_title = $row['title'];
  7674. $item_title = str_replace('_', ' ', $item_title);
  7675. if (empty($item_title)) {
  7676. $path_parts = pathinfo($row['path']);
  7677. $item_title = stripslashes($path_parts['filename']);
  7678. }
  7679. }
  7680. $return = '<legend>';
  7681. $parent = 0;
  7682. if ($id != 0 && is_array($extra_info)) {
  7683. $parent = $extra_info['parent_item_id'];
  7684. }
  7685. $arrLP = $this->getItemsForForm();
  7686. $this->tree_array($arrLP);
  7687. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7688. unset($this->arrMenu);
  7689. if ($action == 'add') {
  7690. $return .= get_lang('CreateTheDocument');
  7691. } elseif ($action == 'move') {
  7692. $return .= get_lang('MoveTheCurrentDocument');
  7693. } else {
  7694. $return .= get_lang('EditTheCurrentDocument');
  7695. }
  7696. $return .= '</legend>';
  7697. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7698. $return .= Display::return_message(
  7699. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7700. false
  7701. );
  7702. }
  7703. $form = new FormValidator(
  7704. 'form',
  7705. 'POST',
  7706. $this->getCurrentBuildingModeURL(),
  7707. '',
  7708. ['enctype' => 'multipart/form-data']
  7709. );
  7710. $defaults['title'] = Security::remove_XSS($item_title);
  7711. if (empty($item_title)) {
  7712. $defaults['title'] = Security::remove_XSS($item_title);
  7713. }
  7714. $defaults['description'] = $item_description;
  7715. $form->addElement('html', $return);
  7716. if ($action != 'move') {
  7717. $data = $this->generate_lp_folder($_course);
  7718. if ($action != 'edit') {
  7719. $folders = DocumentManager::get_all_document_folders(
  7720. $_course,
  7721. 0,
  7722. true
  7723. );
  7724. DocumentManager::build_directory_selector(
  7725. $folders,
  7726. '',
  7727. [],
  7728. true,
  7729. $form,
  7730. 'directory_parent_id'
  7731. );
  7732. }
  7733. if (isset($data['id'])) {
  7734. $defaults['directory_parent_id'] = $data['id'];
  7735. }
  7736. $this->setItemTitle($form);
  7737. }
  7738. $arrHide[0]['value'] = $this->name;
  7739. $arrHide[0]['padding'] = 20;
  7740. for ($i = 0; $i < count($arrLP); $i++) {
  7741. if ($action != 'add') {
  7742. if ($arrLP[$i]['item_type'] == 'dir' &&
  7743. !in_array($arrLP[$i]['id'], $arrHide) &&
  7744. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7745. ) {
  7746. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7747. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7748. }
  7749. } else {
  7750. if ($arrLP[$i]['item_type'] == 'dir') {
  7751. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7752. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7753. }
  7754. }
  7755. }
  7756. $parentSelect = $form->addSelect(
  7757. 'parent',
  7758. get_lang('Parent'),
  7759. [],
  7760. [
  7761. 'id' => 'idParent',
  7762. 'onchange' => 'javascript: load_cbo(this.value);',
  7763. ]
  7764. );
  7765. $my_count = 0;
  7766. foreach ($arrHide as $key => $value) {
  7767. if ($my_count != 0) {
  7768. // The LP name is also the first section and is not in the same charset like the other sections.
  7769. $value['value'] = Security::remove_XSS($value['value']);
  7770. $parentSelect->addOption(
  7771. $value['value'],
  7772. $key,
  7773. 'style="padding-left:'.$value['padding'].'px;"'
  7774. );
  7775. } else {
  7776. $value['value'] = Security::remove_XSS($value['value']);
  7777. $parentSelect->addOption(
  7778. $value['value'],
  7779. $key,
  7780. 'style="padding-left:'.$value['padding'].'px;"'
  7781. );
  7782. }
  7783. $my_count++;
  7784. }
  7785. if (!empty($id)) {
  7786. $parentSelect->setSelected($parent);
  7787. } else {
  7788. $parent_item_id = Session::read('parent_item_id', 0);
  7789. $parentSelect->setSelected($parent_item_id);
  7790. }
  7791. if (is_array($arrLP)) {
  7792. reset($arrLP);
  7793. }
  7794. $arrHide = [];
  7795. // POSITION
  7796. for ($i = 0; $i < count($arrLP); $i++) {
  7797. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7798. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7799. ) {
  7800. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7801. }
  7802. }
  7803. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  7804. $position = $form->addSelect(
  7805. 'previous',
  7806. get_lang('Position'),
  7807. [],
  7808. ['id' => 'previous']
  7809. );
  7810. $position->addOption(get_lang('FirstPosition'), 0);
  7811. foreach ($arrHide as $key => $value) {
  7812. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7813. $position->addOption(
  7814. $value['value'],
  7815. $key,
  7816. 'style="padding-left:'.$padding.'px;"'
  7817. );
  7818. }
  7819. $position->setSelected($selectedPosition);
  7820. if (is_array($arrLP)) {
  7821. reset($arrLP);
  7822. }
  7823. if ($action != 'move') {
  7824. $arrHide = [];
  7825. for ($i = 0; $i < count($arrLP); $i++) {
  7826. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7827. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7828. ) {
  7829. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7830. }
  7831. }
  7832. if (!$no_display_add) {
  7833. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7834. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7835. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  7836. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  7837. ) {
  7838. if (isset($_POST['content'])) {
  7839. $content = stripslashes($_POST['content']);
  7840. } elseif (is_array($extra_info)) {
  7841. //If it's an html document or a text file
  7842. if (!$no_display_edit_textarea) {
  7843. $content = $this->display_document(
  7844. $extra_info['path'],
  7845. false,
  7846. false
  7847. );
  7848. }
  7849. } elseif (is_numeric($extra_info)) {
  7850. $content = $this->display_document(
  7851. $extra_info,
  7852. false,
  7853. false
  7854. );
  7855. } else {
  7856. $content = '';
  7857. }
  7858. if (!$no_display_edit_textarea) {
  7859. // We need to calculate here some specific settings for the online editor.
  7860. // The calculated settings work for documents in the Documents tool
  7861. // (on the root or in subfolders).
  7862. // For documents in native scorm packages it is unclear whether the
  7863. // online editor should be activated or not.
  7864. // A new document, it is in the root of the repository.
  7865. $relative_path = '';
  7866. $relative_prefix = '';
  7867. if (is_array($extra_info) && $extra_info != 'new') {
  7868. // The document already exists. Whe have to determine its relative path towards the repository root.
  7869. $relative_path = explode('/', $extra_info['dir']);
  7870. $cnt = count($relative_path) - 2;
  7871. if ($cnt < 0) {
  7872. $cnt = 0;
  7873. }
  7874. $relative_prefix = str_repeat('../', $cnt);
  7875. $relative_path = array_slice($relative_path, 1, $cnt);
  7876. $relative_path = implode('/', $relative_path);
  7877. if (strlen($relative_path) > 0) {
  7878. $relative_path = $relative_path.'/';
  7879. }
  7880. } else {
  7881. $result = $this->generate_lp_folder($_course);
  7882. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7883. $relative_prefix = '../../';
  7884. }
  7885. $editor_config = [
  7886. 'ToolbarSet' => 'LearningPathDocuments',
  7887. 'Width' => '100%',
  7888. 'Height' => '500',
  7889. 'FullPage' => true,
  7890. 'CreateDocumentDir' => $relative_prefix,
  7891. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7892. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  7893. ];
  7894. if ($_GET['action'] == 'add_item') {
  7895. $class = 'add';
  7896. $text = get_lang('LPCreateDocument');
  7897. } else {
  7898. if ($_GET['action'] == 'edit_item') {
  7899. $class = 'save';
  7900. $text = get_lang('SaveDocument');
  7901. }
  7902. }
  7903. $form->addButtonSave($text, 'submit_button');
  7904. $renderer = $form->defaultRenderer();
  7905. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7906. $form->addElement('html', '<div class="editor-lp">');
  7907. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7908. $form->addElement('html', '</div>');
  7909. $defaults['content_lp'] = $content;
  7910. }
  7911. } elseif (is_numeric($extra_info)) {
  7912. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7913. $return = $this->display_document($extra_info, true, true, true);
  7914. $form->addElement('html', $return);
  7915. }
  7916. }
  7917. }
  7918. if (isset($extra_info['item_type']) &&
  7919. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7920. ) {
  7921. $parentSelect->freeze();
  7922. $position->freeze();
  7923. }
  7924. if ($action == 'move') {
  7925. $form->addElement('hidden', 'title', $item_title);
  7926. $form->addElement('hidden', 'description', $item_description);
  7927. }
  7928. if (is_numeric($extra_info)) {
  7929. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7930. $form->addElement('hidden', 'path', $extra_info);
  7931. } elseif (is_array($extra_info)) {
  7932. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7933. $form->addElement('hidden', 'path', $extra_info['path']);
  7934. }
  7935. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7936. $form->addElement('hidden', 'post_time', time());
  7937. $form->setDefaults($defaults);
  7938. return $form->returnForm();
  7939. }
  7940. /**
  7941. * Returns the form to update or create a read-out text.
  7942. *
  7943. * @param string $action "add" or "edit"
  7944. * @param int $id ID of the lp_item (if already exists)
  7945. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7946. *
  7947. * @throws Exception
  7948. * @throws HTML_QuickForm_Error
  7949. *
  7950. * @return string HTML form
  7951. */
  7952. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  7953. {
  7954. $course_id = api_get_course_int_id();
  7955. $_course = api_get_course_info();
  7956. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7957. $no_display_edit_textarea = false;
  7958. $item_description = '';
  7959. //If action==edit document
  7960. //We don't display the document form if it's not an editable document (html or txt file)
  7961. if ($action == 'edit') {
  7962. if (is_array($extra_info)) {
  7963. $path_parts = pathinfo($extra_info['dir']);
  7964. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7965. $no_display_edit_textarea = true;
  7966. }
  7967. }
  7968. }
  7969. $no_display_add = false;
  7970. $item_title = '';
  7971. $item_description = '';
  7972. if ($id != 0 && is_array($extra_info)) {
  7973. $item_title = stripslashes($extra_info['title']);
  7974. $item_description = stripslashes($extra_info['description']);
  7975. $item_terms = stripslashes($extra_info['terms']);
  7976. if (empty($item_title)) {
  7977. $path_parts = pathinfo($extra_info['path']);
  7978. $item_title = stripslashes($path_parts['filename']);
  7979. }
  7980. } elseif (is_numeric($extra_info)) {
  7981. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  7982. $result = Database::query($sql);
  7983. $row = Database::fetch_array($result);
  7984. $item_title = $row['title'];
  7985. $item_title = str_replace('_', ' ', $item_title);
  7986. if (empty($item_title)) {
  7987. $path_parts = pathinfo($row['path']);
  7988. $item_title = stripslashes($path_parts['filename']);
  7989. }
  7990. }
  7991. $parent = 0;
  7992. if ($id != 0 && is_array($extra_info)) {
  7993. $parent = $extra_info['parent_item_id'];
  7994. }
  7995. $arrLP = $this->getItemsForForm();
  7996. $this->tree_array($arrLP);
  7997. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7998. unset($this->arrMenu);
  7999. if ($action === 'add') {
  8000. $formHeader = get_lang('CreateTheDocument');
  8001. } else {
  8002. $formHeader = get_lang('EditTheCurrentDocument');
  8003. }
  8004. if ('edit' === $action) {
  8005. $urlAudioIcon = Display::url(
  8006. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8007. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8008. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8009. );
  8010. } else {
  8011. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8012. }
  8013. $form = new FormValidator(
  8014. 'frm_add_reading',
  8015. 'POST',
  8016. $this->getCurrentBuildingModeURL(),
  8017. '',
  8018. ['enctype' => 'multipart/form-data']
  8019. );
  8020. $form->addHeader($formHeader);
  8021. $form->addHtml(
  8022. Display::return_message(
  8023. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8024. 'normal',
  8025. false
  8026. )
  8027. );
  8028. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8029. $defaults['description'] = $item_description;
  8030. $data = $this->generate_lp_folder($_course);
  8031. if ($action != 'edit') {
  8032. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8033. DocumentManager::build_directory_selector(
  8034. $folders,
  8035. '',
  8036. [],
  8037. true,
  8038. $form,
  8039. 'directory_parent_id'
  8040. );
  8041. }
  8042. if (isset($data['id'])) {
  8043. $defaults['directory_parent_id'] = $data['id'];
  8044. }
  8045. $this->setItemTitle($form);
  8046. $arrHide[0]['value'] = $this->name;
  8047. $arrHide[0]['padding'] = 20;
  8048. for ($i = 0; $i < count($arrLP); $i++) {
  8049. if ($action != 'add') {
  8050. if ($arrLP[$i]['item_type'] == 'dir' &&
  8051. !in_array($arrLP[$i]['id'], $arrHide) &&
  8052. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8053. ) {
  8054. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8055. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8056. }
  8057. } else {
  8058. if ($arrLP[$i]['item_type'] == 'dir') {
  8059. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8060. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8061. }
  8062. }
  8063. }
  8064. $parent_select = $form->addSelect(
  8065. 'parent',
  8066. get_lang('Parent'),
  8067. [],
  8068. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8069. );
  8070. $my_count = 0;
  8071. foreach ($arrHide as $key => $value) {
  8072. if ($my_count != 0) {
  8073. // The LP name is also the first section and is not in the same charset like the other sections.
  8074. $value['value'] = Security::remove_XSS($value['value']);
  8075. $parent_select->addOption(
  8076. $value['value'],
  8077. $key,
  8078. 'style="padding-left:'.$value['padding'].'px;"'
  8079. );
  8080. } else {
  8081. $value['value'] = Security::remove_XSS($value['value']);
  8082. $parent_select->addOption(
  8083. $value['value'],
  8084. $key,
  8085. 'style="padding-left:'.$value['padding'].'px;"'
  8086. );
  8087. }
  8088. $my_count++;
  8089. }
  8090. if (!empty($id)) {
  8091. $parent_select->setSelected($parent);
  8092. } else {
  8093. $parent_item_id = Session::read('parent_item_id', 0);
  8094. $parent_select->setSelected($parent_item_id);
  8095. }
  8096. if (is_array($arrLP)) {
  8097. reset($arrLP);
  8098. }
  8099. $arrHide = [];
  8100. $s_selected_position = null;
  8101. // POSITION
  8102. $lastPosition = null;
  8103. for ($i = 0; $i < count($arrLP); $i++) {
  8104. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8105. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8106. ) {
  8107. if ((isset($extra_info['previous_item_id']) &&
  8108. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8109. ) {
  8110. $s_selected_position = $arrLP[$i]['id'];
  8111. }
  8112. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8113. }
  8114. $lastPosition = $arrLP[$i]['id'];
  8115. }
  8116. if (empty($s_selected_position)) {
  8117. $s_selected_position = $lastPosition;
  8118. }
  8119. $position = $form->addSelect(
  8120. 'previous',
  8121. get_lang('Position'),
  8122. []
  8123. );
  8124. $position->addOption(get_lang('FirstPosition'), 0);
  8125. foreach ($arrHide as $key => $value) {
  8126. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8127. $position->addOption(
  8128. $value['value'],
  8129. $key,
  8130. 'style="padding-left:'.$padding.'px;"'
  8131. );
  8132. }
  8133. $position->setSelected($s_selected_position);
  8134. if (is_array($arrLP)) {
  8135. reset($arrLP);
  8136. }
  8137. $arrHide = [];
  8138. for ($i = 0; $i < count($arrLP); $i++) {
  8139. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8140. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8141. ) {
  8142. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8143. }
  8144. }
  8145. if (!$no_display_add) {
  8146. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8147. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8148. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8149. if (!$no_display_edit_textarea) {
  8150. $content = '';
  8151. if (isset($_POST['content'])) {
  8152. $content = stripslashes($_POST['content']);
  8153. } elseif (is_array($extra_info)) {
  8154. $content = $this->display_document($extra_info['path'], false, false);
  8155. } elseif (is_numeric($extra_info)) {
  8156. $content = $this->display_document($extra_info, false, false);
  8157. }
  8158. // A new document, it is in the root of the repository.
  8159. if (is_array($extra_info) && $extra_info != 'new') {
  8160. } else {
  8161. $this->generate_lp_folder($_course);
  8162. }
  8163. if ($_GET['action'] == 'add_item') {
  8164. $text = get_lang('LPCreateDocument');
  8165. } else {
  8166. $text = get_lang('SaveDocument');
  8167. }
  8168. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8169. $form
  8170. ->defaultRenderer()
  8171. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8172. $form->addButtonSave($text, 'submit_button');
  8173. $defaults['content_lp'] = $content;
  8174. }
  8175. } elseif (is_numeric($extra_info)) {
  8176. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8177. $return = $this->display_document($extra_info, true, true, true);
  8178. $form->addElement('html', $return);
  8179. }
  8180. }
  8181. if (is_numeric($extra_info)) {
  8182. $form->addElement('hidden', 'path', $extra_info);
  8183. } elseif (is_array($extra_info)) {
  8184. $form->addElement('hidden', 'path', $extra_info['path']);
  8185. }
  8186. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8187. $form->addElement('hidden', 'post_time', time());
  8188. $form->setDefaults($defaults);
  8189. return $form->returnForm();
  8190. }
  8191. /**
  8192. * @param array $courseInfo
  8193. * @param string $content
  8194. * @param string $title
  8195. * @param int $parentId
  8196. *
  8197. * @throws \Doctrine\ORM\ORMException
  8198. * @throws \Doctrine\ORM\OptimisticLockException
  8199. * @throws \Doctrine\ORM\TransactionRequiredException
  8200. *
  8201. * @return int
  8202. */
  8203. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8204. {
  8205. $creatorId = api_get_user_id();
  8206. $sessionId = api_get_session_id();
  8207. // Generates folder
  8208. $result = $this->generate_lp_folder($courseInfo);
  8209. $dir = $result['dir'];
  8210. if (empty($parentId) || $parentId == '/') {
  8211. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8212. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8213. if ($parentId === '/') {
  8214. $dir = '/';
  8215. }
  8216. // Please, do not modify this dirname formatting.
  8217. if (strstr($dir, '..')) {
  8218. $dir = '/';
  8219. }
  8220. if (!empty($dir[0]) && $dir[0] == '.') {
  8221. $dir = substr($dir, 1);
  8222. }
  8223. if (!empty($dir[0]) && $dir[0] != '/') {
  8224. $dir = '/'.$dir;
  8225. }
  8226. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8227. $dir .= '/';
  8228. }
  8229. } else {
  8230. $parentInfo = DocumentManager::get_document_data_by_id(
  8231. $parentId,
  8232. $courseInfo['code']
  8233. );
  8234. if (!empty($parentInfo)) {
  8235. $dir = $parentInfo['path'].'/';
  8236. }
  8237. }
  8238. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8239. if (!is_dir($filepath)) {
  8240. $dir = '/';
  8241. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8242. }
  8243. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8244. if (!empty($title)) {
  8245. $title = api_replace_dangerous_char(stripslashes($title));
  8246. } else {
  8247. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8248. }
  8249. $title = disable_dangerous_file($title);
  8250. $filename = $title;
  8251. $content = !empty($content) ? $content : $_POST['content_lp'];
  8252. $tmpFileName = $filename;
  8253. $i = 0;
  8254. while (file_exists($filepath.$tmpFileName.'.html')) {
  8255. $tmpFileName = $filename.'_'.++$i;
  8256. }
  8257. $filename = $tmpFileName.'.html';
  8258. $content = stripslashes($content);
  8259. if (file_exists($filepath.$filename)) {
  8260. return 0;
  8261. }
  8262. $putContent = file_put_contents($filepath.$filename, $content);
  8263. if ($putContent === false) {
  8264. return 0;
  8265. }
  8266. $fileSize = filesize($filepath.$filename);
  8267. $saveFilePath = $dir.$filename;
  8268. $documentId = add_document(
  8269. $courseInfo,
  8270. $saveFilePath,
  8271. 'file',
  8272. $fileSize,
  8273. $tmpFileName,
  8274. '',
  8275. 0, //readonly
  8276. true,
  8277. null,
  8278. $sessionId,
  8279. $creatorId
  8280. );
  8281. if (!$documentId) {
  8282. return 0;
  8283. }
  8284. api_item_property_update(
  8285. $courseInfo,
  8286. TOOL_DOCUMENT,
  8287. $documentId,
  8288. 'DocumentAdded',
  8289. $creatorId,
  8290. null,
  8291. null,
  8292. null,
  8293. null,
  8294. $sessionId
  8295. );
  8296. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8297. $newTitle = $originalTitle;
  8298. if ($newComment || $newTitle) {
  8299. $em = Database::getManager();
  8300. /** @var CDocument $doc */
  8301. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8302. if ($newComment) {
  8303. $doc->setComment($newComment);
  8304. }
  8305. if ($newTitle) {
  8306. $doc->setTitle($newTitle);
  8307. }
  8308. $em->persist($doc);
  8309. $em->flush();
  8310. }
  8311. return $documentId;
  8312. }
  8313. /**
  8314. * Return HTML form to add/edit a link item.
  8315. *
  8316. * @param string $action (add/edit)
  8317. * @param int $id Item ID if exists
  8318. * @param mixed $extra_info
  8319. *
  8320. * @throws Exception
  8321. * @throws HTML_QuickForm_Error
  8322. *
  8323. * @return string HTML form
  8324. */
  8325. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8326. {
  8327. $course_id = api_get_course_int_id();
  8328. $tbl_link = Database::get_course_table(TABLE_LINK);
  8329. $item_title = '';
  8330. $item_description = '';
  8331. $item_url = '';
  8332. if ($id != 0 && is_array($extra_info)) {
  8333. $item_title = stripslashes($extra_info['title']);
  8334. $item_description = stripslashes($extra_info['description']);
  8335. $item_url = stripslashes($extra_info['url']);
  8336. } elseif (is_numeric($extra_info)) {
  8337. $extra_info = (int) $extra_info;
  8338. $sql = "SELECT title, description, url
  8339. FROM $tbl_link
  8340. WHERE c_id = $course_id AND iid = $extra_info";
  8341. $result = Database::query($sql);
  8342. $row = Database::fetch_array($result);
  8343. $item_title = $row['title'];
  8344. $item_description = $row['description'];
  8345. $item_url = $row['url'];
  8346. }
  8347. $form = new FormValidator(
  8348. 'edit_link',
  8349. 'POST',
  8350. $this->getCurrentBuildingModeURL()
  8351. );
  8352. $defaults = [];
  8353. $parent = 0;
  8354. if ($id != 0 && is_array($extra_info)) {
  8355. $parent = $extra_info['parent_item_id'];
  8356. }
  8357. $arrLP = $this->getItemsForForm();
  8358. $this->tree_array($arrLP);
  8359. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8360. unset($this->arrMenu);
  8361. if ($action == 'add') {
  8362. $legend = get_lang('CreateTheLink');
  8363. } elseif ($action == 'move') {
  8364. $legend = get_lang('MoveCurrentLink');
  8365. } else {
  8366. $legend = get_lang('EditCurrentLink');
  8367. }
  8368. $form->addHeader($legend);
  8369. if ($action != 'move') {
  8370. $this->setItemTitle($form);
  8371. $defaults['title'] = $item_title;
  8372. }
  8373. $selectParent = $form->addSelect(
  8374. 'parent',
  8375. get_lang('Parent'),
  8376. [],
  8377. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8378. );
  8379. $selectParent->addOption($this->name, 0);
  8380. $arrHide = [
  8381. $id,
  8382. ];
  8383. $parent_item_id = Session::read('parent_item_id', 0);
  8384. for ($i = 0; $i < count($arrLP); $i++) {
  8385. if ($action != 'add') {
  8386. if (
  8387. ($arrLP[$i]['item_type'] == 'dir') &&
  8388. !in_array($arrLP[$i]['id'], $arrHide) &&
  8389. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8390. ) {
  8391. $selectParent->addOption(
  8392. $arrLP[$i]['title'],
  8393. $arrLP[$i]['id'],
  8394. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8395. );
  8396. if ($parent == $arrLP[$i]['id']) {
  8397. $selectParent->setSelected($arrLP[$i]['id']);
  8398. }
  8399. } else {
  8400. $arrHide[] = $arrLP[$i]['id'];
  8401. }
  8402. } else {
  8403. if ($arrLP[$i]['item_type'] == 'dir') {
  8404. $selectParent->addOption(
  8405. $arrLP[$i]['title'],
  8406. $arrLP[$i]['id'],
  8407. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8408. );
  8409. if ($parent_item_id == $arrLP[$i]['id']) {
  8410. $selectParent->setSelected($arrLP[$i]['id']);
  8411. }
  8412. }
  8413. }
  8414. }
  8415. if (is_array($arrLP)) {
  8416. reset($arrLP);
  8417. }
  8418. $selectPrevious = $form->addSelect(
  8419. 'previous',
  8420. get_lang('Position'),
  8421. [],
  8422. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8423. );
  8424. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8425. for ($i = 0; $i < count($arrLP); $i++) {
  8426. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8427. $selectPrevious->addOption(
  8428. $arrLP[$i]['title'],
  8429. $arrLP[$i]['id']
  8430. );
  8431. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8432. $selectPrevious->setSelected($arrLP[$i]['id']);
  8433. } elseif ($action == 'add') {
  8434. $selectPrevious->setSelected($arrLP[$i]['id']);
  8435. }
  8436. }
  8437. }
  8438. if ($action != 'move') {
  8439. $urlAttributes = ['class' => 'learnpath_item_form'];
  8440. if (is_numeric($extra_info)) {
  8441. $urlAttributes['disabled'] = 'disabled';
  8442. }
  8443. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8444. $defaults['url'] = $item_url;
  8445. $arrHide = [];
  8446. for ($i = 0; $i < count($arrLP); $i++) {
  8447. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8448. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8449. }
  8450. }
  8451. }
  8452. if ($action == 'add') {
  8453. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8454. } else {
  8455. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8456. }
  8457. if ($action == 'move') {
  8458. $form->addHidden('title', $item_title);
  8459. $form->addHidden('description', $item_description);
  8460. }
  8461. if (is_numeric($extra_info)) {
  8462. $form->addHidden('path', $extra_info);
  8463. } elseif (is_array($extra_info)) {
  8464. $form->addHidden('path', $extra_info['path']);
  8465. }
  8466. $form->addHidden('type', TOOL_LINK);
  8467. $form->addHidden('post_time', time());
  8468. $form->setDefaults($defaults);
  8469. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8470. }
  8471. /**
  8472. * Return HTML form to add/edit a student publication (work).
  8473. *
  8474. * @param string $action
  8475. * @param int $id Item ID if already exists
  8476. * @param string $extra_info
  8477. *
  8478. * @throws Exception
  8479. *
  8480. * @return string HTML form
  8481. */
  8482. public function display_student_publication_form(
  8483. $action = 'add',
  8484. $id = 0,
  8485. $extra_info = ''
  8486. ) {
  8487. $course_id = api_get_course_int_id();
  8488. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8489. $item_title = get_lang('Student_publication');
  8490. if ($id != 0 && is_array($extra_info)) {
  8491. $item_title = stripslashes($extra_info['title']);
  8492. $item_description = stripslashes($extra_info['description']);
  8493. } elseif (is_numeric($extra_info)) {
  8494. $extra_info = (int) $extra_info;
  8495. $sql = "SELECT title, description
  8496. FROM $tbl_publication
  8497. WHERE c_id = $course_id AND id = ".$extra_info;
  8498. $result = Database::query($sql);
  8499. $row = Database::fetch_array($result);
  8500. if ($row) {
  8501. $item_title = $row['title'];
  8502. }
  8503. }
  8504. $parent = 0;
  8505. if ($id != 0 && is_array($extra_info)) {
  8506. $parent = $extra_info['parent_item_id'];
  8507. }
  8508. $arrLP = $this->getItemsForForm();
  8509. $this->tree_array($arrLP);
  8510. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8511. unset($this->arrMenu);
  8512. $form = new FormValidator('frm_student_publication', 'post', '#');
  8513. if ($action == 'add') {
  8514. $form->addHeader(get_lang('Student_publication'));
  8515. } elseif ($action == 'move') {
  8516. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8517. } else {
  8518. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8519. }
  8520. if ($action != 'move') {
  8521. $this->setItemTitle($form);
  8522. }
  8523. $parentSelect = $form->addSelect(
  8524. 'parent',
  8525. get_lang('Parent'),
  8526. ['0' => $this->name],
  8527. [
  8528. 'onchange' => 'javascript: load_cbo(this.value);',
  8529. 'class' => 'learnpath_item_form',
  8530. 'id' => 'idParent',
  8531. ]
  8532. );
  8533. $arrHide = [$id];
  8534. for ($i = 0; $i < count($arrLP); $i++) {
  8535. if ($action != 'add') {
  8536. if (
  8537. ($arrLP[$i]['item_type'] == 'dir') &&
  8538. !in_array($arrLP[$i]['id'], $arrHide) &&
  8539. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8540. ) {
  8541. $parentSelect->addOption(
  8542. $arrLP[$i]['title'],
  8543. $arrLP[$i]['id'],
  8544. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8545. );
  8546. if ($parent == $arrLP[$i]['id']) {
  8547. $parentSelect->setSelected($arrLP[$i]['id']);
  8548. }
  8549. } else {
  8550. $arrHide[] = $arrLP[$i]['id'];
  8551. }
  8552. } else {
  8553. if ($arrLP[$i]['item_type'] == 'dir') {
  8554. $parentSelect->addOption(
  8555. $arrLP[$i]['title'],
  8556. $arrLP[$i]['id'],
  8557. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8558. );
  8559. if ($parent == $arrLP[$i]['id']) {
  8560. $parentSelect->setSelected($arrLP[$i]['id']);
  8561. }
  8562. }
  8563. }
  8564. }
  8565. if (is_array($arrLP)) {
  8566. reset($arrLP);
  8567. }
  8568. $previousSelect = $form->addSelect(
  8569. 'previous',
  8570. get_lang('Position'),
  8571. ['0' => get_lang('FirstPosition')],
  8572. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8573. );
  8574. for ($i = 0; $i < count($arrLP); $i++) {
  8575. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8576. $previousSelect->addOption(
  8577. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8578. $arrLP[$i]['id']
  8579. );
  8580. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8581. $previousSelect->setSelected($arrLP[$i]['id']);
  8582. } elseif ($action == 'add') {
  8583. $previousSelect->setSelected($arrLP[$i]['id']);
  8584. }
  8585. }
  8586. }
  8587. if ($action == 'add') {
  8588. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8589. } else {
  8590. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8591. }
  8592. if ($action == 'move') {
  8593. $form->addHidden('title', $item_title);
  8594. $form->addHidden('description', $item_description);
  8595. }
  8596. if (is_numeric($extra_info)) {
  8597. $form->addHidden('path', $extra_info);
  8598. } elseif (is_array($extra_info)) {
  8599. $form->addHidden('path', $extra_info['path']);
  8600. }
  8601. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8602. $form->addHidden('post_time', time());
  8603. $form->setDefaults(['title' => $item_title]);
  8604. $return = '<div class="sectioncomment">';
  8605. $return .= $form->returnForm();
  8606. $return .= '</div>';
  8607. return $return;
  8608. }
  8609. /**
  8610. * Displays the menu for manipulating a step.
  8611. *
  8612. * @param id $item_id
  8613. * @param string $item_type
  8614. *
  8615. * @return string
  8616. */
  8617. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8618. {
  8619. $_course = api_get_course_info();
  8620. $course_code = api_get_course_id();
  8621. $item_id = (int) $item_id;
  8622. $return = '<div class="actions">';
  8623. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8624. $sql = "SELECT * FROM $tbl_lp_item
  8625. WHERE iid = ".$item_id;
  8626. $result = Database::query($sql);
  8627. $row = Database::fetch_assoc($result);
  8628. $audio_player = null;
  8629. // We display an audio player if needed.
  8630. if (!empty($row['audio'])) {
  8631. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  8632. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  8633. .'<audio src="'.$webAudioPath.'" controls>'
  8634. .'</div><br>';
  8635. }
  8636. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8637. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8638. $return .= Display::url(
  8639. Display::return_icon(
  8640. 'edit.png',
  8641. get_lang('Edit'),
  8642. [],
  8643. ICON_SIZE_SMALL
  8644. ),
  8645. $url.'&action=edit_item&path_item='.$row['path']
  8646. );
  8647. $return .= Display::url(
  8648. Display::return_icon(
  8649. 'move.png',
  8650. get_lang('Move'),
  8651. [],
  8652. ICON_SIZE_SMALL
  8653. ),
  8654. $url.'&action=move_item'
  8655. );
  8656. }
  8657. // Commented for now as prerequisites cannot be added to chapters.
  8658. if ($item_type != 'dir') {
  8659. $return .= Display::url(
  8660. Display::return_icon(
  8661. 'accept.png',
  8662. get_lang('LearnpathPrerequisites'),
  8663. [],
  8664. ICON_SIZE_SMALL
  8665. ),
  8666. $url.'&action=edit_item_prereq'
  8667. );
  8668. }
  8669. $return .= Display::url(
  8670. Display::return_icon(
  8671. 'delete.png',
  8672. get_lang('Delete'),
  8673. [],
  8674. ICON_SIZE_SMALL
  8675. ),
  8676. $url.'&action=delete_item'
  8677. );
  8678. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  8679. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8680. if (empty($documentData)) {
  8681. // Try with iid
  8682. $table = Database::get_course_table(TABLE_DOCUMENT);
  8683. $sql = "SELECT path FROM $table
  8684. WHERE
  8685. c_id = ".api_get_course_int_id()." AND
  8686. iid = ".$row['path']." AND
  8687. path NOT LIKE '%_DELETED_%'";
  8688. $result = Database::query($sql);
  8689. $documentData = Database::fetch_array($result);
  8690. if ($documentData) {
  8691. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  8692. }
  8693. }
  8694. if (isset($documentData['absolute_path_from_document'])) {
  8695. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  8696. }
  8697. }
  8698. $return .= '</div>';
  8699. if (!empty($audio_player)) {
  8700. $return .= $audio_player;
  8701. }
  8702. return $return;
  8703. }
  8704. /**
  8705. * Creates the javascript needed for filling up the checkboxes without page reload.
  8706. *
  8707. * @return string
  8708. */
  8709. public function get_js_dropdown_array()
  8710. {
  8711. $course_id = api_get_course_int_id();
  8712. $return = 'var child_name = new Array();'."\n";
  8713. $return .= 'var child_value = new Array();'."\n\n";
  8714. $return .= 'child_name[0] = new Array();'."\n";
  8715. $return .= 'child_value[0] = new Array();'."\n\n";
  8716. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8717. $sql = "SELECT * FROM ".$tbl_lp_item."
  8718. WHERE
  8719. c_id = $course_id AND
  8720. lp_id = ".$this->lp_id." AND
  8721. parent_item_id = 0
  8722. ORDER BY display_order ASC";
  8723. $res_zero = Database::query($sql);
  8724. $i = 0;
  8725. $list = $this->getItemsForForm(true);
  8726. foreach ($list as $row_zero) {
  8727. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8728. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8729. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8730. }
  8731. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8732. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8733. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8734. }
  8735. }
  8736. $return .= "\n";
  8737. $sql = "SELECT * FROM $tbl_lp_item
  8738. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8739. $res = Database::query($sql);
  8740. while ($row = Database::fetch_array($res)) {
  8741. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8742. WHERE
  8743. c_id = ".$course_id." AND
  8744. parent_item_id = ".$row['iid']."
  8745. ORDER BY display_order ASC";
  8746. $res_parent = Database::query($sql_parent);
  8747. $i = 0;
  8748. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8749. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8750. while ($row_parent = Database::fetch_array($res_parent)) {
  8751. $js_var = json_encode(get_lang('After').' '.$this->cleanItemTitle($row_parent['title']));
  8752. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8753. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8754. }
  8755. $return .= "\n";
  8756. }
  8757. $return .= "
  8758. function load_cbo(id) {
  8759. if (!id) {
  8760. return false;
  8761. }
  8762. var cbo = document.getElementById('previous');
  8763. for(var i = cbo.length - 1; i > 0; i--) {
  8764. cbo.options[i] = null;
  8765. }
  8766. var k=0;
  8767. for(var i = 1; i <= child_name[id].length; i++){
  8768. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  8769. option.style.paddingLeft = '40px';
  8770. cbo.options[i] = option;
  8771. k = i;
  8772. }
  8773. cbo.options[k].selected = true;
  8774. $('#previous').selectpicker('refresh');
  8775. }";
  8776. return $return;
  8777. }
  8778. /**
  8779. * Display the form to allow moving an item.
  8780. *
  8781. * @param int $item_id Item ID
  8782. *
  8783. * @throws Exception
  8784. * @throws HTML_QuickForm_Error
  8785. *
  8786. * @return string HTML form
  8787. */
  8788. public function display_move_item($item_id)
  8789. {
  8790. $return = '';
  8791. if (is_numeric($item_id)) {
  8792. $item_id = (int) $item_id;
  8793. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8794. $sql = "SELECT * FROM $tbl_lp_item
  8795. WHERE iid = $item_id";
  8796. $res = Database::query($sql);
  8797. $row = Database::fetch_array($res);
  8798. switch ($row['item_type']) {
  8799. case 'dir':
  8800. case 'asset':
  8801. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8802. $return .= $this->display_item_form(
  8803. $row['item_type'],
  8804. get_lang('MoveCurrentChapter'),
  8805. 'move',
  8806. $item_id,
  8807. $row
  8808. );
  8809. break;
  8810. case TOOL_DOCUMENT:
  8811. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8812. $return .= $this->display_document_form('move', $item_id, $row);
  8813. break;
  8814. case TOOL_LINK:
  8815. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8816. $return .= $this->display_link_form('move', $item_id, $row);
  8817. break;
  8818. case TOOL_HOTPOTATOES:
  8819. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8820. $return .= $this->display_link_form('move', $item_id, $row);
  8821. break;
  8822. case TOOL_QUIZ:
  8823. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8824. $return .= $this->display_quiz_form('move', $item_id, $row);
  8825. break;
  8826. case TOOL_STUDENTPUBLICATION:
  8827. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8828. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8829. break;
  8830. case TOOL_FORUM:
  8831. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8832. $return .= $this->display_forum_form('move', $item_id, $row);
  8833. break;
  8834. case TOOL_THREAD:
  8835. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8836. $return .= $this->display_forum_form('move', $item_id, $row);
  8837. break;
  8838. }
  8839. }
  8840. return $return;
  8841. }
  8842. /**
  8843. * Return HTML form to allow prerequisites selection.
  8844. *
  8845. * @todo use FormValidator
  8846. *
  8847. * @param int Item ID
  8848. *
  8849. * @return string HTML form
  8850. */
  8851. public function display_item_prerequisites_form($item_id = 0)
  8852. {
  8853. $course_id = api_get_course_int_id();
  8854. $item_id = (int) $item_id;
  8855. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8856. /* Current prerequisite */
  8857. $sql = "SELECT * FROM $tbl_lp_item
  8858. WHERE iid = $item_id";
  8859. $result = Database::query($sql);
  8860. $row = Database::fetch_array($result);
  8861. $prerequisiteId = $row['prerequisite'];
  8862. $return = '<legend>';
  8863. $return .= get_lang('AddEditPrerequisites');
  8864. $return .= '</legend>';
  8865. $return .= '<form method="POST">';
  8866. $return .= '<div class="table-responsive">';
  8867. $return .= '<table class="table table-hover">';
  8868. $return .= '<thead>';
  8869. $return .= '<tr>';
  8870. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8871. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8872. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8873. $return .= '</tr>';
  8874. $return .= '</thead>';
  8875. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8876. $return .= '<tbody>';
  8877. $return .= '<tr>';
  8878. $return .= '<td colspan="3">';
  8879. $return .= '<div class="radio learnpath"><label for="idNone">';
  8880. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8881. $return .= get_lang('None').'</label>';
  8882. $return .= '</div>';
  8883. $return .= '</tr>';
  8884. $sql = "SELECT * FROM $tbl_lp_item
  8885. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8886. $result = Database::query($sql);
  8887. $selectedMinScore = [];
  8888. $selectedMaxScore = [];
  8889. $masteryScore = [];
  8890. while ($row = Database::fetch_array($result)) {
  8891. if ($row['iid'] == $item_id) {
  8892. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8893. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8894. }
  8895. $masteryScore[$row['iid']] = $row['mastery_score'];
  8896. }
  8897. $arrLP = $this->getItemsForForm();
  8898. $this->tree_array($arrLP);
  8899. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8900. unset($this->arrMenu);
  8901. for ($i = 0; $i < count($arrLP); $i++) {
  8902. $item = $arrLP[$i];
  8903. if ($item['id'] == $item_id) {
  8904. break;
  8905. }
  8906. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8907. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8908. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  8909. $return .= '<tr>';
  8910. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8911. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8912. $return .= '<label for="id'.$item['id'].'">';
  8913. $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'].'" />';
  8914. $icon_name = str_replace(' ', '', $item['item_type']);
  8915. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8916. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8917. } else {
  8918. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8919. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8920. } else {
  8921. $return .= Display::return_icon('folder_document.png');
  8922. }
  8923. }
  8924. $return .= $item['title'].'</label>';
  8925. $return .= '</div>';
  8926. $return .= '</td>';
  8927. if ($item['item_type'] == TOOL_QUIZ) {
  8928. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8929. $lpItemObj = new LpItem($course_id, $item['id']);
  8930. $exercise = new Exercise($course_id);
  8931. $exercise->read($lpItemObj->path);
  8932. $lpItemObj->max_score = $exercise->get_max_score();
  8933. $lpItemObj->update();
  8934. $item['max_score'] = $lpItemObj->max_score;
  8935. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  8936. // Backwards compatibility with 1.9.x use mastery_score as min value
  8937. $selectedMinScoreValue = $masteryScoreAsMinValue;
  8938. }
  8939. $return .= '<td>';
  8940. $return .= '<input
  8941. class="form-control"
  8942. size="4" maxlength="3"
  8943. name="min_'.$item['id'].'"
  8944. type="number"
  8945. min="0"
  8946. step="1"
  8947. max="'.$item['max_score'].'"
  8948. value="'.$selectedMinScoreValue.'"
  8949. />';
  8950. $return .= '</td>';
  8951. $return .= '<td>';
  8952. $return .= '<input
  8953. class="form-control"
  8954. size="4"
  8955. maxlength="3"
  8956. name="max_'.$item['id'].'"
  8957. type="number"
  8958. min="0"
  8959. step="1"
  8960. max="'.$item['max_score'].'"
  8961. value="'.$selectedMaxScoreValue.'"
  8962. />';
  8963. $return .= '</td>';
  8964. }
  8965. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8966. $return .= '<td>';
  8967. $return .= '<input
  8968. size="4"
  8969. maxlength="3"
  8970. name="min_'.$item['id'].'"
  8971. type="number"
  8972. min="0"
  8973. step="1"
  8974. max="'.$item['max_score'].'"
  8975. value="'.$selectedMinScoreValue.'"
  8976. />';
  8977. $return .= '</td>';
  8978. $return .= '<td>';
  8979. $return .= '<input
  8980. size="4"
  8981. maxlength="3"
  8982. name="max_'.$item['id'].'"
  8983. type="number"
  8984. min="0"
  8985. step="1"
  8986. max="'.$item['max_score'].'"
  8987. value="'.$selectedMaxScoreValue.'"
  8988. />';
  8989. $return .= '</td>';
  8990. }
  8991. $return .= '</tr>';
  8992. }
  8993. $return .= '<tr>';
  8994. $return .= '</tr>';
  8995. $return .= '</tbody>';
  8996. $return .= '</table>';
  8997. $return .= '</div>';
  8998. $return .= '<div class="form-group">';
  8999. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9000. get_lang('ModifyPrerequisites').'</button>';
  9001. $return .= '</form>';
  9002. return $return;
  9003. }
  9004. /**
  9005. * Return HTML list to allow prerequisites selection for lp.
  9006. *
  9007. * @return string HTML form
  9008. */
  9009. public function display_lp_prerequisites_list()
  9010. {
  9011. $course_id = api_get_course_int_id();
  9012. $lp_id = $this->lp_id;
  9013. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9014. // get current prerequisite
  9015. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9016. $result = Database::query($sql);
  9017. $row = Database::fetch_array($result);
  9018. $prerequisiteId = $row['prerequisite'];
  9019. $session_id = api_get_session_id();
  9020. $session_condition = api_get_session_condition($session_id, true, true);
  9021. $sql = "SELECT * FROM $tbl_lp
  9022. WHERE c_id = $course_id $session_condition
  9023. ORDER BY display_order ";
  9024. $rs = Database::query($sql);
  9025. $return = '';
  9026. $return .= '<select name="prerequisites" class="form-control">';
  9027. $return .= '<option value="0">'.get_lang('None').'</option>';
  9028. if (Database::num_rows($rs) > 0) {
  9029. while ($row = Database::fetch_array($rs)) {
  9030. if ($row['id'] == $lp_id) {
  9031. continue;
  9032. }
  9033. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9034. }
  9035. }
  9036. $return .= '</select>';
  9037. return $return;
  9038. }
  9039. /**
  9040. * Creates a list with all the documents in it.
  9041. *
  9042. * @param bool $showInvisibleFiles
  9043. *
  9044. * @throws Exception
  9045. * @throws HTML_QuickForm_Error
  9046. *
  9047. * @return string
  9048. */
  9049. public function get_documents($showInvisibleFiles = false)
  9050. {
  9051. $course_info = api_get_course_info();
  9052. $sessionId = api_get_session_id();
  9053. $documentTree = DocumentManager::get_document_preview(
  9054. $course_info,
  9055. $this->lp_id,
  9056. null,
  9057. $sessionId,
  9058. true,
  9059. null,
  9060. null,
  9061. $showInvisibleFiles,
  9062. true
  9063. );
  9064. $headers = [
  9065. get_lang('Files'),
  9066. get_lang('CreateTheDocument'),
  9067. get_lang('CreateReadOutText'),
  9068. get_lang('Upload'),
  9069. ];
  9070. $form = new FormValidator(
  9071. 'form_upload',
  9072. 'POST',
  9073. $this->getCurrentBuildingModeURL(),
  9074. '',
  9075. ['enctype' => 'multipart/form-data']
  9076. );
  9077. $folders = DocumentManager::get_all_document_folders(
  9078. api_get_course_info(),
  9079. 0,
  9080. true
  9081. );
  9082. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9083. DocumentManager::build_directory_selector(
  9084. $folders,
  9085. $lpPathInfo['id'],
  9086. [],
  9087. true,
  9088. $form,
  9089. 'directory_parent_id'
  9090. );
  9091. $group = [
  9092. $form->createElement(
  9093. 'radio',
  9094. 'if_exists',
  9095. get_lang('UplWhatIfFileExists'),
  9096. get_lang('UplDoNothing'),
  9097. 'nothing'
  9098. ),
  9099. $form->createElement(
  9100. 'radio',
  9101. 'if_exists',
  9102. null,
  9103. get_lang('UplOverwriteLong'),
  9104. 'overwrite'
  9105. ),
  9106. $form->createElement(
  9107. 'radio',
  9108. 'if_exists',
  9109. null,
  9110. get_lang('UplRenameLong'),
  9111. 'rename'
  9112. ),
  9113. ];
  9114. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9115. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9116. $defaultFileExistsOption = 'rename';
  9117. if (!empty($fileExistsOption)) {
  9118. $defaultFileExistsOption = $fileExistsOption;
  9119. }
  9120. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9121. // Check box options
  9122. $form->addElement(
  9123. 'checkbox',
  9124. 'unzip',
  9125. get_lang('Options'),
  9126. get_lang('Uncompress')
  9127. );
  9128. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9129. $form->addMultipleUpload($url);
  9130. $new = $this->display_document_form('add', 0);
  9131. $frmReadOutText = $this->displayFrmReadOutText('add');
  9132. $tabs = Display::tabs(
  9133. $headers,
  9134. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9135. 'subtab'
  9136. );
  9137. return $tabs;
  9138. }
  9139. /**
  9140. * Creates a list with all the exercises (quiz) in it.
  9141. *
  9142. * @return string
  9143. */
  9144. public function get_exercises()
  9145. {
  9146. $course_id = api_get_course_int_id();
  9147. $session_id = api_get_session_id();
  9148. $userInfo = api_get_user_info();
  9149. // New for hotpotatoes.
  9150. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9151. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9152. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9153. $condition_session = api_get_session_condition($session_id, true, true);
  9154. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9155. $activeCondition = ' active <> -1 ';
  9156. if ($setting) {
  9157. $activeCondition = ' active = 1 ';
  9158. }
  9159. $categoryCondition = '';
  9160. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9161. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9162. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9163. }
  9164. $keywordCondition = '';
  9165. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9166. if (!empty($keyword)) {
  9167. $keyword = Database::escape_string($keyword);
  9168. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9169. }
  9170. $sql_quiz = "SELECT * FROM $tbl_quiz
  9171. WHERE
  9172. c_id = $course_id AND
  9173. $activeCondition
  9174. $condition_session
  9175. $categoryCondition
  9176. $keywordCondition
  9177. ORDER BY title ASC";
  9178. $sql_hot = "SELECT * FROM $tbl_doc
  9179. WHERE
  9180. c_id = $course_id AND
  9181. path LIKE '".$uploadPath."/%/%htm%'
  9182. $condition_session
  9183. ORDER BY id ASC";
  9184. $res_quiz = Database::query($sql_quiz);
  9185. $res_hot = Database::query($sql_hot);
  9186. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9187. // Create a search-box
  9188. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9189. $form->addHidden('action', 'add_item');
  9190. $form->addHidden('type', 'step');
  9191. $form->addHidden('lp_id', $this->lp_id);
  9192. $form->addHidden('lp_build_selected', '2');
  9193. $form->addCourseHiddenParams();
  9194. $form->addText(
  9195. 'keyword',
  9196. get_lang('Search'),
  9197. false,
  9198. [
  9199. 'aria-label' => get_lang('Search'),
  9200. ]
  9201. );
  9202. if (api_get_configuration_value('allow_exercise_categories')) {
  9203. $manager = new ExerciseCategoryManager();
  9204. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9205. if (!empty($options)) {
  9206. $form->addSelect(
  9207. 'category_id',
  9208. get_lang('Category'),
  9209. $options,
  9210. ['placeholder' => get_lang('SelectAnOption')]
  9211. );
  9212. }
  9213. }
  9214. $form->addButtonSearch(get_lang('Search'));
  9215. $return = $form->returnForm();
  9216. $return .= '<ul class="lp_resource">';
  9217. $return .= '<li class="lp_resource_element">';
  9218. $return .= Display::return_icon('new_exercice.png');
  9219. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9220. get_lang('NewExercise').'</a>';
  9221. $return .= '</li>';
  9222. $previewIcon = Display::return_icon(
  9223. 'preview_view.png',
  9224. get_lang('Preview')
  9225. );
  9226. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9227. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9228. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9229. // Display hotpotatoes
  9230. while ($row_hot = Database::fetch_array($res_hot)) {
  9231. $link = Display::url(
  9232. $previewIcon,
  9233. $exerciseUrl.'&file='.$row_hot['path'],
  9234. ['target' => '_blank']
  9235. );
  9236. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9237. $return .= '<a class="moved" href="#">';
  9238. $return .= Display::return_icon(
  9239. 'move_everywhere.png',
  9240. get_lang('Move'),
  9241. [],
  9242. ICON_SIZE_TINY
  9243. );
  9244. $return .= '</a> ';
  9245. $return .= Display::return_icon('hotpotatoes_s.png');
  9246. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9247. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9248. $return .= '</li>';
  9249. }
  9250. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9251. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9252. $title = strip_tags(
  9253. api_html_entity_decode($row_quiz['title'])
  9254. );
  9255. $visibility = api_get_item_visibility(
  9256. ['real_id' => $course_id],
  9257. TOOL_QUIZ,
  9258. $row_quiz['iid'],
  9259. $session_id
  9260. );
  9261. $link = Display::url(
  9262. $previewIcon,
  9263. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9264. ['target' => '_blank']
  9265. );
  9266. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9267. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9268. $return .= $quizIcon;
  9269. $sessionStar = api_get_session_image(
  9270. $row_quiz['session_id'],
  9271. $userInfo['status']
  9272. );
  9273. $return .= Display::url(
  9274. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9275. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9276. [
  9277. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9278. ]
  9279. );
  9280. $return .= '</li>';
  9281. }
  9282. $return .= '</ul>';
  9283. return $return;
  9284. }
  9285. /**
  9286. * Creates a list with all the links in it.
  9287. *
  9288. * @return string
  9289. */
  9290. public function get_links()
  9291. {
  9292. $selfUrl = api_get_self();
  9293. $courseIdReq = api_get_cidreq();
  9294. $course = api_get_course_info();
  9295. $userInfo = api_get_user_info();
  9296. $course_id = $course['real_id'];
  9297. $tbl_link = Database::get_course_table(TABLE_LINK);
  9298. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9299. $moveEverywhereIcon = Display::return_icon(
  9300. 'move_everywhere.png',
  9301. get_lang('Move'),
  9302. [],
  9303. ICON_SIZE_TINY
  9304. );
  9305. $session_id = api_get_session_id();
  9306. $condition_session = api_get_session_condition(
  9307. $session_id,
  9308. true,
  9309. true,
  9310. 'link.session_id'
  9311. );
  9312. $sql = "SELECT
  9313. link.id as link_id,
  9314. link.title as link_title,
  9315. link.session_id as link_session_id,
  9316. link.category_id as category_id,
  9317. link_category.category_title as category_title
  9318. FROM $tbl_link as link
  9319. LEFT JOIN $linkCategoryTable as link_category
  9320. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9321. WHERE link.c_id = $course_id $condition_session
  9322. ORDER BY link_category.category_title ASC, link.title ASC";
  9323. $result = Database::query($sql);
  9324. $categorizedLinks = [];
  9325. $categories = [];
  9326. while ($link = Database::fetch_array($result)) {
  9327. if (!$link['category_id']) {
  9328. $link['category_title'] = get_lang('Uncategorized');
  9329. }
  9330. $categories[$link['category_id']] = $link['category_title'];
  9331. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9332. }
  9333. $linksHtmlCode =
  9334. '<script>
  9335. function toggle_tool(tool, id) {
  9336. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9337. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9338. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9339. } else {
  9340. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9341. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9342. }
  9343. }
  9344. </script>
  9345. <ul class="lp_resource">
  9346. <li class="lp_resource_element">
  9347. '.Display::return_icon('linksnew.gif').'
  9348. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9349. get_lang('LinkAdd').'
  9350. </a>
  9351. </li>';
  9352. foreach ($categorizedLinks as $categoryId => $links) {
  9353. $linkNodes = null;
  9354. foreach ($links as $key => $linkInfo) {
  9355. $title = $linkInfo['link_title'];
  9356. $linkSessionId = $linkInfo['link_session_id'];
  9357. $link = Display::url(
  9358. Display::return_icon('preview_view.png', get_lang('Preview')),
  9359. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9360. ['target' => '_blank']
  9361. );
  9362. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9363. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9364. $linkNodes .=
  9365. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9366. <a class="moved" href="#">'.
  9367. $moveEverywhereIcon.
  9368. '</a>
  9369. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9370. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9371. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9372. Security::remove_XSS($title).$sessionStar.$link.
  9373. '</a>
  9374. </li>';
  9375. }
  9376. }
  9377. $linksHtmlCode .=
  9378. '<li>
  9379. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9380. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9381. align="absbottom" />
  9382. </a>
  9383. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9384. </li>
  9385. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9386. }
  9387. $linksHtmlCode .= '</ul>';
  9388. return $linksHtmlCode;
  9389. }
  9390. /**
  9391. * Creates a list with all the student publications in it.
  9392. *
  9393. * @return string
  9394. */
  9395. public function get_student_publications()
  9396. {
  9397. $return = '<ul class="lp_resource">';
  9398. $return .= '<li class="lp_resource_element">';
  9399. $return .= Display::return_icon('works_new.gif');
  9400. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9401. get_lang('AddAssignmentPage').'</a>';
  9402. $return .= '</li>';
  9403. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9404. $works = getWorkListTeacher(0, 100, null, null, null);
  9405. if (!empty($works)) {
  9406. foreach ($works as $work) {
  9407. $link = Display::url(
  9408. Display::return_icon('preview_view.png', get_lang('Preview')),
  9409. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9410. ['target' => '_blank']
  9411. );
  9412. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9413. $return .= '<a class="moved" href="#">';
  9414. $return .= Display::return_icon(
  9415. 'move_everywhere.png',
  9416. get_lang('Move'),
  9417. [],
  9418. ICON_SIZE_TINY
  9419. );
  9420. $return .= '</a> ';
  9421. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9422. $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.'">'.
  9423. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9424. </a>';
  9425. $return .= '</li>';
  9426. }
  9427. }
  9428. $return .= '</ul>';
  9429. return $return;
  9430. }
  9431. /**
  9432. * Creates a list with all the forums in it.
  9433. *
  9434. * @return string
  9435. */
  9436. public function get_forums()
  9437. {
  9438. require_once '../forum/forumfunction.inc.php';
  9439. $forumCategories = get_forum_categories();
  9440. $forumsInNoCategory = get_forums_in_category(0);
  9441. if (!empty($forumsInNoCategory)) {
  9442. $forumCategories = array_merge(
  9443. $forumCategories,
  9444. [
  9445. [
  9446. 'cat_id' => 0,
  9447. 'session_id' => 0,
  9448. 'visibility' => 1,
  9449. 'cat_comment' => null,
  9450. ],
  9451. ]
  9452. );
  9453. }
  9454. $forumList = get_forums();
  9455. $a_forums = [];
  9456. foreach ($forumCategories as $forumCategory) {
  9457. // The forums in this category.
  9458. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9459. if (!empty($forumsInCategory)) {
  9460. foreach ($forumList as $forum) {
  9461. if (isset($forum['forum_category']) &&
  9462. $forum['forum_category'] == $forumCategory['cat_id']
  9463. ) {
  9464. $a_forums[] = $forum;
  9465. }
  9466. }
  9467. }
  9468. }
  9469. $return = '<ul class="lp_resource">';
  9470. // First add link
  9471. $return .= '<li class="lp_resource_element">';
  9472. $return .= Display::return_icon('new_forum.png');
  9473. $return .= Display::url(
  9474. get_lang('CreateANewForum'),
  9475. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9476. 'action' => 'add',
  9477. 'content' => 'forum',
  9478. 'lp_id' => $this->lp_id,
  9479. ]),
  9480. ['title' => get_lang('CreateANewForum')]
  9481. );
  9482. $return .= '</li>';
  9483. $return .= '<script>
  9484. function toggle_forum(forum_id) {
  9485. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9486. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9487. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9488. } else {
  9489. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9490. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9491. }
  9492. }
  9493. </script>';
  9494. foreach ($a_forums as $forum) {
  9495. if (!empty($forum['forum_id'])) {
  9496. $link = Display::url(
  9497. Display::return_icon('preview_view.png', get_lang('Preview')),
  9498. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9499. ['target' => '_blank']
  9500. );
  9501. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9502. $return .= '<a class="moved" href="#">';
  9503. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9504. $return .= ' </a>';
  9505. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9506. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9507. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9508. </a>
  9509. <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">'.
  9510. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9511. $return .= '</li>';
  9512. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9513. $a_threads = get_threads($forum['forum_id']);
  9514. if (is_array($a_threads)) {
  9515. foreach ($a_threads as $thread) {
  9516. $link = Display::url(
  9517. Display::return_icon('preview_view.png', get_lang('Preview')),
  9518. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9519. ['target' => '_blank']
  9520. );
  9521. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9522. $return .= '&nbsp;<a class="moved" href="#">';
  9523. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9524. $return .= ' </a>';
  9525. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9526. $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.'">'.
  9527. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9528. $return .= '</li>';
  9529. }
  9530. }
  9531. $return .= '</div>';
  9532. }
  9533. }
  9534. $return .= '</ul>';
  9535. return $return;
  9536. }
  9537. /**
  9538. * // TODO: The output encoding should be equal to the system encoding.
  9539. *
  9540. * Exports the learning path as a SCORM package. This is the main function that
  9541. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9542. * whole thing and returns the zip.
  9543. *
  9544. * This method needs to be called in PHP5, as it will fail with non-adequate
  9545. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9546. * you need to call it on a learnpath object.
  9547. *
  9548. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9549. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9550. * path has been modified, it should use the generic method here below.
  9551. *
  9552. * @return string Returns the zip package string, or null if error
  9553. */
  9554. public function scormExport()
  9555. {
  9556. api_set_more_memory_and_time_limits();
  9557. $_course = api_get_course_info();
  9558. $course_id = $_course['real_id'];
  9559. // Create the zip handler (this will remain available throughout the method).
  9560. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9561. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9562. $temp_dir_short = uniqid('scorm_export', true);
  9563. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9564. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9565. $zip_folder = new PclZip($temp_zip_file);
  9566. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9567. $root_path = $main_path = api_get_path(SYS_PATH);
  9568. $files_cleanup = [];
  9569. // Place to temporarily stash the zip file.
  9570. // create the temp dir if it doesn't exist
  9571. // or do a cleanup before creating the zip file.
  9572. if (!is_dir($temp_zip_dir)) {
  9573. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9574. } else {
  9575. // Cleanup: Check the temp dir for old files and delete them.
  9576. $handle = opendir($temp_zip_dir);
  9577. while (false !== ($file = readdir($handle))) {
  9578. if ($file != '.' && $file != '..') {
  9579. unlink("$temp_zip_dir/$file");
  9580. }
  9581. }
  9582. closedir($handle);
  9583. }
  9584. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9585. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9586. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9587. ) {
  9588. // Remove the possible . at the end of the path.
  9589. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9590. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9591. mkdir(
  9592. $dest_path_to_scorm_folder,
  9593. api_get_permissions_for_new_directories(),
  9594. true
  9595. );
  9596. copyr(
  9597. $current_course_path.'/scorm/'.$this->path,
  9598. $dest_path_to_scorm_folder,
  9599. ['imsmanifest'],
  9600. $zip_files
  9601. );
  9602. }
  9603. // Build a dummy imsmanifest structure.
  9604. // Do not add to the zip yet (we still need it).
  9605. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9606. // Aggregation Model official document, section "2.3 Content Packaging".
  9607. // We are going to build a UTF-8 encoded manifest.
  9608. // Later we will recode it to the desired (and supported) encoding.
  9609. $xmldoc = new DOMDocument('1.0');
  9610. $root = $xmldoc->createElement('manifest');
  9611. $root->setAttribute('identifier', 'SingleCourseManifest');
  9612. $root->setAttribute('version', '1.1');
  9613. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9614. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9615. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9616. $root->setAttribute(
  9617. 'xsi:schemaLocation',
  9618. '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'
  9619. );
  9620. // Build mandatory sub-root container elements.
  9621. $metadata = $xmldoc->createElement('metadata');
  9622. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9623. $metadata->appendChild($md_schema);
  9624. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9625. $metadata->appendChild($md_schemaversion);
  9626. $root->appendChild($metadata);
  9627. $organizations = $xmldoc->createElement('organizations');
  9628. $resources = $xmldoc->createElement('resources');
  9629. // Build the only organization we will use in building our learnpaths.
  9630. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9631. $organization = $xmldoc->createElement('organization');
  9632. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9633. // To set the title of the SCORM entity (=organization), we take the name given
  9634. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9635. // learning path charset) as it is the encoding that defines how it is stored
  9636. // in the database. Then we convert it to HTML entities again as the "&" character
  9637. // alone is not authorized in XML (must be &amp;).
  9638. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9639. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9640. $organization->appendChild($org_title);
  9641. $folder_name = 'document';
  9642. // Removes the learning_path/scorm_folder path when exporting see #4841
  9643. $path_to_remove = '';
  9644. $path_to_replace = '';
  9645. $result = $this->generate_lp_folder($_course);
  9646. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9647. $path_to_remove = 'document'.$result['dir'];
  9648. $path_to_replace = $folder_name.'/';
  9649. }
  9650. // Fixes chamilo scorm exports
  9651. if ($this->ref === 'chamilo_scorm_export') {
  9652. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9653. }
  9654. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9655. $link_updates = [];
  9656. $links_to_create = [];
  9657. foreach ($this->ordered_items as $index => $itemId) {
  9658. /** @var learnpathItem $item */
  9659. $item = $this->items[$itemId];
  9660. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9661. // Get included documents from this item.
  9662. if ($item->type === 'sco') {
  9663. $inc_docs = $item->get_resources_from_source(
  9664. null,
  9665. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  9666. );
  9667. } else {
  9668. $inc_docs = $item->get_resources_from_source();
  9669. }
  9670. // Give a child element <item> to the <organization> element.
  9671. $my_item_id = $item->get_id();
  9672. $my_item = $xmldoc->createElement('item');
  9673. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9674. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9675. $my_item->setAttribute('isvisible', 'true');
  9676. // Give a child element <title> to the <item> element.
  9677. $my_title = $xmldoc->createElement(
  9678. 'title',
  9679. htmlspecialchars(
  9680. api_utf8_encode($item->get_title()),
  9681. ENT_QUOTES,
  9682. 'UTF-8'
  9683. )
  9684. );
  9685. $my_item->appendChild($my_title);
  9686. // Give a child element <adlcp:prerequisites> to the <item> element.
  9687. $my_prereqs = $xmldoc->createElement(
  9688. 'adlcp:prerequisites',
  9689. $this->get_scorm_prereq_string($my_item_id)
  9690. );
  9691. $my_prereqs->setAttribute('type', 'aicc_script');
  9692. $my_item->appendChild($my_prereqs);
  9693. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9694. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9695. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9696. //$xmldoc->createElement('adlcp:timelimitaction','');
  9697. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9698. //$xmldoc->createElement('adlcp:datafromlms','');
  9699. // Give a child element <adlcp:masteryscore> to the <item> element.
  9700. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9701. $my_item->appendChild($my_masteryscore);
  9702. // Attach this item to the organization element or hits parent if there is one.
  9703. if (!empty($item->parent) && $item->parent != 0) {
  9704. $children = $organization->childNodes;
  9705. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9706. if (is_object($possible_parent)) {
  9707. $possible_parent->appendChild($my_item);
  9708. } else {
  9709. if ($this->debug > 0) {
  9710. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9711. }
  9712. }
  9713. } else {
  9714. if ($this->debug > 0) {
  9715. error_log('No parent');
  9716. }
  9717. $organization->appendChild($my_item);
  9718. }
  9719. // Get the path of the file(s) from the course directory root.
  9720. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9721. $my_xml_file_path = $my_file_path;
  9722. if (!empty($path_to_remove)) {
  9723. // From docs
  9724. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9725. // From quiz
  9726. if ($this->ref === 'chamilo_scorm_export') {
  9727. $path_to_remove = 'scorm/'.$this->path.'/';
  9728. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9729. }
  9730. }
  9731. $my_sub_dir = dirname($my_file_path);
  9732. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9733. $my_xml_sub_dir = $my_sub_dir;
  9734. // Give a <resource> child to the <resources> element
  9735. $my_resource = $xmldoc->createElement('resource');
  9736. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9737. $my_resource->setAttribute('type', 'webcontent');
  9738. $my_resource->setAttribute('href', $my_xml_file_path);
  9739. // adlcp:scormtype can be either 'sco' or 'asset'.
  9740. if ($item->type === 'sco') {
  9741. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9742. } else {
  9743. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9744. }
  9745. // xml:base is the base directory to find the files declared in this resource.
  9746. $my_resource->setAttribute('xml:base', '');
  9747. // Give a <file> child to the <resource> element.
  9748. $my_file = $xmldoc->createElement('file');
  9749. $my_file->setAttribute('href', $my_xml_file_path);
  9750. $my_resource->appendChild($my_file);
  9751. // Dependency to other files - not yet supported.
  9752. $i = 1;
  9753. if ($inc_docs) {
  9754. foreach ($inc_docs as $doc_info) {
  9755. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9756. continue;
  9757. }
  9758. $my_dep = $xmldoc->createElement('resource');
  9759. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9760. $my_dep->setAttribute('identifier', $res_id);
  9761. $my_dep->setAttribute('type', 'webcontent');
  9762. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9763. $my_dep_file = $xmldoc->createElement('file');
  9764. // Check type of URL.
  9765. if ($doc_info[1] == 'remote') {
  9766. // Remote file. Save url as is.
  9767. $my_dep_file->setAttribute('href', $doc_info[0]);
  9768. $my_dep->setAttribute('xml:base', '');
  9769. } elseif ($doc_info[1] === 'local') {
  9770. switch ($doc_info[2]) {
  9771. case 'url':
  9772. // Local URL - save path as url for now, don't zip file.
  9773. $abs_path = api_get_path(SYS_PATH).
  9774. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9775. $current_dir = dirname($abs_path);
  9776. $current_dir = str_replace('\\', '/', $current_dir);
  9777. $file_path = realpath($abs_path);
  9778. $file_path = str_replace('\\', '/', $file_path);
  9779. $my_dep_file->setAttribute('href', $file_path);
  9780. $my_dep->setAttribute('xml:base', '');
  9781. if (strstr($file_path, $main_path) !== false) {
  9782. // The calculated real path is really inside Chamilo's root path.
  9783. // Reduce file path to what's under the DocumentRoot.
  9784. $replace = $file_path;
  9785. $file_path = substr($file_path, strlen($root_path) - 1);
  9786. $destinationFile = $file_path;
  9787. if (strstr($file_path, 'upload/users') !== false) {
  9788. $pos = strpos($file_path, 'my_files/');
  9789. if ($pos !== false) {
  9790. $onlyDirectory = str_replace(
  9791. 'upload/users/',
  9792. '',
  9793. substr($file_path, $pos, strlen($file_path))
  9794. );
  9795. }
  9796. $replace = $onlyDirectory;
  9797. $destinationFile = $replace;
  9798. }
  9799. $zip_files_abs[] = $file_path;
  9800. $link_updates[$my_file_path][] = [
  9801. 'orig' => $doc_info[0],
  9802. 'dest' => $destinationFile,
  9803. 'replace' => $replace,
  9804. ];
  9805. $my_dep_file->setAttribute('href', $file_path);
  9806. $my_dep->setAttribute('xml:base', '');
  9807. } elseif (empty($file_path)) {
  9808. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9809. $file_path = str_replace('//', '/', $file_path);
  9810. if (file_exists($file_path)) {
  9811. // We get the relative path.
  9812. $file_path = substr($file_path, strlen($current_dir));
  9813. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9814. $link_updates[$my_file_path][] = [
  9815. 'orig' => $doc_info[0],
  9816. 'dest' => $file_path,
  9817. ];
  9818. $my_dep_file->setAttribute('href', $file_path);
  9819. $my_dep->setAttribute('xml:base', '');
  9820. }
  9821. }
  9822. break;
  9823. case 'abs':
  9824. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9825. $my_dep_file->setAttribute('href', $doc_info[0]);
  9826. $my_dep->setAttribute('xml:base', '');
  9827. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9828. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9829. $abs_img_path_without_subdir = $doc_info[0];
  9830. $relp = api_get_path(REL_PATH); // The url-append config param.
  9831. $pos = strpos($abs_img_path_without_subdir, $relp);
  9832. if ($pos === 0) {
  9833. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  9834. }
  9835. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9836. $file_path = str_replace(['\\', '//'], '/', $file_path);
  9837. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9838. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9839. // Check if the current document is in that path.
  9840. if (strstr($file_path, $cur_path) !== false) {
  9841. $destinationFile = substr($file_path, strlen($cur_path));
  9842. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  9843. $fileToTest = $cur_path.$my_file_path;
  9844. if (!empty($path_to_remove)) {
  9845. $fileToTest = str_replace(
  9846. $path_to_remove.'/',
  9847. $path_to_replace,
  9848. $cur_path.$my_file_path
  9849. );
  9850. }
  9851. $relative_path = api_get_relative_path($fileToTest, $file_path);
  9852. // Put the current document in the zip (this array is the array
  9853. // that will manage documents already in the course folder - relative).
  9854. $zip_files[] = $filePathNoCoursePart;
  9855. // Update the links to the current document in the
  9856. // containing document (make them relative).
  9857. $link_updates[$my_file_path][] = [
  9858. 'orig' => $doc_info[0],
  9859. 'dest' => $destinationFile,
  9860. 'replace' => $relative_path,
  9861. ];
  9862. $my_dep_file->setAttribute('href', $file_path);
  9863. $my_dep->setAttribute('xml:base', '');
  9864. } elseif (strstr($file_path, $main_path) !== false) {
  9865. // The calculated real path is really inside Chamilo's root path.
  9866. // Reduce file path to what's under the DocumentRoot.
  9867. $file_path = substr($file_path, strlen($root_path));
  9868. $zip_files_abs[] = $file_path;
  9869. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9870. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9871. $my_dep->setAttribute('xml:base', '');
  9872. } elseif (empty($file_path)) {
  9873. // Probably this is an image inside "/main" directory
  9874. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  9875. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9876. if (file_exists($file_path)) {
  9877. if (strstr($file_path, 'main/default_course_document') !== false) {
  9878. // We get the relative path.
  9879. $pos = strpos($file_path, 'main/default_course_document/');
  9880. if ($pos !== false) {
  9881. $onlyDirectory = str_replace(
  9882. 'main/default_course_document/',
  9883. '',
  9884. substr($file_path, $pos, strlen($file_path))
  9885. );
  9886. }
  9887. $destinationFile = 'default_course_document/'.$onlyDirectory;
  9888. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  9889. $zip_files_abs[] = $fileAbs;
  9890. $link_updates[$my_file_path][] = [
  9891. 'orig' => $doc_info[0],
  9892. 'dest' => $destinationFile,
  9893. ];
  9894. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9895. $my_dep->setAttribute('xml:base', '');
  9896. }
  9897. }
  9898. }
  9899. break;
  9900. case 'rel':
  9901. // Path relative to the current document.
  9902. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9903. if (substr($doc_info[0], 0, 2) === '..') {
  9904. // Relative path going up.
  9905. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9906. $current_dir = str_replace('\\', '/', $current_dir);
  9907. $file_path = realpath($current_dir.$doc_info[0]);
  9908. $file_path = str_replace('\\', '/', $file_path);
  9909. if (strstr($file_path, $main_path) !== false) {
  9910. // The calculated real path is really inside Chamilo's root path.
  9911. // Reduce file path to what's under the DocumentRoot.
  9912. $file_path = substr($file_path, strlen($root_path));
  9913. $zip_files_abs[] = $file_path;
  9914. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9915. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9916. $my_dep->setAttribute('xml:base', '');
  9917. }
  9918. } else {
  9919. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9920. $my_dep_file->setAttribute('href', $doc_info[0]);
  9921. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9922. }
  9923. break;
  9924. default:
  9925. $my_dep_file->setAttribute('href', $doc_info[0]);
  9926. $my_dep->setAttribute('xml:base', '');
  9927. break;
  9928. }
  9929. }
  9930. $my_dep->appendChild($my_dep_file);
  9931. $resources->appendChild($my_dep);
  9932. $dependency = $xmldoc->createElement('dependency');
  9933. $dependency->setAttribute('identifierref', $res_id);
  9934. $my_resource->appendChild($dependency);
  9935. $i++;
  9936. }
  9937. }
  9938. $resources->appendChild($my_resource);
  9939. $zip_files[] = $my_file_path;
  9940. } else {
  9941. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9942. switch ($item->type) {
  9943. case TOOL_LINK:
  9944. $my_item = $xmldoc->createElement('item');
  9945. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9946. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9947. $my_item->setAttribute('isvisible', 'true');
  9948. // Give a child element <title> to the <item> element.
  9949. $my_title = $xmldoc->createElement(
  9950. 'title',
  9951. htmlspecialchars(
  9952. api_utf8_encode($item->get_title()),
  9953. ENT_QUOTES,
  9954. 'UTF-8'
  9955. )
  9956. );
  9957. $my_item->appendChild($my_title);
  9958. // Give a child element <adlcp:prerequisites> to the <item> element.
  9959. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9960. $my_prereqs->setAttribute('type', 'aicc_script');
  9961. $my_item->appendChild($my_prereqs);
  9962. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9963. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9964. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9965. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9966. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9967. //$xmldoc->createElement('adlcp:datafromlms', '');
  9968. // Give a child element <adlcp:masteryscore> to the <item> element.
  9969. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9970. $my_item->appendChild($my_masteryscore);
  9971. // Attach this item to the organization element or its parent if there is one.
  9972. if (!empty($item->parent) && $item->parent != 0) {
  9973. $children = $organization->childNodes;
  9974. for ($i = 0; $i < $children->length; $i++) {
  9975. $item_temp = $children->item($i);
  9976. if ($item_temp->nodeName == 'item') {
  9977. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9978. $item_temp->appendChild($my_item);
  9979. }
  9980. }
  9981. }
  9982. } else {
  9983. $organization->appendChild($my_item);
  9984. }
  9985. $my_file_path = 'link_'.$item->get_id().'.html';
  9986. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9987. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  9988. $rs = Database::query($sql);
  9989. if ($link = Database::fetch_array($rs)) {
  9990. $url = $link['url'];
  9991. $title = stripslashes($link['title']);
  9992. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9993. $my_xml_file_path = $my_file_path;
  9994. $my_sub_dir = dirname($my_file_path);
  9995. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9996. $my_xml_sub_dir = $my_sub_dir;
  9997. // Give a <resource> child to the <resources> element.
  9998. $my_resource = $xmldoc->createElement('resource');
  9999. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10000. $my_resource->setAttribute('type', 'webcontent');
  10001. $my_resource->setAttribute('href', $my_xml_file_path);
  10002. // adlcp:scormtype can be either 'sco' or 'asset'.
  10003. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10004. // xml:base is the base directory to find the files declared in this resource.
  10005. $my_resource->setAttribute('xml:base', '');
  10006. // give a <file> child to the <resource> element.
  10007. $my_file = $xmldoc->createElement('file');
  10008. $my_file->setAttribute('href', $my_xml_file_path);
  10009. $my_resource->appendChild($my_file);
  10010. $resources->appendChild($my_resource);
  10011. }
  10012. break;
  10013. case TOOL_QUIZ:
  10014. $exe_id = $item->path;
  10015. // Should be using ref when everything will be cleaned up in this regard.
  10016. $exe = new Exercise();
  10017. $exe->read($exe_id);
  10018. $my_item = $xmldoc->createElement('item');
  10019. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10020. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10021. $my_item->setAttribute('isvisible', 'true');
  10022. // Give a child element <title> to the <item> element.
  10023. $my_title = $xmldoc->createElement(
  10024. 'title',
  10025. htmlspecialchars(
  10026. api_utf8_encode($item->get_title()),
  10027. ENT_QUOTES,
  10028. 'UTF-8'
  10029. )
  10030. );
  10031. $my_item->appendChild($my_title);
  10032. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10033. $my_item->appendChild($my_max_score);
  10034. // Give a child element <adlcp:prerequisites> to the <item> element.
  10035. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10036. $my_prereqs->setAttribute('type', 'aicc_script');
  10037. $my_item->appendChild($my_prereqs);
  10038. // Give a child element <adlcp:masteryscore> to the <item> element.
  10039. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10040. $my_item->appendChild($my_masteryscore);
  10041. // Attach this item to the organization element or hits parent if there is one.
  10042. if (!empty($item->parent) && $item->parent != 0) {
  10043. $children = $organization->childNodes;
  10044. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10045. if ($possible_parent) {
  10046. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10047. $possible_parent->appendChild($my_item);
  10048. }
  10049. }
  10050. } else {
  10051. $organization->appendChild($my_item);
  10052. }
  10053. // Get the path of the file(s) from the course directory root
  10054. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10055. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10056. // Write the contents of the exported exercise into a (big) html file
  10057. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10058. $scormExercise = new ScormExercise($exe, true);
  10059. $contents = $scormExercise->export();
  10060. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10061. $res = file_put_contents($tmp_file_path, $contents);
  10062. if ($res === false) {
  10063. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10064. }
  10065. $files_cleanup[] = $tmp_file_path;
  10066. $my_xml_file_path = $my_file_path;
  10067. $my_sub_dir = dirname($my_file_path);
  10068. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10069. $my_xml_sub_dir = $my_sub_dir;
  10070. // Give a <resource> child to the <resources> element.
  10071. $my_resource = $xmldoc->createElement('resource');
  10072. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10073. $my_resource->setAttribute('type', 'webcontent');
  10074. $my_resource->setAttribute('href', $my_xml_file_path);
  10075. // adlcp:scormtype can be either 'sco' or 'asset'.
  10076. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10077. // xml:base is the base directory to find the files declared in this resource.
  10078. $my_resource->setAttribute('xml:base', '');
  10079. // Give a <file> child to the <resource> element.
  10080. $my_file = $xmldoc->createElement('file');
  10081. $my_file->setAttribute('href', $my_xml_file_path);
  10082. $my_resource->appendChild($my_file);
  10083. // Get included docs.
  10084. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10085. // Dependency to other files - not yet supported.
  10086. $i = 1;
  10087. foreach ($inc_docs as $doc_info) {
  10088. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10089. continue;
  10090. }
  10091. $my_dep = $xmldoc->createElement('resource');
  10092. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10093. $my_dep->setAttribute('identifier', $res_id);
  10094. $my_dep->setAttribute('type', 'webcontent');
  10095. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10096. $my_dep_file = $xmldoc->createElement('file');
  10097. // Check type of URL.
  10098. if ($doc_info[1] == 'remote') {
  10099. // Remote file. Save url as is.
  10100. $my_dep_file->setAttribute('href', $doc_info[0]);
  10101. $my_dep->setAttribute('xml:base', '');
  10102. } elseif ($doc_info[1] == 'local') {
  10103. switch ($doc_info[2]) {
  10104. case 'url': // Local URL - save path as url for now, don't zip file.
  10105. // Save file but as local file (retrieve from URL).
  10106. $abs_path = api_get_path(SYS_PATH).
  10107. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10108. $current_dir = dirname($abs_path);
  10109. $current_dir = str_replace('\\', '/', $current_dir);
  10110. $file_path = realpath($abs_path);
  10111. $file_path = str_replace('\\', '/', $file_path);
  10112. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10113. $my_dep->setAttribute('xml:base', '');
  10114. if (strstr($file_path, $main_path) !== false) {
  10115. // The calculated real path is really inside the chamilo root path.
  10116. // Reduce file path to what's under the DocumentRoot.
  10117. $file_path = substr($file_path, strlen($root_path));
  10118. $zip_files_abs[] = $file_path;
  10119. $link_updates[$my_file_path][] = [
  10120. 'orig' => $doc_info[0],
  10121. 'dest' => 'document/'.$file_path,
  10122. ];
  10123. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10124. $my_dep->setAttribute('xml:base', '');
  10125. } elseif (empty($file_path)) {
  10126. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10127. $file_path = str_replace('//', '/', $file_path);
  10128. if (file_exists($file_path)) {
  10129. $file_path = substr($file_path, strlen($current_dir));
  10130. // We get the relative path.
  10131. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10132. $link_updates[$my_file_path][] = [
  10133. 'orig' => $doc_info[0],
  10134. 'dest' => 'document/'.$file_path,
  10135. ];
  10136. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10137. $my_dep->setAttribute('xml:base', '');
  10138. }
  10139. }
  10140. break;
  10141. case 'abs':
  10142. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10143. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10144. $current_dir = str_replace('\\', '/', $current_dir);
  10145. $file_path = realpath($doc_info[0]);
  10146. $file_path = str_replace('\\', '/', $file_path);
  10147. $my_dep_file->setAttribute('href', $file_path);
  10148. $my_dep->setAttribute('xml:base', '');
  10149. if (strstr($file_path, $main_path) !== false) {
  10150. // The calculated real path is really inside the chamilo root path.
  10151. // Reduce file path to what's under the DocumentRoot.
  10152. $file_path = substr($file_path, strlen($root_path));
  10153. $zip_files_abs[] = $file_path;
  10154. $link_updates[$my_file_path][] = [
  10155. 'orig' => $doc_info[0],
  10156. 'dest' => $file_path,
  10157. ];
  10158. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10159. $my_dep->setAttribute('xml:base', '');
  10160. } elseif (empty($file_path)) {
  10161. $docSysPartPath = str_replace(
  10162. api_get_path(REL_COURSE_PATH),
  10163. '',
  10164. $doc_info[0]
  10165. );
  10166. $docSysPartPathNoCourseCode = str_replace(
  10167. $_course['directory'].'/',
  10168. '',
  10169. $docSysPartPath
  10170. );
  10171. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10172. if (file_exists($docSysPath)) {
  10173. $file_path = $docSysPartPathNoCourseCode;
  10174. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10175. $link_updates[$my_file_path][] = [
  10176. 'orig' => $doc_info[0],
  10177. 'dest' => $file_path,
  10178. ];
  10179. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10180. $my_dep->setAttribute('xml:base', '');
  10181. }
  10182. }
  10183. break;
  10184. case 'rel':
  10185. // Path relative to the current document. Save xml:base as current document's
  10186. // directory and save file in zip as subdir.file_path
  10187. if (substr($doc_info[0], 0, 2) === '..') {
  10188. // Relative path going up.
  10189. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10190. $current_dir = str_replace('\\', '/', $current_dir);
  10191. $file_path = realpath($current_dir.$doc_info[0]);
  10192. $file_path = str_replace('\\', '/', $file_path);
  10193. if (strstr($file_path, $main_path) !== false) {
  10194. // The calculated real path is really inside Chamilo's root path.
  10195. // Reduce file path to what's under the DocumentRoot.
  10196. $file_path = substr($file_path, strlen($root_path));
  10197. $file_path_dest = $file_path;
  10198. // File path is courses/CHAMILO/document/....
  10199. $info_file_path = explode('/', $file_path);
  10200. if ($info_file_path[0] == 'courses') {
  10201. // Add character "/" in file path.
  10202. $file_path_dest = 'document/'.$file_path;
  10203. }
  10204. $zip_files_abs[] = $file_path;
  10205. $link_updates[$my_file_path][] = [
  10206. 'orig' => $doc_info[0],
  10207. 'dest' => $file_path_dest,
  10208. ];
  10209. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10210. $my_dep->setAttribute('xml:base', '');
  10211. }
  10212. } else {
  10213. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10214. $my_dep_file->setAttribute('href', $doc_info[0]);
  10215. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10216. }
  10217. break;
  10218. default:
  10219. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10220. $my_dep->setAttribute('xml:base', '');
  10221. break;
  10222. }
  10223. }
  10224. $my_dep->appendChild($my_dep_file);
  10225. $resources->appendChild($my_dep);
  10226. $dependency = $xmldoc->createElement('dependency');
  10227. $dependency->setAttribute('identifierref', $res_id);
  10228. $my_resource->appendChild($dependency);
  10229. $i++;
  10230. }
  10231. $resources->appendChild($my_resource);
  10232. $zip_files[] = $my_file_path;
  10233. break;
  10234. default:
  10235. // Get the path of the file(s) from the course directory root
  10236. $my_file_path = 'non_exportable.html';
  10237. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10238. $my_xml_file_path = $my_file_path;
  10239. $my_sub_dir = dirname($my_file_path);
  10240. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10241. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10242. $my_xml_sub_dir = $my_sub_dir;
  10243. // Give a <resource> child to the <resources> element.
  10244. $my_resource = $xmldoc->createElement('resource');
  10245. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10246. $my_resource->setAttribute('type', 'webcontent');
  10247. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10248. // adlcp:scormtype can be either 'sco' or 'asset'.
  10249. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10250. // xml:base is the base directory to find the files declared in this resource.
  10251. $my_resource->setAttribute('xml:base', '');
  10252. // Give a <file> child to the <resource> element.
  10253. $my_file = $xmldoc->createElement('file');
  10254. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10255. $my_resource->appendChild($my_file);
  10256. $resources->appendChild($my_resource);
  10257. break;
  10258. }
  10259. }
  10260. }
  10261. $organizations->appendChild($organization);
  10262. $root->appendChild($organizations);
  10263. $root->appendChild($resources);
  10264. $xmldoc->appendChild($root);
  10265. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10266. // then add the file to the zip, then destroy the file (this is done automatically).
  10267. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10268. foreach ($zip_files as $file_path) {
  10269. if (empty($file_path)) {
  10270. continue;
  10271. }
  10272. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10273. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10274. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10275. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10276. }
  10277. $this->create_path($dest_file);
  10278. @copy($filePath, $dest_file);
  10279. // Check if the file needs a link update.
  10280. if (in_array($file_path, array_keys($link_updates))) {
  10281. $string = file_get_contents($dest_file);
  10282. unlink($dest_file);
  10283. foreach ($link_updates[$file_path] as $old_new) {
  10284. // This is an ugly hack that allows .flv files to be found by the flv player that
  10285. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10286. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10287. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10288. if (substr($old_new['dest'], -3) === 'flv' &&
  10289. substr($old_new['dest'], 0, 5) === 'main/'
  10290. ) {
  10291. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10292. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10293. substr($old_new['dest'], 0, 6) === 'video/'
  10294. ) {
  10295. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10296. }
  10297. // Fix to avoid problems with default_course_document
  10298. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10299. $newDestination = $old_new['dest'];
  10300. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10301. $newDestination = $old_new['replace'];
  10302. }
  10303. } else {
  10304. $newDestination = str_replace('document/', '', $old_new['dest']);
  10305. }
  10306. $string = str_replace($old_new['orig'], $newDestination, $string);
  10307. // Add files inside the HTMLs
  10308. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10309. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10310. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10311. copy(
  10312. $sys_course_path.$new_path,
  10313. $destinationFile
  10314. );
  10315. }
  10316. }
  10317. file_put_contents($dest_file, $string);
  10318. }
  10319. if (file_exists($filePath) && $copyAll) {
  10320. $extension = $this->get_extension($filePath);
  10321. if (in_array($extension, ['html', 'html'])) {
  10322. $containerOrigin = dirname($filePath);
  10323. $containerDestination = dirname($dest_file);
  10324. $finder = new Finder();
  10325. $finder->files()->in($containerOrigin)
  10326. ->notName('*_DELETED_*')
  10327. ->exclude('share_folder')
  10328. ->exclude('chat_files')
  10329. ->exclude('certificates')
  10330. ;
  10331. if (is_dir($containerOrigin) &&
  10332. is_dir($containerDestination)
  10333. ) {
  10334. $fs = new Filesystem();
  10335. $fs->mirror(
  10336. $containerOrigin,
  10337. $containerDestination,
  10338. $finder
  10339. );
  10340. }
  10341. }
  10342. }
  10343. }
  10344. foreach ($zip_files_abs as $file_path) {
  10345. if (empty($file_path)) {
  10346. continue;
  10347. }
  10348. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10349. continue;
  10350. }
  10351. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10352. if (strstr($file_path, 'upload/users') !== false) {
  10353. $pos = strpos($file_path, 'my_files/');
  10354. if ($pos !== false) {
  10355. $onlyDirectory = str_replace(
  10356. 'upload/users/',
  10357. '',
  10358. substr($file_path, $pos, strlen($file_path))
  10359. );
  10360. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10361. }
  10362. }
  10363. if (strstr($file_path, 'default_course_document/') !== false) {
  10364. $replace = str_replace('/main', '', $file_path);
  10365. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10366. }
  10367. if (empty($dest_file)) {
  10368. continue;
  10369. }
  10370. $this->create_path($dest_file);
  10371. copy($main_path.$file_path, $dest_file);
  10372. // Check if the file needs a link update.
  10373. if (in_array($file_path, array_keys($link_updates))) {
  10374. $string = file_get_contents($dest_file);
  10375. unlink($dest_file);
  10376. foreach ($link_updates[$file_path] as $old_new) {
  10377. // This is an ugly hack that allows .flv files to be found by the flv player that
  10378. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10379. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10380. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10381. if (substr($old_new['dest'], -3) == 'flv' &&
  10382. substr($old_new['dest'], 0, 5) == 'main/'
  10383. ) {
  10384. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10385. }
  10386. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10387. }
  10388. file_put_contents($dest_file, $string);
  10389. }
  10390. }
  10391. if (is_array($links_to_create)) {
  10392. foreach ($links_to_create as $file => $link) {
  10393. $content = '<!DOCTYPE html><head>
  10394. <meta charset="'.api_get_language_isocode().'" />
  10395. <title>'.$link['title'].'</title>
  10396. </head>
  10397. <body dir="'.api_get_text_direction().'">
  10398. <div style="text-align:center">
  10399. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10400. </body>
  10401. </html>';
  10402. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10403. }
  10404. }
  10405. // Add non exportable message explanation.
  10406. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10407. $file_content = '<!DOCTYPE html><head>
  10408. <meta charset="'.api_get_language_isocode().'" />
  10409. <title>'.$lang_not_exportable.'</title>
  10410. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10411. </head>
  10412. <body dir="'.api_get_text_direction().'">';
  10413. $file_content .=
  10414. <<<EOD
  10415. <style>
  10416. .error-message {
  10417. font-family: arial, verdana, helvetica, sans-serif;
  10418. border-width: 1px;
  10419. border-style: solid;
  10420. left: 50%;
  10421. margin: 10px auto;
  10422. min-height: 30px;
  10423. padding: 5px;
  10424. right: 50%;
  10425. width: 500px;
  10426. background-color: #FFD1D1;
  10427. border-color: #FF0000;
  10428. color: #000;
  10429. }
  10430. </style>
  10431. <body>
  10432. <div class="error-message">
  10433. $lang_not_exportable
  10434. </div>
  10435. </body>
  10436. </html>
  10437. EOD;
  10438. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10439. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10440. }
  10441. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10442. // Add the extra files that go along with a SCORM package.
  10443. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10444. $fs = new Filesystem();
  10445. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10446. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10447. $manifest = @$xmldoc->saveXML();
  10448. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10449. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10450. $zip_folder->add(
  10451. $archivePath.'/'.$temp_dir_short,
  10452. PCLZIP_OPT_REMOVE_PATH,
  10453. $archivePath.'/'.$temp_dir_short.'/'
  10454. );
  10455. // Clean possible temporary files.
  10456. foreach ($files_cleanup as $file) {
  10457. $res = unlink($file);
  10458. if ($res === false) {
  10459. error_log(
  10460. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10461. 0
  10462. );
  10463. }
  10464. }
  10465. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10466. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10467. }
  10468. /**
  10469. * @param int $lp_id
  10470. *
  10471. * @return bool
  10472. */
  10473. public function scorm_export_to_pdf($lp_id)
  10474. {
  10475. $lp_id = (int) $lp_id;
  10476. $files_to_export = [];
  10477. $sessionId = api_get_session_id();
  10478. $course_data = api_get_course_info($this->cc);
  10479. if (!empty($course_data)) {
  10480. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10481. $list = self::get_flat_ordered_items_list($lp_id);
  10482. if (!empty($list)) {
  10483. foreach ($list as $item_id) {
  10484. $item = $this->items[$item_id];
  10485. switch ($item->type) {
  10486. case 'document':
  10487. // Getting documents from a LP with chamilo documents
  10488. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10489. // Try loading document from the base course.
  10490. if (empty($file_data) && !empty($sessionId)) {
  10491. $file_data = DocumentManager::get_document_data_by_id(
  10492. $item->path,
  10493. $this->cc,
  10494. false,
  10495. 0
  10496. );
  10497. }
  10498. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10499. if (file_exists($file_path)) {
  10500. $files_to_export[] = [
  10501. 'title' => $item->get_title(),
  10502. 'path' => $file_path,
  10503. ];
  10504. }
  10505. break;
  10506. case 'asset': //commes from a scorm package generated by chamilo
  10507. case 'sco':
  10508. $file_path = $scorm_path.'/'.$item->path;
  10509. if (file_exists($file_path)) {
  10510. $files_to_export[] = [
  10511. 'title' => $item->get_title(),
  10512. 'path' => $file_path,
  10513. ];
  10514. }
  10515. break;
  10516. case 'dir':
  10517. $files_to_export[] = [
  10518. 'title' => $item->get_title(),
  10519. 'path' => null,
  10520. ];
  10521. break;
  10522. }
  10523. }
  10524. }
  10525. $pdf = new PDF();
  10526. $result = $pdf->html_to_pdf(
  10527. $files_to_export,
  10528. $this->name,
  10529. $this->cc,
  10530. true,
  10531. true,
  10532. true,
  10533. $this->get_name()
  10534. );
  10535. return $result;
  10536. }
  10537. return false;
  10538. }
  10539. /**
  10540. * Temp function to be moved in main_api or the best place around for this.
  10541. * Creates a file path if it doesn't exist.
  10542. *
  10543. * @param string $path
  10544. */
  10545. public function create_path($path)
  10546. {
  10547. $path_bits = explode('/', dirname($path));
  10548. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10549. $path_built = IS_WINDOWS_OS ? '' : '/';
  10550. foreach ($path_bits as $bit) {
  10551. if (!empty($bit)) {
  10552. $new_path = $path_built.$bit;
  10553. if (is_dir($new_path)) {
  10554. $path_built = $new_path.'/';
  10555. } else {
  10556. mkdir($new_path, api_get_permissions_for_new_directories());
  10557. $path_built = $new_path.'/';
  10558. }
  10559. }
  10560. }
  10561. }
  10562. /**
  10563. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10564. *
  10565. * @return bool The results of the unlink function, or false if there was no image to start with
  10566. */
  10567. public function delete_lp_image()
  10568. {
  10569. $img = $this->get_preview_image();
  10570. if ($img != '') {
  10571. $del_file = $this->get_preview_image_path(null, 'sys');
  10572. if (isset($del_file) && file_exists($del_file)) {
  10573. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10574. if (file_exists($del_file_2)) {
  10575. unlink($del_file_2);
  10576. }
  10577. $this->set_preview_image('');
  10578. return @unlink($del_file);
  10579. }
  10580. }
  10581. return false;
  10582. }
  10583. /**
  10584. * Uploads an author image to the upload/learning_path/images directory.
  10585. *
  10586. * @param array The image array, coming from the $_FILES superglobal
  10587. *
  10588. * @return bool True on success, false on error
  10589. */
  10590. public function upload_image($image_array)
  10591. {
  10592. if (!empty($image_array['name'])) {
  10593. $upload_ok = process_uploaded_file($image_array);
  10594. $has_attachment = true;
  10595. }
  10596. if ($upload_ok && $has_attachment) {
  10597. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10598. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10599. $updir = $sys_course_path.$courseDir;
  10600. // Try to add an extension to the file if it hasn't one.
  10601. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10602. if (filter_extension($new_file_name)) {
  10603. $file_extension = explode('.', $image_array['name']);
  10604. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10605. $filename = uniqid('');
  10606. $new_file_name = $filename.'.'.$file_extension;
  10607. $new_path = $updir.'/'.$new_file_name;
  10608. // Resize the image.
  10609. $temp = new Image($image_array['tmp_name']);
  10610. $temp->resize(104);
  10611. $result = $temp->send_image($new_path);
  10612. // Storing the image filename.
  10613. if ($result) {
  10614. $this->set_preview_image($new_file_name);
  10615. //Resize to 64px to use on course homepage
  10616. $temp->resize(64);
  10617. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10618. return true;
  10619. }
  10620. }
  10621. }
  10622. return false;
  10623. }
  10624. /**
  10625. * @param int $lp_id
  10626. * @param string $status
  10627. */
  10628. public function set_autolaunch($lp_id, $status)
  10629. {
  10630. $course_id = api_get_course_int_id();
  10631. $lp_id = (int) $lp_id;
  10632. $status = (int) $status;
  10633. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10634. // Setting everything to autolaunch = 0
  10635. $attributes['autolaunch'] = 0;
  10636. $where = [
  10637. 'session_id = ? AND c_id = ? ' => [
  10638. api_get_session_id(),
  10639. $course_id,
  10640. ],
  10641. ];
  10642. Database::update($lp_table, $attributes, $where);
  10643. if ($status == 1) {
  10644. //Setting my lp_id to autolaunch = 1
  10645. $attributes['autolaunch'] = 1;
  10646. $where = [
  10647. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10648. $lp_id,
  10649. api_get_session_id(),
  10650. $course_id,
  10651. ],
  10652. ];
  10653. Database::update($lp_table, $attributes, $where);
  10654. }
  10655. }
  10656. /**
  10657. * Gets previous_item_id for the next element of the lp_item table.
  10658. *
  10659. * @author Isaac flores paz
  10660. *
  10661. * @return int Previous item ID
  10662. */
  10663. public function select_previous_item_id()
  10664. {
  10665. $course_id = api_get_course_int_id();
  10666. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10667. // Get the max order of the items
  10668. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10669. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10670. $rs_max_order = Database::query($sql);
  10671. $row_max_order = Database::fetch_object($rs_max_order);
  10672. $max_order = $row_max_order->display_order;
  10673. // Get the previous item ID
  10674. $sql = "SELECT iid as previous FROM $table_lp_item
  10675. WHERE
  10676. c_id = $course_id AND
  10677. lp_id = ".$this->lp_id." AND
  10678. display_order = '$max_order' ";
  10679. $rs_max = Database::query($sql);
  10680. $row_max = Database::fetch_object($rs_max);
  10681. // Return the previous item ID
  10682. return $row_max->previous;
  10683. }
  10684. /**
  10685. * Copies an LP.
  10686. */
  10687. public function copy()
  10688. {
  10689. // Course builder
  10690. $cb = new CourseBuilder();
  10691. //Setting tools that will be copied
  10692. $cb->set_tools_to_build(['learnpaths']);
  10693. //Setting elements that will be copied
  10694. $cb->set_tools_specific_id_list(
  10695. ['learnpaths' => [$this->lp_id]]
  10696. );
  10697. $course = $cb->build();
  10698. //Course restorer
  10699. $course_restorer = new CourseRestorer($course);
  10700. $course_restorer->set_add_text_in_items(true);
  10701. $course_restorer->set_tool_copy_settings(
  10702. ['learnpaths' => ['reset_dates' => true]]
  10703. );
  10704. $course_restorer->restore(
  10705. api_get_course_id(),
  10706. api_get_session_id(),
  10707. false,
  10708. false
  10709. );
  10710. }
  10711. /**
  10712. * Verify document size.
  10713. *
  10714. * @param string $s
  10715. *
  10716. * @return bool
  10717. */
  10718. public static function verify_document_size($s)
  10719. {
  10720. $post_max = ini_get('post_max_size');
  10721. if (substr($post_max, -1, 1) == 'M') {
  10722. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10723. } elseif (substr($post_max, -1, 1) == 'G') {
  10724. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10725. }
  10726. $upl_max = ini_get('upload_max_filesize');
  10727. if (substr($upl_max, -1, 1) == 'M') {
  10728. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10729. } elseif (substr($upl_max, -1, 1) == 'G') {
  10730. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10731. }
  10732. $documents_total_space = DocumentManager::documents_total_space();
  10733. $course_max_space = DocumentManager::get_course_quota();
  10734. $total_size = filesize($s) + $documents_total_space;
  10735. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10736. return true;
  10737. }
  10738. return false;
  10739. }
  10740. /**
  10741. * Clear LP prerequisites.
  10742. */
  10743. public function clear_prerequisites()
  10744. {
  10745. $course_id = $this->get_course_int_id();
  10746. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10747. $lp_id = $this->get_id();
  10748. // Cleaning prerequisites
  10749. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10750. WHERE c_id = $course_id AND lp_id = $lp_id";
  10751. Database::query($sql);
  10752. // Cleaning mastery score for exercises
  10753. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10754. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10755. Database::query($sql);
  10756. }
  10757. public function set_previous_step_as_prerequisite_for_all_items()
  10758. {
  10759. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10760. $course_id = $this->get_course_int_id();
  10761. $lp_id = $this->get_id();
  10762. if (!empty($this->items)) {
  10763. $previous_item_id = null;
  10764. $previous_item_max = 0;
  10765. $previous_item_type = null;
  10766. $last_item_not_dir = null;
  10767. $last_item_not_dir_type = null;
  10768. $last_item_not_dir_max = null;
  10769. foreach ($this->ordered_items as $itemId) {
  10770. $item = $this->getItem($itemId);
  10771. // if there was a previous item... (otherwise jump to set it)
  10772. if (!empty($previous_item_id)) {
  10773. $current_item_id = $item->get_id(); //save current id
  10774. if ($item->get_type() != 'dir') {
  10775. // Current item is not a folder, so it qualifies to get a prerequisites
  10776. if ($last_item_not_dir_type == 'quiz') {
  10777. // if previous is quiz, mark its max score as default score to be achieved
  10778. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10779. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10780. Database::query($sql);
  10781. }
  10782. // now simply update the prerequisite to set it to the last non-chapter item
  10783. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10784. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10785. Database::query($sql);
  10786. // record item as 'non-chapter' reference
  10787. $last_item_not_dir = $item->get_id();
  10788. $last_item_not_dir_type = $item->get_type();
  10789. $last_item_not_dir_max = $item->get_max();
  10790. }
  10791. } else {
  10792. if ($item->get_type() != 'dir') {
  10793. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10794. $last_item_not_dir = $item->get_id();
  10795. $last_item_not_dir_type = $item->get_type();
  10796. $last_item_not_dir_max = $item->get_max();
  10797. }
  10798. }
  10799. // Saving the item as "previous item" for the next loop
  10800. $previous_item_id = $item->get_id();
  10801. $previous_item_max = $item->get_max();
  10802. $previous_item_type = $item->get_type();
  10803. }
  10804. }
  10805. }
  10806. /**
  10807. * @param array $params
  10808. *
  10809. * @throws \Doctrine\ORM\OptimisticLockException
  10810. *
  10811. * @return int
  10812. */
  10813. public static function createCategory($params)
  10814. {
  10815. $em = Database::getManager();
  10816. $item = new CLpCategory();
  10817. $item->setName($params['name']);
  10818. $item->setCId($params['c_id']);
  10819. $em->persist($item);
  10820. $em->flush();
  10821. api_item_property_update(
  10822. api_get_course_info(),
  10823. TOOL_LEARNPATH_CATEGORY,
  10824. $item->getId(),
  10825. 'visible',
  10826. api_get_user_id()
  10827. );
  10828. return $item->getId();
  10829. }
  10830. /**
  10831. * @param array $params
  10832. *
  10833. * @throws \Doctrine\ORM\ORMException
  10834. * @throws \Doctrine\ORM\OptimisticLockException
  10835. * @throws \Doctrine\ORM\TransactionRequiredException
  10836. */
  10837. public static function updateCategory($params)
  10838. {
  10839. $em = Database::getManager();
  10840. /** @var CLpCategory $item */
  10841. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10842. if ($item) {
  10843. $item->setName($params['name']);
  10844. $em->merge($item);
  10845. $em->flush();
  10846. }
  10847. }
  10848. /**
  10849. * @param int $id
  10850. *
  10851. * @throws \Doctrine\ORM\ORMException
  10852. * @throws \Doctrine\ORM\OptimisticLockException
  10853. * @throws \Doctrine\ORM\TransactionRequiredException
  10854. */
  10855. public static function moveUpCategory($id)
  10856. {
  10857. $id = (int) $id;
  10858. $em = Database::getManager();
  10859. /** @var CLpCategory $item */
  10860. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10861. if ($item) {
  10862. $position = $item->getPosition() - 1;
  10863. $item->setPosition($position);
  10864. $em->persist($item);
  10865. $em->flush();
  10866. }
  10867. }
  10868. /**
  10869. * @param int $id
  10870. *
  10871. * @throws \Doctrine\ORM\ORMException
  10872. * @throws \Doctrine\ORM\OptimisticLockException
  10873. * @throws \Doctrine\ORM\TransactionRequiredException
  10874. */
  10875. public static function moveDownCategory($id)
  10876. {
  10877. $id = (int) $id;
  10878. $em = Database::getManager();
  10879. /** @var CLpCategory $item */
  10880. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10881. if ($item) {
  10882. $position = $item->getPosition() + 1;
  10883. $item->setPosition($position);
  10884. $em->persist($item);
  10885. $em->flush();
  10886. }
  10887. }
  10888. /**
  10889. * @param int $courseId
  10890. *
  10891. * @throws \Doctrine\ORM\Query\QueryException
  10892. *
  10893. * @return int|mixed
  10894. */
  10895. public static function getCountCategories($courseId)
  10896. {
  10897. if (empty($courseId)) {
  10898. return 0;
  10899. }
  10900. $em = Database::getManager();
  10901. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10902. $query->setParameter('id', $courseId);
  10903. return $query->getSingleScalarResult();
  10904. }
  10905. /**
  10906. * @param int $courseId
  10907. *
  10908. * @return mixed
  10909. */
  10910. public static function getCategories($courseId)
  10911. {
  10912. $em = Database::getManager();
  10913. // Using doctrine extensions
  10914. /** @var SortableRepository $repo */
  10915. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10916. $items = $repo
  10917. ->getBySortableGroupsQuery(['cId' => $courseId])
  10918. ->getResult();
  10919. return $items;
  10920. }
  10921. /**
  10922. * @param int $id
  10923. *
  10924. * @throws \Doctrine\ORM\ORMException
  10925. * @throws \Doctrine\ORM\OptimisticLockException
  10926. * @throws \Doctrine\ORM\TransactionRequiredException
  10927. *
  10928. * @return CLpCategory
  10929. */
  10930. public static function getCategory($id)
  10931. {
  10932. $id = (int) $id;
  10933. $em = Database::getManager();
  10934. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10935. return $item;
  10936. }
  10937. /**
  10938. * @param int $courseId
  10939. *
  10940. * @return array
  10941. */
  10942. public static function getCategoryByCourse($courseId)
  10943. {
  10944. $em = Database::getManager();
  10945. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10946. ['cId' => $courseId]
  10947. );
  10948. return $items;
  10949. }
  10950. /**
  10951. * @param int $id
  10952. *
  10953. * @throws \Doctrine\ORM\ORMException
  10954. * @throws \Doctrine\ORM\OptimisticLockException
  10955. * @throws \Doctrine\ORM\TransactionRequiredException
  10956. *
  10957. * @return mixed
  10958. */
  10959. public static function deleteCategory($id)
  10960. {
  10961. $em = Database::getManager();
  10962. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10963. if ($item) {
  10964. $courseId = $item->getCId();
  10965. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10966. $query->setParameter('id', $courseId);
  10967. $query->setParameter('catId', $item->getId());
  10968. $lps = $query->getResult();
  10969. // Setting category = 0.
  10970. if ($lps) {
  10971. foreach ($lps as $lpItem) {
  10972. $lpItem->setCategoryId(0);
  10973. }
  10974. }
  10975. // Removing category.
  10976. $em->remove($item);
  10977. $em->flush();
  10978. $courseInfo = api_get_course_info_by_id($courseId);
  10979. $sessionId = api_get_session_id();
  10980. // Delete link tool
  10981. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10982. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10983. // Delete tools
  10984. $sql = "DELETE FROM $tbl_tool
  10985. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10986. Database::query($sql);
  10987. return true;
  10988. }
  10989. return false;
  10990. }
  10991. /**
  10992. * @param int $courseId
  10993. * @param bool $addSelectOption
  10994. *
  10995. * @return mixed
  10996. */
  10997. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10998. {
  10999. $items = self::getCategoryByCourse($courseId);
  11000. $cats = [];
  11001. if ($addSelectOption) {
  11002. $cats = [get_lang('SelectACategory')];
  11003. }
  11004. if (!empty($items)) {
  11005. foreach ($items as $cat) {
  11006. $cats[$cat->getId()] = $cat->getName();
  11007. }
  11008. }
  11009. return $cats;
  11010. }
  11011. /**
  11012. * @param string $courseCode
  11013. * @param int $lpId
  11014. * @param int $user_id
  11015. *
  11016. * @return learnpath
  11017. */
  11018. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11019. {
  11020. $debug = 0;
  11021. $learnPath = null;
  11022. $lpObject = Session::read('lpobject');
  11023. if ($lpObject !== null) {
  11024. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11025. if ($debug) {
  11026. error_log('getLpFromSession: unserialize');
  11027. error_log('------getLpFromSession------');
  11028. error_log('------unserialize------');
  11029. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11030. error_log("api_get_sessionid: ".api_get_session_id());
  11031. }
  11032. }
  11033. if (!is_object($learnPath)) {
  11034. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11035. if ($debug) {
  11036. error_log('------getLpFromSession------');
  11037. error_log('getLpFromSession: create new learnpath');
  11038. error_log("create new LP with $courseCode - $lpId - $user_id");
  11039. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11040. error_log("api_get_sessionid: ".api_get_session_id());
  11041. }
  11042. }
  11043. return $learnPath;
  11044. }
  11045. /**
  11046. * @param int $itemId
  11047. *
  11048. * @return learnpathItem|false
  11049. */
  11050. public function getItem($itemId)
  11051. {
  11052. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11053. return $this->items[$itemId];
  11054. }
  11055. return false;
  11056. }
  11057. /**
  11058. * @return int
  11059. */
  11060. public function getCurrentAttempt()
  11061. {
  11062. $attempt = $this->getItem($this->get_current_item_id());
  11063. if ($attempt) {
  11064. $attemptId = $attempt->get_attempt_id();
  11065. return $attemptId;
  11066. }
  11067. return 0;
  11068. }
  11069. /**
  11070. * @return int
  11071. */
  11072. public function getCategoryId()
  11073. {
  11074. return (int) $this->categoryId;
  11075. }
  11076. /**
  11077. * @param int $categoryId
  11078. *
  11079. * @return bool
  11080. */
  11081. public function setCategoryId($categoryId)
  11082. {
  11083. $this->categoryId = (int) $categoryId;
  11084. $table = Database::get_course_table(TABLE_LP_MAIN);
  11085. $lp_id = $this->get_id();
  11086. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11087. WHERE iid = $lp_id";
  11088. Database::query($sql);
  11089. return true;
  11090. }
  11091. /**
  11092. * Get whether this is a learning path with the possibility to subscribe
  11093. * users or not.
  11094. *
  11095. * @return int
  11096. */
  11097. public function getSubscribeUsers()
  11098. {
  11099. return $this->subscribeUsers;
  11100. }
  11101. /**
  11102. * Set whether this is a learning path with the possibility to subscribe
  11103. * users or not.
  11104. *
  11105. * @param int $value (0 = false, 1 = true)
  11106. *
  11107. * @return bool
  11108. */
  11109. public function setSubscribeUsers($value)
  11110. {
  11111. $this->subscribeUsers = (int) $value;
  11112. $table = Database::get_course_table(TABLE_LP_MAIN);
  11113. $lp_id = $this->get_id();
  11114. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11115. WHERE iid = $lp_id";
  11116. Database::query($sql);
  11117. return true;
  11118. }
  11119. /**
  11120. * Calculate the count of stars for a user in this LP
  11121. * This calculation is based on the following rules:
  11122. * - the student gets one star when he gets to 50% of the learning path
  11123. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11124. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11125. * - the student gets the final star when the score for the *last* test is >= 80%.
  11126. *
  11127. * @param int $sessionId Optional. The session ID
  11128. *
  11129. * @return int The count of stars
  11130. */
  11131. public function getCalculateStars($sessionId = 0)
  11132. {
  11133. $stars = 0;
  11134. $progress = self::getProgress(
  11135. $this->lp_id,
  11136. $this->user_id,
  11137. $this->course_int_id,
  11138. $sessionId
  11139. );
  11140. if ($progress >= 50) {
  11141. $stars++;
  11142. }
  11143. // Calculate stars chapters evaluation
  11144. $exercisesItems = $this->getExercisesItems();
  11145. if (!empty($exercisesItems)) {
  11146. $totalResult = 0;
  11147. foreach ($exercisesItems as $exerciseItem) {
  11148. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11149. $this->user_id,
  11150. $exerciseItem->path,
  11151. $this->course_int_id,
  11152. $sessionId,
  11153. $this->lp_id,
  11154. $exerciseItem->db_id
  11155. );
  11156. $exerciseResultInfo = end($exerciseResultInfo);
  11157. if (!$exerciseResultInfo) {
  11158. continue;
  11159. }
  11160. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11161. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11162. } else {
  11163. $exerciseResult = 0;
  11164. }
  11165. $totalResult += $exerciseResult;
  11166. }
  11167. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11168. if ($totalExerciseAverage >= 50) {
  11169. $stars++;
  11170. }
  11171. if ($totalExerciseAverage >= 80) {
  11172. $stars++;
  11173. }
  11174. }
  11175. // Calculate star for final evaluation
  11176. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11177. if (!empty($finalEvaluationItem)) {
  11178. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11179. $this->user_id,
  11180. $finalEvaluationItem->path,
  11181. $this->course_int_id,
  11182. $sessionId,
  11183. $this->lp_id,
  11184. $finalEvaluationItem->db_id
  11185. );
  11186. $evaluationResultInfo = end($evaluationResultInfo);
  11187. if ($evaluationResultInfo) {
  11188. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11189. if ($evaluationResult >= 80) {
  11190. $stars++;
  11191. }
  11192. }
  11193. }
  11194. return $stars;
  11195. }
  11196. /**
  11197. * Get the items of exercise type.
  11198. *
  11199. * @return array The items. Otherwise return false
  11200. */
  11201. public function getExercisesItems()
  11202. {
  11203. $exercises = [];
  11204. foreach ($this->items as $item) {
  11205. if ($item->type != 'quiz') {
  11206. continue;
  11207. }
  11208. $exercises[] = $item;
  11209. }
  11210. array_pop($exercises);
  11211. return $exercises;
  11212. }
  11213. /**
  11214. * Get the item of exercise type (evaluation type).
  11215. *
  11216. * @return array The final evaluation. Otherwise return false
  11217. */
  11218. public function getFinalEvaluationItem()
  11219. {
  11220. $exercises = [];
  11221. foreach ($this->items as $item) {
  11222. if ($item->type != 'quiz') {
  11223. continue;
  11224. }
  11225. $exercises[] = $item;
  11226. }
  11227. return array_pop($exercises);
  11228. }
  11229. /**
  11230. * Calculate the total points achieved for the current user in this learning path.
  11231. *
  11232. * @param int $sessionId Optional. The session Id
  11233. *
  11234. * @return int
  11235. */
  11236. public function getCalculateScore($sessionId = 0)
  11237. {
  11238. // Calculate stars chapters evaluation
  11239. $exercisesItems = $this->getExercisesItems();
  11240. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11241. $totalExercisesResult = 0;
  11242. $totalEvaluationResult = 0;
  11243. if ($exercisesItems !== false) {
  11244. foreach ($exercisesItems as $exerciseItem) {
  11245. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11246. $this->user_id,
  11247. $exerciseItem->path,
  11248. $this->course_int_id,
  11249. $sessionId,
  11250. $this->lp_id,
  11251. $exerciseItem->db_id
  11252. );
  11253. $exerciseResultInfo = end($exerciseResultInfo);
  11254. if (!$exerciseResultInfo) {
  11255. continue;
  11256. }
  11257. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11258. }
  11259. }
  11260. if (!empty($finalEvaluationItem)) {
  11261. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11262. $this->user_id,
  11263. $finalEvaluationItem->path,
  11264. $this->course_int_id,
  11265. $sessionId,
  11266. $this->lp_id,
  11267. $finalEvaluationItem->db_id
  11268. );
  11269. $evaluationResultInfo = end($evaluationResultInfo);
  11270. if ($evaluationResultInfo) {
  11271. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11272. }
  11273. }
  11274. return $totalExercisesResult + $totalEvaluationResult;
  11275. }
  11276. /**
  11277. * Check if URL is not allowed to be show in a iframe.
  11278. *
  11279. * @param string $src
  11280. *
  11281. * @return string
  11282. */
  11283. public function fixBlockedLinks($src)
  11284. {
  11285. $urlInfo = parse_url($src);
  11286. $platformProtocol = 'https';
  11287. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11288. $platformProtocol = 'http';
  11289. }
  11290. $protocolFixApplied = false;
  11291. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11292. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11293. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11294. if ($platformProtocol != $scheme) {
  11295. Session::write('x_frame_source', $src);
  11296. $src = 'blank.php?error=x_frames_options';
  11297. $protocolFixApplied = true;
  11298. }
  11299. if ($protocolFixApplied == false) {
  11300. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11301. // Check X-Frame-Options
  11302. $ch = curl_init();
  11303. $options = [
  11304. CURLOPT_URL => $src,
  11305. CURLOPT_RETURNTRANSFER => true,
  11306. CURLOPT_HEADER => true,
  11307. CURLOPT_FOLLOWLOCATION => true,
  11308. CURLOPT_ENCODING => "",
  11309. CURLOPT_AUTOREFERER => true,
  11310. CURLOPT_CONNECTTIMEOUT => 120,
  11311. CURLOPT_TIMEOUT => 120,
  11312. CURLOPT_MAXREDIRS => 10,
  11313. ];
  11314. $proxySettings = api_get_configuration_value('proxy_settings');
  11315. if (!empty($proxySettings) &&
  11316. isset($proxySettings['curl_setopt_array'])
  11317. ) {
  11318. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11319. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11320. }
  11321. curl_setopt_array($ch, $options);
  11322. $response = curl_exec($ch);
  11323. $httpCode = curl_getinfo($ch);
  11324. $headers = substr($response, 0, $httpCode['header_size']);
  11325. $error = false;
  11326. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11327. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11328. ) {
  11329. $error = true;
  11330. }
  11331. if ($error) {
  11332. Session::write('x_frame_source', $src);
  11333. $src = 'blank.php?error=x_frames_options';
  11334. }
  11335. }
  11336. }
  11337. return $src;
  11338. }
  11339. /**
  11340. * Check if this LP has a created forum in the basis course.
  11341. *
  11342. * @return bool
  11343. */
  11344. public function lpHasForum()
  11345. {
  11346. $forumTable = Database::get_course_table(TABLE_FORUM);
  11347. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11348. $fakeFrom = "
  11349. $forumTable f
  11350. INNER JOIN $itemProperty ip
  11351. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11352. ";
  11353. $resultData = Database::select(
  11354. 'COUNT(f.iid) AS qty',
  11355. $fakeFrom,
  11356. [
  11357. 'where' => [
  11358. 'ip.visibility != ? AND ' => 2,
  11359. 'ip.tool = ? AND ' => TOOL_FORUM,
  11360. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11361. 'f.lp_id = ?' => intval($this->lp_id),
  11362. ],
  11363. ],
  11364. 'first'
  11365. );
  11366. return $resultData['qty'] > 0;
  11367. }
  11368. /**
  11369. * Get the forum for this learning path.
  11370. *
  11371. * @param int $sessionId
  11372. *
  11373. * @return bool
  11374. */
  11375. public function getForum($sessionId = 0)
  11376. {
  11377. $forumTable = Database::get_course_table(TABLE_FORUM);
  11378. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11379. $fakeFrom = "$forumTable f
  11380. INNER JOIN $itemProperty ip ";
  11381. if ($this->lp_session_id == 0) {
  11382. $fakeFrom .= "
  11383. ON (
  11384. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11385. f.session_id = ip.session_id OR ip.session_id IS NULL
  11386. )
  11387. )
  11388. ";
  11389. } else {
  11390. $fakeFrom .= "
  11391. ON (
  11392. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11393. )
  11394. ";
  11395. }
  11396. $resultData = Database::select(
  11397. 'f.*',
  11398. $fakeFrom,
  11399. [
  11400. 'where' => [
  11401. 'ip.visibility != ? AND ' => 2,
  11402. 'ip.tool = ? AND ' => TOOL_FORUM,
  11403. 'f.session_id = ? AND ' => $sessionId,
  11404. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11405. 'f.lp_id = ?' => intval($this->lp_id),
  11406. ],
  11407. ],
  11408. 'first'
  11409. );
  11410. if (empty($resultData)) {
  11411. return false;
  11412. }
  11413. return $resultData;
  11414. }
  11415. /**
  11416. * Create a forum for this learning path.
  11417. *
  11418. * @param int $forumCategoryId
  11419. *
  11420. * @return int The forum ID if was created. Otherwise return false
  11421. */
  11422. public function createForum($forumCategoryId)
  11423. {
  11424. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11425. $forumId = store_forum(
  11426. [
  11427. 'lp_id' => $this->lp_id,
  11428. 'forum_title' => $this->name,
  11429. 'forum_comment' => null,
  11430. 'forum_category' => (int) $forumCategoryId,
  11431. 'students_can_edit_group' => ['students_can_edit' => 0],
  11432. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11433. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11434. 'group_forum' => 0,
  11435. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11436. ],
  11437. [],
  11438. true
  11439. );
  11440. return $forumId;
  11441. }
  11442. /**
  11443. * Get the LP Final Item form.
  11444. *
  11445. * @throws Exception
  11446. * @throws HTML_QuickForm_Error
  11447. *
  11448. * @return string
  11449. */
  11450. public function getFinalItemForm()
  11451. {
  11452. $finalItem = $this->getFinalItem();
  11453. $title = '';
  11454. if ($finalItem) {
  11455. $title = $finalItem->get_title();
  11456. $buttonText = get_lang('Save');
  11457. $content = $this->getSavedFinalItem();
  11458. } else {
  11459. $buttonText = get_lang('LPCreateDocument');
  11460. $content = $this->getFinalItemTemplate();
  11461. }
  11462. $courseInfo = api_get_course_info();
  11463. $result = $this->generate_lp_folder($courseInfo);
  11464. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11465. $relative_prefix = '../../';
  11466. $editorConfig = [
  11467. 'ToolbarSet' => 'LearningPathDocuments',
  11468. 'Width' => '100%',
  11469. 'Height' => '500',
  11470. 'FullPage' => true,
  11471. 'CreateDocumentDir' => $relative_prefix,
  11472. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11473. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11474. ];
  11475. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11476. 'type' => 'document',
  11477. 'lp_id' => $this->lp_id,
  11478. ]);
  11479. $form = new FormValidator('final_item', 'POST', $url);
  11480. $form->addText('title', get_lang('Title'));
  11481. $form->addButtonSave($buttonText);
  11482. $form->addHtml(
  11483. Display::return_message(
  11484. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11485. 'normal',
  11486. false
  11487. )
  11488. );
  11489. $renderer = $form->defaultRenderer();
  11490. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11491. $form->addHtmlEditor(
  11492. 'content_lp_certificate',
  11493. null,
  11494. true,
  11495. false,
  11496. $editorConfig,
  11497. true
  11498. );
  11499. $form->addHidden('action', 'add_final_item');
  11500. $form->addHidden('path', Session::read('pathItem'));
  11501. $form->addHidden('previous', $this->get_last());
  11502. $form->setDefaults(
  11503. ['title' => $title, 'content_lp_certificate' => $content]
  11504. );
  11505. if ($form->validate()) {
  11506. $values = $form->exportValues();
  11507. $lastItemId = $this->getLastInFirstLevel();
  11508. if (!$finalItem) {
  11509. $documentId = $this->create_document(
  11510. $this->course_info,
  11511. $values['content_lp_certificate'],
  11512. $values['title']
  11513. );
  11514. $this->add_item(
  11515. 0,
  11516. $lastItemId,
  11517. 'final_item',
  11518. $documentId,
  11519. $values['title'],
  11520. ''
  11521. );
  11522. Display::addFlash(
  11523. Display::return_message(get_lang('Added'))
  11524. );
  11525. } else {
  11526. $this->edit_document($this->course_info);
  11527. }
  11528. }
  11529. return $form->returnForm();
  11530. }
  11531. /**
  11532. * Check if the current lp item is first, both, last or none from lp list.
  11533. *
  11534. * @param int $currentItemId
  11535. *
  11536. * @return string
  11537. */
  11538. public function isFirstOrLastItem($currentItemId)
  11539. {
  11540. $lpItemId = [];
  11541. $typeListNotToVerify = self::getChapterTypes();
  11542. // Using get_toc() function instead $this->items because returns the correct order of the items
  11543. foreach ($this->get_toc() as $item) {
  11544. if (!in_array($item['type'], $typeListNotToVerify)) {
  11545. $lpItemId[] = $item['id'];
  11546. }
  11547. }
  11548. $lastLpItemIndex = count($lpItemId) - 1;
  11549. $position = array_search($currentItemId, $lpItemId);
  11550. switch ($position) {
  11551. case 0:
  11552. if (!$lastLpItemIndex) {
  11553. $answer = 'both';
  11554. break;
  11555. }
  11556. $answer = 'first';
  11557. break;
  11558. case $lastLpItemIndex:
  11559. $answer = 'last';
  11560. break;
  11561. default:
  11562. $answer = 'none';
  11563. }
  11564. return $answer;
  11565. }
  11566. /**
  11567. * Get whether this is a learning path with the accumulated SCORM time or not.
  11568. *
  11569. * @return int
  11570. */
  11571. public function getAccumulateScormTime()
  11572. {
  11573. return $this->accumulateScormTime;
  11574. }
  11575. /**
  11576. * Set whether this is a learning path with the accumulated SCORM time or not.
  11577. *
  11578. * @param int $value (0 = false, 1 = true)
  11579. *
  11580. * @return bool Always returns true
  11581. */
  11582. public function setAccumulateScormTime($value)
  11583. {
  11584. $this->accumulateScormTime = (int) $value;
  11585. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11586. $lp_id = $this->get_id();
  11587. $sql = "UPDATE $lp_table
  11588. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11589. WHERE iid = $lp_id";
  11590. Database::query($sql);
  11591. return true;
  11592. }
  11593. /**
  11594. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11595. * the new learning path tool.
  11596. *
  11597. * The function is a big switch on tool type.
  11598. * In each case, we query the corresponding table for information and build the link
  11599. * with that information.
  11600. *
  11601. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11602. * previous work (display_addedresource_link_in_learnpath())
  11603. *
  11604. * @param int $course_id Course code
  11605. * @param int $learningPathId The learning path ID (in lp table)
  11606. * @param int $id_in_path the unique index in the items table
  11607. * @param int $lpViewId
  11608. *
  11609. * @return string
  11610. */
  11611. public static function rl_get_resource_link_for_learnpath(
  11612. $course_id,
  11613. $learningPathId,
  11614. $id_in_path,
  11615. $lpViewId
  11616. ) {
  11617. $session_id = api_get_session_id();
  11618. $course_info = api_get_course_info_by_id($course_id);
  11619. $learningPathId = (int) $learningPathId;
  11620. $id_in_path = (int) $id_in_path;
  11621. $lpViewId = (int) $lpViewId;
  11622. $em = Database::getManager();
  11623. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11624. /** @var CLpItem $rowItem */
  11625. $rowItem = $lpItemRepo->findOneBy([
  11626. 'cId' => $course_id,
  11627. 'lpId' => $learningPathId,
  11628. 'iid' => $id_in_path,
  11629. ]);
  11630. if (!$rowItem) {
  11631. // Try one more time with "id"
  11632. /** @var CLpItem $rowItem */
  11633. $rowItem = $lpItemRepo->findOneBy([
  11634. 'cId' => $course_id,
  11635. 'lpId' => $learningPathId,
  11636. 'id' => $id_in_path,
  11637. ]);
  11638. if (!$rowItem) {
  11639. return -1;
  11640. }
  11641. }
  11642. $course_code = $course_info['code'];
  11643. $type = $rowItem->getItemType();
  11644. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11645. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11646. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11647. $link = '';
  11648. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11649. switch ($type) {
  11650. case 'dir':
  11651. return $main_dir_path.'lp/blank.php';
  11652. case TOOL_CALENDAR_EVENT:
  11653. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11654. case TOOL_ANNOUNCEMENT:
  11655. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11656. case TOOL_LINK:
  11657. $linkInfo = Link::getLinkInfo($id);
  11658. if (isset($linkInfo['url'])) {
  11659. return $linkInfo['url'];
  11660. }
  11661. return '';
  11662. case TOOL_QUIZ:
  11663. if (empty($id)) {
  11664. return '';
  11665. }
  11666. // Get the lp_item_view with the highest view_count.
  11667. $learnpathItemViewResult = $em
  11668. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11669. ->findBy(
  11670. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11671. ['viewCount' => 'DESC'],
  11672. 1
  11673. );
  11674. /** @var CLpItemView $learnpathItemViewData */
  11675. $learnpathItemViewData = current($learnpathItemViewResult);
  11676. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11677. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11678. .http_build_query([
  11679. 'lp_init' => 1,
  11680. 'learnpath_item_view_id' => $learnpathItemViewId,
  11681. 'learnpath_id' => $learningPathId,
  11682. 'learnpath_item_id' => $id_in_path,
  11683. 'exerciseId' => $id,
  11684. ]);
  11685. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11686. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11687. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11688. $myrow = Database::fetch_array($result);
  11689. $path = $myrow['path'];
  11690. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11691. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11692. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11693. case TOOL_FORUM:
  11694. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11695. case TOOL_THREAD:
  11696. // forum post
  11697. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11698. if (empty($id)) {
  11699. return '';
  11700. }
  11701. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11702. $result = Database::query($sql);
  11703. $myrow = Database::fetch_array($result);
  11704. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11705. .$extraParams;
  11706. case TOOL_POST:
  11707. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11708. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11709. $myrow = Database::fetch_array($result);
  11710. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11711. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11712. case TOOL_READOUT_TEXT:
  11713. return api_get_path(WEB_CODE_PATH).
  11714. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  11715. case TOOL_DOCUMENT:
  11716. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  11717. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11718. if (empty($document)) {
  11719. // Try with normal id
  11720. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  11721. if (empty($document)) {
  11722. return '';
  11723. }
  11724. }
  11725. $documentPathInfo = pathinfo($document->getPath());
  11726. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  11727. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11728. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  11729. $openmethod = 2;
  11730. $officedoc = false;
  11731. Session::write('openmethod', $openmethod);
  11732. Session::write('officedoc', $officedoc);
  11733. if ($showDirectUrl) {
  11734. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11735. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  11736. if (Link::isPdfLink($file)) {
  11737. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  11738. return $pdfUrl;
  11739. }
  11740. }
  11741. return $file;
  11742. }
  11743. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11744. case TOOL_LP_FINAL_ITEM:
  11745. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11746. .$extraParams;
  11747. case 'assignments':
  11748. return $main_dir_path.'work/work.php?'.$extraParams;
  11749. case TOOL_DROPBOX:
  11750. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11751. case 'introduction_text': //DEPRECATED
  11752. return '';
  11753. case TOOL_COURSE_DESCRIPTION:
  11754. return $main_dir_path.'course_description?'.$extraParams;
  11755. case TOOL_GROUP:
  11756. return $main_dir_path.'group/group.php?'.$extraParams;
  11757. case TOOL_USER:
  11758. return $main_dir_path.'user/user.php?'.$extraParams;
  11759. case TOOL_STUDENTPUBLICATION:
  11760. if (!empty($rowItem->getPath())) {
  11761. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11762. }
  11763. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11764. }
  11765. return $link;
  11766. }
  11767. /**
  11768. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11769. *
  11770. * @author Yannick Warnier <ywarnier@beeznest.org>
  11771. *
  11772. * @param string $course_code Course code
  11773. * @param int $learningPathId
  11774. * @param int $id_in_path The resource ID
  11775. *
  11776. * @return string
  11777. */
  11778. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11779. {
  11780. $_course = api_get_course_info($course_code);
  11781. if (empty($_course)) {
  11782. return '';
  11783. }
  11784. $course_id = $_course['real_id'];
  11785. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11786. $learningPathId = (int) $learningPathId;
  11787. $id_in_path = (int) $id_in_path;
  11788. $sql = "SELECT item_type, title, ref
  11789. FROM $tbl_lp_item
  11790. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11791. $res_item = Database::query($sql);
  11792. if (Database::num_rows($res_item) < 1) {
  11793. return '';
  11794. }
  11795. $row_item = Database::fetch_array($res_item);
  11796. $type = strtolower($row_item['item_type']);
  11797. $id = $row_item['ref'];
  11798. $output = '';
  11799. switch ($type) {
  11800. case TOOL_CALENDAR_EVENT:
  11801. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11802. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11803. $myrow = Database::fetch_array($result);
  11804. $output = $myrow['title'];
  11805. break;
  11806. case TOOL_ANNOUNCEMENT:
  11807. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11808. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11809. $myrow = Database::fetch_array($result);
  11810. $output = $myrow['title'];
  11811. break;
  11812. case TOOL_LINK:
  11813. // Doesn't take $target into account.
  11814. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11815. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11816. $myrow = Database::fetch_array($result);
  11817. $output = $myrow['title'];
  11818. break;
  11819. case TOOL_QUIZ:
  11820. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11821. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  11822. $myrow = Database::fetch_array($result);
  11823. $output = $myrow['title'];
  11824. break;
  11825. case TOOL_FORUM:
  11826. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11827. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  11828. $myrow = Database::fetch_array($result);
  11829. $output = $myrow['forum_name'];
  11830. break;
  11831. case TOOL_THREAD:
  11832. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11833. // Grabbing the title of the post.
  11834. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11835. $result_title = Database::query($sql_title);
  11836. $myrow_title = Database::fetch_array($result_title);
  11837. $output = $myrow_title['post_title'];
  11838. break;
  11839. case TOOL_POST:
  11840. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11841. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11842. $result = Database::query($sql);
  11843. $post = Database::fetch_array($result);
  11844. $output = $post['post_title'];
  11845. break;
  11846. case 'dir':
  11847. case TOOL_DOCUMENT:
  11848. $title = $row_item['title'];
  11849. $output = '-';
  11850. if (!empty($title)) {
  11851. $output = $title;
  11852. }
  11853. break;
  11854. case 'hotpotatoes':
  11855. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11856. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11857. $myrow = Database::fetch_array($result);
  11858. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11859. $last = count($pathname) - 1; // Making a correct name for the link.
  11860. $filename = $pathname[$last]; // Making a correct name for the link.
  11861. $myrow['path'] = rawurlencode($myrow['path']);
  11862. $output = $filename;
  11863. break;
  11864. }
  11865. return stripslashes($output);
  11866. }
  11867. /**
  11868. * Get the parent names for the current item.
  11869. *
  11870. * @param int $newItemId Optional. The item ID
  11871. *
  11872. * @return array
  11873. */
  11874. public function getCurrentItemParentNames($newItemId = 0)
  11875. {
  11876. $newItemId = $newItemId ?: $this->get_current_item_id();
  11877. $return = [];
  11878. $item = $this->getItem($newItemId);
  11879. $parent = $this->getItem($item->get_parent());
  11880. while ($parent) {
  11881. $return[] = $parent->get_title();
  11882. $parent = $this->getItem($parent->get_parent());
  11883. }
  11884. return array_reverse($return);
  11885. }
  11886. /**
  11887. * Reads and process "lp_subscription_settings" setting.
  11888. *
  11889. * @return array
  11890. */
  11891. public static function getSubscriptionSettings()
  11892. {
  11893. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11894. if (empty($subscriptionSettings)) {
  11895. // By default allow both settings
  11896. $subscriptionSettings = [
  11897. 'allow_add_users_to_lp' => true,
  11898. 'allow_add_users_to_lp_category' => true,
  11899. ];
  11900. } else {
  11901. $subscriptionSettings = $subscriptionSettings['options'];
  11902. }
  11903. return $subscriptionSettings;
  11904. }
  11905. /**
  11906. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  11907. */
  11908. public function exportToCourseBuildFormat()
  11909. {
  11910. if (!api_is_allowed_to_edit()) {
  11911. return false;
  11912. }
  11913. $courseBuilder = new CourseBuilder();
  11914. $itemList = [];
  11915. /** @var learnpathItem $item */
  11916. foreach ($this->items as $item) {
  11917. $itemList[$item->get_type()][] = $item->get_path();
  11918. }
  11919. if (empty($itemList)) {
  11920. return false;
  11921. }
  11922. if (isset($itemList['document'])) {
  11923. // Get parents
  11924. foreach ($itemList['document'] as $documentId) {
  11925. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  11926. if (!empty($documentInfo['parents'])) {
  11927. foreach ($documentInfo['parents'] as $parentInfo) {
  11928. if (in_array($parentInfo['iid'], $itemList['document'])) {
  11929. continue;
  11930. }
  11931. $itemList['document'][] = $parentInfo['iid'];
  11932. }
  11933. }
  11934. }
  11935. $courseInfo = api_get_course_info();
  11936. foreach ($itemList['document'] as $documentId) {
  11937. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  11938. $items = DocumentManager::get_resources_from_source_html(
  11939. $documentInfo['absolute_path'],
  11940. true,
  11941. TOOL_DOCUMENT
  11942. );
  11943. if (!empty($items)) {
  11944. foreach ($items as $item) {
  11945. // Get information about source url
  11946. $url = $item[0]; // url
  11947. $scope = $item[1]; // scope (local, remote)
  11948. $type = $item[2]; // type (rel, abs, url)
  11949. $origParseUrl = parse_url($url);
  11950. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  11951. if ($scope == 'local') {
  11952. if ($type == 'abs' || $type == 'rel') {
  11953. $documentFile = strstr($realOrigPath, 'document');
  11954. if (strpos($realOrigPath, $documentFile) !== false) {
  11955. $documentFile = str_replace('document', '', $documentFile);
  11956. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  11957. // Document found! Add it to the list
  11958. if ($itemDocumentId) {
  11959. $itemList['document'][] = $itemDocumentId;
  11960. }
  11961. }
  11962. }
  11963. }
  11964. }
  11965. }
  11966. }
  11967. $courseBuilder->build_documents(
  11968. api_get_session_id(),
  11969. $this->get_course_int_id(),
  11970. true,
  11971. $itemList['document']
  11972. );
  11973. }
  11974. if (isset($itemList['quiz'])) {
  11975. $courseBuilder->build_quizzes(
  11976. api_get_session_id(),
  11977. $this->get_course_int_id(),
  11978. true,
  11979. $itemList['quiz']
  11980. );
  11981. }
  11982. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  11983. /*if (!empty($itemList['thread'])) {
  11984. $postList = [];
  11985. foreach ($itemList['thread'] as $postId) {
  11986. $post = get_post_information($postId);
  11987. if ($post) {
  11988. if (!isset($itemList['forum'])) {
  11989. $itemList['forum'] = [];
  11990. }
  11991. $itemList['forum'][] = $post['forum_id'];
  11992. $postList[] = $postId;
  11993. }
  11994. }
  11995. if (!empty($postList)) {
  11996. $courseBuilder->build_forum_posts(
  11997. $this->get_course_int_id(),
  11998. null,
  11999. null,
  12000. $postList
  12001. );
  12002. }
  12003. }*/
  12004. if (!empty($itemList['thread'])) {
  12005. $threadList = [];
  12006. $em = Database::getManager();
  12007. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12008. foreach ($itemList['thread'] as $threadId) {
  12009. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12010. $thread = $repo->find($threadId);
  12011. if ($thread) {
  12012. $itemList['forum'][] = $thread->getForumId();
  12013. $threadList[] = $thread->getIid();
  12014. }
  12015. }
  12016. if (!empty($threadList)) {
  12017. $courseBuilder->build_forum_topics(
  12018. api_get_session_id(),
  12019. $this->get_course_int_id(),
  12020. null,
  12021. $threadList
  12022. );
  12023. }
  12024. }
  12025. $forumCategoryList = [];
  12026. if (isset($itemList['forum'])) {
  12027. foreach ($itemList['forum'] as $forumId) {
  12028. $forumInfo = get_forums($forumId);
  12029. $forumCategoryList[] = $forumInfo['forum_category'];
  12030. }
  12031. }
  12032. if (!empty($forumCategoryList)) {
  12033. $courseBuilder->build_forum_category(
  12034. api_get_session_id(),
  12035. $this->get_course_int_id(),
  12036. true,
  12037. $forumCategoryList
  12038. );
  12039. }
  12040. if (!empty($itemList['forum'])) {
  12041. $courseBuilder->build_forums(
  12042. api_get_session_id(),
  12043. $this->get_course_int_id(),
  12044. true,
  12045. $itemList['forum']
  12046. );
  12047. }
  12048. if (isset($itemList['link'])) {
  12049. $courseBuilder->build_links(
  12050. api_get_session_id(),
  12051. $this->get_course_int_id(),
  12052. true,
  12053. $itemList['link']
  12054. );
  12055. }
  12056. if (!empty($itemList['student_publication'])) {
  12057. $courseBuilder->build_works(
  12058. api_get_session_id(),
  12059. $this->get_course_int_id(),
  12060. true,
  12061. $itemList['student_publication']
  12062. );
  12063. }
  12064. $courseBuilder->build_learnpaths(
  12065. api_get_session_id(),
  12066. $this->get_course_int_id(),
  12067. true,
  12068. [$this->get_id()],
  12069. false
  12070. );
  12071. $courseBuilder->restoreDocumentsFromList();
  12072. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12073. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12074. $result = DocumentManager::file_send_for_download(
  12075. $zipPath,
  12076. true,
  12077. $this->get_name().'.zip'
  12078. );
  12079. if ($result) {
  12080. api_not_allowed();
  12081. }
  12082. return true;
  12083. }
  12084. /**
  12085. * Get whether this is a learning path with the accumulated work time or not.
  12086. *
  12087. * @return int
  12088. */
  12089. public function getAccumulateWorkTime()
  12090. {
  12091. return (int) $this->accumulateWorkTime;
  12092. }
  12093. /**
  12094. * Get whether this is a learning path with the accumulated work time or not.
  12095. *
  12096. * @return int
  12097. */
  12098. public function getAccumulateWorkTimeTotalCourse()
  12099. {
  12100. $table = Database::get_course_table(TABLE_LP_MAIN);
  12101. $sql = "SELECT SUM(accumulate_work_time) AS total
  12102. FROM $table
  12103. WHERE c_id = ".$this->course_int_id;
  12104. $result = Database::query($sql);
  12105. $row = Database::fetch_array($result);
  12106. return (int) $row['total'];
  12107. }
  12108. /**
  12109. * Set whether this is a learning path with the accumulated work time or not.
  12110. *
  12111. * @param int $value (0 = false, 1 = true)
  12112. *
  12113. * @return bool
  12114. */
  12115. public function setAccumulateWorkTime($value)
  12116. {
  12117. if (!api_get_configuration_value('lp_minimum_time')) {
  12118. return false;
  12119. }
  12120. $this->accumulateWorkTime = (int) $value;
  12121. $table = Database::get_course_table(TABLE_LP_MAIN);
  12122. $lp_id = $this->get_id();
  12123. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12124. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12125. Database::query($sql);
  12126. return true;
  12127. }
  12128. /**
  12129. * @param int $lpId
  12130. * @param int $courseId
  12131. *
  12132. * @return mixed
  12133. */
  12134. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12135. {
  12136. $lpId = (int) $lpId;
  12137. $courseId = (int) $courseId;
  12138. $table = Database::get_course_table(TABLE_LP_MAIN);
  12139. $sql = "SELECT accumulate_work_time
  12140. FROM $table
  12141. WHERE c_id = $courseId AND id = $lpId";
  12142. $result = Database::query($sql);
  12143. $row = Database::fetch_array($result);
  12144. return $row['accumulate_work_time'];
  12145. }
  12146. /**
  12147. * @param int $courseId
  12148. *
  12149. * @return int
  12150. */
  12151. public static function getAccumulateWorkTimeTotal($courseId)
  12152. {
  12153. $table = Database::get_course_table(TABLE_LP_MAIN);
  12154. $courseId = (int) $courseId;
  12155. $sql = "SELECT SUM(accumulate_work_time) AS total
  12156. FROM $table
  12157. WHERE c_id = $courseId";
  12158. $result = Database::query($sql);
  12159. $row = Database::fetch_array($result);
  12160. return (int) $row['total'];
  12161. }
  12162. /**
  12163. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12164. * and put the images in.
  12165. *
  12166. * @return array
  12167. */
  12168. public static function getIconSelect()
  12169. {
  12170. $theme = api_get_visual_theme();
  12171. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12172. $icons = ['' => get_lang('SelectAnOption')];
  12173. if (is_dir($path)) {
  12174. $finder = new Finder();
  12175. $finder->files()->in($path);
  12176. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12177. /** @var SplFileInfo $file */
  12178. foreach ($finder as $file) {
  12179. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12180. $icons[$file->getFilename()] = $file->getFilename();
  12181. }
  12182. }
  12183. }
  12184. return $icons;
  12185. }
  12186. /**
  12187. * @param int $lpId
  12188. *
  12189. * @return string
  12190. */
  12191. public static function getSelectedIcon($lpId)
  12192. {
  12193. $extraFieldValue = new ExtraFieldValue('lp');
  12194. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12195. $icon = '';
  12196. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12197. $icon = $lpIcon['value'];
  12198. }
  12199. return $icon;
  12200. }
  12201. /**
  12202. * @param int $lpId
  12203. *
  12204. * @return string
  12205. */
  12206. public static function getSelectedIconHtml($lpId)
  12207. {
  12208. $icon = self::getSelectedIcon($lpId);
  12209. if (empty($icon)) {
  12210. return '';
  12211. }
  12212. $theme = api_get_visual_theme();
  12213. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12214. return Display::img($path);
  12215. }
  12216. /**
  12217. * @param string $value
  12218. *
  12219. * @return string
  12220. */
  12221. public function cleanItemTitle($value)
  12222. {
  12223. $value = Security::remove_XSS(strip_tags($value));
  12224. return $value;
  12225. }
  12226. /**
  12227. * @param FormValidator $form
  12228. */
  12229. public function setItemTitle(FormValidator $form)
  12230. {
  12231. if (api_get_configuration_value('save_titles_as_html')) {
  12232. $form->addHtmlEditor(
  12233. 'title',
  12234. get_lang('Title'),
  12235. true,
  12236. false,
  12237. ['ToolbarSet' => 'TitleAsHtml']
  12238. );
  12239. } else {
  12240. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
  12241. $form->applyFilter('title', 'trim');
  12242. $form->applyFilter('title', 'html_filter');
  12243. }
  12244. }
  12245. /**
  12246. * @return array
  12247. */
  12248. public function getItemsForForm($addParentCondition = false)
  12249. {
  12250. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12251. $course_id = api_get_course_int_id();
  12252. $sql = "SELECT * FROM $tbl_lp_item
  12253. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  12254. if ($addParentCondition) {
  12255. $sql .= ' AND parent_item_id = 0 ';
  12256. }
  12257. $sql .= ' ORDER BY display_order ASC';
  12258. $result = Database::query($sql);
  12259. $arrLP = [];
  12260. while ($row = Database::fetch_array($result)) {
  12261. $arrLP[] = [
  12262. 'iid' => $row['iid'],
  12263. 'id' => $row['iid'],
  12264. 'item_type' => $row['item_type'],
  12265. 'title' => $this->cleanItemTitle($row['title']),
  12266. 'title_raw' => $row['title'],
  12267. 'path' => $row['path'],
  12268. 'description' => Security::remove_XSS($row['description']),
  12269. 'parent_item_id' => $row['parent_item_id'],
  12270. 'previous_item_id' => $row['previous_item_id'],
  12271. 'next_item_id' => $row['next_item_id'],
  12272. 'display_order' => $row['display_order'],
  12273. 'max_score' => $row['max_score'],
  12274. 'min_score' => $row['min_score'],
  12275. 'mastery_score' => $row['mastery_score'],
  12276. 'prerequisite' => $row['prerequisite'],
  12277. 'max_time_allowed' => $row['max_time_allowed'],
  12278. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  12279. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  12280. ];
  12281. }
  12282. return $arrLP;
  12283. }
  12284. /**
  12285. * Get the depth level of LP item.
  12286. *
  12287. * @param array $items
  12288. * @param int $currentItemId
  12289. *
  12290. * @return int
  12291. */
  12292. private static function get_level_for_item($items, $currentItemId)
  12293. {
  12294. $parentItemId = 0;
  12295. if (isset($items[$currentItemId])) {
  12296. $parentItemId = $items[$currentItemId]->parent;
  12297. }
  12298. if ($parentItemId == 0) {
  12299. return 0;
  12300. } else {
  12301. return self::get_level_for_item($items, $parentItemId) + 1;
  12302. }
  12303. }
  12304. /**
  12305. * Generate the link for a learnpath category as course tool.
  12306. *
  12307. * @param int $categoryId
  12308. *
  12309. * @return string
  12310. */
  12311. private static function getCategoryLinkForTool($categoryId)
  12312. {
  12313. $categoryId = (int) $categoryId;
  12314. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12315. .http_build_query(
  12316. [
  12317. 'action' => 'view_category',
  12318. 'id' => $categoryId,
  12319. ]
  12320. );
  12321. return $link;
  12322. }
  12323. /**
  12324. * Return the scorm item type object with spaces replaced with _
  12325. * The return result is use to build a css classname like scorm_type_$return.
  12326. *
  12327. * @param $in_type
  12328. *
  12329. * @return mixed
  12330. */
  12331. private static function format_scorm_type_item($in_type)
  12332. {
  12333. return str_replace(' ', '_', $in_type);
  12334. }
  12335. /**
  12336. * Check and obtain the lp final item if exist.
  12337. *
  12338. * @return learnpathItem
  12339. */
  12340. private function getFinalItem()
  12341. {
  12342. if (empty($this->items)) {
  12343. return null;
  12344. }
  12345. foreach ($this->items as $item) {
  12346. if ($item->type !== 'final_item') {
  12347. continue;
  12348. }
  12349. return $item;
  12350. }
  12351. }
  12352. /**
  12353. * Get the LP Final Item Template.
  12354. *
  12355. * @return string
  12356. */
  12357. private function getFinalItemTemplate()
  12358. {
  12359. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12360. }
  12361. /**
  12362. * Get the LP Final Item Url.
  12363. *
  12364. * @return string
  12365. */
  12366. private function getSavedFinalItem()
  12367. {
  12368. $finalItem = $this->getFinalItem();
  12369. $doc = DocumentManager::get_document_data_by_id(
  12370. $finalItem->path,
  12371. $this->cc
  12372. );
  12373. if ($doc && file_exists($doc['absolute_path'])) {
  12374. return file_get_contents($doc['absolute_path']);
  12375. }
  12376. return '';
  12377. }
  12378. }