learnpath.class.php 501 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\CourseBundle\Entity\CLpCategory;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  7. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  8. use Symfony\Component\Filesystem\Filesystem;
  9. use Symfony\Component\Finder\Finder;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CTool;
  12. use Chamilo\UserBundle\Entity\User;
  13. /**
  14. * Class learnpath
  15. * This class defines the parent attributes and methods for Chamilo learnpaths
  16. * and SCORM learnpaths. It is used by the scorm class.
  17. *
  18. * @package chamilo.learnpath
  19. * @author Yannick Warnier <ywarnier@beeznest.org>
  20. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  21. */
  22. class learnpath
  23. {
  24. public $attempt = 0; // The number for the current ID view.
  25. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  26. public $current; // Id of the current item the user is viewing.
  27. public $current_score; // The score of the current item.
  28. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  29. public $current_time_stop; // The time the user closed this resource.
  30. public $default_status = 'not attempted';
  31. public $encoding = 'UTF-8';
  32. public $error = '';
  33. public $extra_information = ''; // This string can be used by proprietary SCORM contents to store data about the current learnpath.
  34. public $force_commit = false; // For SCORM only - if set to true, will send a scorm LMSCommit() request on each LMSSetValue().
  35. public $index; // The index of the active learnpath_item in $ordered_items array.
  36. public $items = array();
  37. public $last; // item_id of last item viewed in the learning path.
  38. public $last_item_seen = 0; // In case we have already come in this learnpath, reuse the last item seen if authorized.
  39. public $license; // Which license this course has been given - not used yet on 20060522.
  40. public $lp_id; // DB ID for this learnpath.
  41. public $lp_view_id; // DB ID for lp_view
  42. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  43. public $message = '';
  44. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  45. public $name; // Learnpath name (they generally have one).
  46. public $ordered_items = array(); // List of the learnpath items in the order they are to be read.
  47. public $path = ''; // Path inside the scorm directory (if scorm).
  48. public $theme; // The current theme of the learning path.
  49. public $preview_image; // The current image of the learning path.
  50. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  51. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  52. public $prevent_reinit = 1;
  53. // Describes the mode of progress bar display.
  54. public $seriousgame_mode = 0;
  55. public $progress_bar_mode = '%';
  56. // Percentage progress as saved in the db.
  57. public $progress_db = '0';
  58. public $proximity; // Wether the content is distant or local or unknown.
  59. public $refs_list = array(); //list of items by ref => db_id. Used only for prerequisites match.
  60. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  61. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  62. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  63. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  64. public $user_id; //ID of the user that is viewing/using the course
  65. public $update_queue = array();
  66. public $scorm_debug = 0;
  67. public $arrMenu = array(); // Array for the menu items.
  68. public $debug = 0; // Logging level.
  69. public $lp_session_id = 0;
  70. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  71. public $prerequisite = 0;
  72. public $use_max_score = 1; // 1 or 0
  73. public $subscribeUsers = 0; // Subscribe users or not
  74. public $created_on = '';
  75. public $modified_on = '';
  76. public $publicated_on = '';
  77. public $expired_on = '';
  78. public $ref = null;
  79. public $course_int_id;
  80. public $course_info = array();
  81. public $categoryId;
  82. /**
  83. * Constructor.
  84. * Needs a database handler, a course code and a learnpath id from the database.
  85. * Also builds the list of items into $this->items.
  86. * @param string $course Course code
  87. * @param integer $lp_id
  88. * @param integer $user_id
  89. */
  90. public function __construct($course, $lp_id, $user_id)
  91. {
  92. $this->encoding = api_get_system_encoding();
  93. if ($this->debug > 0) {
  94. error_log('New LP - In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')', 0);
  95. }
  96. if (empty($course)) {
  97. $course = api_get_course_id();
  98. }
  99. $course_info = api_get_course_info($course);
  100. if (!empty($course_info)) {
  101. $this->cc = $course_info['code'];
  102. $this->course_info = $course_info;
  103. $course_id = $course_info['real_id'];
  104. } else {
  105. $this->error = 'Course code does not exist in database.';
  106. }
  107. $this->set_course_int_id($course_id);
  108. $lp_id = (int)$lp_id;
  109. // Check learnpath ID.
  110. if (empty($lp_id)) {
  111. $this->error = 'Learnpath ID is empty';
  112. } else {
  113. // TODO: Make it flexible to use any course_code (still using env course code here).
  114. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  115. $sql
  116. = "SELECT * FROM $lp_table
  117. WHERE id = '$lp_id' AND c_id = $course_id";
  118. if ($this->debug > 2) {
  119. error_log('New LP - learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  120. }
  121. $res = Database::query($sql);
  122. if (Database::num_rows($res) > 0) {
  123. $this->lp_id = $lp_id;
  124. $row = Database::fetch_array($res);
  125. $this->type = $row['lp_type'];
  126. $this->name = stripslashes($row['name']);
  127. $this->proximity = $row['content_local'];
  128. $this->theme = $row['theme'];
  129. $this->maker = $row['content_maker'];
  130. $this->prevent_reinit = $row['prevent_reinit'];
  131. $this->seriousgame_mode = $row['seriousgame_mode'];
  132. $this->license = $row['content_license'];
  133. $this->scorm_debug = $row['debug'];
  134. $this->js_lib = $row['js_lib'];
  135. $this->path = $row['path'];
  136. $this->preview_image = $row['preview_image'];
  137. $this->author = $row['author'];
  138. $this->hide_toc_frame = $row['hide_toc_frame'];
  139. $this->lp_session_id = $row['session_id'];
  140. $this->use_max_score = $row['use_max_score'];
  141. $this->subscribeUsers = $row['subscribe_users'];
  142. $this->created_on = $row['created_on'];
  143. $this->modified_on = $row['modified_on'];
  144. $this->ref = $row['ref'];
  145. $this->categoryId = $row['category_id'];
  146. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time']
  147. : 'true';
  148. if (!empty($row['publicated_on'])) {
  149. $this->publicated_on = $row['publicated_on'];
  150. }
  151. if (!empty($row['expired_on'])) {
  152. $this->expired_on = $row['expired_on'];
  153. }
  154. if ($this->type == 2) {
  155. if ($row['force_commit'] == 1) {
  156. $this->force_commit = true;
  157. }
  158. }
  159. $this->mode = $row['default_view_mod'];
  160. // Check user ID.
  161. if (empty($user_id)) {
  162. $this->error = 'User ID is empty';
  163. } else {
  164. $user_info = api_get_user_info($user_id);
  165. if (!empty($user_info)) {
  166. $this->user_id = $user_info['user_id'];
  167. } else {
  168. $this->error = 'User ID does not exist in database ('.$sql.')';
  169. }
  170. }
  171. // End of variables checking.
  172. $session_id = api_get_session_id();
  173. // Get the session condition for learning paths of the base + session.
  174. $session = api_get_session_condition($session_id);
  175. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  176. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  177. // Selecting by view_count descending allows to get the highest view_count first.
  178. $sql
  179. = "SELECT * FROM $lp_table
  180. WHERE c_id = $course_id AND lp_id = '$lp_id' AND user_id = '$user_id' $session
  181. ORDER BY view_count DESC";
  182. $res = Database::query($sql);
  183. if ($this->debug > 2) {
  184. error_log('New LP - learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  185. }
  186. if (Database::num_rows($res) > 0) {
  187. if ($this->debug > 2) {
  188. error_log('New LP - learnpath::__construct() '.__LINE__.' - Found previous view', 0);
  189. }
  190. $row = Database::fetch_array($res);
  191. $this->attempt = $row['view_count'];
  192. $this->lp_view_id = $row['id'];
  193. $this->last_item_seen = $row['last_item'];
  194. $this->progress_db = $row['progress'];
  195. $this->lp_view_session_id = $row['session_id'];
  196. } else {
  197. if (!api_is_invitee()) {
  198. if ($this->debug > 2) {
  199. error_log('New LP - learnpath::__construct() '.__LINE__.' - NOT Found previous view', 0);
  200. }
  201. $this->attempt = 1;
  202. $params = [
  203. 'c_id' => $course_id,
  204. 'lp_id' => $lp_id,
  205. 'user_id' => $user_id,
  206. 'view_count' => 1,
  207. 'session_id' => $session_id,
  208. 'last_item' => 0
  209. ];
  210. $this->lp_view_id = Database::insert($lp_table, $params);
  211. if (!empty($this->lp_view_id)) {
  212. $sql = "UPDATE $lp_table SET id = iid WHERE iid = ".$this->lp_view_id;
  213. Database::query($sql);
  214. }
  215. }
  216. }
  217. // Initialise items.
  218. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  219. $sql
  220. = "SELECT * FROM $lp_item_table
  221. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  222. ORDER BY parent_item_id, display_order";
  223. $res = Database::query($sql);
  224. if ($this->debug > 2) {
  225. error_log('New LP - learnpath::__construct() '.__LINE__.' - query lp items: '.$sql, 0);
  226. error_log('-- Start while--', 0);
  227. }
  228. $lp_item_id_list = array();
  229. while ($row = Database::fetch_array($res)) {
  230. $lp_item_id_list[] = $row['id'];
  231. switch ($this->type) {
  232. case 3: //aicc
  233. $oItem = new aiccItem('db', $row['id'], $course_id);
  234. if (is_object($oItem)) {
  235. $my_item_id = $oItem->get_id();
  236. $oItem->set_lp_view($this->lp_view_id, $course_id);
  237. $oItem->set_prevent_reinit($this->prevent_reinit);
  238. // Don't use reference here as the next loop will make the pointed object change.
  239. $this->items[$my_item_id] = $oItem;
  240. $this->refs_list[$oItem->ref] = $my_item_id;
  241. if ($this->debug > 2) {
  242. error_log(
  243. 'New LP - learnpath::__construct() - '.
  244. 'aicc object with id '.$my_item_id.
  245. ' set in items[]',
  246. 0
  247. );
  248. }
  249. }
  250. break;
  251. case 2:
  252. $oItem = new scormItem('db', $row['id'], $course_id);
  253. if (is_object($oItem)) {
  254. $my_item_id = $oItem->get_id();
  255. $oItem->set_lp_view($this->lp_view_id, $course_id);
  256. $oItem->set_prevent_reinit($this->prevent_reinit);
  257. // Don't use reference here as the next loop will make the pointed object change.
  258. $this->items[$my_item_id] = $oItem;
  259. $this->refs_list[$oItem->ref] = $my_item_id;
  260. if ($this->debug > 2) {
  261. error_log('New LP - object with id '.$my_item_id.' set in items[]', 0);
  262. }
  263. }
  264. break;
  265. case 1:
  266. default:
  267. if ($this->debug > 2) {
  268. error_log('New LP - learnpath::__construct() '.__LINE__.' - calling learnpathItem', 0);
  269. }
  270. $oItem = new learnpathItem($row['id'], $user_id, $course_id, $row);
  271. if ($this->debug > 2) {
  272. error_log('New LP - learnpath::__construct() '.__LINE__.' - end calling learnpathItem',
  273. 0);
  274. }
  275. if (is_object($oItem)) {
  276. $my_item_id = $oItem->get_id();
  277. //$oItem->set_lp_view($this->lp_view_id); // Moved down to when we are sure the item_view exists.
  278. $oItem->set_prevent_reinit($this->prevent_reinit);
  279. // Don't use reference here as the next loop will make the pointed object change.
  280. $this->items[$my_item_id] = $oItem;
  281. $this->refs_list[$my_item_id] = $my_item_id;
  282. if ($this->debug > 2) {
  283. error_log(
  284. 'New LP - learnpath::__construct() '.__LINE__.
  285. ' - object with id '.$my_item_id.' set in items[]',
  286. 0
  287. );
  288. }
  289. }
  290. break;
  291. }
  292. // Setting the object level with variable $this->items[$i][parent]
  293. foreach ($this->items as $itemLPObject) {
  294. $level = self::get_level_for_item($this->items, $itemLPObject->db_id);
  295. $itemLPObject->level = $level;
  296. }
  297. // Setting the view in the item object.
  298. if (is_object($this->items[$row['id']])) {
  299. $this->items[$row['id']]->set_lp_view($this->lp_view_id, $course_id);
  300. if ($this->items[$row['id']]->get_type() == TOOL_HOTPOTATOES) {
  301. $this->items[$row['id']]->current_start_time = 0;
  302. $this->items[$row['id']]->current_stop_time = 0;
  303. }
  304. }
  305. }
  306. if ($this->debug > 2) {
  307. error_log('New LP - learnpath::__construct() '.__LINE__.' ----- end while ----', 0);
  308. }
  309. if (!empty($lp_item_id_list)) {
  310. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  311. if (!empty($lp_item_id_list_to_string)) {
  312. // Get last viewing vars.
  313. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  314. // This query should only return one or zero result.
  315. $sql
  316. = "SELECT lp_item_id, status
  317. FROM $itemViewTable
  318. WHERE
  319. c_id = $course_id AND
  320. lp_view_id = ".$this->lp_view_id." AND
  321. lp_item_id IN ('".$lp_item_id_list_to_string."')
  322. ORDER BY view_count DESC ";
  323. if ($this->debug > 2) {
  324. error_log(
  325. 'New LP - learnpath::__construct() - Selecting item_views: '.$sql,
  326. 0
  327. );
  328. }
  329. $status_list = array();
  330. $res = Database::query($sql);
  331. while ($row = Database:: fetch_array($res)) {
  332. $status_list[$row['lp_item_id']] = $row['status'];
  333. }
  334. foreach ($lp_item_id_list as $item_id) {
  335. if (isset($status_list[$item_id])) {
  336. $status = $status_list[$item_id];
  337. if (is_object($this->items[$item_id])) {
  338. $this->items[$item_id]->set_status($status);
  339. if (empty($status)) {
  340. $this->items[$item_id]->set_status(
  341. $this->default_status
  342. );
  343. }
  344. }
  345. } else {
  346. if (!api_is_invitee()) {
  347. if (is_object($this->items[$item_id])) {
  348. $this->items[$item_id]->set_status(
  349. $this->default_status
  350. );
  351. }
  352. if (!empty($this->lp_view_id)) {
  353. // Add that row to the lp_item_view table so that we have something to show in the stats page.
  354. $params = [
  355. 'c_id' => $course_id,
  356. 'lp_item_id' => $course_id,
  357. 'lp_view_id' => $this->lp_view_id,
  358. 'view_count' => 1,
  359. 'status' => 'not attempted',
  360. 'start_time' => api_get_utc_datetime(),
  361. 'total_time' => 0,
  362. 'score' => 0
  363. ];
  364. $insertId = Database::insert($itemViewTable, $params);
  365. if ($insertId) {
  366. $sql
  367. = "UPDATE $itemViewTable SET id = iid
  368. WHERE iid = $insertId";
  369. Database::query($sql);
  370. }
  371. $this->items[$item_id]->set_lp_view(
  372. $this->lp_view_id,
  373. $course_id
  374. );
  375. }
  376. }
  377. }
  378. }
  379. }
  380. }
  381. $this->ordered_items = self::get_flat_ordered_items_list(
  382. $this->get_id(),
  383. 0,
  384. $course_id
  385. );
  386. $this->max_ordered_items = 0;
  387. foreach ($this->ordered_items as $index => $dummy) {
  388. if ($index > $this->max_ordered_items && !empty($dummy)) {
  389. $this->max_ordered_items = $index;
  390. }
  391. }
  392. // TODO: Define the current item better.
  393. $this->first();
  394. if ($this->debug > 2) {
  395. error_log('New LP - learnpath::__construct() '.__LINE__
  396. .' - End of learnpath constructor for learnpath '.$this->get_id(), 0);
  397. }
  398. } else {
  399. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  400. }
  401. }
  402. }
  403. /**
  404. * @return string
  405. */
  406. public function getCourseCode()
  407. {
  408. return $this->cc;
  409. }
  410. /**
  411. * @return int
  412. */
  413. public function get_course_int_id()
  414. {
  415. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  416. }
  417. /**
  418. * @param $course_id
  419. * @return int
  420. */
  421. public function set_course_int_id($course_id)
  422. {
  423. return $this->course_int_id = (int)$course_id;
  424. }
  425. /**
  426. * Get the depth level of LP item
  427. * @param array $items
  428. * @param int $currentItemId
  429. * @return int
  430. */
  431. private static function get_level_for_item($items, $currentItemId)
  432. {
  433. $parentItemId = $items[$currentItemId]->parent;
  434. if ($parentItemId == 0) {
  435. return 0;
  436. } else {
  437. return self::get_level_for_item($items, $parentItemId) + 1;
  438. }
  439. }
  440. /**
  441. * Function rewritten based on old_add_item() from Yannick Warnier.
  442. * Due the fact that users can decide where the item should come, I had to overlook this function and
  443. * I found it better to rewrite it. Old function is still available.
  444. * Added also the possibility to add a description.
  445. *
  446. * @param int $parent
  447. * @param int $previous
  448. * @param string $type
  449. * @param int $id resource ID (ref)
  450. * @param string $title
  451. * @param string $description
  452. * @param int $prerequisites
  453. * @param int $max_time_allowed
  454. * @param int $userId
  455. *
  456. * @return int
  457. */
  458. public function add_item(
  459. $parent,
  460. $previous,
  461. $type = 'dir',
  462. $id,
  463. $title,
  464. $description,
  465. $prerequisites = 0,
  466. $max_time_allowed = 0,
  467. $userId = 0
  468. ) {
  469. $course_id = $this->course_info['real_id'];
  470. if ($this->debug > 0) {
  471. error_log('New LP - In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')', 0);
  472. }
  473. if (empty($course_id)) {
  474. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  475. $this->course_info = api_get_course_info($this->cc);
  476. $course_id = $this->course_info['real_id'];
  477. }
  478. $userId = empty($userId) ? api_get_user_id() : $userId;
  479. $sessionId = api_get_session_id();
  480. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  481. $_course = $this->course_info;
  482. $parent = intval($parent);
  483. $previous = intval($previous);
  484. $id = intval($id);
  485. $max_time_allowed = htmlentities($max_time_allowed);
  486. if (empty($max_time_allowed)) {
  487. $max_time_allowed = 0;
  488. }
  489. $sql
  490. = "SELECT COUNT(id) AS num
  491. FROM $tbl_lp_item
  492. WHERE
  493. c_id = $course_id AND
  494. lp_id = ".$this->get_id()." AND
  495. parent_item_id = ".$parent;
  496. $res_count = Database::query($sql);
  497. $row = Database::fetch_array($res_count);
  498. $num = $row['num'];
  499. if ($num > 0) {
  500. if (empty($previous)) {
  501. $sql
  502. = "SELECT id, next_item_id, display_order
  503. FROM ".$tbl_lp_item."
  504. WHERE
  505. c_id = $course_id AND
  506. lp_id = ".$this->get_id()." AND
  507. parent_item_id = ".$parent." AND
  508. previous_item_id = 0 OR
  509. previous_item_id=".$parent;
  510. $result = Database::query($sql);
  511. $row = Database::fetch_array($result);
  512. $tmp_previous = 0;
  513. $next = $row['id'];
  514. $display_order = 0;
  515. } else {
  516. $previous = (int)$previous;
  517. $sql
  518. = "SELECT id, previous_item_id, next_item_id, display_order
  519. FROM $tbl_lp_item
  520. WHERE
  521. c_id = $course_id AND
  522. lp_id = ".$this->get_id()." AND
  523. id = ".$previous;
  524. $result = Database::query($sql);
  525. $row = Database:: fetch_array($result);
  526. $tmp_previous = $row['id'];
  527. $next = $row['next_item_id'];
  528. $display_order = $row['display_order'];
  529. }
  530. } else {
  531. $tmp_previous = 0;
  532. $next = 0;
  533. $display_order = 0;
  534. }
  535. $id = intval($id);
  536. $typeCleaned = Database::escape_string($type);
  537. if ($type == 'quiz') {
  538. $sql
  539. = 'SELECT SUM(ponderation)
  540. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  541. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  542. ON
  543. quiz_question.id = quiz_rel_question.question_id AND
  544. quiz_question.c_id = quiz_rel_question.c_id
  545. WHERE
  546. quiz_rel_question.exercice_id = '.$id." AND
  547. quiz_question.c_id = $course_id AND
  548. quiz_rel_question.c_id = $course_id ";
  549. $rsQuiz = Database::query($sql);
  550. $max_score = Database::result($rsQuiz, 0, 0);
  551. // Disabling the exercise if we add it inside a LP
  552. $exercise = new Exercise($course_id);
  553. $exercise->read($id);
  554. $exercise->disable();
  555. $exercise->save();
  556. } else {
  557. $max_score = 100;
  558. }
  559. $params = array(
  560. "c_id" => $course_id,
  561. "lp_id" => $this->get_id(),
  562. "item_type" => $typeCleaned,
  563. "ref" => '',
  564. "title" => $title,
  565. "description" => $description,
  566. "path" => $id,
  567. "max_score" => $max_score,
  568. "parent_item_id" => $parent,
  569. "previous_item_id" => $previous,
  570. "next_item_id" => intval($next),
  571. "display_order" => $display_order + 1,
  572. "prerequisite" => $prerequisites,
  573. "max_time_allowed" => $max_time_allowed,
  574. 'min_score' => 0,
  575. 'launch_data' => ''
  576. );
  577. if ($prerequisites != 0) {
  578. $params['prerequisite'] = $prerequisites;
  579. }
  580. $new_item_id = Database::insert($tbl_lp_item, $params);
  581. if ($this->debug > 2) {
  582. error_log('New LP - Inserting dir/chapter: '.$new_item_id, 0);
  583. }
  584. if ($new_item_id) {
  585. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  586. Database::query($sql);
  587. $sql
  588. = "UPDATE $tbl_lp_item
  589. SET previous_item_id = $new_item_id
  590. WHERE c_id = $course_id AND id = $next";
  591. Database::query($sql);
  592. // Update the item that should be before the new item.
  593. $sql
  594. = "UPDATE $tbl_lp_item
  595. SET next_item_id = $new_item_id
  596. WHERE c_id = $course_id AND id = $tmp_previous";
  597. Database::query($sql);
  598. // Update all the items after the new item.
  599. $sql = "UPDATE ".$tbl_lp_item."
  600. SET display_order = display_order + 1
  601. WHERE
  602. c_id = $course_id AND
  603. lp_id = ".$this->get_id()." AND
  604. id <> ".$new_item_id." AND
  605. parent_item_id = ".$parent." AND
  606. display_order > ".$display_order;
  607. Database::query($sql);
  608. // Update the item that should come after the new item.
  609. $sql = "UPDATE ".$tbl_lp_item."
  610. SET ref = ".$new_item_id."
  611. WHERE c_id = $course_id AND id = ".$new_item_id;
  612. Database::query($sql);
  613. // Upload audio.
  614. if (!empty($_FILES['mp3']['name'])) {
  615. // Create the audio folder if it does not exist yet.
  616. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  617. if (!is_dir($filepath.'audio')) {
  618. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  619. $audio_id = add_document(
  620. $_course,
  621. '/audio',
  622. 'folder',
  623. 0,
  624. 'audio',
  625. '',
  626. 0,
  627. true,
  628. null,
  629. $sessionId,
  630. $userId
  631. );
  632. api_item_property_update(
  633. $_course,
  634. TOOL_DOCUMENT,
  635. $audio_id,
  636. 'FolderCreated',
  637. $userId,
  638. null,
  639. null,
  640. null,
  641. null,
  642. $sessionId
  643. );
  644. api_item_property_update(
  645. $_course,
  646. TOOL_DOCUMENT,
  647. $audio_id,
  648. 'invisible',
  649. $userId,
  650. null,
  651. null,
  652. null,
  653. null,
  654. $sessionId
  655. );
  656. }
  657. $file_path = handle_uploaded_document(
  658. $_course,
  659. $_FILES['mp3'],
  660. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  661. '/audio',
  662. $userId,
  663. '',
  664. '',
  665. '',
  666. '',
  667. false
  668. );
  669. // Getting the filename only.
  670. $file_components = explode('/', $file_path);
  671. $file = $file_components[count($file_components) - 1];
  672. // Store the mp3 file in the lp_item table.
  673. $sql
  674. = "UPDATE $tbl_lp_item SET
  675. audio = '".Database::escape_string($file)."'
  676. WHERE id = '".intval($new_item_id)."'";
  677. Database::query($sql);
  678. }
  679. }
  680. return $new_item_id;
  681. }
  682. /**
  683. * Static admin function allowing addition of a learnpath to a course.
  684. * @param string Course code
  685. * @param string Learnpath name
  686. * @param string Learnpath description string, if provided
  687. * @param string Type of learnpath (default = 'guess', others = 'dokeos', 'aicc',...)
  688. * @param string Type of files origin (default = 'zip', others = 'dir','web_dir',...)
  689. * @param string Zip file containing the learnpath or directory containing the learnpath
  690. * @return integer The new learnpath ID on success, 0 on failure
  691. */
  692. public static function add_lp(
  693. $courseCode,
  694. $name,
  695. $description = '',
  696. $learnpath = 'guess',
  697. $origin = 'zip',
  698. $zipname = '',
  699. $publicated_on = '',
  700. $expired_on = '',
  701. $categoryId = 0,
  702. $userId = 0
  703. ) {
  704. global $charset;
  705. if (!empty($courseCode)) {
  706. $courseInfo = api_get_course_info($courseCode);
  707. $course_id = $courseInfo['real_id'];
  708. } else {
  709. $course_id = api_get_course_int_id();
  710. $courseInfo = api_get_course_info();
  711. }
  712. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  713. // Check course code exists.
  714. // Check lp_name doesn't exist, otherwise append something.
  715. $i = 0;
  716. $name = Database::escape_string($name);
  717. $categoryId = intval($categoryId);
  718. // Session id.
  719. $session_id = api_get_session_id();
  720. $userId = empty($userId) ? api_get_user_id() : $userId;
  721. $check_name
  722. = "SELECT * FROM $tbl_lp
  723. WHERE c_id = $course_id AND name = '$name'";
  724. $res_name = Database::query($check_name);
  725. if (empty($publicated_on)) {
  726. //by default the publication date is the same that the creation date
  727. //The behaviour above was changed due BT#2800
  728. // global $_custom;
  729. // if (isset($_custom['lps_hidden_when_no_start_date']) && $_custom['lps_hidden_when_no_start_date']) {
  730. // $publicated_on = null;
  731. // } else {
  732. // $publicated_on = null;
  733. // }
  734. $publicated_on = null;
  735. } else {
  736. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  737. }
  738. if (empty($expired_on)) {
  739. $expired_on = null;
  740. } else {
  741. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  742. }
  743. while (Database::num_rows($res_name)) {
  744. // There is already one such name, update the current one a bit.
  745. $i++;
  746. $name = $name.' - '.$i;
  747. $check_name = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND name = '$name'";
  748. $res_name = Database::query($check_name);
  749. }
  750. // New name does not exist yet; keep it.
  751. // Escape description.
  752. // Kevin: added htmlentities().
  753. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  754. $type = 1;
  755. switch ($learnpath) {
  756. case 'guess':
  757. break;
  758. case 'dokeos':
  759. case 'chamilo':
  760. $type = 1;
  761. break;
  762. case 'aicc':
  763. break;
  764. }
  765. switch ($origin) {
  766. case 'zip':
  767. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  768. break;
  769. case 'manual':
  770. default:
  771. $get_max = "SELECT MAX(display_order) FROM $tbl_lp WHERE c_id = $course_id";
  772. $res_max = Database::query($get_max);
  773. if (Database::num_rows($res_max) < 1) {
  774. $dsp = 1;
  775. } else {
  776. $row = Database::fetch_array($res_max);
  777. $dsp = $row[0] + 1;
  778. }
  779. $params = [
  780. 'c_id' => $course_id,
  781. 'lp_type' => $type,
  782. 'name' => $name,
  783. 'description' => $description,
  784. 'path' => '',
  785. 'default_view_mod' => 'embedded',
  786. 'default_encoding' => 'UTF-8',
  787. 'display_order' => $dsp,
  788. 'content_maker' => 'Chamilo',
  789. 'content_local' => 'local',
  790. 'js_lib' => '',
  791. 'session_id' => $session_id,
  792. 'created_on' => api_get_utc_datetime(),
  793. 'modified_on' => api_get_utc_datetime(),
  794. 'publicated_on' => $publicated_on,
  795. 'expired_on' => $expired_on,
  796. 'category_id' => $categoryId,
  797. 'force_commit' => 0,
  798. 'content_license' => '',
  799. 'debug' => 0,
  800. 'theme' => '',
  801. 'preview_image' => '',
  802. 'author' => '',
  803. 'prerequisite' => 0,
  804. 'hide_toc_frame' => 0,
  805. 'seriousgame_mode' => 0,
  806. 'autolaunch' => 0,
  807. 'max_attempts' => 0,
  808. 'subscribe_users' => 0,
  809. 'accumulate_scorm_time' => 1
  810. ];
  811. $id = Database::insert($tbl_lp, $params);
  812. if ($id > 0) {
  813. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  814. Database::query($sql);
  815. // Insert into item_property.
  816. api_item_property_update(
  817. $courseInfo,
  818. TOOL_LEARNPATH,
  819. $id,
  820. 'LearnpathAdded',
  821. $userId
  822. );
  823. api_set_default_visibility($id, TOOL_LEARNPATH, 0, $courseInfo, $session_id, $userId);
  824. return $id;
  825. }
  826. break;
  827. }
  828. }
  829. /**
  830. * Auto completes the parents of an item in case it's been completed or passed
  831. * @param int $item Optional ID of the item from which to look for parents
  832. */
  833. public function autocomplete_parents($item)
  834. {
  835. $debug = $this->debug;
  836. if ($debug) {
  837. error_log('Learnpath::autocomplete_parents()', 0);
  838. }
  839. if (empty($item)) {
  840. $item = $this->current;
  841. }
  842. $currentItem = $this->getItem($item);
  843. if ($currentItem) {
  844. $parent_id = $currentItem->get_parent();
  845. $parent = $this->getItem($parent_id);
  846. if ($parent) {
  847. // if $item points to an object and there is a parent.
  848. if ($debug) {
  849. error_log(
  850. 'Autocompleting parent of item '.$item.' "'.$currentItem->get_title().'" (item '.$parent_id.' "'
  851. .$parent->get_title().'") ',
  852. 0
  853. );
  854. }
  855. // New experiment including failed and browsed in completed status.
  856. //$current_status = $currentItem->get_status();
  857. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  858. // Fixes chapter auto complete
  859. if (true) {
  860. // If the current item is completed or passes or succeeded.
  861. $updateParentStatus = true;
  862. if ($debug) {
  863. error_log('Status of current item is alright', 0);
  864. }
  865. foreach ($parent->get_children() as $childItemId) {
  866. $childItem = $this->getItem($childItemId);
  867. // If children was not set try to get the info
  868. if (empty($childItem->db_item_view_id)) {
  869. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  870. }
  871. // Check all his brothers (parent's children) for completion status.
  872. if ($childItemId != $item) {
  873. if ($debug) {
  874. error_log(
  875. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '
  876. .$childItem->get_status(),
  877. 0
  878. );
  879. }
  880. // Trying completing parents of failed and browsed items as well.
  881. if ($childItem->status_is(
  882. array(
  883. 'completed',
  884. 'passed',
  885. 'succeeded',
  886. 'browsed',
  887. 'failed'
  888. )
  889. )
  890. ) {
  891. // Keep completion status to true.
  892. continue;
  893. } else {
  894. if ($debug > 2) {
  895. error_log(
  896. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId
  897. .' "'.$childItem->get_title().'", is '.$childItem->get_status()
  898. .' db_item_view_id:#'.$childItem->db_item_view_id,
  899. 0
  900. );
  901. }
  902. $updateParentStatus = false;
  903. break;
  904. }
  905. }
  906. }
  907. if ($updateParentStatus) {
  908. // If all the children were completed:
  909. $parent->set_status('completed');
  910. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  911. // Force the status to "completed"
  912. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  913. $this->update_queue[$parent->get_id()] = 'completed';
  914. if ($debug) {
  915. error_log(
  916. 'Added parent #'.$parent->get_id().' "'.$parent->get_title()
  917. .'" to update queue status: completed '.
  918. print_r($this->update_queue, 1),
  919. 0
  920. );
  921. }
  922. // Recursive call.
  923. $this->autocomplete_parents($parent->get_id());
  924. }
  925. }
  926. } else {
  927. if ($debug) {
  928. error_log("Parent #$parent_id does not exists");
  929. }
  930. }
  931. } else {
  932. if ($debug) {
  933. error_log("#$item is an item that doesn't have parents");
  934. }
  935. }
  936. }
  937. /**
  938. * Auto saves the current results into the database for the whole learnpath
  939. * @todo: Add save operations for the learnpath itself.
  940. */
  941. public function autosave()
  942. {
  943. if ($this->debug > 0) {
  944. error_log('New LP - In learnpath::autosave()', 0);
  945. }
  946. }
  947. /**
  948. * Closes the current resource
  949. *
  950. * Stops the timer
  951. * Saves into the database if required
  952. * Clears the current resource data from this object
  953. * @return boolean True on success, false on failure
  954. */
  955. public function close()
  956. {
  957. if ($this->debug > 0) {
  958. error_log('New LP - In learnpath::close()', 0);
  959. }
  960. if (empty($this->lp_id)) {
  961. $this->error = 'Trying to close this learnpath but no ID is set';
  962. return false;
  963. }
  964. $this->current_time_stop = time();
  965. $this->ordered_items = array();
  966. $this->index = 0;
  967. unset($this->lp_id);
  968. //unset other stuff
  969. return true;
  970. }
  971. /**
  972. * Static admin function allowing removal of a learnpath
  973. * @param array $courseInfo
  974. * @param integer Learnpath ID
  975. * @param string Whether to delete data or keep it (default: 'keep', others: 'remove')
  976. * @return boolean True on success, false on failure (might change that to return number of elements deleted)
  977. */
  978. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  979. {
  980. $course_id = api_get_course_int_id();
  981. if (!empty($courseInfo)) {
  982. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  983. }
  984. // TODO: Implement a way of getting this to work when the current object is not set.
  985. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  986. // If an ID is specifically given and the current LP is not the same, prevent delete.
  987. if (!empty($id) && ($id != $this->lp_id)) {
  988. return false;
  989. }
  990. $lp = Database::get_course_table(TABLE_LP_MAIN);
  991. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  992. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  993. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  994. // Delete lp item id.
  995. foreach ($this->items as $id => $dummy) {
  996. $sql
  997. = "DELETE FROM $lp_item_view
  998. WHERE c_id = $course_id AND lp_item_id = '".$id."'";
  999. Database::query($sql);
  1000. }
  1001. // Proposed by Christophe (nickname: clefevre)
  1002. $sql = "DELETE FROM $lp_item WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  1003. Database::query($sql);
  1004. $sql = "DELETE FROM $lp_view WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  1005. Database::query($sql);
  1006. self::toggle_publish($this->lp_id, 'i');
  1007. if ($this->type == 2 || $this->type == 3) {
  1008. // This is a scorm learning path, delete the files as well.
  1009. $sql
  1010. = "SELECT path FROM $lp
  1011. WHERE c_id = ".$course_id." AND id = ".$this->lp_id;
  1012. $res = Database::query($sql);
  1013. if (Database::num_rows($res) > 0) {
  1014. $row = Database::fetch_array($res);
  1015. $path = $row['path'];
  1016. $sql
  1017. = "SELECT id FROM $lp
  1018. WHERE c_id = ".$course_id." AND path = '$path' AND id != ".$this->lp_id;
  1019. $res = Database::query($sql);
  1020. if (Database::num_rows($res) > 0) {
  1021. // Another learning path uses this directory, so don't delete it.
  1022. if ($this->debug > 2) {
  1023. error_log('New LP - In learnpath::delete(), found other LP using path '.$path
  1024. .', keeping directory', 0);
  1025. }
  1026. } else {
  1027. // No other LP uses that directory, delete it.
  1028. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1029. $course_scorm_dir = api_get_path(SYS_COURSE_PATH)
  1030. .$course_rel_dir; // The absolute system path for this course.
  1031. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) and !empty ($course_scorm_dir)) {
  1032. if ($this->debug > 2) {
  1033. error_log('New LP - In learnpath::delete(), found SCORM, deleting directory: '
  1034. .$course_scorm_dir.$path, 0);
  1035. }
  1036. // Proposed by Christophe (clefevre).
  1037. if (strcmp(substr($path, -2), "/.") == 0) {
  1038. $path = substr($path, 0, -1); // Remove "." at the end.
  1039. }
  1040. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1041. rmdirr($course_scorm_dir.$path);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1047. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1048. // Delete tools
  1049. $sql
  1050. = "DELETE FROM $tbl_tool
  1051. WHERE c_id = ".$course_id." AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1052. Database::query($sql);
  1053. $sql = "DELETE FROM $lp WHERE c_id = ".$course_id." AND id = ".$this->lp_id;
  1054. Database::query($sql);
  1055. // Updates the display order of all lps.
  1056. $this->update_display_order();
  1057. api_item_property_update(
  1058. api_get_course_info(),
  1059. TOOL_LEARNPATH,
  1060. $this->lp_id,
  1061. 'delete',
  1062. api_get_user_id()
  1063. );
  1064. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1065. api_get_course_id(),
  1066. 4,
  1067. $id,
  1068. api_get_session_id()
  1069. );
  1070. if ($link_info !== false) {
  1071. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1072. }
  1073. if (api_get_setting('search_enabled') == 'true') {
  1074. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1075. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1076. }
  1077. }
  1078. /**
  1079. * Removes all the children of one item - dangerous!
  1080. * @param integer $id Element ID of which children have to be removed
  1081. * @return integer Total number of children removed
  1082. */
  1083. public function delete_children_items($id)
  1084. {
  1085. $course_id = $this->course_info['real_id'];
  1086. if ($this->debug > 0) {
  1087. error_log('New LP - In learnpath::delete_children_items('.$id.')', 0);
  1088. }
  1089. $num = 0;
  1090. if (empty ($id) || $id != strval(intval($id))) {
  1091. return false;
  1092. }
  1093. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1094. $sql = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1095. $res = Database::query($sql);
  1096. while ($row = Database::fetch_array($res)) {
  1097. $num += $this->delete_children_items($row['id']);
  1098. $sql_del = "DELETE FROM $lp_item WHERE c_id = ".$course_id." AND id = ".$row['id'];
  1099. Database::query($sql_del);
  1100. $num++;
  1101. }
  1102. return $num;
  1103. }
  1104. /**
  1105. * Removes an item from the current learnpath
  1106. * @param integer $id Elem ID (0 if first)
  1107. * @param integer $remove Whether to remove the resource/data from the
  1108. * system or leave it (default: 'keep', others 'remove')
  1109. * @return integer Number of elements moved
  1110. * @todo implement resource removal
  1111. */
  1112. public function delete_item($id, $remove = 'keep')
  1113. {
  1114. $course_id = api_get_course_int_id();
  1115. if ($this->debug > 0) {
  1116. error_log('New LP - In learnpath::delete_item()', 0);
  1117. }
  1118. // TODO: Implement the resource removal.
  1119. if (empty ($id) || $id != strval(intval($id))) {
  1120. return false;
  1121. }
  1122. // First select item to get previous, next, and display order.
  1123. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1124. $sql_sel = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND id = $id";
  1125. $res_sel = Database::query($sql_sel);
  1126. if (Database::num_rows($res_sel) < 1) {
  1127. return false;
  1128. }
  1129. $row = Database::fetch_array($res_sel);
  1130. $previous = $row['previous_item_id'];
  1131. $next = $row['next_item_id'];
  1132. $display = $row['display_order'];
  1133. $parent = $row['parent_item_id'];
  1134. $lp = $row['lp_id'];
  1135. // Delete children items.
  1136. $num = $this->delete_children_items($id);
  1137. if ($this->debug > 2) {
  1138. error_log('New LP - learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1139. }
  1140. // Now delete the item.
  1141. $sql_del = "DELETE FROM $lp_item WHERE c_id = $course_id AND id = $id";
  1142. if ($this->debug > 2) {
  1143. error_log('New LP - Deleting item: '.$sql_del, 0);
  1144. }
  1145. Database::query($sql_del);
  1146. // Now update surrounding items.
  1147. $sql_upd
  1148. = "UPDATE $lp_item SET next_item_id = $next
  1149. WHERE c_id = ".$course_id." AND id = $previous";
  1150. Database::query($sql_upd);
  1151. $sql_upd
  1152. = "UPDATE $lp_item SET previous_item_id = $previous
  1153. WHERE c_id = ".$course_id." AND id = $next";
  1154. Database::query($sql_upd);
  1155. // Now update all following items with new display order.
  1156. $sql_all
  1157. = "UPDATE $lp_item SET display_order = display_order-1
  1158. WHERE c_id = ".$course_id
  1159. ." AND lp_id = $lp AND parent_item_id = $parent AND display_order > $display";
  1160. Database::query($sql_all);
  1161. //Removing prerequisites since the item will not longer exist
  1162. $sql_all = "UPDATE $lp_item SET prerequisite = '' WHERE c_id = ".$course_id." AND prerequisite = $id";
  1163. Database::query($sql_all);
  1164. // Remove from search engine if enabled.
  1165. if (api_get_setting('search_enabled') == 'true') {
  1166. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1167. $sql
  1168. = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
  1169. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1170. $res = Database::query($sql);
  1171. if (Database::num_rows($res) > 0) {
  1172. $row2 = Database::fetch_array($res);
  1173. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  1174. $di = new ChamiloIndexer();
  1175. $di->remove_document((int)$row2['search_did']);
  1176. }
  1177. $sql
  1178. = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d LIMIT 1';
  1179. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1180. Database::query($sql);
  1181. }
  1182. }
  1183. /**
  1184. * Updates an item's content in place
  1185. * @param integer $id Element ID
  1186. * @param integer $parent Parent item ID
  1187. * @param integer $previous Previous item ID
  1188. * @param string $title Item title
  1189. * @param string $description Item description
  1190. * @param string $prerequisites Prerequisites (optional)
  1191. * @param array $audio The array resulting of the $_FILES[mp3] element
  1192. * @param int $max_time_allowed
  1193. * @param string $url
  1194. * @return boolean True on success, false on error
  1195. */
  1196. public function edit_item(
  1197. $id,
  1198. $parent,
  1199. $previous,
  1200. $title,
  1201. $description,
  1202. $prerequisites = '0',
  1203. $audio = array(),
  1204. $max_time_allowed = 0,
  1205. $url = ''
  1206. ) {
  1207. $course_id = api_get_course_int_id();
  1208. $_course = api_get_course_info();
  1209. if ($this->debug > 0) {
  1210. error_log('New LP - In learnpath::edit_item()', 0);
  1211. }
  1212. if (empty ($max_time_allowed)) {
  1213. $max_time_allowed = 0;
  1214. }
  1215. if (empty ($id) || ($id != strval(intval($id))) || empty ($title)) {
  1216. return false;
  1217. }
  1218. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1219. $sql_select = "SELECT * FROM ".$tbl_lp_item." WHERE c_id = ".$course_id." AND id = ".$id;
  1220. $res_select = Database::query($sql_select);
  1221. $row_select = Database::fetch_array($res_select);
  1222. $audio_update_sql = '';
  1223. if (is_array($audio) && !empty ($audio['tmp_name']) && $audio['error'] === 0) {
  1224. // Create the audio folder if it does not exist yet.
  1225. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1226. if (!is_dir($filepath.'audio')) {
  1227. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1228. $audio_id = add_document(
  1229. $_course,
  1230. '/audio',
  1231. 'folder',
  1232. 0,
  1233. 'audio'
  1234. );
  1235. api_item_property_update(
  1236. $_course,
  1237. TOOL_DOCUMENT,
  1238. $audio_id,
  1239. 'FolderCreated',
  1240. api_get_user_id(),
  1241. null,
  1242. null,
  1243. null,
  1244. null,
  1245. api_get_session_id()
  1246. );
  1247. api_item_property_update(
  1248. $_course,
  1249. TOOL_DOCUMENT,
  1250. $audio_id,
  1251. 'invisible',
  1252. api_get_user_id(),
  1253. null,
  1254. null,
  1255. null,
  1256. null,
  1257. api_get_session_id()
  1258. );
  1259. }
  1260. // Upload file in documents.
  1261. $pi = pathinfo($audio['name']);
  1262. if ($pi['extension'] == 'mp3') {
  1263. $c_det = api_get_course_info($this->cc);
  1264. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1265. $path = handle_uploaded_document(
  1266. $c_det,
  1267. $audio,
  1268. $bp,
  1269. '/audio',
  1270. api_get_user_id(),
  1271. 0,
  1272. null,
  1273. 0,
  1274. 'rename',
  1275. false,
  1276. 0
  1277. );
  1278. $path = substr($path, 7);
  1279. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1280. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1281. }
  1282. }
  1283. $same_parent = ($row_select['parent_item_id'] == $parent) ? true : false;
  1284. $same_previous = ($row_select['previous_item_id'] == $previous) ? true : false;
  1285. // TODO: htmlspecialchars to be checked for encoding related problems.
  1286. if ($same_parent && $same_previous) {
  1287. // Only update title and description.
  1288. $sql = "UPDATE ".$tbl_lp_item."
  1289. SET title = '".Database::escape_string($title)."',
  1290. prerequisite = '".$prerequisites."',
  1291. description = '".Database::escape_string($description)."'
  1292. ".$audio_update_sql.",
  1293. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1294. WHERE c_id = ".$course_id." AND id = ".$id;
  1295. Database::query($sql);
  1296. } else {
  1297. $old_parent = $row_select['parent_item_id'];
  1298. $old_previous = $row_select['previous_item_id'];
  1299. $old_next = $row_select['next_item_id'];
  1300. $old_order = $row_select['display_order'];
  1301. $old_prerequisite = $row_select['prerequisite'];
  1302. $old_max_time_allowed = $row_select['max_time_allowed'];
  1303. /* BEGIN -- virtually remove the current item id */
  1304. /* for the next and previous item it is like the current item doesn't exist anymore */
  1305. if ($old_previous != 0) {
  1306. // Next
  1307. $sql = "UPDATE ".$tbl_lp_item."
  1308. SET next_item_id = ".$old_next."
  1309. WHERE c_id = ".$course_id." AND id = ".$old_previous;
  1310. Database::query($sql);
  1311. }
  1312. if ($old_next != 0) {
  1313. // Previous
  1314. $sql = "UPDATE ".$tbl_lp_item."
  1315. SET previous_item_id = ".$old_previous."
  1316. WHERE c_id = ".$course_id." AND id = ".$old_next;
  1317. Database::query($sql);
  1318. }
  1319. // display_order - 1 for every item with a display_order bigger then the display_order of the current item.
  1320. $sql = "UPDATE ".$tbl_lp_item."
  1321. SET display_order = display_order - 1
  1322. WHERE
  1323. c_id = ".$course_id." AND
  1324. display_order > ".$old_order." AND
  1325. lp_id = ".$this->lp_id." AND
  1326. parent_item_id = ".$old_parent;
  1327. Database::query($sql);
  1328. /* END -- virtually remove the current item id */
  1329. /* BEGIN -- update the current item id to his new location */
  1330. if ($previous == 0) {
  1331. // Select the data of the item that should come after the current item.
  1332. $sql
  1333. = "SELECT id, display_order
  1334. FROM ".$tbl_lp_item."
  1335. WHERE
  1336. c_id = ".$course_id." AND
  1337. lp_id = ".$this->lp_id." AND
  1338. parent_item_id = ".$parent." AND
  1339. previous_item_id = ".$previous;
  1340. $res_select_old = Database::query($sql);
  1341. $row_select_old = Database::fetch_array($res_select_old);
  1342. // If the new parent didn't have children before.
  1343. if (Database::num_rows($res_select_old) == 0) {
  1344. $new_next = 0;
  1345. $new_order = 1;
  1346. } else {
  1347. $new_next = $row_select_old['id'];
  1348. $new_order = $row_select_old['display_order'];
  1349. }
  1350. } else {
  1351. // Select the data of the item that should come before the current item.
  1352. $sql
  1353. = "SELECT next_item_id, display_order
  1354. FROM ".$tbl_lp_item."
  1355. WHERE c_id = ".$course_id." AND id = ".$previous;
  1356. $res_select_old = Database::query($sql);
  1357. $row_select_old = Database::fetch_array($res_select_old);
  1358. $new_next = $row_select_old['next_item_id'];
  1359. $new_order = $row_select_old['display_order'] + 1;
  1360. }
  1361. // TODO: htmlspecialchars to be checked for encoding related problems.
  1362. // Update the current item with the new data.
  1363. $sql = "UPDATE ".$tbl_lp_item."
  1364. SET
  1365. title = '".Database::escape_string($title)."',
  1366. description = '".Database::escape_string($description)."',
  1367. parent_item_id = ".$parent.",
  1368. previous_item_id = ".$previous.",
  1369. next_item_id = ".$new_next.",
  1370. display_order = ".$new_order."
  1371. ".$audio_update_sql."
  1372. WHERE c_id = ".$course_id." AND id = ".$id;
  1373. Database::query($sql);
  1374. if ($previous != 0) {
  1375. // Update the previous item's next_item_id.
  1376. $sql = "UPDATE ".$tbl_lp_item."
  1377. SET next_item_id = ".$id."
  1378. WHERE c_id = ".$course_id." AND id = ".$previous;
  1379. Database::query($sql);
  1380. }
  1381. if ($new_next != 0) {
  1382. // Update the next item's previous_item_id.
  1383. $sql = "UPDATE ".$tbl_lp_item."
  1384. SET previous_item_id = ".$id."
  1385. WHERE c_id = ".$course_id." AND id = ".$new_next;
  1386. Database::query($sql);
  1387. }
  1388. if ($old_prerequisite != $prerequisites) {
  1389. $sql = "UPDATE ".$tbl_lp_item."
  1390. SET prerequisite = '".$prerequisites."'
  1391. WHERE c_id = ".$course_id." AND id = ".$id;
  1392. Database::query($sql);
  1393. }
  1394. if ($old_max_time_allowed != $max_time_allowed) {
  1395. // update max time allowed
  1396. $sql = "UPDATE ".$tbl_lp_item."
  1397. SET max_time_allowed = ".$max_time_allowed."
  1398. WHERE c_id = ".$course_id." AND id = ".$id;
  1399. Database::query($sql);
  1400. }
  1401. // Update all the items with the same or a bigger display_order than the current item.
  1402. $sql = "UPDATE ".$tbl_lp_item."
  1403. SET display_order = display_order + 1
  1404. WHERE
  1405. c_id = ".$course_id." AND
  1406. lp_id = ".$this->get_id()." AND
  1407. id <> ".$id." AND
  1408. parent_item_id = ".$parent." AND
  1409. display_order >= ".$new_order;
  1410. Database::query($sql);
  1411. }
  1412. if ($row_select['item_type'] == 'link') {
  1413. $link = new Link();
  1414. $linkId = $row_select['path'];
  1415. $link->updateLink($linkId, $url);
  1416. }
  1417. }
  1418. /**
  1419. * Updates an item's prereq in place
  1420. * @param integer $id Element ID
  1421. * @param string $prerequisite_id Prerequisite Element ID
  1422. * @param int $mastery_score Prerequisite min score
  1423. * @param int $max_score Prerequisite max score
  1424. *
  1425. * @return boolean True on success, false on error
  1426. */
  1427. public function edit_item_prereq($id, $prerequisite_id, $mastery_score = 0, $max_score = 100)
  1428. {
  1429. $course_id = api_get_course_int_id();
  1430. if ($this->debug > 0) {
  1431. error_log('New LP - In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','
  1432. .$max_score.')', 0);
  1433. }
  1434. if (empty($id) || ($id != strval(intval($id))) || empty ($prerequisite_id)) {
  1435. return false;
  1436. }
  1437. $prerequisite_id = intval($prerequisite_id);
  1438. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1439. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1440. $mastery_score = 0;
  1441. }
  1442. if (!is_numeric($max_score) || $max_score < 0) {
  1443. $max_score = 100;
  1444. }
  1445. /*if ($mastery_score > $max_score) {
  1446. $max_score = $mastery_score;
  1447. }*/
  1448. if (!is_numeric($prerequisite_id)) {
  1449. $prerequisite_id = 'NULL';
  1450. }
  1451. $mastery_score = floatval($mastery_score);
  1452. $max_score = floatval($max_score);
  1453. $sql
  1454. = " UPDATE $tbl_lp_item
  1455. SET
  1456. prerequisite = $prerequisite_id ,
  1457. prerequisite_min_score = $mastery_score ,
  1458. prerequisite_max_score = $max_score
  1459. WHERE c_id = $course_id AND id = $id";
  1460. Database::query($sql);
  1461. if ($prerequisite_id != 'NULL' && $prerequisite_id != '') {
  1462. // Will this be enough to ensure unicity?
  1463. /*$sql = " UPDATE $tbl_lp_item
  1464. SET mastery_score = $mastery_score
  1465. WHERE c_id = $course_id AND ref = '$prerequisite_id'";
  1466. Database::query($sql);*/
  1467. }
  1468. // TODO: Update the item object (can be ignored for now because refreshed).
  1469. return true;
  1470. }
  1471. /**
  1472. * Static admin function exporting a learnpath into a zip file
  1473. * @param string Export type (scorm, zip, cd)
  1474. * @param string Course code
  1475. * @param integer Learnpath ID
  1476. * @param string Zip file name
  1477. * @return string Zip file path (or false on error)
  1478. */
  1479. public function export_lp($type, $course, $id, $zipname)
  1480. {
  1481. if (empty($type) || empty($course) || empty($id) || empty($zipname)) {
  1482. return false;
  1483. }
  1484. $url = '';
  1485. switch ($type) {
  1486. case 'scorm':
  1487. break;
  1488. case 'zip':
  1489. break;
  1490. case 'cdrom':
  1491. break;
  1492. }
  1493. return $url;
  1494. }
  1495. /**
  1496. * Gets all the chapters belonging to the same parent as the item/chapter given
  1497. * Can also be called as abstract method
  1498. * @param integer $id Item ID
  1499. * @return array A list of all the "brother items" (or an empty array on failure)
  1500. */
  1501. public function getSiblingDirectories($id)
  1502. {
  1503. $course_id = api_get_course_int_id();
  1504. if ($this->debug > 0) {
  1505. error_log('New LP - In learnpath::getSiblingDirectories()', 0);
  1506. }
  1507. if (empty($id) || $id != strval(intval($id))) {
  1508. return array();
  1509. }
  1510. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1511. $sql_parent
  1512. = "SELECT * FROM $lp_item
  1513. WHERE c_id = ".$course_id." AND id = $id AND item_type='dir'";
  1514. $res_parent = Database::query($sql_parent);
  1515. if (Database::num_rows($res_parent) > 0) {
  1516. $row_parent = Database::fetch_array($res_parent);
  1517. $parent = $row_parent['parent_item_id'];
  1518. $sql
  1519. = "SELECT * FROM $lp_item
  1520. WHERE
  1521. c_id = ".$course_id." AND
  1522. parent_item_id = $parent AND
  1523. id = $id AND
  1524. item_type='dir'
  1525. ORDER BY display_order";
  1526. $res_bros = Database::query($sql);
  1527. $list = array();
  1528. while ($row_bro = Database::fetch_array($res_bros)) {
  1529. $list[] = $row_bro;
  1530. }
  1531. return $list;
  1532. }
  1533. return array();
  1534. }
  1535. /**
  1536. * Gets all the items belonging to the same parent as the item given
  1537. * Can also be called as abstract method
  1538. * @param integer $id Item ID
  1539. * @return array A list of all the "brother items" (or an empty array on failure)
  1540. */
  1541. public function get_brother_items($id)
  1542. {
  1543. $course_id = api_get_course_int_id();
  1544. if ($this->debug > 0) {
  1545. error_log('New LP - In learnpath::get_brother_items('.$id.')', 0);
  1546. }
  1547. if (empty ($id) || $id != strval(intval($id))) {
  1548. return array();
  1549. }
  1550. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1551. $sql_parent = "SELECT * FROM $lp_item WHERE c_id = $course_id AND id = $id";
  1552. $res_parent = Database::query($sql_parent);
  1553. if (Database::num_rows($res_parent) > 0) {
  1554. $row_parent = Database::fetch_array($res_parent);
  1555. $parent = $row_parent['parent_item_id'];
  1556. $sql_bros = "SELECT * FROM $lp_item WHERE c_id = ".$course_id." AND parent_item_id = $parent
  1557. ORDER BY display_order";
  1558. $res_bros = Database::query($sql_bros);
  1559. $list = [];
  1560. while ($row_bro = Database::fetch_array($res_bros)) {
  1561. $list[] = $row_bro;
  1562. }
  1563. return $list;
  1564. }
  1565. return [];
  1566. }
  1567. /**
  1568. * Get the specific prefix index terms of this learning path
  1569. * @param string $prefix
  1570. * @return array Array of terms
  1571. */
  1572. public function get_common_index_terms_by_prefix($prefix)
  1573. {
  1574. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1575. $terms = get_specific_field_values_list_by_prefix(
  1576. $prefix,
  1577. $this->cc,
  1578. TOOL_LEARNPATH,
  1579. $this->lp_id
  1580. );
  1581. $prefix_terms = array();
  1582. if (!empty($terms)) {
  1583. foreach ($terms as $term) {
  1584. $prefix_terms[] = $term['value'];
  1585. }
  1586. }
  1587. return $prefix_terms;
  1588. }
  1589. /**
  1590. * Gets the number of items currently completed
  1591. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1592. * @return integer The number of items currently completed
  1593. */
  1594. public function get_complete_items_count($failedStatusException = false)
  1595. {
  1596. if ($this->debug > 0) {
  1597. error_log('New LP - In learnpath::get_complete_items_count()', 0);
  1598. }
  1599. $i = 0;
  1600. $completedStatusList = array(
  1601. 'completed',
  1602. 'passed',
  1603. 'succeeded',
  1604. 'browsed'
  1605. );
  1606. if (!$failedStatusException) {
  1607. $completedStatusList[] = 'failed';
  1608. }
  1609. foreach ($this->items as $id => $dummy) {
  1610. // Trying failed and browsed considered "progressed" as well.
  1611. if ($this->items[$id]->status_is($completedStatusList) && $this->items[$id]->get_type() != 'dir'
  1612. ) {
  1613. $i++;
  1614. }
  1615. }
  1616. return $i;
  1617. }
  1618. /**
  1619. * Gets the current item ID
  1620. * @return integer The current learnpath item id
  1621. */
  1622. public function get_current_item_id()
  1623. {
  1624. $current = 0;
  1625. if ($this->debug > 0) {
  1626. error_log('New LP - In learnpath::get_current_item_id()', 0);
  1627. }
  1628. if (!empty($this->current)) {
  1629. $current = $this->current;
  1630. }
  1631. if ($this->debug > 2) {
  1632. error_log('New LP - In learnpath::get_current_item_id() - Returning '.$current, 0);
  1633. }
  1634. return $current;
  1635. }
  1636. /**
  1637. * Force to get the first learnpath item id
  1638. * @return integer The current learnpath item id
  1639. */
  1640. public function get_first_item_id()
  1641. {
  1642. $current = 0;
  1643. if (is_array($this->ordered_items)) {
  1644. $current = $this->ordered_items[0];
  1645. }
  1646. return $current;
  1647. }
  1648. /**
  1649. * Gets the total number of items available for viewing in this SCORM
  1650. * @return integer The total number of items
  1651. */
  1652. public function get_total_items_count()
  1653. {
  1654. if ($this->debug > 0) {
  1655. error_log('New LP - In learnpath::get_total_items_count()', 0);
  1656. }
  1657. return count($this->items);
  1658. }
  1659. /**
  1660. * Gets the total number of items available for viewing in this SCORM but without chapters
  1661. * @return integer The total no-chapters number of items
  1662. */
  1663. public function getTotalItemsCountWithoutDirs()
  1664. {
  1665. if ($this->debug > 0) {
  1666. error_log('New LP - In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1667. }
  1668. $total = 0;
  1669. $typeListNotToCount = self::getChapterTypes();
  1670. foreach ($this->items as $temp2) {
  1671. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1672. $total++;
  1673. }
  1674. }
  1675. return $total;
  1676. }
  1677. /**
  1678. * Gets the first element URL.
  1679. * @return string URL to load into the viewer
  1680. */
  1681. public function first()
  1682. {
  1683. if ($this->debug > 0) {
  1684. error_log('New LP - In learnpath::first()', 0);
  1685. error_log('$this->last_item_seen '.$this->last_item_seen);
  1686. }
  1687. // Test if the last_item_seen exists and is not a dir.
  1688. if (count($this->ordered_items) == 0) {
  1689. $this->index = 0;
  1690. }
  1691. if ($this->debug > 0) {
  1692. if (isset($this->items[$this->last_item_seen])) {
  1693. $status = $this->items[$this->last_item_seen]->get_status();
  1694. }
  1695. error_log('status '.$status);
  1696. }
  1697. if (!empty($this->last_item_seen) && !empty($this->items[$this->last_item_seen])
  1698. && $this->items[$this->last_item_seen]->get_type() != 'dir'
  1699. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1700. //&& !$this->items[$this->last_item_seen]->is_done()
  1701. ) {
  1702. if ($this->debug > 2) {
  1703. error_log('New LP - In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '
  1704. .$this->items[$this->last_item_seen]->get_type(), 0);
  1705. }
  1706. $index = -1;
  1707. foreach ($this->ordered_items as $myindex => $item_id) {
  1708. if ($item_id == $this->last_item_seen) {
  1709. $index = $myindex;
  1710. break;
  1711. }
  1712. }
  1713. if ($index == -1) {
  1714. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1715. if ($this->debug > 2) {
  1716. error_log('New LP - Last item ('.$this->last_item_seen
  1717. .') was found in items but not in ordered_items, panic!', 0);
  1718. }
  1719. return false;
  1720. } else {
  1721. $this->last = $this->last_item_seen;
  1722. $this->current = $this->last_item_seen;
  1723. $this->index = $index;
  1724. }
  1725. } else {
  1726. if ($this->debug > 2) {
  1727. error_log('New LP - In learnpath::first() - No last item seen', 0);
  1728. }
  1729. $index = 0;
  1730. // Loop through all ordered items and stop at the first item that is
  1731. // not a directory *and* that has not been completed yet.
  1732. while (!empty($this->ordered_items[$index]) AND
  1733. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') AND
  1734. (
  1735. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' OR
  1736. $this->items[$this->ordered_items[$index]]->is_done() === true
  1737. ) AND $index < $this->max_ordered_items) {
  1738. $index++;
  1739. }
  1740. $this->last = $this->current;
  1741. // current is
  1742. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1743. $this->index = $index;
  1744. if ($this->debug > 2) {
  1745. error_log('$index '.$index);
  1746. }
  1747. if ($this->debug > 2) {
  1748. error_log('New LP - In learnpath::first() - No last item seen. New last = '.$this->last.'('
  1749. .$this->ordered_items[$index].')', 0);
  1750. }
  1751. }
  1752. if ($this->debug > 2) {
  1753. error_log('New LP - In learnpath::first() - First item is '.$this->get_current_item_id());
  1754. }
  1755. }
  1756. /**
  1757. * Gets the information about an item in a format usable as JavaScript to update
  1758. * the JS API by just printing this content into the <head> section of the message frame
  1759. * @param int $item_id
  1760. * @return string
  1761. */
  1762. public function get_js_info($item_id = 0)
  1763. {
  1764. if ($this->debug > 0) {
  1765. error_log('New LP - In learnpath::get_js_info('.$item_id.')', 0);
  1766. }
  1767. $info = '';
  1768. $item_id = intval($item_id);
  1769. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1770. //if item is defined, return values from DB
  1771. $oItem = $this->items[$item_id];
  1772. $info .= '<script language="javascript">';
  1773. $info .= "top.set_score(".$oItem->get_score().");\n";
  1774. $info .= "top.set_max(".$oItem->get_max().");\n";
  1775. $info .= "top.set_min(".$oItem->get_min().");\n";
  1776. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1777. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1778. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1779. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1780. $info .= "top.set_flag_synchronized();";
  1781. $info .= '</script>';
  1782. if ($this->debug > 2) {
  1783. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1784. }
  1785. return $info;
  1786. } else {
  1787. // If item_id is empty, just update to default SCORM data.
  1788. $info .= '<script language="javascript">';
  1789. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1790. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1791. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1792. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1793. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1794. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1795. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1796. $info .= "top.set_flag_synchronized();";
  1797. $info .= '</script>';
  1798. if ($this->debug > 2) {
  1799. error_log('New LP - in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1800. }
  1801. return $info;
  1802. }
  1803. }
  1804. /**
  1805. * Gets the js library from the database
  1806. * @return string The name of the javascript library to be used
  1807. */
  1808. public function get_js_lib()
  1809. {
  1810. $lib = '';
  1811. if (!empty ($this->js_lib)) {
  1812. $lib = $this->js_lib;
  1813. }
  1814. return $lib;
  1815. }
  1816. /**
  1817. * Gets the learnpath database ID
  1818. * @return integer Learnpath ID in the lp table
  1819. */
  1820. public function get_id()
  1821. {
  1822. if (!empty ($this->lp_id)) {
  1823. return $this->lp_id;
  1824. } else {
  1825. return 0;
  1826. }
  1827. }
  1828. /**
  1829. * Gets the last element URL.
  1830. * @return string URL to load into the viewer
  1831. */
  1832. public function get_last()
  1833. {
  1834. if ($this->debug > 0) {
  1835. error_log('New LP - In learnpath::get_last()', 0);
  1836. }
  1837. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1838. if (count($this->ordered_items) > 0) {
  1839. $this->index = count($this->ordered_items) - 1;
  1840. return $this->ordered_items[$this->index];
  1841. }
  1842. return false;
  1843. }
  1844. /**
  1845. * Gets the navigation bar for the learnpath display screen
  1846. * @return string The HTML string to use as a navigation bar
  1847. */
  1848. public function get_navigation_bar($idBar = null, $display = null)
  1849. {
  1850. if ($this->debug > 0) {
  1851. error_log('New LP - In learnpath::get_navigation_bar()', 0);
  1852. }
  1853. if (empty($idBar)) {
  1854. $idBar = 'control-top';
  1855. }
  1856. $navbar = null;
  1857. $lp_id = $this->lp_id;
  1858. $mycurrentitemid = $this->get_current_item_id();
  1859. $reportingText = get_lang('Reporting');
  1860. $previousText = get_lang('ScormPrevious');
  1861. $nextText = get_lang('ScormNext');
  1862. $fullScreenText = get_lang('ScormExitFullScreen');
  1863. if ($this->mode == 'fullscreen') {
  1864. $navbar
  1865. = '
  1866. <span id="'.$idBar.'" class="buttons">
  1867. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id
  1868. .'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1869. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1870. </a>
  1871. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item('.$mycurrentitemid
  1872. .',\'previous\');return false;" title="'.$previousText.'">
  1873. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1874. </a>
  1875. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item('.$mycurrentitemid
  1876. .',\'next\');return false;" title="'.$nextText.'">
  1877. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1878. </a>
  1879. <a class="icon-toolbar" id="view-embedded" href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'
  1880. .$fullScreenText.'">
  1881. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1882. </a>
  1883. </span>';
  1884. } else {
  1885. $navbar
  1886. = '
  1887. <span id="'.$idBar.'" class="buttons text-right">
  1888. <a class="icon-toolbar" href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lp_id
  1889. .'" onclick="window.parent.API.save_asset();return true;" target="content_name" title="'.$reportingText.'" id="stats_link">
  1890. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1891. </a>
  1892. <a class="icon-toolbar" id="scorm-previous" href="#" onclick="switch_item('.$mycurrentitemid
  1893. .',\'previous\');return false;" title="'.$previousText.'">
  1894. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1895. </a>
  1896. <a class="icon-toolbar" id="scorm-next" href="#" onclick="switch_item('.$mycurrentitemid
  1897. .',\'next\');return false;" title="'.$nextText.'">
  1898. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1899. </a>
  1900. </span>';
  1901. }
  1902. return $navbar;
  1903. }
  1904. /**
  1905. * Gets the next resource in queue (url).
  1906. * @return string URL to load into the viewer
  1907. */
  1908. public function get_next_index()
  1909. {
  1910. if ($this->debug > 0) {
  1911. error_log('New LP - In learnpath::get_next_index()', 0);
  1912. }
  1913. // TODO
  1914. $index = $this->index;
  1915. $index++;
  1916. if ($this->debug > 2) {
  1917. error_log('New LP - Now looking at ordered_items['.($index).'] - type is '
  1918. .$this->items[$this->ordered_items[$index]]->type, 0);
  1919. }
  1920. while (!empty ($this->ordered_items[$index]) AND ($this->items[$this->ordered_items[$index]]->get_type()
  1921. == 'dir') AND $index < $this->max_ordered_items) {
  1922. $index++;
  1923. if ($index == $this->max_ordered_items) {
  1924. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1925. return $this->index;
  1926. } else {
  1927. return $index;
  1928. }
  1929. }
  1930. }
  1931. if (empty ($this->ordered_items[$index])) {
  1932. return $this->index;
  1933. }
  1934. if ($this->debug > 2) {
  1935. error_log('New LP - index is now '.$index, 0);
  1936. }
  1937. return $index;
  1938. }
  1939. /**
  1940. * Gets item_id for the next element
  1941. * @return integer Next item (DB) ID
  1942. */
  1943. public function get_next_item_id()
  1944. {
  1945. if ($this->debug > 0) {
  1946. error_log('New LP - In learnpath::get_next_item_id()', 0);
  1947. }
  1948. $new_index = $this->get_next_index();
  1949. if (!empty ($new_index)) {
  1950. if (isset ($this->ordered_items[$new_index])) {
  1951. if ($this->debug > 2) {
  1952. error_log('New LP - In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index],
  1953. 0);
  1954. }
  1955. return $this->ordered_items[$new_index];
  1956. }
  1957. }
  1958. if ($this->debug > 2) {
  1959. error_log('New LP - In learnpath::get_next_index() - Problem - Returning 0', 0);
  1960. }
  1961. return 0;
  1962. }
  1963. /**
  1964. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...)
  1965. *
  1966. * Generally, the package provided is in the form of a zip file, so the function
  1967. * has been written to test a zip file. If not a zip, the function will return the
  1968. * default return value: ''
  1969. * @param string the path to the file
  1970. * @param string the original name of the file
  1971. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1972. */
  1973. public static function get_package_type($file_path, $file_name)
  1974. {
  1975. // Get name of the zip file without the extension.
  1976. $file_info = pathinfo($file_name);
  1977. $filename = $file_info['basename']; // Name including extension.
  1978. $extension = $file_info['extension']; // Extension only.
  1979. if (!empty($_POST['ppt2lp'])
  1980. && !in_array(strtolower($extension), array(
  1981. 'dll',
  1982. 'exe'
  1983. ))
  1984. ) {
  1985. return 'oogie';
  1986. }
  1987. if (!empty($_POST['woogie'])
  1988. && !in_array(strtolower($extension), array(
  1989. 'dll',
  1990. 'exe'
  1991. ))
  1992. ) {
  1993. return 'woogie';
  1994. }
  1995. $zipFile = new PclZip($file_path);
  1996. // Check the zip content (real size and file extension).
  1997. $zipContentArray = $zipFile->listContent();
  1998. $package_type = '';
  1999. $at_root = false;
  2000. $manifest = '';
  2001. $aicc_match_crs = 0;
  2002. $aicc_match_au = 0;
  2003. $aicc_match_des = 0;
  2004. $aicc_match_cst = 0;
  2005. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2006. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2007. foreach ($zipContentArray as $thisContent) {
  2008. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2009. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2010. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2011. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2012. $package_type = 'scorm';
  2013. break; // Exit the foreach loop.
  2014. } elseif (
  2015. preg_match('/aicc\//i', $thisContent['filename'])
  2016. || in_array(strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2017. array('crs', 'au', 'des', 'cst'))
  2018. ) {
  2019. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2020. switch ($ext) {
  2021. case 'crs':
  2022. $aicc_match_crs = 1;
  2023. break;
  2024. case 'au':
  2025. $aicc_match_au = 1;
  2026. break;
  2027. case 'des':
  2028. $aicc_match_des = 1;
  2029. break;
  2030. case 'cst':
  2031. $aicc_match_cst = 1;
  2032. break;
  2033. default:
  2034. break;
  2035. }
  2036. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2037. } else {
  2038. $package_type = '';
  2039. }
  2040. }
  2041. }
  2042. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2043. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2044. $package_type = 'aicc';
  2045. }
  2046. return $package_type;
  2047. }
  2048. /**
  2049. * Gets the previous resource in queue (url). Also initialises time values for this viewing
  2050. * @return string URL to load into the viewer
  2051. */
  2052. public function get_previous_index()
  2053. {
  2054. if ($this->debug > 0) {
  2055. error_log('New LP - In learnpath::get_previous_index()', 0);
  2056. }
  2057. $index = $this->index;
  2058. if (isset ($this->ordered_items[$index - 1])) {
  2059. $index--;
  2060. while (isset($this->ordered_items[$index])
  2061. && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')) {
  2062. $index--;
  2063. if ($index < 0) {
  2064. return $this->index;
  2065. }
  2066. }
  2067. } else {
  2068. if ($this->debug > 2) {
  2069. error_log('New LP - get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2070. }
  2071. // There is no previous item.
  2072. }
  2073. return $index;
  2074. }
  2075. /**
  2076. * Gets item_id for the next element
  2077. * @return integer Previous item (DB) ID
  2078. */
  2079. public function get_previous_item_id()
  2080. {
  2081. if ($this->debug > 0) {
  2082. error_log('New LP - In learnpath::get_previous_item_id()', 0);
  2083. }
  2084. $new_index = $this->get_previous_index();
  2085. return $this->ordered_items[$new_index];
  2086. }
  2087. /**
  2088. * Gets the progress value from the progress_db attribute
  2089. * @return integer Current progress value
  2090. * @deprecated This method does not seem to be used as of 20170514
  2091. */
  2092. public function get_progress()
  2093. {
  2094. if ($this->debug > 0) {
  2095. error_log('New LP - In learnpath::get_progress()', 0);
  2096. }
  2097. if (!empty ($this->progress_db)) {
  2098. return $this->progress_db;
  2099. }
  2100. return 0;
  2101. }
  2102. /**
  2103. * Returns the HTML necessary to print a mediaplayer block inside a page
  2104. * @return string The mediaplayer HTML
  2105. */
  2106. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2107. {
  2108. $course_id = api_get_course_int_id();
  2109. $_course = api_get_course_info();
  2110. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2111. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2112. // Getting all the information about the item.
  2113. $sql
  2114. = "SELECT * FROM $tbl_lp_item as lp
  2115. INNER JOIN $tbl_lp_item_view as lp_view
  2116. ON (lp.id = lp_view.lp_item_id AND lp.c_id = lp_view.c_id)
  2117. WHERE
  2118. lp.id = '$lpItemId' AND
  2119. lp.c_id = $course_id AND
  2120. lp_view.c_id = $course_id";
  2121. $result = Database::query($sql);
  2122. $row = Database::fetch_assoc($result);
  2123. $output = '';
  2124. if (!empty ($row['audio'])) {
  2125. $list = $_SESSION['oLP']->get_toc();
  2126. $type_quiz = false;
  2127. foreach ($list as $toc) {
  2128. if ($toc['id'] == $_SESSION['oLP']->current && ($toc['type'] == 'quiz')) {
  2129. $type_quiz = true;
  2130. }
  2131. }
  2132. if ($type_quiz) {
  2133. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2134. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2135. } else {
  2136. $autostart_audio = $autostart;
  2137. }
  2138. } else {
  2139. $autostart_audio = 'true';
  2140. }
  2141. $courseInfo = api_get_course_info();
  2142. $audio = $row['audio'];
  2143. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2144. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2145. if (!file_exists($file)) {
  2146. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2147. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2148. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'
  2149. .api_get_cidreq();
  2150. }
  2151. $player = Display::getMediaPlayer(
  2152. $file,
  2153. array(
  2154. 'id' => 'lp_audio_media_player',
  2155. 'url' => $url,
  2156. 'autoplay' => $autostart_audio,
  2157. 'width' => '100%'
  2158. )
  2159. );
  2160. // The mp3 player.
  2161. $output = '<div id="container">';
  2162. $output .= $player;
  2163. $output .= '</div>';
  2164. }
  2165. return $output;
  2166. }
  2167. /**
  2168. * @param int $studentId
  2169. * @param int $prerequisite
  2170. * @param array $courseInfo
  2171. * @param int $sessionId
  2172. *
  2173. * @return bool
  2174. */
  2175. public static function isBlockedByPrerequisite(
  2176. $studentId,
  2177. $prerequisite,
  2178. $courseInfo,
  2179. $sessionId
  2180. ) {
  2181. $isBlocked = false;
  2182. if (!empty($prerequisite)) {
  2183. $progress = self::getProgress(
  2184. $prerequisite,
  2185. $studentId,
  2186. $courseInfo['real_id'],
  2187. $sessionId
  2188. );
  2189. if ($progress < 100) {
  2190. $isBlocked = true;
  2191. }
  2192. }
  2193. return $isBlocked;
  2194. }
  2195. /**
  2196. * Checks if the learning path is visible for student after the progress
  2197. * of its prerequisite is completed, considering the time availability and
  2198. * the LP visibility.
  2199. * @param int $lp_id
  2200. * @param int $student_id
  2201. * @param string Course code (optional)
  2202. * @param int $sessionId
  2203. * @return bool
  2204. */
  2205. public static function is_lp_visible_for_student(
  2206. $lp_id,
  2207. $student_id,
  2208. $courseCode = null,
  2209. $sessionId = 0
  2210. ) {
  2211. $courseInfo = api_get_course_info($courseCode);
  2212. $lp_id = (int)$lp_id;
  2213. $sessionId = (int)$sessionId;
  2214. if (empty($sessionId)) {
  2215. $sessionId = api_get_session_id();
  2216. }
  2217. if (empty($courseInfo)) {
  2218. return false;
  2219. }
  2220. $itemInfo = api_get_item_property_info(
  2221. $courseInfo['real_id'],
  2222. TOOL_LEARNPATH,
  2223. $lp_id,
  2224. $sessionId
  2225. );
  2226. // If the item was deleted.
  2227. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2228. return false;
  2229. }
  2230. // @todo remove this query and load the row info as a parameter
  2231. $tbl_learnpath = Database::get_course_table(TABLE_LP_MAIN);
  2232. // Get current prerequisite
  2233. $sql
  2234. = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2235. FROM $tbl_learnpath
  2236. WHERE c_id = ".$courseInfo['real_id']." AND id = $lp_id";
  2237. $rs = Database::query($sql);
  2238. $now = time();
  2239. if (Database::num_rows($rs) > 0) {
  2240. $row = Database::fetch_array($rs, 'ASSOC');
  2241. $prerequisite = $row['prerequisite'];
  2242. $is_visible = true;
  2243. $isBlocked = self::isBlockedByPrerequisite(
  2244. $student_id,
  2245. $prerequisite,
  2246. $courseInfo,
  2247. $sessionId
  2248. );
  2249. if ($isBlocked) {
  2250. $is_visible = false;
  2251. }
  2252. // Also check the time availability of the LP
  2253. if ($is_visible) {
  2254. // Adding visibility restrictions
  2255. if (!empty($row['publicated_on'])) {
  2256. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2257. $is_visible = false;
  2258. }
  2259. }
  2260. // Blocking empty start times see BT#2800
  2261. global $_custom;
  2262. if (isset($_custom['lps_hidden_when_no_start_date']) && $_custom['lps_hidden_when_no_start_date']
  2263. ) {
  2264. if (empty($row['publicated_on'])) {
  2265. $is_visible = false;
  2266. }
  2267. }
  2268. if (!empty($row['expired_on'])) {
  2269. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2270. $is_visible = false;
  2271. }
  2272. }
  2273. }
  2274. // Check if the subscription users/group to a LP is ON
  2275. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1) {
  2276. // Try group
  2277. $is_visible = false;
  2278. // Checking only the user visibility
  2279. $userVisibility = api_get_item_visibility(
  2280. $courseInfo,
  2281. 'learnpath',
  2282. $row['id'],
  2283. $sessionId,
  2284. $student_id,
  2285. 'LearnpathSubscription'
  2286. );
  2287. if ($userVisibility == 1) {
  2288. $is_visible = true;
  2289. } else {
  2290. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2291. if (!empty($userGroups)) {
  2292. foreach ($userGroups as $groupInfo) {
  2293. $groupId = $groupInfo['iid'];
  2294. $userVisibility = api_get_item_visibility(
  2295. $courseInfo,
  2296. 'learnpath',
  2297. $row['id'],
  2298. $sessionId,
  2299. null,
  2300. 'LearnpathSubscription',
  2301. $groupId
  2302. );
  2303. if ($userVisibility == 1) {
  2304. $is_visible = true;
  2305. break;
  2306. }
  2307. }
  2308. }
  2309. }
  2310. }
  2311. return $is_visible;
  2312. }
  2313. return false;
  2314. }
  2315. /**
  2316. * @param int $lpId
  2317. * @param int $userId
  2318. * @param int $courseId
  2319. * @param int $sessionId
  2320. * @return int
  2321. */
  2322. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2323. {
  2324. $lpId = intval($lpId);
  2325. $userId = intval($userId);
  2326. $courseId = intval($courseId);
  2327. $sessionId = intval($sessionId);
  2328. $progress = 0;
  2329. $sessionCondition = api_get_session_condition($sessionId);
  2330. $table = Database::get_course_table(TABLE_LP_VIEW);
  2331. $sql
  2332. = "SELECT * FROM $table
  2333. WHERE
  2334. c_id = ".$courseId." AND
  2335. lp_id = $lpId AND
  2336. user_id = $userId $sessionCondition";
  2337. $res = Database::query($sql);
  2338. if (Database::num_rows($res) > 0) {
  2339. $row = Database:: fetch_array($res);
  2340. $progress = $row['progress'];
  2341. }
  2342. return (int)$progress;
  2343. }
  2344. /**
  2345. * Displays a progress bar
  2346. * completed so far.
  2347. * @param integer $percentage Progress value to display
  2348. * @param string $text_add Text to display near the progress value
  2349. * @return string HTML string containing the progress bar
  2350. */
  2351. public static function get_progress_bar($percentage = -1, $text_add = '')
  2352. {
  2353. $text = $percentage.$text_add;
  2354. $output
  2355. = '<div class="progress">
  2356. <div id="progress_bar_value" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="'
  2357. .$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2358. '.$text.'
  2359. </div>
  2360. </div>';
  2361. return $output;
  2362. }
  2363. /**
  2364. * @param string $mode can be '%' or 'abs'
  2365. * otherwise this value will be used $this->progress_bar_mode
  2366. * @return string
  2367. */
  2368. public function getProgressBar($mode = null)
  2369. {
  2370. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2371. return self::get_progress_bar($percentage, $text_add);
  2372. }
  2373. /**
  2374. * Gets the progress bar info to display inside the progress bar.
  2375. * Also used by scorm_api.php
  2376. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2377. * we display a number of completed elements per total elements
  2378. * @param integer $add Additional steps to fake as completed
  2379. * @return list array Percentage or number and symbol (% or /xx)
  2380. */
  2381. public function get_progress_bar_text($mode = '', $add = 0)
  2382. {
  2383. if ($this->debug > 0) {
  2384. error_log('New LP - In learnpath::get_progress_bar_text()', 0);
  2385. }
  2386. if (empty($mode)) {
  2387. $mode = $this->progress_bar_mode;
  2388. }
  2389. $total_items = $this->getTotalItemsCountWithoutDirs();
  2390. if ($this->debug > 2) {
  2391. error_log('New LP - Total items available in this learnpath: '.$total_items, 0);
  2392. }
  2393. $completeItems = $this->get_complete_items_count();
  2394. if ($this->debug > 2) {
  2395. error_log('New LP - Items completed so far: '.$completeItems, 0);
  2396. }
  2397. if ($add != 0) {
  2398. $completeItems += $add;
  2399. if ($this->debug > 2) {
  2400. error_log('New LP - Items completed so far (+modifier): '.$completeItems, 0);
  2401. }
  2402. }
  2403. $text = '';
  2404. if ($completeItems > $total_items) {
  2405. $completeItems = $total_items;
  2406. }
  2407. $percentage = 0;
  2408. if ($mode == '%') {
  2409. if ($total_items > 0) {
  2410. $percentage = ((float)$completeItems / (float)$total_items) * 100;
  2411. } else {
  2412. $percentage = 0;
  2413. }
  2414. $percentage = number_format($percentage, 0);
  2415. $text = '%';
  2416. } elseif ($mode == 'abs') {
  2417. $percentage = $completeItems;
  2418. $text = '/'.$total_items;
  2419. }
  2420. return array(
  2421. $percentage,
  2422. $text
  2423. );
  2424. }
  2425. /**
  2426. * Gets the progress bar mode
  2427. * @return string The progress bar mode attribute
  2428. */
  2429. public function get_progress_bar_mode()
  2430. {
  2431. if ($this->debug > 0) {
  2432. error_log('New LP - In learnpath::get_progress_bar_mode()', 0);
  2433. }
  2434. if (!empty ($this->progress_bar_mode)) {
  2435. return $this->progress_bar_mode;
  2436. } else {
  2437. return '%';
  2438. }
  2439. }
  2440. /**
  2441. * Gets the learnpath proximity (remote or local)
  2442. * @return string Learnpath proximity
  2443. */
  2444. public function get_proximity()
  2445. {
  2446. if ($this->debug > 0) {
  2447. error_log('New LP - In learnpath::get_proximity()', 0);
  2448. }
  2449. if (!empty ($this->proximity)) {
  2450. return $this->proximity;
  2451. } else {
  2452. return '';
  2453. }
  2454. }
  2455. /**
  2456. * Gets the learnpath theme (remote or local)
  2457. * @return string Learnpath theme
  2458. */
  2459. public function get_theme()
  2460. {
  2461. if ($this->debug > 0) {
  2462. error_log('New LP - In learnpath::get_theme()', 0);
  2463. }
  2464. if (!empty ($this->theme)) {
  2465. return $this->theme;
  2466. } else {
  2467. return '';
  2468. }
  2469. }
  2470. /**
  2471. * Gets the learnpath session id
  2472. * @return int
  2473. */
  2474. public function get_lp_session_id()
  2475. {
  2476. if ($this->debug > 0) {
  2477. error_log('New LP - In learnpath::get_lp_session_id()', 0);
  2478. }
  2479. if (!empty ($this->lp_session_id)) {
  2480. return (int)$this->lp_session_id;
  2481. } else {
  2482. return 0;
  2483. }
  2484. }
  2485. /**
  2486. * Gets the learnpath image
  2487. * @return string Web URL of the LP image
  2488. */
  2489. public function get_preview_image()
  2490. {
  2491. if ($this->debug > 0) {
  2492. error_log('New LP - In learnpath::get_preview_image()', 0);
  2493. }
  2494. if (!empty($this->preview_image)) {
  2495. return $this->preview_image;
  2496. } else {
  2497. return '';
  2498. }
  2499. }
  2500. /**
  2501. * @param string $size
  2502. * @param string $path_type
  2503. * @return bool|string
  2504. */
  2505. public function get_preview_image_path($size = null, $path_type = 'web')
  2506. {
  2507. $preview_image = $this->get_preview_image();
  2508. if (isset($preview_image) && !empty($preview_image)) {
  2509. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2510. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2511. if (isset($size)) {
  2512. $info = pathinfo($preview_image);
  2513. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2514. if (file_exists($image_sys_path.$image_custom_size)) {
  2515. if ($path_type == 'web') {
  2516. return $image_path.$image_custom_size;
  2517. } else {
  2518. return $image_sys_path.$image_custom_size;
  2519. }
  2520. }
  2521. } else {
  2522. if ($path_type == 'web') {
  2523. return $image_path.$preview_image;
  2524. } else {
  2525. return $image_sys_path.$preview_image;
  2526. }
  2527. }
  2528. }
  2529. return false;
  2530. }
  2531. /**
  2532. * Gets the learnpath author
  2533. * @return string LP's author
  2534. */
  2535. public function get_author()
  2536. {
  2537. if ($this->debug > 0) {
  2538. error_log('New LP - In learnpath::get_author()', 0);
  2539. }
  2540. if (!empty ($this->author)) {
  2541. return $this->author;
  2542. } else {
  2543. return '';
  2544. }
  2545. }
  2546. /**
  2547. * Gets the learnpath author
  2548. * @return string LP's author
  2549. */
  2550. public function get_hide_toc_frame()
  2551. {
  2552. if ($this->debug > 0) {
  2553. error_log('New LP - In learnpath::get_author()', 0);
  2554. }
  2555. if (!empty ($this->hide_toc_frame)) {
  2556. return $this->hide_toc_frame;
  2557. } else {
  2558. return '';
  2559. }
  2560. }
  2561. /**
  2562. * Generate a new prerequisites string for a given item. If this item was a sco and
  2563. * its prerequisites were strings (instead of IDs), then transform those strings into
  2564. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2565. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2566. * same rule as the scorm_export() method
  2567. * @param integer Item ID
  2568. * @return string Prerequisites string ready for the export as SCORM
  2569. */
  2570. public function get_scorm_prereq_string($item_id)
  2571. {
  2572. if ($this->debug > 0) {
  2573. error_log('New LP - In learnpath::get_scorm_prereq_string()', 0);
  2574. }
  2575. if (!is_object($this->items[$item_id])) {
  2576. return false;
  2577. }
  2578. /** @var learnpathItem $oItem */
  2579. $oItem = $this->items[$item_id];
  2580. $prereq = $oItem->get_prereq_string();
  2581. if (empty($prereq)) {
  2582. return '';
  2583. }
  2584. if (preg_match('/^\d+$/', $prereq) && is_object($this->items[$prereq])) {
  2585. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2586. // then simply return it (with the ITEM_ prefix).
  2587. //return 'ITEM_' . $prereq;
  2588. return $this->items[$prereq]->ref;
  2589. } else {
  2590. if (isset($this->refs_list[$prereq])) {
  2591. // It's a simple string item from which the ID can be found in the refs list,
  2592. // so we can transform it directly to an ID for export.
  2593. return $this->items[$this->refs_list[$prereq]]->ref;
  2594. } else {
  2595. if (isset($this->refs_list['ITEM_'.$prereq])) {
  2596. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2597. } else {
  2598. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2599. // and replace them, one by one, by the internal IDs (chamilo db)
  2600. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2601. // by a space as well.
  2602. $find = array(
  2603. '&',
  2604. '|',
  2605. '~',
  2606. '=',
  2607. '<>',
  2608. '{',
  2609. '}',
  2610. '*',
  2611. '(',
  2612. ')'
  2613. );
  2614. $replace = array(
  2615. ' ',
  2616. ' ',
  2617. ' ',
  2618. ' ',
  2619. ' ',
  2620. ' ',
  2621. ' ',
  2622. ' ',
  2623. ' ',
  2624. ' '
  2625. );
  2626. $prereq_mod = str_replace($find, $replace, $prereq);
  2627. $ids = explode(' ', $prereq_mod);
  2628. foreach ($ids as $id) {
  2629. $id = trim($id);
  2630. if (isset ($this->refs_list[$id])) {
  2631. $prereq = preg_replace('/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2632. 'ITEM_'.$this->refs_list[$id], $prereq);
  2633. }
  2634. }
  2635. return $prereq;
  2636. }
  2637. }
  2638. }
  2639. }
  2640. /**
  2641. * Returns the XML DOM document's node
  2642. * @param resource Reference to a list of objects to search for the given ITEM_*
  2643. * @param string The identifier to look for
  2644. * @return mixed The reference to the element found with that identifier. False if not found
  2645. */
  2646. public function get_scorm_xml_node(& $children, $id)
  2647. {
  2648. for ($i = 0; $i < $children->length; $i++) {
  2649. $item_temp = $children->item($i);
  2650. if ($item_temp->nodeName == 'item') {
  2651. if ($item_temp->getAttribute('identifier') == $id) {
  2652. return $item_temp;
  2653. }
  2654. }
  2655. $subchildren = $item_temp->childNodes;
  2656. if ($subchildren && $subchildren->length > 0) {
  2657. $val = $this->get_scorm_xml_node($subchildren, $id);
  2658. if (is_object($val)) {
  2659. return $val;
  2660. }
  2661. }
  2662. }
  2663. return false;
  2664. }
  2665. /**
  2666. * Gets the status list for all LP's items
  2667. * @return array Array of [index] => [item ID => current status]
  2668. */
  2669. public function get_items_status_list()
  2670. {
  2671. if ($this->debug > 0) {
  2672. error_log('New LP - In learnpath::get_items_status_list()', 0);
  2673. }
  2674. $list = array();
  2675. foreach ($this->ordered_items as $item_id) {
  2676. $list[] = array(
  2677. $item_id => $this->items[$item_id]->get_status()
  2678. );
  2679. }
  2680. return $list;
  2681. }
  2682. /**
  2683. * Return the number of interactions for the given learnpath Item View ID.
  2684. * This method can be used as static.
  2685. * @param integer Item View ID
  2686. * @param integer course id
  2687. * @return integer Number of interactions
  2688. */
  2689. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2690. {
  2691. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2692. $lp_iv_id = intval($lp_iv_id);
  2693. $course_id = intval($course_id);
  2694. $sql
  2695. = "SELECT count(*) FROM $table
  2696. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2697. $res = Database::query($sql);
  2698. $num = 0;
  2699. if (Database::num_rows($res)) {
  2700. $row = Database::fetch_array($res);
  2701. $num = $row[0];
  2702. }
  2703. return $num;
  2704. }
  2705. /**
  2706. * Return the interactions as an array for the given lp_iv_id.
  2707. * This method can be used as static.
  2708. * @param integer Learnpath Item View ID
  2709. * @return array
  2710. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2711. */
  2712. public static function get_iv_interactions_array($lp_iv_id)
  2713. {
  2714. $course_id = api_get_course_int_id();
  2715. $list = array();
  2716. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2717. if (empty($lp_iv_id)) {
  2718. return array();
  2719. }
  2720. $sql
  2721. = "SELECT * FROM $table
  2722. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2723. ORDER BY order_id ASC";
  2724. $res = Database::query($sql);
  2725. $num = Database::num_rows($res);
  2726. if ($num > 0) {
  2727. $list[] = array(
  2728. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2729. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2730. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2731. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2732. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2733. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2734. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2735. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES)
  2736. );
  2737. while ($row = Database::fetch_array($res)) {
  2738. $list[] = array(
  2739. 'order_id' => ($row['order_id'] + 1),
  2740. 'id' => urldecode($row['interaction_id']),
  2741. //urldecode because they often have %2F or stuff like that
  2742. 'type' => $row['interaction_type'],
  2743. 'time' => $row['completion_time'],
  2744. //'correct_responses' => $row['correct_responses'],
  2745. 'correct_responses' => '',
  2746. // Hide correct responses from students.
  2747. 'student_response' => $row['student_response'],
  2748. 'result' => $row['result'],
  2749. 'latency' => $row['latency']
  2750. );
  2751. }
  2752. }
  2753. return $list;
  2754. }
  2755. /**
  2756. * Return the number of objectives for the given learnpath Item View ID.
  2757. * This method can be used as static.
  2758. * @param integer Item View ID
  2759. * @return integer Number of objectives
  2760. */
  2761. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2762. {
  2763. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2764. $course_id = intval($course_id);
  2765. $lp_iv_id = intval($lp_iv_id);
  2766. $sql
  2767. = "SELECT count(*) FROM $table
  2768. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2769. //@todo seems that this always returns 0
  2770. $res = Database::query($sql);
  2771. $num = 0;
  2772. if (Database::num_rows($res)) {
  2773. $row = Database::fetch_array($res);
  2774. $num = $row[0];
  2775. }
  2776. return $num;
  2777. }
  2778. /**
  2779. * Return the objectives as an array for the given lp_iv_id.
  2780. * This method can be used as static.
  2781. * @param integer Learnpath Item View ID
  2782. * @return array
  2783. * @todo Translate labels
  2784. */
  2785. public static function get_iv_objectives_array($lp_iv_id = 0)
  2786. {
  2787. $course_id = api_get_course_int_id();
  2788. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2789. $sql
  2790. = "SELECT * FROM $table
  2791. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id
  2792. ORDER BY order_id ASC";
  2793. $res = Database::query($sql);
  2794. $num = Database::num_rows($res);
  2795. $list = array();
  2796. if ($num > 0) {
  2797. $list[] = array(
  2798. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2799. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2800. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2801. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2802. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2803. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES)
  2804. );
  2805. while ($row = Database::fetch_array($res)) {
  2806. $list[] = array(
  2807. 'order_id' => ($row['order_id'] + 1),
  2808. 'objective_id' => urldecode($row['objective_id']),
  2809. // urldecode() because they often have %2F or stuff like that.
  2810. 'score_raw' => $row['score_raw'],
  2811. 'score_max' => $row['score_max'],
  2812. 'score_min' => $row['score_min'],
  2813. 'status' => $row['status']
  2814. );
  2815. }
  2816. }
  2817. return $list;
  2818. }
  2819. /**
  2820. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2821. * used by get_html_toc() to be ready to display
  2822. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2823. */
  2824. public function get_toc()
  2825. {
  2826. if ($this->debug > 0) {
  2827. error_log('learnpath::get_toc()', 0);
  2828. }
  2829. $toc = array();
  2830. foreach ($this->ordered_items as $item_id) {
  2831. if ($this->debug > 2) {
  2832. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2833. }
  2834. // TODO: Change this link generation and use new function instead.
  2835. $toc[] = array(
  2836. 'id' => $item_id,
  2837. 'title' => $this->items[$item_id]->get_title(),
  2838. 'status' => $this->items[$item_id]->get_status(),
  2839. 'level' => $this->items[$item_id]->get_level(),
  2840. 'type' => $this->items[$item_id]->get_type(),
  2841. 'description' => $this->items[$item_id]->get_description(),
  2842. 'path' => $this->items[$item_id]->get_path(),
  2843. 'parent' => $this->items[$item_id]->get_parent(),
  2844. );
  2845. }
  2846. if ($this->debug > 2) {
  2847. error_log('New LP - In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2848. }
  2849. return $toc;
  2850. }
  2851. /**
  2852. * Generate and return the table of contents for this learnpath. The JS
  2853. * table returned is used inside of scorm_api.php
  2854. * @return string A JS array vairiable construction
  2855. */
  2856. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2857. {
  2858. if ($this->debug > 0) {
  2859. error_log('New LP - In learnpath::get_items_details_as_js()', 0);
  2860. }
  2861. $toc = $varname.' = new Array();';
  2862. foreach ($this->ordered_items as $item_id) {
  2863. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2864. }
  2865. if ($this->debug > 2) {
  2866. error_log('New LP - In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2867. }
  2868. return $toc;
  2869. }
  2870. /**
  2871. * Gets the learning path type
  2872. * @param boolean Return the name? If false, return the ID. Default is false.
  2873. * @return mixed Type ID or name, depending on the parameter
  2874. */
  2875. public function get_type($get_name = false)
  2876. {
  2877. $res = false;
  2878. if ($this->debug > 0) {
  2879. error_log('New LP - In learnpath::get_type()', 0);
  2880. }
  2881. if (!empty ($this->type) && (!$get_name)) {
  2882. $res = $this->type;
  2883. }
  2884. if ($this->debug > 2) {
  2885. error_log('New LP - In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2886. }
  2887. return $res;
  2888. }
  2889. /**
  2890. * Gets the learning path type as static method
  2891. * @param boolean Return the name? If false, return the ID. Default is false.
  2892. * @return mixed Type ID or name, depending on the parameter
  2893. */
  2894. public static function get_type_static($lp_id = 0)
  2895. {
  2896. $course_id = api_get_course_int_id();
  2897. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2898. $lp_id = intval($lp_id);
  2899. $sql
  2900. = "SELECT lp_type FROM $tbl_lp
  2901. WHERE c_id = $course_id AND id = '".$lp_id."'";
  2902. $res = Database::query($sql);
  2903. if ($res === false) {
  2904. return null;
  2905. }
  2906. if (Database::num_rows($res) <= 0) {
  2907. return null;
  2908. }
  2909. $row = Database::fetch_array($res);
  2910. return $row['lp_type'];
  2911. }
  2912. /**
  2913. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2914. * This method can be used as abstract and is recursive
  2915. * @param integer Learnpath ID
  2916. * @param integer Parent ID of the items to look for
  2917. * @return mixed Ordered list of item IDs or false on error
  2918. */
  2919. public static function get_flat_ordered_items_list($lp, $parent = 0, $course_id = null)
  2920. {
  2921. if (empty($course_id)) {
  2922. $course_id = api_get_course_int_id();
  2923. } else {
  2924. $course_id = intval($course_id);
  2925. }
  2926. $list = array();
  2927. if (empty($lp)) {
  2928. return false;
  2929. }
  2930. $lp = intval($lp);
  2931. $parent = intval($parent);
  2932. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2933. $sql
  2934. = "SELECT id FROM $tbl_lp_item
  2935. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2936. ORDER BY display_order";
  2937. $res = Database::query($sql);
  2938. while ($row = Database::fetch_array($res)) {
  2939. $sublist = self::get_flat_ordered_items_list($lp, $row['id'], $course_id);
  2940. $list[] = $row['id'];
  2941. foreach ($sublist as $item) {
  2942. $list[] = $item;
  2943. }
  2944. }
  2945. return $list;
  2946. }
  2947. /**
  2948. * @return array
  2949. */
  2950. public static function getChapterTypes()
  2951. {
  2952. return array(
  2953. 'dir'
  2954. );
  2955. }
  2956. /**
  2957. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display
  2958. * @return string HTML TOC ready to display
  2959. */
  2960. public function getParentToc($tree)
  2961. {
  2962. if ($this->debug > 0) {
  2963. error_log('In learnpath::get_html_toc()', 0);
  2964. }
  2965. if (empty($tree)) {
  2966. $tree = $this->get_toc();
  2967. }
  2968. $dirTypes = self::getChapterTypes();
  2969. $myCurrentId = $this->get_current_item_id();
  2970. $listParent = [];
  2971. $listChildren = [];
  2972. $listNotParent = [];
  2973. $list = [];
  2974. foreach ($tree as $subtree) {
  2975. if (in_array($subtree['type'], $dirTypes)) {
  2976. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2977. $subtree['children'] = $listChildren;
  2978. if (!empty($subtree['children'])) {
  2979. foreach ($subtree['children'] as $subItem) {
  2980. if ($subItem['id'] == $this->current) {
  2981. $subtree['parent_current'] = 'in';
  2982. $subtree['current'] = 'on';
  2983. }
  2984. }
  2985. }
  2986. $listParent[] = $subtree;
  2987. }
  2988. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2989. $classStatus = [
  2990. 'not attempted' => 'scorm_not_attempted',
  2991. 'incomplete' => 'scorm_not_attempted',
  2992. 'failed' => 'scorm_failed',
  2993. 'completed' => 'scorm_completed',
  2994. 'passed' => 'scorm_completed',
  2995. 'succeeded' => 'scorm_completed',
  2996. 'browsed' => 'scorm_completed',
  2997. ];
  2998. if (isset($classStatus[$subtree['status']])) {
  2999. $cssStatus = $classStatus[$subtree['status']];
  3000. }
  3001. $title = Security::remove_XSS($subtree['title']);
  3002. unset($subtree['title']);
  3003. if (empty ($title)) {
  3004. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3005. }
  3006. $classStyle = null;
  3007. if ($subtree['id'] == $this->current) {
  3008. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3009. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3010. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3011. }
  3012. $subtree['title'] = $title;
  3013. $subtree['class'] = $cssStatus.' '.$classStyle;
  3014. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3015. $subtree['current_id'] = $myCurrentId;
  3016. $listNotParent[] = $subtree;
  3017. }
  3018. }
  3019. $list['are_parents'] = $listParent;
  3020. $list['not_parents'] = $listNotParent;
  3021. return $list;
  3022. }
  3023. /**
  3024. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display
  3025. * @return string HTML TOC ready to display
  3026. */
  3027. public function getChildrenToc($tree, $id, $parent = true)
  3028. {
  3029. if ($this->debug > 0) {
  3030. error_log('In learnpath::get_html_toc()', 0);
  3031. }
  3032. if (empty($tree)) {
  3033. $tree = $this->get_toc();
  3034. }
  3035. $dirTypes = self::getChapterTypes();
  3036. $mycurrentitemid = $this->get_current_item_id();
  3037. $list = [];
  3038. $classStatus = [
  3039. 'not attempted' => 'scorm_not_attempted',
  3040. 'incomplete' => 'scorm_not_attempted',
  3041. 'failed' => 'scorm_failed',
  3042. 'completed' => 'scorm_completed',
  3043. 'passed' => 'scorm_completed',
  3044. 'succeeded' => 'scorm_completed',
  3045. 'browsed' => 'scorm_completed',
  3046. ];
  3047. foreach ($tree as $subtree) {
  3048. $subtree['tree'] = null;
  3049. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3050. if ($subtree['id'] == $this->current) {
  3051. $subtree['current'] = 'active';
  3052. } else {
  3053. $subtree['current'] = null;
  3054. }
  3055. if (isset($classStatus[$subtree['status']])) {
  3056. $cssStatus = $classStatus[$subtree['status']];
  3057. }
  3058. $title = Security::remove_XSS($subtree['title']);
  3059. unset($subtree['title']);
  3060. if (empty ($title)) {
  3061. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3062. }
  3063. $classStyle = null;
  3064. if ($subtree['id'] == $this->current) {
  3065. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3066. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3067. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3068. }
  3069. if (in_array($subtree['type'], $dirTypes)) {
  3070. $subtree['title'] = stripslashes($title);
  3071. } else {
  3072. $subtree['title'] = $title;
  3073. $subtree['class'] = $cssStatus.' '.$classStyle;
  3074. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3075. $subtree['current_id'] = $mycurrentitemid;
  3076. }
  3077. $list[] = $subtree;
  3078. }
  3079. }
  3080. return $list;
  3081. }
  3082. /**
  3083. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display
  3084. * @return string HTML TOC ready to display
  3085. */
  3086. public function getListArrayToc($toc_list = null)
  3087. {
  3088. if ($this->debug > 0) {
  3089. error_log('In learnpath::get_html_toc()', 0);
  3090. }
  3091. if (empty($toc_list)) {
  3092. $toc_list = $this->get_toc();
  3093. }
  3094. // Temporary variables.
  3095. $mycurrentitemid = $this->get_current_item_id();
  3096. $list = [];
  3097. $arrayList = [];
  3098. $classStatus = [
  3099. 'not attempted' => 'scorm_not_attempted',
  3100. 'incomplete' => 'scorm_not_attempted',
  3101. 'failed' => 'scorm_failed',
  3102. 'completed' => 'scorm_completed',
  3103. 'passed' => 'scorm_completed',
  3104. 'succeeded' => 'scorm_completed',
  3105. 'browsed' => 'scorm_completed',
  3106. ];
  3107. foreach ($toc_list as $item) {
  3108. $list['id'] = $item['id'];
  3109. $list['status'] = $item['status'];
  3110. $cssStatus = null;
  3111. if (isset($classStatus[$item['status']])) {
  3112. $cssStatus = $classStatus[$item['status']];
  3113. }
  3114. $classStyle = ' ';
  3115. $dirTypes = self::getChapterTypes();
  3116. if (in_array($item['type'], $dirTypes)) {
  3117. $classStyle = 'scorm_item_section ';
  3118. }
  3119. if ($item['id'] == $this->current) {
  3120. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3121. } elseif (!in_array($item['type'], $dirTypes)) {
  3122. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3123. }
  3124. $title = $item['title'];
  3125. if (empty($title)) {
  3126. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $item['id']);
  3127. }
  3128. $title = Security::remove_XSS($item['title']);
  3129. if (empty($item['description'])) {
  3130. $list['description'] = $title;
  3131. } else {
  3132. $list['description'] = $item['description'];
  3133. }
  3134. $list['class'] = $classStyle.' '.$cssStatus;
  3135. $list['level'] = $item['level'];
  3136. $list['type'] = $item['type'];
  3137. if (in_array($item['type'], $dirTypes)) {
  3138. $list['css_level'] = 'level_'.$item['level'];
  3139. } else {
  3140. $list['css_level'] = 'level_'.$item['level']
  3141. .' scorm_type_'
  3142. .learnpath::format_scorm_type_item($item['type']);
  3143. }
  3144. if (in_array($item['type'], $dirTypes)) {
  3145. $list['title'] = stripslashes($title);
  3146. } else {
  3147. $list['title'] = stripslashes($title);
  3148. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3149. $list['current_id'] = $mycurrentitemid;
  3150. }
  3151. $arrayList[] = $list;
  3152. }
  3153. return $arrayList;
  3154. }
  3155. /**
  3156. * Returns an HTML-formatted string ready to display with teacher buttons
  3157. * in LP view menu
  3158. * @return string HTML TOC ready to display
  3159. */
  3160. public function get_teacher_toc_buttons()
  3161. {
  3162. $is_allowed_to_edit = api_is_allowed_to_edit(null, true, false, false);
  3163. $hide_teacher_icons_lp = api_get_configuration_value('hide_teacher_icons_lp');
  3164. $html = '';
  3165. if ($is_allowed_to_edit && $hide_teacher_icons_lp == false) {
  3166. $gradebook = '';
  3167. if (!empty($_GET['gradebook'])) {
  3168. $gradebook = Security::remove_XSS($_GET['gradebook']);
  3169. }
  3170. if ($this->get_lp_session_id() == api_get_session_id()) {
  3171. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3172. $html .= '<div class="btn-group">';
  3173. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()
  3174. ."&gradebook=$gradebook&action=build&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3175. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3176. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()
  3177. ."&action=add_item&type=step&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3178. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3179. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()
  3180. ."&gradebook=$gradebook&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3181. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3182. $html .= '</div>';
  3183. $html .= '</div>';
  3184. }
  3185. }
  3186. return $html;
  3187. }
  3188. /**
  3189. * Gets the learnpath maker name - generally the editor's name
  3190. * @return string Learnpath maker name
  3191. */
  3192. public function get_maker()
  3193. {
  3194. if ($this->debug > 0) {
  3195. error_log('New LP - In learnpath::get_maker()', 0);
  3196. }
  3197. if (!empty ($this->maker)) {
  3198. return $this->maker;
  3199. } else {
  3200. return '';
  3201. }
  3202. }
  3203. /**
  3204. * Gets the learnpath name/title
  3205. * @return string Learnpath name/title
  3206. */
  3207. public function get_name()
  3208. {
  3209. if ($this->debug > 0) {
  3210. error_log('New LP - In learnpath::get_name()', 0);
  3211. }
  3212. if (!empty ($this->name)) {
  3213. return $this->name;
  3214. } else {
  3215. return 'N/A';
  3216. }
  3217. }
  3218. /**
  3219. * Gets a link to the resource from the present location, depending on item ID.
  3220. * @param string $type Type of link expected
  3221. * @param integer $item_id Learnpath item ID
  3222. * @return string $provided_toc Link to the lp_item resource
  3223. */
  3224. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3225. {
  3226. $course_id = $this->get_course_int_id();
  3227. if ($this->debug > 0) {
  3228. error_log('New LP - In learnpath::get_link('.$type.','.$item_id.')', 0);
  3229. }
  3230. if (empty($item_id)) {
  3231. if ($this->debug > 2) {
  3232. error_log('New LP - In learnpath::get_link() - no item id given in learnpath::get_link(), using current: '
  3233. .$this->get_current_item_id(), 0);
  3234. }
  3235. $item_id = $this->get_current_item_id();
  3236. }
  3237. if (empty($item_id)) {
  3238. if ($this->debug > 2) {
  3239. error_log('New LP - In learnpath::get_link() - no current item id found in learnpath object', 0);
  3240. }
  3241. //still empty, this means there was no item_id given and we are not in an object context or
  3242. //the object property is empty, return empty link
  3243. $item_id = $this->first();
  3244. return '';
  3245. }
  3246. $file = '';
  3247. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3248. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3249. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3250. $item_id = intval($item_id);
  3251. $sql
  3252. = "SELECT
  3253. l.lp_type as ltype,
  3254. l.path as lpath,
  3255. li.item_type as litype,
  3256. li.path as lipath,
  3257. li.parameters as liparams
  3258. FROM $lp_table l
  3259. INNER JOIN $lp_item_table li
  3260. ON (li.lp_id = l.id AND l.c_id = $course_id AND li.c_id = $course_id )
  3261. WHERE li.id = $item_id ";
  3262. if ($this->debug > 2) {
  3263. error_log('New LP - In learnpath::get_link() - selecting item '.$sql, 0);
  3264. }
  3265. $res = Database::query($sql);
  3266. if (Database::num_rows($res) > 0) {
  3267. $row = Database::fetch_array($res);
  3268. $lp_type = $row['ltype'];
  3269. $lp_path = $row['lpath'];
  3270. $lp_item_type = $row['litype'];
  3271. $lp_item_path = $row['lipath'];
  3272. $lp_item_params = $row['liparams'];
  3273. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3274. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3275. }
  3276. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3277. if ($type == 'http') {
  3278. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path(); //web path
  3279. } else {
  3280. $course_path = $sys_course_path; //system path
  3281. }
  3282. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc), then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3283. if (in_array($lp_item_type,
  3284. array('quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication'))) {
  3285. $lp_type = 1;
  3286. }
  3287. if ($this->debug > 2) {
  3288. error_log('New LP - In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3289. error_log('New LP - In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3290. }
  3291. // Now go through the specific cases to get the end of the path
  3292. // @todo Use constants instead of int values.
  3293. switch ($lp_type) {
  3294. case 1 :
  3295. $file = self::rl_get_resource_link_for_learnpath(
  3296. $course_id,
  3297. $this->get_id(),
  3298. $item_id,
  3299. $this->get_view_id()
  3300. );
  3301. if ($this->debug > 0) {
  3302. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3303. }
  3304. switch ($lp_item_type) {
  3305. case 'dir':
  3306. $file = 'lp_content.php?type=dir';
  3307. break;
  3308. case 'link':
  3309. if (Link::is_youtube_link($file)) {
  3310. $src = Link::get_youtube_video_id($file);
  3311. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3312. } elseif (Link::isVimeoLink($file)) {
  3313. $src = Link::getVimeoLinkId($file);
  3314. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3315. } else {
  3316. // If the current site is HTTPS and the link is
  3317. // HTTP, browsers will refuse opening the link
  3318. $urlId = api_get_current_access_url_id();
  3319. $url = api_get_access_url($urlId, false);
  3320. $protocol = substr($url['url'], 0, 5);
  3321. if ($protocol === 'https') {
  3322. $linkProtocol = substr($file, 0, 5);
  3323. if ($linkProtocol === 'http:') {
  3324. //this is the special intervention case
  3325. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='
  3326. .urlencode($file);
  3327. }
  3328. }
  3329. }
  3330. break;
  3331. case 'quiz':
  3332. // Check how much attempts of a exercise exits in lp
  3333. $lp_item_id = $this->get_current_item_id();
  3334. $lp_view_id = $this->get_view_id();
  3335. $prevent_reinit = null;
  3336. if (isset($this->items[$this->current])) {
  3337. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3338. }
  3339. if (empty($provided_toc)) {
  3340. if ($this->debug > 0) {
  3341. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3342. }
  3343. $list = $this->get_toc();
  3344. } else {
  3345. if ($this->debug > 0) {
  3346. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3347. }
  3348. $list = $provided_toc;
  3349. }
  3350. $type_quiz = false;
  3351. foreach ($list as $toc) {
  3352. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3353. $type_quiz = true;
  3354. }
  3355. }
  3356. if ($type_quiz) {
  3357. $lp_item_id = intval($lp_item_id);
  3358. $lp_view_id = intval($lp_view_id);
  3359. $sql
  3360. = "SELECT count(*) FROM $lp_item_view_table
  3361. WHERE
  3362. c_id = $course_id AND
  3363. lp_item_id='".$lp_item_id."' AND
  3364. lp_view_id ='".$lp_view_id."' AND
  3365. status='completed'";
  3366. $result = Database::query($sql);
  3367. $row_count = Database:: fetch_row($result);
  3368. $count_item_view = (int)$row_count[0];
  3369. $not_multiple_attempt = 0;
  3370. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3371. $not_multiple_attempt = 1;
  3372. }
  3373. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3374. }
  3375. break;
  3376. }
  3377. $tmp_array = explode('/', $file);
  3378. $document_name = $tmp_array[count($tmp_array) - 1];
  3379. if (strpos($document_name, '_DELETED_')) {
  3380. $file = 'blank.php?error=document_deleted';
  3381. }
  3382. break;
  3383. case 2 :
  3384. if ($this->debug > 2) {
  3385. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3386. }
  3387. if ($lp_item_type != 'dir') {
  3388. // Quite complex here:
  3389. // We want to make sure 'http://' (and similar) links can
  3390. // be loaded as is (withouth the Chamilo path in front) but
  3391. // some contents use this form: resource.htm?resource=http://blablabla
  3392. // which means we have to find a protocol at the path's start, otherwise
  3393. // it should not be considered as an external URL.
  3394. //if ($this->prerequisites_match($item_id)) {
  3395. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3396. if ($this->debug > 2) {
  3397. error_log('New LP - In learnpath::get_link() '.__LINE__
  3398. .' - Found match for protocol in '.$lp_item_path, 0);
  3399. }
  3400. // Distant url, return as is.
  3401. $file = $lp_item_path;
  3402. } else {
  3403. if ($this->debug > 2) {
  3404. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '
  3405. .$lp_item_path, 0);
  3406. }
  3407. // Prevent getting untranslatable urls.
  3408. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3409. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3410. // Prepare the path.
  3411. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3412. // TODO: Fix this for urls with protocol header.
  3413. $file = str_replace('//', '/', $file);
  3414. $file = str_replace(':/', '://', $file);
  3415. if (substr($lp_path, -1) == '/') {
  3416. $lp_path = substr($lp_path, 0, -1);
  3417. }
  3418. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3419. // if file not found.
  3420. $decoded = html_entity_decode($lp_item_path);
  3421. list ($decoded) = explode('?', $decoded);
  3422. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3423. $file = self::rl_get_resource_link_for_learnpath(
  3424. $course_id,
  3425. $this->get_id(),
  3426. $item_id,
  3427. $this->get_view_id()
  3428. );
  3429. if (empty($file)) {
  3430. $file = 'blank.php?error=document_not_found';
  3431. } else {
  3432. $tmp_array = explode('/', $file);
  3433. $document_name = $tmp_array[count($tmp_array) - 1];
  3434. if (strpos($document_name, '_DELETED_')) {
  3435. $file = 'blank.php?error=document_deleted';
  3436. } else {
  3437. $file = 'blank.php?error=document_not_found';
  3438. }
  3439. }
  3440. } else {
  3441. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3442. }
  3443. }
  3444. }
  3445. // We want to use parameters if they were defined in the imsmanifest
  3446. if (strpos($file, 'blank.php') === false) {
  3447. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3448. }
  3449. } else {
  3450. $file = 'lp_content.php?type=dir';
  3451. }
  3452. break;
  3453. case 3 :
  3454. if ($this->debug > 2) {
  3455. error_log('New LP - In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3456. }
  3457. // Formatting AICC HACP append URL.
  3458. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='
  3459. .urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3460. if (!empty($lp_item_params)) {
  3461. $aicc_append .= $lp_item_params.'&';
  3462. }
  3463. if ($lp_item_type != 'dir') {
  3464. // Quite complex here:
  3465. // We want to make sure 'http://' (and similar) links can
  3466. // be loaded as is (withouth the Chamilo path in front) but
  3467. // some contents use this form: resource.htm?resource=http://blablabla
  3468. // which means we have to find a protocol at the path's start, otherwise
  3469. // it should not be considered as an external URL.
  3470. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3471. if ($this->debug > 2) {
  3472. error_log('New LP - In learnpath::get_link() '.__LINE__
  3473. .' - Found match for protocol in '.$lp_item_path, 0);
  3474. }
  3475. // Distant url, return as is.
  3476. $file = $lp_item_path;
  3477. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3478. /*
  3479. if (stristr($file,'<servername>') !== false) {
  3480. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3481. }
  3482. */
  3483. if (stripos($file, '<servername>') !== false) {
  3484. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3485. $web_course_path = str_replace('https://', '',
  3486. str_replace('http://', '', $course_path));
  3487. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3488. }
  3489. //
  3490. $file .= $aicc_append;
  3491. } else {
  3492. if ($this->debug > 2) {
  3493. error_log('New LP - In learnpath::get_link() '.__LINE__.' - No starting protocol in '
  3494. .$lp_item_path, 0);
  3495. }
  3496. // Prevent getting untranslatable urls.
  3497. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3498. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3499. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3500. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3501. // TODO: Fix this for urls with protocol header.
  3502. $file = str_replace('//', '/', $file);
  3503. $file = str_replace(':/', '://', $file);
  3504. $file .= $aicc_append;
  3505. }
  3506. } else {
  3507. $file = 'lp_content.php?type=dir';
  3508. }
  3509. break;
  3510. case 4 :
  3511. break;
  3512. default:
  3513. break;
  3514. }
  3515. // Replace &amp; by & because &amp; will break URL with params
  3516. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3517. }
  3518. if ($this->debug > 2) {
  3519. error_log('New LP - In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3520. }
  3521. return $file;
  3522. }
  3523. /**
  3524. * Gets the latest usable view or generate a new one
  3525. * @param integer Optional attempt number. If none given, takes the highest from the lp_view table
  3526. * @return integer DB lp_view id
  3527. */
  3528. public function get_view($attempt_num = 0)
  3529. {
  3530. if ($this->debug > 0) {
  3531. error_log('New LP - In learnpath::get_view()', 0);
  3532. }
  3533. $search = '';
  3534. // Use $attempt_num to enable multi-views management (disabled so far).
  3535. if ($attempt_num != 0 AND intval(strval($attempt_num)) == $attempt_num) {
  3536. $search = 'AND view_count = '.$attempt_num;
  3537. }
  3538. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3539. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3540. $course_id = api_get_course_int_id();
  3541. $sessionId = api_get_session_id();
  3542. $sql
  3543. = "SELECT id, view_count FROM $lp_view_table
  3544. WHERE
  3545. c_id = ".$course_id." AND
  3546. lp_id = ".$this->get_id()." AND
  3547. user_id = ".$this->get_user_id()." AND
  3548. session_id = $sessionId
  3549. $search
  3550. ORDER BY view_count DESC";
  3551. $res = Database::query($sql);
  3552. if (Database::num_rows($res) > 0) {
  3553. $row = Database::fetch_array($res);
  3554. $this->lp_view_id = $row['id'];
  3555. } else {
  3556. if (!api_is_invitee()) {
  3557. // There is no database record, create one.
  3558. $sql
  3559. = "INSERT INTO $lp_view_table (c_id, lp_id,user_id, view_count, session_id) VALUES
  3560. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3561. Database::query($sql);
  3562. $id = Database::insert_id();
  3563. $this->lp_view_id = $id;
  3564. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3565. Database::query($sql);
  3566. }
  3567. }
  3568. return $this->lp_view_id;
  3569. }
  3570. /**
  3571. * Gets the current view id
  3572. * @return integer View ID (from lp_view)
  3573. */
  3574. public function get_view_id()
  3575. {
  3576. if ($this->debug > 0) {
  3577. error_log('New LP - In learnpath::get_view_id()', 0);
  3578. }
  3579. if (!empty ($this->lp_view_id)) {
  3580. return $this->lp_view_id;
  3581. } else {
  3582. return 0;
  3583. }
  3584. }
  3585. /**
  3586. * Gets the update queue
  3587. * @return array Array containing IDs of items to be updated by JavaScript
  3588. */
  3589. public function get_update_queue()
  3590. {
  3591. if ($this->debug > 0) {
  3592. error_log('New LP - In learnpath::get_update_queue()', 0);
  3593. }
  3594. return $this->update_queue;
  3595. }
  3596. /**
  3597. * Gets the user ID
  3598. * @return integer User ID
  3599. */
  3600. public function get_user_id()
  3601. {
  3602. if ($this->debug > 0) {
  3603. error_log('New LP - In learnpath::get_user_id()', 0);
  3604. }
  3605. if (!empty ($this->user_id)) {
  3606. return $this->user_id;
  3607. } else {
  3608. return false;
  3609. }
  3610. }
  3611. /**
  3612. * Checks if any of the items has an audio element attached
  3613. * @return bool True or false
  3614. */
  3615. public function has_audio()
  3616. {
  3617. if ($this->debug > 1) {
  3618. error_log('New LP - In learnpath::has_audio()', 0);
  3619. }
  3620. $has = false;
  3621. foreach ($this->items as $i => $item) {
  3622. if (!empty ($this->items[$i]->audio)) {
  3623. $has = true;
  3624. break;
  3625. }
  3626. }
  3627. return $has;
  3628. }
  3629. /**
  3630. * Logs a message into a file
  3631. * @param string Message to log
  3632. * @return boolean True on success, false on error or if msg empty
  3633. */
  3634. public function log($msg)
  3635. {
  3636. if ($this->debug > 0) {
  3637. error_log('New LP - In learnpath::log()', 0);
  3638. }
  3639. // TODO
  3640. $this->error .= $msg;
  3641. return true;
  3642. }
  3643. /**
  3644. * Moves an item up and down at its level
  3645. * @param integer Item to move up and down
  3646. * @param string Direction 'up' or 'down'
  3647. * @return integer New display order, or false on error
  3648. */
  3649. public function move_item($id, $direction)
  3650. {
  3651. $course_id = api_get_course_int_id();
  3652. if ($this->debug > 0) {
  3653. error_log('New LP - In learnpath::move_item('.$id.','.$direction.')', 0);
  3654. }
  3655. if (empty($id) || empty($direction)) {
  3656. return false;
  3657. }
  3658. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3659. $sql_sel
  3660. = "SELECT *
  3661. FROM ".$tbl_lp_item."
  3662. WHERE c_id = ".$course_id." AND id = ".$id;
  3663. $res_sel = Database::query($sql_sel);
  3664. // Check if elem exists.
  3665. if (Database::num_rows($res_sel) < 1) {
  3666. return false;
  3667. }
  3668. // Gather data.
  3669. $row = Database::fetch_array($res_sel);
  3670. $previous = $row['previous_item_id'];
  3671. $next = $row['next_item_id'];
  3672. $display = $row['display_order'];
  3673. $parent = $row['parent_item_id'];
  3674. $lp = $row['lp_id'];
  3675. // Update the item (switch with previous/next one).
  3676. switch ($direction) {
  3677. case 'up':
  3678. if ($this->debug > 2) {
  3679. error_log('Movement up detected', 0);
  3680. }
  3681. if ($display > 1) {
  3682. $sql_sel2
  3683. = "SELECT * FROM $tbl_lp_item
  3684. WHERE c_id = ".$course_id." AND id = $previous";
  3685. if ($this->debug > 2) {
  3686. error_log('Selecting previous: '.$sql_sel2, 0);
  3687. }
  3688. $res_sel2 = Database::query($sql_sel2);
  3689. if (Database::num_rows($res_sel2) < 1) {
  3690. $previous_previous = 0;
  3691. }
  3692. // Gather data.
  3693. $row2 = Database::fetch_array($res_sel2);
  3694. $previous_previous = $row2['previous_item_id'];
  3695. // Update previous_previous item (switch "next" with current).
  3696. if ($previous_previous != 0) {
  3697. $sql_upd2
  3698. = "UPDATE $tbl_lp_item SET
  3699. next_item_id = $id
  3700. WHERE c_id = ".$course_id." AND id = $previous_previous";
  3701. if ($this->debug > 2) {
  3702. error_log($sql_upd2, 0);
  3703. }
  3704. Database::query($sql_upd2);
  3705. }
  3706. // Update previous item (switch with current).
  3707. if ($previous != 0) {
  3708. $sql_upd2
  3709. = "UPDATE $tbl_lp_item SET
  3710. next_item_id = $next,
  3711. previous_item_id = $id,
  3712. display_order = display_order +1
  3713. WHERE c_id = ".$course_id." AND id = $previous";
  3714. if ($this->debug > 2) {
  3715. error_log($sql_upd2, 0);
  3716. }
  3717. Database::query($sql_upd2);
  3718. }
  3719. // Update current item (switch with previous).
  3720. if ($id != 0) {
  3721. $sql_upd2
  3722. = "UPDATE $tbl_lp_item SET
  3723. next_item_id = $previous,
  3724. previous_item_id = $previous_previous,
  3725. display_order = display_order-1
  3726. WHERE c_id = ".$course_id." AND id = $id";
  3727. if ($this->debug > 2) {
  3728. error_log($sql_upd2, 0);
  3729. }
  3730. Database::query($sql_upd2);
  3731. }
  3732. // Update next item (new previous item).
  3733. if ($next != 0) {
  3734. $sql_upd2
  3735. = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3736. WHERE c_id = ".$course_id." AND id = $next";
  3737. if ($this->debug > 2) {
  3738. error_log($sql_upd2, 0);
  3739. }
  3740. Database::query($sql_upd2);
  3741. }
  3742. $display = $display - 1;
  3743. }
  3744. break;
  3745. case 'down':
  3746. if ($this->debug > 2) {
  3747. error_log('Movement down detected', 0);
  3748. }
  3749. if ($next != 0) {
  3750. $sql_sel2 = "SELECT * FROM $tbl_lp_item WHERE c_id = ".$course_id." AND id = $next";
  3751. if ($this->debug > 2) {
  3752. error_log('Selecting next: '.$sql_sel2, 0);
  3753. }
  3754. $res_sel2 = Database::query($sql_sel2);
  3755. if (Database::num_rows($res_sel2) < 1) {
  3756. $next_next = 0;
  3757. }
  3758. // Gather data.
  3759. $row2 = Database::fetch_array($res_sel2);
  3760. $next_next = $row2['next_item_id'];
  3761. // Update previous item (switch with current).
  3762. if ($previous != 0) {
  3763. $sql_upd2
  3764. = "UPDATE $tbl_lp_item SET next_item_id = $next
  3765. WHERE c_id = ".$course_id." AND id = $previous";
  3766. Database::query($sql_upd2);
  3767. }
  3768. // Update current item (switch with previous).
  3769. if ($id != 0) {
  3770. $sql_upd2
  3771. = "UPDATE $tbl_lp_item SET
  3772. previous_item_id = $next, next_item_id = $next_next, display_order = display_order+1
  3773. WHERE c_id = ".$course_id." AND id = $id";
  3774. Database::query($sql_upd2);
  3775. }
  3776. // Update next item (new previous item).
  3777. if ($next != 0) {
  3778. $sql_upd2
  3779. = "UPDATE $tbl_lp_item SET
  3780. previous_item_id = $previous, next_item_id = $id, display_order = display_order-1
  3781. WHERE c_id = ".$course_id." AND id = $next";
  3782. Database::query($sql_upd2);
  3783. }
  3784. // Update next_next item (switch "previous" with current).
  3785. if ($next_next != 0) {
  3786. $sql_upd2
  3787. = "UPDATE $tbl_lp_item SET
  3788. previous_item_id = $id
  3789. WHERE c_id = ".$course_id." AND id = $next_next";
  3790. Database::query($sql_upd2);
  3791. }
  3792. $display = $display + 1;
  3793. }
  3794. break;
  3795. default:
  3796. return false;
  3797. }
  3798. return $display;
  3799. }
  3800. /**
  3801. * Move a LP up (display_order)
  3802. * @param int $lp_id Learnpath ID
  3803. * @param int $categoryId
  3804. * @return bool
  3805. */
  3806. public static function move_up($lp_id, $categoryId = 0)
  3807. {
  3808. $courseId = api_get_course_int_id();
  3809. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3810. $categoryCondition = '';
  3811. if (!empty($categoryId)) {
  3812. $categoryId = (int)$categoryId;
  3813. $categoryCondition = " AND category_id = $categoryId";
  3814. }
  3815. $sql
  3816. = "SELECT * FROM $lp_table
  3817. WHERE c_id = $courseId
  3818. $categoryCondition
  3819. ORDER BY display_order";
  3820. $res = Database::query($sql);
  3821. if ($res === false) {
  3822. return false;
  3823. }
  3824. $lps = [];
  3825. $lp_order = [];
  3826. $num = Database::num_rows($res);
  3827. // First check the order is correct, globally (might be wrong because
  3828. // of versions < 1.8.4)
  3829. if ($num > 0) {
  3830. $i = 1;
  3831. while ($row = Database::fetch_array($res)) {
  3832. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3833. $sql
  3834. = "UPDATE $lp_table SET display_order = $i
  3835. WHERE c_id = $courseId AND id = ".$row['id'];
  3836. Database::query($sql);
  3837. }
  3838. $row['display_order'] = $i;
  3839. $lps[$row['id']] = $row;
  3840. $lp_order[$i] = $row['id'];
  3841. $i++;
  3842. }
  3843. }
  3844. if ($num > 1) { // If there's only one element, no need to sort.
  3845. $order = $lps[$lp_id]['display_order'];
  3846. if ($order > 1) { // If it's the first element, no need to move up.
  3847. $sql
  3848. = "UPDATE $lp_table SET display_order = $order
  3849. WHERE c_id = $courseId AND id = ".$lp_order[$order - 1];
  3850. Database::query($sql);
  3851. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3852. WHERE c_id = $courseId AND id = ".$lp_id;
  3853. Database::query($sql);
  3854. }
  3855. }
  3856. return true;
  3857. }
  3858. /**
  3859. * Move a learnpath down (display_order)
  3860. * @param int $lp_id Learnpath ID
  3861. * @param int $categoryId
  3862. * @return bool
  3863. */
  3864. public static function move_down($lp_id, $categoryId = 0)
  3865. {
  3866. $courseId = api_get_course_int_id();
  3867. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3868. $categoryCondition = '';
  3869. if (!empty($categoryId)) {
  3870. $categoryId = (int)$categoryId;
  3871. $categoryCondition = " AND category_id = $categoryId";
  3872. }
  3873. $sql
  3874. = "SELECT * FROM $lp_table
  3875. WHERE c_id = $courseId
  3876. $categoryCondition
  3877. ORDER BY display_order";
  3878. $res = Database::query($sql);
  3879. if ($res === false) {
  3880. return false;
  3881. }
  3882. $lps = [];
  3883. $lp_order = [];
  3884. $num = Database::num_rows($res);
  3885. $max = 0;
  3886. // First check the order is correct, globally (might be wrong because
  3887. // of versions < 1.8.4).
  3888. if ($num > 0) {
  3889. $i = 1;
  3890. while ($row = Database::fetch_array($res)) {
  3891. $max = $i;
  3892. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3893. $need_fix = true;
  3894. $sql_u
  3895. = "UPDATE $lp_table SET display_order = $i
  3896. WHERE c_id = ".$courseId." AND id = ".$row['id'];
  3897. Database::query($sql_u);
  3898. }
  3899. $row['display_order'] = $i;
  3900. $lps[$row['id']] = $row;
  3901. $lp_order[$i] = $row['id'];
  3902. $i++;
  3903. }
  3904. }
  3905. if ($num > 1) { // If there's only one element, no need to sort.
  3906. $order = $lps[$lp_id]['display_order'];
  3907. if ($order < $max) { // If it's the first element, no need to move up.
  3908. $sql_u1
  3909. = "UPDATE $lp_table SET display_order = $order
  3910. WHERE c_id = ".$courseId." AND id = ".$lp_order[$order + 1];
  3911. Database::query($sql_u1);
  3912. $sql_u2 = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3913. WHERE c_id = ".$courseId." AND id = ".$lp_id;
  3914. Database::query($sql_u2);
  3915. }
  3916. }
  3917. return true;
  3918. }
  3919. /**
  3920. * Updates learnpath attributes to point to the next element
  3921. * The last part is similar to set_current_item but processing the other way around
  3922. */
  3923. public function next()
  3924. {
  3925. if ($this->debug > 0) {
  3926. error_log('New LP - In learnpath::next()', 0);
  3927. }
  3928. $this->last = $this->get_current_item_id();
  3929. $this->items[$this->last]->save(false, $this->prerequisites_match($this->last));
  3930. $this->autocomplete_parents($this->last);
  3931. $new_index = $this->get_next_index();
  3932. if ($this->debug > 2) {
  3933. error_log('New LP - New index: '.$new_index, 0);
  3934. }
  3935. $this->index = $new_index;
  3936. if ($this->debug > 2) {
  3937. error_log('New LP - Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3938. }
  3939. $this->current = $this->ordered_items[$new_index];
  3940. if ($this->debug > 2) {
  3941. error_log('New LP - new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3942. }
  3943. }
  3944. /**
  3945. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3946. * class, this might be redefined to allow several behaviours depending on the document type.
  3947. * @param integer Resource ID
  3948. * @return boolean True on success, false otherwise
  3949. */
  3950. public function open($id)
  3951. {
  3952. if ($this->debug > 0) {
  3953. error_log('New LP - In learnpath::open()', 0);
  3954. }
  3955. // TODO:
  3956. // set the current resource attribute to this resource
  3957. // switch on element type (redefine in child class?)
  3958. // set status for this item to "opened"
  3959. // start timer
  3960. // initialise score
  3961. $this->index = 0; //or = the last item seen (see $this->last)
  3962. }
  3963. /**
  3964. * Check that all prerequisites are fulfilled. Returns true and an
  3965. * empty string on success, returns false
  3966. * and the prerequisite string on error.
  3967. * This function is based on the rules for aicc_script language as
  3968. * described in the SCORM 1.2 CAM documentation page 108.
  3969. * @param integer $itemId Optional item ID. If none given, uses the current open item.
  3970. * @return boolean True if prerequisites are matched, false otherwise -
  3971. * Empty string if true returned, prerequisites string otherwise.
  3972. */
  3973. public function prerequisites_match($itemId = null)
  3974. {
  3975. $debug = $this->debug;
  3976. if ($debug > 0) {
  3977. error_log('In learnpath::prerequisites_match()', 0);
  3978. }
  3979. if (empty($itemId)) {
  3980. $itemId = $this->current;
  3981. }
  3982. $currentItem = $this->getItem($itemId);
  3983. if ($currentItem) {
  3984. if ($this->type == 2) {
  3985. // Getting prereq from scorm
  3986. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3987. } else {
  3988. $prereq_string = $currentItem->get_prereq_string();
  3989. }
  3990. if (empty($prereq_string)) {
  3991. if ($debug > 0) {
  3992. error_log('Found prereq_string is empty return true');
  3993. }
  3994. return true;
  3995. }
  3996. // Clean spaces.
  3997. $prereq_string = str_replace(' ', '', $prereq_string);
  3998. if ($debug > 0) {
  3999. error_log('Found prereq_string: '.$prereq_string, 0);
  4000. }
  4001. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4002. $result = $currentItem->parse_prereq(
  4003. $prereq_string,
  4004. $this->items,
  4005. $this->refs_list,
  4006. $this->get_user_id()
  4007. );
  4008. if ($result === false) {
  4009. $this->set_error_msg($currentItem->prereq_alert);
  4010. }
  4011. } else {
  4012. $result = true;
  4013. if ($debug > 1) {
  4014. error_log('$this->items['.$itemId.'] was not an object', 0);
  4015. }
  4016. }
  4017. if ($debug > 1) {
  4018. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4019. }
  4020. return $result;
  4021. }
  4022. /**
  4023. * Updates learnpath attributes to point to the previous element
  4024. * The last part is similar to set_current_item but processing the other way around
  4025. */
  4026. public function previous()
  4027. {
  4028. if ($this->debug > 0) {
  4029. error_log('New LP - In learnpath::previous()', 0);
  4030. }
  4031. $this->last = $this->get_current_item_id();
  4032. $this->items[$this->last]->save(false, $this->prerequisites_match($this->last));
  4033. $this->autocomplete_parents($this->last);
  4034. $new_index = $this->get_previous_index();
  4035. $this->index = $new_index;
  4036. $this->current = $this->ordered_items[$new_index];
  4037. }
  4038. /**
  4039. * Publishes a learnpath. This basically means show or hide the learnpath
  4040. * to normal users.
  4041. * Can be used as abstract
  4042. * @param integer Learnpath ID
  4043. * @param string New visibility
  4044. */
  4045. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4046. {
  4047. $action = 'visible';
  4048. if ($set_visibility != 1) {
  4049. $action = 'invisible';
  4050. self::toggle_publish($lp_id, 'i');
  4051. }
  4052. return api_item_property_update(
  4053. api_get_course_info(),
  4054. TOOL_LEARNPATH,
  4055. $lp_id,
  4056. $action,
  4057. api_get_user_id()
  4058. );
  4059. }
  4060. /**
  4061. * Publishes a learnpath category.
  4062. * This basically means show or hide the learnpath category to normal users.
  4063. * @param int $id
  4064. * @param int $visibility
  4065. * @return bool
  4066. */
  4067. public static function toggleCategoryVisibility($id, $visibility = 1)
  4068. {
  4069. $action = 'visible';
  4070. if ($visibility != 1) {
  4071. $action = 'invisible';
  4072. $list = new LearnpathList(api_get_user_id(), null, null, null, false, $id);
  4073. $learPaths = $list->get_flat_list();
  4074. foreach ($learPaths as $lp) {
  4075. learnpath::toggle_visibility($lp['iid'], 0);
  4076. }
  4077. learnpath::toggleCategoryPublish($id, 0);
  4078. }
  4079. return api_item_property_update(
  4080. api_get_course_info(),
  4081. TOOL_LEARNPATH_CATEGORY,
  4082. $id,
  4083. $action,
  4084. api_get_user_id()
  4085. );
  4086. }
  4087. /**
  4088. * Publishes a learnpath. This basically means show or hide the learnpath
  4089. * on the course homepage
  4090. * Can be used as abstract
  4091. * @param integer $lp_id Learnpath id
  4092. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4093. * @return bool
  4094. */
  4095. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4096. {
  4097. $course_id = api_get_course_int_id();
  4098. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4099. $lp_id = intval($lp_id);
  4100. $sql
  4101. = "SELECT * FROM $tbl_lp
  4102. WHERE c_id = $course_id AND id = $lp_id";
  4103. $result = Database::query($sql);
  4104. if (Database::num_rows($result)) {
  4105. $row = Database::fetch_array($result);
  4106. $name = Database::escape_string($row['name']);
  4107. if ($set_visibility == 'i') {
  4108. $v = 0;
  4109. }
  4110. if ($set_visibility == 'v') {
  4111. $v = 1;
  4112. }
  4113. $session_id = api_get_session_id();
  4114. $session_condition = api_get_session_condition($session_id);
  4115. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4116. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4117. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4118. $sql
  4119. = "SELECT * FROM $tbl_tool
  4120. WHERE
  4121. c_id = $course_id AND
  4122. (link = '$link' OR link = '$oldLink') AND
  4123. image = 'scormbuilder.gif' AND
  4124. (
  4125. link LIKE '$link%' OR
  4126. link LIKE '$oldLink%'
  4127. )
  4128. $session_condition
  4129. ";
  4130. $result = Database::query($sql);
  4131. $num = Database::num_rows($result);
  4132. if ($set_visibility == 'i' && $num > 0) {
  4133. $sql
  4134. = "DELETE FROM $tbl_tool
  4135. WHERE
  4136. c_id = $course_id AND
  4137. (link = '$link' OR link = '$oldLink') AND
  4138. image='scormbuilder.gif'
  4139. $session_condition";
  4140. Database::query($sql);
  4141. } elseif ($set_visibility == 'v' && $num == 0) {
  4142. $sql
  4143. = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4144. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4145. Database::query($sql);
  4146. $insertId = Database::insert_id();
  4147. if ($insertId) {
  4148. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4149. Database::query($sql);
  4150. }
  4151. } elseif ($set_visibility == 'v' && $num > 0) {
  4152. $sql
  4153. = "UPDATE $tbl_tool SET
  4154. c_id = $course_id,
  4155. name = '$name',
  4156. link = '$link',
  4157. image = 'scormbuilder.gif',
  4158. visibility = '$v',
  4159. admin = '0',
  4160. address = 'pastillegris.gif',
  4161. added_tool = 0,
  4162. session_id = $session_id
  4163. WHERE
  4164. c_id = ".$course_id." AND
  4165. (link = '$link' OR link = '$oldLink') AND
  4166. image='scormbuilder.gif'
  4167. $session_condition
  4168. ";
  4169. Database::query($sql);
  4170. } else {
  4171. // Parameter and database incompatible, do nothing, exit.
  4172. return false;
  4173. }
  4174. } else {
  4175. return false;
  4176. }
  4177. }
  4178. /**
  4179. * Generate the link for a learnpath category as course tool
  4180. * @param int $categoryId
  4181. * @return string
  4182. */
  4183. private static function getCategoryLinkForTool($categoryId)
  4184. {
  4185. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  4186. .http_build_query(
  4187. [
  4188. 'action' => 'view_category',
  4189. 'id' => $categoryId
  4190. ]
  4191. );
  4192. return $link;
  4193. }
  4194. /**
  4195. * Publishes a learnpath.
  4196. * Show or hide the learnpath category on the course homepage
  4197. * @param int $id
  4198. * @param int $setVisibility
  4199. * @return bool
  4200. */
  4201. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4202. {
  4203. $courseId = api_get_course_int_id();
  4204. $sessionId = api_get_session_id();
  4205. $sessionCondition = api_get_session_condition($sessionId, true, false, 't.sessionId');
  4206. $em = Database::getManager();
  4207. /** @var CLpCategory $category */
  4208. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4209. if (!$category) {
  4210. return false;
  4211. }
  4212. $link = self::getCategoryLinkForTool($id);
  4213. /** @var CTool $tool */
  4214. $tool = $em
  4215. ->createQuery("
  4216. SELECT t FROM ChamiloCourseBundle:CTool t
  4217. WHERE
  4218. t.cId = :course AND
  4219. t.link = :link1 AND
  4220. t.image = 'lp_category.gif' AND
  4221. t.link LIKE :link2
  4222. $sessionCondition
  4223. ")
  4224. ->setParameters([
  4225. 'course' => (int)$courseId,
  4226. 'link1' => $link,
  4227. 'link2' => "$link%"
  4228. ])
  4229. ->getOneOrNullResult();
  4230. if ($setVisibility == 0 && $tool) {
  4231. $em->remove($tool);
  4232. $em->flush();
  4233. return true;
  4234. }
  4235. if ($setVisibility == 1 && !$tool) {
  4236. $tool = new CTool();
  4237. $tool
  4238. ->setCategory('authoring')
  4239. ->setCId($courseId)
  4240. ->setName(strip_tags($category->getName()))
  4241. ->setLink($link)
  4242. ->setImage('lp_category.gif')
  4243. ->setVisibility(1)
  4244. ->setAdmin(0)
  4245. ->setAddress('pastillegris.gif')
  4246. ->setAddedTool(0)
  4247. ->setSessionId($sessionId)
  4248. ->setTarget('_self');
  4249. $em->persist($tool);
  4250. $em->flush();
  4251. $tool->setId($tool->getIid());
  4252. $em->persist($tool);
  4253. $em->flush();
  4254. return true;
  4255. }
  4256. if ($setVisibility == 1 && $tool) {
  4257. $tool
  4258. ->setName(strip_tags($category->getName()))
  4259. ->setVisibility(1);
  4260. $em->persist($tool);
  4261. $em->flush();
  4262. return true;
  4263. }
  4264. return false;
  4265. }
  4266. /**
  4267. * Check if the learnpath category is visible for a user
  4268. * @param CLpCategory $category
  4269. * @param User $user
  4270. * @return bool
  4271. */
  4272. public static function categoryIsVisibleForStudent(
  4273. CLpCategory $category,
  4274. User $user
  4275. ) {
  4276. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4277. if ($isAllowedToEdit) {
  4278. return true;
  4279. }
  4280. $users = $category->getUsers();
  4281. if (empty($users) || !$users->count()) {
  4282. return true;
  4283. }
  4284. if ($category->hasUserAdded($user)) {
  4285. return true;
  4286. }
  4287. return false;
  4288. }
  4289. /**
  4290. * Check if a learnpath category is published as course tool
  4291. * @param CLpCategory $category
  4292. * @param int $courseId
  4293. * @return bool
  4294. */
  4295. public static function categoryIsPusblished(
  4296. CLpCategory $category,
  4297. $courseId
  4298. ) {
  4299. $link = self::getCategoryLinkForTool($category->getId());
  4300. $em = Database::getManager();
  4301. $tools = $em
  4302. ->createQuery("
  4303. SELECT t FROM ChamiloCourseBundle:CTool t
  4304. WHERE t.cId = :course AND
  4305. t.name = :name AND
  4306. t.image = 'lp_category.gif' AND
  4307. t.link LIKE :link
  4308. ")
  4309. ->setParameters([
  4310. 'course' => $courseId,
  4311. 'name' => strip_tags($category->getName()),
  4312. 'link' => "$link%"
  4313. ])
  4314. ->getResult();
  4315. /** @var CTool $tool */
  4316. $tool = current($tools);
  4317. return $tool ? $tool->getVisibility() : false;
  4318. }
  4319. /**
  4320. * Restart the whole learnpath. Return the URL of the first element.
  4321. * Make sure the results are saved with anoter method. This method should probably be
  4322. * redefined in children classes.
  4323. * To use a similar method statically, use the create_new_attempt() method
  4324. * @return string URL to load in the viewer
  4325. */
  4326. public function restart()
  4327. {
  4328. if ($this->debug > 0) {
  4329. error_log('New LP - In learnpath::restart()', 0);
  4330. }
  4331. // TODO
  4332. // Call autosave method to save the current progress.
  4333. //$this->index = 0;
  4334. if (api_is_invitee()) {
  4335. return false;
  4336. }
  4337. $session_id = api_get_session_id();
  4338. $course_id = api_get_course_int_id();
  4339. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4340. $sql
  4341. = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4342. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4343. if ($this->debug > 2) {
  4344. error_log('New LP - Inserting new lp_view for restart: '.$sql, 0);
  4345. }
  4346. Database::query($sql);
  4347. $view_id = Database::insert_id();
  4348. if ($view_id) {
  4349. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4350. Database::query($sql);
  4351. $this->lp_view_id = $view_id;
  4352. $this->attempt = $this->attempt + 1;
  4353. } else {
  4354. $this->error = 'Could not insert into item_view table...';
  4355. return false;
  4356. }
  4357. $this->autocomplete_parents($this->current);
  4358. foreach ($this->items as $index => $dummy) {
  4359. $this->items[$index]->restart();
  4360. $this->items[$index]->set_lp_view($this->lp_view_id);
  4361. }
  4362. $this->first();
  4363. return true;
  4364. }
  4365. /**
  4366. * Saves the current item
  4367. * @return boolean
  4368. */
  4369. public function save_current()
  4370. {
  4371. if ($this->debug > 0) {
  4372. error_log('learnpath::save_current()', 0);
  4373. }
  4374. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4375. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4376. if ($this->debug > 2) {
  4377. error_log('New LP - save_current() saving item '.$this->current, 0);
  4378. }
  4379. if ($this->debug > 2) {
  4380. error_log(''.print_r($this->items, true), 0);
  4381. }
  4382. if (isset($this->items[$this->current]) && is_object($this->items[$this->current])
  4383. ) {
  4384. $res = $this->items[$this->current]->save(false, $this->prerequisites_match($this->current));
  4385. $this->autocomplete_parents($this->current);
  4386. $status = $this->items[$this->current]->get_status();
  4387. $this->update_queue[$this->current] = $status;
  4388. return $res;
  4389. }
  4390. return false;
  4391. }
  4392. /**
  4393. * Saves the given item
  4394. * @param integer $item_id Optional (will take from $_REQUEST if null)
  4395. * @param boolean $from_outside Save from url params (true) or from current attributes (false). Optional.
  4396. * Defaults to true
  4397. * @return boolean
  4398. */
  4399. public function save_item($item_id = null, $from_outside = true)
  4400. {
  4401. $debug = $this->debug;
  4402. if ($debug) {
  4403. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4404. }
  4405. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4406. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4407. if (empty($item_id)) {
  4408. $item_id = intval($_REQUEST['id']);
  4409. }
  4410. if (empty($item_id)) {
  4411. $item_id = $this->get_current_item_id();
  4412. }
  4413. if (isset($this->items[$item_id]) && is_object($this->items[$item_id])) {
  4414. if ($debug) {
  4415. error_log('Object exists');
  4416. }
  4417. // Saving the item.
  4418. $res = $this->items[$item_id]->save(
  4419. $from_outside,
  4420. $this->prerequisites_match($item_id)
  4421. );
  4422. if ($debug) {
  4423. error_log('update_queue before:');
  4424. error_log(print_r($this->update_queue, 1));
  4425. }
  4426. $this->autocomplete_parents($item_id);
  4427. $status = $this->items[$item_id]->get_status();
  4428. $this->update_queue[$item_id] = $status;
  4429. if ($debug) {
  4430. error_log('get_status(): '.$status);
  4431. error_log('update_queue after:');
  4432. error_log(print_r($this->update_queue, 1));
  4433. }
  4434. return $res;
  4435. }
  4436. return false;
  4437. }
  4438. /**
  4439. * Saves the last item seen's ID only in case
  4440. */
  4441. public function save_last()
  4442. {
  4443. $course_id = api_get_course_int_id();
  4444. if ($this->debug > 0) {
  4445. error_log('New LP - In learnpath::save_last()', 0);
  4446. }
  4447. $session_condition = api_get_session_condition(api_get_session_id(), true, false);
  4448. $table = Database::get_course_table(TABLE_LP_VIEW);
  4449. if (isset($this->current) && !api_is_invitee()) {
  4450. if ($this->debug > 2) {
  4451. error_log('New LP - Saving current item ('.$this->current.') for later review', 0);
  4452. }
  4453. $sql
  4454. = "UPDATE $table SET
  4455. last_item = ".intval($this->get_current_item_id())."
  4456. WHERE
  4457. c_id = $course_id AND
  4458. lp_id = ".$this->get_id()." AND
  4459. user_id = ".$this->get_user_id()." ".$session_condition;
  4460. if ($this->debug > 2) {
  4461. error_log('New LP - Saving last item seen : '.$sql, 0);
  4462. }
  4463. Database::query($sql);
  4464. }
  4465. if (!api_is_invitee()) {
  4466. // Save progress.
  4467. list($progress,) = $this->get_progress_bar_text('%');
  4468. if ($progress >= 0 && $progress <= 100) {
  4469. $progress = (int)$progress;
  4470. $sql
  4471. = "UPDATE $table SET
  4472. progress = $progress
  4473. WHERE
  4474. c_id = ".$course_id." AND
  4475. lp_id = ".$this->get_id()." AND
  4476. user_id = ".$this->get_user_id()." ".$session_condition;
  4477. // Ignore errors as some tables might not have the progress field just yet.
  4478. Database::query($sql);
  4479. $this->progress_db = $progress;
  4480. }
  4481. }
  4482. }
  4483. /**
  4484. * Sets the current item ID (checks if valid and authorized first)
  4485. * @param integer $item_id New item ID. If not given or not authorized, defaults to current
  4486. */
  4487. public function set_current_item($item_id = null)
  4488. {
  4489. if ($this->debug > 0) {
  4490. error_log('New LP - In learnpath::set_current_item('.$item_id.')', 0);
  4491. }
  4492. if (empty ($item_id)) {
  4493. if ($this->debug > 2) {
  4494. error_log('New LP - No new current item given, ignore...', 0);
  4495. }
  4496. // Do nothing.
  4497. } else {
  4498. if ($this->debug > 2) {
  4499. error_log('New LP - New current item given is '.$item_id.'...', 0);
  4500. }
  4501. if (is_numeric($item_id)) {
  4502. $item_id = intval($item_id);
  4503. // TODO: Check in database here.
  4504. $this->last = $this->current;
  4505. $this->current = $item_id;
  4506. // TODO: Update $this->index as well.
  4507. foreach ($this->ordered_items as $index => $item) {
  4508. if ($item == $this->current) {
  4509. $this->index = $index;
  4510. break;
  4511. }
  4512. }
  4513. if ($this->debug > 2) {
  4514. error_log('New LP - set_current_item('.$item_id.') done. Index is now : '.$this->index, 0);
  4515. }
  4516. } else {
  4517. error_log('New LP - set_current_item('.$item_id.') failed. Not a numeric value: ', 0);
  4518. }
  4519. }
  4520. }
  4521. /**
  4522. * Sets the encoding
  4523. * @param string New encoding
  4524. * @return bool
  4525. * TODO (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4526. */
  4527. public function set_encoding($enc = 'UTF-8')
  4528. {
  4529. if ($this->debug > 0) {
  4530. error_log('New LP - In learnpath::set_encoding()', 0);
  4531. }
  4532. $course_id = api_get_course_int_id();
  4533. $enc = api_refine_encoding_id($enc);
  4534. if (empty($enc)) {
  4535. $enc = api_get_system_encoding();
  4536. }
  4537. if (api_is_encoding_supported($enc)) {
  4538. $lp = $this->get_id();
  4539. if ($lp != 0) {
  4540. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4541. $sql
  4542. = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4543. WHERE c_id = ".$course_id." AND id = ".$lp;
  4544. $res = Database::query($sql);
  4545. return $res;
  4546. }
  4547. }
  4548. return false;
  4549. }
  4550. /**
  4551. * Sets the JS lib setting in the database directly.
  4552. * This is the JavaScript library file this lp needs to load on startup
  4553. * @param string Proximity setting
  4554. * @return boolean True on update success. False otherwise.
  4555. */
  4556. public function set_jslib($lib = '')
  4557. {
  4558. if ($this->debug > 0) {
  4559. error_log('New LP - In learnpath::set_jslib()', 0);
  4560. }
  4561. $lp = $this->get_id();
  4562. $course_id = api_get_course_int_id();
  4563. if ($lp != 0) {
  4564. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4565. $sql
  4566. = "UPDATE $tbl_lp SET js_lib = '$lib'
  4567. WHERE c_id = ".$course_id." AND id = ".$lp;
  4568. $res = Database::query($sql);
  4569. return $res;
  4570. } else {
  4571. return false;
  4572. }
  4573. }
  4574. /**
  4575. * Sets the name of the LP maker (publisher) (and save)
  4576. * @param string Optional string giving the new content_maker of this learnpath
  4577. * @return boolean True
  4578. */
  4579. public function set_maker($name = '')
  4580. {
  4581. if ($this->debug > 0) {
  4582. error_log('New LP - In learnpath::set_maker()', 0);
  4583. }
  4584. if (empty ($name)) {
  4585. return false;
  4586. }
  4587. $this->maker = $name;
  4588. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4589. $course_id = api_get_course_int_id();
  4590. $lp_id = $this->get_id();
  4591. $sql
  4592. = "UPDATE $lp_table SET
  4593. content_maker = '".Database::escape_string($this->maker)."'
  4594. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4595. if ($this->debug > 2) {
  4596. error_log('New LP - lp updated with new content_maker : '.$this->maker, 0);
  4597. }
  4598. Database::query($sql);
  4599. return true;
  4600. }
  4601. /**
  4602. * Sets the name of the current learnpath (and save)
  4603. * @param string $name Optional string giving the new name of this learnpath
  4604. * @return boolean True/False
  4605. */
  4606. public function set_name($name = null)
  4607. {
  4608. if ($this->debug > 0) {
  4609. error_log('New LP - In learnpath::set_name()', 0);
  4610. }
  4611. if (empty($name)) {
  4612. return false;
  4613. }
  4614. $this->name = Database::escape_string($name);
  4615. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4616. $lp_id = $this->get_id();
  4617. $course_id = $this->course_info['real_id'];
  4618. $sql
  4619. = "UPDATE $lp_table SET
  4620. name = '".Database::escape_string($this->name)."'
  4621. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4622. if ($this->debug > 2) {
  4623. error_log('New LP - lp updated with new name : '.$this->name, 0);
  4624. }
  4625. $result = Database::query($sql);
  4626. // If the lp is visible on the homepage, change his name there.
  4627. if (Database::affected_rows($result)) {
  4628. $session_id = api_get_session_id();
  4629. $session_condition = api_get_session_condition($session_id);
  4630. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4631. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4632. $sql
  4633. = "UPDATE $tbl_tool SET name = '$this->name'
  4634. WHERE
  4635. c_id = $course_id AND
  4636. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4637. Database::query($sql);
  4638. return true;
  4639. } else {
  4640. return false;
  4641. }
  4642. }
  4643. /**
  4644. * Set index specified prefix terms for all items in this path
  4645. * @param string Comma-separated list of terms
  4646. * @param char Xapian term prefix
  4647. * @return boolean False on error, true otherwise
  4648. */
  4649. public function set_terms_by_prefix($terms_string, $prefix)
  4650. {
  4651. $course_id = api_get_course_int_id();
  4652. if (api_get_setting('search_enabled') !== 'true') {
  4653. return false;
  4654. }
  4655. if (!extension_loaded('xapian')) {
  4656. return false;
  4657. }
  4658. $terms_string = trim($terms_string);
  4659. $terms = explode(',', $terms_string);
  4660. array_walk($terms, 'trim_value');
  4661. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4662. // Don't do anything if no change, verify only at DB, not the search engine.
  4663. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4664. return false;
  4665. }
  4666. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4667. require_once api_get_path(LIBRARY_PATH).'search/ChamiloIndexer.class.php';
  4668. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4669. require_once api_get_path(LIBRARY_PATH).'search/IndexableChunk.class.php';
  4670. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4671. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4672. $lp_id = intval($_POST['lp_id']);
  4673. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4674. $result = Database::query($sql);
  4675. $di = new ChamiloIndexer();
  4676. while ($lp_item = Database::fetch_array($result)) {
  4677. // Get search_did.
  4678. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4679. $sql
  4680. = 'SELECT * FROM %s
  4681. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4682. LIMIT 1';
  4683. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4684. //echo $sql; echo '<br>';
  4685. $res = Database::query($sql);
  4686. if (Database::num_rows($res) > 0) {
  4687. $se_ref = Database::fetch_array($res);
  4688. // Compare terms.
  4689. $doc = $di->get_document($se_ref['search_did']);
  4690. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4691. $xterms = array();
  4692. foreach ($xapian_terms as $xapian_term) {
  4693. $xterms[] = substr($xapian_term['name'], 1);
  4694. }
  4695. $dterms = $terms;
  4696. $missing_terms = array_diff($dterms, $xterms);
  4697. $deprecated_terms = array_diff($xterms, $dterms);
  4698. // Save it to search engine.
  4699. foreach ($missing_terms as $term) {
  4700. $doc->add_term($prefix.$term, 1);
  4701. }
  4702. foreach ($deprecated_terms as $term) {
  4703. $doc->remove_term($prefix.$term);
  4704. }
  4705. $di->getDb()->replace_document((int)$se_ref['search_did'], $doc);
  4706. $di->getDb()->flush();
  4707. }
  4708. }
  4709. return true;
  4710. }
  4711. /**
  4712. * Sets the theme of the LP (local/remote) (and save)
  4713. * @param string Optional string giving the new theme of this learnpath
  4714. * @return bool Returns true if theme name is not empty
  4715. */
  4716. public function set_theme($name = '')
  4717. {
  4718. $course_id = api_get_course_int_id();
  4719. if ($this->debug > 0) {
  4720. error_log('New LP - In learnpath::set_theme()', 0);
  4721. }
  4722. $this->theme = $name;
  4723. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4724. $lp_id = $this->get_id();
  4725. $sql = "UPDATE $lp_table SET theme = '".Database::escape_string($this->theme)."'
  4726. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4727. if ($this->debug > 2) {
  4728. error_log('New LP - lp updated with new theme : '.$this->theme, 0);
  4729. }
  4730. Database::query($sql);
  4731. return true;
  4732. }
  4733. /**
  4734. * Sets the image of an LP (and save)
  4735. * @param string Optional string giving the new image of this learnpath
  4736. * @return bool Returns true if theme name is not empty
  4737. */
  4738. public function set_preview_image($name = '')
  4739. {
  4740. $course_id = api_get_course_int_id();
  4741. if ($this->debug > 0) {
  4742. error_log('New LP - In learnpath::set_preview_image()', 0);
  4743. }
  4744. $this->preview_image = $name;
  4745. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4746. $lp_id = $this->get_id();
  4747. $sql
  4748. = "UPDATE $lp_table SET
  4749. preview_image = '".Database::escape_string($this->preview_image)."'
  4750. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4751. if ($this->debug > 2) {
  4752. error_log('New LP - lp updated with new preview image : '.$this->preview_image, 0);
  4753. }
  4754. Database::query($sql);
  4755. return true;
  4756. }
  4757. /**
  4758. * Sets the author of a LP (and save)
  4759. * @param string Optional string giving the new author of this learnpath
  4760. * @return bool Returns true if author's name is not empty
  4761. */
  4762. public function set_author($name = '')
  4763. {
  4764. $course_id = api_get_course_int_id();
  4765. if ($this->debug > 0) {
  4766. error_log('New LP - In learnpath::set_author()', 0);
  4767. }
  4768. $this->author = $name;
  4769. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4770. $lp_id = $this->get_id();
  4771. $sql = "UPDATE $lp_table SET author = '".Database::escape_string($name)."'
  4772. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4773. if ($this->debug > 2) {
  4774. error_log('New LP - lp updated with new preview author : '.$this->author, 0);
  4775. }
  4776. Database::query($sql);
  4777. return true;
  4778. }
  4779. /**
  4780. * Sets the hide_toc_frame parameter of a LP (and save)
  4781. * @param int 1 if frame is hidden 0 then else
  4782. * @return bool Returns true if author's name is not empty
  4783. */
  4784. public function set_hide_toc_frame($hide)
  4785. {
  4786. $course_id = api_get_course_int_id();
  4787. if ($this->debug > 0) {
  4788. error_log('New LP - In learnpath::set_hide_toc_frame()', 0);
  4789. }
  4790. if (intval($hide) == $hide) {
  4791. $this->hide_toc_frame = $hide;
  4792. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4793. $lp_id = $this->get_id();
  4794. $sql
  4795. = "UPDATE $lp_table SET
  4796. hide_toc_frame = '".(int)$this->hide_toc_frame."'
  4797. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4798. if ($this->debug > 2) {
  4799. error_log('New LP - lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4800. }
  4801. Database::query($sql);
  4802. return true;
  4803. } else {
  4804. return false;
  4805. }
  4806. }
  4807. /**
  4808. * Sets the prerequisite of a LP (and save)
  4809. * @param int integer giving the new prerequisite of this learnpath
  4810. * @return bool returns true if prerequisite is not empty
  4811. */
  4812. public function set_prerequisite($prerequisite)
  4813. {
  4814. $course_id = api_get_course_int_id();
  4815. if ($this->debug > 0) {
  4816. error_log('New LP - In learnpath::set_prerequisite()', 0);
  4817. }
  4818. $this->prerequisite = intval($prerequisite);
  4819. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4820. $lp_id = $this->get_id();
  4821. $sql = "UPDATE $lp_table SET prerequisite = '".$this->prerequisite."'
  4822. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4823. if ($this->debug > 2) {
  4824. error_log('New LP - lp updated with new preview requisite : '.$this->requisite, 0);
  4825. }
  4826. Database::query($sql);
  4827. return true;
  4828. }
  4829. /**
  4830. * Sets the location/proximity of the LP (local/remote) (and save)
  4831. * @param string Optional string giving the new location of this learnpath
  4832. * @return boolean True on success / False on error
  4833. */
  4834. public function set_proximity($name = '')
  4835. {
  4836. $course_id = api_get_course_int_id();
  4837. if ($this->debug > 0) {
  4838. error_log('New LP - In learnpath::set_proximity()', 0);
  4839. }
  4840. if (empty ($name)) {
  4841. return false;
  4842. }
  4843. $this->proximity = $name;
  4844. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4845. $lp_id = $this->get_id();
  4846. $sql
  4847. = "UPDATE $lp_table SET
  4848. content_local = '".Database::escape_string($name)."'
  4849. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4850. if ($this->debug > 2) {
  4851. error_log('New LP - lp updated with new proximity : '.$this->proximity, 0);
  4852. }
  4853. Database::query($sql);
  4854. return true;
  4855. }
  4856. /**
  4857. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item
  4858. * @param integer DB ID of the item
  4859. */
  4860. public function set_previous_item($id)
  4861. {
  4862. if ($this->debug > 0) {
  4863. error_log('New LP - In learnpath::set_previous_item()', 0);
  4864. }
  4865. $this->last = $id;
  4866. }
  4867. /**
  4868. * Sets use_max_score
  4869. * @param string $use_max_score Optional string giving the new location of this learnpath
  4870. * @return boolean True on success / False on error
  4871. */
  4872. public function set_use_max_score($use_max_score = 1)
  4873. {
  4874. $course_id = api_get_course_int_id();
  4875. if ($this->debug > 0) {
  4876. error_log('New LP - In learnpath::set_use_max_score()', 0);
  4877. }
  4878. $use_max_score = intval($use_max_score);
  4879. $this->use_max_score = $use_max_score;
  4880. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4881. $lp_id = $this->get_id();
  4882. $sql
  4883. = "UPDATE $lp_table SET
  4884. use_max_score = '".$this->use_max_score."'
  4885. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4886. if ($this->debug > 2) {
  4887. error_log('New LP - lp updated with new use_max_score : '.$this->use_max_score, 0);
  4888. }
  4889. Database::query($sql);
  4890. return true;
  4891. }
  4892. /**
  4893. * Sets and saves the expired_on date
  4894. * @param string $expired_on Optional string giving the new author of this learnpath
  4895. * @return bool Returns true if author's name is not empty
  4896. */
  4897. public function set_expired_on($expired_on)
  4898. {
  4899. if ($this->debug > 0) {
  4900. error_log('New LP - In learnpath::set_expired_on()', 0);
  4901. }
  4902. $em = Database::getManager();
  4903. /** @var CLp $lp */
  4904. $lp = $em
  4905. ->getRepository('ChamiloCourseBundle:CLp')
  4906. ->findOneBy(['id' => $this->get_id(), 'cId' => api_get_course_int_id()]);
  4907. if (!$lp) {
  4908. return false;
  4909. }
  4910. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4911. $lp->setExpiredOn($this->expired_on);
  4912. $em->persist($lp);
  4913. $em->flush();
  4914. if ($this->debug > 2) {
  4915. error_log('New LP - lp updated with new expired_on : '.$this->expired_on, 0);
  4916. }
  4917. return true;
  4918. }
  4919. /**
  4920. * Sets and saves the publicated_on date
  4921. * @param string $publicated_on Optional string giving the new author of this learnpath
  4922. * @return bool Returns true if author's name is not empty
  4923. */
  4924. public function set_publicated_on($publicated_on)
  4925. {
  4926. if ($this->debug > 0) {
  4927. error_log('New LP - In learnpath::set_expired_on()', 0);
  4928. }
  4929. $em = Database::getManager();
  4930. /** @var CLp $lp */
  4931. $lp = $em
  4932. ->getRepository('ChamiloCourseBundle:CLp')
  4933. ->findOneBy(['id' => $this->get_id(), 'cId' => api_get_course_int_id()]);
  4934. if (!$lp) {
  4935. return false;
  4936. }
  4937. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4938. $lp->setPublicatedOn($this->publicated_on);
  4939. $em->persist($lp);
  4940. $em->flush();
  4941. if ($this->debug > 2) {
  4942. error_log('New LP - lp updated with new publicated_on : '.$this->publicated_on, 0);
  4943. }
  4944. return true;
  4945. }
  4946. /**
  4947. * Sets and saves the expired_on date
  4948. * @return bool Returns true if author's name is not empty
  4949. */
  4950. public function set_modified_on()
  4951. {
  4952. $course_id = api_get_course_int_id();
  4953. if ($this->debug > 0) {
  4954. error_log('New LP - In learnpath::set_expired_on()', 0);
  4955. }
  4956. $this->modified_on = api_get_utc_datetime();
  4957. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4958. $lp_id = $this->get_id();
  4959. $sql = "UPDATE $lp_table SET modified_on = '".$this->modified_on."'
  4960. WHERE c_id = ".$course_id." AND id = '$lp_id'";
  4961. if ($this->debug > 2) {
  4962. error_log('New LP - lp updated with new expired_on : '.$this->modified_on, 0);
  4963. }
  4964. Database::query($sql);
  4965. return true;
  4966. }
  4967. /**
  4968. * Sets the object's error message
  4969. * @param string Error message. If empty, reinits the error string
  4970. * @return void
  4971. */
  4972. public function set_error_msg($error = '')
  4973. {
  4974. if ($this->debug > 0) {
  4975. error_log('New LP - In learnpath::set_error_msg()', 0);
  4976. }
  4977. if (empty ($error)) {
  4978. $this->error = '';
  4979. } else {
  4980. $this->error .= $error;
  4981. }
  4982. }
  4983. /**
  4984. * Launches the current item if not 'sco'
  4985. * (starts timer and make sure there is a record ready in the DB)
  4986. * @param boolean $allow_new_attempt Whether to allow a new attempt or not
  4987. * @return boolean
  4988. */
  4989. public function start_current_item($allow_new_attempt = false)
  4990. {
  4991. if ($this->debug > 0) {
  4992. error_log('New LP - In learnpath::start_current_item()', 0);
  4993. }
  4994. if ($this->current != 0 && is_object($this->items[$this->current])) {
  4995. $type = $this->get_type();
  4996. $item_type = $this->items[$this->current]->get_type();
  4997. if (($type == 2 && $item_type != 'sco') || ($type == 3 && $item_type != 'au')
  4998. || ($type == 1
  4999. && $item_type != TOOL_QUIZ
  5000. && $item_type != TOOL_HOTPOTATOES)
  5001. ) {
  5002. $this->items[$this->current]->open($allow_new_attempt);
  5003. $this->autocomplete_parents($this->current);
  5004. $prereq_check = $this->prerequisites_match($this->current);
  5005. $this->items[$this->current]->save(false, $prereq_check);
  5006. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  5007. }
  5008. // If sco, then it is supposed to have been updated by some other call.
  5009. if ($item_type == 'sco') {
  5010. $this->items[$this->current]->restart();
  5011. }
  5012. }
  5013. if ($this->debug > 0) {
  5014. error_log('New LP - End of learnpath::start_current_item()', 0);
  5015. }
  5016. return true;
  5017. }
  5018. /**
  5019. * Stops the processing and counters for the old item (as held in $this->last)
  5020. * @return boolean True/False
  5021. */
  5022. public function stop_previous_item()
  5023. {
  5024. if ($this->debug > 0) {
  5025. error_log('New LP - In learnpath::stop_previous_item()', 0);
  5026. }
  5027. if ($this->last != 0 && $this->last != $this->current && is_object($this->items[$this->last])) {
  5028. if ($this->debug > 2) {
  5029. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' is object', 0);
  5030. }
  5031. switch ($this->get_type()) {
  5032. case '3':
  5033. if ($this->items[$this->last]->get_type() != 'au') {
  5034. if ($this->debug > 2) {
  5035. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last
  5036. .' in lp_type 3 is <> au', 0);
  5037. }
  5038. $this->items[$this->last]->close();
  5039. //$this->autocomplete_parents($this->last);
  5040. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  5041. } else {
  5042. if ($this->debug > 2) {
  5043. error_log('New LP - In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals',
  5044. 0);
  5045. }
  5046. }
  5047. break;
  5048. case '2':
  5049. if ($this->items[$this->last]->get_type() != 'sco') {
  5050. if ($this->debug > 2) {
  5051. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last
  5052. .' in lp_type 2 is <> sco', 0);
  5053. }
  5054. $this->items[$this->last]->close();
  5055. //$this->autocomplete_parents($this->last);
  5056. //$this->update_queue[$this->last] = $this->items[$this->last]->get_status();
  5057. } else {
  5058. if ($this->debug > 2) {
  5059. error_log('New LP - In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals',
  5060. 0);
  5061. }
  5062. }
  5063. break;
  5064. case '1':
  5065. default:
  5066. if ($this->debug > 2) {
  5067. error_log('New LP - In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset',
  5068. 0);
  5069. }
  5070. $this->items[$this->last]->close();
  5071. break;
  5072. }
  5073. } else {
  5074. if ($this->debug > 2) {
  5075. error_log('New LP - In learnpath::stop_previous_item() - No previous element found, ignoring...', 0);
  5076. }
  5077. return false;
  5078. }
  5079. return true;
  5080. }
  5081. /**
  5082. * Updates the default view mode from fullscreen to embedded and inversely
  5083. * @return string The current default view mode ('fullscreen' or 'embedded')
  5084. */
  5085. public function update_default_view_mode()
  5086. {
  5087. $course_id = api_get_course_int_id();
  5088. if ($this->debug > 0) {
  5089. error_log('New LP - In learnpath::update_default_view_mode()', 0);
  5090. }
  5091. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5092. $sql
  5093. = "SELECT * FROM $lp_table
  5094. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5095. $res = Database::query($sql);
  5096. if (Database::num_rows($res) > 0) {
  5097. $row = Database::fetch_array($res);
  5098. $default_view_mode = $row['default_view_mod'];
  5099. $view_mode = $default_view_mode;
  5100. switch ($default_view_mode) {
  5101. case 'fullscreen': // default with popup
  5102. $view_mode = 'embedded';
  5103. break;
  5104. case 'embedded': // default view with left menu
  5105. $view_mode = 'embedframe';
  5106. break;
  5107. case 'embedframe': //folded menu
  5108. $view_mode = 'impress';
  5109. break;
  5110. case 'impress':
  5111. $view_mode = 'fullscreen';
  5112. break;
  5113. }
  5114. $sql
  5115. = "UPDATE $lp_table SET default_view_mod = '$view_mode'
  5116. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5117. Database::query($sql);
  5118. $this->mode = $view_mode;
  5119. return $view_mode;
  5120. } else {
  5121. if ($this->debug > 2) {
  5122. error_log('New LP - Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5123. }
  5124. }
  5125. return -1;
  5126. }
  5127. /**
  5128. * Updates the default behaviour about auto-commiting SCORM updates
  5129. * @return boolean True if auto-commit has been set to 'on', false otherwise
  5130. */
  5131. public function update_default_scorm_commit()
  5132. {
  5133. $course_id = api_get_course_int_id();
  5134. if ($this->debug > 0) {
  5135. error_log('New LP - In learnpath::update_default_scorm_commit()', 0);
  5136. }
  5137. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5138. $sql
  5139. = "SELECT * FROM $lp_table
  5140. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5141. $res = Database::query($sql);
  5142. if (Database::num_rows($res) > 0) {
  5143. $row = Database::fetch_array($res);
  5144. $force = $row['force_commit'];
  5145. if ($force == 1) {
  5146. $force = 0;
  5147. $force_return = false;
  5148. } elseif ($force == 0) {
  5149. $force = 1;
  5150. $force_return = true;
  5151. }
  5152. $sql
  5153. = "UPDATE $lp_table SET force_commit = $force
  5154. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5155. Database::query($sql);
  5156. $this->force_commit = $force_return;
  5157. return $force_return;
  5158. } else {
  5159. if ($this->debug > 2) {
  5160. error_log('New LP - Problem in update_default_scorm_commit() - could not find LP '.$this->get_id()
  5161. .' in DB', 0);
  5162. }
  5163. }
  5164. return -1;
  5165. }
  5166. /**
  5167. * Updates the order of learning paths (goes through all of them by order and fills the gaps)
  5168. * @return bool True on success, false on failure
  5169. */
  5170. public function update_display_order()
  5171. {
  5172. $course_id = api_get_course_int_id();
  5173. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5174. $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." ORDER BY display_order";
  5175. $res = Database::query($sql);
  5176. if ($res === false) {
  5177. return false;
  5178. }
  5179. $num = Database::num_rows($res);
  5180. // First check the order is correct, globally (might be wrong because
  5181. // of versions < 1.8.4).
  5182. if ($num > 0) {
  5183. $i = 1;
  5184. while ($row = Database::fetch_array($res)) {
  5185. if ($row['display_order'] != $i) {
  5186. // If we find a gap in the order, we need to fix it.
  5187. $sql
  5188. = "UPDATE $lp_table SET display_order = $i
  5189. WHERE c_id = ".$course_id." AND id = ".$row['id'];
  5190. Database::query($sql);
  5191. }
  5192. $i++;
  5193. }
  5194. }
  5195. return true;
  5196. }
  5197. /**
  5198. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view
  5199. * @return boolean True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5200. */
  5201. public function update_reinit()
  5202. {
  5203. $course_id = api_get_course_int_id();
  5204. if ($this->debug > 0) {
  5205. error_log('New LP - In learnpath::update_reinit()', 0);
  5206. }
  5207. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5208. $sql
  5209. = "SELECT * FROM $lp_table
  5210. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5211. $res = Database::query($sql);
  5212. if (Database::num_rows($res) > 0) {
  5213. $row = Database::fetch_array($res);
  5214. $force = $row['prevent_reinit'];
  5215. if ($force == 1) {
  5216. $force = 0;
  5217. } elseif ($force == 0) {
  5218. $force = 1;
  5219. }
  5220. $sql
  5221. = "UPDATE $lp_table SET prevent_reinit = $force
  5222. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5223. Database::query($sql);
  5224. $this->prevent_reinit = $force;
  5225. return $force;
  5226. } else {
  5227. if ($this->debug > 2) {
  5228. error_log('New LP - Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5229. }
  5230. }
  5231. return -1;
  5232. }
  5233. /**
  5234. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag
  5235. * @return string 'single', 'multi' or 'seriousgame'
  5236. * @author ndiechburg <noel@cblue.be>
  5237. **/
  5238. public function get_attempt_mode()
  5239. {
  5240. //Set default value for seriousgame_mode
  5241. if (!isset($this->seriousgame_mode)) {
  5242. $this->seriousgame_mode = 0;
  5243. }
  5244. // Set default value for prevent_reinit
  5245. if (!isset($this->prevent_reinit)) {
  5246. $this->prevent_reinit = 1;
  5247. }
  5248. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5249. return 'seriousgame';
  5250. }
  5251. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5252. return 'single';
  5253. }
  5254. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5255. return 'multiple';
  5256. }
  5257. return 'single';
  5258. }
  5259. /**
  5260. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags
  5261. * @param string 'seriousgame', 'single' or 'multiple'
  5262. * @return boolean
  5263. * @author ndiechburg <noel@cblue.be>
  5264. **/
  5265. public function set_attempt_mode($mode)
  5266. {
  5267. $course_id = api_get_course_int_id();
  5268. switch ($mode) {
  5269. case 'seriousgame':
  5270. $sg_mode = 1;
  5271. $prevent_reinit = 1;
  5272. break;
  5273. case 'single':
  5274. $sg_mode = 0;
  5275. $prevent_reinit = 1;
  5276. break;
  5277. case 'multiple':
  5278. $sg_mode = 0;
  5279. $prevent_reinit = 0;
  5280. break;
  5281. default:
  5282. $sg_mode = 0;
  5283. $prevent_reinit = 0;
  5284. break;
  5285. }
  5286. $this->prevent_reinit = $prevent_reinit;
  5287. $this->seriousgame_mode = $sg_mode;
  5288. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5289. $sql
  5290. = "UPDATE $lp_table SET
  5291. prevent_reinit = $prevent_reinit ,
  5292. seriousgame_mode = $sg_mode
  5293. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5294. $res = Database::query($sql);
  5295. if ($res) {
  5296. return true;
  5297. } else {
  5298. return false;
  5299. }
  5300. }
  5301. /**
  5302. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm)
  5303. * @return boolean
  5304. * @author ndiechburg <noel@cblue.be>
  5305. **/
  5306. public function switch_attempt_mode()
  5307. {
  5308. if ($this->debug > 0) {
  5309. error_log('New LP - In learnpath::switch_attempt_mode()', 0);
  5310. }
  5311. $mode = $this->get_attempt_mode();
  5312. switch ($mode) {
  5313. case 'single':
  5314. $next_mode = 'multiple';
  5315. break;
  5316. case 'multiple':
  5317. $next_mode = 'seriousgame';
  5318. break;
  5319. case 'seriousgame':
  5320. $next_mode = 'single';
  5321. break;
  5322. default:
  5323. $next_mode = 'single';
  5324. break;
  5325. }
  5326. $this->set_attempt_mode($next_mode);
  5327. }
  5328. /**
  5329. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5330. * but possibility to do again a completed item.
  5331. * @return boolean true if seriousgame_mode has been set to 1, false otherwise
  5332. * @author ndiechburg <noel@cblue.be>
  5333. **/
  5334. public function set_seriousgame_mode()
  5335. {
  5336. $course_id = api_get_course_int_id();
  5337. if ($this->debug > 0) {
  5338. error_log('New LP - In learnpath::set_seriousgame_mode()', 0);
  5339. }
  5340. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5341. $sql = "SELECT * FROM $lp_table WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5342. $res = Database::query($sql);
  5343. if (Database::num_rows($res) > 0) {
  5344. $row = Database::fetch_array($res);
  5345. $force = $row['seriousgame_mode'];
  5346. if ($force == 1) {
  5347. $force = 0;
  5348. } elseif ($force == 0) {
  5349. $force = 1;
  5350. }
  5351. $sql
  5352. = "UPDATE $lp_table SET seriousgame_mode = $force
  5353. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5354. Database::query($sql);
  5355. $this->seriousgame_mode = $force;
  5356. return $force;
  5357. } else {
  5358. if ($this->debug > 2) {
  5359. error_log('New LP - Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB',
  5360. 0);
  5361. }
  5362. }
  5363. return -1;
  5364. }
  5365. /**
  5366. * Updates the "scorm_debug" value that shows or hide the debug window
  5367. * @return boolean True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5368. */
  5369. public function update_scorm_debug()
  5370. {
  5371. $course_id = api_get_course_int_id();
  5372. if ($this->debug > 0) {
  5373. error_log('New LP - In learnpath::update_scorm_debug()', 0);
  5374. }
  5375. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5376. $sql
  5377. = "SELECT * FROM $lp_table
  5378. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5379. $res = Database::query($sql);
  5380. if (Database::num_rows($res) > 0) {
  5381. $row = Database::fetch_array($res);
  5382. $force = $row['debug'];
  5383. if ($force == 1) {
  5384. $force = 0;
  5385. } elseif ($force == 0) {
  5386. $force = 1;
  5387. }
  5388. $sql
  5389. = "UPDATE $lp_table SET debug = $force
  5390. WHERE c_id = ".$course_id." AND id = ".$this->get_id();
  5391. Database::query($sql);
  5392. $this->scorm_debug = $force;
  5393. return $force;
  5394. } else {
  5395. if ($this->debug > 2) {
  5396. error_log('New LP - Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5397. }
  5398. }
  5399. return -1;
  5400. }
  5401. /**
  5402. * Function that makes a call to the function sort_tree_array and create_tree_array
  5403. * @author Kevin Van Den Haute
  5404. * @param array
  5405. */
  5406. public function tree_array($array)
  5407. {
  5408. if ($this->debug > 1) {
  5409. error_log('New LP - In learnpath::tree_array()', 0);
  5410. }
  5411. $array = $this->sort_tree_array($array);
  5412. $this->create_tree_array($array);
  5413. }
  5414. /**
  5415. * Creates an array with the elements of the learning path tree in it
  5416. * @author Kevin Van Den Haute
  5417. * @param array $array
  5418. * @param int $parent
  5419. * @param int $depth
  5420. * @param array $tmp
  5421. */
  5422. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = array())
  5423. {
  5424. if ($this->debug > 1) {
  5425. error_log('New LP - In learnpath::create_tree_array())', 0);
  5426. }
  5427. if (is_array($array)) {
  5428. for ($i = 0; $i < count($array); $i++) {
  5429. if ($array[$i]['parent_item_id'] == $parent) {
  5430. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5431. $tmp[] = $array[$i]['parent_item_id'];
  5432. $depth++;
  5433. }
  5434. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5435. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5436. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5437. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score'])
  5438. ? $array[$i]['prerequisite_min_score'] : null;
  5439. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score'])
  5440. ? $array[$i]['prerequisite_max_score'] : null;
  5441. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5442. $this->arrMenu[] = array(
  5443. 'id' => $array[$i]['id'],
  5444. 'ref' => $ref,
  5445. 'item_type' => $array[$i]['item_type'],
  5446. 'title' => $array[$i]['title'],
  5447. 'path' => $path,
  5448. 'description' => $array[$i]['description'],
  5449. 'parent_item_id' => $array[$i]['parent_item_id'],
  5450. 'previous_item_id' => $array[$i]['previous_item_id'],
  5451. 'next_item_id' => $array[$i]['next_item_id'],
  5452. 'min_score' => $array[$i]['min_score'],
  5453. 'max_score' => $array[$i]['max_score'],
  5454. 'mastery_score' => $array[$i]['mastery_score'],
  5455. 'display_order' => $array[$i]['display_order'],
  5456. 'prerequisite' => $preq,
  5457. 'depth' => $depth,
  5458. 'audio' => $audio,
  5459. 'prerequisite_min_score' => $prerequisiteMinScore,
  5460. 'prerequisite_max_score' => $prerequisiteMaxScore
  5461. );
  5462. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5463. }
  5464. }
  5465. }
  5466. }
  5467. /**
  5468. * Sorts a multi dimensional array by parent id and display order
  5469. * @author Kevin Van Den Haute
  5470. * @param array $array (array with al the learning path items in it)
  5471. * @return array
  5472. */
  5473. public function sort_tree_array($array)
  5474. {
  5475. foreach ($array as $key => $row) {
  5476. $parent[$key] = $row['parent_item_id'];
  5477. $position[$key] = $row['display_order'];
  5478. }
  5479. if (count($array) > 0) {
  5480. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5481. }
  5482. return $array;
  5483. }
  5484. /**
  5485. * Function that creates a html list of learning path items so that we can add audio files to them
  5486. * @author Kevin Van Den Haute
  5487. * @return string
  5488. */
  5489. public function overview()
  5490. {
  5491. if ($this->debug > 0) {
  5492. error_log('New LP - In learnpath::overview()', 0);
  5493. }
  5494. $_SESSION['gradebook'] = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : null;
  5495. $return = '';
  5496. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5497. // we need to start a form when we want to update all the mp3 files
  5498. if ($update_audio == 'true') {
  5499. $return .= '<form action="'.api_get_self().'?'.api_get_cidreq().'&updateaudio='
  5500. .Security::remove_XSS($_GET['updateaudio']).'&action='.Security::remove_XSS($_GET['action']).'&lp_id='
  5501. .$_SESSION['oLP']->lp_id
  5502. .'" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
  5503. }
  5504. $return .= '<div id="message"></div>';
  5505. if (count($this->items) == 0) {
  5506. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5507. } else {
  5508. $return_audio = '<table class="data_table">';
  5509. $return_audio .= '<tr>';
  5510. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5511. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5512. $return_audio .= '</tr>';
  5513. if ($update_audio != 'true') {
  5514. $return .= '<div class="col-md-12">';
  5515. $return .= self::return_new_tree($update_audio);
  5516. $return .= '</div>';
  5517. $return .= Display::div(
  5518. Display::url(get_lang('Save'), '#', array('id' => 'listSubmit', 'class' => 'btn btn-primary')),
  5519. array('style' => 'float:left; margin-top:15px;width:100%')
  5520. );
  5521. } else {
  5522. $return_audio .= self::return_new_tree($update_audio);
  5523. $return .= $return_audio.'</table>';
  5524. }
  5525. // We need to close the form when we are updating the mp3 files.
  5526. if ($update_audio == 'true') {
  5527. $return .= '<div class="footer-audio">';
  5528. $return .= Display::button(
  5529. 'save_audio',
  5530. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5531. array('class' => 'btn btn-primary', 'type' => 'submit')
  5532. );
  5533. $return .= '</div>';
  5534. }
  5535. }
  5536. // We need to close the form when we are updating the mp3 files.
  5537. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5538. $return .= '</form>';
  5539. }
  5540. return $return;
  5541. }
  5542. /**
  5543. * @param string string $update_audio
  5544. * @param bool $drop_element_here
  5545. * @return string
  5546. */
  5547. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5548. {
  5549. $return = '';
  5550. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5551. $course_id = api_get_course_int_id();
  5552. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  5553. $sql
  5554. = "SELECT * FROM $tbl_lp_item
  5555. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5556. $result = Database::query($sql);
  5557. $arrLP = array();
  5558. while ($row = Database::fetch_array($result)) {
  5559. $arrLP[] = array(
  5560. 'id' => $row['id'],
  5561. 'item_type' => $row['item_type'],
  5562. 'title' => Security::remove_XSS($row['title']),
  5563. 'path' => $row['path'],
  5564. 'description' => Security::remove_XSS($row['description']),
  5565. 'parent_item_id' => $row['parent_item_id'],
  5566. 'previous_item_id' => $row['previous_item_id'],
  5567. 'next_item_id' => $row['next_item_id'],
  5568. 'max_score' => $row['max_score'],
  5569. 'min_score' => $row['min_score'],
  5570. 'mastery_score' => $row['mastery_score'],
  5571. 'prerequisite' => $row['prerequisite'],
  5572. 'display_order' => $row['display_order'],
  5573. 'audio' => $row['audio'],
  5574. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5575. 'prerequisite_min_score' => $row['prerequisite_min_score']
  5576. );
  5577. }
  5578. $this->tree_array($arrLP);
  5579. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  5580. unset($this->arrMenu);
  5581. $default_data = null;
  5582. $default_content = null;
  5583. $elements = array();
  5584. $return_audio = null;
  5585. for ($i = 0; $i < count($arrLP); $i++) {
  5586. $title = $arrLP[$i]['title'];
  5587. $title_cut = cut($arrLP[$i]['title'], 25);
  5588. // Link for the documents
  5589. if ($arrLP[$i]['item_type'] == 'document') {
  5590. $url = api_get_self().'?'.api_get_cidreq().'&action=view_item&mode=preview_document&id='
  5591. .$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5592. $title_cut = Display::url(
  5593. $title_cut,
  5594. $url,
  5595. array(
  5596. 'class' => 'ajax moved',
  5597. 'data-title' => $title_cut
  5598. )
  5599. );
  5600. }
  5601. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5602. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5603. Session::write('pathItem', $arrLP[$i]['path']);
  5604. }
  5605. if (($i % 2) == 0) {
  5606. $oddClass = 'row_odd';
  5607. } else {
  5608. $oddClass = 'row_even';
  5609. }
  5610. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5611. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5612. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  5613. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5614. } else {
  5615. if (file_exists('../img/lp_'.$icon_name.'.gif')) {
  5616. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5617. } else {
  5618. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5619. $icon = Display::return_icon('certificate.png');
  5620. } else {
  5621. $icon = Display::return_icon('folder_document.gif');
  5622. }
  5623. }
  5624. }
  5625. // The audio column.
  5626. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5627. $audio = '';
  5628. if (!$update_audio || $update_audio <> 'true') {
  5629. if (empty($arrLP[$i]['audio'])) {
  5630. $audio .= '';
  5631. }
  5632. } else {
  5633. $types = self::getChapterTypes();
  5634. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5635. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5636. if (!empty ($arrLP[$i]['audio'])) {
  5637. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5638. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id']
  5639. .'" />'.get_lang('RemoveAudio');
  5640. }
  5641. }
  5642. }
  5643. $return_audio .= Display::span($icon.' '.$title).Display::tag('td', $audio, array('style' => ''));
  5644. $return_audio .= '</td>';
  5645. $move_icon = '';
  5646. $move_item_icon = '';
  5647. $edit_icon = '';
  5648. $delete_icon = '';
  5649. $audio_icon = '';
  5650. $prerequisities_icon = '';
  5651. $forumIcon = '';
  5652. $previewIcon = '';
  5653. if ($is_allowed_to_edit) {
  5654. if (!$update_audio || $update_audio <> 'true') {
  5655. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5656. $move_icon .= '<a class="moved" href="#">';
  5657. $move_icon .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(),
  5658. ICON_SIZE_TINY);
  5659. $move_icon .= '</a>';
  5660. }
  5661. }
  5662. // No edit for this item types
  5663. if (!in_array($arrLP[$i]['item_type'], array('sco', 'asset', 'final_item'))) {
  5664. if ($arrLP[$i]['item_type'] != 'dir') {
  5665. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&view=build&id='
  5666. .$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path']
  5667. .'" class="btn btn-default">';
  5668. $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(),
  5669. ICON_SIZE_TINY);
  5670. $edit_icon .= '</a>';
  5671. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5672. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5673. $this->course_int_id,
  5674. $this->lp_session_id
  5675. );
  5676. if ($forumThread) {
  5677. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5678. 'action' => 'dissociate_forum',
  5679. 'id' => $arrLP[$i]['id'],
  5680. 'lp_id' => $this->lp_id
  5681. ]);
  5682. $forumIcon = Display::url(
  5683. Display::return_icon('forum.png', get_lang('DissociateForumToLPItem'), [],
  5684. ICON_SIZE_TINY),
  5685. $forumIconUrl,
  5686. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5687. );
  5688. } else {
  5689. $forumIconUrl = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  5690. 'action' => 'create_forum',
  5691. 'id' => $arrLP[$i]['id'],
  5692. 'lp_id' => $this->lp_id
  5693. ]);
  5694. $forumIcon = Display::url(
  5695. Display::return_icon('forum.png', get_lang('AssociateForumToLPItem'), [],
  5696. ICON_SIZE_TINY),
  5697. $forumIconUrl,
  5698. ['class' => "btn btn-default lp-btn-associate-forum"]
  5699. );
  5700. }
  5701. }
  5702. } else {
  5703. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='
  5704. .$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path']
  5705. .'" class="btn btn-default">';
  5706. $edit_icon .= Display::return_icon('edit.png', get_lang('LearnpathEditModule'), array(),
  5707. ICON_SIZE_TINY);
  5708. $edit_icon .= '</a>';
  5709. }
  5710. } else {
  5711. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5712. $edit_icon .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=edit_item&id='
  5713. .$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5714. $edit_icon .= Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_TINY);
  5715. $edit_icon .= '</a>';
  5716. }
  5717. }
  5718. $delete_icon .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=delete_item&id='
  5719. .$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" onclick="return confirmation(\''.addslashes($title)
  5720. .'\');" class="btn btn-default">';
  5721. $delete_icon .= Display::return_icon(
  5722. 'delete.png',
  5723. get_lang('LearnpathDeleteModule'),
  5724. [],
  5725. ICON_SIZE_TINY
  5726. );
  5727. $delete_icon .= '</a>';
  5728. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5729. $previewImage = Display::return_icon(
  5730. 'preview_view.png',
  5731. get_lang('Preview'),
  5732. [],
  5733. ICON_SIZE_TINY
  5734. );
  5735. switch ($arrLP[$i]['item_type']) {
  5736. case TOOL_DOCUMENT:
  5737. case TOOL_LP_FINAL_ITEM:
  5738. $urlPreviewLink = api_get_self().'?'.api_get_cidreq()
  5739. .'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5740. $previewIcon = Display::url(
  5741. $previewImage,
  5742. $urlPreviewLink,
  5743. array(
  5744. 'target' => '_blank',
  5745. 'class' => 'btn btn-default',
  5746. 'data-title' => $arrLP[$i]['title']
  5747. )
  5748. );
  5749. break;
  5750. case TOOL_THREAD:
  5751. case TOOL_FORUM:
  5752. case TOOL_QUIZ:
  5753. case TOOL_STUDENTPUBLICATION:
  5754. case TOOL_LP_FINAL_ITEM:
  5755. case TOOL_LINK:
  5756. //$target = '';
  5757. //$class = 'btn btn-default ajax';
  5758. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5759. $class = 'btn btn-default';
  5760. $target = '_blank';
  5761. //}
  5762. $link = self::rl_get_resource_link_for_learnpath(
  5763. $this->course_int_id,
  5764. $this->lp_id,
  5765. $arrLP[$i]['id'],
  5766. 0,
  5767. ''
  5768. );
  5769. $previewIcon = Display::url(
  5770. $previewImage,
  5771. $link,
  5772. [
  5773. 'class' => $class,
  5774. 'data-title' => $arrLP[$i]['title'],
  5775. 'target' => $target
  5776. ]
  5777. );
  5778. break;
  5779. default:
  5780. $previewIcon = Display::url(
  5781. $previewImage,
  5782. $url.'&action=view_item',
  5783. ['class' => 'btn btn-default', 'target' => '_blank']
  5784. );
  5785. break;
  5786. }
  5787. if ($arrLP[$i]['item_type'] != 'dir') {
  5788. $prerequisities_icon = Display::url(
  5789. Display::return_icon(
  5790. 'accept.png',
  5791. get_lang('LearnpathPrerequisites'),
  5792. array(),
  5793. ICON_SIZE_TINY
  5794. ),
  5795. $url.'&action=edit_item_prereq', ['class' => 'btn btn-default']
  5796. );
  5797. if ($arrLP[$i]['item_type'] != 'final_item') {
  5798. $move_item_icon = Display::url(
  5799. Display::return_icon(
  5800. 'move.png',
  5801. get_lang('Move'),
  5802. array(),
  5803. ICON_SIZE_TINY
  5804. ),
  5805. $url.'&action=move_item',
  5806. ['class' => 'btn btn-default']
  5807. );
  5808. }
  5809. $audio_icon = Display::url(
  5810. Display::return_icon('audio.png', get_lang('UplUpload'), array(), ICON_SIZE_TINY),
  5811. $url.'&action=add_audio',
  5812. ['class' => 'btn btn-default']
  5813. );
  5814. }
  5815. }
  5816. if ($update_audio != 'true') {
  5817. $row = $move_icon.' '.$icon.
  5818. Display::span($title_cut).
  5819. Display::tag(
  5820. 'div',
  5821. "<div class=\"btn-group btn-group-xs\">$previewIcon $audio $edit_icon $forumIcon $prerequisities_icon $move_item_icon $audio_icon $delete_icon</div>",
  5822. array('class' => 'btn-toolbar button_actions')
  5823. );
  5824. } else {
  5825. $row = Display::span($title.$icon).Display::span($audio, array('class' => 'button_actions'));
  5826. }
  5827. $parent_id = $arrLP[$i]['parent_item_id'];
  5828. $default_data[$arrLP[$i]['id']] = $row;
  5829. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5830. if (empty($parent_id)) {
  5831. $elements[$arrLP[$i]['id']]['data'] = $row;
  5832. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5833. } else {
  5834. $parent_arrays = array();
  5835. if ($arrLP[$i]['depth'] > 1) {
  5836. //Getting list of parents
  5837. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5838. foreach ($arrLP as $item) {
  5839. if ($item['id'] == $parent_id) {
  5840. if ($item['parent_item_id'] == 0) {
  5841. $parent_id = $item['id'];
  5842. break;
  5843. } else {
  5844. $parent_id = $item['parent_item_id'];
  5845. if (empty($parent_arrays)) {
  5846. $parent_arrays[] = intval($item['id']);
  5847. }
  5848. $parent_arrays[] = $parent_id;
  5849. break;
  5850. }
  5851. }
  5852. }
  5853. }
  5854. }
  5855. if (!empty($parent_arrays)) {
  5856. $parent_arrays = array_reverse($parent_arrays);
  5857. $val = '$elements';
  5858. $x = 0;
  5859. foreach ($parent_arrays as $item) {
  5860. if ($x != count($parent_arrays) - 1) {
  5861. $val .= '["'.$item.'"]["children"]';
  5862. } else {
  5863. $val .= '["'.$item.'"]["children"]';
  5864. }
  5865. $x++;
  5866. }
  5867. $val .= "";
  5868. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5869. eval($code_str);
  5870. } else {
  5871. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5872. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5873. }
  5874. }
  5875. }
  5876. $list = '<ul id="lp_item_list">';
  5877. $tree = self::print_recursive($elements, $default_data, $default_content);
  5878. if (!empty($tree)) {
  5879. $list .= $tree;
  5880. } else {
  5881. if ($drop_element_here) {
  5882. $list .= Display::return_message(get_lang("DragAndDropAnElementHere"));
  5883. }
  5884. }
  5885. $list .= '</ul>';
  5886. $return .= Display::panelCollapse(
  5887. $this->name,
  5888. $list,
  5889. 'scorm-list',
  5890. null,
  5891. 'scorm-list-accordion',
  5892. 'scorm-list-collapse'
  5893. );
  5894. if ($update_audio == 'true') {
  5895. $return = $return_audio;
  5896. }
  5897. return $return;
  5898. }
  5899. /**
  5900. * @param array $elements
  5901. * @param array $default_data
  5902. * @param array $default_content
  5903. * @return string
  5904. */
  5905. public function print_recursive($elements, $default_data, $default_content)
  5906. {
  5907. $return = '';
  5908. foreach ($elements as $key => $item) {
  5909. if (isset($item['load_data']) || empty($item['data'])) {
  5910. $item['data'] = $default_data[$item['load_data']];
  5911. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5912. }
  5913. $sub_list = '';
  5914. if (isset($item['type']) && $item['type'] == 'dir') {
  5915. $sub_list = Display::tag('li', '', array('class' => 'sub_item empty')); // empty value
  5916. }
  5917. if (empty($item['children'])) {
  5918. $sub_list = Display::tag('ul', $sub_list, array('id' => 'UL_'.$key, 'class' => 'record li_container'));
  5919. $active = null;
  5920. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5921. $active = 'active';
  5922. }
  5923. $return .= Display::tag(
  5924. 'li',
  5925. Display::div($item['data'], array('class' => "item_data $active")).$sub_list,
  5926. array('id' => $key, 'class' => 'record li_container')
  5927. );
  5928. } else {
  5929. // Sections
  5930. if (isset($item['children'])) {
  5931. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5932. }
  5933. $sub_list = Display::tag('ul', $sub_list.$data,
  5934. array('id' => 'UL_'.$key, 'class' => 'record li_container'));
  5935. $return .= Display::tag(
  5936. 'li',
  5937. Display::div($item['data'], array('class' => 'item_data')).$sub_list,
  5938. array('id' => $key, 'class' => 'record li_container')
  5939. );
  5940. }
  5941. }
  5942. return $return;
  5943. }
  5944. /**
  5945. * This function builds the action menu
  5946. * @param bool $returnContent Optional
  5947. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5948. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5949. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5950. * @return string
  5951. */
  5952. public function build_action_menu(
  5953. $returnContent = false,
  5954. $showRequirementButtons = true,
  5955. $isConfigPage = false,
  5956. $allowExpand = true
  5957. ) {
  5958. $gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : null;
  5959. $actionsLeft = '';
  5960. $actionsRight = '';
  5961. $actionsLeft .= Display::url(
  5962. Display:: return_icon('preview_view.png', get_lang('Display'), '', ICON_SIZE_MEDIUM),
  5963. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5964. 'gradebook' => $gradebook,
  5965. 'action' => 'view',
  5966. 'lp_id' => $_SESSION['oLP']->lp_id,
  5967. 'isStudentView' => 'true'
  5968. ])
  5969. );
  5970. $actionsLeft .= Display::url(
  5971. Display:: return_icon('upload_audio.png', get_lang('UpdateAllAudioFragments'), '', ICON_SIZE_MEDIUM),
  5972. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5973. 'action' => 'admin_view',
  5974. 'lp_id' => $_SESSION['oLP']->lp_id,
  5975. 'updateaudio' => 'true'
  5976. ])
  5977. );
  5978. if (!$isConfigPage) {
  5979. $actionsLeft .= Display::url(
  5980. Display::return_icon('settings.png', get_lang('CourseSettings'), '', ICON_SIZE_MEDIUM),
  5981. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5982. 'action' => 'edit',
  5983. 'lp_id' => $_SESSION['oLP']->lp_id
  5984. ])
  5985. );
  5986. } else {
  5987. $actionsLeft .= Display::url(
  5988. Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_MEDIUM),
  5989. 'lp_controller.php?'.http_build_query([
  5990. 'action' => 'build',
  5991. 'lp_id' => $_SESSION['oLP']->lp_id
  5992. ]).'&'.api_get_cidreq()
  5993. );
  5994. }
  5995. if ($allowExpand) {
  5996. $actionsLeft .= Display::url(
  5997. Display::return_icon('expand.png', get_lang('Expand'), array('id' => 'expand'), ICON_SIZE_MEDIUM).
  5998. Display::return_icon('contract.png', get_lang('Collapse'), array('id' => 'contract', 'class' => 'hide'),
  5999. ICON_SIZE_MEDIUM),
  6000. '#',
  6001. ['role' => 'button', 'id' => 'hide_bar_template']
  6002. );
  6003. }
  6004. if ($showRequirementButtons) {
  6005. $buttons = array(
  6006. array(
  6007. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6008. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6009. 'action' => 'set_previous_step_as_prerequisite',
  6010. 'lp_id' => $_SESSION['oLP']->lp_id
  6011. ])
  6012. ),
  6013. array(
  6014. 'title' => get_lang('ClearAllPrerequisites'),
  6015. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6016. 'action' => 'clear_prerequisites',
  6017. 'lp_id' => $_SESSION['oLP']->lp_id
  6018. ])
  6019. ),
  6020. );
  6021. $actionsRight = Display::groupButtonWithDropDown(get_lang('PrerequisitesOptions'), $buttons, true);
  6022. }
  6023. $toolbar = Display::toolbarAction('actions-lp-controller', array($actionsLeft, $actionsRight));
  6024. if ($returnContent) {
  6025. return $toolbar;
  6026. }
  6027. echo $toolbar;
  6028. }
  6029. /**
  6030. * Creates the default learning path folder
  6031. * @param array $course
  6032. * @param int $creatorId
  6033. * @return bool
  6034. */
  6035. public static function generate_learning_path_folder($course, $creatorId = 0)
  6036. {
  6037. // Creating learning_path folder
  6038. $dir = '/learning_path';
  6039. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6040. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6041. $folder = false;
  6042. if (!is_dir($filepath.'/'.$dir)) {
  6043. $folderData = create_unexisting_directory(
  6044. $course,
  6045. $creatorId,
  6046. 0,
  6047. 0,
  6048. 0,
  6049. $filepath,
  6050. $dir,
  6051. get_lang('LearningPaths'),
  6052. 0
  6053. );
  6054. if (!empty($folderData)) {
  6055. $folder = true;
  6056. }
  6057. } else {
  6058. $folder = true;
  6059. }
  6060. return $folder;
  6061. }
  6062. /**
  6063. * @param array $course
  6064. * @param string $lp_name
  6065. * @param int $creatorId
  6066. * @return array
  6067. */
  6068. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6069. {
  6070. $filepath = '';
  6071. $dir = '/learning_path/';
  6072. if (empty($lp_name)) {
  6073. $lp_name = $this->name;
  6074. }
  6075. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6076. $folder = self::generate_learning_path_folder($course, $creatorId);
  6077. // Limits title size
  6078. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6079. $dir = $dir.$title;
  6080. // Creating LP folder
  6081. $documentId = null;
  6082. if ($folder) {
  6083. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6084. if (!is_dir($filepath.'/'.$dir)) {
  6085. $folderData = create_unexisting_directory(
  6086. $course,
  6087. $creatorId,
  6088. 0,
  6089. 0,
  6090. 0,
  6091. $filepath,
  6092. $dir,
  6093. $lp_name
  6094. );
  6095. if (!empty($folderData)) {
  6096. $folder = true;
  6097. }
  6098. $documentId = $folderData['id'];
  6099. } else {
  6100. $folder = true;
  6101. }
  6102. $dir = $dir.'/';
  6103. if ($folder) {
  6104. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6105. }
  6106. }
  6107. if (empty($documentId)) {
  6108. $dir = api_remove_trailing_slash($dir);
  6109. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6110. }
  6111. $array = array(
  6112. 'dir' => $dir,
  6113. 'filepath' => $filepath,
  6114. 'folder' => $folder,
  6115. 'id' => $documentId
  6116. );
  6117. return $array;
  6118. }
  6119. /**
  6120. * Create a new document //still needs some finetuning
  6121. * @param array $courseInfo
  6122. * @param string $content
  6123. * @param string $title
  6124. * @param string $extension
  6125. * @param int $parentId
  6126. * @param int $creatorId creator id
  6127. * @return string
  6128. */
  6129. public function create_document(
  6130. $courseInfo,
  6131. $content = '',
  6132. $title = '',
  6133. $extension = 'html',
  6134. $parentId = 0,
  6135. $creatorId = 0
  6136. ) {
  6137. if (!empty($courseInfo)) {
  6138. $course_id = $courseInfo['real_id'];
  6139. } else {
  6140. $course_id = api_get_course_int_id();
  6141. }
  6142. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6143. $sessionId = api_get_session_id();
  6144. // Generates folder
  6145. $result = $this->generate_lp_folder($courseInfo);
  6146. $dir = $result['dir'];
  6147. if (empty($parentId) || $parentId == '/') {
  6148. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6149. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6150. if ($parentId === '/') {
  6151. $dir = '/';
  6152. }
  6153. // Please, do not modify this dirname formatting.
  6154. if (strstr($dir, '..')) {
  6155. $dir = '/';
  6156. }
  6157. if (!empty($dir[0]) && $dir[0] == '.') {
  6158. $dir = substr($dir, 1);
  6159. }
  6160. if (!empty($dir[0]) && $dir[0] != '/') {
  6161. $dir = '/'.$dir;
  6162. }
  6163. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6164. $dir .= '/';
  6165. }
  6166. } else {
  6167. $parentInfo = DocumentManager::get_document_data_by_id($parentId, $courseInfo['code']);
  6168. if (!empty($parentInfo)) {
  6169. $dir = $parentInfo['path'].'/';
  6170. }
  6171. }
  6172. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6173. if (!is_dir($filepath)) {
  6174. $dir = '/';
  6175. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6176. }
  6177. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6178. // is already escaped twice when it gets here.
  6179. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6180. if (!empty($title)) {
  6181. $title = api_replace_dangerous_char(stripslashes($title));
  6182. } else {
  6183. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6184. }
  6185. $title = disable_dangerous_file($title);
  6186. $filename = $title;
  6187. $content = !empty($content) ? $content : $_POST['content_lp'];
  6188. $tmp_filename = $filename;
  6189. $i = 0;
  6190. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6191. $tmp_filename = $filename.'_'.++$i;
  6192. }
  6193. $filename = $tmp_filename.'.'.$extension;
  6194. if ($extension == 'html') {
  6195. $content = stripslashes($content);
  6196. $content = str_replace(
  6197. api_get_path(WEB_COURSE_PATH),
  6198. api_get_path(REL_PATH).'courses/',
  6199. $content
  6200. );
  6201. // Change the path of mp3 to absolute.
  6202. // The first regexp deals with :// urls.
  6203. $content = preg_replace(
  6204. "|(flashvars=\"file=)([^:/]+)/|",
  6205. "$1".api_get_path(
  6206. REL_COURSE_PATH
  6207. ).$courseInfo['path'].'/document/',
  6208. $content
  6209. );
  6210. // The second regexp deals with audio/ urls.
  6211. $content = preg_replace(
  6212. "|(flashvars=\"file=)([^/]+)/|",
  6213. "$1".api_get_path(
  6214. REL_COURSE_PATH
  6215. ).$courseInfo['path'].'/document/$2/',
  6216. $content
  6217. );
  6218. // For flv player: To prevent edition problem with firefox, we have to use a strange tip (don't blame me please).
  6219. $content = str_replace(
  6220. '</body>',
  6221. '<style type="text/css">body{}</style></body>',
  6222. $content
  6223. );
  6224. }
  6225. if (!file_exists($filepath.$filename)) {
  6226. if ($fp = @ fopen($filepath.$filename, 'w')) {
  6227. fputs($fp, $content);
  6228. fclose($fp);
  6229. $file_size = filesize($filepath.$filename);
  6230. $save_file_path = $dir.$filename;
  6231. $document_id = add_document(
  6232. $courseInfo,
  6233. $save_file_path,
  6234. 'file',
  6235. $file_size,
  6236. $tmp_filename,
  6237. '',
  6238. 0, //readonly
  6239. true,
  6240. null,
  6241. $sessionId,
  6242. $creatorId
  6243. );
  6244. if ($document_id) {
  6245. api_item_property_update(
  6246. $courseInfo,
  6247. TOOL_DOCUMENT,
  6248. $document_id,
  6249. 'DocumentAdded',
  6250. $creatorId,
  6251. null,
  6252. null,
  6253. null,
  6254. null,
  6255. $sessionId
  6256. );
  6257. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6258. $new_title = $originalTitle;
  6259. if ($new_comment || $new_title) {
  6260. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6261. $ct = '';
  6262. if ($new_comment) {
  6263. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6264. }
  6265. if ($new_title) {
  6266. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6267. }
  6268. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6269. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6270. Database::query($sql);
  6271. }
  6272. }
  6273. return $document_id;
  6274. }
  6275. }
  6276. }
  6277. /**
  6278. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'
  6279. * @param array $_course array
  6280. * @return void
  6281. */
  6282. public function edit_document($_course)
  6283. {
  6284. $course_id = api_get_course_int_id();
  6285. $urlAppend = api_get_configuration_value('url_append');
  6286. // Please, do not modify this dirname formatting.
  6287. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6288. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6289. if (strstr($dir, '..')) {
  6290. $dir = '/';
  6291. }
  6292. if (isset($dir[0]) && $dir[0] == '.') {
  6293. $dir = substr($dir, 1);
  6294. }
  6295. if (isset($dir[0]) && $dir[0] != '/') {
  6296. $dir = '/'.$dir;
  6297. }
  6298. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6299. $dir .= '/';
  6300. }
  6301. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6302. if (!is_dir($filepath)) {
  6303. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6304. }
  6305. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6306. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6307. $document_id = intval($_POST['path']);
  6308. $sql = "SELECT path FROM ".$table_doc."
  6309. WHERE c_id = $course_id AND id = ".$document_id;
  6310. $res = Database::query($sql);
  6311. $row = Database::fetch_array($res);
  6312. $content = stripslashes($_POST['content_lp']);
  6313. $file = $filepath.$row['path'];
  6314. if ($fp = @ fopen($file, 'w')) {
  6315. $content = str_replace(api_get_path(WEB_COURSE_PATH), $urlAppend.api_get_path(REL_COURSE_PATH),
  6316. $content);
  6317. // Change the path of mp3 to absolute.
  6318. // The first regexp deals with :// urls.
  6319. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|",
  6320. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/', $content);
  6321. // The second regexp deals with audio/ urls.
  6322. $content = preg_replace("|(flashvars=\"file=)([^:/]+)/|",
  6323. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/', $content);
  6324. fputs($fp, $content);
  6325. fclose($fp);
  6326. $sql = "UPDATE ".$table_doc." SET
  6327. title='".Database::escape_string($_POST['title'])."'
  6328. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6329. Database::query($sql);
  6330. }
  6331. }
  6332. }
  6333. /**
  6334. * Displays the selected item, with a panel for manipulating the item
  6335. * @param int $item_id
  6336. * @param string $msg
  6337. * @return string
  6338. */
  6339. public function display_item($item_id, $msg = null, $show_actions = true)
  6340. {
  6341. $course_id = api_get_course_int_id();
  6342. $return = '';
  6343. if (is_numeric($item_id)) {
  6344. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6345. $sql
  6346. = "SELECT lp.* FROM $tbl_lp_item as lp
  6347. WHERE
  6348. c_id = $course_id AND
  6349. lp.id = ".intval($item_id);
  6350. $result = Database::query($sql);
  6351. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6352. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6353. // Prevents wrong parent selection for document, see Bug#1251.
  6354. if ($row['item_type'] != 'dir') {
  6355. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6356. }
  6357. if ($show_actions) {
  6358. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6359. }
  6360. $return .= '<div style="padding:10px;">';
  6361. if ($msg != '') {
  6362. $return .= $msg;
  6363. }
  6364. $return .= '<h3>'.$row['title'].'</h3>';
  6365. switch ($row['item_type']) {
  6366. case TOOL_THREAD:
  6367. $link = $this->rl_get_resource_link_for_learnpath(
  6368. $course_id,
  6369. $row['lp_id'],
  6370. $item_id,
  6371. 0
  6372. );
  6373. $return .= Display::url(
  6374. get_lang('GoToThread'),
  6375. $link,
  6376. ['class' => 'btn btn-primary']
  6377. );
  6378. break;
  6379. case TOOL_FORUM:
  6380. $return .= Display::url(
  6381. get_lang('GoToForum'),
  6382. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6383. ['class' => 'btn btn-primary']
  6384. );
  6385. break;
  6386. case TOOL_QUIZ:
  6387. if (!empty($row['path'])) {
  6388. $exercise = new Exercise();
  6389. $exercise->read($row['path']);
  6390. $return .= $exercise->description.'<br />';
  6391. $return .= Display::url(
  6392. get_lang('GoToExercise'),
  6393. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='
  6394. .$exercise->id,
  6395. ['class' => 'btn btn-primary']
  6396. );
  6397. }
  6398. break;
  6399. case TOOL_LP_FINAL_ITEM:
  6400. $return .= $this->getSavedFinalItem();
  6401. break;
  6402. case TOOL_DOCUMENT:
  6403. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6404. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6405. WHERE c_id = ".$course_id." AND id = ".intval($row['path']);
  6406. $result = Database::query($sql_doc);
  6407. $path_file = Database::result($result, 0, 0);
  6408. $path_parts = pathinfo($path_file);
  6409. // TODO: Correct the following naive comparisons.
  6410. if (in_array($path_parts['extension'], array(
  6411. 'html',
  6412. 'txt',
  6413. 'png',
  6414. 'jpg',
  6415. 'JPG',
  6416. 'jpeg',
  6417. 'JPEG',
  6418. 'gif',
  6419. 'swf',
  6420. 'pdf',
  6421. 'htm'
  6422. ))) {
  6423. $return .= $this->display_document($row['path'], true, true);
  6424. }
  6425. break;
  6426. case TOOL_HOTPOTATOES:
  6427. $return .= $this->display_document($row['path'], false, true);
  6428. break;
  6429. }
  6430. $return .= '</div>';
  6431. }
  6432. }
  6433. return $return;
  6434. }
  6435. /**
  6436. * Shows the needed forms for editing a specific item
  6437. * @param int $item_id
  6438. * @return string
  6439. */
  6440. public function display_edit_item($item_id)
  6441. {
  6442. $course_id = api_get_course_int_id();
  6443. $return = '';
  6444. if (is_numeric($item_id)) {
  6445. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6446. $sql
  6447. = "SELECT * FROM $tbl_lp_item
  6448. WHERE c_id = ".$course_id." AND id = ".intval($item_id);
  6449. $res = Database::query($sql);
  6450. $row = Database::fetch_array($res);
  6451. switch ($row['item_type']) {
  6452. case 'dir':
  6453. case 'asset':
  6454. case 'sco':
  6455. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6456. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6457. $return .= $this->display_item_form(
  6458. $row['item_type'],
  6459. get_lang('EditCurrentChapter').' :',
  6460. 'edit',
  6461. $item_id,
  6462. $row
  6463. );
  6464. } else {
  6465. $return .= $this->display_item_small_form(
  6466. $row['item_type'],
  6467. get_lang('EditCurrentChapter').' :',
  6468. $row
  6469. );
  6470. }
  6471. break;
  6472. case TOOL_DOCUMENT:
  6473. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6474. $sql
  6475. = "SELECT lp.*, doc.path as dir
  6476. FROM $tbl_lp_item as lp
  6477. LEFT JOIN $tbl_doc as doc
  6478. ON (doc.id = lp.path AND lp.c_id = doc.c_id)
  6479. WHERE
  6480. lp.c_id = $course_id AND
  6481. doc.c_id = $course_id AND
  6482. lp.id = ".intval($item_id);
  6483. $res_step = Database::query($sql);
  6484. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6485. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6486. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6487. break;
  6488. case TOOL_LINK:
  6489. $link_id = (string)$row['path'];
  6490. if (ctype_digit($link_id)) {
  6491. $tbl_link = Database::get_course_table(TABLE_LINK);
  6492. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6493. WHERE c_id = '.$course_id.' AND id = '.intval($link_id);
  6494. $res_link = Database::query($sql_select);
  6495. $row_link = Database::fetch_array($res_link);
  6496. if (is_array($row_link)) {
  6497. $row['url'] = $row_link['url'];
  6498. }
  6499. }
  6500. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6501. $return .= $this->display_link_form('edit', $item_id, $row);
  6502. break;
  6503. case TOOL_LP_FINAL_ITEM:
  6504. Session::write('finalItem', true);
  6505. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6506. $sql
  6507. = "SELECT lp.*, doc.path as dir
  6508. FROM $tbl_lp_item as lp
  6509. LEFT JOIN $tbl_doc as doc
  6510. ON (doc.id = lp.path AND lp.c_id = doc.c_id)
  6511. WHERE
  6512. lp.c_id = $course_id AND
  6513. doc.c_id = $course_id AND
  6514. lp.id = ".intval($item_id);
  6515. $res_step = Database::query($sql);
  6516. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6517. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6518. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6519. break;
  6520. case TOOL_QUIZ:
  6521. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6522. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6523. break;
  6524. case TOOL_HOTPOTATOES:
  6525. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6526. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6527. break;
  6528. case TOOL_STUDENTPUBLICATION:
  6529. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6530. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6531. break;
  6532. case TOOL_FORUM:
  6533. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6534. $return .= $this->display_forum_form('edit', $item_id, $row);
  6535. break;
  6536. case TOOL_THREAD:
  6537. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6538. $return .= $this->display_thread_form('edit', $item_id, $row);
  6539. break;
  6540. }
  6541. }
  6542. return $return;
  6543. }
  6544. /**
  6545. * Function that displays a list with al the resources that
  6546. * could be added to the learning path
  6547. * @return string
  6548. */
  6549. public function display_resources()
  6550. {
  6551. $course_code = api_get_course_id();
  6552. // Get all the docs.
  6553. $documents = $this->get_documents(true);
  6554. // Get all the exercises.
  6555. $exercises = $this->get_exercises();
  6556. // Get all the links.
  6557. $links = $this->get_links();
  6558. // Get all the student publications.
  6559. $works = $this->get_student_publications();
  6560. // Get all the forums.
  6561. $forums = $this->get_forums(null, $course_code);
  6562. // Get the final item form (see BT#11048) .
  6563. $finish = $this->getFinalItemForm();
  6564. $headers = array(
  6565. Display::return_icon('folder_document.png', get_lang('Documents'), array(), ICON_SIZE_BIG),
  6566. Display::return_icon('quiz.png', get_lang('Quiz'), array(), ICON_SIZE_BIG),
  6567. Display::return_icon('links.png', get_lang('Links'), array(), ICON_SIZE_BIG),
  6568. Display::return_icon('works.png', get_lang('Works'), array(), ICON_SIZE_BIG),
  6569. Display::return_icon('forum.png', get_lang('Forums'), array(), ICON_SIZE_BIG),
  6570. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), array(), ICON_SIZE_BIG),
  6571. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6572. );
  6573. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6574. $dir = $_SESSION['oLP']->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6575. echo Display::tabs(
  6576. $headers,
  6577. array(
  6578. $documents,
  6579. $exercises,
  6580. $links,
  6581. $works,
  6582. $forums,
  6583. $dir,
  6584. $finish,
  6585. ),
  6586. 'resource_tab'
  6587. );
  6588. return true;
  6589. }
  6590. /**
  6591. * Returns the extension of a document
  6592. * @param string $filename
  6593. * @return string Extension (part after the last dot)
  6594. */
  6595. public function get_extension($filename)
  6596. {
  6597. $explode = explode('.', $filename);
  6598. return $explode[count($explode) - 1];
  6599. }
  6600. /**
  6601. * Displays a document by id
  6602. * @param int $id
  6603. * @return string
  6604. */
  6605. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6606. {
  6607. $_course = api_get_course_info();
  6608. $course_id = api_get_course_int_id();
  6609. $return = '';
  6610. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6611. $sql_doc = "SELECT * FROM ".$tbl_doc."
  6612. WHERE c_id = ".$course_id." AND id = ".$id;
  6613. $res_doc = Database::query($sql_doc);
  6614. $row_doc = Database::fetch_array($res_doc);
  6615. // TODO: Add a path filter.
  6616. if ($iframe) {
  6617. $return .= '<iframe id="learnpath_preview_frame" frameborder="0" height="400" width="100%" scrolling="auto" src="'
  6618. .api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.str_replace('%2F', '/',
  6619. urlencode($row_doc['path'])).'?'.api_get_cidreq().'"></iframe>';
  6620. } else {
  6621. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6622. }
  6623. return $return;
  6624. }
  6625. /**
  6626. * Return HTML form to add/edit a quiz
  6627. * @param string $action Action (add/edit)
  6628. * @param integer $id Item ID if already exists
  6629. * @param mixed $extra_info Extra information (quiz ID if integer)
  6630. * @return string HTML form
  6631. */
  6632. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6633. {
  6634. $course_id = api_get_course_int_id();
  6635. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6636. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6637. if ($id != 0 && is_array($extra_info)) {
  6638. $item_title = $extra_info['title'];
  6639. $item_description = $extra_info['description'];
  6640. } elseif (is_numeric($extra_info)) {
  6641. $sql
  6642. = "SELECT title, description
  6643. FROM $tbl_quiz
  6644. WHERE c_id = $course_id AND id = ".$extra_info;
  6645. $result = Database::query($sql);
  6646. $row = Database::fetch_array($result);
  6647. $item_title = $row['title'];
  6648. $item_description = $row['description'];
  6649. } else {
  6650. $item_title = '';
  6651. $item_description = '';
  6652. }
  6653. $item_title = Security::remove_XSS($item_title);
  6654. $item_description = Security::remove_XSS($item_description);
  6655. if ($id != 0 && is_array($extra_info)) {
  6656. $parent = $extra_info['parent_item_id'];
  6657. } else {
  6658. $parent = 0;
  6659. }
  6660. $sql
  6661. = "SELECT * FROM $tbl_lp_item
  6662. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  6663. $result = Database::query($sql);
  6664. $arrLP = array();
  6665. while ($row = Database::fetch_array($result)) {
  6666. $arrLP[] = array(
  6667. 'id' => $row['id'],
  6668. 'item_type' => $row['item_type'],
  6669. 'title' => $row['title'],
  6670. 'path' => $row['path'],
  6671. 'description' => $row['description'],
  6672. 'parent_item_id' => $row['parent_item_id'],
  6673. 'previous_item_id' => $row['previous_item_id'],
  6674. 'next_item_id' => $row['next_item_id'],
  6675. 'display_order' => $row['display_order'],
  6676. 'max_score' => $row['max_score'],
  6677. 'min_score' => $row['min_score'],
  6678. 'mastery_score' => $row['mastery_score'],
  6679. 'prerequisite' => $row['prerequisite'],
  6680. 'max_time_allowed' => $row['max_time_allowed']
  6681. );
  6682. }
  6683. $this->tree_array($arrLP);
  6684. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  6685. unset($this->arrMenu);
  6686. $form = new FormValidator(
  6687. 'quiz_form',
  6688. 'POST',
  6689. $this->getCurrentBuildingModeURL()
  6690. );
  6691. $defaults = [];
  6692. if ($action == 'add') {
  6693. $legend = get_lang('CreateTheExercise');
  6694. } elseif ($action == 'move') {
  6695. $legend = get_lang('MoveTheCurrentExercise');
  6696. } else {
  6697. $legend = get_lang('EditCurrentExecice');
  6698. }
  6699. if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
  6700. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6701. }
  6702. $form->addHeader($legend);
  6703. if ($action != 'move') {
  6704. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  6705. $defaults['title'] = $item_title;
  6706. }
  6707. // Select for Parent item, root or chapter
  6708. $selectParent = $form->addSelect(
  6709. 'parent',
  6710. get_lang('Parent'),
  6711. [],
  6712. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6713. );
  6714. $selectParent->addOption($this->name, 0);
  6715. $arrHide = array(
  6716. $id
  6717. );
  6718. for ($i = 0; $i < count($arrLP); $i++) {
  6719. if ($action != 'add') {
  6720. if (
  6721. ($arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide)
  6722. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6723. ) {
  6724. $selectParent->addOption(
  6725. $arrLP[$i]['title'],
  6726. $arrLP[$i]['id'],
  6727. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6728. );
  6729. if ($parent == $arrLP[$i]['id']) {
  6730. $selectParent->setSelected($arrLP[$i]['id']);
  6731. }
  6732. } else {
  6733. $arrHide[] = $arrLP[$i]['id'];
  6734. }
  6735. } else {
  6736. if ($arrLP[$i]['item_type'] == 'dir') {
  6737. $selectParent->addOption(
  6738. $arrLP[$i]['title'],
  6739. $arrLP[$i]['id'], ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6740. );
  6741. if ($parent == $arrLP[$i]['id']) {
  6742. $selectParent->setSelected($arrLP[$i]['id']);
  6743. }
  6744. }
  6745. }
  6746. }
  6747. if (is_array($arrLP)) {
  6748. reset($arrLP);
  6749. }
  6750. $selectPrevious = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
  6751. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6752. for ($i = 0; $i < count($arrLP); $i++) {
  6753. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6754. $selectPrevious->addOption(get_lang('After').' "'.$arrLP[$i]['title'].'"', $arrLP[$i]['id']);
  6755. if (is_array($extra_info)) {
  6756. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6757. $selectPrevious->setSelected($arrLP[$i]['id']);
  6758. }
  6759. } elseif ($action == 'add') {
  6760. $selectPrevious->setSelected($arrLP[$i]['id']);
  6761. }
  6762. }
  6763. }
  6764. if ($action != 'move') {
  6765. $id_prerequisite = 0;
  6766. if (is_array($arrLP)) {
  6767. foreach ($arrLP as $key => $value) {
  6768. if ($value['id'] == $id) {
  6769. $id_prerequisite = $value['prerequisite'];
  6770. break;
  6771. }
  6772. }
  6773. }
  6774. $arrHide = array();
  6775. for ($i = 0; $i < count($arrLP); $i++) {
  6776. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6777. if (is_array($extra_info)) {
  6778. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6779. $s_selected_position = $arrLP[$i]['id'];
  6780. }
  6781. } elseif ($action == 'add') {
  6782. $s_selected_position = 0;
  6783. }
  6784. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6785. }
  6786. }
  6787. /*// Commented the prerequisites, only visible in edit (exercise).
  6788. $return .= '<tr>';
  6789. $return .= '<td class="label"><label for="idPrerequisites">'.get_lang('LearnpathPrerequisites').'</label></td>';
  6790. $return .= '<td class="input"><select name="prerequisites" id="prerequisites" class="learnpath_item_form"><option value="0">'.get_lang('NoPrerequisites').'</option>';
  6791. foreach($arrHide as $key => $value){
  6792. if($key==$s_selected_position && $action == 'add'){
  6793. $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
  6794. }
  6795. elseif($key==$id_prerequisite && $action == 'edit'){
  6796. $return .= '<option value="'.$key.'" selected="selected">'.$value['value'].'</option>';
  6797. }
  6798. else{
  6799. $return .= '<option value="'.$key.'">'.$value['value'].'</option>';
  6800. }
  6801. }
  6802. $return .= "</select></td>";
  6803. */
  6804. /*$return .= '<tr>';
  6805. $return .= '<td class="label"><label for="maxTimeAllowed">' . get_lang('MaxTimeAllowed') . '</label></td>';
  6806. $return .= '<td class="input"><input name="maxTimeAllowed" style="width:98%;" id="maxTimeAllowed" value="' . $extra_info['max_time_allowed'] . '" /></td>';
  6807. // Remove temporarily the test description.
  6808. //$return .= '<td class="label"><label for="idDescription">'.get_lang('Description').' :</label></td>';
  6809. //$return .= '<td class="input"><textarea id="idDescription" name="description" rows="4">' . $item_description . '</textarea></td>';
  6810. $return .= '</tr>'; */
  6811. }
  6812. if ($action == 'add') {
  6813. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6814. } else {
  6815. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6816. }
  6817. if ($action == 'move') {
  6818. $form->addHidden('title', $item_title);
  6819. $form->addHidden('description', $item_description);
  6820. }
  6821. if (is_numeric($extra_info)) {
  6822. $form->addHidden('path', $extra_info);
  6823. } elseif (is_array($extra_info)) {
  6824. $form->addHidden('path', $extra_info['path']);
  6825. }
  6826. $form->addHidden('type', TOOL_QUIZ);
  6827. $form->addHidden('post_time', time());
  6828. $form->setDefaults($defaults);
  6829. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6830. }
  6831. /**
  6832. * Addition of Hotpotatoes tests
  6833. * @param string Action
  6834. * @param integer Internal ID of the item
  6835. * @param mixed Extra information - can be an array with title and description indexes
  6836. * @return string HTML structure to display the hotpotatoes addition formular
  6837. */
  6838. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6839. {
  6840. $course_id = api_get_course_int_id();
  6841. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  6842. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6843. if ($id != 0 && is_array($extra_info)) {
  6844. $item_title = stripslashes($extra_info['title']);
  6845. $item_description = stripslashes($extra_info['description']);
  6846. } elseif (is_numeric($extra_info)) {
  6847. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6848. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  6849. WHERE
  6850. c_id = ".$course_id." AND
  6851. path LIKE '".$uploadPath."/%/%htm%' AND
  6852. id = ".(int)$extra_info."
  6853. ORDER BY id ASC";
  6854. $res_hot = Database::query($sql);
  6855. $row = Database::fetch_array($res_hot);
  6856. $item_title = $row['title'];
  6857. $item_description = $row['description'];
  6858. if (!empty ($row['comment'])) {
  6859. $item_title = $row['comment'];
  6860. }
  6861. } else {
  6862. $item_title = '';
  6863. $item_description = '';
  6864. }
  6865. if ($id != 0 && is_array($extra_info)) {
  6866. $parent = $extra_info['parent_item_id'];
  6867. } else {
  6868. $parent = 0;
  6869. }
  6870. $sql
  6871. = "SELECT * FROM $tbl_lp_item
  6872. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  6873. $result = Database::query($sql);
  6874. $arrLP = array();
  6875. while ($row = Database::fetch_array($result)) {
  6876. $arrLP[] = array(
  6877. 'id' => $row['id'],
  6878. 'item_type' => $row['item_type'],
  6879. 'title' => $row['title'],
  6880. 'path' => $row['path'],
  6881. 'description' => $row['description'],
  6882. 'parent_item_id' => $row['parent_item_id'],
  6883. 'previous_item_id' => $row['previous_item_id'],
  6884. 'next_item_id' => $row['next_item_id'],
  6885. 'display_order' => $row['display_order'],
  6886. 'max_score' => $row['max_score'],
  6887. 'min_score' => $row['min_score'],
  6888. 'mastery_score' => $row['mastery_score'],
  6889. 'prerequisite' => $row['prerequisite'],
  6890. 'max_time_allowed' => $row['max_time_allowed']
  6891. );
  6892. }
  6893. $legend = '<legend>';
  6894. if ($action == 'add') {
  6895. $legend .= get_lang('CreateTheExercise');
  6896. } elseif ($action == 'move') {
  6897. $legend .= get_lang('MoveTheCurrentExercise');
  6898. } else {
  6899. $legend .= get_lang('EditCurrentExecice');
  6900. }
  6901. if (isset ($_GET['edit']) && $_GET['edit'] == 'true') {
  6902. $legend .= Display:: return_message(
  6903. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6904. );
  6905. }
  6906. $legend .= '</legend>';
  6907. $return = '<form method="POST">';
  6908. $return .= $legend;
  6909. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6910. $return .= '<tr>';
  6911. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6912. $return .= '<td class="input">';
  6913. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6914. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6915. $arrHide = array(
  6916. $id
  6917. );
  6918. if (count($arrLP) > 0) {
  6919. for ($i = 0; $i < count($arrLP); $i++) {
  6920. if ($action != 'add') {
  6921. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide)
  6922. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6923. ) {
  6924. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '')
  6925. .'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'
  6926. .$arrLP[$i]['title'].'</option>';
  6927. } else {
  6928. $arrHide[] = $arrLP[$i]['id'];
  6929. }
  6930. } else {
  6931. if ($arrLP[$i]['item_type'] == 'dir') {
  6932. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '')
  6933. .'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'
  6934. .$arrLP[$i]['title'].'</option>';
  6935. }
  6936. }
  6937. }
  6938. reset($arrLP);
  6939. }
  6940. $return .= '</select>';
  6941. $return .= '</td>';
  6942. $return .= '</tr>';
  6943. $return .= '<tr>';
  6944. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6945. $return .= '<td class="input">';
  6946. $return .= '<select id="previous" name="previous" size="1">';
  6947. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6948. for ($i = 0; $i < count($arrLP); $i++) {
  6949. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6950. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6951. $selected = 'selected="selected" ';
  6952. } elseif ($action == 'add') {
  6953. $selected = 'selected="selected" ';
  6954. } else {
  6955. $selected = '';
  6956. }
  6957. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'
  6958. .$arrLP[$i]['title'].'"</option>';
  6959. }
  6960. }
  6961. $return .= '</select>';
  6962. $return .= '</td>';
  6963. $return .= '</tr>';
  6964. if ($action != 'move') {
  6965. $return .= '<tr>';
  6966. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  6967. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  6968. $return .= '</tr>';
  6969. $id_prerequisite = 0;
  6970. if (is_array($arrLP) && count($arrLP) > 0) {
  6971. foreach ($arrLP as $key => $value) {
  6972. if ($value['id'] == $id) {
  6973. $id_prerequisite = $value['prerequisite'];
  6974. break;
  6975. }
  6976. }
  6977. $arrHide = array();
  6978. for ($i = 0; $i < count($arrLP); $i++) {
  6979. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6980. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6981. $s_selected_position = $arrLP[$i]['id'];
  6982. } elseif ($action == 'add') {
  6983. $s_selected_position = 0;
  6984. }
  6985. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6986. }
  6987. }
  6988. }
  6989. }
  6990. $return .= '<tr>';
  6991. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'
  6992. .get_lang('SaveHotpotatoes').'</button></td>';
  6993. $return .= '</tr>';
  6994. $return .= '</table>';
  6995. if ($action == 'move') {
  6996. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  6997. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  6998. }
  6999. if (is_numeric($extra_info)) {
  7000. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7001. } elseif (is_array($extra_info)) {
  7002. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7003. }
  7004. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7005. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7006. $return .= '</form>';
  7007. return $return;
  7008. }
  7009. /**
  7010. * Return the form to display the forum edit/add option
  7011. * @param string Action (add/edit)
  7012. * @param integer ID of the lp_item if already exists
  7013. * @param mixed Forum ID or title
  7014. * @return string HTML form
  7015. */
  7016. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7017. {
  7018. $course_id = api_get_course_int_id();
  7019. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7020. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7021. if ($id != 0 && is_array($extra_info)) {
  7022. $item_title = stripslashes($extra_info['title']);
  7023. } elseif (is_numeric($extra_info)) {
  7024. $sql
  7025. = "SELECT forum_title as title, forum_comment as comment
  7026. FROM ".$tbl_forum."
  7027. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7028. $result = Database::query($sql);
  7029. $row = Database::fetch_array($result);
  7030. $item_title = $row['title'];
  7031. $item_description = $row['comment'];
  7032. } else {
  7033. $item_title = '';
  7034. $item_description = '';
  7035. }
  7036. if ($id != 0 && is_array($extra_info)) {
  7037. $parent = $extra_info['parent_item_id'];
  7038. } else {
  7039. $parent = 0;
  7040. }
  7041. $sql = "SELECT * FROM ".$tbl_lp_item."
  7042. WHERE
  7043. c_id = ".$course_id." AND
  7044. lp_id = ".$this->lp_id;
  7045. $result = Database::query($sql);
  7046. $arrLP = array();
  7047. while ($row = Database::fetch_array($result)) {
  7048. $arrLP[] = array(
  7049. 'id' => $row['id'],
  7050. 'item_type' => $row['item_type'],
  7051. 'title' => $row['title'],
  7052. 'path' => $row['path'],
  7053. 'description' => $row['description'],
  7054. 'parent_item_id' => $row['parent_item_id'],
  7055. 'previous_item_id' => $row['previous_item_id'],
  7056. 'next_item_id' => $row['next_item_id'],
  7057. 'display_order' => $row['display_order'],
  7058. 'max_score' => $row['max_score'],
  7059. 'min_score' => $row['min_score'],
  7060. 'mastery_score' => $row['mastery_score'],
  7061. 'prerequisite' => $row['prerequisite']
  7062. );
  7063. }
  7064. $this->tree_array($arrLP);
  7065. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7066. unset($this->arrMenu);
  7067. if ($action == 'add') {
  7068. $legend = get_lang('CreateTheForum');
  7069. } elseif ($action == 'move') {
  7070. $legend = get_lang('MoveTheCurrentForum');
  7071. } else {
  7072. $legend = get_lang('EditCurrentForum');
  7073. }
  7074. $form = new FormValidator(
  7075. 'forum_form',
  7076. 'POST',
  7077. $this->getCurrentBuildingModeURL()
  7078. );
  7079. $defaults = [];
  7080. $form->addHeader($legend);
  7081. if ($action != 'move') {
  7082. $form->addText(
  7083. 'title',
  7084. get_lang('Title'),
  7085. true,
  7086. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7087. );
  7088. $defaults['title'] = $item_title;
  7089. }
  7090. $selectParent = $form->addSelect(
  7091. 'parent',
  7092. get_lang('Parent'),
  7093. [],
  7094. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7095. );
  7096. $selectParent->addOption($this->name, 0);
  7097. $arrHide = array(
  7098. $id
  7099. );
  7100. //$parent_item_id = $_SESSION['parent_item_id'];
  7101. for ($i = 0; $i < count($arrLP); $i++) {
  7102. if ($action != 'add') {
  7103. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide)
  7104. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7105. ) {
  7106. $selectParent->addOption(
  7107. $arrLP[$i]['title'],
  7108. $arrLP[$i]['id'],
  7109. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7110. );
  7111. if ($parent == $arrLP[$i]['id']) {
  7112. $selectParent->setSelected($arrLP[$i]['id']);
  7113. }
  7114. } else {
  7115. $arrHide[] = $arrLP[$i]['id'];
  7116. }
  7117. } else {
  7118. if ($arrLP[$i]['item_type'] == 'dir') {
  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. }
  7128. }
  7129. }
  7130. if (is_array($arrLP)) {
  7131. reset($arrLP);
  7132. }
  7133. $selectPrevious = $form->addSelect(
  7134. 'previous',
  7135. get_lang('Position'),
  7136. [],
  7137. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7138. );
  7139. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7140. for ($i = 0; $i < count($arrLP); $i++) {
  7141. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7142. $selectPrevious->addOption(get_lang('After').' "'.$arrLP[$i]['title'].'"', $arrLP[$i]['id']);
  7143. if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7144. $selectPrevious->setSelected($arrLP[$i]['id']);
  7145. } elseif ($action == 'add') {
  7146. $selectPrevious->setSelected($arrLP[$i]['id']);
  7147. }
  7148. }
  7149. }
  7150. if ($action != 'move') {
  7151. $id_prerequisite = 0;
  7152. if (is_array($arrLP)) {
  7153. foreach ($arrLP as $key => $value) {
  7154. if ($value['id'] == $id) {
  7155. $id_prerequisite = $value['prerequisite'];
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. $arrHide = array();
  7161. for ($i = 0; $i < count($arrLP); $i++) {
  7162. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7163. if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7164. $s_selected_position = $arrLP[$i]['id'];
  7165. } elseif ($action == 'add') {
  7166. $s_selected_position = 0;
  7167. }
  7168. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7169. }
  7170. }
  7171. }
  7172. if ($action == 'add') {
  7173. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7174. } else {
  7175. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7176. }
  7177. if ($action == 'move') {
  7178. $form->addHidden('title', $item_title);
  7179. $form->addHidden('description', $item_description);
  7180. }
  7181. if (is_numeric($extra_info)) {
  7182. $form->addHidden('path', $extra_info);
  7183. } elseif (is_array($extra_info)) {
  7184. $form->addHidden('path', $extra_info['path']);
  7185. }
  7186. $form->addHidden('type', TOOL_FORUM);
  7187. $form->addHidden('post_time', time());
  7188. $form->setDefaults($defaults);
  7189. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7190. }
  7191. /**
  7192. * Return HTML form to add/edit forum threads
  7193. * @param string Action (add/edit)
  7194. * @param integer Item ID if already exists in learning path
  7195. * @param mixed Extra information (thread ID if integer)
  7196. * @return string HTML form
  7197. */
  7198. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7199. {
  7200. $course_id = api_get_course_int_id();
  7201. if (empty($course_id)) {
  7202. return null;
  7203. }
  7204. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7205. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7206. if ($id != 0 && is_array($extra_info)) {
  7207. $item_title = stripslashes($extra_info['title']);
  7208. } elseif (is_numeric($extra_info)) {
  7209. $sql
  7210. = "SELECT thread_title as title FROM $tbl_forum
  7211. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7212. $result = Database::query($sql);
  7213. $row = Database::fetch_array($result);
  7214. $item_title = $row['title'];
  7215. $item_description = '';
  7216. } else {
  7217. $item_title = '';
  7218. $item_description = '';
  7219. }
  7220. if ($id != 0 && is_array($extra_info)) {
  7221. $parent = $extra_info['parent_item_id'];
  7222. } else {
  7223. $parent = 0;
  7224. }
  7225. $sql = "SELECT * FROM ".$tbl_lp_item."
  7226. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  7227. $result = Database::query($sql);
  7228. $arrLP = array();
  7229. while ($row = Database::fetch_array($result)) {
  7230. $arrLP[] = array(
  7231. 'id' => $row['id'],
  7232. 'item_type' => $row['item_type'],
  7233. 'title' => $row['title'],
  7234. 'path' => $row['path'],
  7235. 'description' => $row['description'],
  7236. 'parent_item_id' => $row['parent_item_id'],
  7237. 'previous_item_id' => $row['previous_item_id'],
  7238. 'next_item_id' => $row['next_item_id'],
  7239. 'display_order' => $row['display_order'],
  7240. 'max_score' => $row['max_score'],
  7241. 'min_score' => $row['min_score'],
  7242. 'mastery_score' => $row['mastery_score'],
  7243. 'prerequisite' => $row['prerequisite']
  7244. );
  7245. }
  7246. $this->tree_array($arrLP);
  7247. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7248. unset($this->arrMenu);
  7249. $form = new FormValidator(
  7250. 'thread_form',
  7251. 'POST',
  7252. $this->getCurrentBuildingModeURL()
  7253. );
  7254. $defaults = [];
  7255. if ($action == 'add') {
  7256. $legend = get_lang('CreateTheForum');
  7257. } elseif ($action == 'move') {
  7258. $legend = get_lang('MoveTheCurrentForum');
  7259. } else {
  7260. $legend = get_lang('EditCurrentForum');
  7261. }
  7262. $form->addHeader($legend);
  7263. $selectParent = $form->addSelect(
  7264. 'parent',
  7265. get_lang('Parent'),
  7266. [],
  7267. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7268. );
  7269. $selectParent->addOption($this->name, 0);
  7270. $arrHide = array(
  7271. $id
  7272. );
  7273. for ($i = 0; $i < count($arrLP); $i++) {
  7274. if ($action != 'add') {
  7275. if (
  7276. ($arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide)
  7277. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7278. ) {
  7279. $selectParent->addOption(
  7280. $arrLP[$i]['title'],
  7281. $arrLP[$i]['id'],
  7282. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7283. );
  7284. if ($parent == $arrLP[$i]['id']) {
  7285. $selectParent->setSelected($arrLP[$i]['id']);
  7286. }
  7287. } else {
  7288. $arrHide[] = $arrLP[$i]['id'];
  7289. }
  7290. } else {
  7291. if ($arrLP[$i]['item_type'] == 'dir') {
  7292. $selectParent->addOption(
  7293. $arrLP[$i]['title'],
  7294. $arrLP[$i]['id'],
  7295. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7296. );
  7297. if ($parent == $arrLP[$i]['id']) {
  7298. $selectParent->setSelected($arrLP[$i]['id']);
  7299. }
  7300. }
  7301. }
  7302. }
  7303. if ($arrLP != null) {
  7304. reset($arrLP);
  7305. }
  7306. $selectPrevious = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
  7307. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7308. for ($i = 0; $i < count($arrLP); $i++) {
  7309. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7310. $selectPrevious->addOption(
  7311. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7312. $arrLP[$i]['id']
  7313. );
  7314. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7315. $selectPrevious->setSelected($arrLP[$i]['id']);
  7316. } elseif ($action == 'add') {
  7317. $selectPrevious->setSelected($arrLP[$i]['id']);
  7318. }
  7319. }
  7320. }
  7321. if ($action != 'move') {
  7322. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7323. $defaults['title'] = $item_title;
  7324. $id_prerequisite = 0;
  7325. if ($arrLP != null) {
  7326. foreach ($arrLP as $key => $value) {
  7327. if ($value['id'] == $id) {
  7328. $id_prerequisite = $value['prerequisite'];
  7329. break;
  7330. }
  7331. }
  7332. }
  7333. $arrHide = array();
  7334. $s_selected_position = 0;
  7335. for ($i = 0; $i < count($arrLP); $i++) {
  7336. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7337. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7338. $s_selected_position = $arrLP[$i]['id'];
  7339. } elseif ($action == 'add') {
  7340. $s_selected_position = 0;
  7341. }
  7342. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7343. }
  7344. }
  7345. $selectPrerequisites = $form->addSelect(
  7346. 'prerequisites',
  7347. get_lang('LearnpathPrerequisites'),
  7348. [],
  7349. ['id' => 'prerequisites']
  7350. );
  7351. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7352. foreach ($arrHide as $key => $value) {
  7353. $selectPrerequisites->addOption($value['value'], $key);
  7354. if ($key == $s_selected_position && $action == 'add') {
  7355. $selectPrerequisites->setSelected($key);
  7356. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7357. $selectPrerequisites->setSelected($key);
  7358. }
  7359. }
  7360. }
  7361. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7362. if ($action == 'move') {
  7363. $form->addHidden('title', $item_title);
  7364. $form->addHidden('description', $item_description);
  7365. }
  7366. if (is_numeric($extra_info)) {
  7367. $form->addHidden('path', $extra_info);
  7368. } elseif (is_array($extra_info)) {
  7369. $form->addHidden('path', $extra_info['path']);
  7370. }
  7371. $form->addHidden('type', TOOL_THREAD);
  7372. $form->addHidden('post_time', time());
  7373. $form->setDefaults($defaults);
  7374. return $form->returnForm();
  7375. }
  7376. /**
  7377. * Return the HTML form to display an item (generally a dir item)
  7378. * @param string Item type (dir)
  7379. * @param string Title (optional, only when creating)
  7380. * @param string Action ('add'/'edit')
  7381. * @param integer lp_item ID
  7382. * @param mixed Extra info
  7383. * @return string HTML form
  7384. */
  7385. public function display_item_form($item_type, $title = '', $action = 'add_item', $id = 0, $extra_info = 'new')
  7386. {
  7387. $course_id = api_get_course_int_id();
  7388. $_course = api_get_course_info();
  7389. global $charset;
  7390. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7391. if ($id != 0 && is_array($extra_info)) {
  7392. $item_title = $extra_info['title'];
  7393. $item_description = $extra_info['description'];
  7394. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'
  7395. .stripslashes($extra_info['path']);
  7396. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7397. } else {
  7398. $item_title = '';
  7399. $item_description = '';
  7400. $item_path_fck = '';
  7401. }
  7402. if ($id != 0 && is_array($extra_info)) {
  7403. $parent = $extra_info['parent_item_id'];
  7404. } else {
  7405. $parent = 0;
  7406. }
  7407. $id = intval($id);
  7408. $sql = "SELECT * FROM ".$tbl_lp_item."
  7409. WHERE
  7410. c_id = ".$course_id." AND
  7411. lp_id = ".$this->lp_id." AND
  7412. id != $id";
  7413. if ($item_type == 'dir') {
  7414. $sql .= " AND parent_item_id = 0";
  7415. }
  7416. $result = Database::query($sql);
  7417. $arrLP = [];
  7418. while ($row = Database::fetch_array($result)) {
  7419. $arrLP[] = array(
  7420. 'id' => $row['id'],
  7421. 'item_type' => $row['item_type'],
  7422. 'title' => $row['title'],
  7423. 'path' => $row['path'],
  7424. 'description' => $row['description'],
  7425. 'parent_item_id' => $row['parent_item_id'],
  7426. 'previous_item_id' => $row['previous_item_id'],
  7427. 'next_item_id' => $row['next_item_id'],
  7428. 'max_score' => $row['max_score'],
  7429. 'min_score' => $row['min_score'],
  7430. 'mastery_score' => $row['mastery_score'],
  7431. 'prerequisite' => $row['prerequisite'],
  7432. 'display_order' => $row['display_order']
  7433. );
  7434. }
  7435. $this->tree_array($arrLP);
  7436. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7437. unset($this->arrMenu);
  7438. $gradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : null;
  7439. $url = api_get_self().'?'.api_get_cidreq().'&gradeboook='.$gradebook.'&action='.$action.'&type='.$item_type
  7440. .'&lp_id='.$this->lp_id;
  7441. $form = new FormValidator('form', 'POST', $url);
  7442. $defaults['title'] = api_html_entity_decode($item_title, ENT_QUOTES, $charset);
  7443. $defaults['description'] = $item_description;
  7444. $form->addElement('header', $title);
  7445. //$arrHide = array($id);
  7446. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7447. $arrHide[0]['padding'] = 20;
  7448. $charset = api_get_system_encoding();
  7449. for ($i = 0; $i < count($arrLP); $i++) {
  7450. if ($action != 'add') {
  7451. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide)
  7452. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7453. ) {
  7454. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7455. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7456. if ($parent == $arrLP[$i]['id']) {
  7457. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7458. }
  7459. }
  7460. } else {
  7461. if ($arrLP[$i]['item_type'] == 'dir') {
  7462. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7463. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7464. if ($parent == $arrLP[$i]['id']) {
  7465. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7466. }
  7467. }
  7468. }
  7469. }
  7470. if ($action != 'move') {
  7471. $form->addElement('text', 'title', get_lang('Title'));
  7472. $form->applyFilter('title', 'html_filter');
  7473. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7474. } else {
  7475. $form->addElement('hidden', 'title');
  7476. }
  7477. $parent_select = $form->addElement(
  7478. 'select',
  7479. 'parent',
  7480. get_lang('Parent'),
  7481. '',
  7482. array(
  7483. 'id' => 'idParent',
  7484. 'onchange' => "javascript: load_cbo(this.value);",
  7485. )
  7486. );
  7487. foreach ($arrHide as $key => $value) {
  7488. $parent_select->addOption($value['value'], $key, 'style="padding-left:'.$value['padding'].'px;"');
  7489. }
  7490. if (!empty($s_selected_parent)) {
  7491. $parent_select->setSelected($s_selected_parent);
  7492. }
  7493. if (is_array($arrLP)) {
  7494. reset($arrLP);
  7495. }
  7496. $arrHide = array();
  7497. // POSITION
  7498. for ($i = 0; $i < count($arrLP); $i++) {
  7499. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7500. //this is the same!
  7501. if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7502. $s_selected_position = $arrLP[$i]['id'];
  7503. } elseif ($action == 'add') {
  7504. $s_selected_position = $arrLP[$i]['id'];
  7505. }
  7506. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7507. }
  7508. }
  7509. $position = $form->addElement(
  7510. 'select',
  7511. 'previous',
  7512. get_lang('Position'),
  7513. '',
  7514. array('id' => 'previous')
  7515. );
  7516. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7517. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7518. foreach ($arrHide as $key => $value) {
  7519. $position->addOption($value['value'].'"', $key, 'style="padding-left:'.$padding.'px;"');
  7520. }
  7521. if (!empty ($s_selected_position)) {
  7522. $position->setSelected($s_selected_position);
  7523. }
  7524. if (is_array($arrLP)) {
  7525. reset($arrLP);
  7526. }
  7527. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7528. //fix in order to use the tab
  7529. if ($item_type == 'dir') {
  7530. $form->addElement('hidden', 'type', 'dir');
  7531. }
  7532. $extension = null;
  7533. if (!empty($item_path)) {
  7534. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7535. }
  7536. //assets can't be modified
  7537. //$item_type == 'asset' ||
  7538. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7539. if ($item_type == 'sco') {
  7540. $form->addElement('html', '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>');
  7541. }
  7542. $renderer = $form->defaultRenderer();
  7543. $renderer->setElementTemplate('<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7544. 'content_lp');
  7545. $relative_prefix = '';
  7546. $editor_config = array(
  7547. 'ToolbarSet' => 'LearningPathDocuments',
  7548. 'Width' => '100%',
  7549. 'Height' => '500',
  7550. 'FullPage' => true,
  7551. 'CreateDocumentDir' => $relative_prefix,
  7552. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7553. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck
  7554. );
  7555. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7556. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7557. $defaults['content_lp'] = file_get_contents($content_path);
  7558. }
  7559. $form->addElement('hidden', 'type', $item_type);
  7560. $form->addElement('hidden', 'post_time', time());
  7561. $form->setDefaults($defaults);
  7562. return $form->return_form();
  7563. }
  7564. /**
  7565. * @return string
  7566. */
  7567. public function getCurrentBuildingModeURL()
  7568. {
  7569. $pathItem = isset($_GET['path_item']) ? (int)$_GET['path_item'] : '';
  7570. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7571. $id = isset($_GET['id']) ? (int)$_GET['id'] : '';
  7572. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7573. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='
  7574. .$pathItem.'&view='.$view.'&id='.$id;
  7575. return $currentUrl;
  7576. }
  7577. /**
  7578. * Returns the form to update or create a document
  7579. * @param string $action (add/edit)
  7580. * @param integer $id ID of the lp_item (if already exists)
  7581. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7582. * @return string HTML form
  7583. */
  7584. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7585. {
  7586. $course_id = api_get_course_int_id();
  7587. $_course = api_get_course_info();
  7588. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7589. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7590. $no_display_edit_textarea = false;
  7591. $item_description = '';
  7592. //If action==edit document
  7593. //We don't display the document form if it's not an editable document (html or txt file)
  7594. if ($action == 'edit') {
  7595. if (is_array($extra_info)) {
  7596. $path_parts = pathinfo($extra_info['dir']);
  7597. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7598. $no_display_edit_textarea = true;
  7599. }
  7600. }
  7601. }
  7602. $no_display_add = false;
  7603. // If action==add an existing document
  7604. // We don't display the document form if it's not an editable document (html or txt file).
  7605. if ($action == 'add') {
  7606. if (is_numeric($extra_info)) {
  7607. $sql_doc
  7608. = "SELECT path FROM $tbl_doc
  7609. WHERE c_id = $course_id AND id = ".intval($extra_info);
  7610. $result = Database::query($sql_doc);
  7611. $path_file = Database::result($result, 0, 0);
  7612. $path_parts = pathinfo($path_file);
  7613. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7614. $no_display_add = true;
  7615. }
  7616. }
  7617. }
  7618. if ($id != 0 && is_array($extra_info)) {
  7619. $item_title = stripslashes($extra_info['title']);
  7620. $item_description = stripslashes($extra_info['description']);
  7621. $item_terms = stripslashes($extra_info['terms']);
  7622. if (empty ($item_title)) {
  7623. $path_parts = pathinfo($extra_info['path']);
  7624. $item_title = stripslashes($path_parts['filename']);
  7625. }
  7626. } elseif (is_numeric($extra_info)) {
  7627. $sql
  7628. = "SELECT path, title FROM $tbl_doc
  7629. WHERE
  7630. c_id = ".$course_id." AND
  7631. id = ".intval($extra_info);
  7632. $result = Database::query($sql);
  7633. $row = Database::fetch_array($result);
  7634. $item_title = $row['title'];
  7635. $item_title = str_replace('_', ' ', $item_title);
  7636. if (empty ($item_title)) {
  7637. $path_parts = pathinfo($row['path']);
  7638. $item_title = stripslashes($path_parts['filename']);
  7639. }
  7640. } else {
  7641. $item_title = '';
  7642. $item_description = '';
  7643. }
  7644. $return = '<legend>';
  7645. if ($id != 0 && is_array($extra_info)) {
  7646. $parent = $extra_info['parent_item_id'];
  7647. } else {
  7648. $parent = 0;
  7649. }
  7650. $sql
  7651. = "SELECT * FROM $tbl_lp_item
  7652. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7653. $result = Database::query($sql);
  7654. $arrLP = array();
  7655. while ($row = Database::fetch_array($result)) {
  7656. $arrLP[] = array(
  7657. 'id' => $row['id'],
  7658. 'item_type' => $row['item_type'],
  7659. 'title' => $row['title'],
  7660. 'path' => $row['path'],
  7661. 'description' => $row['description'],
  7662. 'parent_item_id' => $row['parent_item_id'],
  7663. 'previous_item_id' => $row['previous_item_id'],
  7664. 'next_item_id' => $row['next_item_id'],
  7665. 'display_order' => $row['display_order'],
  7666. 'max_score' => $row['max_score'],
  7667. 'min_score' => $row['min_score'],
  7668. 'mastery_score' => $row['mastery_score'],
  7669. 'prerequisite' => $row['prerequisite']
  7670. );
  7671. }
  7672. $this->tree_array($arrLP);
  7673. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  7674. unset($this->arrMenu);
  7675. if ($action == 'add') {
  7676. $return .= get_lang('CreateTheDocument');
  7677. } elseif ($action == 'move') {
  7678. $return .= get_lang('MoveTheCurrentDocument');
  7679. } else {
  7680. $return .= get_lang('EditTheCurrentDocument');
  7681. }
  7682. $return .= '</legend>';
  7683. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7684. $return .= Display::return_message(
  7685. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7686. false
  7687. );
  7688. }
  7689. $form = new FormValidator(
  7690. 'form',
  7691. 'POST',
  7692. $this->getCurrentBuildingModeURL(),
  7693. '',
  7694. array('enctype' => 'multipart/form-data')
  7695. );
  7696. $defaults['title'] = Security::remove_XSS($item_title);
  7697. if (empty($item_title)) {
  7698. $defaults['title'] = Security::remove_XSS($item_title);
  7699. }
  7700. $defaults['description'] = $item_description;
  7701. $form->addElement('html', $return);
  7702. if ($action != 'move') {
  7703. $data = $this->generate_lp_folder($_course);
  7704. if ($action != 'edit') {
  7705. $folders = DocumentManager::get_all_document_folders(
  7706. $_course,
  7707. 0,
  7708. true
  7709. );
  7710. DocumentManager::build_directory_selector(
  7711. $folders,
  7712. '',
  7713. array(),
  7714. true,
  7715. $form,
  7716. 'directory_parent_id'
  7717. );
  7718. }
  7719. if (isset($data['id'])) {
  7720. $defaults['directory_parent_id'] = $data['id'];
  7721. }
  7722. $form->addElement(
  7723. 'text',
  7724. 'title',
  7725. get_lang('Title'),
  7726. array('id' => 'idTitle', 'class' => 'col-md-4')
  7727. );
  7728. $form->applyFilter('title', 'html_filter');
  7729. }
  7730. $arrHide[0]['value'] = $this->name;
  7731. $arrHide[0]['padding'] = 20;
  7732. for ($i = 0; $i < count($arrLP); $i++) {
  7733. if ($action != 'add') {
  7734. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide)
  7735. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7736. ) {
  7737. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7738. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7739. if ($parent == $arrLP[$i]['id']) {
  7740. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7741. }
  7742. }
  7743. } else {
  7744. if ($arrLP[$i]['item_type'] == 'dir') {
  7745. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7746. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7747. if ($parent == $arrLP[$i]['id']) {
  7748. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7749. }
  7750. }
  7751. }
  7752. }
  7753. $parent_select = $form->addSelect(
  7754. 'parent',
  7755. get_lang('Parent'),
  7756. [],
  7757. [
  7758. 'id' => 'idParent',
  7759. 'onchange' => 'javascript: load_cbo(this.value);',
  7760. ]
  7761. );
  7762. $my_count = 0;
  7763. foreach ($arrHide as $key => $value) {
  7764. if ($my_count != 0) {
  7765. // The LP name is also the first section and is not in the same charset like the other sections.
  7766. $value['value'] = Security::remove_XSS($value['value']);
  7767. $parent_select->addOption($value['value'], $key, 'style="padding-left:'.$value['padding'].'px;"');
  7768. } else {
  7769. $value['value'] = Security::remove_XSS($value['value']);
  7770. $parent_select->addOption($value['value'], $key, 'style="padding-left:'.$value['padding'].'px;"');
  7771. }
  7772. $my_count++;
  7773. }
  7774. if (!empty($id)) {
  7775. $parent_select->setSelected($parent);
  7776. } else {
  7777. $parent_item_id = isset($_SESSION['parent_item_id']) ? $_SESSION['parent_item_id'] : 0;
  7778. $parent_select->setSelected($parent_item_id);
  7779. }
  7780. if (is_array($arrLP)) {
  7781. reset($arrLP);
  7782. }
  7783. $arrHide = array();
  7784. $s_selected_position = null;
  7785. // POSITION
  7786. $lastPosition = null;
  7787. for ($i = 0; $i < count($arrLP); $i++) {
  7788. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id)
  7789. || $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7790. ) {
  7791. if ((isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id'])
  7792. || $action == 'add'
  7793. ) {
  7794. $s_selected_position = $arrLP[$i]['id'];
  7795. }
  7796. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7797. }
  7798. $lastPosition = $arrLP[$i]['id'];
  7799. }
  7800. if (empty($s_selected_position)) {
  7801. $s_selected_position = $lastPosition;
  7802. }
  7803. $position = $form->addSelect('previous', get_lang('Position'), [], ['id' => 'previous']);
  7804. $position->addOption(get_lang('FirstPosition'), 0);
  7805. foreach ($arrHide as $key => $value) {
  7806. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7807. $position->addOption(
  7808. $value['value'],
  7809. $key,
  7810. 'style="padding-left:'.$padding.'px;"'
  7811. );
  7812. }
  7813. $position->setSelected($s_selected_position);
  7814. if (is_array($arrLP)) {
  7815. reset($arrLP);
  7816. }
  7817. if ($action != 'move') {
  7818. $id_prerequisite = 0;
  7819. if (is_array($arrLP)) {
  7820. foreach ($arrLP as $key => $value) {
  7821. if ($value['id'] == $id) {
  7822. $id_prerequisite = $value['prerequisite'];
  7823. break;
  7824. }
  7825. }
  7826. }
  7827. $arrHide = array();
  7828. for ($i = 0; $i < count($arrLP); $i++) {
  7829. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir'
  7830. && $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7831. ) {
  7832. if (isset($extra_info['previous_item_id']) && $extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7833. $s_selected_position = $arrLP[$i]['id'];
  7834. } elseif ($action == 'add') {
  7835. $s_selected_position = $arrLP[$i]['id'];
  7836. }
  7837. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7838. }
  7839. }
  7840. if (!$no_display_add) {
  7841. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7842. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7843. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM
  7844. || $edit == 'true'
  7845. ) {
  7846. if (isset ($_POST['content'])) {
  7847. $content = stripslashes($_POST['content']);
  7848. } elseif (is_array($extra_info)) {
  7849. //If it's an html document or a text file
  7850. if (!$no_display_edit_textarea) {
  7851. $content = $this->display_document($extra_info['path'], false, false);
  7852. }
  7853. } elseif (is_numeric($extra_info)) {
  7854. $content = $this->display_document(
  7855. $extra_info,
  7856. false,
  7857. false
  7858. );
  7859. } else {
  7860. $content = '';
  7861. }
  7862. if (!$no_display_edit_textarea) {
  7863. // We need to calculate here some specific settings for the online editor.
  7864. // The calculated settings work for documents in the Documents tool
  7865. // (on the root or in subfolders).
  7866. // For documents in native scorm packages it is unclear whether the
  7867. // online editor should be activated or not.
  7868. // A new document, it is in the root of the repository.
  7869. $relative_path = '';
  7870. $relative_prefix = '';
  7871. if (is_array($extra_info) && $extra_info != 'new') {
  7872. // The document already exists. Whe have to determine its relative path towards the repository root.
  7873. $relative_path = explode('/', $extra_info['dir']);
  7874. $cnt = count($relative_path) - 2;
  7875. if ($cnt < 0) {
  7876. $cnt = 0;
  7877. }
  7878. $relative_prefix = str_repeat('../', $cnt);
  7879. $relative_path = array_slice($relative_path, 1, $cnt);
  7880. $relative_path = implode('/', $relative_path);
  7881. if (strlen($relative_path) > 0) {
  7882. $relative_path = $relative_path.'/';
  7883. }
  7884. } else {
  7885. $result = $this->generate_lp_folder($_course);
  7886. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7887. $relative_prefix = '../../';
  7888. }
  7889. $editor_config = array(
  7890. 'ToolbarSet' => 'LearningPathDocuments',
  7891. 'Width' => '100%',
  7892. 'Height' => '500',
  7893. 'FullPage' => true,
  7894. 'CreateDocumentDir' => $relative_prefix,
  7895. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7896. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'
  7897. .$relative_path
  7898. );
  7899. if ($_GET['action'] == 'add_item') {
  7900. $class = 'add';
  7901. $text = get_lang('LPCreateDocument');
  7902. } else {
  7903. if ($_GET['action'] == 'edit_item') {
  7904. $class = 'save';
  7905. $text = get_lang('SaveDocument');
  7906. }
  7907. }
  7908. $form->addButtonSave($text, 'submit_button');
  7909. $renderer = $form->defaultRenderer();
  7910. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7911. $form->addElement('html', '<div class="editor-lp">');
  7912. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7913. $form->addElement('html', '</div>');
  7914. $defaults['content_lp'] = $content;
  7915. }
  7916. } elseif (is_numeric($extra_info)) {
  7917. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7918. $return = $this->display_document($extra_info, true, true, true);
  7919. $form->addElement('html', $return);
  7920. }
  7921. }
  7922. }
  7923. if (isset($extra_info['item_type']) && $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7924. ) {
  7925. $parent_select->freeze();
  7926. $position->freeze();
  7927. }
  7928. if ($action == 'move') {
  7929. $form->addElement('hidden', 'title', $item_title);
  7930. $form->addElement('hidden', 'description', $item_description);
  7931. }
  7932. if (is_numeric($extra_info)) {
  7933. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7934. $form->addElement('hidden', 'path', $extra_info);
  7935. } elseif (is_array($extra_info)) {
  7936. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7937. $form->addElement('hidden', 'path', $extra_info['path']);
  7938. }
  7939. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7940. $form->addElement('hidden', 'post_time', time());
  7941. $form->setDefaults($defaults);
  7942. return $form->returnForm();
  7943. }
  7944. /**
  7945. * Return HTML form to add/edit a link item
  7946. * @param string $action (add/edit)
  7947. * @param integer $id Item ID if exists
  7948. * @param mixed $extra_info
  7949. * @return string HTML form
  7950. */
  7951. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  7952. {
  7953. $course_id = api_get_course_int_id();
  7954. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7955. $tbl_link = Database::get_course_table(TABLE_LINK);
  7956. if ($id != 0 && is_array($extra_info)) {
  7957. $item_title = stripslashes($extra_info['title']);
  7958. $item_description = stripslashes($extra_info['description']);
  7959. $item_url = stripslashes($extra_info['url']);
  7960. } elseif (is_numeric($extra_info)) {
  7961. $extra_info = intval($extra_info);
  7962. $sql = "SELECT title, description, url FROM ".$tbl_link."
  7963. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  7964. $result = Database::query($sql);
  7965. $row = Database::fetch_array($result);
  7966. $item_title = $row['title'];
  7967. $item_description = $row['description'];
  7968. $item_url = $row['url'];
  7969. } else {
  7970. $item_title = '';
  7971. $item_description = '';
  7972. $item_url = '';
  7973. }
  7974. $form = new FormValidator(
  7975. 'edit_link',
  7976. 'POST',
  7977. $this->getCurrentBuildingModeURL()
  7978. );
  7979. $defaults = [];
  7980. if ($id != 0 && is_array($extra_info)) {
  7981. $parent = $extra_info['parent_item_id'];
  7982. } else {
  7983. $parent = 0;
  7984. }
  7985. $sql = "SELECT * FROM ".$tbl_lp_item."
  7986. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  7987. $result = Database::query($sql);
  7988. $arrLP = array();
  7989. while ($row = Database::fetch_array($result)) {
  7990. $arrLP[] = array(
  7991. 'id' => $row['id'],
  7992. 'item_type' => $row['item_type'],
  7993. 'title' => $row['title'],
  7994. 'path' => $row['path'],
  7995. 'description' => $row['description'],
  7996. 'parent_item_id' => $row['parent_item_id'],
  7997. 'previous_item_id' => $row['previous_item_id'],
  7998. 'next_item_id' => $row['next_item_id'],
  7999. 'display_order' => $row['display_order'],
  8000. 'max_score' => $row['max_score'],
  8001. 'min_score' => $row['min_score'],
  8002. 'mastery_score' => $row['mastery_score'],
  8003. 'prerequisite' => $row['prerequisite']
  8004. );
  8005. }
  8006. $this->tree_array($arrLP);
  8007. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8008. unset($this->arrMenu);
  8009. if ($action == 'add') {
  8010. $legend = get_lang('CreateTheLink');
  8011. } elseif ($action == 'move') {
  8012. $legend = get_lang('MoveCurrentLink');
  8013. } else {
  8014. $legend = get_lang('EditCurrentLink');
  8015. }
  8016. $form->addHeader($legend);
  8017. if ($action != 'move') {
  8018. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8019. $defaults['title'] = $item_title;
  8020. }
  8021. $selectParent = $form->addSelect(
  8022. 'parent',
  8023. get_lang('Parent'),
  8024. [],
  8025. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8026. );
  8027. $selectParent->addOption($this->name, 0);
  8028. $arrHide = array(
  8029. $id
  8030. );
  8031. $parent_item_id = isset($_SESSION['parent_item_id']) ? $_SESSION['parent_item_id'] : 0;
  8032. for ($i = 0; $i < count($arrLP); $i++) {
  8033. if ($action != 'add') {
  8034. if (
  8035. ($arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide)
  8036. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8037. ) {
  8038. $selectParent->addOption(
  8039. $arrLP[$i]['title'],
  8040. $arrLP[$i]['id'],
  8041. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8042. );
  8043. if ($parent == $arrLP[$i]['id']) {
  8044. $selectParent->setSelected($arrLP[$i]['id']);
  8045. }
  8046. } else {
  8047. $arrHide[] = $arrLP[$i]['id'];
  8048. }
  8049. } else {
  8050. if ($arrLP[$i]['item_type'] == 'dir') {
  8051. $selectParent->addOption(
  8052. $arrLP[$i]['title'],
  8053. $arrLP[$i]['id'],
  8054. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8055. );
  8056. if ($parent_item_id == $arrLP[$i]['id']) {
  8057. $selectParent->setSelected($arrLP[$i]['id']);
  8058. }
  8059. }
  8060. }
  8061. }
  8062. if (is_array($arrLP)) {
  8063. reset($arrLP);
  8064. }
  8065. $selectPrevious = $form->addSelect(
  8066. 'previous',
  8067. get_lang('Position'),
  8068. [],
  8069. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8070. );
  8071. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8072. for ($i = 0; $i < count($arrLP); $i++) {
  8073. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8074. $selectPrevious->addOption($arrLP[$i]['title'], $arrLP[$i]['id']);
  8075. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8076. $selectPrevious->setSelected($arrLP[$i]['id']);
  8077. } elseif ($action == 'add') {
  8078. $selectPrevious->setSelected($arrLP[$i]['id']);
  8079. }
  8080. }
  8081. }
  8082. if ($action != 'move') {
  8083. $urlAttributes = ['class' => 'learnpath_item_form'];
  8084. if (is_numeric($extra_info)) {
  8085. $urlAttributes['disabled'] = 'disabled';
  8086. }
  8087. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8088. $defaults['url'] = $item_url;
  8089. $id_prerequisite = 0;
  8090. if (is_array($arrLP)) {
  8091. foreach ($arrLP as $key => $value) {
  8092. if ($value['id'] == $id) {
  8093. $id_prerequisite = $value['prerequisite'];
  8094. break;
  8095. }
  8096. }
  8097. }
  8098. $arrHide = array();
  8099. for ($i = 0; $i < count($arrLP); $i++) {
  8100. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8101. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8102. $s_selected_position = $arrLP[$i]['id'];
  8103. } elseif ($action == 'add') {
  8104. $s_selected_position = 0;
  8105. }
  8106. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8107. }
  8108. }
  8109. }
  8110. if ($action == 'add') {
  8111. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8112. } else {
  8113. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8114. }
  8115. if ($action == 'move') {
  8116. $form->addHidden('title', $item_title);
  8117. $form->addHidden('description', $item_description);
  8118. }
  8119. if (is_numeric($extra_info)) {
  8120. $form->addHidden('path', $extra_info);
  8121. } elseif (is_array($extra_info)) {
  8122. $form->addHidden('path', $extra_info['path']);
  8123. }
  8124. $form->addHidden('type', TOOL_LINK);
  8125. $form->addHidden('post_time', time());
  8126. $form->setDefaults($defaults);
  8127. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8128. }
  8129. /**
  8130. * Return HTML form to add/edit a student publication (work)
  8131. * @param string Action (add/edit)
  8132. * @param integer Item ID if already exists
  8133. * @param mixed Extra info (work ID if integer)
  8134. * @return string HTML form
  8135. */
  8136. public function display_student_publication_form($action = 'add', $id = 0, $extra_info = '')
  8137. {
  8138. $course_id = api_get_course_int_id();
  8139. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8140. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8141. if ($id != 0 && is_array($extra_info)) {
  8142. $item_title = stripslashes($extra_info['title']);
  8143. $item_description = stripslashes($extra_info['description']);
  8144. } elseif (is_numeric($extra_info)) {
  8145. $extra_info = intval($extra_info);
  8146. $sql
  8147. = "SELECT title, description
  8148. FROM $tbl_publication
  8149. WHERE c_id = $course_id AND id = ".$extra_info;
  8150. $result = Database::query($sql);
  8151. $row = Database::fetch_array($result);
  8152. $item_title = $row['title'];
  8153. } else {
  8154. $item_title = get_lang('Student_publication');
  8155. }
  8156. if ($id != 0 && is_array($extra_info)) {
  8157. $parent = $extra_info['parent_item_id'];
  8158. } else {
  8159. $parent = 0;
  8160. }
  8161. $sql
  8162. = "SELECT * FROM $tbl_lp_item
  8163. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8164. $result = Database::query($sql);
  8165. $arrLP = array();
  8166. while ($row = Database::fetch_array($result)) {
  8167. $arrLP[] = array(
  8168. 'id' => $row['id'],
  8169. 'item_type' => $row['item_type'],
  8170. 'title' => $row['title'],
  8171. 'path' => $row['path'],
  8172. 'description' => $row['description'],
  8173. 'parent_item_id' => $row['parent_item_id'],
  8174. 'previous_item_id' => $row['previous_item_id'],
  8175. 'next_item_id' => $row['next_item_id'],
  8176. 'display_order' => $row['display_order'],
  8177. 'max_score' => $row['max_score'],
  8178. 'min_score' => $row['min_score'],
  8179. 'mastery_score' => $row['mastery_score'],
  8180. 'prerequisite' => $row['prerequisite']
  8181. );
  8182. }
  8183. $this->tree_array($arrLP);
  8184. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8185. unset($this->arrMenu);
  8186. $form = new FormValidator('frm_student_publication', 'post', '#');
  8187. if ($action == 'add') {
  8188. $form->addHeader(get_lang('Student_publication'));
  8189. } elseif ($action == 'move') {
  8190. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8191. } else {
  8192. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8193. }
  8194. if ($action != 'move') {
  8195. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form', 'id' => 'idTitle']);
  8196. }
  8197. $parentSelect = $form->addSelect(
  8198. 'parent',
  8199. get_lang('Parent'),
  8200. ['0' => $this->name],
  8201. [
  8202. 'onchange' => 'javascript: load_cbo(this.value);',
  8203. 'class' => 'learnpath_item_form',
  8204. 'id' => 'idParent'
  8205. ]
  8206. );
  8207. $arrHide = array($id);
  8208. for ($i = 0; $i < count($arrLP); $i++) {
  8209. if ($action != 'add') {
  8210. if (
  8211. ($arrLP[$i]['item_type'] == 'dir') && !in_array($arrLP[$i]['id'], $arrHide)
  8212. && !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8213. ) {
  8214. $parentSelect->addOption(
  8215. $arrLP[$i]['title'],
  8216. $arrLP[$i]['id'],
  8217. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8218. );
  8219. if ($parent == $arrLP[$i]['id']) {
  8220. $parentSelect->setSelected($arrLP[$i]['id']);
  8221. }
  8222. } else {
  8223. $arrHide[] = $arrLP[$i]['id'];
  8224. }
  8225. } else {
  8226. if ($arrLP[$i]['item_type'] == 'dir') {
  8227. $parentSelect->addOption(
  8228. $arrLP[$i]['title'],
  8229. $arrLP[$i]['id'],
  8230. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8231. );
  8232. if ($parent == $arrLP[$i]['id']) {
  8233. $parentSelect->setSelected($arrLP[$i]['id']);
  8234. }
  8235. }
  8236. }
  8237. }
  8238. if (is_array($arrLP)) {
  8239. reset($arrLP);
  8240. }
  8241. $previousSelect = $form->addSelect(
  8242. 'previous',
  8243. get_lang('Position'),
  8244. ['0' => get_lang('FirstPosition')],
  8245. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8246. );
  8247. for ($i = 0; $i < count($arrLP); $i++) {
  8248. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8249. $previousSelect->addOption(
  8250. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8251. $arrLP[$i]['id']
  8252. );
  8253. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8254. $previousSelect->setSelected($arrLP[$i]['id']);
  8255. } elseif ($action == 'add') {
  8256. $previousSelect->setSelected($arrLP[$i]['id']);
  8257. }
  8258. }
  8259. }
  8260. if ($action != 'move') {
  8261. $id_prerequisite = 0;
  8262. if (is_array($arrLP)) {
  8263. foreach ($arrLP as $key => $value) {
  8264. if ($value['id'] == $id) {
  8265. $id_prerequisite = $value['prerequisite'];
  8266. break;
  8267. }
  8268. }
  8269. }
  8270. $arrHide = array();
  8271. for ($i = 0; $i < count($arrLP); $i++) {
  8272. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8273. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8274. $s_selected_position = $arrLP[$i]['id'];
  8275. } elseif ($action == 'add') {
  8276. $s_selected_position = 0;
  8277. }
  8278. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8279. }
  8280. }
  8281. }
  8282. if ($action == 'add') {
  8283. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8284. } else {
  8285. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8286. }
  8287. if ($action == 'move') {
  8288. $form->addHidden('title', $item_title);
  8289. $form->addHidden('description', $item_description);
  8290. }
  8291. if (is_numeric($extra_info)) {
  8292. $form->addHidden('path', $extra_info);
  8293. } elseif (is_array($extra_info)) {
  8294. $form->addHidden('path', $extra_info['path']);
  8295. }
  8296. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8297. $form->addHidden('post_time', time());
  8298. $form->setDefaults(['title' => $item_title]);
  8299. $return = '<div class="sectioncomment">';
  8300. $return .= $form->returnForm();
  8301. $return .= '</div>';
  8302. return $return;
  8303. }
  8304. /**
  8305. * Displays the menu for manipulating a step
  8306. * @param $item_id
  8307. * @param string $item_type
  8308. * @return string
  8309. */
  8310. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8311. {
  8312. $_course = api_get_course_info();
  8313. $course_id = api_get_course_int_id();
  8314. $course_code = api_get_course_id();
  8315. $return = '<div class="actions">';
  8316. switch ($item_type) {
  8317. case 'dir':
  8318. // Commented the message cause should not show it.
  8319. //$lang = get_lang('TitleManipulateChapter');
  8320. break;
  8321. case TOOL_LP_FINAL_ITEM:
  8322. case TOOL_DOCUMENT:
  8323. // Commented the message cause should not show it.
  8324. //$lang = get_lang('TitleManipulateDocument');
  8325. break;
  8326. case TOOL_LINK:
  8327. case 'link' :
  8328. // Commented the message cause should not show it.
  8329. //$lang = get_lang('TitleManipulateLink');
  8330. break;
  8331. case TOOL_QUIZ:
  8332. // Commented the message cause should not show it.
  8333. //$lang = get_lang('TitleManipulateQuiz');
  8334. break;
  8335. case TOOL_STUDENTPUBLICATION:
  8336. // Commented the message cause should not show it.
  8337. //$lang = get_lang('TitleManipulateStudentPublication');
  8338. break;
  8339. }
  8340. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8341. $item_id = intval($item_id);
  8342. $sql = "SELECT * FROM ".$tbl_lp_item." as lp
  8343. WHERE lp.c_id = ".$course_id." AND lp.id = ".$item_id;
  8344. $result = Database::query($sql);
  8345. $row = Database::fetch_assoc($result);
  8346. $audio_player = null;
  8347. // We display an audio player if needed.
  8348. if (!empty($row['audio'])) {
  8349. $audio_player
  8350. .= '<div class="lp_mediaplayer" id="container">
  8351. <a href="http://www.macromedia.com/go/getflashplayer">Get the Flash Player</a> to see this player.
  8352. </div>';
  8353. $audio_player .= '<script type="text/javascript" src="../inc/lib/mediaplayer/swfobject.js"></script>';
  8354. $audio_player
  8355. .= '<script>
  8356. var s1 = new SWFObject("../inc/lib/mediaplayer/player.swf","ply","250","20","9","#FFFFFF");
  8357. s1.addParam("allowscriptaccess","always");
  8358. s1.addParam("flashvars","file=../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'
  8359. .$row['audio'].'&autostart=true");
  8360. s1.write("container");
  8361. </script>';
  8362. }
  8363. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8364. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8365. $return .= Display::url(
  8366. Display::return_icon(
  8367. 'edit.png',
  8368. get_lang('Edit'),
  8369. array(),
  8370. ICON_SIZE_SMALL
  8371. ),
  8372. $url.'&action=edit_item&path_item='.$row['path']
  8373. );
  8374. $return .= Display::url(
  8375. Display::return_icon(
  8376. 'move.png',
  8377. get_lang('Move'),
  8378. array(),
  8379. ICON_SIZE_SMALL
  8380. ),
  8381. $url.'&action=move_item'
  8382. );
  8383. }
  8384. // Commented for now as prerequisites cannot be added to chapters.
  8385. if ($item_type != 'dir') {
  8386. $return .= Display::url(
  8387. Display::return_icon('accept.png', get_lang('LearnpathPrerequisites'), array(), ICON_SIZE_SMALL),
  8388. $url.'&action=edit_item_prereq'
  8389. );
  8390. }
  8391. $return .= Display::url(
  8392. Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL),
  8393. $url.'&action=delete_item'
  8394. );
  8395. if ($item_type == TOOL_HOTPOTATOES) {
  8396. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8397. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8398. }
  8399. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  8400. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8401. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8402. }
  8403. $return .= '</div>';
  8404. if (!empty($audio_player)) {
  8405. $return .= '<br />'.$audio_player;
  8406. }
  8407. return $return;
  8408. }
  8409. /**
  8410. * Creates the javascript needed for filling up the checkboxes without page reload
  8411. * @return string
  8412. */
  8413. public function get_js_dropdown_array()
  8414. {
  8415. $course_id = api_get_course_int_id();
  8416. $return = 'var child_name = new Array();'."\n";
  8417. $return .= 'var child_value = new Array();'."\n\n";
  8418. $return .= 'child_name[0] = new Array();'."\n";
  8419. $return .= 'child_value[0] = new Array();'."\n\n";
  8420. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8421. $sql = "SELECT * FROM ".$tbl_lp_item."
  8422. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id." AND parent_item_id = 0
  8423. ORDER BY display_order ASC";
  8424. $res_zero = Database::query($sql);
  8425. $i = 0;
  8426. while ($row_zero = Database::fetch_array($res_zero)) {
  8427. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8428. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8429. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8430. }
  8431. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8432. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8433. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['id'].'";'."\n";
  8434. }
  8435. }
  8436. $return .= "\n";
  8437. $sql = "SELECT * FROM ".$tbl_lp_item."
  8438. WHERE c_id = ".$course_id." AND lp_id = ".$this->lp_id;
  8439. $res = Database::query($sql);
  8440. while ($row = Database::fetch_array($res)) {
  8441. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8442. WHERE
  8443. c_id = ".$course_id." AND
  8444. parent_item_id = ".$row['id']."
  8445. ORDER BY display_order ASC";
  8446. $res_parent = Database::query($sql_parent);
  8447. $i = 0;
  8448. $return .= 'child_name['.$row['id'].'] = new Array();'."\n";
  8449. $return .= 'child_value['.$row['id'].'] = new Array();'."\n\n";
  8450. while ($row_parent = Database::fetch_array($res_parent)) {
  8451. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  8452. $return .= 'child_name['.$row['id'].']['.$i.'] = '.$js_var.' ;'."\n";
  8453. $return .= 'child_value['.$row['id'].']['.$i++.'] = "'.$row_parent['id'].'";'."\n";
  8454. }
  8455. $return .= "\n";
  8456. }
  8457. return $return;
  8458. }
  8459. /**
  8460. * Display the form to allow moving an item
  8461. * @param integer Item ID
  8462. * @return string HTML form
  8463. */
  8464. public function display_move_item($item_id)
  8465. {
  8466. $course_id = api_get_course_int_id();
  8467. $return = '';
  8468. if (is_numeric($item_id)) {
  8469. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8470. $sql = "SELECT * FROM ".$tbl_lp_item."
  8471. WHERE c_id = ".$course_id." AND id = ".$item_id;
  8472. $res = Database::query($sql);
  8473. $row = Database::fetch_array($res);
  8474. switch ($row['item_type']) {
  8475. case 'dir':
  8476. case 'asset':
  8477. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8478. $return .= $this->display_item_form($row['item_type'], get_lang('MoveCurrentChapter'), 'move',
  8479. $item_id, $row);
  8480. break;
  8481. case TOOL_DOCUMENT:
  8482. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8483. $return .= $this->display_document_form('move', $item_id, $row);
  8484. break;
  8485. case TOOL_LINK:
  8486. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8487. $return .= $this->display_link_form('move', $item_id, $row);
  8488. break;
  8489. case TOOL_HOTPOTATOES:
  8490. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8491. $return .= $this->display_link_form('move', $item_id, $row);
  8492. break;
  8493. case TOOL_QUIZ:
  8494. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8495. $return .= $this->display_quiz_form('move', $item_id, $row);
  8496. break;
  8497. case TOOL_STUDENTPUBLICATION:
  8498. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8499. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8500. break;
  8501. case TOOL_FORUM:
  8502. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8503. $return .= $this->display_forum_form('move', $item_id, $row);
  8504. break;
  8505. case TOOL_THREAD:
  8506. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8507. $return .= $this->display_forum_form('move', $item_id, $row);
  8508. break;
  8509. }
  8510. }
  8511. return $return;
  8512. }
  8513. /**
  8514. * Displays a basic form on the overview page for changing the item title and the item description.
  8515. * @param string $item_type
  8516. * @param string $title
  8517. * @param array $data
  8518. * @return string
  8519. */
  8520. public function display_item_small_form($item_type, $title = '', $data = array())
  8521. {
  8522. $url = api_get_self().'?'.api_get_cidreq().'&action=edit_item&lp_id='.$this->lp_id;
  8523. $form = new FormValidator('small_form', 'post', $url);
  8524. $form->addElement('header', $title);
  8525. $form->addElement('text', 'title', get_lang('Title'));
  8526. $form->addButtonSave(get_lang('Save'), 'submit_button');
  8527. $form->addElement('hidden', 'id', $data['id']);
  8528. $form->addElement('hidden', 'parent', $data['parent_item_id']);
  8529. $form->addElement('hidden', 'previous', $data['previous_item_id']);
  8530. $form->setDefaults(array('title' => $data['title']));
  8531. return $form->toHtml();
  8532. }
  8533. /**
  8534. * Return HTML form to allow prerequisites selection
  8535. * @todo use FormValidator
  8536. * @param integer Item ID
  8537. * @return string HTML form
  8538. */
  8539. public function display_item_prerequisites_form($item_id)
  8540. {
  8541. $course_id = api_get_course_int_id();
  8542. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8543. $item_id = intval($item_id);
  8544. /* Current prerequisite */
  8545. $sql
  8546. = "SELECT * FROM $tbl_lp_item
  8547. WHERE c_id = $course_id AND id = ".$item_id;
  8548. $result = Database::query($sql);
  8549. $row = Database::fetch_array($result);
  8550. $prerequisiteId = $row['prerequisite'];
  8551. $return = '<legend>';
  8552. $return .= get_lang('AddEditPrerequisites');
  8553. $return .= '</legend>';
  8554. $return .= '<form method="POST">';
  8555. $return .= '<div class="table-responsive">';
  8556. $return .= '<table class="table table-hover">';
  8557. $return .= '<tr>';
  8558. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8559. $return .= '<th width="140" >'.get_lang('Minimum').'</th>';
  8560. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8561. $return .= '</tr>';
  8562. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8563. $return .= '<tr>';
  8564. $return .= '<td colspan="3">';
  8565. $return .= '<div class="radio learnpath"><label for="idNone">';
  8566. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8567. $return .= get_lang('None').'</label>';
  8568. $return .= '</div>';
  8569. $return .= '</tr>';
  8570. $sql
  8571. = "SELECT * FROM $tbl_lp_item
  8572. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8573. $result = Database::query($sql);
  8574. $arrLP = array();
  8575. $selectedMinScore = array();
  8576. $selectedMaxScore = array();
  8577. while ($row = Database::fetch_array($result)) {
  8578. if ($row['id'] == $item_id) {
  8579. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8580. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8581. }
  8582. $arrLP[] = array(
  8583. 'id' => $row['id'],
  8584. 'item_type' => $row['item_type'],
  8585. 'title' => $row['title'],
  8586. 'ref' => $row['ref'],
  8587. 'description' => $row['description'],
  8588. 'parent_item_id' => $row['parent_item_id'],
  8589. 'previous_item_id' => $row['previous_item_id'],
  8590. 'next_item_id' => $row['next_item_id'],
  8591. 'max_score' => $row['max_score'],
  8592. 'min_score' => $row['min_score'],
  8593. 'mastery_score' => $row['mastery_score'],
  8594. 'prerequisite' => $row['prerequisite'],
  8595. 'next_item_id' => $row['next_item_id'],
  8596. 'display_order' => $row['display_order'],
  8597. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  8598. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  8599. );
  8600. }
  8601. $this->tree_array($arrLP);
  8602. $arrLP = isset($this->arrMenu) ? $this->arrMenu : null;
  8603. unset($this->arrMenu);
  8604. for ($i = 0; $i < count($arrLP); $i++) {
  8605. $item = $arrLP[$i];
  8606. if ($item['id'] == $item_id) {
  8607. break;
  8608. }
  8609. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']]
  8610. : $item['max_score'];
  8611. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8612. $return .= '<tr>';
  8613. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES)
  8614. ? ' colspan="3"' : '').'>';
  8615. $return .= '<div style="margin-left:'.$item['depth'] * 20 .'px;" class="radio learnpath">';
  8616. $return .= '<label for="id'.$item['id'].'">';
  8617. $return .= '<input'.(in_array($prerequisiteId, array($item['id'], $item['ref'])) ? ' checked="checked" '
  8618. : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id']
  8619. .'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  8620. $icon_name = str_replace(' ', '', $item['item_type']);
  8621. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8622. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8623. } else {
  8624. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8625. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8626. } else {
  8627. $return .= Display::return_icon('folder_document.png');
  8628. }
  8629. }
  8630. $return .= $item['title'].'</label>';
  8631. $return .= '</div>';
  8632. $return .= '</td>';
  8633. if ($item['item_type'] == TOOL_QUIZ) {
  8634. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8635. $tmp_obj_lp_item = new LpItem($course_id, $item['id']);
  8636. $tmp_obj_exercice = new Exercise();
  8637. $tmp_obj_exercice->read($tmp_obj_lp_item->path);
  8638. $tmp_obj_lp_item->max_score = $tmp_obj_exercice->get_max_score();
  8639. $tmp_obj_lp_item->update_in_bdd();
  8640. $item['max_score'] = $tmp_obj_lp_item->max_score;
  8641. $return .= '<td>';
  8642. $return .= '<input class="form-control" size="4" maxlength="3" name="min_'.$item['id']
  8643. .'" type="number" min="0" step="any" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue
  8644. .'" />';
  8645. $return .= '</td>';
  8646. $return .= '<td>';
  8647. $return .= '<input class="form-control" size="4" maxlength="3" name="max_'.$item['id']
  8648. .'" type="number" min="0" step="any" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue
  8649. .'" />';
  8650. $return .= '</td>';
  8651. }
  8652. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8653. $return .= '<td>';
  8654. $return .= '<center><input size="4" maxlength="3" name="min_'.$item['id']
  8655. .'" type="number" min="0" step="any" max="'.$item['max_score'].'" value="'.$selectedMinScoreValue
  8656. .'" /></center>';
  8657. $return .= '</td>';
  8658. $return .= '<td>';
  8659. $return .= '<center><input size="4" maxlength="3" name="max_'.$item['id']
  8660. .'" type="number" min="0" step="any" max="'.$item['max_score'].'" value="'.$selectedMaxScoreValue
  8661. .'" /></center>';
  8662. $return .= '</td>';
  8663. }
  8664. $return .= '</tr>';
  8665. }
  8666. $return .= '<tr>';
  8667. $return .= '</tr>';
  8668. $return .= '</table>';
  8669. $return .= '</div>';
  8670. $return .= '<div class="form-group">';
  8671. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.get_lang('ModifyPrerequisites')
  8672. .'</button>';
  8673. $return .= '</form>';
  8674. return $return;
  8675. }
  8676. /**
  8677. * Return HTML list to allow prerequisites selection for lp
  8678. * @param integer Item ID
  8679. * @return string HTML form
  8680. */
  8681. public function display_lp_prerequisites_list()
  8682. {
  8683. $course_id = api_get_course_int_id();
  8684. $lp_id = $this->lp_id;
  8685. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  8686. // get current prerequisite
  8687. $sql = "SELECT * FROM $tbl_lp WHERE c_id = $course_id AND id = $lp_id ";
  8688. $result = Database::query($sql);
  8689. $row = Database::fetch_array($result);
  8690. $prerequisiteId = $row['prerequisite'];
  8691. $session_id = api_get_session_id();
  8692. $session_condition = api_get_session_condition($session_id, true, true);
  8693. $sql
  8694. = "SELECT * FROM $tbl_lp
  8695. WHERE c_id = $course_id $session_condition
  8696. ORDER BY display_order ";
  8697. $rs = Database::query($sql);
  8698. $return = '';
  8699. $return .= '<select name="prerequisites" class="form-control">';
  8700. $return .= '<option value="0">'.get_lang('None').'</option>';
  8701. if (Database::num_rows($rs) > 0) {
  8702. while ($row = Database::fetch_array($rs)) {
  8703. if ($row['id'] == $lp_id) {
  8704. continue;
  8705. }
  8706. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'
  8707. .$row['name'].'</option>';
  8708. }
  8709. }
  8710. $return .= '</select>';
  8711. return $return;
  8712. }
  8713. /**
  8714. * Creates a list with all the documents in it
  8715. * @param bool $showInvisibleFiles
  8716. * @return string
  8717. */
  8718. public function get_documents($showInvisibleFiles = false)
  8719. {
  8720. $course_info = api_get_course_info();
  8721. $sessionId = api_get_session_id();
  8722. $documentTree = DocumentManager::get_document_preview(
  8723. $course_info,
  8724. $this->lp_id,
  8725. null,
  8726. $sessionId,
  8727. true,
  8728. null,
  8729. null,
  8730. $showInvisibleFiles,
  8731. true
  8732. );
  8733. $headers = array(
  8734. get_lang('Files'),
  8735. get_lang('CreateTheDocument'),
  8736. get_lang('Upload')
  8737. );
  8738. $form = new FormValidator(
  8739. 'form_upload',
  8740. 'POST',
  8741. $this->getCurrentBuildingModeURL(),
  8742. '',
  8743. array('enctype' => 'multipart/form-data'),
  8744. FormValidator::LAYOUT_INLINE
  8745. );
  8746. $folders = DocumentManager::get_all_document_folders(
  8747. api_get_course_info(),
  8748. 0,
  8749. true
  8750. );
  8751. DocumentManager::build_directory_selector(
  8752. $folders,
  8753. '',
  8754. array(),
  8755. true,
  8756. $form,
  8757. 'directory_parent_id'
  8758. );
  8759. $form->addHtml('<hr>');
  8760. $group = array(
  8761. $form->createElement(
  8762. 'radio',
  8763. 'if_exists',
  8764. get_lang("UplWhatIfFileExists"),
  8765. get_lang('Yes'),
  8766. 'nothing'
  8767. ),
  8768. $form->createElement(
  8769. 'radio',
  8770. 'if_exists',
  8771. null,
  8772. get_lang('UplOverwriteLong'),
  8773. 'overwrite'
  8774. ),
  8775. $form->createElement(
  8776. 'radio',
  8777. 'if_exists',
  8778. null,
  8779. get_lang('UplRenameLong'),
  8780. 'rename'
  8781. )
  8782. );
  8783. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  8784. $form->addHtml('<br />');
  8785. /*$form->addElement('radio', 'if_exists', get_lang('UplWhatIfFileExists'), get_lang('UplDoNothing'), 'nothing');
  8786. $form->addElement('radio', 'if_exists', '', get_lang('UplOverwriteLong'), 'overwrite');
  8787. $form->addElement('radio', 'if_exists', '', get_lang('UplRenameLong'), 'rename');*/
  8788. $form->setDefaults(['if_exists' => 'rename']);
  8789. // Check box options
  8790. $form->addElement(
  8791. 'checkbox',
  8792. 'unzip',
  8793. get_lang('Options'),
  8794. get_lang('Uncompress')
  8795. );
  8796. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  8797. $form->addMultipleUpload($url);
  8798. $new = $this->display_document_form('add', 0);
  8799. $tabs = Display::tabs($headers, array($documentTree, $new, $form->returnForm()), 'subtab');
  8800. return $tabs;
  8801. }
  8802. /**
  8803. * Creates a list with all the exercises (quiz) in it
  8804. * @return string
  8805. */
  8806. public function get_exercises()
  8807. {
  8808. $course_id = api_get_course_int_id();
  8809. $session_id = api_get_session_id();
  8810. $userInfo = api_get_user_info();
  8811. // New for hotpotatoes.
  8812. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  8813. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8814. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  8815. $condition_session = api_get_session_condition($session_id, true, true);
  8816. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  8817. $activeCondition = ' active <> -1 ';
  8818. if ($setting) {
  8819. $activeCondition = ' active = 1 ';
  8820. }
  8821. $sql_quiz
  8822. = "SELECT * FROM $tbl_quiz
  8823. WHERE c_id = $course_id AND $activeCondition $condition_session
  8824. ORDER BY title ASC";
  8825. $sql_hot
  8826. = "SELECT * FROM $tbl_doc
  8827. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  8828. ORDER BY id ASC";
  8829. $res_quiz = Database::query($sql_quiz);
  8830. $res_hot = Database::query($sql_hot);
  8831. $return = '<ul class="lp_resource">';
  8832. $return .= '<li class="lp_resource_element">';
  8833. $return .= Display::return_icon('new_exercice.png');
  8834. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='
  8835. .$this->lp_id.'">'.
  8836. get_lang('NewExercise').'</a>';
  8837. $return .= '</li>';
  8838. $previewIcon = Display::return_icon('preview_view.png', get_lang('Preview'));
  8839. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  8840. // Display hotpotatoes
  8841. while ($row_hot = Database::fetch_array($res_hot)) {
  8842. $link = Display::url(
  8843. $previewIcon,
  8844. $exerciseUrl.'&file='.$row_hot['path'],
  8845. ['target' => '_blank']
  8846. );
  8847. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'
  8848. .$row_hot['title'].'" >';
  8849. $return .= '<a class="moved" href="#">';
  8850. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  8851. $return .= '</a> ';
  8852. $return .= Display::return_icon('hotpotatoes_s.png');
  8853. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES
  8854. .'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  8855. ((!empty ($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link
  8856. .'</a>';
  8857. $return .= '</li>';
  8858. }
  8859. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  8860. while ($row_quiz = Database::fetch_array($res_quiz)) {
  8861. $title = strip_tags(
  8862. api_html_entity_decode($row_quiz['title'])
  8863. );
  8864. $link = Display::url(
  8865. $previewIcon,
  8866. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  8867. ['target' => '_blank']
  8868. );
  8869. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title
  8870. .'" >';
  8871. $return .= '<a class="moved" href="#">';
  8872. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  8873. $return .= '</a> ';
  8874. $return .= Display::return_icon('quizz_small.gif', '', array(), ICON_SIZE_TINY);
  8875. $sessionStar = api_get_session_image($row_quiz['session_id'], $userInfo['status']);
  8876. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ
  8877. .'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id.'">'.
  8878. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  8879. '</a>';
  8880. $return .= '</li>';
  8881. }
  8882. $return .= '</ul>';
  8883. return $return;
  8884. }
  8885. /**
  8886. * Creates a list with all the links in it
  8887. * @return string
  8888. */
  8889. public function get_links()
  8890. {
  8891. $selfUrl = api_get_self();
  8892. $courseIdReq = api_get_cidreq();
  8893. $course = api_get_course_info();
  8894. $userInfo = api_get_user_info();
  8895. $course_id = $course['real_id'];
  8896. $tbl_link = Database::get_course_table(TABLE_LINK);
  8897. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  8898. $moveEverywhereIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  8899. $session_id = api_get_session_id();
  8900. $condition_session = api_get_session_condition(
  8901. $session_id,
  8902. true,
  8903. true,
  8904. "link.session_id"
  8905. );
  8906. $sql
  8907. = "SELECT
  8908. link.id as link_id,
  8909. link.title as link_title,
  8910. link.session_id as link_session_id,
  8911. link.category_id as category_id,
  8912. link_category.category_title as category_title
  8913. FROM $tbl_link as link
  8914. LEFT JOIN $linkCategoryTable as link_category
  8915. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  8916. WHERE link.c_id = ".$course_id." $condition_session
  8917. ORDER BY link_category.category_title ASC, link.title ASC";
  8918. $result = Database::query($sql);
  8919. $categorizedLinks = array();
  8920. $categories = array();
  8921. while ($link = Database::fetch_array($result)) {
  8922. if (!$link['category_id']) {
  8923. $link['category_title'] = get_lang('Uncategorized');
  8924. }
  8925. $categories[$link['category_id']] = $link['category_title'];
  8926. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  8927. }
  8928. $linksHtmlCode
  8929. = '<script>
  8930. function toggle_tool(tool, id){
  8931. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  8932. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  8933. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  8934. } else {
  8935. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  8936. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  8937. }
  8938. }
  8939. </script>
  8940. <ul class="lp_resource">
  8941. <li class="lp_resource_element">
  8942. '.Display::return_icon('linksnew.gif').'
  8943. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='
  8944. .$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  8945. get_lang('LinkAdd').'
  8946. </a>
  8947. </li>';
  8948. foreach ($categorizedLinks as $categoryId => $links) {
  8949. $linkNodes = null;
  8950. foreach ($links as $key => $linkInfo) {
  8951. $title = $linkInfo['link_title'];
  8952. $linkSessionId = $linkInfo['link_session_id'];
  8953. $link = Display::url(
  8954. Display::return_icon('preview_view.png', get_lang('Preview')),
  8955. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  8956. ['target' => '_blank']
  8957. );
  8958. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  8959. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  8960. $linkNodes .= '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'
  8961. .$title.'" >
  8962. <a class="moved" href="#">'.
  8963. $moveEverywhereIcon.
  8964. '</a>
  8965. '.Display::return_icon('lp_link.png').'
  8966. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  8967. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  8968. Security::remove_XSS($title).$sessionStar.$link.
  8969. '</a>
  8970. </li>';
  8971. }
  8972. }
  8973. $linksHtmlCode
  8974. .= '<li>
  8975. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  8976. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  8977. align="absbottom" />
  8978. </a>
  8979. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  8980. </li>
  8981. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  8982. }
  8983. $linksHtmlCode .= '</ul>';
  8984. return $linksHtmlCode;
  8985. }
  8986. /**
  8987. * Creates a list with all the student publications in it
  8988. * @return string
  8989. */
  8990. public function get_student_publications()
  8991. {
  8992. $return = '<ul class="lp_resource">';
  8993. $return .= '<li class="lp_resource_element">';
  8994. $return .= Display::return_icon('works_new.gif');
  8995. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION
  8996. .'&lp_id='.$this->lp_id.'">'.
  8997. get_lang('AddAssignmentPage').'</a>';
  8998. $return .= '</li>';
  8999. $sessionId = api_get_session_id();
  9000. if (empty($sessionId)) {
  9001. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9002. $works = getWorkListTeacher(0, 100, null, null, null);
  9003. if (!empty($works)) {
  9004. foreach ($works as $work) {
  9005. $link = Display::url(
  9006. Display::return_icon('preview_view.png', get_lang('Preview')),
  9007. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9008. ['target' => '_blank']
  9009. );
  9010. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'
  9011. .TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80))
  9012. .'">';
  9013. $return .= '<a class="moved" href="#">';
  9014. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  9015. $return .= '</a> ';
  9016. $return .= Display::return_icon('works.gif');
  9017. $return .= ' <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='
  9018. .TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id.'">'.
  9019. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9020. </a>';
  9021. $return .= '</li>';
  9022. }
  9023. }
  9024. }
  9025. $return .= '</ul>';
  9026. return $return;
  9027. }
  9028. /**
  9029. * Creates a list with all the forums in it
  9030. * @return string
  9031. */
  9032. public function get_forums()
  9033. {
  9034. require_once '../forum/forumfunction.inc.php';
  9035. require_once '../forum/forumconfig.inc.php';
  9036. $forumCategories = get_forum_categories();
  9037. $forumsInNoCategory = get_forums_in_category(0);
  9038. if (!empty($forumsInNoCategory)) {
  9039. $forumCategories = array_merge(
  9040. $forumCategories,
  9041. array(
  9042. array(
  9043. 'cat_id' => 0,
  9044. 'session_id' => 0,
  9045. 'visibility' => 1,
  9046. 'cat_comment' => null,
  9047. ),
  9048. )
  9049. );
  9050. }
  9051. $forumList = get_forums();
  9052. $a_forums = [];
  9053. foreach ($forumCategories as $forumCategory) {
  9054. // The forums in this category.
  9055. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9056. if (!empty($forumsInCategory)) {
  9057. foreach ($forumList as $forum) {
  9058. if (isset($forum['forum_category']) && $forum['forum_category'] == $forumCategory['cat_id']) {
  9059. $a_forums[] = $forum;
  9060. }
  9061. }
  9062. }
  9063. }
  9064. $return = '<ul class="lp_resource">';
  9065. // First add link
  9066. $return .= '<li class="lp_resource_element">';
  9067. $return .= Display::return_icon('new_forum.png');
  9068. $return .= Display::url(
  9069. get_lang('CreateANewForum'),
  9070. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9071. 'action' => 'add',
  9072. 'content' => 'forum',
  9073. 'lp_id' => $this->lp_id
  9074. ]),
  9075. ['title' => get_lang('CreateANewForum')]
  9076. );
  9077. $return .= '</li>';
  9078. $return
  9079. .= '<script>
  9080. function toggle_forum(forum_id) {
  9081. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9082. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9083. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9084. } else {
  9085. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9086. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9087. }
  9088. }
  9089. </script>';
  9090. foreach ($a_forums as $forum) {
  9091. if (!empty($forum['forum_id'])) {
  9092. $link = Display::url(
  9093. Display::return_icon('preview_view.png', get_lang('Preview')),
  9094. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9095. ['target' => '_blank']
  9096. );
  9097. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM
  9098. .'" title="'.$forum['forum_title'].'" >';
  9099. $return .= '<a class="moved" href="#">';
  9100. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(), ICON_SIZE_TINY);
  9101. $return .= ' </a>';
  9102. $return .= Display::return_icon('lp_forum.png', '', array(), ICON_SIZE_TINY);
  9103. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9104. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9105. </a>
  9106. <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='
  9107. .TOOL_FORUM.'&forum_id='.$forum['forum_id'].'&lp_id='.$this->lp_id
  9108. .'" style="vertical-align:middle">'.
  9109. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9110. $return .= '</li>';
  9111. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9112. $a_threads = get_threads($forum['forum_id']);
  9113. if (is_array($a_threads)) {
  9114. foreach ($a_threads as $thread) {
  9115. $link = Display::url(
  9116. Display::return_icon('preview_view.png', get_lang('Preview')),
  9117. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='
  9118. .$forum['forum_id'].'&thread='.$thread['thread_id'],
  9119. ['target' => '_blank']
  9120. );
  9121. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'
  9122. .TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9123. $return .= '&nbsp;<a class="moved" href="#">';
  9124. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), array(),
  9125. ICON_SIZE_TINY);
  9126. $return .= ' </a>';
  9127. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), array(), ICON_SIZE_TINY);
  9128. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq()
  9129. .'&action=add_item&type='.TOOL_THREAD.'&thread_id='.$thread['thread_id'].'&lp_id='
  9130. .$this->lp_id.'">'.
  9131. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9132. $return .= '</li>';
  9133. }
  9134. }
  9135. $return .= '</div>';
  9136. }
  9137. }
  9138. $return .= '</ul>';
  9139. return $return;
  9140. }
  9141. /**
  9142. * // TODO: The output encoding should be equal to the system encoding.
  9143. * Exports the learning path as a SCORM package. This is the main function that
  9144. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9145. * whole thing and returns the zip.
  9146. * This method needs to be called in PHP5, as it will fail with non-adequate
  9147. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9148. * you need to call it on a learnpath object.
  9149. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9150. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9151. * path has been modified, it should use the generic method here below.
  9152. * @TODO link this function with the export_lp() function in the same class
  9153. * @param string Optional name of zip file. If none, title of learnpath is
  9154. * domesticated and trailed with ".zip"
  9155. * @return string Returns the zip package string, or null if error
  9156. */
  9157. public function scorm_export()
  9158. {
  9159. $_course = api_get_course_info();
  9160. $course_id = $_course['real_id'];
  9161. // Remove memory and time limits as much as possible as this might be a long process...
  9162. if (function_exists('ini_set')) {
  9163. api_set_memory_limit('256M');
  9164. ini_set('max_execution_time', 600);
  9165. }
  9166. // Create the zip handler (this will remain available throughout the method).
  9167. $archive_path = api_get_path(SYS_ARCHIVE_PATH);
  9168. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9169. $temp_dir_short = uniqid();
  9170. $temp_zip_dir = $archive_path.'/'.$temp_dir_short;
  9171. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9172. $zip_folder = new PclZip($temp_zip_file);
  9173. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9174. $root_path = $main_path = api_get_path(SYS_PATH);
  9175. $files_cleanup = array();
  9176. // Place to temporarily stash the zip file.
  9177. // create the temp dir if it doesn't exist
  9178. // or do a cleanup before creating the zip file.
  9179. if (!is_dir($temp_zip_dir)) {
  9180. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9181. } else {
  9182. // Cleanup: Check the temp dir for old files and delete them.
  9183. $handle = opendir($temp_zip_dir);
  9184. while (false !== ($file = readdir($handle))) {
  9185. if ($file != '.' && $file != '..') {
  9186. unlink("$temp_zip_dir/$file");
  9187. }
  9188. }
  9189. closedir($handle);
  9190. }
  9191. $zip_files = $zip_files_abs = $zip_files_dist = array();
  9192. if (is_dir($current_course_path.'/scorm/'.$this->path)
  9193. && is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9194. ) {
  9195. // Remove the possible . at the end of the path.
  9196. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9197. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9198. mkdir($dest_path_to_scorm_folder, api_get_permissions_for_new_directories(), true);
  9199. copyr(
  9200. $current_course_path.'/scorm/'.$this->path,
  9201. $dest_path_to_scorm_folder,
  9202. array('imsmanifest'),
  9203. $zip_files
  9204. );
  9205. }
  9206. // Build a dummy imsmanifest structure.
  9207. // Do not add to the zip yet (we still need it).
  9208. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9209. // Aggregation Model official document, section "2.3 Content Packaging".
  9210. // We are going to build a UTF-8 encoded manifest. Later we will recode it to the desired (and supported) encoding.
  9211. $xmldoc = new DOMDocument('1.0');
  9212. $root = $xmldoc->createElement('manifest');
  9213. $root->setAttribute('identifier', 'SingleCourseManifest');
  9214. $root->setAttribute('version', '1.1');
  9215. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9216. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9217. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9218. $root->setAttribute('xsi:schemaLocation',
  9219. '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');
  9220. // Build mandatory sub-root container elements.
  9221. $metadata = $xmldoc->createElement('metadata');
  9222. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9223. $metadata->appendChild($md_schema);
  9224. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9225. $metadata->appendChild($md_schemaversion);
  9226. $root->appendChild($metadata);
  9227. $organizations = $xmldoc->createElement('organizations');
  9228. $resources = $xmldoc->createElement('resources');
  9229. // Build the only organization we will use in building our learnpaths.
  9230. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9231. $organization = $xmldoc->createElement('organization');
  9232. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9233. // To set the title of the SCORM entity (=organization), we take the name given
  9234. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9235. // learning path charset) as it is the encoding that defines how it is stored
  9236. // in the database. Then we convert it to HTML entities again as the "&" character
  9237. // alone is not authorized in XML (must be &amp;).
  9238. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9239. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9240. $organization->appendChild($org_title);
  9241. $folder_name = 'document';
  9242. // Removes the learning_path/scorm_folder path when exporting see #4841
  9243. $path_to_remove = null;
  9244. $result = $this->generate_lp_folder($_course);
  9245. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9246. $path_to_remove = 'document'.$result['dir'];
  9247. $path_to_replace = $folder_name.'/';
  9248. }
  9249. // Fixes chamilo scorm exports
  9250. if ($this->ref === 'chamilo_scorm_export') {
  9251. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9252. }
  9253. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9254. // Always call the learnpathItem->scorm_export() method to change it to the SCORM format.
  9255. $link_updates = array();
  9256. $links_to_create = array();
  9257. //foreach ($this->items as $index => $item) {
  9258. foreach ($this->ordered_items as $index => $itemId) {
  9259. $item = $this->items[$itemId];
  9260. if (!in_array($item->type, array(TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION))) {
  9261. // Get included documents from this item.
  9262. if ($item->type === 'sco') {
  9263. $inc_docs = $item->get_resources_from_source(
  9264. null,
  9265. api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'.'scorm/'.$this->path.'/'
  9266. .$item->get_path()
  9267. );
  9268. } else {
  9269. $inc_docs = $item->get_resources_from_source();
  9270. }
  9271. // Give a child element <item> to the <organization> element.
  9272. $my_item_id = $item->get_id();
  9273. $my_item = $xmldoc->createElement('item');
  9274. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9275. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9276. $my_item->setAttribute('isvisible', 'true');
  9277. // Give a child element <title> to the <item> element.
  9278. $my_title = $xmldoc->createElement('title',
  9279. htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
  9280. $my_item->appendChild($my_title);
  9281. // Give a child element <adlcp:prerequisites> to the <item> element.
  9282. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites',
  9283. $this->get_scorm_prereq_string($my_item_id));
  9284. $my_prereqs->setAttribute('type', 'aicc_script');
  9285. $my_item->appendChild($my_prereqs);
  9286. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9287. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9288. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9289. //$xmldoc->createElement('adlcp:timelimitaction','');
  9290. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9291. //$xmldoc->createElement('adlcp:datafromlms','');
  9292. // Give a child element <adlcp:masteryscore> to the <item> element.
  9293. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9294. $my_item->appendChild($my_masteryscore);
  9295. // Attach this item to the organization element or hits parent if there is one.
  9296. if (!empty($item->parent) && $item->parent != 0) {
  9297. $children = $organization->childNodes;
  9298. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9299. if (is_object($possible_parent)) {
  9300. $possible_parent->appendChild($my_item);
  9301. } else {
  9302. if ($this->debug > 0) {
  9303. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9304. }
  9305. }
  9306. } else {
  9307. if ($this->debug > 0) {
  9308. error_log('No parent');
  9309. }
  9310. $organization->appendChild($my_item);
  9311. }
  9312. // Get the path of the file(s) from the course directory root.
  9313. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9314. if (!empty($path_to_remove)) {
  9315. //From docs
  9316. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9317. //From quiz
  9318. if ($this->ref === 'chamilo_scorm_export') {
  9319. $path_to_remove = 'scorm/'.$this->path.'/';
  9320. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9321. }
  9322. } else {
  9323. $my_xml_file_path = $my_file_path;
  9324. }
  9325. $my_sub_dir = dirname($my_file_path);
  9326. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9327. $my_xml_sub_dir = $my_sub_dir;
  9328. // Give a <resource> child to the <resources> element
  9329. $my_resource = $xmldoc->createElement('resource');
  9330. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9331. $my_resource->setAttribute('type', 'webcontent');
  9332. $my_resource->setAttribute('href', $my_xml_file_path);
  9333. // adlcp:scormtype can be either 'sco' or 'asset'.
  9334. if ($item->type === 'sco') {
  9335. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9336. } else {
  9337. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9338. }
  9339. // xml:base is the base directory to find the files declared in this resource.
  9340. $my_resource->setAttribute('xml:base', '');
  9341. // Give a <file> child to the <resource> element.
  9342. $my_file = $xmldoc->createElement('file');
  9343. $my_file->setAttribute('href', $my_xml_file_path);
  9344. $my_resource->appendChild($my_file);
  9345. // Dependency to other files - not yet supported.
  9346. $i = 1;
  9347. if ($inc_docs) {
  9348. foreach ($inc_docs as $doc_info) {
  9349. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9350. continue;
  9351. }
  9352. $my_dep = $xmldoc->createElement('resource');
  9353. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9354. $my_dep->setAttribute('identifier', $res_id);
  9355. $my_dep->setAttribute('type', 'webcontent');
  9356. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9357. $my_dep_file = $xmldoc->createElement('file');
  9358. // Check type of URL.
  9359. if ($doc_info[1] == 'remote') {
  9360. // Remote file. Save url as is.
  9361. $my_dep_file->setAttribute('href', $doc_info[0]);
  9362. $my_dep->setAttribute('xml:base', '');
  9363. } elseif ($doc_info[1] === 'local') {
  9364. switch ($doc_info[2]) {
  9365. case 'url': // Local URL - save path as url for now, don't zip file.
  9366. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '',
  9367. $doc_info[0]);
  9368. $current_dir = dirname($abs_path);
  9369. $current_dir = str_replace('\\', '/', $current_dir);
  9370. $file_path = realpath($abs_path);
  9371. $file_path = str_replace('\\', '/', $file_path);
  9372. $my_dep_file->setAttribute('href', $file_path);
  9373. $my_dep->setAttribute('xml:base', '');
  9374. if (strstr($file_path, $main_path) !== false) {
  9375. // The calculated real path is really inside Chamilo's root path.
  9376. // Reduce file path to what's under the DocumentRoot.
  9377. $file_path = substr($file_path, strlen($root_path) - 1);
  9378. //echo $file_path;echo '<br /><br />';
  9379. //error_log(__LINE__.'Reduced url path: '.$file_path, 0);
  9380. $zip_files_abs[] = $file_path;
  9381. $link_updates[$my_file_path][] = array(
  9382. 'orig' => $doc_info[0],
  9383. 'dest' => $file_path
  9384. );
  9385. $my_dep_file->setAttribute('href', $file_path);
  9386. $my_dep->setAttribute('xml:base', '');
  9387. } elseif (empty($file_path)) {
  9388. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9389. if (strpos($document_root, -1) == '/') {
  9390. $document_root = substr(0, -1, $document_root);
  9391. }*/
  9392. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9393. $file_path = str_replace('//', '/', $file_path);
  9394. if (file_exists($file_path)) {
  9395. $file_path = substr($file_path,
  9396. strlen($current_dir)); // We get the relative path.
  9397. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9398. $link_updates[$my_file_path][] = array(
  9399. 'orig' => $doc_info[0],
  9400. 'dest' => $file_path
  9401. );
  9402. $my_dep_file->setAttribute('href', $file_path);
  9403. $my_dep->setAttribute('xml:base', '');
  9404. }
  9405. }
  9406. break;
  9407. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9408. $my_dep_file->setAttribute('href', $doc_info[0]);
  9409. $my_dep->setAttribute('xml:base', '');
  9410. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9411. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9412. $abs_img_path_without_subdir = $doc_info[0];
  9413. $relp = api_get_path(REL_PATH); // The url-append config param.
  9414. $pos = strpos($abs_img_path_without_subdir, $relp);
  9415. if ($pos === 0) {
  9416. $abs_img_path_without_subdir = '/'.substr($abs_img_path_without_subdir,
  9417. strlen($relp));
  9418. }
  9419. //$file_path = realpath(api_get_path(SYS_PATH).$abs_img_path_without_subdir);
  9420. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9421. $file_path = str_replace('\\', '/', $file_path);
  9422. $file_path = str_replace('//', '/', $file_path);
  9423. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9424. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path
  9425. : $current_course_path.'/';
  9426. // Check if the current document is in that path.
  9427. if (strstr($file_path, $cur_path) !== false) {
  9428. // The document is in that path, now get the relative path
  9429. // to the containing document.
  9430. $orig_file_path = dirname($cur_path.$my_file_path).'/';
  9431. $orig_file_path = str_replace('\\', '/', $orig_file_path);
  9432. $relative_path = '';
  9433. if (strstr($file_path, $cur_path) !== false) {
  9434. //$relative_path = substr($file_path, strlen($orig_file_path));
  9435. $relative_path = str_replace($cur_path, '', $file_path);
  9436. $file_path = substr($file_path, strlen($cur_path));
  9437. } else {
  9438. // This case is still a problem as it's difficult to calculate a relative path easily
  9439. // might still generate wrong links.
  9440. //$file_path = substr($file_path,strlen($cur_path));
  9441. // Calculate the directory path to the current file (without trailing slash).
  9442. $my_relative_path = dirname($file_path);
  9443. $my_relative_path = str_replace('\\', '/', $my_relative_path);
  9444. $my_relative_file = basename($file_path);
  9445. // Calculate the directory path to the containing file (without trailing slash).
  9446. $my_orig_file_path = substr($orig_file_path, 0, -1);
  9447. $dotdot = '';
  9448. $subdir = '';
  9449. while (strstr($my_relative_path, $my_orig_file_path) === false
  9450. && (strlen($my_orig_file_path) > 1)
  9451. && (strlen($my_relative_path) > 1)) {
  9452. $my_relative_path2 = dirname($my_relative_path);
  9453. $my_relative_path2 = str_replace('\\', '/', $my_relative_path2);
  9454. $my_orig_file_path = dirname($my_orig_file_path);
  9455. $my_orig_file_path = str_replace('\\', '/', $my_orig_file_path);
  9456. $subdir = substr($my_relative_path, strlen($my_relative_path2) + 1).'/'
  9457. .$subdir;
  9458. $dotdot += '../';
  9459. $my_relative_path = $my_relative_path2;
  9460. }
  9461. $relative_path = $dotdot.$subdir.$my_relative_file;
  9462. }
  9463. // Put the current document in the zip (this array is the array
  9464. // that will manage documents already in the course folder - relative).
  9465. $zip_files[] = $file_path;
  9466. // Update the links to the current document in the containing document (make them relative).
  9467. $link_updates[$my_file_path][] = array(
  9468. 'orig' => $doc_info[0],
  9469. 'dest' => $relative_path
  9470. );
  9471. $my_dep_file->setAttribute('href', $file_path);
  9472. $my_dep->setAttribute('xml:base', '');
  9473. } elseif (strstr($file_path, $main_path) !== false) {
  9474. // The calculated real path is really inside Chamilo's root path.
  9475. // Reduce file path to what's under the DocumentRoot.
  9476. $file_path = substr($file_path, strlen($root_path));
  9477. //echo $file_path;echo '<br /><br />';
  9478. //error_log('Reduced path: '.$file_path, 0);
  9479. $zip_files_abs[] = $file_path;
  9480. $link_updates[$my_file_path][] = array(
  9481. 'orig' => $doc_info[0],
  9482. 'dest' => $file_path
  9483. );
  9484. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9485. $my_dep->setAttribute('xml:base', '');
  9486. } elseif (empty($file_path)) {
  9487. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9488. if(strpos($document_root,-1) == '/') {
  9489. $document_root = substr(0, -1, $document_root);
  9490. }*/
  9491. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9492. $file_path = str_replace('//', '/', $file_path);
  9493. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '',
  9494. $doc_info[0]);
  9495. $current_dir = dirname($abs_path);
  9496. $current_dir = str_replace('\\', '/', $current_dir);
  9497. if (file_exists($file_path)) {
  9498. $file_path = substr($file_path,
  9499. strlen($current_dir)); // We get the relative path.
  9500. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9501. $link_updates[$my_file_path][] = array(
  9502. 'orig' => $doc_info[0],
  9503. 'dest' => $file_path
  9504. );
  9505. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9506. $my_dep->setAttribute('xml:base', '');
  9507. }
  9508. }
  9509. break;
  9510. case 'rel':
  9511. // Path relative to the current document.
  9512. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9513. if (substr($doc_info[0], 0, 2) == '..') {
  9514. // Relative path going up.
  9515. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9516. $current_dir = str_replace('\\', '/', $current_dir);
  9517. $file_path = realpath($current_dir.$doc_info[0]);
  9518. $file_path = str_replace('\\', '/', $file_path);
  9519. //error_log($file_path.' <-> '.$main_path,0);
  9520. if (strstr($file_path, $main_path) !== false) {
  9521. // The calculated real path is really inside Chamilo's root path.
  9522. // Reduce file path to what's under the DocumentRoot.
  9523. $file_path = substr($file_path, strlen($root_path));
  9524. //error_log('Reduced path: '.$file_path, 0);
  9525. $zip_files_abs[] = $file_path;
  9526. $link_updates[$my_file_path][] = array(
  9527. 'orig' => $doc_info[0],
  9528. 'dest' => $file_path
  9529. );
  9530. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9531. $my_dep->setAttribute('xml:base', '');
  9532. }
  9533. } else {
  9534. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9535. $my_dep_file->setAttribute('href', $doc_info[0]);
  9536. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9537. }
  9538. break;
  9539. default:
  9540. $my_dep_file->setAttribute('href', $doc_info[0]);
  9541. $my_dep->setAttribute('xml:base', '');
  9542. break;
  9543. }
  9544. }
  9545. $my_dep->appendChild($my_dep_file);
  9546. $resources->appendChild($my_dep);
  9547. $dependency = $xmldoc->createElement('dependency');
  9548. $dependency->setAttribute('identifierref', $res_id);
  9549. $my_resource->appendChild($dependency);
  9550. $i++;
  9551. }
  9552. }
  9553. $resources->appendChild($my_resource);
  9554. $zip_files[] = $my_file_path;
  9555. } else {
  9556. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9557. switch ($item->type) {
  9558. case TOOL_LINK:
  9559. $my_item = $xmldoc->createElement('item');
  9560. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9561. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9562. $my_item->setAttribute('isvisible', 'true');
  9563. // Give a child element <title> to the <item> element.
  9564. $my_title = $xmldoc->createElement('title',
  9565. htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
  9566. $my_item->appendChild($my_title);
  9567. // Give a child element <adlcp:prerequisites> to the <item> element.
  9568. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9569. $my_prereqs->setAttribute('type', 'aicc_script');
  9570. $my_item->appendChild($my_prereqs);
  9571. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9572. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9573. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9574. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9575. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9576. //$xmldoc->createElement('adlcp:datafromlms', '');
  9577. // Give a child element <adlcp:masteryscore> to the <item> element.
  9578. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9579. $my_item->appendChild($my_masteryscore);
  9580. // Attach this item to the organization element or its parent if there is one.
  9581. if (!empty($item->parent) && $item->parent != 0) {
  9582. $children = $organization->childNodes;
  9583. for ($i = 0; $i < $children->length; $i++) {
  9584. $item_temp = $children->item($i);
  9585. if ($item_temp->nodeName == 'item') {
  9586. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9587. $item_temp->appendChild($my_item);
  9588. }
  9589. }
  9590. }
  9591. } else {
  9592. $organization->appendChild($my_item);
  9593. }
  9594. $my_file_path = 'link_'.$item->get_id().'.html';
  9595. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9596. WHERE c_id = '.$course_id.' AND id='.$item->path;
  9597. $rs = Database::query($sql);
  9598. if ($link = Database::fetch_array($rs)) {
  9599. $url = $link['url'];
  9600. $title = stripslashes($link['title']);
  9601. $links_to_create[$my_file_path] = array('title' => $title, 'url' => $url);
  9602. $my_xml_file_path = $my_file_path;
  9603. $my_sub_dir = dirname($my_file_path);
  9604. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9605. $my_xml_sub_dir = $my_sub_dir;
  9606. // Give a <resource> child to the <resources> element.
  9607. $my_resource = $xmldoc->createElement('resource');
  9608. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9609. $my_resource->setAttribute('type', 'webcontent');
  9610. $my_resource->setAttribute('href', $my_xml_file_path);
  9611. // adlcp:scormtype can be either 'sco' or 'asset'.
  9612. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9613. // xml:base is the base directory to find the files declared in this resource.
  9614. $my_resource->setAttribute('xml:base', '');
  9615. // give a <file> child to the <resource> element.
  9616. $my_file = $xmldoc->createElement('file');
  9617. $my_file->setAttribute('href', $my_xml_file_path);
  9618. $my_resource->appendChild($my_file);
  9619. $resources->appendChild($my_resource);
  9620. }
  9621. break;
  9622. case TOOL_QUIZ:
  9623. $exe_id = $item->path; // Should be using ref when everything will be cleaned up in this regard.
  9624. $exe = new Exercise();
  9625. $exe->read($exe_id);
  9626. $my_item = $xmldoc->createElement('item');
  9627. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9628. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9629. $my_item->setAttribute('isvisible', 'true');
  9630. // Give a child element <title> to the <item> element.
  9631. $my_title = $xmldoc->createElement('title',
  9632. htmlspecialchars(api_utf8_encode($item->get_title()), ENT_QUOTES, 'UTF-8'));
  9633. $my_item->appendChild($my_title);
  9634. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  9635. //$my_item->appendChild($my_max_score);
  9636. // Give a child element <adlcp:prerequisites> to the <item> element.
  9637. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9638. $my_prereqs->setAttribute('type', 'aicc_script');
  9639. $my_item->appendChild($my_prereqs);
  9640. // Give a child element <adlcp:masteryscore> to the <item> element.
  9641. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9642. $my_item->appendChild($my_masteryscore);
  9643. // Attach this item to the organization element or hits parent if there is one.
  9644. if (!empty($item->parent) && $item->parent != 0) {
  9645. $children = $organization->childNodes;
  9646. /*for ($i = 0; $i < $children->length; $i++) {
  9647. $item_temp = $children->item($i);
  9648. if ($exe_id == 81) {
  9649. error_log($item_temp->nodeName );
  9650. error_log($item_temp->getAttribute('identifier'));
  9651. }
  9652. if ($item_temp->nodeName == 'item') {
  9653. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9654. $item_temp->appendChild($my_item);
  9655. }
  9656. }
  9657. }*/
  9658. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9659. if ($possible_parent) {
  9660. if ($possible_parent->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9661. $possible_parent->appendChild($my_item);
  9662. }
  9663. }
  9664. } else {
  9665. $organization->appendChild($my_item);
  9666. }
  9667. // Get the path of the file(s) from the course directory root
  9668. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9669. $my_file_path = 'quiz_'.$item->get_id().'.html';
  9670. // Write the contents of the exported exercise into a (big) html file
  9671. // to later pack it into the exported SCORM. The file will be removed afterwards.
  9672. $contents = ScormSection::export_exercise_to_scorm($exe, true);
  9673. $tmp_file_path = $archive_path.$temp_dir_short.'/'.$my_file_path;
  9674. $res = file_put_contents($tmp_file_path, $contents);
  9675. if ($res === false) {
  9676. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  9677. }
  9678. $files_cleanup[] = $tmp_file_path;
  9679. $my_xml_file_path = $my_file_path;
  9680. $my_sub_dir = dirname($my_file_path);
  9681. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9682. $my_xml_sub_dir = $my_sub_dir;
  9683. // Give a <resource> child to the <resources> element.
  9684. $my_resource = $xmldoc->createElement('resource');
  9685. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9686. $my_resource->setAttribute('type', 'webcontent');
  9687. $my_resource->setAttribute('href', $my_xml_file_path);
  9688. // adlcp:scormtype can be either 'sco' or 'asset'.
  9689. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9690. // xml:base is the base directory to find the files declared in this resource.
  9691. $my_resource->setAttribute('xml:base', '');
  9692. // Give a <file> child to the <resource> element.
  9693. $my_file = $xmldoc->createElement('file');
  9694. $my_file->setAttribute('href', $my_xml_file_path);
  9695. $my_resource->appendChild($my_file);
  9696. // Get included docs.
  9697. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  9698. // Dependency to other files - not yet supported.
  9699. $i = 1;
  9700. foreach ($inc_docs as $doc_info) {
  9701. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9702. continue;
  9703. }
  9704. $my_dep = $xmldoc->createElement('resource');
  9705. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9706. $my_dep->setAttribute('identifier', $res_id);
  9707. $my_dep->setAttribute('type', 'webcontent');
  9708. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9709. $my_dep_file = $xmldoc->createElement('file');
  9710. // Check type of URL.
  9711. if ($doc_info[1] == 'remote') {
  9712. // Remote file. Save url as is.
  9713. $my_dep_file->setAttribute('href', $doc_info[0]);
  9714. $my_dep->setAttribute('xml:base', '');
  9715. } elseif ($doc_info[1] == 'local') {
  9716. switch ($doc_info[2]) {
  9717. case 'url': // Local URL - save path as url for now, don't zip file.
  9718. // Save file but as local file (retrieve from URL).
  9719. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '',
  9720. $doc_info[0]);
  9721. $current_dir = dirname($abs_path);
  9722. $current_dir = str_replace('\\', '/', $current_dir);
  9723. $file_path = realpath($abs_path);
  9724. $file_path = str_replace('\\', '/', $file_path);
  9725. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9726. $my_dep->setAttribute('xml:base', '');
  9727. if (strstr($file_path, $main_path) !== false) {
  9728. // The calculated real path is really inside the chamilo root path.
  9729. // Reduce file path to what's under the DocumentRoot.
  9730. $file_path = substr($file_path, strlen($root_path));
  9731. $zip_files_abs[] = $file_path;
  9732. $link_updates[$my_file_path][] = array(
  9733. 'orig' => $doc_info[0],
  9734. 'dest' => 'document/'.$file_path
  9735. );
  9736. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9737. $my_dep->setAttribute('xml:base', '');
  9738. } elseif (empty($file_path)) {
  9739. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH),api_get_path(REL_PATH)));
  9740. if (strpos($document_root,-1) == '/') {
  9741. $document_root = substr(0, -1, $document_root);
  9742. }*/
  9743. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9744. $file_path = str_replace('//', '/', $file_path);
  9745. if (file_exists($file_path)) {
  9746. $file_path = substr($file_path,
  9747. strlen($current_dir)); // We get the relative path.
  9748. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9749. $link_updates[$my_file_path][] = array(
  9750. 'orig' => $doc_info[0],
  9751. 'dest' => 'document/'.$file_path
  9752. );
  9753. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9754. $my_dep->setAttribute('xml:base', '');
  9755. }
  9756. }
  9757. break;
  9758. case 'abs': // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9759. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9760. $current_dir = str_replace('\\', '/', $current_dir);
  9761. $file_path = realpath($doc_info[0]);
  9762. $file_path = str_replace('\\', '/', $file_path);
  9763. $my_dep_file->setAttribute('href', $file_path);
  9764. $my_dep->setAttribute('xml:base', '');
  9765. if (strstr($file_path, $main_path) !== false) {
  9766. // The calculated real path is really inside the chamilo root path.
  9767. // Reduce file path to what's under the DocumentRoot.
  9768. $file_path = substr($file_path, strlen($root_path));
  9769. //echo $file_path;echo '<br /><br />';
  9770. //error_log('Reduced path: '.$file_path, 0);
  9771. $zip_files_abs[] = $file_path;
  9772. $link_updates[$my_file_path][] = array(
  9773. 'orig' => $doc_info[0],
  9774. 'dest' => $file_path
  9775. );
  9776. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9777. $my_dep->setAttribute('xml:base', '');
  9778. } elseif (empty($file_path)) {
  9779. /*$document_root = substr(api_get_path(SYS_PATH), 0, strpos(api_get_path(SYS_PATH), api_get_path(REL_PATH)));
  9780. if (strpos($document_root,-1) == '/') {
  9781. $document_root = substr(0, -1, $document_root);
  9782. }*/
  9783. $file_path = $_SERVER['DOCUMENT_ROOT'].$doc_info[0];
  9784. $file_path = str_replace('//', '/', $file_path);
  9785. if (file_exists($file_path)) {
  9786. $file_path = substr($file_path,
  9787. strlen($current_dir)); // We get the relative path.
  9788. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9789. $link_updates[$my_file_path][] = array(
  9790. 'orig' => $doc_info[0],
  9791. 'dest' => $file_path
  9792. );
  9793. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9794. $my_dep->setAttribute('xml:base', '');
  9795. }
  9796. }
  9797. break;
  9798. case 'rel': // Path relative to the current document. Save xml:base as current document's directory and save file in zip as subdir.file_path
  9799. if (substr($doc_info[0], 0, 2) == '..') {
  9800. // Relative path going up.
  9801. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9802. $current_dir = str_replace('\\', '/', $current_dir);
  9803. $file_path = realpath($current_dir.$doc_info[0]);
  9804. $file_path = str_replace('\\', '/', $file_path);
  9805. //error_log($file_path.' <-> '.$main_path, 0);
  9806. if (strstr($file_path, $main_path) !== false) {
  9807. // The calculated real path is really inside Chamilo's root path.
  9808. // Reduce file path to what's under the DocumentRoot.
  9809. $file_path = substr($file_path, strlen($root_path));
  9810. $file_path_dest = $file_path;
  9811. // File path is courses/CHAMILO/document/....
  9812. $info_file_path = explode('/', $file_path);
  9813. if ($info_file_path[0]
  9814. == 'courses'
  9815. ) { // Add character "/" in file path.
  9816. $file_path_dest = 'document/'.$file_path;
  9817. }
  9818. //error_log('Reduced path: '.$file_path, 0);
  9819. $zip_files_abs[] = $file_path;
  9820. $link_updates[$my_file_path][] = array(
  9821. 'orig' => $doc_info[0],
  9822. 'dest' => $file_path_dest
  9823. );
  9824. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9825. $my_dep->setAttribute('xml:base', '');
  9826. }
  9827. } else {
  9828. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9829. $my_dep_file->setAttribute('href', $doc_info[0]);
  9830. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9831. }
  9832. break;
  9833. default:
  9834. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  9835. $my_dep->setAttribute('xml:base', '');
  9836. break;
  9837. }
  9838. }
  9839. $my_dep->appendChild($my_dep_file);
  9840. $resources->appendChild($my_dep);
  9841. $dependency = $xmldoc->createElement('dependency');
  9842. $dependency->setAttribute('identifierref', $res_id);
  9843. $my_resource->appendChild($dependency);
  9844. $i++;
  9845. }
  9846. $resources->appendChild($my_resource);
  9847. $zip_files[] = $my_file_path;
  9848. break;
  9849. default:
  9850. // Get the path of the file(s) from the course directory root
  9851. $my_file_path = 'non_exportable.html';
  9852. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  9853. $my_xml_file_path = $my_file_path;
  9854. $my_sub_dir = dirname($my_file_path);
  9855. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9856. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  9857. $my_xml_sub_dir = $my_sub_dir;
  9858. // Give a <resource> child to the <resources> element.
  9859. $my_resource = $xmldoc->createElement('resource');
  9860. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9861. $my_resource->setAttribute('type', 'webcontent');
  9862. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  9863. // adlcp:scormtype can be either 'sco' or 'asset'.
  9864. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9865. // xml:base is the base directory to find the files declared in this resource.
  9866. $my_resource->setAttribute('xml:base', '');
  9867. // Give a <file> child to the <resource> element.
  9868. $my_file = $xmldoc->createElement('file');
  9869. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  9870. $my_resource->appendChild($my_file);
  9871. $resources->appendChild($my_resource);
  9872. break;
  9873. }
  9874. }
  9875. }
  9876. $organizations->appendChild($organization);
  9877. $root->appendChild($organizations);
  9878. $root->appendChild($resources);
  9879. $xmldoc->appendChild($root);
  9880. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  9881. // TODO: Add a readme file here, with a short description and a link to the Reload player
  9882. // then add the file to the zip, then destroy the file (this is done automatically).
  9883. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  9884. foreach ($zip_files as $file_path) {
  9885. if (empty($file_path)) {
  9886. continue;
  9887. }
  9888. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  9889. $dest_file = $archive_path.$temp_dir_short.'/'.$file_path;
  9890. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  9891. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  9892. }
  9893. $this->create_path($dest_file);
  9894. @copy($filePath, $dest_file);
  9895. // Check if the file needs a link update.
  9896. if (in_array($file_path, array_keys($link_updates))) {
  9897. $string = file_get_contents($dest_file);
  9898. unlink($dest_file);
  9899. foreach ($link_updates[$file_path] as $old_new) {
  9900. // This is an ugly hack that allows .flv files to be found by the flv player that
  9901. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  9902. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  9903. // ../../.. to return from inc/lib/flv_player to the document/main path.
  9904. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  9905. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  9906. } elseif (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 6) == 'video/') {
  9907. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  9908. }
  9909. //Fix to avoid problems with default_course_document
  9910. if (strpos("main/default_course_document", $old_new['dest'] === false)) {
  9911. //$newDestination = str_replace('document/', $mult.'document/', $old_new['dest']);
  9912. $newDestination = $old_new['dest'];
  9913. } else {
  9914. $newDestination = str_replace('document/', '', $old_new['dest']);
  9915. }
  9916. $string = str_replace($old_new['orig'], $newDestination, $string);
  9917. // Add files inside the HTMLs
  9918. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  9919. $destinationFile = $archive_path.$temp_dir_short.'/'.$old_new['dest'];
  9920. if (file_exists($sys_course_path.$new_path)) {
  9921. copy($sys_course_path.$new_path, $destinationFile);
  9922. }
  9923. }
  9924. file_put_contents($dest_file, $string);
  9925. }
  9926. if (file_exists($filePath) && $copyAll) {
  9927. $extension = $this->get_extension($filePath);
  9928. if (in_array($extension, ['html', 'html'])) {
  9929. $containerOrigin = dirname($filePath);
  9930. $containerDestination = dirname($dest_file);
  9931. $finder = new Finder();
  9932. $finder->files()->in($containerOrigin)
  9933. ->notName('*_DELETED_*')
  9934. ->exclude('share_folder')
  9935. ->exclude('chat_files')
  9936. ->exclude('certificates');
  9937. if (is_dir($containerOrigin) && is_dir($containerDestination)) {
  9938. $fs = new Filesystem();
  9939. $fs->mirror(
  9940. $containerOrigin,
  9941. $containerDestination,
  9942. $finder
  9943. );
  9944. }
  9945. }
  9946. }
  9947. }
  9948. foreach ($zip_files_abs as $file_path) {
  9949. if (empty($file_path)) {
  9950. continue;
  9951. }
  9952. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  9953. continue;
  9954. }
  9955. $dest_file = $archive_path.$temp_dir_short.'/document/'.$file_path;
  9956. $this->create_path($dest_file);
  9957. copy($main_path.$file_path, $dest_file);
  9958. // Check if the file needs a link update.
  9959. if (in_array($file_path, array_keys($link_updates))) {
  9960. $string = file_get_contents($dest_file);
  9961. unlink($dest_file);
  9962. foreach ($link_updates[$file_path] as $old_new) {
  9963. // This is an ugly hack that allows .flv files to be found by the flv player that
  9964. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  9965. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  9966. // ../../.. to return from inc/lib/flv_player to the document/main path.
  9967. if (substr($old_new['dest'], -3) == 'flv' && substr($old_new['dest'], 0, 5) == 'main/') {
  9968. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  9969. }
  9970. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  9971. }
  9972. file_put_contents($dest_file, $string);
  9973. }
  9974. }
  9975. if (is_array($links_to_create)) {
  9976. foreach ($links_to_create as $file => $link) {
  9977. $file_content
  9978. = '<!DOCTYPE html><head>
  9979. <meta charset="'.api_get_language_isocode().'" />
  9980. <title>'.$link['title'].'</title>
  9981. </head>
  9982. <body dir="'.api_get_text_direction().'">
  9983. <div style="text-align:center">
  9984. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  9985. </body>
  9986. </html>';
  9987. file_put_contents($archive_path.$temp_dir_short.'/'.$file, $file_content);
  9988. }
  9989. }
  9990. // Add non exportable message explanation.
  9991. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  9992. $file_content
  9993. = '<!DOCTYPE html><head>
  9994. <meta charset="'.api_get_language_isocode().'" />
  9995. <title>'.$lang_not_exportable.'</title>
  9996. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  9997. </head>
  9998. <body dir="'.api_get_text_direction().'">';
  9999. $file_content
  10000. .= <<<EOD
  10001. <style>
  10002. .error-message {
  10003. font-family: arial, verdana, helvetica, sans-serif;
  10004. border-width: 1px;
  10005. border-style: solid;
  10006. left: 50%;
  10007. margin: 10px auto;
  10008. min-height: 30px;
  10009. padding: 5px;
  10010. right: 50%;
  10011. width: 500px;
  10012. background-color: #FFD1D1;
  10013. border-color: #FF0000;
  10014. color: #000;
  10015. }
  10016. </style>
  10017. <body>
  10018. <div class="error-message">
  10019. $lang_not_exportable
  10020. </div>
  10021. </body>
  10022. </html>
  10023. EOD;
  10024. if (!is_dir($archive_path.$temp_dir_short.'/document')) {
  10025. @mkdir($archive_path.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10026. }
  10027. file_put_contents($archive_path.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10028. // Add the extra files that go along with a SCORM package.
  10029. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10030. $fs = new Filesystem();
  10031. $fs->mirror($main_code_path, $archive_path.$temp_dir_short);
  10032. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10033. $manifest = @$xmldoc->saveXML();
  10034. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10035. file_put_contents($archive_path.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10036. $zip_folder->add(
  10037. $archive_path.'/'.$temp_dir_short,
  10038. PCLZIP_OPT_REMOVE_PATH,
  10039. $archive_path.'/'.$temp_dir_short.'/'
  10040. );
  10041. // Clean possible temporary files.
  10042. foreach ($files_cleanup as $file) {
  10043. $res = unlink($file);
  10044. if ($res === false) {
  10045. error_log(
  10046. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10047. 0
  10048. );
  10049. }
  10050. }
  10051. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10052. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10053. }
  10054. /**
  10055. * @param int $lp_id
  10056. * @return bool
  10057. */
  10058. public function scorm_export_to_pdf($lp_id)
  10059. {
  10060. $lp_id = intval($lp_id);
  10061. $files_to_export = array();
  10062. $course_data = api_get_course_info($this->cc);
  10063. if (!empty($course_data)) {
  10064. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10065. $list = self::get_flat_ordered_items_list($lp_id);
  10066. if (!empty($list)) {
  10067. foreach ($list as $item_id) {
  10068. $item = $this->items[$item_id];
  10069. switch ($item->type) {
  10070. case 'document':
  10071. //Getting documents from a LP with chamilo documents
  10072. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10073. // Try loading document from the base course.
  10074. if (empty($file_data) && !empty($sessionId)) {
  10075. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc, false, 0);
  10076. }
  10077. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'
  10078. .$file_data['path'];
  10079. if (file_exists($file_path)) {
  10080. $files_to_export[] = array('title' => $item->get_title(), 'path' => $file_path);
  10081. }
  10082. break;
  10083. case 'asset': //commes from a scorm package generated by chamilo
  10084. case 'sco':
  10085. $file_path = $scorm_path.'/'.$item->path;
  10086. if (file_exists($file_path)) {
  10087. $files_to_export[] = array('title' => $item->get_title(), 'path' => $file_path);
  10088. }
  10089. break;
  10090. case 'dir':
  10091. $files_to_export[] = array('title' => $item->get_title(), 'path' => null);
  10092. break;
  10093. }
  10094. }
  10095. }
  10096. $pdf = new PDF();
  10097. $result = $pdf->html_to_pdf($files_to_export, $this->name, $this->cc, true);
  10098. return $result;
  10099. }
  10100. return false;
  10101. }
  10102. /**
  10103. * Temp function to be moved in main_api or the best place around for this.
  10104. * Creates a file path if it doesn't exist
  10105. * @param string $path
  10106. */
  10107. public function create_path($path)
  10108. {
  10109. $path_bits = explode('/', dirname($path));
  10110. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10111. $path_built = IS_WINDOWS_OS ? '' : '/';
  10112. foreach ($path_bits as $bit) {
  10113. if (!empty ($bit)) {
  10114. $new_path = $path_built.$bit;
  10115. if (is_dir($new_path)) {
  10116. $path_built = $new_path.'/';
  10117. } else {
  10118. mkdir($new_path, api_get_permissions_for_new_directories());
  10119. $path_built = $new_path.'/';
  10120. }
  10121. }
  10122. }
  10123. }
  10124. /**
  10125. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10126. * @return boolean The results of the unlink function, or false if there was no image to start with
  10127. */
  10128. public function delete_lp_image()
  10129. {
  10130. $img = $this->get_preview_image();
  10131. if ($img != '') {
  10132. $del_file = $this->get_preview_image_path(null, 'sys');
  10133. if (isset($del_file) && file_exists($del_file)) {
  10134. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10135. if (file_exists($del_file_2)) {
  10136. unlink($del_file_2);
  10137. }
  10138. $this->set_preview_image('');
  10139. return @unlink($del_file);
  10140. }
  10141. }
  10142. return false;
  10143. }
  10144. /**
  10145. * Uploads an author image to the upload/learning_path/images directory
  10146. * @param array The image array, coming from the $_FILES superglobal
  10147. * @return boolean True on success, false on error
  10148. */
  10149. public function upload_image($image_array)
  10150. {
  10151. if (!empty ($image_array['name'])) {
  10152. $upload_ok = process_uploaded_file($image_array);
  10153. $has_attachment = true;
  10154. }
  10155. if ($upload_ok) {
  10156. if ($has_attachment) {
  10157. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10158. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10159. $updir = $sys_course_path.$courseDir;
  10160. // Try to add an extension to the file if it hasn't one.
  10161. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10162. if (filter_extension($new_file_name)) {
  10163. $file_extension = explode('.', $image_array['name']);
  10164. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10165. $filename = uniqid('');
  10166. $new_file_name = $filename.'.'.$file_extension;
  10167. $new_path = $updir.'/'.$new_file_name;
  10168. // Resize the image.
  10169. $temp = new Image($image_array['tmp_name']);
  10170. $temp->resize(104);
  10171. $result = $temp->send_image($new_path);
  10172. // Storing the image filename.
  10173. if ($result) {
  10174. $this->set_preview_image($new_file_name);
  10175. //Resize to 64px to use on course homepage
  10176. $temp->resize(64);
  10177. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10178. return true;
  10179. }
  10180. }
  10181. }
  10182. }
  10183. return false;
  10184. }
  10185. /**
  10186. * @param int $lp_id
  10187. * @param string $status
  10188. */
  10189. public function set_autolaunch($lp_id, $status)
  10190. {
  10191. $course_id = api_get_course_int_id();
  10192. $lp_id = intval($lp_id);
  10193. $status = intval($status);
  10194. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10195. // Setting everything to autolaunch = 0
  10196. $attributes['autolaunch'] = 0;
  10197. $where = array('session_id = ? AND c_id = ? ' => array(api_get_session_id(), $course_id));
  10198. Database::update($lp_table, $attributes, $where);
  10199. if ($status == 1) {
  10200. //Setting my lp_id to autolaunch = 1
  10201. $attributes['autolaunch'] = 1;
  10202. $where = array('id = ? AND session_id = ? AND c_id = ?' => array($lp_id, api_get_session_id(), $course_id));
  10203. Database::update($lp_table, $attributes, $where);
  10204. }
  10205. }
  10206. /**
  10207. * Gets previous_item_id for the next element of the lp_item table
  10208. * @author Isaac flores paz
  10209. * @return integer Previous item ID
  10210. */
  10211. public function select_previous_item_id()
  10212. {
  10213. $course_id = api_get_course_int_id();
  10214. if ($this->debug > 0) {
  10215. error_log('New LP - In learnpath::select_previous_item_id()', 0);
  10216. }
  10217. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10218. // Get the max order of the items
  10219. $sql
  10220. = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10221. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'";
  10222. $rs_max_order = Database::query($sql);
  10223. $row_max_order = Database::fetch_object($rs_max_order);
  10224. $max_order = $row_max_order->display_order;
  10225. // Get the previous item ID
  10226. $sql
  10227. = "SELECT id as previous FROM $table_lp_item
  10228. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."' AND display_order = '".$max_order."' ";
  10229. $rs_max = Database::query($sql);
  10230. $row_max = Database::fetch_object($rs_max);
  10231. // Return the previous item ID
  10232. return $row_max->previous;
  10233. }
  10234. /**
  10235. * Copies an LP
  10236. */
  10237. public function copy()
  10238. {
  10239. // Course builder
  10240. $cb = new CourseBuilder();
  10241. //Setting tools that will be copied
  10242. $cb->set_tools_to_build(array('learnpaths'));
  10243. //Setting elements that will be copied
  10244. $cb->set_tools_specific_id_list(
  10245. array('learnpaths' => array($this->lp_id))
  10246. );
  10247. $course = $cb->build();
  10248. //Course restorer
  10249. $course_restorer = new CourseRestorer($course);
  10250. $course_restorer->set_add_text_in_items(true);
  10251. $course_restorer->set_tool_copy_settings(array('learnpaths' => array('reset_dates' => true)));
  10252. $course_restorer->restore(api_get_course_id(), api_get_session_id(), false, false);
  10253. }
  10254. public function verify_document_size($s)
  10255. {
  10256. $post_max = ini_get('post_max_size');
  10257. if (substr($post_max, -1, 1) == 'M') {
  10258. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10259. } elseif (substr($post_max, -1, 1) == 'G') {
  10260. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10261. }
  10262. $upl_max = ini_get('upload_max_filesize');
  10263. if (substr($upl_max, -1, 1) == 'M') {
  10264. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10265. } elseif (substr($upl_max, -1, 1) == 'G') {
  10266. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10267. }
  10268. $documents_total_space = DocumentManager::documents_total_space();
  10269. $course_max_space = DocumentManager::get_course_quota();
  10270. $total_size = filesize($s) + $documents_total_space;
  10271. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10272. return true;
  10273. } else {
  10274. return false;
  10275. }
  10276. }
  10277. /**
  10278. * Clear LP prerequisites
  10279. */
  10280. public function clear_prerequisites()
  10281. {
  10282. $course_id = $this->get_course_int_id();
  10283. if ($this->debug > 0) {
  10284. error_log('New LP - In learnpath::clear_prerequisites()', 0);
  10285. }
  10286. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10287. $lp_id = $this->get_id();
  10288. //Cleaning prerequisites
  10289. $sql
  10290. = "UPDATE $tbl_lp_item SET prerequisite = ''
  10291. WHERE c_id = ".$course_id." AND lp_id = '$lp_id'";
  10292. Database::query($sql);
  10293. //Cleaning mastery score for exercises
  10294. $sql
  10295. = "UPDATE $tbl_lp_item SET mastery_score = ''
  10296. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND item_type = 'quiz'";
  10297. Database::query($sql);
  10298. }
  10299. public function set_previous_step_as_prerequisite_for_all_items()
  10300. {
  10301. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10302. $course_id = $this->get_course_int_id();
  10303. $lp_id = $this->get_id();
  10304. if (!empty($this->items)) {
  10305. $previous_item_id = null;
  10306. $previous_item_max = 0;
  10307. $previous_item_type = null;
  10308. $last_item_not_dir = null;
  10309. $last_item_not_dir_type = null;
  10310. $last_item_not_dir_max = null;
  10311. foreach ($this->items as $item) {
  10312. // if there was a previous item... (otherwise jump to set it)
  10313. if (!empty($previous_item_id)) {
  10314. $current_item_id = $item->get_id(); //save current id
  10315. if ($item->get_type() != 'dir') {
  10316. // Current item is not a folder, so it qualifies to get a prerequisites
  10317. if ($last_item_not_dir_type == 'quiz') {
  10318. // if previous is quiz, mark its max score as default score to be achieved
  10319. $sql
  10320. = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10321. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$last_item_not_dir'";
  10322. Database::query($sql);
  10323. }
  10324. // now simply update the prerequisite to set it to the last non-chapter item
  10325. $sql
  10326. = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10327. WHERE c_id = ".$course_id." AND lp_id = '$lp_id' AND id = '$current_item_id'";
  10328. Database::query($sql);
  10329. // record item as 'non-chapter' reference
  10330. $last_item_not_dir = $item->get_id();
  10331. $last_item_not_dir_type = $item->get_type();
  10332. $last_item_not_dir_max = $item->get_max();
  10333. }
  10334. } else {
  10335. if ($item->get_type() != 'dir') {
  10336. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10337. $last_item_not_dir = $item->get_id();
  10338. $last_item_not_dir_type = $item->get_type();
  10339. $last_item_not_dir_max = $item->get_max();
  10340. }
  10341. }
  10342. // Saving the item as "previous item" for the next loop
  10343. $previous_item_id = $item->get_id();
  10344. $previous_item_max = $item->get_max();
  10345. $previous_item_type = $item->get_type();
  10346. }
  10347. }
  10348. }
  10349. /**
  10350. * @param array $params
  10351. */
  10352. public static function createCategory($params)
  10353. {
  10354. $em = Database::getManager();
  10355. $item = new CLpCategory();
  10356. $item->setName($params['name']);
  10357. $item->setCId($params['c_id']);
  10358. $em->persist($item);
  10359. $em->flush();
  10360. }
  10361. /**
  10362. * @param array $params
  10363. */
  10364. public static function updateCategory($params)
  10365. {
  10366. $em = Database::getManager();
  10367. /** @var CLpCategory $item */
  10368. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10369. if ($item) {
  10370. $item->setName($params['name']);
  10371. $em->merge($item);
  10372. $em->flush();
  10373. }
  10374. }
  10375. /**
  10376. * @param int $id
  10377. */
  10378. public static function moveUpCategory($id)
  10379. {
  10380. $em = Database::getManager();
  10381. /** @var CLpCategory $item */
  10382. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10383. if ($item) {
  10384. $position = $item->getPosition() - 1;
  10385. $item->setPosition($position);
  10386. $em->persist($item);
  10387. $em->flush();
  10388. }
  10389. }
  10390. /**
  10391. * @param int $id
  10392. */
  10393. public static function moveDownCategory($id)
  10394. {
  10395. $em = Database::getManager();
  10396. /** @var CLpCategory $item */
  10397. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10398. if ($item) {
  10399. $position = $item->getPosition() + 1;
  10400. $item->setPosition($position);
  10401. $em->persist($item);
  10402. $em->flush();
  10403. }
  10404. }
  10405. /**
  10406. * @param int $courseId
  10407. * @return int|mixed
  10408. */
  10409. public static function getCountCategories($courseId)
  10410. {
  10411. if (empty($course_id)) {
  10412. return 0;
  10413. }
  10414. $em = Database::getManager();
  10415. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10416. $query->setParameter('id', $courseId);
  10417. return $query->getSingleScalarResult();
  10418. }
  10419. /**
  10420. * @param int $courseId
  10421. * @return mixed
  10422. */
  10423. public static function getCategories($courseId)
  10424. {
  10425. $em = Database::getManager();
  10426. //Default behaviour
  10427. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10428. array('cId' => $course_id),
  10429. array('name' => 'ASC')
  10430. );*/
  10431. // Using doctrine extensions
  10432. /** @var SortableRepository $repo */
  10433. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10434. $items = $repo
  10435. ->getBySortableGroupsQuery(['cId' => $courseId])
  10436. ->getResult();
  10437. return $items;
  10438. }
  10439. /**
  10440. * @param int $id
  10441. * @return CLpCategory
  10442. */
  10443. public static function getCategory($id)
  10444. {
  10445. $em = Database::getManager();
  10446. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10447. return $item;
  10448. }
  10449. /**
  10450. * @param int $courseId
  10451. * @return array
  10452. */
  10453. public static function getCategoryByCourse($courseId)
  10454. {
  10455. $em = Database::getManager();
  10456. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10457. array('cId' => $courseId)
  10458. );
  10459. return $items;
  10460. }
  10461. /**
  10462. * @param int $id
  10463. * @return mixed
  10464. */
  10465. public static function deleteCategory($id)
  10466. {
  10467. $em = Database::getManager();
  10468. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10469. if ($item) {
  10470. $courseId = $item->getCId();
  10471. $query
  10472. = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10473. $query->setParameter('id', $courseId);
  10474. $query->setParameter('catId', $item->getId());
  10475. $lps = $query->getResult();
  10476. // Setting category = 0.
  10477. if ($lps) {
  10478. foreach ($lps as $lpItem) {
  10479. $lpItem->setCategoryId(0);
  10480. }
  10481. }
  10482. // Removing category.
  10483. $em->remove($item);
  10484. $em->flush();
  10485. }
  10486. }
  10487. /**
  10488. * @param int $courseId
  10489. * @param bool $addSelectOption
  10490. * @return mixed
  10491. */
  10492. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10493. {
  10494. $items = self::getCategoryByCourse($courseId);
  10495. $cats = array();
  10496. if ($addSelectOption) {
  10497. $cats = array(get_lang('SelectACategory'));
  10498. }
  10499. if (!empty($items)) {
  10500. foreach ($items as $cat) {
  10501. $cats[$cat->getId()] = $cat->getName();
  10502. }
  10503. }
  10504. return $cats;
  10505. }
  10506. /**
  10507. * Return the scorm item type object with spaces replaced with _
  10508. * The return result is use to build a css classname like scorm_type_$return
  10509. * @param $in_type
  10510. * @return mixed
  10511. */
  10512. private static function format_scorm_type_item($in_type)
  10513. {
  10514. return str_replace(' ', '_', $in_type);
  10515. }
  10516. /**
  10517. * @param string $courseCode
  10518. * @param int $lp_id
  10519. * @param int $user_id
  10520. * @return learnpath
  10521. */
  10522. public static function getLpFromSession($courseCode, $lp_id, $user_id)
  10523. {
  10524. $learnPath = null;
  10525. $lpObject = Session::read('lpobject');
  10526. if ($lpObject !== null) {
  10527. $learnPath = unserialize($lpObject);
  10528. }
  10529. if (!is_object($learnPath)) {
  10530. $learnPath = new learnpath($courseCode, $lp_id, $user_id);
  10531. }
  10532. return $learnPath;
  10533. }
  10534. /**
  10535. * @param int $itemId
  10536. * @return learnpathItem|false
  10537. */
  10538. public function getItem($itemId)
  10539. {
  10540. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  10541. return $this->items[$itemId];
  10542. }
  10543. return false;
  10544. }
  10545. /**
  10546. * @return int
  10547. */
  10548. public function getCategoryId()
  10549. {
  10550. return $this->categoryId;
  10551. }
  10552. /**
  10553. * @param int $categoryId
  10554. * @return bool
  10555. */
  10556. public function setCategoryId($categoryId)
  10557. {
  10558. $this->categoryId = intval($categoryId);
  10559. $courseId = api_get_course_int_id();
  10560. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10561. $lp_id = $this->get_id();
  10562. $sql = "UPDATE $lp_table SET category_id = ".$this->categoryId."
  10563. WHERE c_id = $courseId AND id = $lp_id";
  10564. Database::query($sql);
  10565. return true;
  10566. }
  10567. /**
  10568. * Get whether this is a learning path with the possibility to subscribe
  10569. * users or not
  10570. * @return int
  10571. */
  10572. public function getSubscribeUsers()
  10573. {
  10574. return $this->subscribeUsers;
  10575. }
  10576. /**
  10577. * Set whether this is a learning path with the possibility to subscribe
  10578. * users or not
  10579. * @param int $subscribeUsers (0 = false, 1 = true)
  10580. */
  10581. public function setSubscribeUsers($value)
  10582. {
  10583. if ($this->debug > 0) {
  10584. error_log('New LP - In learnpath::set_subscribe_users()', 0);
  10585. }
  10586. $this->subscribeUsers = intval($value);;
  10587. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10588. $lp_id = $this->get_id();
  10589. $sql = "UPDATE $lp_table SET subscribe_users = ".$this->subscribeUsers."
  10590. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  10591. Database::query($sql);
  10592. return true;
  10593. }
  10594. /**
  10595. * Calculate the count of stars for a user in this LP
  10596. * This calculation is based on the following rules:
  10597. * - the student gets one star when he gets to 50% of the learning path
  10598. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  10599. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  10600. * - the student gets the final star when the score for the *last* test is >= 80%
  10601. * @param int $sessionId Optional. The session ID
  10602. * @return int The count of stars
  10603. */
  10604. public function getCalculateStars($sessionId = 0)
  10605. {
  10606. $stars = 0;
  10607. $progress = self::getProgress($this->lp_id, $this->user_id, $this->course_int_id, $sessionId);
  10608. if ($progress >= 50) {
  10609. $stars++;
  10610. }
  10611. // Calculate stars chapters evaluation
  10612. $exercisesItems = $this->getExercisesItems();
  10613. if (!empty($exercisesItems)) {
  10614. $totalResult = 0;
  10615. foreach ($exercisesItems as $exerciseItem) {
  10616. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10617. $this->user_id,
  10618. $exerciseItem->path,
  10619. $this->course_int_id,
  10620. $sessionId,
  10621. $this->lp_id,
  10622. $exerciseItem->db_id
  10623. );
  10624. $exerciseResultInfo = end($exerciseResultInfo);
  10625. if (!$exerciseResultInfo) {
  10626. continue;
  10627. }
  10628. if (!empty($exerciseResultInfo['exe_weighting'])) {
  10629. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  10630. } else {
  10631. $exerciseResult = 0;
  10632. }
  10633. $totalResult += $exerciseResult;
  10634. }
  10635. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  10636. if ($totalExerciseAverage >= 50) {
  10637. $stars++;
  10638. }
  10639. if ($totalExerciseAverage >= 80) {
  10640. $stars++;
  10641. }
  10642. }
  10643. // Calculate star for final evaluation
  10644. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10645. if (!empty($finalEvaluationItem)) {
  10646. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10647. $this->user_id,
  10648. $finalEvaluationItem->path,
  10649. $this->course_int_id,
  10650. $sessionId,
  10651. $this->lp_id,
  10652. $finalEvaluationItem->db_id
  10653. );
  10654. $evaluationResultInfo = end($evaluationResultInfo);
  10655. if ($evaluationResultInfo) {
  10656. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  10657. if ($evaluationResult >= 80) {
  10658. $stars++;
  10659. }
  10660. }
  10661. }
  10662. return $stars;
  10663. }
  10664. /**
  10665. * Get the items of exercise type
  10666. * @return array The items. Otherwise return false
  10667. */
  10668. public function getExercisesItems()
  10669. {
  10670. $exercises = [];
  10671. foreach ($this->items as $item) {
  10672. if ($item->type != 'quiz') {
  10673. continue;
  10674. }
  10675. $exercises[] = $item;
  10676. }
  10677. array_pop($exercises);
  10678. return $exercises;
  10679. }
  10680. /**
  10681. * Get the item of exercise type (evaluation type)
  10682. * @return array The final evaluation. Otherwise return false
  10683. */
  10684. public function getFinalEvaluationItem()
  10685. {
  10686. $exercises = [];
  10687. foreach ($this->items as $item) {
  10688. if ($item->type != 'quiz') {
  10689. continue;
  10690. }
  10691. $exercises[] = $item;
  10692. }
  10693. return array_pop($exercises);
  10694. }
  10695. /**
  10696. * Calculate the total points achieved for the current user in this learning path
  10697. * @param int $sessionId Optional. The session Id
  10698. * @return int
  10699. */
  10700. public function getCalculateScore($sessionId = 0)
  10701. {
  10702. // Calculate stars chapters evaluation
  10703. $exercisesItems = $this->getExercisesItems();
  10704. $finalEvaluationItem = $this->getFinalEvaluationItem();
  10705. $totalExercisesResult = 0;
  10706. $totalEvaluationResult = 0;
  10707. if ($exercisesItems !== false) {
  10708. foreach ($exercisesItems as $exerciseItem) {
  10709. $exerciseResultInfo = Event::getExerciseResultsByUser(
  10710. $this->user_id,
  10711. $exerciseItem->path,
  10712. $this->course_int_id,
  10713. $sessionId,
  10714. $this->lp_id,
  10715. $exerciseItem->db_id
  10716. );
  10717. $exerciseResultInfo = end($exerciseResultInfo);
  10718. if (!$exerciseResultInfo) {
  10719. continue;
  10720. }
  10721. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  10722. }
  10723. }
  10724. if (!empty($finalEvaluationItem)) {
  10725. $evaluationResultInfo = Event::getExerciseResultsByUser(
  10726. $this->user_id,
  10727. $finalEvaluationItem->path,
  10728. $this->course_int_id,
  10729. $sessionId,
  10730. $this->lp_id,
  10731. $finalEvaluationItem->db_id
  10732. );
  10733. $evaluationResultInfo = end($evaluationResultInfo);
  10734. if ($evaluationResultInfo) {
  10735. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  10736. }
  10737. }
  10738. return $totalExercisesResult + $totalEvaluationResult;
  10739. }
  10740. /**
  10741. * Check if URL is not allowed to be show in a iframe
  10742. * @param string $src
  10743. * @return string
  10744. */
  10745. public function fixBlockedLinks($src)
  10746. {
  10747. $urlInfo = parse_url($src);
  10748. $platformProtocol = 'https';
  10749. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  10750. $platformProtocol = 'http';
  10751. }
  10752. $protocolFixApplied = false;
  10753. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  10754. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  10755. if ($platformProtocol != $scheme) {
  10756. Session::write('x_frame_source', $src);
  10757. $src = 'blank.php?error=x_frames_options';
  10758. $protocolFixApplied = true;
  10759. }
  10760. if ($protocolFixApplied == false) {
  10761. if (strpos($src, api_get_path(WEB_CODE_PATH)) === false) {
  10762. // Check X-Frame-Options
  10763. $ch = curl_init();
  10764. $options = array(
  10765. CURLOPT_URL => $src,
  10766. CURLOPT_RETURNTRANSFER => true,
  10767. CURLOPT_HEADER => true,
  10768. CURLOPT_FOLLOWLOCATION => true,
  10769. CURLOPT_ENCODING => "",
  10770. CURLOPT_AUTOREFERER => true,
  10771. CURLOPT_CONNECTTIMEOUT => 120,
  10772. CURLOPT_TIMEOUT => 120,
  10773. CURLOPT_MAXREDIRS => 10,
  10774. );
  10775. curl_setopt_array($ch, $options);
  10776. $response = curl_exec($ch);
  10777. $httpCode = curl_getinfo($ch);
  10778. $headers = substr($response, 0, $httpCode['header_size']);
  10779. $error = false;
  10780. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  10781. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  10782. ) {
  10783. $error = true;
  10784. }
  10785. if ($error) {
  10786. Session::write('x_frame_source', $src);
  10787. $src = 'blank.php?error=x_frames_options';
  10788. }
  10789. }
  10790. }
  10791. return $src;
  10792. }
  10793. /**
  10794. * Check if this LP has a created forum in the basis course
  10795. * @return boolean
  10796. */
  10797. public function lpHasForum()
  10798. {
  10799. $forumTable = Database::get_course_table(TABLE_FORUM);
  10800. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10801. $fakeFrom
  10802. = "
  10803. $forumTable f
  10804. INNER JOIN $itemProperty ip
  10805. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  10806. ";
  10807. $resultData = Database::select(
  10808. 'COUNT(f.iid) AS qty',
  10809. $fakeFrom,
  10810. [
  10811. 'where' => [
  10812. 'ip.visibility != ? AND ' => 2,
  10813. 'ip.tool = ? AND ' => TOOL_FORUM,
  10814. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10815. 'f.lp_id = ?' => intval($this->lp_id)
  10816. ]
  10817. ],
  10818. 'first'
  10819. );
  10820. return $resultData['qty'] > 0;
  10821. }
  10822. /**
  10823. * Get the forum for this learning path
  10824. * @return boolean
  10825. */
  10826. public function getForum($sessionId = 0)
  10827. {
  10828. $forumTable = Database::get_course_table(TABLE_FORUM);
  10829. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  10830. $fakeFrom
  10831. = "$forumTable f
  10832. INNER JOIN $itemProperty ip ";
  10833. if ($this->lp_session_id == 0) {
  10834. $fakeFrom
  10835. .= "
  10836. ON (
  10837. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  10838. f.session_id = ip.session_id OR ip.session_id IS NULL
  10839. )
  10840. )
  10841. ";
  10842. } else {
  10843. $fakeFrom
  10844. .= "
  10845. ON (
  10846. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  10847. )
  10848. ";
  10849. }
  10850. $resultData = Database::select(
  10851. 'f.*',
  10852. $fakeFrom,
  10853. [
  10854. 'where' => [
  10855. 'ip.visibility != ? AND ' => 2,
  10856. 'ip.tool = ? AND ' => TOOL_FORUM,
  10857. 'f.session_id = ? AND ' => $sessionId,
  10858. 'f.c_id = ? AND ' => intval($this->course_int_id),
  10859. 'f.lp_id = ?' => intval($this->lp_id)
  10860. ]
  10861. ],
  10862. 'first'
  10863. );
  10864. if (empty($resultData)) {
  10865. return false;
  10866. }
  10867. return $resultData;
  10868. }
  10869. /**
  10870. * Create a forum for this learning path
  10871. * @param type $forumCategoryId
  10872. * @return int The forum ID if was created. Otherwise return false
  10873. */
  10874. public function createForum($forumCategoryId)
  10875. {
  10876. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  10877. $forumId = store_forum(
  10878. [
  10879. 'lp_id' => $this->lp_id,
  10880. 'forum_title' => $this->name,
  10881. 'forum_comment' => null,
  10882. 'forum_category' => intval($forumCategoryId),
  10883. 'students_can_edit_group' => ['students_can_edit' => 0],
  10884. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  10885. 'default_view_type_group' => ['default_view_type' => 'flat'],
  10886. 'group_forum' => 0,
  10887. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public']
  10888. ],
  10889. [],
  10890. true
  10891. );
  10892. return $forumId;
  10893. }
  10894. /**
  10895. * Check and obtain the lp final item if exist
  10896. * @return learnpathItem
  10897. */
  10898. private function getFinalItem()
  10899. {
  10900. if (empty($this->items)) {
  10901. return null;
  10902. }
  10903. foreach ($this->items as $item) {
  10904. if ($item->type !== 'final_item') {
  10905. continue;
  10906. }
  10907. return $item;
  10908. }
  10909. }
  10910. /**
  10911. * Get the LP Final Item Template
  10912. * @return string
  10913. */
  10914. private function getFinalItemTemplate()
  10915. {
  10916. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  10917. }
  10918. /**
  10919. * Get the LP Final Item Url
  10920. * @return string
  10921. */
  10922. private function getSavedFinalItem()
  10923. {
  10924. $finalItem = $this->getFinalItem();
  10925. $doc = DocumentManager::get_document_data_by_id($finalItem->path, $this->cc);
  10926. if ($doc && file_exists($doc['absolute_path'])) {
  10927. return file_get_contents($doc['absolute_path']);
  10928. }
  10929. return '';
  10930. }
  10931. /**
  10932. * Get the LP Final Item form
  10933. * @return string
  10934. */
  10935. public function getFinalItemForm()
  10936. {
  10937. $finalItem = $this->getFinalItem();
  10938. $title = '';
  10939. if ($finalItem) {
  10940. $title = $finalItem->get_title();
  10941. $buttonText = get_lang('Save');
  10942. $content = $this->getSavedFinalItem();
  10943. } else {
  10944. $buttonText = get_lang('LPCreateDocument');
  10945. $content = $this->getFinalItemTemplate();
  10946. }
  10947. $courseInfo = api_get_course_info();
  10948. $result = $this->generate_lp_folder($courseInfo);
  10949. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  10950. $relative_prefix = '../../';
  10951. $editorConfig = [
  10952. 'ToolbarSet' => 'LearningPathDocuments',
  10953. 'Width' => '100%',
  10954. 'Height' => '500',
  10955. 'FullPage' => true,
  10956. 'CreateDocumentDir' => $relative_prefix,
  10957. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  10958. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path
  10959. ];
  10960. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  10961. 'type' => 'document',
  10962. 'lp_id' => $this->lp_id
  10963. ]);
  10964. $form = new FormValidator('final_item', 'POST', $url);
  10965. $form->addText('title', get_lang('Title'));
  10966. $form->addButtonSave($buttonText);
  10967. $form->addHtml(
  10968. Display::return_message(
  10969. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  10970. 'normal',
  10971. false
  10972. )
  10973. );
  10974. $renderer = $form->defaultRenderer();
  10975. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  10976. $form->addHtmlEditor('content_lp_certificate', null, true, false, $editorConfig, true);
  10977. $form->addHidden('action', 'add_final_item');
  10978. $form->addHidden('path', Session::read('pathItem'));
  10979. $form->addHidden('previous', $this->get_last());
  10980. $form->setDefaults(
  10981. ['title' => $title, 'content_lp_certificate' => $content]
  10982. );
  10983. if ($form->validate()) {
  10984. $values = $form->exportValues();
  10985. $lastItemId = $this->get_last();
  10986. if (!$finalItem) {
  10987. $documentId = $this->create_document(
  10988. $this->course_info,
  10989. $values['content_lp_certificate'],
  10990. $values['title']
  10991. );
  10992. $this->add_item(
  10993. 0,
  10994. $lastItemId,
  10995. 'final_item',
  10996. $documentId,
  10997. $values['title'],
  10998. ''
  10999. );
  11000. Display::addFlash(
  11001. Display::return_message(get_lang('Added'))
  11002. );
  11003. } else {
  11004. $this->edit_document($this->course_info);
  11005. }
  11006. }
  11007. return $form->returnForm();
  11008. }
  11009. /**
  11010. * Check if the current lp item is first, both, last or none from lp list
  11011. * @param int $currentItemId
  11012. * @return string
  11013. */
  11014. public function isFirstOrLastItem($currentItemId)
  11015. {
  11016. if ($this->debug > 0) {
  11017. error_log('New LP - In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11018. }
  11019. $lpItemId = [];
  11020. $typeListNotToVerify = self::getChapterTypes();
  11021. // Using get_toc() function instead $this->items because returns the correct order of the items
  11022. foreach ($this->get_toc() as $item) {
  11023. if (!in_array($item['type'], $typeListNotToVerify)) {
  11024. $lpItemId[] = $item['id'];
  11025. }
  11026. }
  11027. $lastLpItemIndex = count($lpItemId) - 1;
  11028. $position = array_search($currentItemId, $lpItemId);
  11029. switch ($position) {
  11030. case 0:
  11031. if (!$lastLpItemIndex) {
  11032. $answer = 'both';
  11033. break;
  11034. }
  11035. $answer = 'first';
  11036. break;
  11037. case $lastLpItemIndex:
  11038. $answer = 'last';
  11039. break;
  11040. default:
  11041. $answer = 'none';
  11042. }
  11043. return $answer;
  11044. }
  11045. /**
  11046. * Get whether this is a learning path with the accumulated SCORM time or not
  11047. * @return int
  11048. */
  11049. public function getAccumulateScormTime()
  11050. {
  11051. return $this->accumulateScormTime;
  11052. }
  11053. /**
  11054. * Set whether this is a learning path with the accumulated SCORM time or not
  11055. * @param int $value (0 = false, 1 = true)
  11056. * @return bool Always returns true
  11057. */
  11058. public function setAccumulateScormTime($value)
  11059. {
  11060. if ($this->debug > 0) {
  11061. error_log('New LP - In learnpath::setAccumulateScormTime()', 0);
  11062. }
  11063. $this->accumulateScormTime = intval($value);
  11064. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11065. $lp_id = $this->get_id();
  11066. $sql = "UPDATE $lp_table SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11067. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  11068. Database::query($sql);
  11069. return true;
  11070. }
  11071. /**
  11072. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11073. * the new learning path tool.
  11074. * The function is a big switch on tool type.
  11075. * In each case, we query the corresponding table for information and build the link
  11076. * with that information.
  11077. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11078. * previous work (display_addedresource_link_in_learnpath())
  11079. * @param int $course_id Course code
  11080. * @param int $learningPathId The learning path ID (in lp table)
  11081. * @param int $id_in_path the unique index in the items table
  11082. * @param int $lpViewId
  11083. * @param string $origin
  11084. * @return string
  11085. */
  11086. public static function rl_get_resource_link_for_learnpath(
  11087. $course_id,
  11088. $learningPathId,
  11089. $id_in_path,
  11090. $lpViewId,
  11091. $origin = 'learnpath'
  11092. ) {
  11093. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11094. $course_info = api_get_course_info_by_id($course_id);
  11095. $course_id = $course_info['real_id'];
  11096. $course_code = $course_info['code'];
  11097. $session_id = api_get_session_id();
  11098. $learningPathId = intval($learningPathId);
  11099. $id_in_path = intval($id_in_path);
  11100. $lpViewId = intval($lpViewId);
  11101. $em = Database::getManager();
  11102. $sql
  11103. = "SELECT * FROM $tbl_lp_item
  11104. WHERE
  11105. c_id = $course_id AND
  11106. lp_id = $learningPathId AND
  11107. id = $id_in_path
  11108. ";
  11109. $res_item = Database::query($sql);
  11110. if (Database::num_rows($res_item) < 1) {
  11111. return -1;
  11112. }
  11113. $row_item = Database::fetch_array($res_item, 'ASSOC');
  11114. $item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  11115. // Get the lp_item_view with the highest view_count.
  11116. $sql
  11117. = "SELECT * FROM $item_view_table
  11118. WHERE
  11119. c_id = $course_id AND
  11120. lp_item_id = ".$row_item['id']." AND
  11121. lp_view_id = $lpViewId
  11122. ORDER BY view_count DESC";
  11123. $learnpathItemViewResult = Database::query($sql);
  11124. $learnpathItemViewData = Database::fetch_array($learnpathItemViewResult, 'ASSOC');
  11125. $learnpathItemViewId = 0;
  11126. if (isset($learnpathItemViewData)) {
  11127. $learnpathItemViewId = $learnpathItemViewData['id'];
  11128. }
  11129. $type = strtolower($row_item['item_type']);
  11130. $id = (strcmp($row_item['path'], '') == 0) ? '0' : $row_item['path'];
  11131. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11132. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11133. $link = '';
  11134. $extraParams = "origin=$origin&cidReq=$course_code&session_id=$session_id&id_session=$session_id";
  11135. switch ($type) {
  11136. case 'dir':
  11137. $link .= $main_dir_path.'lp/blank.php';
  11138. break;
  11139. case TOOL_CALENDAR_EVENT:
  11140. $link .= $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11141. break;
  11142. case TOOL_ANNOUNCEMENT:
  11143. $link .= $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11144. break;
  11145. case TOOL_LINK:
  11146. $link .= $main_dir_path.'link/link_goto.php?link_id='.$id.'&'.$extraParams;
  11147. break;
  11148. case TOOL_QUIZ:
  11149. if (!empty($id)) {
  11150. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11151. $sql = "SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id";
  11152. $result = Database::query($sql);
  11153. $myrow = Database::fetch_array($result);
  11154. if ($row_item['title'] != '') {
  11155. $myrow['title'] = $row_item['title'];
  11156. }
  11157. $link .= $main_dir_path.'exercise/overview.php?lp_init=1&learnpath_item_view_id='
  11158. .$learnpathItemViewId.'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11159. .'&exerciseId='.$id.'&'.$extraParams;
  11160. }
  11161. break;
  11162. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11163. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11164. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND id=$id");
  11165. $myrow = Database::fetch_array($result);
  11166. $path = $myrow['path'];
  11167. $link .= $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11168. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path.'&lp_view_id='
  11169. .$lpViewId.'&'.$extraParams;
  11170. break;
  11171. case TOOL_FORUM:
  11172. $link .= $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11173. break;
  11174. case TOOL_THREAD: //forum post
  11175. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11176. if (!empty($id)) {
  11177. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11178. $result = Database::query($sql);
  11179. $myrow = Database::fetch_array($result);
  11180. $link .= $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11181. .$extraParams;
  11182. }
  11183. break;
  11184. case TOOL_POST:
  11185. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11186. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11187. $myrow = Database::fetch_array($result);
  11188. $link .= $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11189. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11190. break;
  11191. case TOOL_DOCUMENT:
  11192. $document = $em
  11193. ->getRepository('ChamiloCourseBundle:CDocument')
  11194. ->findOneBy(['cId' => $course_id, 'id' => $id]);
  11195. if (!$document) {
  11196. break;
  11197. }
  11198. $documentPathInfo = pathinfo($document->getPath());
  11199. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  11200. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11201. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  11202. if ($showDirectUrl) {
  11203. $link = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11204. } else {
  11205. $link = api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11206. }
  11207. $openmethod = 2;
  11208. $officedoc = false;
  11209. Session::write('openmethod', $openmethod);
  11210. Session::write('officedoc', $officedoc);
  11211. break;
  11212. case TOOL_LP_FINAL_ITEM:
  11213. $link .= api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11214. .$extraParams;
  11215. break;
  11216. case 'assignments':
  11217. $link .= $main_dir_path.'work/work.php?'.$extraParams;
  11218. break;
  11219. case TOOL_DROPBOX:
  11220. $link .= $main_dir_path.'dropbox/index.php?'.$extraParams;
  11221. break;
  11222. case 'introduction_text': //DEPRECATED
  11223. $link .= '';
  11224. break;
  11225. case TOOL_COURSE_DESCRIPTION:
  11226. $link .= $main_dir_path.'course_description?'.$extraParams;
  11227. break;
  11228. case TOOL_GROUP:
  11229. $link .= $main_dir_path.'group/group.php?'.$extraParams;
  11230. break;
  11231. case TOOL_USER:
  11232. $link .= $main_dir_path.'user/user.php?'.$extraParams;
  11233. break;
  11234. case TOOL_STUDENTPUBLICATION:
  11235. if (!empty($row_item['path'])) {
  11236. $link .= $main_dir_path.'work/work_list.php?id='.$row_item['path'].'&'.$extraParams;
  11237. break;
  11238. }
  11239. $link .= $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$row_item['path'].'&'.$extraParams;
  11240. break;
  11241. } //end switch
  11242. return $link;
  11243. }
  11244. /**
  11245. * Gets the name of a resource (generally used in learnpath when no name is provided)
  11246. * @author Yannick Warnier <ywarnier@beeznest.org>
  11247. * @param string Course code
  11248. * @param string The tool type (using constants declared in main_api.lib.php)
  11249. * @param integer The resource ID
  11250. */
  11251. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11252. {
  11253. $_course = api_get_course_info($course_code);
  11254. $course_id = $_course['real_id'];
  11255. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11256. $learningPathId = intval($learningPathId);
  11257. $id_in_path = intval($id_in_path);
  11258. $sql_item
  11259. = "SELECT item_type, title, ref FROM $tbl_lp_item
  11260. WHERE c_id = $course_id AND lp_id = $learningPathId AND id = $id_in_path";
  11261. $res_item = Database::query($sql_item);
  11262. if (Database::num_rows($res_item) < 1) {
  11263. return '';
  11264. }
  11265. $row_item = Database::fetch_array($res_item);
  11266. $type = strtolower($row_item['item_type']);
  11267. $id = $row_item['ref'];
  11268. $output = '';
  11269. switch ($type) {
  11270. case TOOL_CALENDAR_EVENT:
  11271. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11272. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11273. $myrow = Database::fetch_array($result);
  11274. $output = $myrow['title'];
  11275. break;
  11276. case TOOL_ANNOUNCEMENT:
  11277. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11278. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11279. $myrow = Database::fetch_array($result);
  11280. $output = $myrow['title'];
  11281. break;
  11282. case TOOL_LINK:
  11283. // Doesn't take $target into account.
  11284. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11285. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11286. $myrow = Database::fetch_array($result);
  11287. $output = $myrow['title'];
  11288. break;
  11289. case TOOL_QUIZ:
  11290. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11291. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id=$id");
  11292. $myrow = Database::fetch_array($result);
  11293. $output = $myrow['title'];
  11294. break;
  11295. case TOOL_FORUM:
  11296. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11297. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id=$id");
  11298. $myrow = Database::fetch_array($result);
  11299. $output = $myrow['forum_name'];
  11300. break;
  11301. case TOOL_THREAD: //=topics
  11302. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11303. // Grabbing the title of the post.
  11304. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11305. $result_title = Database::query($sql_title);
  11306. $myrow_title = Database::fetch_array($result_title);
  11307. $output = $myrow_title['post_title'];
  11308. break;
  11309. case TOOL_POST:
  11310. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11311. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  11312. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11313. $result = Database::query($sql);
  11314. $post = Database::fetch_array($result);
  11315. $output = $post['post_title'];
  11316. break;
  11317. case 'dir':
  11318. $title = $row_item['title'];
  11319. if (!empty($title)) {
  11320. $output = $title;
  11321. } else {
  11322. $output = '-';
  11323. }
  11324. break;
  11325. case TOOL_DOCUMENT:
  11326. $title = $row_item['title'];
  11327. if (!empty($title)) {
  11328. $output = $title;
  11329. } else {
  11330. $output = '-';
  11331. }
  11332. break;
  11333. case 'hotpotatoes':
  11334. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11335. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND id = $id");
  11336. $myrow = Database::fetch_array($result);
  11337. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11338. $last = count($pathname) - 1; // Making a correct name for the link.
  11339. $filename = $pathname[$last]; // Making a correct name for the link.
  11340. $ext = explode('.', $filename);
  11341. $ext = strtolower($ext[sizeof($ext) - 1]);
  11342. $myrow['path'] = rawurlencode($myrow['path']);
  11343. $output = $filename;
  11344. break;
  11345. }
  11346. return stripslashes($output);
  11347. }
  11348. /**
  11349. * Get the parent names for the current item
  11350. * @return array
  11351. */
  11352. public function getCurrentItemParentNames()
  11353. {
  11354. $return = [];
  11355. $item = $this->getItem($this->get_current_item_id());
  11356. $parent = $this->getItem($item->get_parent());
  11357. while ($parent) {
  11358. $return[] = $parent->get_title();
  11359. $parent = $this->getItem($parent->get_parent());
  11360. }
  11361. return array_reverse($return);
  11362. }
  11363. }
  11364. if (!function_exists('trim_value')) {
  11365. function trim_value(& $value)
  11366. {
  11367. $value = trim($value);
  11368. }
  11369. }