learnpath.class.php 505 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CItemProperty;
  9. use Chamilo\CourseBundle\Entity\CLp;
  10. use Chamilo\CourseBundle\Entity\CLpCategory;
  11. use Chamilo\CourseBundle\Entity\CLpItem;
  12. use Chamilo\CourseBundle\Entity\CLpItemView;
  13. use Chamilo\CourseBundle\Entity\CTool;
  14. use Chamilo\UserBundle\Entity\User;
  15. use ChamiloSession as Session;
  16. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  17. use Symfony\Component\Filesystem\Filesystem;
  18. use Symfony\Component\Finder\Finder;
  19. /**
  20. * Class learnpath
  21. * This class defines the parent attributes and methods for Chamilo learnpaths
  22. * and SCORM learnpaths. It is used by the scorm class.
  23. *
  24. * @todo decouple class
  25. *
  26. * @package chamilo.learnpath
  27. *
  28. * @author Yannick Warnier <ywarnier@beeznest.org>
  29. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  30. */
  31. class learnpath
  32. {
  33. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  34. public $attempt = 0; // The number for the current ID view.
  35. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  36. public $current; // Id of the current item the user is viewing.
  37. public $current_score; // The score of the current item.
  38. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  39. public $current_time_stop; // The time the user closed this resource.
  40. public $default_status = 'not attempted';
  41. public $encoding = 'UTF-8';
  42. public $error = '';
  43. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  44. public $index; // The index of the active learnpath_item in $ordered_items array.
  45. public $items = [];
  46. public $last; // item_id of last item viewed in the learning path.
  47. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  48. public $license; // Which license this course has been given - not used yet on 20060522.
  49. public $lp_id; // DB iid for this learnpath.
  50. public $lp_view_id; // DB ID for lp_view
  51. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  52. public $message = '';
  53. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  54. public $name; // Learnpath name (they generally have one).
  55. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  56. public $path = ''; // Path inside the scorm directory (if scorm).
  57. public $theme; // The current theme of the learning path.
  58. public $preview_image; // The current image of the learning path.
  59. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  60. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  61. public $prevent_reinit = 1;
  62. // Describes the mode of progress bar display.
  63. public $seriousgame_mode = 0;
  64. public $progress_bar_mode = '%';
  65. // Percentage progress as saved in the db.
  66. public $progress_db = 0;
  67. public $proximity; // Wether the content is distant or local or unknown.
  68. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  69. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  70. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  71. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  72. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  73. public $user_id; //ID of the user that is viewing/using the course
  74. public $update_queue = [];
  75. public $scorm_debug = 0;
  76. public $arrMenu = []; // Array for the menu items.
  77. public $debug = 0; // Logging level.
  78. public $lp_session_id = 0;
  79. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  80. public $prerequisite = 0;
  81. public $use_max_score = 1; // 1 or 0
  82. public $subscribeUsers = 0; // Subscribe users or not
  83. public $created_on = '';
  84. public $modified_on = '';
  85. public $publicated_on = '';
  86. public $expired_on = '';
  87. public $ref = null;
  88. public $course_int_id;
  89. public $course_info = [];
  90. public $categoryId;
  91. /**
  92. * Constructor.
  93. * Needs a database handler, a course code and a learnpath id from the database.
  94. * Also builds the list of items into $this->items.
  95. *
  96. * @param string $course Course code
  97. * @param int $lp_id c_lp.iid
  98. * @param int $user_id
  99. */
  100. public function __construct($course, $lp_id, $user_id)
  101. {
  102. $debug = $this->debug;
  103. $this->encoding = api_get_system_encoding();
  104. if ($debug) {
  105. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  106. }
  107. if (empty($course)) {
  108. $course = api_get_course_id();
  109. }
  110. $course_info = api_get_course_info($course);
  111. if (!empty($course_info)) {
  112. $this->cc = $course_info['code'];
  113. $this->course_info = $course_info;
  114. $course_id = $course_info['real_id'];
  115. } else {
  116. $this->error = 'Course code does not exist in database.';
  117. }
  118. $lp_id = (int) $lp_id;
  119. $course_id = (int) $course_id;
  120. $this->set_course_int_id($course_id);
  121. // Check learnpath ID.
  122. if (empty($lp_id) || empty($course_id)) {
  123. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  124. } else {
  125. // TODO: Make it flexible to use any course_code (still using env course code here).
  126. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  127. $sql = "SELECT * FROM $lp_table
  128. WHERE iid = $lp_id";
  129. if ($debug) {
  130. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  131. }
  132. $res = Database::query($sql);
  133. if (Database::num_rows($res) > 0) {
  134. $this->lp_id = $lp_id;
  135. $row = Database::fetch_array($res);
  136. $this->type = $row['lp_type'];
  137. $this->name = stripslashes($row['name']);
  138. $this->proximity = $row['content_local'];
  139. $this->theme = $row['theme'];
  140. $this->maker = $row['content_maker'];
  141. $this->prevent_reinit = $row['prevent_reinit'];
  142. $this->seriousgame_mode = $row['seriousgame_mode'];
  143. $this->license = $row['content_license'];
  144. $this->scorm_debug = $row['debug'];
  145. $this->js_lib = $row['js_lib'];
  146. $this->path = $row['path'];
  147. $this->preview_image = $row['preview_image'];
  148. $this->author = $row['author'];
  149. $this->hide_toc_frame = $row['hide_toc_frame'];
  150. $this->lp_session_id = $row['session_id'];
  151. $this->use_max_score = $row['use_max_score'];
  152. $this->subscribeUsers = $row['subscribe_users'];
  153. $this->created_on = $row['created_on'];
  154. $this->modified_on = $row['modified_on'];
  155. $this->ref = $row['ref'];
  156. $this->categoryId = $row['category_id'];
  157. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  158. if (!empty($row['publicated_on'])) {
  159. $this->publicated_on = $row['publicated_on'];
  160. }
  161. if (!empty($row['expired_on'])) {
  162. $this->expired_on = $row['expired_on'];
  163. }
  164. if ($this->type == 2) {
  165. if ($row['force_commit'] == 1) {
  166. $this->force_commit = true;
  167. }
  168. }
  169. $this->mode = $row['default_view_mod'];
  170. // Check user ID.
  171. if (empty($user_id)) {
  172. $this->error = 'User ID is empty';
  173. } else {
  174. $userInfo = api_get_user_info($user_id);
  175. if (!empty($userInfo)) {
  176. $this->user_id = $userInfo['user_id'];
  177. } else {
  178. $this->error = 'User ID does not exist in database #'.$user_id;
  179. }
  180. }
  181. // End of variables checking.
  182. $session_id = api_get_session_id();
  183. // Get the session condition for learning paths of the base + session.
  184. $session = api_get_session_condition($session_id);
  185. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  186. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  187. // Selecting by view_count descending allows to get the highest view_count first.
  188. $sql = "SELECT * FROM $lp_table
  189. WHERE
  190. c_id = $course_id AND
  191. lp_id = $lp_id AND
  192. user_id = $user_id
  193. $session
  194. ORDER BY view_count DESC";
  195. $res = Database::query($sql);
  196. if ($debug) {
  197. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  198. }
  199. if (Database::num_rows($res) > 0) {
  200. if ($debug) {
  201. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  202. }
  203. $row = Database::fetch_array($res);
  204. $this->attempt = $row['view_count'];
  205. $this->lp_view_id = $row['id'];
  206. $this->last_item_seen = $row['last_item'];
  207. $this->progress_db = $row['progress'];
  208. $this->lp_view_session_id = $row['session_id'];
  209. } elseif (!api_is_invitee()) {
  210. if ($debug) {
  211. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  212. }
  213. $this->attempt = 1;
  214. $params = [
  215. 'c_id' => $course_id,
  216. 'lp_id' => $lp_id,
  217. 'user_id' => $user_id,
  218. 'view_count' => 1,
  219. 'session_id' => $session_id,
  220. 'last_item' => 0,
  221. ];
  222. $this->last_item_seen = 0;
  223. $this->lp_view_session_id = $session_id;
  224. $this->lp_view_id = Database::insert($lp_table, $params);
  225. if (!empty($this->lp_view_id)) {
  226. $sql = "UPDATE $lp_table SET id = iid
  227. WHERE iid = ".$this->lp_view_id;
  228. Database::query($sql);
  229. }
  230. }
  231. // Initialise items.
  232. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  233. $sql = "SELECT * FROM $lp_item_table
  234. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  235. ORDER BY parent_item_id, display_order";
  236. $res = Database::query($sql);
  237. if ($debug) {
  238. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  239. error_log('-- Start while--');
  240. }
  241. $lp_item_id_list = [];
  242. while ($row = Database::fetch_array($res)) {
  243. $lp_item_id_list[] = $row['iid'];
  244. switch ($this->type) {
  245. case 3: //aicc
  246. $oItem = new aiccItem('db', $row['iid'], $course_id);
  247. if (is_object($oItem)) {
  248. $my_item_id = $oItem->get_id();
  249. $oItem->set_lp_view($this->lp_view_id, $course_id);
  250. $oItem->set_prevent_reinit($this->prevent_reinit);
  251. // Don't use reference here as the next loop will make the pointed object change.
  252. $this->items[$my_item_id] = $oItem;
  253. $this->refs_list[$oItem->ref] = $my_item_id;
  254. if ($debug) {
  255. error_log(
  256. 'learnpath::__construct() - '.
  257. 'aicc object with id '.$my_item_id.
  258. ' set in items[]',
  259. 0
  260. );
  261. }
  262. }
  263. break;
  264. case 2:
  265. $oItem = new scormItem('db', $row['iid'], $course_id);
  266. if (is_object($oItem)) {
  267. $my_item_id = $oItem->get_id();
  268. $oItem->set_lp_view($this->lp_view_id, $course_id);
  269. $oItem->set_prevent_reinit($this->prevent_reinit);
  270. // Don't use reference here as the next loop will make the pointed object change.
  271. $this->items[$my_item_id] = $oItem;
  272. $this->refs_list[$oItem->ref] = $my_item_id;
  273. if ($debug) {
  274. error_log('object with id '.$my_item_id.' set in items[]');
  275. }
  276. }
  277. break;
  278. case 1:
  279. default:
  280. if ($debug) {
  281. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  282. }
  283. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  284. if ($debug) {
  285. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  286. }
  287. if (is_object($oItem)) {
  288. $my_item_id = $oItem->get_id();
  289. // Moved down to when we are sure the item_view exists.
  290. //$oItem->set_lp_view($this->lp_view_id);
  291. $oItem->set_prevent_reinit($this->prevent_reinit);
  292. // Don't use reference here as the next loop will make the pointed object change.
  293. $this->items[$my_item_id] = $oItem;
  294. $this->refs_list[$my_item_id] = $my_item_id;
  295. if ($debug) {
  296. error_log(
  297. 'learnpath::__construct() '.__LINE__.
  298. ' - object with id '.$my_item_id.' set in items[]'
  299. );
  300. }
  301. }
  302. break;
  303. }
  304. // Setting the object level with variable $this->items[$i][parent]
  305. foreach ($this->items as $itemLPObject) {
  306. $level = self::get_level_for_item(
  307. $this->items,
  308. $itemLPObject->db_id
  309. );
  310. $itemLPObject->level = $level;
  311. }
  312. // Setting the view in the item object.
  313. if (is_object($this->items[$row['iid']])) {
  314. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  315. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  316. $this->items[$row['iid']]->current_start_time = 0;
  317. $this->items[$row['iid']]->current_stop_time = 0;
  318. }
  319. }
  320. }
  321. if ($debug) {
  322. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  323. }
  324. if (!empty($lp_item_id_list)) {
  325. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  326. if (!empty($lp_item_id_list_to_string)) {
  327. // Get last viewing vars.
  328. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  329. // This query should only return one or zero result.
  330. $sql = "SELECT lp_item_id, status
  331. FROM $itemViewTable
  332. WHERE
  333. c_id = $course_id AND
  334. lp_view_id = ".$this->lp_view_id." AND
  335. lp_item_id IN ('".$lp_item_id_list_to_string."')
  336. ORDER BY view_count DESC ";
  337. if ($debug) {
  338. error_log(
  339. 'learnpath::__construct() - Selecting item_views: '.$sql,
  340. 0
  341. );
  342. }
  343. $status_list = [];
  344. $res = Database::query($sql);
  345. while ($row = Database:: fetch_array($res)) {
  346. $status_list[$row['lp_item_id']] = $row['status'];
  347. }
  348. foreach ($lp_item_id_list as $item_id) {
  349. if (isset($status_list[$item_id])) {
  350. $status = $status_list[$item_id];
  351. if (is_object($this->items[$item_id])) {
  352. $this->items[$item_id]->set_status($status);
  353. if (empty($status)) {
  354. $this->items[$item_id]->set_status(
  355. $this->default_status
  356. );
  357. }
  358. }
  359. } else {
  360. if (!api_is_invitee()) {
  361. if (is_object($this->items[$item_id])) {
  362. $this->items[$item_id]->set_status(
  363. $this->default_status
  364. );
  365. }
  366. if (!empty($this->lp_view_id)) {
  367. // Add that row to the lp_item_view table so that
  368. // we have something to show in the stats page.
  369. $params = [
  370. 'c_id' => $course_id,
  371. 'lp_item_id' => $item_id,
  372. 'lp_view_id' => $this->lp_view_id,
  373. 'view_count' => 1,
  374. 'status' => 'not attempted',
  375. 'start_time' => time(),
  376. 'total_time' => 0,
  377. 'score' => 0,
  378. ];
  379. $insertId = Database::insert($itemViewTable, $params);
  380. if ($insertId) {
  381. $sql = "UPDATE $itemViewTable SET id = iid
  382. WHERE iid = $insertId";
  383. Database::query($sql);
  384. }
  385. $this->items[$item_id]->set_lp_view(
  386. $this->lp_view_id,
  387. $course_id
  388. );
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }
  395. $this->ordered_items = self::get_flat_ordered_items_list(
  396. $this->get_id(),
  397. 0,
  398. $course_id
  399. );
  400. $this->max_ordered_items = 0;
  401. foreach ($this->ordered_items as $index => $dummy) {
  402. if ($index > $this->max_ordered_items && !empty($dummy)) {
  403. $this->max_ordered_items = $index;
  404. }
  405. }
  406. // TODO: Define the current item better.
  407. $this->first();
  408. if ($debug) {
  409. error_log('lp_view_session_id '.$this->lp_view_session_id);
  410. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  411. }
  412. } else {
  413. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  414. }
  415. }
  416. }
  417. /**
  418. * @return string
  419. */
  420. public function getCourseCode()
  421. {
  422. return $this->cc;
  423. }
  424. /**
  425. * @return int
  426. */
  427. public function get_course_int_id()
  428. {
  429. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  430. }
  431. /**
  432. * @param $course_id
  433. *
  434. * @return int
  435. */
  436. public function set_course_int_id($course_id)
  437. {
  438. return $this->course_int_id = (int) $course_id;
  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('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  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 = (int) $parent;
  483. $previous = (int) $previous;
  484. $id = (int) $id;
  485. $max_time_allowed = htmlentities($max_time_allowed);
  486. if (empty($max_time_allowed)) {
  487. $max_time_allowed = 0;
  488. }
  489. $sql = "SELECT COUNT(iid) AS num
  490. FROM $tbl_lp_item
  491. WHERE
  492. c_id = $course_id AND
  493. lp_id = ".$this->get_id()." AND
  494. parent_item_id = ".$parent;
  495. $res_count = Database::query($sql);
  496. $row = Database::fetch_array($res_count);
  497. $num = $row['num'];
  498. $tmp_previous = 0;
  499. $display_order = 0;
  500. $next = 0;
  501. if ($num > 0) {
  502. if (empty($previous)) {
  503. $sql = "SELECT iid, next_item_id, display_order
  504. FROM $tbl_lp_item
  505. WHERE
  506. c_id = $course_id AND
  507. lp_id = ".$this->get_id()." AND
  508. parent_item_id = $parent AND
  509. previous_item_id = 0 OR
  510. previous_item_id = $parent";
  511. $result = Database::query($sql);
  512. $row = Database::fetch_array($result);
  513. if ($row) {
  514. $next = $row['iid'];
  515. }
  516. } else {
  517. $previous = (int) $previous;
  518. $sql = "SELECT iid, 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. if ($row) {
  527. $tmp_previous = $row['iid'];
  528. $next = $row['next_item_id'];
  529. $display_order = $row['display_order'];
  530. }
  531. }
  532. }
  533. $id = (int) $id;
  534. $typeCleaned = Database::escape_string($type);
  535. $max_score = 100;
  536. if ($type === 'quiz') {
  537. $sql = 'SELECT SUM(ponderation)
  538. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  539. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  540. ON
  541. quiz_question.id = quiz_rel_question.question_id AND
  542. quiz_question.c_id = quiz_rel_question.c_id
  543. WHERE
  544. quiz_rel_question.exercice_id = '.$id." AND
  545. quiz_question.c_id = $course_id AND
  546. quiz_rel_question.c_id = $course_id ";
  547. $rsQuiz = Database::query($sql);
  548. $max_score = Database::result($rsQuiz, 0, 0);
  549. // Disabling the exercise if we add it inside a LP
  550. $exercise = new Exercise($course_id);
  551. $exercise->read($id);
  552. $exercise->disable();
  553. $exercise->save();
  554. }
  555. $params = [
  556. 'c_id' => $course_id,
  557. 'lp_id' => $this->get_id(),
  558. 'item_type' => $typeCleaned,
  559. 'ref' => '',
  560. 'title' => $title,
  561. 'description' => $description,
  562. 'path' => $id,
  563. 'max_score' => $max_score,
  564. 'parent_item_id' => $parent,
  565. 'previous_item_id' => $previous,
  566. 'next_item_id' => (int) $next,
  567. 'display_order' => $display_order + 1,
  568. 'prerequisite' => $prerequisites,
  569. 'max_time_allowed' => $max_time_allowed,
  570. 'min_score' => 0,
  571. 'launch_data' => '',
  572. ];
  573. if ($prerequisites != 0) {
  574. $params['prerequisite'] = $prerequisites;
  575. }
  576. $new_item_id = Database::insert($tbl_lp_item, $params);
  577. if ($new_item_id) {
  578. if ($this->debug > 2) {
  579. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  580. }
  581. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  582. Database::query($sql);
  583. if (!empty($next)) {
  584. $sql = "UPDATE $tbl_lp_item
  585. SET previous_item_id = $new_item_id
  586. WHERE c_id = $course_id AND id = $next";
  587. Database::query($sql);
  588. }
  589. // Update the item that should be before the new item.
  590. if (!empty($tmp_previous)) {
  591. $sql = "UPDATE $tbl_lp_item
  592. SET next_item_id = $new_item_id
  593. WHERE c_id = $course_id AND id = $tmp_previous";
  594. Database::query($sql);
  595. }
  596. // Update all the items after the new item.
  597. $sql = "UPDATE $tbl_lp_item
  598. SET display_order = display_order + 1
  599. WHERE
  600. c_id = $course_id AND
  601. lp_id = ".$this->get_id()." AND
  602. iid <> $new_item_id AND
  603. parent_item_id = $parent AND
  604. display_order > $display_order";
  605. Database::query($sql);
  606. // Update the item that should come after the new item.
  607. $sql = "UPDATE $tbl_lp_item
  608. SET ref = $new_item_id
  609. WHERE c_id = $course_id AND iid = $new_item_id";
  610. Database::query($sql);
  611. // Upload audio.
  612. if (!empty($_FILES['mp3']['name'])) {
  613. // Create the audio folder if it does not exist yet.
  614. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  615. if (!is_dir($filepath.'audio')) {
  616. mkdir(
  617. $filepath.'audio',
  618. api_get_permissions_for_new_directories()
  619. );
  620. $audio_id = add_document(
  621. $_course,
  622. '/audio',
  623. 'folder',
  624. 0,
  625. 'audio',
  626. '',
  627. 0,
  628. true,
  629. null,
  630. $sessionId,
  631. $userId
  632. );
  633. api_item_property_update(
  634. $_course,
  635. TOOL_DOCUMENT,
  636. $audio_id,
  637. 'FolderCreated',
  638. $userId,
  639. null,
  640. null,
  641. null,
  642. null,
  643. $sessionId
  644. );
  645. api_item_property_update(
  646. $_course,
  647. TOOL_DOCUMENT,
  648. $audio_id,
  649. 'invisible',
  650. $userId,
  651. null,
  652. null,
  653. null,
  654. null,
  655. $sessionId
  656. );
  657. }
  658. $file_path = handle_uploaded_document(
  659. $_course,
  660. $_FILES['mp3'],
  661. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  662. '/audio',
  663. $userId,
  664. '',
  665. '',
  666. '',
  667. '',
  668. false
  669. );
  670. // Getting the filename only.
  671. $file_components = explode('/', $file_path);
  672. $file = $file_components[count($file_components) - 1];
  673. // Store the mp3 file in the lp_item table.
  674. $sql = "UPDATE $tbl_lp_item SET
  675. audio = '".Database::escape_string($file)."'
  676. WHERE iid = '".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. *
  685. * @param string $courseCode
  686. * @param string $name
  687. * @param string $description
  688. * @param string $learnpath
  689. * @param string $origin
  690. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  691. * @param string $publicated_on
  692. * @param string $expired_on
  693. * @param int $categoryId
  694. * @param int $userId
  695. *
  696. * @return int The new learnpath ID on success, 0 on failure
  697. */
  698. public static function add_lp(
  699. $courseCode,
  700. $name,
  701. $description = '',
  702. $learnpath = 'guess',
  703. $origin = 'zip',
  704. $zipname = '',
  705. $publicated_on = '',
  706. $expired_on = '',
  707. $categoryId = 0,
  708. $userId = 0
  709. ) {
  710. global $charset;
  711. if (!empty($courseCode)) {
  712. $courseInfo = api_get_course_info($courseCode);
  713. $course_id = $courseInfo['real_id'];
  714. } else {
  715. $course_id = api_get_course_int_id();
  716. $courseInfo = api_get_course_info();
  717. }
  718. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  719. // Check course code exists.
  720. // Check lp_name doesn't exist, otherwise append something.
  721. $i = 0;
  722. $name = Database::escape_string($name);
  723. $categoryId = (int) $categoryId;
  724. // Session id.
  725. $session_id = api_get_session_id();
  726. $userId = empty($userId) ? api_get_user_id() : $userId;
  727. $check_name = "SELECT * FROM $tbl_lp
  728. WHERE c_id = $course_id AND name = '$name'";
  729. $res_name = Database::query($check_name);
  730. if (empty($publicated_on)) {
  731. $publicated_on = null;
  732. } else {
  733. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  734. }
  735. if (empty($expired_on)) {
  736. $expired_on = null;
  737. } else {
  738. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  739. }
  740. while (Database::num_rows($res_name)) {
  741. // There is already one such name, update the current one a bit.
  742. $i++;
  743. $name = $name.' - '.$i;
  744. $check_name = "SELECT * FROM $tbl_lp
  745. WHERE c_id = $course_id AND name = '$name'";
  746. $res_name = Database::query($check_name);
  747. }
  748. // New name does not exist yet; keep it.
  749. // Escape description.
  750. // Kevin: added htmlentities().
  751. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  752. $type = 1;
  753. switch ($learnpath) {
  754. case 'guess':
  755. break;
  756. case 'dokeos':
  757. case 'chamilo':
  758. $type = 1;
  759. break;
  760. case 'aicc':
  761. break;
  762. }
  763. switch ($origin) {
  764. case 'zip':
  765. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  766. break;
  767. case 'manual':
  768. default:
  769. $get_max = "SELECT MAX(display_order)
  770. FROM $tbl_lp WHERE c_id = $course_id";
  771. $res_max = Database::query($get_max);
  772. if (Database::num_rows($res_max) < 1) {
  773. $dsp = 1;
  774. } else {
  775. $row = Database::fetch_array($res_max);
  776. $dsp = $row[0] + 1;
  777. }
  778. $params = [
  779. 'c_id' => $course_id,
  780. 'lp_type' => $type,
  781. 'name' => $name,
  782. 'description' => $description,
  783. 'path' => '',
  784. 'default_view_mod' => 'embedded',
  785. 'default_encoding' => 'UTF-8',
  786. 'display_order' => $dsp,
  787. 'content_maker' => 'Chamilo',
  788. 'content_local' => 'local',
  789. 'js_lib' => '',
  790. 'session_id' => $session_id,
  791. 'created_on' => api_get_utc_datetime(),
  792. 'modified_on' => api_get_utc_datetime(),
  793. 'publicated_on' => $publicated_on,
  794. 'expired_on' => $expired_on,
  795. 'category_id' => $categoryId,
  796. 'force_commit' => 0,
  797. 'content_license' => '',
  798. 'debug' => 0,
  799. 'theme' => '',
  800. 'preview_image' => '',
  801. 'author' => '',
  802. 'prerequisite' => 0,
  803. 'hide_toc_frame' => 0,
  804. 'seriousgame_mode' => 0,
  805. 'autolaunch' => 0,
  806. 'max_attempts' => 0,
  807. 'subscribe_users' => 0,
  808. 'accumulate_scorm_time' => 1,
  809. ];
  810. $id = Database::insert($tbl_lp, $params);
  811. if ($id > 0) {
  812. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  813. Database::query($sql);
  814. // Insert into item_property.
  815. api_item_property_update(
  816. $courseInfo,
  817. TOOL_LEARNPATH,
  818. $id,
  819. 'LearnpathAdded',
  820. $userId
  821. );
  822. api_set_default_visibility(
  823. $id,
  824. TOOL_LEARNPATH,
  825. 0,
  826. $courseInfo,
  827. $session_id,
  828. $userId
  829. );
  830. return $id;
  831. }
  832. break;
  833. }
  834. }
  835. /**
  836. * Auto completes the parents of an item in case it's been completed or passed.
  837. *
  838. * @param int $item Optional ID of the item from which to look for parents
  839. */
  840. public function autocomplete_parents($item)
  841. {
  842. $debug = $this->debug;
  843. if ($debug) {
  844. error_log('Learnpath::autocomplete_parents()');
  845. }
  846. if (empty($item)) {
  847. $item = $this->current;
  848. }
  849. $currentItem = $this->getItem($item);
  850. if ($currentItem) {
  851. $parent_id = $currentItem->get_parent();
  852. $parent = $this->getItem($parent_id);
  853. if ($parent) {
  854. // if $item points to an object and there is a parent.
  855. if ($debug) {
  856. error_log(
  857. 'Autocompleting parent of item '.$item.' '.
  858. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  859. 0
  860. );
  861. }
  862. // New experiment including failed and browsed in completed status.
  863. //$current_status = $currentItem->get_status();
  864. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  865. // Fixes chapter auto complete
  866. if (true) {
  867. // If the current item is completed or passes or succeeded.
  868. $updateParentStatus = true;
  869. if ($debug) {
  870. error_log('Status of current item is alright');
  871. }
  872. foreach ($parent->get_children() as $childItemId) {
  873. $childItem = $this->getItem($childItemId);
  874. // If children was not set try to get the info
  875. if (empty($childItem->db_item_view_id)) {
  876. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  877. }
  878. // Check all his brothers (parent's children) for completion status.
  879. if ($childItemId != $item) {
  880. if ($debug) {
  881. error_log(
  882. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  883. 0
  884. );
  885. }
  886. // Trying completing parents of failed and browsed items as well.
  887. if ($childItem->status_is(
  888. [
  889. 'completed',
  890. 'passed',
  891. 'succeeded',
  892. 'browsed',
  893. 'failed',
  894. ]
  895. )
  896. ) {
  897. // Keep completion status to true.
  898. continue;
  899. } else {
  900. if ($debug > 2) {
  901. error_log(
  902. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
  903. 0
  904. );
  905. }
  906. $updateParentStatus = false;
  907. break;
  908. }
  909. }
  910. }
  911. if ($updateParentStatus) {
  912. // If all the children were completed:
  913. $parent->set_status('completed');
  914. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  915. // Force the status to "completed"
  916. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  917. $this->update_queue[$parent->get_id()] = 'completed';
  918. if ($debug) {
  919. error_log(
  920. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  921. print_r($this->update_queue, 1),
  922. 0
  923. );
  924. }
  925. // Recursive call.
  926. $this->autocomplete_parents($parent->get_id());
  927. }
  928. }
  929. } else {
  930. if ($debug) {
  931. error_log("Parent #$parent_id does not exists");
  932. }
  933. }
  934. } else {
  935. if ($debug) {
  936. error_log("#$item is an item that doesn't have parents");
  937. }
  938. }
  939. }
  940. /**
  941. * Closes the current resource.
  942. *
  943. * Stops the timer
  944. * Saves into the database if required
  945. * Clears the current resource data from this object
  946. *
  947. * @return bool True on success, false on failure
  948. */
  949. public function close()
  950. {
  951. if ($this->debug > 0) {
  952. error_log('In learnpath::close()', 0);
  953. }
  954. if (empty($this->lp_id)) {
  955. $this->error = 'Trying to close this learnpath but no ID is set';
  956. return false;
  957. }
  958. $this->current_time_stop = time();
  959. $this->ordered_items = [];
  960. $this->index = 0;
  961. unset($this->lp_id);
  962. //unset other stuff
  963. return true;
  964. }
  965. /**
  966. * Static admin function allowing removal of a learnpath.
  967. *
  968. * @param array $courseInfo
  969. * @param int $id Learnpath ID
  970. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  971. *
  972. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  973. */
  974. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  975. {
  976. $course_id = api_get_course_int_id();
  977. if (!empty($courseInfo)) {
  978. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  979. }
  980. // TODO: Implement a way of getting this to work when the current object is not set.
  981. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  982. // If an ID is specifically given and the current LP is not the same, prevent delete.
  983. if (!empty($id) && ($id != $this->lp_id)) {
  984. return false;
  985. }
  986. $lp = Database::get_course_table(TABLE_LP_MAIN);
  987. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  988. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  989. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  990. // Delete lp item id.
  991. foreach ($this->items as $lpItemId => $dummy) {
  992. $sql = "DELETE FROM $lp_item_view
  993. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  994. Database::query($sql);
  995. }
  996. // Proposed by Christophe (nickname: clefevre)
  997. $sql = "DELETE FROM $lp_item
  998. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  999. Database::query($sql);
  1000. $sql = "DELETE FROM $lp_view
  1001. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1002. Database::query($sql);
  1003. self::toggle_publish($this->lp_id, 'i');
  1004. if ($this->type == 2 || $this->type == 3) {
  1005. // This is a scorm learning path, delete the files as well.
  1006. $sql = "SELECT path FROM $lp
  1007. WHERE iid = ".$this->lp_id;
  1008. $res = Database::query($sql);
  1009. if (Database::num_rows($res) > 0) {
  1010. $row = Database::fetch_array($res);
  1011. $path = $row['path'];
  1012. $sql = "SELECT id FROM $lp
  1013. WHERE
  1014. c_id = $course_id AND
  1015. path = '$path' AND
  1016. iid != ".$this->lp_id;
  1017. $res = Database::query($sql);
  1018. if (Database::num_rows($res) > 0) {
  1019. // Another learning path uses this directory, so don't delete it.
  1020. if ($this->debug > 2) {
  1021. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1022. }
  1023. } else {
  1024. // No other LP uses that directory, delete it.
  1025. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1026. // The absolute system path for this course.
  1027. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1028. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1029. if ($this->debug > 2) {
  1030. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1031. }
  1032. // Proposed by Christophe (clefevre).
  1033. if (strcmp(substr($path, -2), "/.") == 0) {
  1034. $path = substr($path, 0, -1); // Remove "." at the end.
  1035. }
  1036. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1037. rmdirr($course_scorm_dir.$path);
  1038. }
  1039. }
  1040. }
  1041. }
  1042. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1043. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1044. // Delete tools
  1045. $sql = "DELETE FROM $tbl_tool
  1046. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1047. Database::query($sql);
  1048. $sql = "DELETE FROM $lp
  1049. WHERE iid = ".$this->lp_id;
  1050. Database::query($sql);
  1051. // Updates the display order of all lps.
  1052. $this->update_display_order();
  1053. api_item_property_update(
  1054. api_get_course_info(),
  1055. TOOL_LEARNPATH,
  1056. $this->lp_id,
  1057. 'delete',
  1058. api_get_user_id()
  1059. );
  1060. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1061. api_get_course_id(),
  1062. 4,
  1063. $id,
  1064. api_get_session_id()
  1065. );
  1066. if ($link_info !== false) {
  1067. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1068. }
  1069. if (api_get_setting('search_enabled') == 'true') {
  1070. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1071. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1072. }
  1073. }
  1074. /**
  1075. * Removes all the children of one item - dangerous!
  1076. *
  1077. * @param int $id Element ID of which children have to be removed
  1078. *
  1079. * @return int Total number of children removed
  1080. */
  1081. public function delete_children_items($id)
  1082. {
  1083. $course_id = $this->course_info['real_id'];
  1084. if ($this->debug > 0) {
  1085. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1086. }
  1087. $num = 0;
  1088. if (empty($id) || $id != strval(intval($id))) {
  1089. return false;
  1090. }
  1091. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1092. $sql = "SELECT * FROM $lp_item
  1093. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1094. $res = Database::query($sql);
  1095. while ($row = Database::fetch_array($res)) {
  1096. $num += $this->delete_children_items($row['iid']);
  1097. $sql = "DELETE FROM $lp_item
  1098. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1099. Database::query($sql);
  1100. $num++;
  1101. }
  1102. return $num;
  1103. }
  1104. /**
  1105. * Removes an item from the current learnpath.
  1106. *
  1107. * @param int $id Elem ID (0 if first)
  1108. *
  1109. * @return int Number of elements moved
  1110. *
  1111. * @todo implement resource removal
  1112. */
  1113. public function delete_item($id)
  1114. {
  1115. $course_id = api_get_course_int_id();
  1116. if ($this->debug > 0) {
  1117. error_log('In learnpath::delete_item()', 0);
  1118. }
  1119. // TODO: Implement the resource removal.
  1120. if (empty($id) || $id != strval(intval($id))) {
  1121. return false;
  1122. }
  1123. // First select item to get previous, next, and display order.
  1124. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1125. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1126. $res_sel = Database::query($sql_sel);
  1127. if (Database::num_rows($res_sel) < 1) {
  1128. return false;
  1129. }
  1130. $row = Database::fetch_array($res_sel);
  1131. $previous = $row['previous_item_id'];
  1132. $next = $row['next_item_id'];
  1133. $display = $row['display_order'];
  1134. $parent = $row['parent_item_id'];
  1135. $lp = $row['lp_id'];
  1136. // Delete children items.
  1137. $num = $this->delete_children_items($id);
  1138. if ($this->debug > 2) {
  1139. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1140. }
  1141. // Now delete the item.
  1142. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1143. if ($this->debug > 2) {
  1144. error_log('Deleting item: '.$sql_del, 0);
  1145. }
  1146. Database::query($sql_del);
  1147. // Now update surrounding items.
  1148. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1149. WHERE iid = $previous";
  1150. Database::query($sql_upd);
  1151. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1152. WHERE iid = $next";
  1153. Database::query($sql_upd);
  1154. // Now update all following items with new display order.
  1155. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1156. WHERE
  1157. c_id = $course_id AND
  1158. lp_id = $lp AND
  1159. parent_item_id = $parent AND
  1160. display_order > $display";
  1161. Database::query($sql_all);
  1162. //Removing prerequisites since the item will not longer exist
  1163. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1164. WHERE c_id = $course_id AND prerequisite = $id";
  1165. Database::query($sql_all);
  1166. // Remove from search engine if enabled.
  1167. if (api_get_setting('search_enabled') === 'true') {
  1168. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1169. $sql = 'SELECT * FROM %s
  1170. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1171. LIMIT 1';
  1172. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1173. $res = Database::query($sql);
  1174. if (Database::num_rows($res) > 0) {
  1175. $row2 = Database::fetch_array($res);
  1176. $di = new ChamiloIndexer();
  1177. $di->remove_document($row2['search_did']);
  1178. }
  1179. $sql = 'DELETE FROM %s
  1180. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1181. LIMIT 1';
  1182. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1183. Database::query($sql);
  1184. }
  1185. }
  1186. /**
  1187. * Updates an item's content in place.
  1188. *
  1189. * @param int $id Element ID
  1190. * @param int $parent Parent item ID
  1191. * @param int $previous Previous item ID
  1192. * @param string $title Item title
  1193. * @param string $description Item description
  1194. * @param string $prerequisites Prerequisites (optional)
  1195. * @param array $audio The array resulting of the $_FILES[mp3] element
  1196. * @param int $max_time_allowed
  1197. * @param string $url
  1198. *
  1199. * @return bool True on success, false on error
  1200. */
  1201. public function edit_item(
  1202. $id,
  1203. $parent,
  1204. $previous,
  1205. $title,
  1206. $description,
  1207. $prerequisites = '0',
  1208. $audio = [],
  1209. $max_time_allowed = 0,
  1210. $url = ''
  1211. ) {
  1212. $course_id = api_get_course_int_id();
  1213. $_course = api_get_course_info();
  1214. if ($this->debug > 0) {
  1215. error_log('In learnpath::edit_item()', 0);
  1216. }
  1217. if (empty($max_time_allowed)) {
  1218. $max_time_allowed = 0;
  1219. }
  1220. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1221. return false;
  1222. }
  1223. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1224. $sql = "SELECT * FROM $tbl_lp_item
  1225. WHERE iid = $id";
  1226. $res_select = Database::query($sql);
  1227. $row_select = Database::fetch_array($res_select);
  1228. $audio_update_sql = '';
  1229. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1230. // Create the audio folder if it does not exist yet.
  1231. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1232. if (!is_dir($filepath.'audio')) {
  1233. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1234. $audio_id = add_document(
  1235. $_course,
  1236. '/audio',
  1237. 'folder',
  1238. 0,
  1239. 'audio'
  1240. );
  1241. api_item_property_update(
  1242. $_course,
  1243. TOOL_DOCUMENT,
  1244. $audio_id,
  1245. 'FolderCreated',
  1246. api_get_user_id(),
  1247. null,
  1248. null,
  1249. null,
  1250. null,
  1251. api_get_session_id()
  1252. );
  1253. api_item_property_update(
  1254. $_course,
  1255. TOOL_DOCUMENT,
  1256. $audio_id,
  1257. 'invisible',
  1258. api_get_user_id(),
  1259. null,
  1260. null,
  1261. null,
  1262. null,
  1263. api_get_session_id()
  1264. );
  1265. }
  1266. // Upload file in documents.
  1267. $pi = pathinfo($audio['name']);
  1268. if ($pi['extension'] == 'mp3') {
  1269. $c_det = api_get_course_info($this->cc);
  1270. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1271. $path = handle_uploaded_document(
  1272. $c_det,
  1273. $audio,
  1274. $bp,
  1275. '/audio',
  1276. api_get_user_id(),
  1277. 0,
  1278. null,
  1279. 0,
  1280. 'rename',
  1281. false,
  1282. 0
  1283. );
  1284. $path = substr($path, 7);
  1285. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1286. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1287. }
  1288. }
  1289. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1290. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1291. // TODO: htmlspecialchars to be checked for encoding related problems.
  1292. if ($same_parent && $same_previous) {
  1293. // Only update title and description.
  1294. $sql = "UPDATE $tbl_lp_item
  1295. SET title = '".Database::escape_string($title)."',
  1296. prerequisite = '".$prerequisites."',
  1297. description = '".Database::escape_string($description)."'
  1298. ".$audio_update_sql.",
  1299. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1300. WHERE iid = $id";
  1301. Database::query($sql);
  1302. } else {
  1303. $old_parent = $row_select['parent_item_id'];
  1304. $old_previous = $row_select['previous_item_id'];
  1305. $old_next = $row_select['next_item_id'];
  1306. $old_order = $row_select['display_order'];
  1307. $old_prerequisite = $row_select['prerequisite'];
  1308. $old_max_time_allowed = $row_select['max_time_allowed'];
  1309. /* BEGIN -- virtually remove the current item id */
  1310. /* for the next and previous item it is like the current item doesn't exist anymore */
  1311. if ($old_previous != 0) {
  1312. // Next
  1313. $sql = "UPDATE $tbl_lp_item
  1314. SET next_item_id = $old_next
  1315. WHERE iid = $old_previous";
  1316. Database::query($sql);
  1317. }
  1318. if (!empty($old_next)) {
  1319. // Previous
  1320. $sql = "UPDATE $tbl_lp_item
  1321. SET previous_item_id = $old_previous
  1322. WHERE iid = $old_next";
  1323. Database::query($sql);
  1324. }
  1325. // display_order - 1 for every item with a display_order
  1326. // bigger then the display_order of the current item.
  1327. $sql = "UPDATE $tbl_lp_item
  1328. SET display_order = display_order - 1
  1329. WHERE
  1330. c_id = $course_id AND
  1331. display_order > $old_order AND
  1332. lp_id = ".$this->lp_id." AND
  1333. parent_item_id = $old_parent";
  1334. Database::query($sql);
  1335. /* END -- virtually remove the current item id */
  1336. /* BEGIN -- update the current item id to his new location */
  1337. if ($previous == 0) {
  1338. // Select the data of the item that should come after the current item.
  1339. $sql = "SELECT id, display_order
  1340. FROM $tbl_lp_item
  1341. WHERE
  1342. c_id = $course_id AND
  1343. lp_id = ".$this->lp_id." AND
  1344. parent_item_id = $parent AND
  1345. previous_item_id = $previous";
  1346. $res_select_old = Database::query($sql);
  1347. $row_select_old = Database::fetch_array($res_select_old);
  1348. // If the new parent didn't have children before.
  1349. if (Database::num_rows($res_select_old) == 0) {
  1350. $new_next = 0;
  1351. $new_order = 1;
  1352. } else {
  1353. $new_next = $row_select_old['id'];
  1354. $new_order = $row_select_old['display_order'];
  1355. }
  1356. } else {
  1357. // Select the data of the item that should come before the current item.
  1358. $sql = "SELECT next_item_id, display_order
  1359. FROM $tbl_lp_item
  1360. WHERE iid = $previous";
  1361. $res_select_old = Database::query($sql);
  1362. $row_select_old = Database::fetch_array($res_select_old);
  1363. $new_next = $row_select_old['next_item_id'];
  1364. $new_order = $row_select_old['display_order'] + 1;
  1365. }
  1366. // TODO: htmlspecialchars to be checked for encoding related problems.
  1367. // Update the current item with the new data.
  1368. $sql = "UPDATE $tbl_lp_item
  1369. SET
  1370. title = '".Database::escape_string($title)."',
  1371. description = '".Database::escape_string($description)."',
  1372. parent_item_id = $parent,
  1373. previous_item_id = $previous,
  1374. next_item_id = $new_next,
  1375. display_order = $new_order
  1376. $audio_update_sql
  1377. WHERE iid = $id";
  1378. Database::query($sql);
  1379. if ($previous != 0) {
  1380. // Update the previous item's next_item_id.
  1381. $sql = "UPDATE $tbl_lp_item
  1382. SET next_item_id = $id
  1383. WHERE iid = $previous";
  1384. Database::query($sql);
  1385. }
  1386. if (!empty($new_next)) {
  1387. // Update the next item's previous_item_id.
  1388. $sql = "UPDATE $tbl_lp_item
  1389. SET previous_item_id = $id
  1390. WHERE iid = $new_next";
  1391. Database::query($sql);
  1392. }
  1393. if ($old_prerequisite != $prerequisites) {
  1394. $sql = "UPDATE $tbl_lp_item
  1395. SET prerequisite = '$prerequisites'
  1396. WHERE iid = $id";
  1397. Database::query($sql);
  1398. }
  1399. if ($old_max_time_allowed != $max_time_allowed) {
  1400. // update max time allowed
  1401. $sql = "UPDATE $tbl_lp_item
  1402. SET max_time_allowed = $max_time_allowed
  1403. WHERE iid = $id";
  1404. Database::query($sql);
  1405. }
  1406. // Update all the items with the same or a bigger display_order than the current item.
  1407. $sql = "UPDATE $tbl_lp_item
  1408. SET display_order = display_order + 1
  1409. WHERE
  1410. c_id = $course_id AND
  1411. lp_id = ".$this->get_id()." AND
  1412. iid <> $id AND
  1413. parent_item_id = $parent AND
  1414. display_order >= $new_order";
  1415. Database::query($sql);
  1416. }
  1417. if ($row_select['item_type'] == 'link') {
  1418. $link = new Link();
  1419. $linkId = $row_select['path'];
  1420. $link->updateLink($linkId, $url);
  1421. }
  1422. }
  1423. /**
  1424. * Updates an item's prereq in place.
  1425. *
  1426. * @param int $id Element ID
  1427. * @param string $prerequisite_id Prerequisite Element ID
  1428. * @param int $mastery_score Prerequisite min score
  1429. * @param int $max_score Prerequisite max score
  1430. *
  1431. * @return bool True on success, false on error
  1432. */
  1433. public function edit_item_prereq(
  1434. $id,
  1435. $prerequisite_id,
  1436. $mastery_score = 0,
  1437. $max_score = 100
  1438. ) {
  1439. $course_id = api_get_course_int_id();
  1440. if ($this->debug > 0) {
  1441. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$mastery_score.','.$max_score.')', 0);
  1442. }
  1443. if (empty($id) || ($id != strval(intval($id))) || empty($prerequisite_id)) {
  1444. return false;
  1445. }
  1446. $prerequisite_id = (int) $prerequisite_id;
  1447. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1448. if (!is_numeric($mastery_score) || $mastery_score < 0) {
  1449. $mastery_score = 0;
  1450. }
  1451. if (!is_numeric($max_score) || $max_score < 0) {
  1452. $max_score = 100;
  1453. }
  1454. /*if ($mastery_score > $max_score) {
  1455. $max_score = $mastery_score;
  1456. }*/
  1457. if (!is_numeric($prerequisite_id)) {
  1458. $prerequisite_id = 'NULL';
  1459. }
  1460. $mastery_score = floatval($mastery_score);
  1461. $max_score = floatval($max_score);
  1462. $sql = " UPDATE $tbl_lp_item
  1463. SET
  1464. prerequisite = $prerequisite_id ,
  1465. prerequisite_min_score = $mastery_score ,
  1466. prerequisite_max_score = $max_score
  1467. WHERE iid = $id";
  1468. Database::query($sql);
  1469. // TODO: Update the item object (can be ignored for now because refreshed).
  1470. return true;
  1471. }
  1472. /**
  1473. * Gets all the chapters belonging to the same parent as the item/chapter given
  1474. * Can also be called as abstract method.
  1475. *
  1476. * @param int $id Item ID
  1477. *
  1478. * @return array A list of all the "brother items" (or an empty array on failure)
  1479. */
  1480. public function getSiblingDirectories($id)
  1481. {
  1482. $course_id = api_get_course_int_id();
  1483. if ($this->debug > 0) {
  1484. error_log('In learnpath::getSiblingDirectories()', 0);
  1485. }
  1486. if (empty($id) || $id != strval(intval($id))) {
  1487. return [];
  1488. }
  1489. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1490. $sql_parent = "SELECT * FROM $lp_item
  1491. WHERE iid = $id AND item_type='dir'";
  1492. $res_parent = Database::query($sql_parent);
  1493. if (Database::num_rows($res_parent) > 0) {
  1494. $row_parent = Database::fetch_array($res_parent);
  1495. $parent = $row_parent['parent_item_id'];
  1496. $sql = "SELECT * FROM $lp_item
  1497. WHERE
  1498. parent_item_id = $parent AND
  1499. iid = $id AND
  1500. item_type='dir'
  1501. ORDER BY display_order";
  1502. $res_bros = Database::query($sql);
  1503. $list = [];
  1504. while ($row_bro = Database::fetch_array($res_bros)) {
  1505. $list[] = $row_bro;
  1506. }
  1507. return $list;
  1508. }
  1509. return [];
  1510. }
  1511. /**
  1512. * Gets all the items belonging to the same parent as the item given
  1513. * Can also be called as abstract method.
  1514. *
  1515. * @param int $id Item ID
  1516. *
  1517. * @return array A list of all the "brother items" (or an empty array on failure)
  1518. */
  1519. public function get_brother_items($id)
  1520. {
  1521. $course_id = api_get_course_int_id();
  1522. if ($this->debug > 0) {
  1523. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1524. }
  1525. if (empty($id) || $id != strval(intval($id))) {
  1526. return [];
  1527. }
  1528. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1529. $sql_parent = "SELECT * FROM $lp_item
  1530. WHERE iid = $id";
  1531. $res_parent = Database::query($sql_parent);
  1532. if (Database::num_rows($res_parent) > 0) {
  1533. $row_parent = Database::fetch_array($res_parent);
  1534. $parent = $row_parent['parent_item_id'];
  1535. $sql = "SELECT * FROM $lp_item
  1536. WHERE c_id = $course_id AND parent_item_id = $parent
  1537. ORDER BY display_order";
  1538. $res_bros = Database::query($sql);
  1539. $list = [];
  1540. while ($row_bro = Database::fetch_array($res_bros)) {
  1541. $list[] = $row_bro;
  1542. }
  1543. return $list;
  1544. }
  1545. return [];
  1546. }
  1547. /**
  1548. * Get the specific prefix index terms of this learning path.
  1549. *
  1550. * @param string $prefix
  1551. *
  1552. * @return array Array of terms
  1553. */
  1554. public function get_common_index_terms_by_prefix($prefix)
  1555. {
  1556. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1557. $terms = get_specific_field_values_list_by_prefix(
  1558. $prefix,
  1559. $this->cc,
  1560. TOOL_LEARNPATH,
  1561. $this->lp_id
  1562. );
  1563. $prefix_terms = [];
  1564. if (!empty($terms)) {
  1565. foreach ($terms as $term) {
  1566. $prefix_terms[] = $term['value'];
  1567. }
  1568. }
  1569. return $prefix_terms;
  1570. }
  1571. /**
  1572. * Gets the number of items currently completed.
  1573. *
  1574. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1575. *
  1576. * @return int The number of items currently completed
  1577. */
  1578. public function get_complete_items_count($failedStatusException = false)
  1579. {
  1580. if ($this->debug > 0) {
  1581. error_log('In learnpath::get_complete_items_count()', 0);
  1582. }
  1583. $i = 0;
  1584. $completedStatusList = [
  1585. 'completed',
  1586. 'passed',
  1587. 'succeeded',
  1588. 'browsed',
  1589. ];
  1590. if (!$failedStatusException) {
  1591. $completedStatusList[] = 'failed';
  1592. }
  1593. foreach ($this->items as $id => $dummy) {
  1594. // Trying failed and browsed considered "progressed" as well.
  1595. if ($this->items[$id]->status_is($completedStatusList) &&
  1596. $this->items[$id]->get_type() != 'dir'
  1597. ) {
  1598. $i++;
  1599. }
  1600. }
  1601. return $i;
  1602. }
  1603. /**
  1604. * Gets the current item ID.
  1605. *
  1606. * @return int The current learnpath item id
  1607. */
  1608. public function get_current_item_id()
  1609. {
  1610. $current = 0;
  1611. if ($this->debug > 0) {
  1612. error_log('In learnpath::get_current_item_id()', 0);
  1613. }
  1614. if (!empty($this->current)) {
  1615. $current = $this->current;
  1616. }
  1617. if ($this->debug > 2) {
  1618. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1619. }
  1620. return $current;
  1621. }
  1622. /**
  1623. * Force to get the first learnpath item id.
  1624. *
  1625. * @return int The current learnpath item id
  1626. */
  1627. public function get_first_item_id()
  1628. {
  1629. $current = 0;
  1630. if (is_array($this->ordered_items)) {
  1631. $current = $this->ordered_items[0];
  1632. }
  1633. return $current;
  1634. }
  1635. /**
  1636. * Gets the total number of items available for viewing in this SCORM.
  1637. *
  1638. * @return int The total number of items
  1639. */
  1640. public function get_total_items_count()
  1641. {
  1642. if ($this->debug > 0) {
  1643. error_log('In learnpath::get_total_items_count()', 0);
  1644. }
  1645. return count($this->items);
  1646. }
  1647. /**
  1648. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1649. *
  1650. * @return int The total no-chapters number of items
  1651. */
  1652. public function getTotalItemsCountWithoutDirs()
  1653. {
  1654. if ($this->debug > 0) {
  1655. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1656. }
  1657. $total = 0;
  1658. $typeListNotToCount = self::getChapterTypes();
  1659. foreach ($this->items as $temp2) {
  1660. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1661. $total++;
  1662. }
  1663. }
  1664. return $total;
  1665. }
  1666. /**
  1667. * Sets the first element URL.
  1668. */
  1669. public function first()
  1670. {
  1671. if ($this->debug > 0) {
  1672. error_log('In learnpath::first()', 0);
  1673. error_log('$this->last_item_seen '.$this->last_item_seen);
  1674. }
  1675. // Test if the last_item_seen exists and is not a dir.
  1676. if (count($this->ordered_items) == 0) {
  1677. $this->index = 0;
  1678. }
  1679. if (!empty($this->last_item_seen) &&
  1680. !empty($this->items[$this->last_item_seen]) &&
  1681. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1682. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1683. //&& !$this->items[$this->last_item_seen]->is_done()
  1684. ) {
  1685. if ($this->debug > 2) {
  1686. error_log(
  1687. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1688. $this->items[$this->last_item_seen]->get_type()
  1689. );
  1690. }
  1691. $index = -1;
  1692. foreach ($this->ordered_items as $myindex => $item_id) {
  1693. if ($item_id == $this->last_item_seen) {
  1694. $index = $myindex;
  1695. break;
  1696. }
  1697. }
  1698. if ($index == -1) {
  1699. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1700. if ($this->debug > 2) {
  1701. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1702. }
  1703. return false;
  1704. } else {
  1705. $this->last = $this->last_item_seen;
  1706. $this->current = $this->last_item_seen;
  1707. $this->index = $index;
  1708. }
  1709. } else {
  1710. if ($this->debug > 2) {
  1711. error_log('In learnpath::first() - No last item seen', 0);
  1712. }
  1713. $index = 0;
  1714. // Loop through all ordered items and stop at the first item that is
  1715. // not a directory *and* that has not been completed yet.
  1716. while (!empty($this->ordered_items[$index]) &&
  1717. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1718. (
  1719. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1720. $this->items[$this->ordered_items[$index]]->is_done() === true
  1721. ) && $index < $this->max_ordered_items) {
  1722. $index++;
  1723. }
  1724. $this->last = $this->current;
  1725. // current is
  1726. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1727. $this->index = $index;
  1728. if ($this->debug > 2) {
  1729. error_log('$index '.$index);
  1730. error_log('In learnpath::first() - No last item seen');
  1731. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1732. }
  1733. }
  1734. if ($this->debug > 2) {
  1735. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1736. }
  1737. }
  1738. /**
  1739. * Gets the information about an item in a format usable as JavaScript to update
  1740. * the JS API by just printing this content into the <head> section of the message frame.
  1741. *
  1742. * @param int $item_id
  1743. *
  1744. * @return string
  1745. */
  1746. public function get_js_info($item_id = 0)
  1747. {
  1748. if ($this->debug > 0) {
  1749. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1750. }
  1751. $info = '';
  1752. $item_id = intval($item_id);
  1753. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1754. //if item is defined, return values from DB
  1755. $oItem = $this->items[$item_id];
  1756. $info .= '<script language="javascript">';
  1757. $info .= "top.set_score(".$oItem->get_score().");\n";
  1758. $info .= "top.set_max(".$oItem->get_max().");\n";
  1759. $info .= "top.set_min(".$oItem->get_min().");\n";
  1760. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1761. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1762. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1763. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1764. $info .= "top.set_flag_synchronized();";
  1765. $info .= '</script>';
  1766. if ($this->debug > 2) {
  1767. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1768. }
  1769. return $info;
  1770. } else {
  1771. // If item_id is empty, just update to default SCORM data.
  1772. $info .= '<script language="javascript">';
  1773. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1774. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1775. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1776. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1777. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1778. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1779. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1780. $info .= "top.set_flag_synchronized();";
  1781. $info .= '</script>';
  1782. if ($this->debug > 2) {
  1783. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1784. }
  1785. return $info;
  1786. }
  1787. }
  1788. /**
  1789. * Gets the js library from the database.
  1790. *
  1791. * @return string The name of the javascript library to be used
  1792. */
  1793. public function get_js_lib()
  1794. {
  1795. $lib = '';
  1796. if (!empty($this->js_lib)) {
  1797. $lib = $this->js_lib;
  1798. }
  1799. return $lib;
  1800. }
  1801. /**
  1802. * Gets the learnpath database ID.
  1803. *
  1804. * @return int Learnpath ID in the lp table
  1805. */
  1806. public function get_id()
  1807. {
  1808. if (!empty($this->lp_id)) {
  1809. return $this->lp_id;
  1810. } else {
  1811. return 0;
  1812. }
  1813. }
  1814. /**
  1815. * Gets the last element URL.
  1816. *
  1817. * @return string URL to load into the viewer
  1818. */
  1819. public function get_last()
  1820. {
  1821. if ($this->debug > 0) {
  1822. error_log('In learnpath::get_last()', 0);
  1823. }
  1824. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1825. if (count($this->ordered_items) > 0) {
  1826. $this->index = count($this->ordered_items) - 1;
  1827. return $this->ordered_items[$this->index];
  1828. }
  1829. return false;
  1830. }
  1831. /**
  1832. * Gets the navigation bar for the learnpath display screen.
  1833. *
  1834. * @return string The HTML string to use as a navigation bar
  1835. */
  1836. public function get_navigation_bar($idBar = null, $display = null)
  1837. {
  1838. if ($this->debug > 0) {
  1839. error_log('In learnpath::get_navigation_bar()', 0);
  1840. }
  1841. if (empty($idBar)) {
  1842. $idBar = 'control-top';
  1843. }
  1844. $lpId = $this->lp_id;
  1845. $mycurrentitemid = $this->get_current_item_id();
  1846. $reportingText = get_lang('Reporting');
  1847. $previousText = get_lang('ScormPrevious');
  1848. $nextText = get_lang('ScormNext');
  1849. $fullScreenText = get_lang('ScormExitFullScreen');
  1850. $settings = api_get_configuration_value('lp_view_settings');
  1851. $display = isset($settings['display']) ? $settings['display'] : false;
  1852. $reportingIcon = '
  1853. <a class="icon-toolbar"
  1854. id="stats_link"
  1855. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1856. onclick="window.parent.API.save_asset(); return true;"
  1857. target="content_name" title="'.$reportingText.'">
  1858. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1859. </a>';
  1860. if (!empty($display)) {
  1861. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1862. if ($showReporting == false) {
  1863. $reportingIcon = '';
  1864. }
  1865. }
  1866. $previousIcon = '
  1867. <a class="icon-toolbar" id="scorm-previous" href="#"
  1868. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1869. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1870. </a>';
  1871. $nextIcon = '
  1872. <a class="icon-toolbar" id="scorm-next" href="#"
  1873. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1874. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1875. </a>';
  1876. if ($this->mode == 'fullscreen') {
  1877. $navbar = '
  1878. <span id="'.$idBar.'" class="buttons">
  1879. '.$reportingIcon.'
  1880. '.$previousIcon.'
  1881. '.$nextIcon.'
  1882. <a class="icon-toolbar" id="view-embedded"
  1883. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1884. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1885. </a>
  1886. </span>';
  1887. } else {
  1888. $navbar = '
  1889. <span id="'.$idBar.'" class="buttons text-right">
  1890. '.$reportingIcon.'
  1891. '.$previousIcon.'
  1892. '.$nextIcon.'
  1893. </span>';
  1894. }
  1895. return $navbar;
  1896. }
  1897. /**
  1898. * Gets the next resource in queue (url).
  1899. *
  1900. * @return string URL to load into the viewer
  1901. */
  1902. public function get_next_index()
  1903. {
  1904. if ($this->debug > 0) {
  1905. error_log('In learnpath::get_next_index()', 0);
  1906. }
  1907. // TODO
  1908. $index = $this->index;
  1909. $index++;
  1910. if ($this->debug > 2) {
  1911. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1912. }
  1913. while (
  1914. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1915. $index < $this->max_ordered_items
  1916. ) {
  1917. $index++;
  1918. if ($index == $this->max_ordered_items) {
  1919. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1920. return $this->index;
  1921. } else {
  1922. return $index;
  1923. }
  1924. }
  1925. }
  1926. if (empty($this->ordered_items[$index])) {
  1927. return $this->index;
  1928. }
  1929. if ($this->debug > 2) {
  1930. error_log('index is now '.$index, 0);
  1931. }
  1932. return $index;
  1933. }
  1934. /**
  1935. * Gets item_id for the next element.
  1936. *
  1937. * @return int Next item (DB) ID
  1938. */
  1939. public function get_next_item_id()
  1940. {
  1941. if ($this->debug > 0) {
  1942. error_log('In learnpath::get_next_item_id()', 0);
  1943. }
  1944. $new_index = $this->get_next_index();
  1945. if (!empty($new_index)) {
  1946. if (isset($this->ordered_items[$new_index])) {
  1947. if ($this->debug > 2) {
  1948. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1949. }
  1950. return $this->ordered_items[$new_index];
  1951. }
  1952. }
  1953. if ($this->debug > 2) {
  1954. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1955. }
  1956. return 0;
  1957. }
  1958. /**
  1959. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1960. *
  1961. * Generally, the package provided is in the form of a zip file, so the function
  1962. * has been written to test a zip file. If not a zip, the function will return the
  1963. * default return value: ''
  1964. *
  1965. * @param string $file_path the path to the file
  1966. * @param string $file_name the original name of the file
  1967. *
  1968. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1969. */
  1970. public static function get_package_type($file_path, $file_name)
  1971. {
  1972. // Get name of the zip file without the extension.
  1973. $file_info = pathinfo($file_name);
  1974. $extension = $file_info['extension']; // Extension only.
  1975. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1976. 'dll',
  1977. 'exe',
  1978. ])) {
  1979. return 'oogie';
  1980. }
  1981. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1982. 'dll',
  1983. 'exe',
  1984. ])) {
  1985. return 'woogie';
  1986. }
  1987. $zipFile = new PclZip($file_path);
  1988. // Check the zip content (real size and file extension).
  1989. $zipContentArray = $zipFile->listContent();
  1990. $package_type = '';
  1991. $manifest = '';
  1992. $aicc_match_crs = 0;
  1993. $aicc_match_au = 0;
  1994. $aicc_match_des = 0;
  1995. $aicc_match_cst = 0;
  1996. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1997. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1998. foreach ($zipContentArray as $thisContent) {
  1999. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2000. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2001. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2002. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2003. $package_type = 'scorm';
  2004. break; // Exit the foreach loop.
  2005. } elseif (
  2006. preg_match('/aicc\//i', $thisContent['filename']) ||
  2007. in_array(
  2008. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2009. ['crs', 'au', 'des', 'cst']
  2010. )
  2011. ) {
  2012. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2013. switch ($ext) {
  2014. case 'crs':
  2015. $aicc_match_crs = 1;
  2016. break;
  2017. case 'au':
  2018. $aicc_match_au = 1;
  2019. break;
  2020. case 'des':
  2021. $aicc_match_des = 1;
  2022. break;
  2023. case 'cst':
  2024. $aicc_match_cst = 1;
  2025. break;
  2026. default:
  2027. break;
  2028. }
  2029. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2030. } else {
  2031. $package_type = '';
  2032. }
  2033. }
  2034. }
  2035. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2036. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2037. $package_type = 'aicc';
  2038. }
  2039. // Try with chamilo course builder
  2040. if (empty($package_type)) {
  2041. $package_type = 'chamilo';
  2042. }
  2043. return $package_type;
  2044. }
  2045. /**
  2046. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2047. *
  2048. * @return string URL to load into the viewer
  2049. */
  2050. public function get_previous_index()
  2051. {
  2052. if ($this->debug > 0) {
  2053. error_log('In learnpath::get_previous_index()', 0);
  2054. }
  2055. $index = $this->index;
  2056. if (isset($this->ordered_items[$index - 1])) {
  2057. $index--;
  2058. while (isset($this->ordered_items[$index]) &&
  2059. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2060. ) {
  2061. $index--;
  2062. if ($index < 0) {
  2063. return $this->index;
  2064. }
  2065. }
  2066. } else {
  2067. if ($this->debug > 2) {
  2068. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2069. }
  2070. // There is no previous item.
  2071. }
  2072. return $index;
  2073. }
  2074. /**
  2075. * Gets item_id for the next element.
  2076. *
  2077. * @return int Previous item (DB) ID
  2078. */
  2079. public function get_previous_item_id()
  2080. {
  2081. if ($this->debug > 0) {
  2082. error_log('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. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2089. *
  2090. * @param int $lpItemId
  2091. * @param string $autostart
  2092. *
  2093. * @return string The mediaplayer HTML
  2094. */
  2095. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2096. {
  2097. $course_id = api_get_course_int_id();
  2098. $_course = api_get_course_info();
  2099. if (empty($_course)) {
  2100. return '';
  2101. }
  2102. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2103. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2104. $lpItemId = (int) $lpItemId;
  2105. // Getting all the information about the item.
  2106. $sql = "SELECT * FROM $tbl_lp_item as lpi
  2107. INNER JOIN $tbl_lp_item_view as lp_view
  2108. ON (lpi.iid = lp_view.lp_item_id)
  2109. WHERE
  2110. lpi.iid = $lpItemId AND
  2111. lp_view.c_id = $course_id";
  2112. $result = Database::query($sql);
  2113. $row = Database::fetch_assoc($result);
  2114. $output = '';
  2115. if (!empty($row['audio'])) {
  2116. $list = $_SESSION['oLP']->get_toc();
  2117. $type_quiz = false;
  2118. foreach ($list as $toc) {
  2119. if ($toc['id'] == $_SESSION['oLP']->current && $toc['type'] == 'quiz') {
  2120. $type_quiz = true;
  2121. }
  2122. }
  2123. if ($type_quiz) {
  2124. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2125. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2126. } else {
  2127. $autostart_audio = $autostart;
  2128. }
  2129. } else {
  2130. $autostart_audio = 'true';
  2131. }
  2132. $courseInfo = api_get_course_info();
  2133. $audio = $row['audio'];
  2134. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2135. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2136. if (!file_exists($file)) {
  2137. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2138. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2139. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2140. }
  2141. $player = Display::getMediaPlayer(
  2142. $file,
  2143. [
  2144. 'id' => 'lp_audio_media_player',
  2145. 'url' => $url,
  2146. 'autoplay' => $autostart_audio,
  2147. 'width' => '100%',
  2148. ]
  2149. );
  2150. // The mp3 player.
  2151. $output = '<div id="container">';
  2152. $output .= $player;
  2153. $output .= '</div>';
  2154. }
  2155. return $output;
  2156. }
  2157. /**
  2158. * @param int $studentId
  2159. * @param int $prerequisite
  2160. * @param array $courseInfo
  2161. * @param int $sessionId
  2162. *
  2163. * @return bool
  2164. */
  2165. public static function isBlockedByPrerequisite(
  2166. $studentId,
  2167. $prerequisite,
  2168. $courseInfo,
  2169. $sessionId
  2170. ) {
  2171. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2172. if ($allow) {
  2173. if (api_is_allowed_to_edit() ||
  2174. api_is_platform_admin(true) ||
  2175. api_is_drh() ||
  2176. api_is_coach($sessionId, $courseInfo['real_id'], false)
  2177. ) {
  2178. return false;
  2179. }
  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. *
  2200. * @param int $lp_id
  2201. * @param int $student_id
  2202. * @param null $courseCode
  2203. * @param int $sessionId
  2204. *
  2205. * @return bool
  2206. */
  2207. public static function is_lp_visible_for_student(
  2208. $lp_id,
  2209. $student_id,
  2210. $courseCode = null,
  2211. $sessionId = 0
  2212. ) {
  2213. $courseInfo = api_get_course_info($courseCode);
  2214. $lp_id = (int) $lp_id;
  2215. $sessionId = (int) $sessionId;
  2216. if (empty($courseInfo)) {
  2217. return false;
  2218. }
  2219. if (empty($sessionId)) {
  2220. $sessionId = api_get_session_id();
  2221. }
  2222. $itemInfo = api_get_item_property_info(
  2223. $courseInfo['real_id'],
  2224. TOOL_LEARNPATH,
  2225. $lp_id,
  2226. $sessionId
  2227. );
  2228. // If the item was deleted.
  2229. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2230. return false;
  2231. }
  2232. // @todo remove this query and load the row info as a parameter
  2233. $table = Database::get_course_table(TABLE_LP_MAIN);
  2234. // Get current prerequisite
  2235. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2236. FROM $table
  2237. WHERE iid = $lp_id";
  2238. $rs = Database::query($sql);
  2239. $now = time();
  2240. if (Database::num_rows($rs) > 0) {
  2241. $row = Database::fetch_array($rs, 'ASSOC');
  2242. $prerequisite = $row['prerequisite'];
  2243. $is_visible = true;
  2244. $isBlocked = self::isBlockedByPrerequisite(
  2245. $student_id,
  2246. $prerequisite,
  2247. $courseInfo,
  2248. $sessionId
  2249. );
  2250. if ($isBlocked) {
  2251. $is_visible = false;
  2252. }
  2253. // Also check the time availability of the LP
  2254. if ($is_visible) {
  2255. // Adding visibility restrictions
  2256. if (!empty($row['publicated_on'])) {
  2257. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2258. $is_visible = false;
  2259. }
  2260. }
  2261. // Blocking empty start times see BT#2800
  2262. global $_custom;
  2263. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2264. $_custom['lps_hidden_when_no_start_date']
  2265. ) {
  2266. if (empty($row['publicated_on'])) {
  2267. $is_visible = false;
  2268. }
  2269. }
  2270. if (!empty($row['expired_on'])) {
  2271. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2272. $is_visible = false;
  2273. }
  2274. }
  2275. }
  2276. $subscriptionSettings = self::getSubscriptionSettings();
  2277. // Check if the subscription users/group to a LP is ON
  2278. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2279. $subscriptionSettings['allow_add_users_to_lp'] === true
  2280. ) {
  2281. // Try group
  2282. $is_visible = false;
  2283. // Checking only the user visibility
  2284. $userVisibility = api_get_item_visibility(
  2285. $courseInfo,
  2286. 'learnpath',
  2287. $row['id'],
  2288. $sessionId,
  2289. $student_id,
  2290. 'LearnpathSubscription'
  2291. );
  2292. if ($userVisibility == 1) {
  2293. $is_visible = true;
  2294. } else {
  2295. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2296. if (!empty($userGroups)) {
  2297. foreach ($userGroups as $groupInfo) {
  2298. $groupId = $groupInfo['iid'];
  2299. $userVisibility = api_get_item_visibility(
  2300. $courseInfo,
  2301. 'learnpath',
  2302. $row['id'],
  2303. $sessionId,
  2304. null,
  2305. 'LearnpathSubscription',
  2306. $groupId
  2307. );
  2308. if ($userVisibility == 1) {
  2309. $is_visible = true;
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. }
  2315. }
  2316. return $is_visible;
  2317. }
  2318. return false;
  2319. }
  2320. /**
  2321. * @param int $lpId
  2322. * @param int $userId
  2323. * @param int $courseId
  2324. * @param int $sessionId
  2325. *
  2326. * @return int
  2327. */
  2328. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2329. {
  2330. $lpId = (int) $lpId;
  2331. $userId = (int) $userId;
  2332. $courseId = (int) $courseId;
  2333. $sessionId = (int) $sessionId;
  2334. $progress = 0;
  2335. $sessionCondition = api_get_session_condition($sessionId);
  2336. $table = Database::get_course_table(TABLE_LP_VIEW);
  2337. $sql = "SELECT * FROM $table
  2338. WHERE
  2339. c_id = $courseId AND
  2340. lp_id = $lpId AND
  2341. user_id = $userId $sessionCondition ";
  2342. $res = Database::query($sql);
  2343. if (Database::num_rows($res) > 0) {
  2344. $row = Database:: fetch_array($res);
  2345. $progress = $row['progress'];
  2346. }
  2347. return (int) $progress;
  2348. }
  2349. /**
  2350. * Displays a progress bar
  2351. * completed so far.
  2352. *
  2353. * @param int $percentage Progress value to display
  2354. * @param string $text_add Text to display near the progress value
  2355. *
  2356. * @return string HTML string containing the progress bar
  2357. */
  2358. public static function get_progress_bar($percentage = -1, $text_add = '')
  2359. {
  2360. $text = $percentage.$text_add;
  2361. $output = '<div class="progress">
  2362. <div id="progress_bar_value"
  2363. class="progress-bar progress-bar-success" role="progressbar"
  2364. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2365. '.$text.'
  2366. </div>
  2367. </div>';
  2368. return $output;
  2369. }
  2370. /**
  2371. * @param string $mode can be '%' or 'abs'
  2372. * otherwise this value will be used $this->progress_bar_mode
  2373. *
  2374. * @return string
  2375. */
  2376. public function getProgressBar($mode = null)
  2377. {
  2378. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2379. return self::get_progress_bar($percentage, $text_add);
  2380. }
  2381. /**
  2382. * Gets the progress bar info to display inside the progress bar.
  2383. * Also used by scorm_api.php.
  2384. *
  2385. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2386. * we display a number of completed elements per total elements
  2387. * @param int $add Additional steps to fake as completed
  2388. *
  2389. * @return array Percentage or number and symbol (% or /xx)
  2390. */
  2391. public function get_progress_bar_text($mode = '', $add = 0)
  2392. {
  2393. if ($this->debug > 0) {
  2394. error_log('In learnpath::get_progress_bar_text()', 0);
  2395. }
  2396. if (empty($mode)) {
  2397. $mode = $this->progress_bar_mode;
  2398. }
  2399. $total_items = $this->getTotalItemsCountWithoutDirs();
  2400. if ($this->debug > 2) {
  2401. error_log('Total items available in this learnpath: '.$total_items, 0);
  2402. }
  2403. $completeItems = $this->get_complete_items_count();
  2404. if ($this->debug > 2) {
  2405. error_log('Items completed so far: '.$completeItems, 0);
  2406. }
  2407. if ($add != 0) {
  2408. $completeItems += $add;
  2409. if ($this->debug > 2) {
  2410. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2411. }
  2412. }
  2413. $text = '';
  2414. if ($completeItems > $total_items) {
  2415. $completeItems = $total_items;
  2416. }
  2417. $percentage = 0;
  2418. if ($mode == '%') {
  2419. if ($total_items > 0) {
  2420. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2421. } else {
  2422. $percentage = 0;
  2423. }
  2424. $percentage = number_format($percentage, 0);
  2425. $text = '%';
  2426. } elseif ($mode == 'abs') {
  2427. $percentage = $completeItems;
  2428. $text = '/'.$total_items;
  2429. }
  2430. return [
  2431. $percentage,
  2432. $text,
  2433. ];
  2434. }
  2435. /**
  2436. * Gets the progress bar mode.
  2437. *
  2438. * @return string The progress bar mode attribute
  2439. */
  2440. public function get_progress_bar_mode()
  2441. {
  2442. if ($this->debug > 0) {
  2443. error_log('In learnpath::get_progress_bar_mode()', 0);
  2444. }
  2445. if (!empty($this->progress_bar_mode)) {
  2446. return $this->progress_bar_mode;
  2447. } else {
  2448. return '%';
  2449. }
  2450. }
  2451. /**
  2452. * Gets the learnpath theme (remote or local).
  2453. *
  2454. * @return string Learnpath theme
  2455. */
  2456. public function get_theme()
  2457. {
  2458. if ($this->debug > 0) {
  2459. error_log('In learnpath::get_theme()', 0);
  2460. }
  2461. if (!empty($this->theme)) {
  2462. return $this->theme;
  2463. } else {
  2464. return '';
  2465. }
  2466. }
  2467. /**
  2468. * Gets the learnpath session id.
  2469. *
  2470. * @return int
  2471. */
  2472. public function get_lp_session_id()
  2473. {
  2474. if ($this->debug > 0) {
  2475. error_log('In learnpath::get_lp_session_id()', 0);
  2476. }
  2477. if (!empty($this->lp_session_id)) {
  2478. return (int) $this->lp_session_id;
  2479. } else {
  2480. return 0;
  2481. }
  2482. }
  2483. /**
  2484. * Gets the learnpath image.
  2485. *
  2486. * @return string Web URL of the LP image
  2487. */
  2488. public function get_preview_image()
  2489. {
  2490. if ($this->debug > 0) {
  2491. error_log('In learnpath::get_preview_image()', 0);
  2492. }
  2493. if (!empty($this->preview_image)) {
  2494. return $this->preview_image;
  2495. } else {
  2496. return '';
  2497. }
  2498. }
  2499. /**
  2500. * @param string $size
  2501. * @param string $path_type
  2502. *
  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. *
  2534. * @return string LP's author
  2535. */
  2536. public function get_author()
  2537. {
  2538. if ($this->debug > 0) {
  2539. error_log('In learnpath::get_author()', 0);
  2540. }
  2541. if (!empty($this->author)) {
  2542. return $this->author;
  2543. } else {
  2544. return '';
  2545. }
  2546. }
  2547. /**
  2548. * Gets hide table of contents.
  2549. *
  2550. * @return int
  2551. */
  2552. public function getHideTableOfContents()
  2553. {
  2554. return (int) $this->hide_toc_frame;
  2555. }
  2556. /**
  2557. * Generate a new prerequisites string for a given item. If this item was a sco and
  2558. * its prerequisites were strings (instead of IDs), then transform those strings into
  2559. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2560. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2561. * same rule as the scormExport() method.
  2562. *
  2563. * @param int $item_id Item ID
  2564. *
  2565. * @return string Prerequisites string ready for the export as SCORM
  2566. */
  2567. public function get_scorm_prereq_string($item_id)
  2568. {
  2569. if ($this->debug > 0) {
  2570. error_log('In learnpath::get_scorm_prereq_string()');
  2571. }
  2572. if (!is_object($this->items[$item_id])) {
  2573. return false;
  2574. }
  2575. /** @var learnpathItem $oItem */
  2576. $oItem = $this->items[$item_id];
  2577. $prereq = $oItem->get_prereq_string();
  2578. if (empty($prereq)) {
  2579. return '';
  2580. }
  2581. if (preg_match('/^\d+$/', $prereq) &&
  2582. isset($this->items[$prereq]) &&
  2583. is_object($this->items[$prereq])
  2584. ) {
  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. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2595. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2596. } else {
  2597. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2598. // and replace them, one by one, by the internal IDs (chamilo db)
  2599. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2600. // by a space as well.
  2601. $find = [
  2602. '&',
  2603. '|',
  2604. '~',
  2605. '=',
  2606. '<>',
  2607. '{',
  2608. '}',
  2609. '*',
  2610. '(',
  2611. ')',
  2612. ];
  2613. $replace = [
  2614. ' ',
  2615. ' ',
  2616. ' ',
  2617. ' ',
  2618. ' ',
  2619. ' ',
  2620. ' ',
  2621. ' ',
  2622. ' ',
  2623. ' ',
  2624. ];
  2625. $prereq_mod = str_replace($find, $replace, $prereq);
  2626. $ids = explode(' ', $prereq_mod);
  2627. foreach ($ids as $id) {
  2628. $id = trim($id);
  2629. if (isset($this->refs_list[$id])) {
  2630. $prereq = preg_replace(
  2631. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2632. 'ITEM_'.$this->refs_list[$id],
  2633. $prereq
  2634. );
  2635. }
  2636. }
  2637. return $prereq;
  2638. }
  2639. }
  2640. }
  2641. /**
  2642. * Returns the XML DOM document's node.
  2643. *
  2644. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2645. * @param string $id The identifier to look for
  2646. *
  2647. * @return mixed The reference to the element found with that identifier. False if not found
  2648. */
  2649. public function get_scorm_xml_node(&$children, $id)
  2650. {
  2651. for ($i = 0; $i < $children->length; $i++) {
  2652. $item_temp = $children->item($i);
  2653. if ($item_temp->nodeName == 'item') {
  2654. if ($item_temp->getAttribute('identifier') == $id) {
  2655. return $item_temp;
  2656. }
  2657. }
  2658. $subchildren = $item_temp->childNodes;
  2659. if ($subchildren && $subchildren->length > 0) {
  2660. $val = $this->get_scorm_xml_node($subchildren, $id);
  2661. if (is_object($val)) {
  2662. return $val;
  2663. }
  2664. }
  2665. }
  2666. return false;
  2667. }
  2668. /**
  2669. * Gets the status list for all LP's items.
  2670. *
  2671. * @return array Array of [index] => [item ID => current status]
  2672. */
  2673. public function get_items_status_list()
  2674. {
  2675. if ($this->debug > 0) {
  2676. error_log('In learnpath::get_items_status_list()', 0);
  2677. }
  2678. $list = [];
  2679. foreach ($this->ordered_items as $item_id) {
  2680. $list[] = [
  2681. $item_id => $this->items[$item_id]->get_status(),
  2682. ];
  2683. }
  2684. return $list;
  2685. }
  2686. /**
  2687. * Return the number of interactions for the given learnpath Item View ID.
  2688. * This method can be used as static.
  2689. *
  2690. * @param int $lp_iv_id Item View ID
  2691. * @param int $course_id course id
  2692. *
  2693. * @return int
  2694. */
  2695. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2696. {
  2697. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2698. $lp_iv_id = (int) $lp_iv_id;
  2699. $course_id = (int) $course_id;
  2700. $sql = "SELECT count(*) FROM $table
  2701. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2702. $res = Database::query($sql);
  2703. $num = 0;
  2704. if (Database::num_rows($res)) {
  2705. $row = Database::fetch_array($res);
  2706. $num = $row[0];
  2707. }
  2708. return $num;
  2709. }
  2710. /**
  2711. * Return the interactions as an array for the given lp_iv_id.
  2712. * This method can be used as static.
  2713. *
  2714. * @param int $lp_iv_id Learnpath Item View ID
  2715. *
  2716. * @return array
  2717. *
  2718. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2719. */
  2720. public static function get_iv_interactions_array($lp_iv_id)
  2721. {
  2722. $course_id = api_get_course_int_id();
  2723. $list = [];
  2724. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2725. if (empty($lp_iv_id)) {
  2726. return [];
  2727. }
  2728. $sql = "SELECT * FROM $table
  2729. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2730. ORDER BY order_id ASC";
  2731. $res = Database::query($sql);
  2732. $num = Database::num_rows($res);
  2733. if ($num > 0) {
  2734. $list[] = [
  2735. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2736. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2737. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2738. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2739. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2740. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2741. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2742. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2743. ];
  2744. while ($row = Database::fetch_array($res)) {
  2745. $list[] = [
  2746. 'order_id' => ($row['order_id'] + 1),
  2747. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2748. 'type' => $row['interaction_type'],
  2749. 'time' => $row['completion_time'],
  2750. //'correct_responses' => $row['correct_responses'],
  2751. 'correct_responses' => '', // Hide correct responses from students.
  2752. 'student_response' => $row['student_response'],
  2753. 'result' => $row['result'],
  2754. 'latency' => $row['latency'],
  2755. ];
  2756. }
  2757. }
  2758. return $list;
  2759. }
  2760. /**
  2761. * Return the number of objectives for the given learnpath Item View ID.
  2762. * This method can be used as static.
  2763. *
  2764. * @param int $lp_iv_id Item View ID
  2765. * @param int $course_id Course ID
  2766. *
  2767. * @return int Number of objectives
  2768. */
  2769. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2770. {
  2771. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2772. $course_id = intval($course_id);
  2773. $lp_iv_id = intval($lp_iv_id);
  2774. $sql = "SELECT count(*) FROM $table
  2775. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2776. //@todo seems that this always returns 0
  2777. $res = Database::query($sql);
  2778. $num = 0;
  2779. if (Database::num_rows($res)) {
  2780. $row = Database::fetch_array($res);
  2781. $num = $row[0];
  2782. }
  2783. return $num;
  2784. }
  2785. /**
  2786. * Return the objectives as an array for the given lp_iv_id.
  2787. * This method can be used as static.
  2788. *
  2789. * @param int $lpItemViewId Learnpath Item View ID
  2790. *
  2791. * @return array
  2792. *
  2793. * @todo Translate labels
  2794. */
  2795. public static function get_iv_objectives_array($lpItemViewId = 0)
  2796. {
  2797. $course_id = api_get_course_int_id();
  2798. $lpItemViewId = (int) $lpItemViewId;
  2799. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2800. $sql = "SELECT * FROM $table
  2801. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2802. ORDER BY order_id ASC";
  2803. $res = Database::query($sql);
  2804. $num = Database::num_rows($res);
  2805. $list = [];
  2806. if ($num > 0) {
  2807. $list[] = [
  2808. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2809. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2810. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2811. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2812. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2813. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2814. ];
  2815. while ($row = Database::fetch_array($res)) {
  2816. $list[] = [
  2817. 'order_id' => ($row['order_id'] + 1),
  2818. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2819. 'score_raw' => $row['score_raw'],
  2820. 'score_max' => $row['score_max'],
  2821. 'score_min' => $row['score_min'],
  2822. 'status' => $row['status'],
  2823. ];
  2824. }
  2825. }
  2826. return $list;
  2827. }
  2828. /**
  2829. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2830. * used by get_html_toc() to be ready to display.
  2831. *
  2832. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2833. */
  2834. public function get_toc()
  2835. {
  2836. if ($this->debug > 0) {
  2837. error_log('learnpath::get_toc()', 0);
  2838. }
  2839. $toc = [];
  2840. foreach ($this->ordered_items as $item_id) {
  2841. if ($this->debug > 2) {
  2842. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2843. }
  2844. // TODO: Change this link generation and use new function instead.
  2845. $toc[] = [
  2846. 'id' => $item_id,
  2847. 'title' => $this->items[$item_id]->get_title(),
  2848. 'status' => $this->items[$item_id]->get_status(),
  2849. 'level' => $this->items[$item_id]->get_level(),
  2850. 'type' => $this->items[$item_id]->get_type(),
  2851. 'description' => $this->items[$item_id]->get_description(),
  2852. 'path' => $this->items[$item_id]->get_path(),
  2853. 'parent' => $this->items[$item_id]->get_parent(),
  2854. ];
  2855. }
  2856. if ($this->debug > 2) {
  2857. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2858. }
  2859. return $toc;
  2860. }
  2861. /**
  2862. * Generate and return the table of contents for this learnpath. The JS
  2863. * table returned is used inside of scorm_api.php.
  2864. *
  2865. * @param string $varname
  2866. *
  2867. * @return string A JS array variable construction
  2868. */
  2869. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2870. {
  2871. if ($this->debug > 0) {
  2872. error_log('In learnpath::get_items_details_as_js()', 0);
  2873. }
  2874. $toc = $varname.' = new Array();';
  2875. foreach ($this->ordered_items as $item_id) {
  2876. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2877. }
  2878. if ($this->debug > 2) {
  2879. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2880. }
  2881. return $toc;
  2882. }
  2883. /**
  2884. * Gets the learning path type.
  2885. *
  2886. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2887. *
  2888. * @return mixed Type ID or name, depending on the parameter
  2889. */
  2890. public function get_type($get_name = false)
  2891. {
  2892. $res = false;
  2893. if ($this->debug > 0) {
  2894. error_log('In learnpath::get_type()', 0);
  2895. }
  2896. if (!empty($this->type) && (!$get_name)) {
  2897. $res = $this->type;
  2898. }
  2899. if ($this->debug > 2) {
  2900. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2901. }
  2902. return $res;
  2903. }
  2904. /**
  2905. * Gets the learning path type as static method.
  2906. *
  2907. * @param int $lp_id
  2908. *
  2909. * @return mixed Type ID or name, depending on the parameter
  2910. */
  2911. public static function get_type_static($lp_id = 0)
  2912. {
  2913. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2914. $lp_id = intval($lp_id);
  2915. $sql = "SELECT lp_type FROM $tbl_lp
  2916. WHERE iid = $lp_id";
  2917. $res = Database::query($sql);
  2918. if ($res === false) {
  2919. return null;
  2920. }
  2921. if (Database::num_rows($res) <= 0) {
  2922. return null;
  2923. }
  2924. $row = Database::fetch_array($res);
  2925. return $row['lp_type'];
  2926. }
  2927. /**
  2928. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2929. * This method can be used as abstract and is recursive.
  2930. *
  2931. * @param int $lp Learnpath ID
  2932. * @param int $parent Parent ID of the items to look for
  2933. * @param int $course_id
  2934. *
  2935. * @return array Ordered list of item IDs (empty array on error)
  2936. */
  2937. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2938. {
  2939. if (empty($course_id)) {
  2940. $course_id = api_get_course_int_id();
  2941. } else {
  2942. $course_id = (int) $course_id;
  2943. }
  2944. $list = [];
  2945. if (empty($lp)) {
  2946. return $list;
  2947. }
  2948. $lp = (int) $lp;
  2949. $parent = (int) $parent;
  2950. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2951. $sql = "SELECT iid FROM $tbl_lp_item
  2952. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2953. ORDER BY display_order";
  2954. $res = Database::query($sql);
  2955. while ($row = Database::fetch_array($res)) {
  2956. $sublist = self::get_flat_ordered_items_list(
  2957. $lp,
  2958. $row['iid'],
  2959. $course_id
  2960. );
  2961. $list[] = $row['iid'];
  2962. foreach ($sublist as $item) {
  2963. $list[] = $item;
  2964. }
  2965. }
  2966. return $list;
  2967. }
  2968. /**
  2969. * @return array
  2970. */
  2971. public static function getChapterTypes()
  2972. {
  2973. return [
  2974. 'dir',
  2975. ];
  2976. }
  2977. /**
  2978. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2979. *
  2980. * @param $tree
  2981. *
  2982. * @return array HTML TOC ready to display
  2983. */
  2984. public function getParentToc($tree)
  2985. {
  2986. if ($this->debug > 0) {
  2987. error_log('In learnpath::get_html_toc()', 0);
  2988. }
  2989. if (empty($tree)) {
  2990. $tree = $this->get_toc();
  2991. }
  2992. $dirTypes = self::getChapterTypes();
  2993. $myCurrentId = $this->get_current_item_id();
  2994. $listParent = [];
  2995. $listChildren = [];
  2996. $listNotParent = [];
  2997. $list = [];
  2998. foreach ($tree as $subtree) {
  2999. if (in_array($subtree['type'], $dirTypes)) {
  3000. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3001. $subtree['children'] = $listChildren;
  3002. if (!empty($subtree['children'])) {
  3003. foreach ($subtree['children'] as $subItem) {
  3004. if ($subItem['id'] == $this->current) {
  3005. $subtree['parent_current'] = 'in';
  3006. $subtree['current'] = 'on';
  3007. }
  3008. }
  3009. }
  3010. $listParent[] = $subtree;
  3011. }
  3012. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3013. $classStatus = [
  3014. 'not attempted' => 'scorm_not_attempted',
  3015. 'incomplete' => 'scorm_not_attempted',
  3016. 'failed' => 'scorm_failed',
  3017. 'completed' => 'scorm_completed',
  3018. 'passed' => 'scorm_completed',
  3019. 'succeeded' => 'scorm_completed',
  3020. 'browsed' => 'scorm_completed',
  3021. ];
  3022. if (isset($classStatus[$subtree['status']])) {
  3023. $cssStatus = $classStatus[$subtree['status']];
  3024. }
  3025. $title = Security::remove_XSS($subtree['title']);
  3026. unset($subtree['title']);
  3027. if (empty($title)) {
  3028. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3029. }
  3030. $classStyle = null;
  3031. if ($subtree['id'] == $this->current) {
  3032. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3033. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3034. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3035. }
  3036. $subtree['title'] = $title;
  3037. $subtree['class'] = $classStyle.' '.$cssStatus;
  3038. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3039. $subtree['current_id'] = $myCurrentId;
  3040. $listNotParent[] = $subtree;
  3041. }
  3042. }
  3043. $list['are_parents'] = $listParent;
  3044. $list['not_parents'] = $listNotParent;
  3045. return $list;
  3046. }
  3047. /**
  3048. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3049. *
  3050. * @param array $tree
  3051. * @param int $id
  3052. * @param bool $parent
  3053. *
  3054. * @return array HTML TOC ready to display
  3055. */
  3056. public function getChildrenToc($tree, $id, $parent = true)
  3057. {
  3058. if ($this->debug > 0) {
  3059. error_log('In learnpath::get_html_toc()', 0);
  3060. }
  3061. if (empty($tree)) {
  3062. $tree = $this->get_toc();
  3063. }
  3064. $dirTypes = self::getChapterTypes();
  3065. $mycurrentitemid = $this->get_current_item_id();
  3066. $list = [];
  3067. $classStatus = [
  3068. 'not attempted' => 'scorm_not_attempted',
  3069. 'incomplete' => 'scorm_not_attempted',
  3070. 'failed' => 'scorm_failed',
  3071. 'completed' => 'scorm_completed',
  3072. 'passed' => 'scorm_completed',
  3073. 'succeeded' => 'scorm_completed',
  3074. 'browsed' => 'scorm_completed',
  3075. ];
  3076. foreach ($tree as $subtree) {
  3077. $subtree['tree'] = null;
  3078. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3079. if ($subtree['id'] == $this->current) {
  3080. $subtree['current'] = 'active';
  3081. } else {
  3082. $subtree['current'] = null;
  3083. }
  3084. if (isset($classStatus[$subtree['status']])) {
  3085. $cssStatus = $classStatus[$subtree['status']];
  3086. }
  3087. $title = Security::remove_XSS($subtree['title']);
  3088. unset($subtree['title']);
  3089. if (empty($title)) {
  3090. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3091. }
  3092. $classStyle = null;
  3093. if ($subtree['id'] == $this->current) {
  3094. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3095. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3096. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3097. }
  3098. if (in_array($subtree['type'], $dirTypes)) {
  3099. $subtree['title'] = stripslashes($title);
  3100. } else {
  3101. $subtree['title'] = $title;
  3102. $subtree['class'] = $classStyle.' '.$cssStatus;
  3103. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3104. $subtree['current_id'] = $mycurrentitemid;
  3105. }
  3106. $list[] = $subtree;
  3107. }
  3108. }
  3109. return $list;
  3110. }
  3111. /**
  3112. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3113. *
  3114. * @param array $toc_list
  3115. *
  3116. * @return array HTML TOC ready to display
  3117. */
  3118. public function getListArrayToc($toc_list = [])
  3119. {
  3120. if ($this->debug > 0) {
  3121. error_log('In learnpath::get_html_toc()', 0);
  3122. }
  3123. if (empty($toc_list)) {
  3124. $toc_list = $this->get_toc();
  3125. }
  3126. // Temporary variables.
  3127. $mycurrentitemid = $this->get_current_item_id();
  3128. $list = [];
  3129. $arrayList = [];
  3130. $classStatus = [
  3131. 'not attempted' => 'scorm_not_attempted',
  3132. 'incomplete' => 'scorm_not_attempted',
  3133. 'failed' => 'scorm_failed',
  3134. 'completed' => 'scorm_completed',
  3135. 'passed' => 'scorm_completed',
  3136. 'succeeded' => 'scorm_completed',
  3137. 'browsed' => 'scorm_completed',
  3138. ];
  3139. foreach ($toc_list as $item) {
  3140. $list['id'] = $item['id'];
  3141. $list['status'] = $item['status'];
  3142. $cssStatus = null;
  3143. if (isset($classStatus[$item['status']])) {
  3144. $cssStatus = $classStatus[$item['status']];
  3145. }
  3146. $classStyle = ' ';
  3147. $dirTypes = self::getChapterTypes();
  3148. if (in_array($item['type'], $dirTypes)) {
  3149. $classStyle = 'scorm_item_section ';
  3150. }
  3151. if ($item['id'] == $this->current) {
  3152. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3153. } elseif (!in_array($item['type'], $dirTypes)) {
  3154. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3155. }
  3156. $title = $item['title'];
  3157. if (empty($title)) {
  3158. $title = self::rl_get_resource_name(
  3159. api_get_course_id(),
  3160. $this->get_id(),
  3161. $item['id']
  3162. );
  3163. }
  3164. $title = Security::remove_XSS($item['title']);
  3165. if (empty($item['description'])) {
  3166. $list['description'] = $title;
  3167. } else {
  3168. $list['description'] = $item['description'];
  3169. }
  3170. $list['class'] = $classStyle.' '.$cssStatus;
  3171. $list['level'] = $item['level'];
  3172. $list['type'] = $item['type'];
  3173. if (in_array($item['type'], $dirTypes)) {
  3174. $list['css_level'] = 'level_'.$item['level'];
  3175. } else {
  3176. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3177. }
  3178. if (in_array($item['type'], $dirTypes)) {
  3179. $list['title'] = stripslashes($title);
  3180. } else {
  3181. $list['title'] = stripslashes($title);
  3182. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3183. $list['current_id'] = $mycurrentitemid;
  3184. }
  3185. $arrayList[] = $list;
  3186. }
  3187. return $arrayList;
  3188. }
  3189. /**
  3190. * Returns an HTML-formatted string ready to display with teacher buttons
  3191. * in LP view menu.
  3192. *
  3193. * @return string HTML TOC ready to display
  3194. */
  3195. public function get_teacher_toc_buttons()
  3196. {
  3197. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3198. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3199. $html = '';
  3200. if ($isAllow && $hideIcons == false) {
  3201. if ($this->get_lp_session_id() == api_get_session_id()) {
  3202. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3203. $html .= '<div class="btn-group">';
  3204. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=build&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3205. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3206. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=add_item&type=step&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3207. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3208. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3209. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3210. $html .= '</div>';
  3211. $html .= '</div>';
  3212. }
  3213. }
  3214. return $html;
  3215. }
  3216. /**
  3217. * Gets the learnpath maker name - generally the editor's name.
  3218. *
  3219. * @return string Learnpath maker name
  3220. */
  3221. public function get_maker()
  3222. {
  3223. if ($this->debug > 0) {
  3224. error_log('In learnpath::get_maker()', 0);
  3225. }
  3226. if (!empty($this->maker)) {
  3227. return $this->maker;
  3228. } else {
  3229. return '';
  3230. }
  3231. }
  3232. /**
  3233. * Gets the learnpath name/title.
  3234. *
  3235. * @return string Learnpath name/title
  3236. */
  3237. public function get_name()
  3238. {
  3239. if ($this->debug > 0) {
  3240. error_log('In learnpath::get_name()', 0);
  3241. }
  3242. if (!empty($this->name)) {
  3243. return $this->name;
  3244. } else {
  3245. return 'N/A';
  3246. }
  3247. }
  3248. /**
  3249. * Gets a link to the resource from the present location, depending on item ID.
  3250. *
  3251. * @param string $type Type of link expected
  3252. * @param int $item_id Learnpath item ID
  3253. * @param bool $provided_toc
  3254. *
  3255. * @return string $provided_toc Link to the lp_item resource
  3256. */
  3257. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3258. {
  3259. $course_id = $this->get_course_int_id();
  3260. if ($this->debug > 0) {
  3261. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3262. }
  3263. if (empty($item_id)) {
  3264. if ($this->debug > 2) {
  3265. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3266. error_log('using current: '.$this->get_current_item_id(), 0);
  3267. }
  3268. $item_id = $this->get_current_item_id();
  3269. if (empty($item_id)) {
  3270. if ($this->debug > 2) {
  3271. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3272. }
  3273. //still empty, this means there was no item_id given and we are not in an object context or
  3274. //the object property is empty, return empty link
  3275. $this->first();
  3276. return '';
  3277. }
  3278. }
  3279. $file = '';
  3280. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3281. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3282. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3283. $item_id = (int) $item_id;
  3284. $sql = "SELECT
  3285. l.lp_type as ltype,
  3286. l.path as lpath,
  3287. li.item_type as litype,
  3288. li.path as lipath,
  3289. li.parameters as liparams
  3290. FROM $lp_table l
  3291. INNER JOIN $lp_item_table li
  3292. ON (li.lp_id = l.iid)
  3293. WHERE
  3294. li.iid = $item_id
  3295. ";
  3296. if ($this->debug > 2) {
  3297. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3298. }
  3299. $res = Database::query($sql);
  3300. if (Database::num_rows($res) > 0) {
  3301. $row = Database::fetch_array($res);
  3302. $lp_type = $row['ltype'];
  3303. $lp_path = $row['lpath'];
  3304. $lp_item_type = $row['litype'];
  3305. $lp_item_path = $row['lipath'];
  3306. $lp_item_params = $row['liparams'];
  3307. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3308. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3309. }
  3310. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3311. if ($type === 'http') {
  3312. //web path
  3313. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3314. } else {
  3315. $course_path = $sys_course_path; //system path
  3316. }
  3317. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3318. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3319. if (in_array(
  3320. $lp_item_type,
  3321. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3322. )
  3323. ) {
  3324. $lp_type = 1;
  3325. }
  3326. if ($this->debug > 2) {
  3327. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3328. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3329. }
  3330. // Now go through the specific cases to get the end of the path
  3331. // @todo Use constants instead of int values.
  3332. switch ($lp_type) {
  3333. case 1:
  3334. $file = self::rl_get_resource_link_for_learnpath(
  3335. $course_id,
  3336. $this->get_id(),
  3337. $item_id,
  3338. $this->get_view_id()
  3339. );
  3340. if ($this->debug > 0) {
  3341. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3342. }
  3343. switch ($lp_item_type) {
  3344. case 'dir':
  3345. $file = 'lp_content.php?type=dir';
  3346. break;
  3347. case 'link':
  3348. if (Link::is_youtube_link($file)) {
  3349. $src = Link::get_youtube_video_id($file);
  3350. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3351. } elseif (Link::isVimeoLink($file)) {
  3352. $src = Link::getVimeoLinkId($file);
  3353. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3354. } else {
  3355. // If the current site is HTTPS and the link is
  3356. // HTTP, browsers will refuse opening the link
  3357. $urlId = api_get_current_access_url_id();
  3358. $url = api_get_access_url($urlId, false);
  3359. $protocol = substr($url['url'], 0, 5);
  3360. if ($protocol === 'https') {
  3361. $linkProtocol = substr($file, 0, 5);
  3362. if ($linkProtocol === 'http:') {
  3363. //this is the special intervention case
  3364. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3365. }
  3366. }
  3367. }
  3368. break;
  3369. case 'quiz':
  3370. // Check how much attempts of a exercise exits in lp
  3371. $lp_item_id = $this->get_current_item_id();
  3372. $lp_view_id = $this->get_view_id();
  3373. $prevent_reinit = null;
  3374. if (isset($this->items[$this->current])) {
  3375. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3376. }
  3377. if (empty($provided_toc)) {
  3378. if ($this->debug > 0) {
  3379. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3380. }
  3381. $list = $this->get_toc();
  3382. } else {
  3383. if ($this->debug > 0) {
  3384. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3385. }
  3386. $list = $provided_toc;
  3387. }
  3388. $type_quiz = false;
  3389. foreach ($list as $toc) {
  3390. if ($toc['id'] == $lp_item_id && ($toc['type'] == 'quiz')) {
  3391. $type_quiz = true;
  3392. }
  3393. }
  3394. if ($type_quiz) {
  3395. $lp_item_id = intval($lp_item_id);
  3396. $lp_view_id = intval($lp_view_id);
  3397. $sql = "SELECT count(*) FROM $lp_item_view_table
  3398. WHERE
  3399. c_id = $course_id AND
  3400. lp_item_id='".$lp_item_id."' AND
  3401. lp_view_id ='".$lp_view_id."' AND
  3402. status='completed'";
  3403. $result = Database::query($sql);
  3404. $row_count = Database:: fetch_row($result);
  3405. $count_item_view = (int) $row_count[0];
  3406. $not_multiple_attempt = 0;
  3407. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3408. $not_multiple_attempt = 1;
  3409. }
  3410. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3411. }
  3412. break;
  3413. }
  3414. $tmp_array = explode('/', $file);
  3415. $document_name = $tmp_array[count($tmp_array) - 1];
  3416. if (strpos($document_name, '_DELETED_')) {
  3417. $file = 'blank.php?error=document_deleted';
  3418. }
  3419. break;
  3420. case 2:
  3421. if ($this->debug > 2) {
  3422. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3423. }
  3424. if ($lp_item_type != 'dir') {
  3425. // Quite complex here:
  3426. // We want to make sure 'http://' (and similar) links can
  3427. // be loaded as is (withouth the Chamilo path in front) but
  3428. // some contents use this form: resource.htm?resource=http://blablabla
  3429. // which means we have to find a protocol at the path's start, otherwise
  3430. // it should not be considered as an external URL.
  3431. // if ($this->prerequisites_match($item_id)) {
  3432. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3433. if ($this->debug > 2) {
  3434. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3435. }
  3436. // Distant url, return as is.
  3437. $file = $lp_item_path;
  3438. } else {
  3439. if ($this->debug > 2) {
  3440. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3441. }
  3442. // Prevent getting untranslatable urls.
  3443. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3444. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3445. // Prepare the path.
  3446. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3447. // TODO: Fix this for urls with protocol header.
  3448. $file = str_replace('//', '/', $file);
  3449. $file = str_replace(':/', '://', $file);
  3450. if (substr($lp_path, -1) == '/') {
  3451. $lp_path = substr($lp_path, 0, -1);
  3452. }
  3453. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3454. // if file not found.
  3455. $decoded = html_entity_decode($lp_item_path);
  3456. list($decoded) = explode('?', $decoded);
  3457. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3458. $file = self::rl_get_resource_link_for_learnpath(
  3459. $course_id,
  3460. $this->get_id(),
  3461. $item_id,
  3462. $this->get_view_id()
  3463. );
  3464. if (empty($file)) {
  3465. $file = 'blank.php?error=document_not_found';
  3466. } else {
  3467. $tmp_array = explode('/', $file);
  3468. $document_name = $tmp_array[count($tmp_array) - 1];
  3469. if (strpos($document_name, '_DELETED_')) {
  3470. $file = 'blank.php?error=document_deleted';
  3471. } else {
  3472. $file = 'blank.php?error=document_not_found';
  3473. }
  3474. }
  3475. } else {
  3476. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3477. }
  3478. }
  3479. }
  3480. // We want to use parameters if they were defined in the imsmanifest
  3481. if (strpos($file, 'blank.php') === false) {
  3482. $lp_item_params = ltrim($lp_item_params, '?');
  3483. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3484. }
  3485. } else {
  3486. $file = 'lp_content.php?type=dir';
  3487. }
  3488. break;
  3489. case 3:
  3490. if ($this->debug > 2) {
  3491. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3492. }
  3493. // Formatting AICC HACP append URL.
  3494. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3495. if (!empty($lp_item_params)) {
  3496. $aicc_append .= $lp_item_params.'&';
  3497. }
  3498. if ($lp_item_type != 'dir') {
  3499. // Quite complex here:
  3500. // We want to make sure 'http://' (and similar) links can
  3501. // be loaded as is (withouth the Chamilo path in front) but
  3502. // some contents use this form: resource.htm?resource=http://blablabla
  3503. // which means we have to find a protocol at the path's start, otherwise
  3504. // it should not be considered as an external URL.
  3505. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3506. if ($this->debug > 2) {
  3507. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3508. }
  3509. // Distant url, return as is.
  3510. $file = $lp_item_path;
  3511. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3512. /*
  3513. if (stristr($file,'<servername>') !== false) {
  3514. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3515. }
  3516. */
  3517. if (stripos($file, '<servername>') !== false) {
  3518. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3519. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3520. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3521. }
  3522. $file .= $aicc_append;
  3523. } else {
  3524. if ($this->debug > 2) {
  3525. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3526. }
  3527. // Prevent getting untranslatable urls.
  3528. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3529. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3530. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3531. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3532. // TODO: Fix this for urls with protocol header.
  3533. $file = str_replace('//', '/', $file);
  3534. $file = str_replace(':/', '://', $file);
  3535. $file .= $aicc_append;
  3536. }
  3537. } else {
  3538. $file = 'lp_content.php?type=dir';
  3539. }
  3540. break;
  3541. case 4:
  3542. break;
  3543. default:
  3544. break;
  3545. }
  3546. // Replace &amp; by & because &amp; will break URL with params
  3547. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3548. }
  3549. if ($this->debug > 2) {
  3550. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3551. }
  3552. return $file;
  3553. }
  3554. /**
  3555. * Gets the latest usable view or generate a new one.
  3556. *
  3557. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3558. *
  3559. * @return int DB lp_view id
  3560. */
  3561. public function get_view($attempt_num = 0)
  3562. {
  3563. if ($this->debug > 0) {
  3564. error_log('In learnpath::get_view()', 0);
  3565. }
  3566. $search = '';
  3567. // Use $attempt_num to enable multi-views management (disabled so far).
  3568. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3569. $search = 'AND view_count = '.$attempt_num;
  3570. }
  3571. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3572. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3573. $course_id = api_get_course_int_id();
  3574. $sessionId = api_get_session_id();
  3575. $sql = "SELECT iid, view_count FROM $lp_view_table
  3576. WHERE
  3577. c_id = $course_id AND
  3578. lp_id = ".$this->get_id()." AND
  3579. user_id = ".$this->get_user_id()." AND
  3580. session_id = $sessionId
  3581. $search
  3582. ORDER BY view_count DESC";
  3583. $res = Database::query($sql);
  3584. if (Database::num_rows($res) > 0) {
  3585. $row = Database::fetch_array($res);
  3586. $this->lp_view_id = $row['iid'];
  3587. } elseif (!api_is_invitee()) {
  3588. // There is no database record, create one.
  3589. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3590. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3591. Database::query($sql);
  3592. $id = Database::insert_id();
  3593. $this->lp_view_id = $id;
  3594. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3595. Database::query($sql);
  3596. }
  3597. return $this->lp_view_id;
  3598. }
  3599. /**
  3600. * Gets the current view id.
  3601. *
  3602. * @return int View ID (from lp_view)
  3603. */
  3604. public function get_view_id()
  3605. {
  3606. if ($this->debug > 0) {
  3607. error_log('In learnpath::get_view_id()', 0);
  3608. }
  3609. if (!empty($this->lp_view_id)) {
  3610. return $this->lp_view_id;
  3611. } else {
  3612. return 0;
  3613. }
  3614. }
  3615. /**
  3616. * Gets the update queue.
  3617. *
  3618. * @return array Array containing IDs of items to be updated by JavaScript
  3619. */
  3620. public function get_update_queue()
  3621. {
  3622. if ($this->debug > 0) {
  3623. error_log('In learnpath::get_update_queue()', 0);
  3624. }
  3625. return $this->update_queue;
  3626. }
  3627. /**
  3628. * Gets the user ID.
  3629. *
  3630. * @return int User ID
  3631. */
  3632. public function get_user_id()
  3633. {
  3634. if ($this->debug > 0) {
  3635. error_log('In learnpath::get_user_id()', 0);
  3636. }
  3637. if (!empty($this->user_id)) {
  3638. return $this->user_id;
  3639. } else {
  3640. return false;
  3641. }
  3642. }
  3643. /**
  3644. * Checks if any of the items has an audio element attached.
  3645. *
  3646. * @return bool True or false
  3647. */
  3648. public function has_audio()
  3649. {
  3650. if ($this->debug > 1) {
  3651. error_log('In learnpath::has_audio()', 0);
  3652. }
  3653. $has = false;
  3654. foreach ($this->items as $i => $item) {
  3655. if (!empty($this->items[$i]->audio)) {
  3656. $has = true;
  3657. break;
  3658. }
  3659. }
  3660. return $has;
  3661. }
  3662. /**
  3663. * Moves an item up and down at its level.
  3664. *
  3665. * @param int $id Item to move up and down
  3666. * @param string $direction Direction 'up' or 'down'
  3667. *
  3668. * @return bool|int
  3669. */
  3670. public function move_item($id, $direction)
  3671. {
  3672. $course_id = api_get_course_int_id();
  3673. if ($this->debug > 0) {
  3674. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3675. }
  3676. if (empty($id) || empty($direction)) {
  3677. return false;
  3678. }
  3679. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3680. $sql_sel = "SELECT *
  3681. FROM $tbl_lp_item
  3682. WHERE
  3683. iid = $id
  3684. ";
  3685. $res_sel = Database::query($sql_sel);
  3686. // Check if elem exists.
  3687. if (Database::num_rows($res_sel) < 1) {
  3688. return false;
  3689. }
  3690. // Gather data.
  3691. $row = Database::fetch_array($res_sel);
  3692. $previous = $row['previous_item_id'];
  3693. $next = $row['next_item_id'];
  3694. $display = $row['display_order'];
  3695. $parent = $row['parent_item_id'];
  3696. $lp = $row['lp_id'];
  3697. // Update the item (switch with previous/next one).
  3698. switch ($direction) {
  3699. case 'up':
  3700. if ($this->debug > 2) {
  3701. error_log('Movement up detected', 0);
  3702. }
  3703. if ($display > 1) {
  3704. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3705. WHERE iid = $previous";
  3706. if ($this->debug > 2) {
  3707. error_log('Selecting previous: '.$sql_sel2, 0);
  3708. }
  3709. $res_sel2 = Database::query($sql_sel2);
  3710. if (Database::num_rows($res_sel2) < 1) {
  3711. $previous_previous = 0;
  3712. }
  3713. // Gather data.
  3714. $row2 = Database::fetch_array($res_sel2);
  3715. $previous_previous = $row2['previous_item_id'];
  3716. // Update previous_previous item (switch "next" with current).
  3717. if ($previous_previous != 0) {
  3718. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3719. next_item_id = $id
  3720. WHERE iid = $previous_previous";
  3721. if ($this->debug > 2) {
  3722. error_log($sql_upd2, 0);
  3723. }
  3724. Database::query($sql_upd2);
  3725. }
  3726. // Update previous item (switch with current).
  3727. if ($previous != 0) {
  3728. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3729. next_item_id = $next,
  3730. previous_item_id = $id,
  3731. display_order = display_order +1
  3732. WHERE iid = $previous";
  3733. if ($this->debug > 2) {
  3734. error_log($sql_upd2, 0);
  3735. }
  3736. Database::query($sql_upd2);
  3737. }
  3738. // Update current item (switch with previous).
  3739. if ($id != 0) {
  3740. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3741. next_item_id = $previous,
  3742. previous_item_id = $previous_previous,
  3743. display_order = display_order-1
  3744. WHERE c_id = ".$course_id." AND id = $id";
  3745. if ($this->debug > 2) {
  3746. error_log($sql_upd2, 0);
  3747. }
  3748. Database::query($sql_upd2);
  3749. }
  3750. // Update next item (new previous item).
  3751. if (!empty($next)) {
  3752. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3753. WHERE iid = $next";
  3754. if ($this->debug > 2) {
  3755. error_log($sql_upd2, 0);
  3756. }
  3757. Database::query($sql_upd2);
  3758. }
  3759. $display = $display - 1;
  3760. }
  3761. break;
  3762. case 'down':
  3763. if ($this->debug > 2) {
  3764. error_log('Movement down detected', 0);
  3765. }
  3766. if ($next != 0) {
  3767. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3768. WHERE iid = $next";
  3769. if ($this->debug > 2) {
  3770. error_log('Selecting next: '.$sql_sel2, 0);
  3771. }
  3772. $res_sel2 = Database::query($sql_sel2);
  3773. if (Database::num_rows($res_sel2) < 1) {
  3774. $next_next = 0;
  3775. }
  3776. // Gather data.
  3777. $row2 = Database::fetch_array($res_sel2);
  3778. $next_next = $row2['next_item_id'];
  3779. // Update previous item (switch with current).
  3780. if ($previous != 0) {
  3781. $sql_upd2 = "UPDATE $tbl_lp_item
  3782. SET next_item_id = $next
  3783. WHERE iid = $previous";
  3784. Database::query($sql_upd2);
  3785. }
  3786. // Update current item (switch with previous).
  3787. if ($id != 0) {
  3788. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3789. previous_item_id = $next,
  3790. next_item_id = $next_next,
  3791. display_order = display_order + 1
  3792. WHERE iid = $id";
  3793. Database::query($sql_upd2);
  3794. }
  3795. // Update next item (new previous item).
  3796. if ($next != 0) {
  3797. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3798. previous_item_id = $previous,
  3799. next_item_id = $id,
  3800. display_order = display_order-1
  3801. WHERE iid = $next";
  3802. Database::query($sql_upd2);
  3803. }
  3804. // Update next_next item (switch "previous" with current).
  3805. if ($next_next != 0) {
  3806. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3807. previous_item_id = $id
  3808. WHERE iid = $next_next";
  3809. Database::query($sql_upd2);
  3810. }
  3811. $display = $display + 1;
  3812. }
  3813. break;
  3814. default:
  3815. return false;
  3816. }
  3817. return $display;
  3818. }
  3819. /**
  3820. * Move a LP up (display_order).
  3821. *
  3822. * @param int $lp_id Learnpath ID
  3823. * @param int $categoryId Category ID
  3824. *
  3825. * @return bool
  3826. */
  3827. public static function move_up($lp_id, $categoryId = 0)
  3828. {
  3829. $courseId = api_get_course_int_id();
  3830. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3831. $categoryCondition = '';
  3832. if (!empty($categoryId)) {
  3833. $categoryId = (int) $categoryId;
  3834. $categoryCondition = " AND category_id = $categoryId";
  3835. }
  3836. $sql = "SELECT * FROM $lp_table
  3837. WHERE c_id = $courseId
  3838. $categoryCondition
  3839. ORDER BY display_order";
  3840. $res = Database::query($sql);
  3841. if ($res === false) {
  3842. return false;
  3843. }
  3844. $lps = [];
  3845. $lp_order = [];
  3846. $num = Database::num_rows($res);
  3847. // First check the order is correct, globally (might be wrong because
  3848. // of versions < 1.8.4)
  3849. if ($num > 0) {
  3850. $i = 1;
  3851. while ($row = Database::fetch_array($res)) {
  3852. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3853. $sql = "UPDATE $lp_table SET display_order = $i
  3854. WHERE iid = ".$row['iid'];
  3855. Database::query($sql);
  3856. }
  3857. $row['display_order'] = $i;
  3858. $lps[$row['iid']] = $row;
  3859. $lp_order[$i] = $row['iid'];
  3860. $i++;
  3861. }
  3862. }
  3863. if ($num > 1) { // If there's only one element, no need to sort.
  3864. $order = $lps[$lp_id]['display_order'];
  3865. if ($order > 1) { // If it's the first element, no need to move up.
  3866. $sql = "UPDATE $lp_table SET display_order = $order
  3867. WHERE iid = ".$lp_order[$order - 1];
  3868. Database::query($sql);
  3869. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3870. WHERE iid = $lp_id";
  3871. Database::query($sql);
  3872. }
  3873. }
  3874. return true;
  3875. }
  3876. /**
  3877. * Move a learnpath down (display_order).
  3878. *
  3879. * @param int $lp_id Learnpath ID
  3880. * @param int $categoryId Category ID
  3881. *
  3882. * @return bool
  3883. */
  3884. public static function move_down($lp_id, $categoryId = 0)
  3885. {
  3886. $courseId = api_get_course_int_id();
  3887. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3888. $categoryCondition = '';
  3889. if (!empty($categoryId)) {
  3890. $categoryId = (int) $categoryId;
  3891. $categoryCondition = " AND category_id = $categoryId";
  3892. }
  3893. $sql = "SELECT * FROM $lp_table
  3894. WHERE c_id = $courseId
  3895. $categoryCondition
  3896. ORDER BY display_order";
  3897. $res = Database::query($sql);
  3898. if ($res === false) {
  3899. return false;
  3900. }
  3901. $lps = [];
  3902. $lp_order = [];
  3903. $num = Database::num_rows($res);
  3904. $max = 0;
  3905. // First check the order is correct, globally (might be wrong because
  3906. // of versions < 1.8.4).
  3907. if ($num > 0) {
  3908. $i = 1;
  3909. while ($row = Database::fetch_array($res)) {
  3910. $max = $i;
  3911. if ($row['display_order'] != $i) {
  3912. // If we find a gap in the order, we need to fix it.
  3913. $sql = "UPDATE $lp_table SET display_order = $i
  3914. WHERE iid = ".$row['iid'];
  3915. Database::query($sql);
  3916. }
  3917. $row['display_order'] = $i;
  3918. $lps[$row['iid']] = $row;
  3919. $lp_order[$i] = $row['iid'];
  3920. $i++;
  3921. }
  3922. }
  3923. if ($num > 1) { // If there's only one element, no need to sort.
  3924. $order = $lps[$lp_id]['display_order'];
  3925. if ($order < $max) { // If it's the first element, no need to move up.
  3926. $sql = "UPDATE $lp_table SET display_order = $order
  3927. WHERE iid = ".$lp_order[$order + 1];
  3928. Database::query($sql);
  3929. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3930. WHERE iid = $lp_id";
  3931. Database::query($sql);
  3932. }
  3933. }
  3934. return true;
  3935. }
  3936. /**
  3937. * Updates learnpath attributes to point to the next element
  3938. * The last part is similar to set_current_item but processing the other way around.
  3939. */
  3940. public function next()
  3941. {
  3942. if ($this->debug > 0) {
  3943. error_log('In learnpath::next()', 0);
  3944. }
  3945. $this->last = $this->get_current_item_id();
  3946. $this->items[$this->last]->save(
  3947. false,
  3948. $this->prerequisites_match($this->last)
  3949. );
  3950. $this->autocomplete_parents($this->last);
  3951. $new_index = $this->get_next_index();
  3952. if ($this->debug > 2) {
  3953. error_log('New index: '.$new_index, 0);
  3954. }
  3955. $this->index = $new_index;
  3956. if ($this->debug > 2) {
  3957. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3958. }
  3959. $this->current = $this->ordered_items[$new_index];
  3960. if ($this->debug > 2) {
  3961. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3962. }
  3963. }
  3964. /**
  3965. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3966. * class, this might be redefined to allow several behaviours depending on the document type.
  3967. *
  3968. * @param int $id Resource ID
  3969. */
  3970. public function open($id)
  3971. {
  3972. if ($this->debug > 0) {
  3973. error_log('In learnpath::open()', 0);
  3974. }
  3975. // TODO:
  3976. // set the current resource attribute to this resource
  3977. // switch on element type (redefine in child class?)
  3978. // set status for this item to "opened"
  3979. // start timer
  3980. // initialise score
  3981. $this->index = 0; //or = the last item seen (see $this->last)
  3982. }
  3983. /**
  3984. * Check that all prerequisites are fulfilled. Returns true and an
  3985. * empty string on success, returns false
  3986. * and the prerequisite string on error.
  3987. * This function is based on the rules for aicc_script language as
  3988. * described in the SCORM 1.2 CAM documentation page 108.
  3989. *
  3990. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3991. *
  3992. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  3993. * string otherwise
  3994. */
  3995. public function prerequisites_match($itemId = null)
  3996. {
  3997. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3998. if ($allow) {
  3999. if (api_is_allowed_to_edit() ||
  4000. api_is_platform_admin(true) ||
  4001. api_is_drh() ||
  4002. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4003. ) {
  4004. return true;
  4005. }
  4006. }
  4007. $debug = $this->debug;
  4008. if ($debug > 0) {
  4009. error_log('In learnpath::prerequisites_match()', 0);
  4010. }
  4011. if (empty($itemId)) {
  4012. $itemId = $this->current;
  4013. }
  4014. $currentItem = $this->getItem($itemId);
  4015. if ($currentItem) {
  4016. if ($this->type == 2) {
  4017. // Getting prereq from scorm
  4018. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4019. } else {
  4020. $prereq_string = $currentItem->get_prereq_string();
  4021. }
  4022. if (empty($prereq_string)) {
  4023. if ($debug > 0) {
  4024. error_log('Found prereq_string is empty return true');
  4025. }
  4026. return true;
  4027. }
  4028. // Clean spaces.
  4029. $prereq_string = str_replace(' ', '', $prereq_string);
  4030. if ($debug > 0) {
  4031. error_log('Found prereq_string: '.$prereq_string, 0);
  4032. }
  4033. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4034. $result = $currentItem->parse_prereq(
  4035. $prereq_string,
  4036. $this->items,
  4037. $this->refs_list,
  4038. $this->get_user_id()
  4039. );
  4040. if ($result === false) {
  4041. $this->set_error_msg($currentItem->prereq_alert);
  4042. }
  4043. } else {
  4044. $result = true;
  4045. if ($debug > 1) {
  4046. error_log('$this->items['.$itemId.'] was not an object', 0);
  4047. }
  4048. }
  4049. if ($debug > 1) {
  4050. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4051. }
  4052. return $result;
  4053. }
  4054. /**
  4055. * Updates learnpath attributes to point to the previous element
  4056. * The last part is similar to set_current_item but processing the other way around.
  4057. */
  4058. public function previous()
  4059. {
  4060. if ($this->debug > 0) {
  4061. error_log('In learnpath::previous()', 0);
  4062. }
  4063. $this->last = $this->get_current_item_id();
  4064. $this->items[$this->last]->save(
  4065. false,
  4066. $this->prerequisites_match($this->last)
  4067. );
  4068. $this->autocomplete_parents($this->last);
  4069. $new_index = $this->get_previous_index();
  4070. $this->index = $new_index;
  4071. $this->current = $this->ordered_items[$new_index];
  4072. }
  4073. /**
  4074. * Publishes a learnpath. This basically means show or hide the learnpath
  4075. * to normal users.
  4076. * Can be used as abstract.
  4077. *
  4078. * @param int $lp_id Learnpath ID
  4079. * @param int $set_visibility New visibility
  4080. *
  4081. * @return bool
  4082. */
  4083. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4084. {
  4085. $action = 'visible';
  4086. if ($set_visibility != 1) {
  4087. $action = 'invisible';
  4088. self::toggle_publish($lp_id, 'i');
  4089. }
  4090. return api_item_property_update(
  4091. api_get_course_info(),
  4092. TOOL_LEARNPATH,
  4093. $lp_id,
  4094. $action,
  4095. api_get_user_id()
  4096. );
  4097. }
  4098. /**
  4099. * Publishes a learnpath category.
  4100. * This basically means show or hide the learnpath category to normal users.
  4101. *
  4102. * @param int $id
  4103. * @param int $visibility
  4104. *
  4105. * @throws \Doctrine\ORM\NonUniqueResultException
  4106. * @throws \Doctrine\ORM\ORMException
  4107. * @throws \Doctrine\ORM\OptimisticLockException
  4108. * @throws \Doctrine\ORM\TransactionRequiredException
  4109. *
  4110. * @return bool
  4111. */
  4112. public static function toggleCategoryVisibility($id, $visibility = 1)
  4113. {
  4114. $action = 'visible';
  4115. if ($visibility != 1) {
  4116. $action = 'invisible';
  4117. $list = new LearnpathList(
  4118. api_get_user_id(),
  4119. null,
  4120. null,
  4121. null,
  4122. false,
  4123. $id
  4124. );
  4125. $lpList = $list->get_flat_list();
  4126. foreach ($lpList as $lp) {
  4127. self::toggle_visibility($lp['iid'], 0);
  4128. }
  4129. self::toggleCategoryPublish($id, 0);
  4130. }
  4131. return api_item_property_update(
  4132. api_get_course_info(),
  4133. TOOL_LEARNPATH_CATEGORY,
  4134. $id,
  4135. $action,
  4136. api_get_user_id()
  4137. );
  4138. }
  4139. /**
  4140. * Publishes a learnpath. This basically means show or hide the learnpath
  4141. * on the course homepage
  4142. * Can be used as abstract.
  4143. *
  4144. * @param int $lp_id Learnpath id
  4145. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4146. *
  4147. * @return bool
  4148. */
  4149. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4150. {
  4151. $course_id = api_get_course_int_id();
  4152. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4153. $lp_id = (int) $lp_id;
  4154. $sql = "SELECT * FROM $tbl_lp
  4155. WHERE iid = $lp_id";
  4156. $result = Database::query($sql);
  4157. if (Database::num_rows($result)) {
  4158. $row = Database::fetch_array($result);
  4159. $name = Database::escape_string($row['name']);
  4160. if ($set_visibility == 'i') {
  4161. $v = 0;
  4162. }
  4163. if ($set_visibility == 'v') {
  4164. $v = 1;
  4165. }
  4166. $session_id = api_get_session_id();
  4167. $session_condition = api_get_session_condition($session_id);
  4168. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4169. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4170. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4171. $sql = "SELECT * FROM $tbl_tool
  4172. WHERE
  4173. c_id = $course_id AND
  4174. (link = '$link' OR link = '$oldLink') AND
  4175. image = 'scormbuilder.gif' AND
  4176. (
  4177. link LIKE '$link%' OR
  4178. link LIKE '$oldLink%'
  4179. )
  4180. $session_condition
  4181. ";
  4182. $result = Database::query($sql);
  4183. $num = Database::num_rows($result);
  4184. if ($set_visibility == 'i' && $num > 0) {
  4185. $sql = "DELETE FROM $tbl_tool
  4186. WHERE
  4187. c_id = $course_id AND
  4188. (link = '$link' OR link = '$oldLink') AND
  4189. image='scormbuilder.gif'
  4190. $session_condition";
  4191. Database::query($sql);
  4192. } elseif ($set_visibility == 'v' && $num == 0) {
  4193. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4194. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4195. Database::query($sql);
  4196. $insertId = Database::insert_id();
  4197. if ($insertId) {
  4198. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4199. Database::query($sql);
  4200. }
  4201. } elseif ($set_visibility == 'v' && $num > 0) {
  4202. $sql = "UPDATE $tbl_tool SET
  4203. c_id = $course_id,
  4204. name = '$name',
  4205. link = '$link',
  4206. image = 'scormbuilder.gif',
  4207. visibility = '$v',
  4208. admin = '0',
  4209. address = 'pastillegris.gif',
  4210. added_tool = 0,
  4211. session_id = $session_id
  4212. WHERE
  4213. c_id = ".$course_id." AND
  4214. (link = '$link' OR link = '$oldLink') AND
  4215. image='scormbuilder.gif'
  4216. $session_condition
  4217. ";
  4218. Database::query($sql);
  4219. } else {
  4220. // Parameter and database incompatible, do nothing, exit.
  4221. return false;
  4222. }
  4223. } else {
  4224. return false;
  4225. }
  4226. }
  4227. /**
  4228. * Publishes a learnpath.
  4229. * Show or hide the learnpath category on the course homepage.
  4230. *
  4231. * @param int $id
  4232. * @param int $setVisibility
  4233. *
  4234. * @throws \Doctrine\ORM\NonUniqueResultException
  4235. * @throws \Doctrine\ORM\ORMException
  4236. * @throws \Doctrine\ORM\OptimisticLockException
  4237. * @throws \Doctrine\ORM\TransactionRequiredException
  4238. *
  4239. * @return bool
  4240. */
  4241. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4242. {
  4243. $courseId = api_get_course_int_id();
  4244. $sessionId = api_get_session_id();
  4245. $sessionCondition = api_get_session_condition(
  4246. $sessionId,
  4247. true,
  4248. false,
  4249. 't.sessionId'
  4250. );
  4251. $em = Database::getManager();
  4252. /** @var CLpCategory $category */
  4253. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4254. if (!$category) {
  4255. return false;
  4256. }
  4257. $link = self::getCategoryLinkForTool($id);
  4258. /** @var CTool $tool */
  4259. $tool = $em->createQuery("
  4260. SELECT t FROM ChamiloCourseBundle:CTool t
  4261. WHERE
  4262. t.cId = :course AND
  4263. t.link = :link1 AND
  4264. t.image = 'lp_category.gif' AND
  4265. t.link LIKE :link2
  4266. $sessionCondition
  4267. ")
  4268. ->setParameters([
  4269. 'course' => (int) $courseId,
  4270. 'link1' => $link,
  4271. 'link2' => "$link%",
  4272. ])
  4273. ->getOneOrNullResult();
  4274. if ($setVisibility == 0 && $tool) {
  4275. $em->remove($tool);
  4276. $em->flush();
  4277. return true;
  4278. }
  4279. if ($setVisibility == 1 && !$tool) {
  4280. $tool = new CTool();
  4281. $tool
  4282. ->setCategory('authoring')
  4283. ->setCId($courseId)
  4284. ->setName(strip_tags($category->getName()))
  4285. ->setLink($link)
  4286. ->setImage('lp_category.gif')
  4287. ->setVisibility(1)
  4288. ->setAdmin(0)
  4289. ->setAddress('pastillegris.gif')
  4290. ->setAddedTool(0)
  4291. ->setSessionId($sessionId)
  4292. ->setTarget('_self');
  4293. $em->persist($tool);
  4294. $em->flush();
  4295. $tool->setId($tool->getIid());
  4296. $em->persist($tool);
  4297. $em->flush();
  4298. return true;
  4299. }
  4300. if ($setVisibility == 1 && $tool) {
  4301. $tool
  4302. ->setName(strip_tags($category->getName()))
  4303. ->setVisibility(1);
  4304. $em->persist($tool);
  4305. $em->flush();
  4306. return true;
  4307. }
  4308. return false;
  4309. }
  4310. /**
  4311. * Check if the learnpath category is visible for a user.
  4312. *
  4313. * @param CLpCategory $category
  4314. * @param User $user
  4315. *
  4316. * @return bool
  4317. */
  4318. public static function categoryIsVisibleForStudent(
  4319. CLpCategory $category,
  4320. User $user
  4321. ) {
  4322. $subscriptionSettings = self::getSubscriptionSettings();
  4323. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4324. return true;
  4325. }
  4326. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4327. if ($isAllowedToEdit) {
  4328. return true;
  4329. }
  4330. if (empty($category)) {
  4331. return false;
  4332. }
  4333. $users = $category->getUsers();
  4334. if (empty($users) || !$users->count()) {
  4335. return true;
  4336. }
  4337. if ($category->hasUserAdded($user)) {
  4338. return true;
  4339. }
  4340. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4341. if (!empty($groups)) {
  4342. $em = Database::getManager();
  4343. /** @var ItemPropertyRepository $itemRepo */
  4344. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4345. /** @var CourseRepository $courseRepo */
  4346. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4347. $sessionId = api_get_session_id();
  4348. $session = null;
  4349. if (!empty($sessionId)) {
  4350. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4351. }
  4352. $course = $courseRepo->find(api_get_course_int_id());
  4353. // Subscribed groups to a LP
  4354. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4355. TOOL_LEARNPATH_CATEGORY,
  4356. $category->getId(),
  4357. $course,
  4358. $session
  4359. );
  4360. if (!empty($subscribedGroupsInLp)) {
  4361. $groups = array_column($groups, 'iid');
  4362. /** @var CItemProperty $item */
  4363. foreach ($subscribedGroupsInLp as $item) {
  4364. if ($item->getGroup() &&
  4365. in_array($item->getGroup()->getId(), $groups)
  4366. ) {
  4367. return true;
  4368. }
  4369. }
  4370. }
  4371. }
  4372. return false;
  4373. }
  4374. /**
  4375. * Check if a learnpath category is published as course tool.
  4376. *
  4377. * @param CLpCategory $category
  4378. * @param int $courseId
  4379. *
  4380. * @return bool
  4381. */
  4382. public static function categoryIsPublished(
  4383. CLpCategory $category,
  4384. $courseId
  4385. ) {
  4386. $link = self::getCategoryLinkForTool($category->getId());
  4387. $em = Database::getManager();
  4388. $tools = $em
  4389. ->createQuery("
  4390. SELECT t FROM ChamiloCourseBundle:CTool t
  4391. WHERE t.cId = :course AND
  4392. t.name = :name AND
  4393. t.image = 'lp_category.gif' AND
  4394. t.link LIKE :link
  4395. ")
  4396. ->setParameters([
  4397. 'course' => $courseId,
  4398. 'name' => strip_tags($category->getName()),
  4399. 'link' => "$link%",
  4400. ])
  4401. ->getResult();
  4402. /** @var CTool $tool */
  4403. $tool = current($tools);
  4404. return $tool ? $tool->getVisibility() : false;
  4405. }
  4406. /**
  4407. * Restart the whole learnpath. Return the URL of the first element.
  4408. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4409. * To use a similar method statically, use the create_new_attempt() method.
  4410. *
  4411. * @return bool
  4412. */
  4413. public function restart()
  4414. {
  4415. if ($this->debug > 0) {
  4416. error_log('In learnpath::restart()', 0);
  4417. }
  4418. // TODO
  4419. // Call autosave method to save the current progress.
  4420. //$this->index = 0;
  4421. if (api_is_invitee()) {
  4422. return false;
  4423. }
  4424. $session_id = api_get_session_id();
  4425. $course_id = api_get_course_int_id();
  4426. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4427. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4428. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4429. if ($this->debug > 2) {
  4430. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4431. }
  4432. Database::query($sql);
  4433. $view_id = Database::insert_id();
  4434. if ($view_id) {
  4435. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4436. Database::query($sql);
  4437. $this->lp_view_id = $view_id;
  4438. $this->attempt = $this->attempt + 1;
  4439. } else {
  4440. $this->error = 'Could not insert into item_view table...';
  4441. return false;
  4442. }
  4443. $this->autocomplete_parents($this->current);
  4444. foreach ($this->items as $index => $dummy) {
  4445. $this->items[$index]->restart();
  4446. $this->items[$index]->set_lp_view($this->lp_view_id);
  4447. }
  4448. $this->first();
  4449. return true;
  4450. }
  4451. /**
  4452. * Saves the current item.
  4453. *
  4454. * @return bool
  4455. */
  4456. public function save_current()
  4457. {
  4458. $debug = $this->debug;
  4459. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4460. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4461. if ($debug) {
  4462. error_log('save_current() saving item '.$this->current, 0);
  4463. error_log(''.print_r($this->items, true), 0);
  4464. }
  4465. if (isset($this->items[$this->current]) &&
  4466. is_object($this->items[$this->current])
  4467. ) {
  4468. if ($debug) {
  4469. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4470. }
  4471. $res = $this->items[$this->current]->save(
  4472. false,
  4473. $this->prerequisites_match($this->current)
  4474. );
  4475. $this->autocomplete_parents($this->current);
  4476. $status = $this->items[$this->current]->get_status();
  4477. $this->update_queue[$this->current] = $status;
  4478. if ($debug) {
  4479. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4480. }
  4481. return $res;
  4482. }
  4483. return false;
  4484. }
  4485. /**
  4486. * Saves the given item.
  4487. *
  4488. * @param int $item_id Optional (will take from $_REQUEST if null)
  4489. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4490. *
  4491. * @return bool
  4492. */
  4493. public function save_item($item_id = null, $from_outside = true)
  4494. {
  4495. $debug = $this->debug;
  4496. if ($debug) {
  4497. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4498. }
  4499. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4500. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4501. if (empty($item_id)) {
  4502. $item_id = intval($_REQUEST['id']);
  4503. }
  4504. if (empty($item_id)) {
  4505. $item_id = $this->get_current_item_id();
  4506. }
  4507. if (isset($this->items[$item_id]) &&
  4508. is_object($this->items[$item_id])
  4509. ) {
  4510. if ($debug) {
  4511. error_log('Object exists');
  4512. }
  4513. // Saving the item.
  4514. $res = $this->items[$item_id]->save(
  4515. $from_outside,
  4516. $this->prerequisites_match($item_id)
  4517. );
  4518. if ($debug) {
  4519. error_log('update_queue before:');
  4520. error_log(print_r($this->update_queue, 1));
  4521. }
  4522. $this->autocomplete_parents($item_id);
  4523. $status = $this->items[$item_id]->get_status();
  4524. $this->update_queue[$item_id] = $status;
  4525. if ($debug) {
  4526. error_log('get_status(): '.$status);
  4527. error_log('update_queue after:');
  4528. error_log(print_r($this->update_queue, 1));
  4529. }
  4530. return $res;
  4531. }
  4532. return false;
  4533. }
  4534. /**
  4535. * Saves the last item seen's ID only in case.
  4536. */
  4537. public function save_last()
  4538. {
  4539. $course_id = api_get_course_int_id();
  4540. $debug = $this->debug;
  4541. if ($debug) {
  4542. error_log('In learnpath::save_last()', 0);
  4543. }
  4544. $session_condition = api_get_session_condition(
  4545. api_get_session_id(),
  4546. true,
  4547. false
  4548. );
  4549. $table = Database::get_course_table(TABLE_LP_VIEW);
  4550. if (isset($this->current) && !api_is_invitee()) {
  4551. if ($debug) {
  4552. error_log('Saving current item ('.$this->current.') for later review', 0);
  4553. }
  4554. $sql = "UPDATE $table SET
  4555. last_item = ".intval($this->get_current_item_id())."
  4556. WHERE
  4557. c_id = $course_id AND
  4558. lp_id = ".$this->get_id()." AND
  4559. user_id = ".$this->get_user_id()." ".$session_condition;
  4560. if ($debug) {
  4561. error_log('Saving last item seen : '.$sql, 0);
  4562. }
  4563. Database::query($sql);
  4564. }
  4565. if (!api_is_invitee()) {
  4566. // Save progress.
  4567. list($progress) = $this->get_progress_bar_text('%');
  4568. if ($progress >= 0 && $progress <= 100) {
  4569. $progress = (int) $progress;
  4570. $sql = "UPDATE $table SET
  4571. progress = $progress
  4572. WHERE
  4573. c_id = $course_id AND
  4574. lp_id = ".$this->get_id()." AND
  4575. user_id = ".$this->get_user_id()." ".$session_condition;
  4576. // Ignore errors as some tables might not have the progress field just yet.
  4577. Database::query($sql);
  4578. if ($debug) {
  4579. error_log($sql);
  4580. }
  4581. $this->progress_db = $progress;
  4582. }
  4583. }
  4584. }
  4585. /**
  4586. * Sets the current item ID (checks if valid and authorized first).
  4587. *
  4588. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4589. */
  4590. public function set_current_item($item_id = null)
  4591. {
  4592. $debug = $this->debug;
  4593. if ($debug) {
  4594. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4595. }
  4596. if (empty($item_id)) {
  4597. if ($debug) {
  4598. error_log('No new current item given, ignore...', 0);
  4599. }
  4600. // Do nothing.
  4601. } else {
  4602. if ($debug) {
  4603. error_log('New current item given is '.$item_id.'...', 0);
  4604. }
  4605. if (is_numeric($item_id)) {
  4606. $item_id = intval($item_id);
  4607. // TODO: Check in database here.
  4608. $this->last = $this->current;
  4609. $this->current = $item_id;
  4610. // TODO: Update $this->index as well.
  4611. foreach ($this->ordered_items as $index => $item) {
  4612. if ($item == $this->current) {
  4613. $this->index = $index;
  4614. break;
  4615. }
  4616. }
  4617. if ($debug) {
  4618. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4619. }
  4620. } else {
  4621. if ($debug) {
  4622. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4623. }
  4624. }
  4625. }
  4626. }
  4627. /**
  4628. * Sets the encoding.
  4629. *
  4630. * @param string $enc New encoding
  4631. *
  4632. * @return bool
  4633. *
  4634. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4635. */
  4636. public function set_encoding($enc = 'UTF-8')
  4637. {
  4638. if ($this->debug > 0) {
  4639. error_log('In learnpath::set_encoding()', 0);
  4640. }
  4641. $enc = api_refine_encoding_id($enc);
  4642. if (empty($enc)) {
  4643. $enc = api_get_system_encoding();
  4644. }
  4645. if (api_is_encoding_supported($enc)) {
  4646. $lp = $this->get_id();
  4647. if ($lp != 0) {
  4648. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4649. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4650. WHERE iid = ".$lp;
  4651. $res = Database::query($sql);
  4652. return $res;
  4653. }
  4654. }
  4655. return false;
  4656. }
  4657. /**
  4658. * Sets the JS lib setting in the database directly.
  4659. * This is the JavaScript library file this lp needs to load on startup.
  4660. *
  4661. * @param string $lib Proximity setting
  4662. *
  4663. * @return bool True on update success. False otherwise.
  4664. */
  4665. public function set_jslib($lib = '')
  4666. {
  4667. if ($this->debug > 0) {
  4668. error_log('In learnpath::set_jslib()', 0);
  4669. }
  4670. $lp = $this->get_id();
  4671. if ($lp != 0) {
  4672. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4673. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4674. WHERE iid = $lp";
  4675. $res = Database::query($sql);
  4676. return $res;
  4677. } else {
  4678. return false;
  4679. }
  4680. }
  4681. /**
  4682. * Sets the name of the LP maker (publisher) (and save).
  4683. *
  4684. * @param string $name Optional string giving the new content_maker of this learnpath
  4685. *
  4686. * @return bool True
  4687. */
  4688. public function set_maker($name = '')
  4689. {
  4690. if ($this->debug > 0) {
  4691. error_log('In learnpath::set_maker()', 0);
  4692. }
  4693. if (empty($name)) {
  4694. return false;
  4695. }
  4696. $this->maker = $name;
  4697. $table = Database::get_course_table(TABLE_LP_MAIN);
  4698. $lp_id = $this->get_id();
  4699. $sql = "UPDATE $table SET
  4700. content_maker = '".Database::escape_string($this->maker)."'
  4701. WHERE iid = $lp_id";
  4702. if ($this->debug > 2) {
  4703. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4704. }
  4705. Database::query($sql);
  4706. return true;
  4707. }
  4708. /**
  4709. * Sets the name of the current learnpath (and save).
  4710. *
  4711. * @param string $name Optional string giving the new name of this learnpath
  4712. *
  4713. * @return bool True/False
  4714. */
  4715. public function set_name($name = null)
  4716. {
  4717. if ($this->debug > 0) {
  4718. error_log('In learnpath::set_name()', 0);
  4719. }
  4720. if (empty($name)) {
  4721. return false;
  4722. }
  4723. $this->name = Database::escape_string($name);
  4724. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4725. $lp_id = $this->get_id();
  4726. $course_id = $this->course_info['real_id'];
  4727. $sql = "UPDATE $lp_table SET
  4728. name = '".Database::escape_string($this->name)."'
  4729. WHERE iid = $lp_id";
  4730. if ($this->debug > 2) {
  4731. error_log('lp updated with new name : '.$this->name, 0);
  4732. }
  4733. $result = Database::query($sql);
  4734. // If the lp is visible on the homepage, change his name there.
  4735. if (Database::affected_rows($result)) {
  4736. $session_id = api_get_session_id();
  4737. $session_condition = api_get_session_condition($session_id);
  4738. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4739. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4740. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4741. WHERE
  4742. c_id = $course_id AND
  4743. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4744. Database::query($sql);
  4745. return true;
  4746. } else {
  4747. return false;
  4748. }
  4749. }
  4750. /**
  4751. * Set index specified prefix terms for all items in this path.
  4752. *
  4753. * @param string $terms_string Comma-separated list of terms
  4754. * @param string $prefix Xapian term prefix
  4755. *
  4756. * @return bool False on error, true otherwise
  4757. */
  4758. public function set_terms_by_prefix($terms_string, $prefix)
  4759. {
  4760. $course_id = api_get_course_int_id();
  4761. if (api_get_setting('search_enabled') !== 'true') {
  4762. return false;
  4763. }
  4764. if (!extension_loaded('xapian')) {
  4765. return false;
  4766. }
  4767. $terms_string = trim($terms_string);
  4768. $terms = explode(',', $terms_string);
  4769. array_walk($terms, 'trim_value');
  4770. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4771. // Don't do anything if no change, verify only at DB, not the search engine.
  4772. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4773. return false;
  4774. }
  4775. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4776. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4777. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4778. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4779. $lp_id = intval($_POST['lp_id']);
  4780. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4781. $result = Database::query($sql);
  4782. $di = new ChamiloIndexer();
  4783. while ($lp_item = Database::fetch_array($result)) {
  4784. // Get search_did.
  4785. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4786. $sql = 'SELECT * FROM %s
  4787. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4788. LIMIT 1';
  4789. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4790. //echo $sql; echo '<br>';
  4791. $res = Database::query($sql);
  4792. if (Database::num_rows($res) > 0) {
  4793. $se_ref = Database::fetch_array($res);
  4794. // Compare terms.
  4795. $doc = $di->get_document($se_ref['search_did']);
  4796. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4797. $xterms = [];
  4798. foreach ($xapian_terms as $xapian_term) {
  4799. $xterms[] = substr($xapian_term['name'], 1);
  4800. }
  4801. $dterms = $terms;
  4802. $missing_terms = array_diff($dterms, $xterms);
  4803. $deprecated_terms = array_diff($xterms, $dterms);
  4804. // Save it to search engine.
  4805. foreach ($missing_terms as $term) {
  4806. $doc->add_term($prefix.$term, 1);
  4807. }
  4808. foreach ($deprecated_terms as $term) {
  4809. $doc->remove_term($prefix.$term);
  4810. }
  4811. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4812. $di->getDb()->flush();
  4813. }
  4814. }
  4815. return true;
  4816. }
  4817. /**
  4818. * Sets the theme of the LP (local/remote) (and save).
  4819. *
  4820. * @param string $name Optional string giving the new theme of this learnpath
  4821. *
  4822. * @return bool Returns true if theme name is not empty
  4823. */
  4824. public function set_theme($name = '')
  4825. {
  4826. if ($this->debug > 0) {
  4827. error_log('In learnpath::set_theme()', 0);
  4828. }
  4829. $this->theme = $name;
  4830. $table = Database::get_course_table(TABLE_LP_MAIN);
  4831. $lp_id = $this->get_id();
  4832. $sql = "UPDATE $table
  4833. SET theme = '".Database::escape_string($this->theme)."'
  4834. WHERE iid = $lp_id";
  4835. if ($this->debug > 2) {
  4836. error_log('lp updated with new theme : '.$this->theme, 0);
  4837. }
  4838. Database::query($sql);
  4839. return true;
  4840. }
  4841. /**
  4842. * Sets the image of an LP (and save).
  4843. *
  4844. * @param string $name Optional string giving the new image of this learnpath
  4845. *
  4846. * @return bool Returns true if theme name is not empty
  4847. */
  4848. public function set_preview_image($name = '')
  4849. {
  4850. if ($this->debug > 0) {
  4851. error_log('In learnpath::set_preview_image()', 0);
  4852. }
  4853. $this->preview_image = $name;
  4854. $table = Database::get_course_table(TABLE_LP_MAIN);
  4855. $lp_id = $this->get_id();
  4856. $sql = "UPDATE $table SET
  4857. preview_image = '".Database::escape_string($this->preview_image)."'
  4858. WHERE iid = $lp_id";
  4859. if ($this->debug > 2) {
  4860. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4861. }
  4862. Database::query($sql);
  4863. return true;
  4864. }
  4865. /**
  4866. * Sets the author of a LP (and save).
  4867. *
  4868. * @param string $name Optional string giving the new author of this learnpath
  4869. *
  4870. * @return bool Returns true if author's name is not empty
  4871. */
  4872. public function set_author($name = '')
  4873. {
  4874. if ($this->debug > 0) {
  4875. error_log('In learnpath::set_author()', 0);
  4876. }
  4877. $this->author = $name;
  4878. $table = Database::get_course_table(TABLE_LP_MAIN);
  4879. $lp_id = $this->get_id();
  4880. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4881. WHERE iid = $lp_id";
  4882. if ($this->debug > 2) {
  4883. error_log('lp updated with new preview author : '.$this->author, 0);
  4884. }
  4885. Database::query($sql);
  4886. return true;
  4887. }
  4888. /**
  4889. * Sets the hide_toc_frame parameter of a LP (and save).
  4890. *
  4891. * @param int $hide 1 if frame is hidden 0 then else
  4892. *
  4893. * @return bool Returns true if author's name is not empty
  4894. */
  4895. public function set_hide_toc_frame($hide)
  4896. {
  4897. if ($this->debug > 0) {
  4898. error_log('In learnpath::set_hide_toc_frame()', 0);
  4899. }
  4900. if (intval($hide) == $hide) {
  4901. $this->hide_toc_frame = $hide;
  4902. $table = Database::get_course_table(TABLE_LP_MAIN);
  4903. $lp_id = $this->get_id();
  4904. $sql = "UPDATE $table SET
  4905. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4906. WHERE iid = $lp_id";
  4907. if ($this->debug > 2) {
  4908. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4909. }
  4910. Database::query($sql);
  4911. return true;
  4912. } else {
  4913. return false;
  4914. }
  4915. }
  4916. /**
  4917. * Sets the prerequisite of a LP (and save).
  4918. *
  4919. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4920. *
  4921. * @return bool returns true if prerequisite is not empty
  4922. */
  4923. public function set_prerequisite($prerequisite)
  4924. {
  4925. if ($this->debug > 0) {
  4926. error_log('In learnpath::set_prerequisite()', 0);
  4927. }
  4928. $this->prerequisite = (int) $prerequisite;
  4929. $table = Database::get_course_table(TABLE_LP_MAIN);
  4930. $lp_id = $this->get_id();
  4931. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4932. WHERE iid = $lp_id";
  4933. if ($this->debug > 2) {
  4934. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  4935. }
  4936. Database::query($sql);
  4937. return true;
  4938. }
  4939. /**
  4940. * Sets the location/proximity of the LP (local/remote) (and save).
  4941. *
  4942. * @param string $name Optional string giving the new location of this learnpath
  4943. *
  4944. * @return bool True on success / False on error
  4945. */
  4946. public function set_proximity($name = '')
  4947. {
  4948. if ($this->debug > 0) {
  4949. error_log('In learnpath::set_proximity()', 0);
  4950. }
  4951. if (empty($name)) {
  4952. return false;
  4953. }
  4954. $this->proximity = $name;
  4955. $table = Database::get_course_table(TABLE_LP_MAIN);
  4956. $lp_id = $this->get_id();
  4957. $sql = "UPDATE $table SET
  4958. content_local = '".Database::escape_string($name)."'
  4959. WHERE iid = $lp_id";
  4960. if ($this->debug > 2) {
  4961. error_log('lp updated with new proximity : '.$this->proximity, 0);
  4962. }
  4963. Database::query($sql);
  4964. return true;
  4965. }
  4966. /**
  4967. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4968. *
  4969. * @param int $id DB ID of the item
  4970. */
  4971. public function set_previous_item($id)
  4972. {
  4973. if ($this->debug > 0) {
  4974. error_log('In learnpath::set_previous_item()', 0);
  4975. }
  4976. $this->last = $id;
  4977. }
  4978. /**
  4979. * Sets use_max_score.
  4980. *
  4981. * @param int $use_max_score Optional string giving the new location of this learnpath
  4982. *
  4983. * @return bool True on success / False on error
  4984. */
  4985. public function set_use_max_score($use_max_score = 1)
  4986. {
  4987. if ($this->debug > 0) {
  4988. error_log('In learnpath::set_use_max_score()', 0);
  4989. }
  4990. $use_max_score = intval($use_max_score);
  4991. $this->use_max_score = $use_max_score;
  4992. $table = Database::get_course_table(TABLE_LP_MAIN);
  4993. $lp_id = $this->get_id();
  4994. $sql = "UPDATE $table SET
  4995. use_max_score = '".$this->use_max_score."'
  4996. WHERE iid = $lp_id";
  4997. if ($this->debug > 2) {
  4998. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  4999. }
  5000. Database::query($sql);
  5001. return true;
  5002. }
  5003. /**
  5004. * Sets and saves the expired_on date.
  5005. *
  5006. * @param string $expired_on Optional string giving the new author of this learnpath
  5007. *
  5008. * @throws \Doctrine\ORM\OptimisticLockException
  5009. *
  5010. * @return bool Returns true if author's name is not empty
  5011. */
  5012. public function set_expired_on($expired_on)
  5013. {
  5014. if ($this->debug > 0) {
  5015. error_log('In learnpath::set_expired_on()', 0);
  5016. }
  5017. $em = Database::getManager();
  5018. /** @var CLp $lp */
  5019. $lp = $em
  5020. ->getRepository('ChamiloCourseBundle:CLp')
  5021. ->findOneBy(
  5022. [
  5023. 'iid' => $this->get_id(),
  5024. ]
  5025. );
  5026. if (!$lp) {
  5027. return false;
  5028. }
  5029. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5030. $lp->setExpiredOn($this->expired_on);
  5031. $em->persist($lp);
  5032. $em->flush();
  5033. if ($this->debug > 2) {
  5034. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  5035. }
  5036. return true;
  5037. }
  5038. /**
  5039. * Sets and saves the publicated_on date.
  5040. *
  5041. * @param string $publicated_on Optional string giving the new author of this learnpath
  5042. *
  5043. * @throws \Doctrine\ORM\OptimisticLockException
  5044. *
  5045. * @return bool Returns true if author's name is not empty
  5046. */
  5047. public function set_publicated_on($publicated_on)
  5048. {
  5049. if ($this->debug > 0) {
  5050. error_log('In learnpath::set_expired_on()', 0);
  5051. }
  5052. $em = Database::getManager();
  5053. /** @var CLp $lp */
  5054. $lp = $em
  5055. ->getRepository('ChamiloCourseBundle:CLp')
  5056. ->findOneBy(
  5057. [
  5058. 'iid' => $this->get_id(),
  5059. ]
  5060. );
  5061. if (!$lp) {
  5062. return false;
  5063. }
  5064. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5065. $lp->setPublicatedOn($this->publicated_on);
  5066. $em->persist($lp);
  5067. $em->flush();
  5068. if ($this->debug > 2) {
  5069. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5070. }
  5071. return true;
  5072. }
  5073. /**
  5074. * Sets and saves the expired_on date.
  5075. *
  5076. * @return bool Returns true if author's name is not empty
  5077. */
  5078. public function set_modified_on()
  5079. {
  5080. if ($this->debug > 0) {
  5081. error_log('In learnpath::set_expired_on()', 0);
  5082. }
  5083. $this->modified_on = api_get_utc_datetime();
  5084. $table = Database::get_course_table(TABLE_LP_MAIN);
  5085. $lp_id = $this->get_id();
  5086. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5087. WHERE iid = $lp_id";
  5088. if ($this->debug > 2) {
  5089. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5090. }
  5091. Database::query($sql);
  5092. return true;
  5093. }
  5094. /**
  5095. * Sets the object's error message.
  5096. *
  5097. * @param string $error Error message. If empty, reinits the error string
  5098. */
  5099. public function set_error_msg($error = '')
  5100. {
  5101. if ($this->debug > 0) {
  5102. error_log('In learnpath::set_error_msg()', 0);
  5103. }
  5104. if (empty($error)) {
  5105. $this->error = '';
  5106. } else {
  5107. $this->error .= $error;
  5108. }
  5109. }
  5110. /**
  5111. * Launches the current item if not 'sco'
  5112. * (starts timer and make sure there is a record ready in the DB).
  5113. *
  5114. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5115. *
  5116. * @return bool
  5117. */
  5118. public function start_current_item($allow_new_attempt = false)
  5119. {
  5120. $debug = $this->debug;
  5121. if ($debug) {
  5122. error_log('In learnpath::start_current_item()');
  5123. error_log('current: '.$this->current);
  5124. }
  5125. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5126. $type = $this->get_type();
  5127. $item_type = $this->items[$this->current]->get_type();
  5128. if (($type == 2 && $item_type != 'sco') ||
  5129. ($type == 3 && $item_type != 'au') ||
  5130. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5131. ) {
  5132. if ($debug) {
  5133. error_log('item type: '.$item_type);
  5134. error_log('lp type: '.$type);
  5135. }
  5136. $this->items[$this->current]->open($allow_new_attempt);
  5137. $this->autocomplete_parents($this->current);
  5138. $prereq_check = $this->prerequisites_match($this->current);
  5139. if ($debug) {
  5140. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5141. }
  5142. $this->items[$this->current]->save(false, $prereq_check);
  5143. }
  5144. // If sco, then it is supposed to have been updated by some other call.
  5145. if ($item_type == 'sco') {
  5146. $this->items[$this->current]->restart();
  5147. }
  5148. }
  5149. if ($debug) {
  5150. error_log('lp_view_session_id');
  5151. error_log($this->lp_view_session_id);
  5152. error_log('api session id');
  5153. error_log(api_get_session_id());
  5154. error_log('End of learnpath::start_current_item()');
  5155. }
  5156. return true;
  5157. }
  5158. /**
  5159. * Stops the processing and counters for the old item (as held in $this->last).
  5160. *
  5161. * @return bool True/False
  5162. */
  5163. public function stop_previous_item()
  5164. {
  5165. $debug = $this->debug;
  5166. if ($debug) {
  5167. error_log('In learnpath::stop_previous_item()', 0);
  5168. }
  5169. if ($this->last != 0 && $this->last != $this->current &&
  5170. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5171. ) {
  5172. if ($debug) {
  5173. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5174. }
  5175. switch ($this->get_type()) {
  5176. case '3':
  5177. if ($this->items[$this->last]->get_type() != 'au') {
  5178. if ($debug) {
  5179. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5180. }
  5181. $this->items[$this->last]->close();
  5182. } else {
  5183. if ($debug) {
  5184. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5185. }
  5186. }
  5187. break;
  5188. case '2':
  5189. if ($this->items[$this->last]->get_type() != 'sco') {
  5190. if ($debug) {
  5191. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5192. }
  5193. $this->items[$this->last]->close();
  5194. } else {
  5195. if ($debug) {
  5196. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5197. }
  5198. }
  5199. break;
  5200. case '1':
  5201. default:
  5202. if ($debug) {
  5203. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5204. }
  5205. $this->items[$this->last]->close();
  5206. break;
  5207. }
  5208. } else {
  5209. if ($debug) {
  5210. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5211. }
  5212. return false;
  5213. }
  5214. return true;
  5215. }
  5216. /**
  5217. * Updates the default view mode from fullscreen to embedded and inversely.
  5218. *
  5219. * @return string The current default view mode ('fullscreen' or 'embedded')
  5220. */
  5221. public function update_default_view_mode()
  5222. {
  5223. if ($this->debug > 0) {
  5224. error_log('In learnpath::update_default_view_mode()', 0);
  5225. }
  5226. $table = Database::get_course_table(TABLE_LP_MAIN);
  5227. $sql = "SELECT * FROM $table
  5228. WHERE iid = ".$this->get_id();
  5229. $res = Database::query($sql);
  5230. if (Database::num_rows($res) > 0) {
  5231. $row = Database::fetch_array($res);
  5232. $default_view_mode = $row['default_view_mod'];
  5233. $view_mode = $default_view_mode;
  5234. switch ($default_view_mode) {
  5235. case 'fullscreen': // default with popup
  5236. $view_mode = 'embedded';
  5237. break;
  5238. case 'embedded': // default view with left menu
  5239. $view_mode = 'embedframe';
  5240. break;
  5241. case 'embedframe': //folded menu
  5242. $view_mode = 'impress';
  5243. break;
  5244. case 'impress':
  5245. $view_mode = 'fullscreen';
  5246. break;
  5247. }
  5248. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5249. WHERE iid = ".$this->get_id();
  5250. Database::query($sql);
  5251. $this->mode = $view_mode;
  5252. return $view_mode;
  5253. } else {
  5254. if ($this->debug > 2) {
  5255. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5256. }
  5257. }
  5258. return -1;
  5259. }
  5260. /**
  5261. * Updates the default behaviour about auto-commiting SCORM updates.
  5262. *
  5263. * @return bool True if auto-commit has been set to 'on', false otherwise
  5264. */
  5265. public function update_default_scorm_commit()
  5266. {
  5267. if ($this->debug > 0) {
  5268. error_log('In learnpath::update_default_scorm_commit()', 0);
  5269. }
  5270. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5271. $sql = "SELECT * FROM $lp_table
  5272. WHERE iid = ".$this->get_id();
  5273. $res = Database::query($sql);
  5274. if (Database::num_rows($res) > 0) {
  5275. $row = Database::fetch_array($res);
  5276. $force = $row['force_commit'];
  5277. if ($force == 1) {
  5278. $force = 0;
  5279. $force_return = false;
  5280. } elseif ($force == 0) {
  5281. $force = 1;
  5282. $force_return = true;
  5283. }
  5284. $sql = "UPDATE $lp_table SET force_commit = $force
  5285. WHERE iid = ".$this->get_id();
  5286. Database::query($sql);
  5287. $this->force_commit = $force_return;
  5288. return $force_return;
  5289. } else {
  5290. if ($this->debug > 2) {
  5291. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5292. }
  5293. }
  5294. return -1;
  5295. }
  5296. /**
  5297. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5298. *
  5299. * @return bool True on success, false on failure
  5300. */
  5301. public function update_display_order()
  5302. {
  5303. $course_id = api_get_course_int_id();
  5304. $table = Database::get_course_table(TABLE_LP_MAIN);
  5305. $sql = "SELECT * FROM $table
  5306. WHERE c_id = $course_id
  5307. ORDER BY display_order";
  5308. $res = Database::query($sql);
  5309. if ($res === false) {
  5310. return false;
  5311. }
  5312. $num = Database::num_rows($res);
  5313. // First check the order is correct, globally (might be wrong because
  5314. // of versions < 1.8.4).
  5315. if ($num > 0) {
  5316. $i = 1;
  5317. while ($row = Database::fetch_array($res)) {
  5318. if ($row['display_order'] != $i) {
  5319. // If we find a gap in the order, we need to fix it.
  5320. $sql = "UPDATE $table SET display_order = $i
  5321. WHERE iid = ".$row['iid'];
  5322. Database::query($sql);
  5323. }
  5324. $i++;
  5325. }
  5326. }
  5327. return true;
  5328. }
  5329. /**
  5330. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5331. *
  5332. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5333. */
  5334. public function update_reinit()
  5335. {
  5336. if ($this->debug > 0) {
  5337. error_log('In learnpath::update_reinit()', 0);
  5338. }
  5339. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5340. $sql = "SELECT * FROM $lp_table
  5341. WHERE iid = ".$this->get_id();
  5342. $res = Database::query($sql);
  5343. if (Database::num_rows($res) > 0) {
  5344. $row = Database::fetch_array($res);
  5345. $force = $row['prevent_reinit'];
  5346. if ($force == 1) {
  5347. $force = 0;
  5348. } elseif ($force == 0) {
  5349. $force = 1;
  5350. }
  5351. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5352. WHERE iid = ".$this->get_id();
  5353. Database::query($sql);
  5354. $this->prevent_reinit = $force;
  5355. return $force;
  5356. } else {
  5357. if ($this->debug > 2) {
  5358. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5359. }
  5360. }
  5361. return -1;
  5362. }
  5363. /**
  5364. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5365. *
  5366. * @return string 'single', 'multi' or 'seriousgame'
  5367. *
  5368. * @author ndiechburg <noel@cblue.be>
  5369. */
  5370. public function get_attempt_mode()
  5371. {
  5372. //Set default value for seriousgame_mode
  5373. if (!isset($this->seriousgame_mode)) {
  5374. $this->seriousgame_mode = 0;
  5375. }
  5376. // Set default value for prevent_reinit
  5377. if (!isset($this->prevent_reinit)) {
  5378. $this->prevent_reinit = 1;
  5379. }
  5380. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5381. return 'seriousgame';
  5382. }
  5383. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5384. return 'single';
  5385. }
  5386. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5387. return 'multiple';
  5388. }
  5389. return 'single';
  5390. }
  5391. /**
  5392. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5393. *
  5394. * @param string 'seriousgame', 'single' or 'multiple'
  5395. *
  5396. * @return bool
  5397. *
  5398. * @author ndiechburg <noel@cblue.be>
  5399. */
  5400. public function set_attempt_mode($mode)
  5401. {
  5402. switch ($mode) {
  5403. case 'seriousgame':
  5404. $sg_mode = 1;
  5405. $prevent_reinit = 1;
  5406. break;
  5407. case 'single':
  5408. $sg_mode = 0;
  5409. $prevent_reinit = 1;
  5410. break;
  5411. case 'multiple':
  5412. $sg_mode = 0;
  5413. $prevent_reinit = 0;
  5414. break;
  5415. default:
  5416. $sg_mode = 0;
  5417. $prevent_reinit = 0;
  5418. break;
  5419. }
  5420. $this->prevent_reinit = $prevent_reinit;
  5421. $this->seriousgame_mode = $sg_mode;
  5422. $table = Database::get_course_table(TABLE_LP_MAIN);
  5423. $sql = "UPDATE $table SET
  5424. prevent_reinit = $prevent_reinit ,
  5425. seriousgame_mode = $sg_mode
  5426. WHERE iid = ".$this->get_id();
  5427. $res = Database::query($sql);
  5428. if ($res) {
  5429. return true;
  5430. } else {
  5431. return false;
  5432. }
  5433. }
  5434. /**
  5435. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5436. *
  5437. * @author ndiechburg <noel@cblue.be>
  5438. */
  5439. public function switch_attempt_mode()
  5440. {
  5441. if ($this->debug > 0) {
  5442. error_log('In learnpath::switch_attempt_mode()', 0);
  5443. }
  5444. $mode = $this->get_attempt_mode();
  5445. switch ($mode) {
  5446. case 'single':
  5447. $next_mode = 'multiple';
  5448. break;
  5449. case 'multiple':
  5450. $next_mode = 'seriousgame';
  5451. break;
  5452. case 'seriousgame':
  5453. $next_mode = 'single';
  5454. break;
  5455. default:
  5456. $next_mode = 'single';
  5457. break;
  5458. }
  5459. $this->set_attempt_mode($next_mode);
  5460. }
  5461. /**
  5462. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5463. * but possibility to do again a completed item.
  5464. *
  5465. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5466. *
  5467. * @author ndiechburg <noel@cblue.be>
  5468. */
  5469. public function set_seriousgame_mode()
  5470. {
  5471. if ($this->debug > 0) {
  5472. error_log('In learnpath::set_seriousgame_mode()', 0);
  5473. }
  5474. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5475. $sql = "SELECT * FROM $lp_table
  5476. WHERE iid = ".$this->get_id();
  5477. $res = Database::query($sql);
  5478. if (Database::num_rows($res) > 0) {
  5479. $row = Database::fetch_array($res);
  5480. $force = $row['seriousgame_mode'];
  5481. if ($force == 1) {
  5482. $force = 0;
  5483. } elseif ($force == 0) {
  5484. $force = 1;
  5485. }
  5486. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5487. WHERE iid = ".$this->get_id();
  5488. Database::query($sql);
  5489. $this->seriousgame_mode = $force;
  5490. return $force;
  5491. } else {
  5492. if ($this->debug > 2) {
  5493. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5494. }
  5495. }
  5496. return -1;
  5497. }
  5498. /**
  5499. * Updates the "scorm_debug" value that shows or hide the debug window.
  5500. *
  5501. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5502. */
  5503. public function update_scorm_debug()
  5504. {
  5505. if ($this->debug > 0) {
  5506. error_log('In learnpath::update_scorm_debug()', 0);
  5507. }
  5508. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5509. $sql = "SELECT * FROM $lp_table
  5510. WHERE iid = ".$this->get_id();
  5511. $res = Database::query($sql);
  5512. if (Database::num_rows($res) > 0) {
  5513. $row = Database::fetch_array($res);
  5514. $force = $row['debug'];
  5515. if ($force == 1) {
  5516. $force = 0;
  5517. } elseif ($force == 0) {
  5518. $force = 1;
  5519. }
  5520. $sql = "UPDATE $lp_table SET debug = $force
  5521. WHERE iid = ".$this->get_id();
  5522. Database::query($sql);
  5523. $this->scorm_debug = $force;
  5524. return $force;
  5525. } else {
  5526. if ($this->debug > 2) {
  5527. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5528. }
  5529. }
  5530. return -1;
  5531. }
  5532. /**
  5533. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5534. *
  5535. * @author Kevin Van Den Haute
  5536. *
  5537. * @param array
  5538. */
  5539. public function tree_array($array)
  5540. {
  5541. if ($this->debug > 1) {
  5542. error_log('In learnpath::tree_array()', 0);
  5543. }
  5544. $array = $this->sort_tree_array($array);
  5545. $this->create_tree_array($array);
  5546. }
  5547. /**
  5548. * Creates an array with the elements of the learning path tree in it.
  5549. *
  5550. * @author Kevin Van Den Haute
  5551. *
  5552. * @param array $array
  5553. * @param int $parent
  5554. * @param int $depth
  5555. * @param array $tmp
  5556. */
  5557. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5558. {
  5559. if ($this->debug > 1) {
  5560. error_log('In learnpath::create_tree_array())', 0);
  5561. }
  5562. if (is_array($array)) {
  5563. for ($i = 0; $i < count($array); $i++) {
  5564. if ($array[$i]['parent_item_id'] == $parent) {
  5565. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5566. $tmp[] = $array[$i]['parent_item_id'];
  5567. $depth++;
  5568. }
  5569. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5570. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5571. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5572. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5573. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5574. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5575. $this->arrMenu[] = [
  5576. 'id' => $array[$i]['id'],
  5577. 'ref' => $ref,
  5578. 'item_type' => $array[$i]['item_type'],
  5579. 'title' => $array[$i]['title'],
  5580. 'path' => $path,
  5581. 'description' => $array[$i]['description'],
  5582. 'parent_item_id' => $array[$i]['parent_item_id'],
  5583. 'previous_item_id' => $array[$i]['previous_item_id'],
  5584. 'next_item_id' => $array[$i]['next_item_id'],
  5585. 'min_score' => $array[$i]['min_score'],
  5586. 'max_score' => $array[$i]['max_score'],
  5587. 'mastery_score' => $array[$i]['mastery_score'],
  5588. 'display_order' => $array[$i]['display_order'],
  5589. 'prerequisite' => $preq,
  5590. 'depth' => $depth,
  5591. 'audio' => $audio,
  5592. 'prerequisite_min_score' => $prerequisiteMinScore,
  5593. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5594. ];
  5595. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5596. }
  5597. }
  5598. }
  5599. }
  5600. /**
  5601. * Sorts a multi dimensional array by parent id and display order.
  5602. *
  5603. * @author Kevin Van Den Haute
  5604. *
  5605. * @param array $array (array with al the learning path items in it)
  5606. *
  5607. * @return array
  5608. */
  5609. public function sort_tree_array($array)
  5610. {
  5611. foreach ($array as $key => $row) {
  5612. $parent[$key] = $row['parent_item_id'];
  5613. $position[$key] = $row['display_order'];
  5614. }
  5615. if (count($array) > 0) {
  5616. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5617. }
  5618. return $array;
  5619. }
  5620. /**
  5621. * Function that creates a html list of learning path items so that we can add audio files to them.
  5622. *
  5623. * @author Kevin Van Den Haute
  5624. *
  5625. * @return string
  5626. */
  5627. public function overview()
  5628. {
  5629. if ($this->debug > 0) {
  5630. error_log('In learnpath::overview()', 0);
  5631. }
  5632. $return = '';
  5633. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5634. // we need to start a form when we want to update all the mp3 files
  5635. if ($update_audio == 'true') {
  5636. $return .= '<form action="'.api_get_self().'?'.api_get_cidreq().'&updateaudio='.Security::remove_XSS($_GET['updateaudio']).'&action='.Security::remove_XSS($_GET['action']).'&lp_id='.$_SESSION['oLP']->lp_id.'" method="post" enctype="multipart/form-data" name="updatemp3" id="updatemp3">';
  5637. }
  5638. $return .= '<div id="message"></div>';
  5639. if (count($this->items) == 0) {
  5640. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5641. } else {
  5642. $return_audio = '<table class="data_table">';
  5643. $return_audio .= '<tr>';
  5644. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5645. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5646. $return_audio .= '</tr>';
  5647. if ($update_audio != 'true') {
  5648. $return .= '<div class="col-md-12">';
  5649. $return .= self::return_new_tree($update_audio);
  5650. $return .= '</div>';
  5651. $return .= Display::div(
  5652. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5653. ['style' => 'float:left; margin-top:15px;width:100%']
  5654. );
  5655. } else {
  5656. $return_audio .= self::return_new_tree($update_audio);
  5657. $return .= $return_audio.'</table>';
  5658. }
  5659. // We need to close the form when we are updating the mp3 files.
  5660. if ($update_audio == 'true') {
  5661. $return .= '<div class="footer-audio">';
  5662. $return .= Display::button(
  5663. 'save_audio',
  5664. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5665. ['class' => 'btn btn-primary', 'type' => 'submit']
  5666. );
  5667. $return .= '</div>';
  5668. }
  5669. }
  5670. // We need to close the form when we are updating the mp3 files.
  5671. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5672. $return .= '</form>';
  5673. }
  5674. return $return;
  5675. }
  5676. /**
  5677. * @param string $update_audio
  5678. *
  5679. * @return array
  5680. */
  5681. public function processBuildMenuElements($update_audio = 'false')
  5682. {
  5683. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5684. $course_id = api_get_course_int_id();
  5685. $table = Database::get_course_table(TABLE_LP_ITEM);
  5686. $sql = "SELECT * FROM $table
  5687. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5688. $result = Database::query($sql);
  5689. $arrLP = [];
  5690. while ($row = Database::fetch_array($result)) {
  5691. $arrLP[] = [
  5692. 'id' => $row['iid'],
  5693. 'item_type' => $row['item_type'],
  5694. 'title' => Security::remove_XSS($row['title']),
  5695. 'path' => $row['path'],
  5696. 'description' => Security::remove_XSS($row['description']),
  5697. 'parent_item_id' => $row['parent_item_id'],
  5698. 'previous_item_id' => $row['previous_item_id'],
  5699. 'next_item_id' => $row['next_item_id'],
  5700. 'max_score' => $row['max_score'],
  5701. 'min_score' => $row['min_score'],
  5702. 'mastery_score' => $row['mastery_score'],
  5703. 'prerequisite' => $row['prerequisite'],
  5704. 'display_order' => $row['display_order'],
  5705. 'audio' => $row['audio'],
  5706. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5707. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5708. ];
  5709. }
  5710. $this->tree_array($arrLP);
  5711. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5712. unset($this->arrMenu);
  5713. $default_data = null;
  5714. $default_content = null;
  5715. $elements = [];
  5716. $return_audio = null;
  5717. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5718. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5719. for ($i = 0; $i < count($arrLP); $i++) {
  5720. $title = $arrLP[$i]['title'];
  5721. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5722. // Link for the documents
  5723. if ($arrLP[$i]['item_type'] == 'document') {
  5724. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5725. $title_cut = Display::url(
  5726. $title_cut,
  5727. $url,
  5728. [
  5729. 'class' => 'ajax moved',
  5730. 'data-title' => $title,
  5731. 'title' => $title,
  5732. ]
  5733. );
  5734. }
  5735. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5736. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5737. Session::write('pathItem', $arrLP[$i]['path']);
  5738. }
  5739. if (($i % 2) == 0) {
  5740. $oddClass = 'row_odd';
  5741. } else {
  5742. $oddClass = 'row_even';
  5743. }
  5744. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5745. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5746. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5747. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5748. } else {
  5749. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5750. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5751. } else {
  5752. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5753. $icon = Display::return_icon('certificate.png');
  5754. } else {
  5755. $icon = Display::return_icon('folder_document.gif');
  5756. }
  5757. }
  5758. }
  5759. // The audio column.
  5760. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5761. $audio = '';
  5762. if (!$update_audio || $update_audio != 'true') {
  5763. if (empty($arrLP[$i]['audio'])) {
  5764. $audio .= '';
  5765. }
  5766. } else {
  5767. $types = self::getChapterTypes();
  5768. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5769. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5770. if (!empty($arrLP[$i]['audio'])) {
  5771. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5772. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5773. }
  5774. }
  5775. }
  5776. $return_audio .= Display::span($icon.' '.$title).
  5777. Display::tag(
  5778. 'td',
  5779. $audio,
  5780. ['style' => '']
  5781. );
  5782. $return_audio .= '</td>';
  5783. $move_icon = '';
  5784. $move_item_icon = '';
  5785. $edit_icon = '';
  5786. $delete_icon = '';
  5787. $audio_icon = '';
  5788. $prerequisities_icon = '';
  5789. $forumIcon = '';
  5790. $previewIcon = '';
  5791. $pluginCalendarIcon = '';
  5792. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5793. $plugin = null;
  5794. if ($pluginCalendar) {
  5795. $plugin = LearningCalendarPlugin::create();
  5796. }
  5797. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5798. if ($is_allowed_to_edit) {
  5799. if (!$update_audio || $update_audio != 'true') {
  5800. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5801. $move_icon .= '<a class="moved" href="#">';
  5802. $move_icon .= Display::return_icon(
  5803. 'move_everywhere.png',
  5804. get_lang('Move'),
  5805. [],
  5806. ICON_SIZE_TINY
  5807. );
  5808. $move_icon .= '</a>';
  5809. }
  5810. }
  5811. // No edit for this item types
  5812. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5813. if ($arrLP[$i]['item_type'] != 'dir') {
  5814. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5815. $edit_icon .= Display::return_icon(
  5816. 'edit.png',
  5817. get_lang('LearnpathEditModule'),
  5818. [],
  5819. ICON_SIZE_TINY
  5820. );
  5821. $edit_icon .= '</a>';
  5822. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5823. $forumThread = null;
  5824. if (isset($this->items[$arrLP[$i]['id']])) {
  5825. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5826. $this->course_int_id,
  5827. $this->lp_session_id
  5828. );
  5829. }
  5830. if ($forumThread) {
  5831. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5832. 'action' => 'dissociate_forum',
  5833. 'id' => $arrLP[$i]['id'],
  5834. 'lp_id' => $this->lp_id,
  5835. ]);
  5836. $forumIcon = Display::url(
  5837. Display::return_icon(
  5838. 'forum.png',
  5839. get_lang('DissociateForumToLPItem'),
  5840. [],
  5841. ICON_SIZE_TINY
  5842. ),
  5843. $forumIconUrl,
  5844. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5845. );
  5846. } else {
  5847. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5848. 'action' => 'create_forum',
  5849. 'id' => $arrLP[$i]['id'],
  5850. 'lp_id' => $this->lp_id,
  5851. ]);
  5852. $forumIcon = Display::url(
  5853. Display::return_icon(
  5854. 'forum.png',
  5855. get_lang('AssociateForumToLPItem'),
  5856. [],
  5857. ICON_SIZE_TINY
  5858. ),
  5859. $forumIconUrl,
  5860. ['class' => 'btn btn-default lp-btn-associate-forum']
  5861. );
  5862. }
  5863. }
  5864. } else {
  5865. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'&path_item='.$arrLP[$i]['path'].'" class="btn btn-default">';
  5866. $edit_icon .= Display::return_icon(
  5867. 'edit.png',
  5868. get_lang('LearnpathEditModule'),
  5869. [],
  5870. ICON_SIZE_TINY
  5871. );
  5872. $edit_icon .= '</a>';
  5873. }
  5874. } else {
  5875. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5876. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5877. $edit_icon .= Display::return_icon(
  5878. 'edit.png',
  5879. get_lang('Edit'),
  5880. [],
  5881. ICON_SIZE_TINY
  5882. );
  5883. $edit_icon .= '</a>';
  5884. }
  5885. }
  5886. if ($pluginCalendar) {
  5887. $pluginLink = $pluginUrl.
  5888. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5889. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5890. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5891. if ($itemInfo && $itemInfo['value'] == 1) {
  5892. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5893. }
  5894. $pluginCalendarIcon = Display::url(
  5895. $iconCalendar,
  5896. $pluginLink,
  5897. ['class' => 'btn btn-default']
  5898. );
  5899. }
  5900. $delete_icon .= ' <a
  5901. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5902. onclick="return confirmation(\''.addslashes($title).'\');"
  5903. class="btn btn-default">';
  5904. $delete_icon .= Display::return_icon(
  5905. 'delete.png',
  5906. get_lang('LearnpathDeleteModule'),
  5907. [],
  5908. ICON_SIZE_TINY
  5909. );
  5910. $delete_icon .= '</a>';
  5911. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5912. $previewImage = Display::return_icon(
  5913. 'preview_view.png',
  5914. get_lang('Preview'),
  5915. [],
  5916. ICON_SIZE_TINY
  5917. );
  5918. switch ($arrLP[$i]['item_type']) {
  5919. case TOOL_DOCUMENT:
  5920. case TOOL_LP_FINAL_ITEM:
  5921. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5922. $previewIcon = Display::url(
  5923. $previewImage,
  5924. $urlPreviewLink,
  5925. [
  5926. 'target' => '_blank',
  5927. 'class' => 'btn btn-default',
  5928. 'data-title' => $arrLP[$i]['title'],
  5929. 'title' => $arrLP[$i]['title'],
  5930. ]
  5931. );
  5932. break;
  5933. case TOOL_THREAD:
  5934. case TOOL_FORUM:
  5935. case TOOL_QUIZ:
  5936. case TOOL_STUDENTPUBLICATION:
  5937. case TOOL_LP_FINAL_ITEM:
  5938. case TOOL_LINK:
  5939. //$target = '';
  5940. //$class = 'btn btn-default ajax';
  5941. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  5942. $class = 'btn btn-default';
  5943. $target = '_blank';
  5944. //}
  5945. $link = self::rl_get_resource_link_for_learnpath(
  5946. $this->course_int_id,
  5947. $this->lp_id,
  5948. $arrLP[$i]['id'],
  5949. 0
  5950. );
  5951. $previewIcon = Display::url(
  5952. $previewImage,
  5953. $link,
  5954. [
  5955. 'class' => $class,
  5956. 'data-title' => $arrLP[$i]['title'],
  5957. 'title' => $arrLP[$i]['title'],
  5958. 'target' => $target,
  5959. ]
  5960. );
  5961. break;
  5962. default:
  5963. $previewIcon = Display::url(
  5964. $previewImage,
  5965. $url.'&action=view_item',
  5966. ['class' => 'btn btn-default', 'target' => '_blank']
  5967. );
  5968. break;
  5969. }
  5970. if ($arrLP[$i]['item_type'] != 'dir') {
  5971. $prerequisities_icon = Display::url(
  5972. Display::return_icon(
  5973. 'accept.png',
  5974. get_lang('LearnpathPrerequisites'),
  5975. [],
  5976. ICON_SIZE_TINY
  5977. ),
  5978. $url.'&action=edit_item_prereq',
  5979. ['class' => 'btn btn-default']
  5980. );
  5981. if ($arrLP[$i]['item_type'] != 'final_item') {
  5982. $move_item_icon = Display::url(
  5983. Display::return_icon(
  5984. 'move.png',
  5985. get_lang('Move'),
  5986. [],
  5987. ICON_SIZE_TINY
  5988. ),
  5989. $url.'&action=move_item',
  5990. ['class' => 'btn btn-default']
  5991. );
  5992. }
  5993. $audio_icon = Display::url(
  5994. Display::return_icon(
  5995. 'audio.png',
  5996. get_lang('UplUpload'),
  5997. [],
  5998. ICON_SIZE_TINY
  5999. ),
  6000. $url.'&action=add_audio',
  6001. ['class' => 'btn btn-default']
  6002. );
  6003. }
  6004. }
  6005. if ($update_audio != 'true') {
  6006. $row = $move_icon.' '.$icon.
  6007. Display::span($title_cut).
  6008. Display::tag(
  6009. 'div',
  6010. "<div class=\"btn-group btn-group-xs\">
  6011. $previewIcon
  6012. $audio
  6013. $edit_icon
  6014. $pluginCalendarIcon
  6015. $forumIcon
  6016. $prerequisities_icon
  6017. $move_item_icon
  6018. $audio_icon
  6019. $delete_icon
  6020. </div>",
  6021. ['class' => 'btn-toolbar button_actions']
  6022. );
  6023. } else {
  6024. $row =
  6025. Display::span($title.$icon).
  6026. Display::span($audio, ['class' => 'button_actions']);
  6027. }
  6028. $parent_id = $arrLP[$i]['parent_item_id'];
  6029. $default_data[$arrLP[$i]['id']] = $row;
  6030. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6031. if (empty($parent_id)) {
  6032. $elements[$arrLP[$i]['id']]['data'] = $row;
  6033. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6034. } else {
  6035. $parent_arrays = [];
  6036. if ($arrLP[$i]['depth'] > 1) {
  6037. //Getting list of parents
  6038. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6039. foreach ($arrLP as $item) {
  6040. if ($item['id'] == $parent_id) {
  6041. if ($item['parent_item_id'] == 0) {
  6042. $parent_id = $item['id'];
  6043. break;
  6044. } else {
  6045. $parent_id = $item['parent_item_id'];
  6046. if (empty($parent_arrays)) {
  6047. $parent_arrays[] = intval($item['id']);
  6048. }
  6049. $parent_arrays[] = $parent_id;
  6050. break;
  6051. }
  6052. }
  6053. }
  6054. }
  6055. }
  6056. if (!empty($parent_arrays)) {
  6057. $parent_arrays = array_reverse($parent_arrays);
  6058. $val = '$elements';
  6059. $x = 0;
  6060. foreach ($parent_arrays as $item) {
  6061. if ($x != count($parent_arrays) - 1) {
  6062. $val .= '["'.$item.'"]["children"]';
  6063. } else {
  6064. $val .= '["'.$item.'"]["children"]';
  6065. }
  6066. $x++;
  6067. }
  6068. $val .= "";
  6069. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6070. eval($code_str);
  6071. } else {
  6072. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6073. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6074. }
  6075. }
  6076. }
  6077. return [
  6078. 'elements' => $elements,
  6079. 'default_data' => $default_data,
  6080. 'default_content' => $default_content,
  6081. 'return_audio' => $return_audio,
  6082. ];
  6083. }
  6084. /**
  6085. * @param string $updateAudio true/false strings
  6086. *
  6087. * @return string
  6088. */
  6089. public function returnLpItemList($updateAudio)
  6090. {
  6091. $result = $this->processBuildMenuElements($updateAudio);
  6092. $html = self::print_recursive(
  6093. $result['elements'],
  6094. $result['default_data'],
  6095. $result['default_content']
  6096. );
  6097. if (!empty($html)) {
  6098. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6099. }
  6100. return $html;
  6101. }
  6102. /**
  6103. * @param string $update_audio
  6104. * @param bool $drop_element_here
  6105. *
  6106. * @return string
  6107. */
  6108. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6109. {
  6110. $return = '';
  6111. $result = $this->processBuildMenuElements($update_audio);
  6112. $list = '<ul id="lp_item_list">';
  6113. $tree = $this->print_recursive(
  6114. $result['elements'],
  6115. $result['default_data'],
  6116. $result['default_content']
  6117. );
  6118. if (!empty($tree)) {
  6119. $list .= $tree;
  6120. } else {
  6121. if ($drop_element_here) {
  6122. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6123. }
  6124. }
  6125. $list .= '</ul>';
  6126. $return .= Display::panelCollapse(
  6127. $this->name,
  6128. $list,
  6129. 'scorm-list',
  6130. null,
  6131. 'scorm-list-accordion',
  6132. 'scorm-list-collapse'
  6133. );
  6134. if ($update_audio === 'true') {
  6135. $return = $result['return_audio'];
  6136. }
  6137. return $return;
  6138. }
  6139. /**
  6140. * @param array $elements
  6141. * @param array $default_data
  6142. * @param array $default_content
  6143. *
  6144. * @return string
  6145. */
  6146. public function print_recursive($elements, $default_data, $default_content)
  6147. {
  6148. $return = '';
  6149. foreach ($elements as $key => $item) {
  6150. if (isset($item['load_data']) || empty($item['data'])) {
  6151. $item['data'] = $default_data[$item['load_data']];
  6152. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6153. }
  6154. $sub_list = '';
  6155. if (isset($item['type']) && $item['type'] == 'dir') {
  6156. // empty value
  6157. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6158. }
  6159. if (empty($item['children'])) {
  6160. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6161. $active = null;
  6162. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6163. $active = 'active';
  6164. }
  6165. $return .= Display::tag(
  6166. 'li',
  6167. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6168. ['id' => $key, 'class' => 'record li_container']
  6169. );
  6170. } else {
  6171. // Sections
  6172. $data = '';
  6173. if (isset($item['children'])) {
  6174. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6175. }
  6176. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6177. $return .= Display::tag(
  6178. 'li',
  6179. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6180. ['id' => $key, 'class' => 'record li_container']
  6181. );
  6182. }
  6183. }
  6184. return $return;
  6185. }
  6186. /**
  6187. * This function builds the action menu.
  6188. *
  6189. * @param bool $returnContent Optional
  6190. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6191. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6192. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6193. *
  6194. * @return string
  6195. */
  6196. public function build_action_menu(
  6197. $returnContent = false,
  6198. $showRequirementButtons = true,
  6199. $isConfigPage = false,
  6200. $allowExpand = true
  6201. ) {
  6202. $actionsLeft = '';
  6203. $actionsRight = '';
  6204. $actionsLeft .= Display::url(
  6205. Display::return_icon(
  6206. 'preview_view.png',
  6207. get_lang('Preview'),
  6208. '',
  6209. ICON_SIZE_MEDIUM
  6210. ),
  6211. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6212. 'action' => 'view',
  6213. 'lp_id' => $this->lp_id,
  6214. 'isStudentView' => 'true',
  6215. ])
  6216. );
  6217. $actionsLeft .= Display::url(
  6218. Display::return_icon(
  6219. 'upload_audio.png',
  6220. get_lang('UpdateAllAudioFragments'),
  6221. '',
  6222. ICON_SIZE_MEDIUM
  6223. ),
  6224. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6225. 'action' => 'admin_view',
  6226. 'lp_id' => $this->lp_id,
  6227. 'updateaudio' => 'true',
  6228. ])
  6229. );
  6230. if (!$isConfigPage) {
  6231. $actionsLeft .= Display::url(
  6232. Display::return_icon(
  6233. 'settings.png',
  6234. get_lang('CourseSettings'),
  6235. '',
  6236. ICON_SIZE_MEDIUM
  6237. ),
  6238. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6239. 'action' => 'edit',
  6240. 'lp_id' => $this->lp_id,
  6241. ])
  6242. );
  6243. } else {
  6244. $actionsLeft .= Display::url(
  6245. Display::return_icon(
  6246. 'edit.png',
  6247. get_lang('Edit'),
  6248. '',
  6249. ICON_SIZE_MEDIUM
  6250. ),
  6251. 'lp_controller.php?'.http_build_query([
  6252. 'action' => 'build',
  6253. 'lp_id' => $this->lp_id,
  6254. ]).'&'.api_get_cidreq()
  6255. );
  6256. }
  6257. if ($allowExpand) {
  6258. $actionsLeft .= Display::url(
  6259. Display::return_icon(
  6260. 'expand.png',
  6261. get_lang('Expand'),
  6262. ['id' => 'expand'],
  6263. ICON_SIZE_MEDIUM
  6264. ).
  6265. Display::return_icon(
  6266. 'contract.png',
  6267. get_lang('Collapse'),
  6268. ['id' => 'contract', 'class' => 'hide'],
  6269. ICON_SIZE_MEDIUM
  6270. ),
  6271. '#',
  6272. ['role' => 'button', 'id' => 'hide_bar_template']
  6273. );
  6274. }
  6275. if ($showRequirementButtons) {
  6276. $buttons = [
  6277. [
  6278. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6279. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6280. 'action' => 'set_previous_step_as_prerequisite',
  6281. 'lp_id' => $this->lp_id,
  6282. ]),
  6283. ],
  6284. [
  6285. 'title' => get_lang('ClearAllPrerequisites'),
  6286. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6287. 'action' => 'clear_prerequisites',
  6288. 'lp_id' => $this->lp_id,
  6289. ]),
  6290. ],
  6291. ];
  6292. $actionsRight = Display::groupButtonWithDropDown(
  6293. get_lang('PrerequisitesOptions'),
  6294. $buttons,
  6295. true
  6296. );
  6297. }
  6298. $toolbar = Display::toolbarAction(
  6299. 'actions-lp-controller',
  6300. [$actionsLeft, $actionsRight]
  6301. );
  6302. if ($returnContent) {
  6303. return $toolbar;
  6304. }
  6305. echo $toolbar;
  6306. }
  6307. /**
  6308. * Creates the default learning path folder.
  6309. *
  6310. * @param array $course
  6311. * @param int $creatorId
  6312. *
  6313. * @return bool
  6314. */
  6315. public static function generate_learning_path_folder($course, $creatorId = 0)
  6316. {
  6317. // Creating learning_path folder
  6318. $dir = '/learning_path';
  6319. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6320. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6321. $folder = false;
  6322. if (!is_dir($filepath.'/'.$dir)) {
  6323. $folderData = create_unexisting_directory(
  6324. $course,
  6325. $creatorId,
  6326. 0,
  6327. null,
  6328. 0,
  6329. $filepath,
  6330. $dir,
  6331. get_lang('LearningPaths'),
  6332. 0
  6333. );
  6334. if (!empty($folderData)) {
  6335. $folder = true;
  6336. }
  6337. } else {
  6338. $folder = true;
  6339. }
  6340. return $folder;
  6341. }
  6342. /**
  6343. * @param array $course
  6344. * @param string $lp_name
  6345. * @param int $creatorId
  6346. *
  6347. * @return array
  6348. */
  6349. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6350. {
  6351. $filepath = '';
  6352. $dir = '/learning_path/';
  6353. if (empty($lp_name)) {
  6354. $lp_name = $this->name;
  6355. }
  6356. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6357. $folder = self::generate_learning_path_folder($course, $creatorId);
  6358. // Limits title size
  6359. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6360. $dir = $dir.$title;
  6361. // Creating LP folder
  6362. $documentId = null;
  6363. if ($folder) {
  6364. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6365. if (!is_dir($filepath.'/'.$dir)) {
  6366. $folderData = create_unexisting_directory(
  6367. $course,
  6368. $creatorId,
  6369. 0,
  6370. 0,
  6371. 0,
  6372. $filepath,
  6373. $dir,
  6374. $lp_name
  6375. );
  6376. if (!empty($folderData)) {
  6377. $folder = true;
  6378. }
  6379. $documentId = $folderData['id'];
  6380. } else {
  6381. $folder = true;
  6382. }
  6383. $dir = $dir.'/';
  6384. if ($folder) {
  6385. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6386. }
  6387. }
  6388. if (empty($documentId)) {
  6389. $dir = api_remove_trailing_slash($dir);
  6390. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6391. }
  6392. $array = [
  6393. 'dir' => $dir,
  6394. 'filepath' => $filepath,
  6395. 'folder' => $folder,
  6396. 'id' => $documentId,
  6397. ];
  6398. return $array;
  6399. }
  6400. /**
  6401. * Create a new document //still needs some finetuning.
  6402. *
  6403. * @param array $courseInfo
  6404. * @param string $content
  6405. * @param string $title
  6406. * @param string $extension
  6407. * @param int $parentId
  6408. * @param int $creatorId creator id
  6409. *
  6410. * @return int
  6411. */
  6412. public function create_document(
  6413. $courseInfo,
  6414. $content = '',
  6415. $title = '',
  6416. $extension = 'html',
  6417. $parentId = 0,
  6418. $creatorId = 0
  6419. ) {
  6420. if (!empty($courseInfo)) {
  6421. $course_id = $courseInfo['real_id'];
  6422. } else {
  6423. $course_id = api_get_course_int_id();
  6424. }
  6425. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6426. $sessionId = api_get_session_id();
  6427. // Generates folder
  6428. $result = $this->generate_lp_folder($courseInfo);
  6429. $dir = $result['dir'];
  6430. if (empty($parentId) || $parentId == '/') {
  6431. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6432. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6433. if ($parentId === '/') {
  6434. $dir = '/';
  6435. }
  6436. // Please, do not modify this dirname formatting.
  6437. if (strstr($dir, '..')) {
  6438. $dir = '/';
  6439. }
  6440. if (!empty($dir[0]) && $dir[0] == '.') {
  6441. $dir = substr($dir, 1);
  6442. }
  6443. if (!empty($dir[0]) && $dir[0] != '/') {
  6444. $dir = '/'.$dir;
  6445. }
  6446. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6447. $dir .= '/';
  6448. }
  6449. } else {
  6450. $parentInfo = DocumentManager::get_document_data_by_id(
  6451. $parentId,
  6452. $courseInfo['code']
  6453. );
  6454. if (!empty($parentInfo)) {
  6455. $dir = $parentInfo['path'].'/';
  6456. }
  6457. }
  6458. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6459. if (!is_dir($filepath)) {
  6460. $dir = '/';
  6461. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6462. }
  6463. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6464. // is already escaped twice when it gets here.
  6465. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6466. if (!empty($title)) {
  6467. $title = api_replace_dangerous_char(stripslashes($title));
  6468. } else {
  6469. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6470. }
  6471. $title = disable_dangerous_file($title);
  6472. $filename = $title;
  6473. $content = !empty($content) ? $content : $_POST['content_lp'];
  6474. $tmp_filename = $filename;
  6475. $i = 0;
  6476. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6477. $tmp_filename = $filename.'_'.++$i;
  6478. }
  6479. $filename = $tmp_filename.'.'.$extension;
  6480. if ($extension == 'html') {
  6481. $content = stripslashes($content);
  6482. $content = str_replace(
  6483. api_get_path(WEB_COURSE_PATH),
  6484. api_get_path(REL_PATH).'courses/',
  6485. $content
  6486. );
  6487. // Change the path of mp3 to absolute.
  6488. // The first regexp deals with :// urls.
  6489. $content = preg_replace(
  6490. "|(flashvars=\"file=)([^:/]+)/|",
  6491. "$1".api_get_path(
  6492. REL_COURSE_PATH
  6493. ).$courseInfo['path'].'/document/',
  6494. $content
  6495. );
  6496. // The second regexp deals with audio/ urls.
  6497. $content = preg_replace(
  6498. "|(flashvars=\"file=)([^/]+)/|",
  6499. "$1".api_get_path(
  6500. REL_COURSE_PATH
  6501. ).$courseInfo['path'].'/document/$2/',
  6502. $content
  6503. );
  6504. // For flv player: To prevent edition problem with firefox,
  6505. // we have to use a strange tip (don't blame me please).
  6506. $content = str_replace(
  6507. '</body>',
  6508. '<style type="text/css">body{}</style></body>',
  6509. $content
  6510. );
  6511. }
  6512. if (!file_exists($filepath.$filename)) {
  6513. if ($fp = @fopen($filepath.$filename, 'w')) {
  6514. fputs($fp, $content);
  6515. fclose($fp);
  6516. $file_size = filesize($filepath.$filename);
  6517. $save_file_path = $dir.$filename;
  6518. $document_id = add_document(
  6519. $courseInfo,
  6520. $save_file_path,
  6521. 'file',
  6522. $file_size,
  6523. $tmp_filename,
  6524. '',
  6525. 0, //readonly
  6526. true,
  6527. null,
  6528. $sessionId,
  6529. $creatorId
  6530. );
  6531. if ($document_id) {
  6532. api_item_property_update(
  6533. $courseInfo,
  6534. TOOL_DOCUMENT,
  6535. $document_id,
  6536. 'DocumentAdded',
  6537. $creatorId,
  6538. null,
  6539. null,
  6540. null,
  6541. null,
  6542. $sessionId
  6543. );
  6544. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6545. $new_title = $originalTitle;
  6546. if ($new_comment || $new_title) {
  6547. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6548. $ct = '';
  6549. if ($new_comment) {
  6550. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6551. }
  6552. if ($new_title) {
  6553. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6554. }
  6555. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6556. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6557. Database::query($sql);
  6558. }
  6559. }
  6560. return $document_id;
  6561. }
  6562. }
  6563. }
  6564. /**
  6565. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6566. *
  6567. * @param array $_course array
  6568. */
  6569. public function edit_document($_course)
  6570. {
  6571. $course_id = api_get_course_int_id();
  6572. $urlAppend = api_get_configuration_value('url_append');
  6573. // Please, do not modify this dirname formatting.
  6574. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6575. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6576. if (strstr($dir, '..')) {
  6577. $dir = '/';
  6578. }
  6579. if (isset($dir[0]) && $dir[0] == '.') {
  6580. $dir = substr($dir, 1);
  6581. }
  6582. if (isset($dir[0]) && $dir[0] != '/') {
  6583. $dir = '/'.$dir;
  6584. }
  6585. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6586. $dir .= '/';
  6587. }
  6588. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6589. if (!is_dir($filepath)) {
  6590. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6591. }
  6592. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6593. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6594. $document_id = (int) $_POST['path'];
  6595. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6596. if (empty($documentInfo)) {
  6597. // Try with iid
  6598. $table = Database::get_course_table(TABLE_DOCUMENT);
  6599. $sql = "SELECT id, path FROM $table
  6600. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6601. $res_doc = Database::query($sql);
  6602. $row = Database::fetch_array($res_doc);
  6603. if ($row) {
  6604. $document_id = $row['id'];
  6605. $documentPath = $row['path'];
  6606. }
  6607. } else {
  6608. $documentPath = $documentInfo['path'];
  6609. }
  6610. $content = stripslashes($_POST['content_lp']);
  6611. $file = $filepath.$documentPath;
  6612. if (!file_exists($file)) {
  6613. return false;
  6614. }
  6615. if ($fp = @fopen($file, 'w')) {
  6616. $content = str_replace(
  6617. api_get_path(WEB_COURSE_PATH),
  6618. $urlAppend.api_get_path(REL_COURSE_PATH),
  6619. $content
  6620. );
  6621. // Change the path of mp3 to absolute.
  6622. // The first regexp deals with :// urls.
  6623. $content = preg_replace(
  6624. "|(flashvars=\"file=)([^:/]+)/|",
  6625. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6626. $content
  6627. );
  6628. // The second regexp deals with audio/ urls.
  6629. $content = preg_replace(
  6630. "|(flashvars=\"file=)([^:/]+)/|",
  6631. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6632. $content
  6633. );
  6634. fputs($fp, $content);
  6635. fclose($fp);
  6636. $sql = "UPDATE $table_doc SET
  6637. title='".Database::escape_string($_POST['title'])."'
  6638. WHERE c_id = $course_id AND id = ".$document_id;
  6639. Database::query($sql);
  6640. }
  6641. }
  6642. }
  6643. /**
  6644. * Displays the selected item, with a panel for manipulating the item.
  6645. *
  6646. * @param int $item_id
  6647. * @param string $msg
  6648. * @param bool $show_actions
  6649. *
  6650. * @return string
  6651. */
  6652. public function display_item($item_id, $msg = null, $show_actions = true)
  6653. {
  6654. $course_id = api_get_course_int_id();
  6655. $return = '';
  6656. if (is_numeric($item_id)) {
  6657. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6658. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6659. WHERE lp.iid = ".intval($item_id);
  6660. $result = Database::query($sql);
  6661. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6662. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6663. // Prevents wrong parent selection for document, see Bug#1251.
  6664. if ($row['item_type'] != 'dir') {
  6665. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6666. }
  6667. if ($show_actions) {
  6668. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6669. }
  6670. $return .= '<div style="padding:10px;">';
  6671. if ($msg != '') {
  6672. $return .= $msg;
  6673. }
  6674. $return .= '<h3>'.$row['title'].'</h3>';
  6675. switch ($row['item_type']) {
  6676. case TOOL_THREAD:
  6677. $link = $this->rl_get_resource_link_for_learnpath(
  6678. $course_id,
  6679. $row['lp_id'],
  6680. $item_id,
  6681. 0
  6682. );
  6683. $return .= Display::url(
  6684. get_lang('GoToThread'),
  6685. $link,
  6686. ['class' => 'btn btn-primary']
  6687. );
  6688. break;
  6689. case TOOL_FORUM:
  6690. $return .= Display::url(
  6691. get_lang('GoToForum'),
  6692. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6693. ['class' => 'btn btn-primary']
  6694. );
  6695. break;
  6696. case TOOL_QUIZ:
  6697. if (!empty($row['path'])) {
  6698. $exercise = new Exercise();
  6699. $exercise->read($row['path']);
  6700. $return .= $exercise->description.'<br />';
  6701. $return .= Display::url(
  6702. get_lang('GoToExercise'),
  6703. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6704. ['class' => 'btn btn-primary']
  6705. );
  6706. }
  6707. break;
  6708. case TOOL_LP_FINAL_ITEM:
  6709. $return .= $this->getSavedFinalItem();
  6710. break;
  6711. case TOOL_DOCUMENT:
  6712. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6713. $sql_doc = "SELECT path FROM ".$tbl_doc."
  6714. WHERE c_id = ".$course_id." AND iid = ".intval($row['path']);
  6715. $result = Database::query($sql_doc);
  6716. $path_file = Database::result($result, 0, 0);
  6717. $path_parts = pathinfo($path_file);
  6718. // TODO: Correct the following naive comparisons.
  6719. if (in_array($path_parts['extension'], [
  6720. 'html',
  6721. 'txt',
  6722. 'png',
  6723. 'jpg',
  6724. 'JPG',
  6725. 'jpeg',
  6726. 'JPEG',
  6727. 'gif',
  6728. 'swf',
  6729. 'pdf',
  6730. 'htm',
  6731. ])) {
  6732. $return .= $this->display_document($row['path'], true, true);
  6733. }
  6734. break;
  6735. case TOOL_HOTPOTATOES:
  6736. $return .= $this->display_document($row['path'], false, true);
  6737. break;
  6738. }
  6739. $return .= '</div>';
  6740. }
  6741. }
  6742. return $return;
  6743. }
  6744. /**
  6745. * Shows the needed forms for editing a specific item.
  6746. *
  6747. * @param int $item_id
  6748. *
  6749. * @throws Exception
  6750. * @throws HTML_QuickForm_Error
  6751. *
  6752. * @return string
  6753. */
  6754. public function display_edit_item($item_id)
  6755. {
  6756. $course_id = api_get_course_int_id();
  6757. $return = '';
  6758. $item_id = (int) $item_id;
  6759. if (empty($item_id)) {
  6760. return '';
  6761. }
  6762. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6763. $sql = "SELECT * FROM $tbl_lp_item
  6764. WHERE iid = ".$item_id;
  6765. $res = Database::query($sql);
  6766. $row = Database::fetch_array($res);
  6767. switch ($row['item_type']) {
  6768. case 'dir':
  6769. case 'asset':
  6770. case 'sco':
  6771. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6772. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6773. $return .= $this->display_item_form(
  6774. $row['item_type'],
  6775. get_lang('EditCurrentChapter').' :',
  6776. 'edit',
  6777. $item_id,
  6778. $row
  6779. );
  6780. } else {
  6781. $return .= $this->display_item_form(
  6782. $row['item_type'],
  6783. get_lang('EditCurrentChapter').' :',
  6784. 'edit_item',
  6785. $item_id,
  6786. $row
  6787. );
  6788. }
  6789. break;
  6790. case TOOL_DOCUMENT:
  6791. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6792. $sql = "SELECT lp.*, doc.path as dir
  6793. FROM $tbl_lp_item as lp
  6794. LEFT JOIN $tbl_doc as doc
  6795. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6796. WHERE
  6797. doc.c_id = $course_id AND
  6798. lp.iid = ".$item_id;
  6799. $res_step = Database::query($sql);
  6800. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6801. $return .= $this->display_manipulate(
  6802. $item_id,
  6803. $row['item_type']
  6804. );
  6805. $return .= $this->display_document_form(
  6806. 'edit',
  6807. $item_id,
  6808. $row_step
  6809. );
  6810. break;
  6811. case TOOL_LINK:
  6812. $link_id = (string) $row['path'];
  6813. if (ctype_digit($link_id)) {
  6814. $tbl_link = Database::get_course_table(TABLE_LINK);
  6815. $sql_select = 'SELECT url FROM '.$tbl_link.'
  6816. WHERE c_id = '.$course_id.' AND iid = '.intval($link_id);
  6817. $res_link = Database::query($sql_select);
  6818. $row_link = Database::fetch_array($res_link);
  6819. if (is_array($row_link)) {
  6820. $row['url'] = $row_link['url'];
  6821. }
  6822. }
  6823. $return .= $this->display_manipulate(
  6824. $item_id,
  6825. $row['item_type']
  6826. );
  6827. $return .= $this->display_link_form('edit', $item_id, $row);
  6828. break;
  6829. case TOOL_LP_FINAL_ITEM:
  6830. Session::write('finalItem', true);
  6831. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6832. $sql = "SELECT lp.*, doc.path as dir
  6833. FROM $tbl_lp_item as lp
  6834. LEFT JOIN $tbl_doc as doc
  6835. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6836. WHERE
  6837. doc.c_id = $course_id AND
  6838. lp.iid = ".$item_id;
  6839. $res_step = Database::query($sql);
  6840. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6841. $return .= $this->display_manipulate(
  6842. $item_id,
  6843. $row['item_type']
  6844. );
  6845. $return .= $this->display_document_form(
  6846. 'edit',
  6847. $item_id,
  6848. $row_step
  6849. );
  6850. break;
  6851. case TOOL_QUIZ:
  6852. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6853. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6854. break;
  6855. case TOOL_HOTPOTATOES:
  6856. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6857. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6858. break;
  6859. case TOOL_STUDENTPUBLICATION:
  6860. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6861. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6862. break;
  6863. case TOOL_FORUM:
  6864. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6865. $return .= $this->display_forum_form('edit', $item_id, $row);
  6866. break;
  6867. case TOOL_THREAD:
  6868. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6869. $return .= $this->display_thread_form('edit', $item_id, $row);
  6870. break;
  6871. }
  6872. return $return;
  6873. }
  6874. /**
  6875. * Function that displays a list with al the resources that
  6876. * could be added to the learning path.
  6877. *
  6878. * @throws Exception
  6879. * @throws HTML_QuickForm_Error
  6880. *
  6881. * @return bool
  6882. */
  6883. public function display_resources()
  6884. {
  6885. $course_code = api_get_course_id();
  6886. // Get all the docs.
  6887. $documents = $this->get_documents(true);
  6888. // Get all the exercises.
  6889. $exercises = $this->get_exercises();
  6890. // Get all the links.
  6891. $links = $this->get_links();
  6892. // Get all the student publications.
  6893. $works = $this->get_student_publications();
  6894. // Get all the forums.
  6895. $forums = $this->get_forums(null, $course_code);
  6896. // Get the final item form (see BT#11048) .
  6897. $finish = $this->getFinalItemForm();
  6898. $headers = [
  6899. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6900. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6901. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6902. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6903. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6904. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6905. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6906. ];
  6907. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6908. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6909. echo Display::tabs(
  6910. $headers,
  6911. [
  6912. $documents,
  6913. $exercises,
  6914. $links,
  6915. $works,
  6916. $forums,
  6917. $dir,
  6918. $finish,
  6919. ],
  6920. 'resource_tab'
  6921. );
  6922. return true;
  6923. }
  6924. /**
  6925. * Returns the extension of a document.
  6926. *
  6927. * @param string $filename
  6928. *
  6929. * @return string Extension (part after the last dot)
  6930. */
  6931. public function get_extension($filename)
  6932. {
  6933. $explode = explode('.', $filename);
  6934. return $explode[count($explode) - 1];
  6935. }
  6936. /**
  6937. * Displays a document by id.
  6938. *
  6939. * @param int $id
  6940. * @param bool $show_title
  6941. * @param bool $iframe
  6942. * @param bool $edit_link
  6943. *
  6944. * @return string
  6945. */
  6946. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6947. {
  6948. $_course = api_get_course_info();
  6949. $course_id = api_get_course_int_id();
  6950. $id = (int) $id;
  6951. $return = '';
  6952. $table = Database::get_course_table(TABLE_DOCUMENT);
  6953. $sql_doc = "SELECT * FROM $table
  6954. WHERE c_id = $course_id AND iid = $id";
  6955. $res_doc = Database::query($sql_doc);
  6956. $row_doc = Database::fetch_array($res_doc);
  6957. // TODO: Add a path filter.
  6958. if ($iframe) {
  6959. $return .= '<iframe id="learnpath_preview_frame" frameborder="0" height="400" width="100%" scrolling="auto" src="'.api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.str_replace('%2F', '/', urlencode($row_doc['path'])).'?'.api_get_cidreq().'"></iframe>';
  6960. } else {
  6961. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6962. }
  6963. return $return;
  6964. }
  6965. /**
  6966. * Return HTML form to add/edit a quiz.
  6967. *
  6968. * @param string $action Action (add/edit)
  6969. * @param int $id Item ID if already exists
  6970. * @param mixed $extra_info Extra information (quiz ID if integer)
  6971. *
  6972. * @throws Exception
  6973. *
  6974. * @return string HTML form
  6975. */
  6976. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6977. {
  6978. $course_id = api_get_course_int_id();
  6979. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6980. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6981. if ($id != 0 && is_array($extra_info)) {
  6982. $item_title = $extra_info['title'];
  6983. $item_description = $extra_info['description'];
  6984. } elseif (is_numeric($extra_info)) {
  6985. $sql = "SELECT title, description
  6986. FROM $tbl_quiz
  6987. WHERE c_id = $course_id AND iid = ".$extra_info;
  6988. $result = Database::query($sql);
  6989. $row = Database::fetch_array($result);
  6990. $item_title = $row['title'];
  6991. $item_description = $row['description'];
  6992. } else {
  6993. $item_title = '';
  6994. $item_description = '';
  6995. }
  6996. $item_title = Security::remove_XSS($item_title);
  6997. $item_description = Security::remove_XSS($item_description);
  6998. if ($id != 0 && is_array($extra_info)) {
  6999. $parent = $extra_info['parent_item_id'];
  7000. } else {
  7001. $parent = 0;
  7002. }
  7003. $sql = "SELECT * FROM $tbl_lp_item
  7004. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7005. $result = Database::query($sql);
  7006. $arrLP = [];
  7007. while ($row = Database::fetch_array($result)) {
  7008. $arrLP[] = [
  7009. 'id' => $row['iid'],
  7010. 'item_type' => $row['item_type'],
  7011. 'title' => $row['title'],
  7012. 'path' => $row['path'],
  7013. 'description' => $row['description'],
  7014. 'parent_item_id' => $row['parent_item_id'],
  7015. 'previous_item_id' => $row['previous_item_id'],
  7016. 'next_item_id' => $row['next_item_id'],
  7017. 'display_order' => $row['display_order'],
  7018. 'max_score' => $row['max_score'],
  7019. 'min_score' => $row['min_score'],
  7020. 'mastery_score' => $row['mastery_score'],
  7021. 'prerequisite' => $row['prerequisite'],
  7022. 'max_time_allowed' => $row['max_time_allowed'],
  7023. ];
  7024. }
  7025. $this->tree_array($arrLP);
  7026. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7027. unset($this->arrMenu);
  7028. $form = new FormValidator(
  7029. 'quiz_form',
  7030. 'POST',
  7031. $this->getCurrentBuildingModeURL()
  7032. );
  7033. $defaults = [];
  7034. if ($action == 'add') {
  7035. $legend = get_lang('CreateTheExercise');
  7036. } elseif ($action == 'move') {
  7037. $legend = get_lang('MoveTheCurrentExercise');
  7038. } else {
  7039. $legend = get_lang('EditCurrentExecice');
  7040. }
  7041. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7042. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7043. }
  7044. $form->addHeader($legend);
  7045. if ($action != 'move') {
  7046. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7047. $defaults['title'] = $item_title;
  7048. }
  7049. // Select for Parent item, root or chapter
  7050. $selectParent = $form->addSelect(
  7051. 'parent',
  7052. get_lang('Parent'),
  7053. [],
  7054. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7055. );
  7056. $selectParent->addOption($this->name, 0);
  7057. $arrHide = [
  7058. $id,
  7059. ];
  7060. for ($i = 0; $i < count($arrLP); $i++) {
  7061. if ($action != 'add') {
  7062. if (
  7063. ($arrLP[$i]['item_type'] == 'dir') &&
  7064. !in_array($arrLP[$i]['id'], $arrHide) &&
  7065. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7066. ) {
  7067. $selectParent->addOption(
  7068. $arrLP[$i]['title'],
  7069. $arrLP[$i]['id'],
  7070. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7071. );
  7072. if ($parent == $arrLP[$i]['id']) {
  7073. $selectParent->setSelected($arrLP[$i]['id']);
  7074. }
  7075. } else {
  7076. $arrHide[] = $arrLP[$i]['id'];
  7077. }
  7078. } else {
  7079. if ($arrLP[$i]['item_type'] == 'dir') {
  7080. $selectParent->addOption(
  7081. $arrLP[$i]['title'],
  7082. $arrLP[$i]['id'],
  7083. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7084. );
  7085. if ($parent == $arrLP[$i]['id']) {
  7086. $selectParent->setSelected($arrLP[$i]['id']);
  7087. }
  7088. }
  7089. }
  7090. }
  7091. if (is_array($arrLP)) {
  7092. reset($arrLP);
  7093. }
  7094. $selectPrevious = $form->addSelect(
  7095. 'previous',
  7096. get_lang('Position'),
  7097. [],
  7098. ['id' => 'previous']
  7099. );
  7100. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7101. for ($i = 0; $i < count($arrLP); $i++) {
  7102. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7103. $arrLP[$i]['id'] != $id
  7104. ) {
  7105. $selectPrevious->addOption(
  7106. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7107. $arrLP[$i]['id']
  7108. );
  7109. if (is_array($extra_info)) {
  7110. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7111. $selectPrevious->setSelected($arrLP[$i]['id']);
  7112. }
  7113. } elseif ($action == 'add') {
  7114. $selectPrevious->setSelected($arrLP[$i]['id']);
  7115. }
  7116. }
  7117. }
  7118. if ($action != 'move') {
  7119. $arrHide = [];
  7120. for ($i = 0; $i < count($arrLP); $i++) {
  7121. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7122. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7123. }
  7124. }
  7125. }
  7126. if ($action == 'add') {
  7127. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7128. } else {
  7129. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7130. }
  7131. if ($action == 'move') {
  7132. $form->addHidden('title', $item_title);
  7133. $form->addHidden('description', $item_description);
  7134. }
  7135. if (is_numeric($extra_info)) {
  7136. $form->addHidden('path', $extra_info);
  7137. } elseif (is_array($extra_info)) {
  7138. $form->addHidden('path', $extra_info['path']);
  7139. }
  7140. $form->addHidden('type', TOOL_QUIZ);
  7141. $form->addHidden('post_time', time());
  7142. $form->setDefaults($defaults);
  7143. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7144. }
  7145. /**
  7146. * Addition of Hotpotatoes tests.
  7147. *
  7148. * @param string $action
  7149. * @param int $id Internal ID of the item
  7150. * @param string $extra_info
  7151. *
  7152. * @return string HTML structure to display the hotpotatoes addition formular
  7153. */
  7154. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7155. {
  7156. $course_id = api_get_course_int_id();
  7157. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7158. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7159. if ($id != 0 && is_array($extra_info)) {
  7160. $item_title = stripslashes($extra_info['title']);
  7161. $item_description = stripslashes($extra_info['description']);
  7162. } elseif (is_numeric($extra_info)) {
  7163. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7164. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7165. WHERE
  7166. c_id = ".$course_id." AND
  7167. path LIKE '".$uploadPath."/%/%htm%' AND
  7168. iid = ".(int) $extra_info."
  7169. ORDER BY iid ASC";
  7170. $res_hot = Database::query($sql);
  7171. $row = Database::fetch_array($res_hot);
  7172. $item_title = $row['title'];
  7173. $item_description = $row['description'];
  7174. if (!empty($row['comment'])) {
  7175. $item_title = $row['comment'];
  7176. }
  7177. } else {
  7178. $item_title = '';
  7179. $item_description = '';
  7180. }
  7181. if ($id != 0 && is_array($extra_info)) {
  7182. $parent = $extra_info['parent_item_id'];
  7183. } else {
  7184. $parent = 0;
  7185. }
  7186. $sql = "SELECT * FROM $tbl_lp_item
  7187. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7188. $result = Database::query($sql);
  7189. $arrLP = [];
  7190. while ($row = Database::fetch_array($result)) {
  7191. $arrLP[] = [
  7192. 'id' => $row['id'],
  7193. 'item_type' => $row['item_type'],
  7194. 'title' => $row['title'],
  7195. 'path' => $row['path'],
  7196. 'description' => $row['description'],
  7197. 'parent_item_id' => $row['parent_item_id'],
  7198. 'previous_item_id' => $row['previous_item_id'],
  7199. 'next_item_id' => $row['next_item_id'],
  7200. 'display_order' => $row['display_order'],
  7201. 'max_score' => $row['max_score'],
  7202. 'min_score' => $row['min_score'],
  7203. 'mastery_score' => $row['mastery_score'],
  7204. 'prerequisite' => $row['prerequisite'],
  7205. 'max_time_allowed' => $row['max_time_allowed'],
  7206. ];
  7207. }
  7208. $legend = '<legend>';
  7209. if ($action == 'add') {
  7210. $legend .= get_lang('CreateTheExercise');
  7211. } elseif ($action == 'move') {
  7212. $legend .= get_lang('MoveTheCurrentExercise');
  7213. } else {
  7214. $legend .= get_lang('EditCurrentExecice');
  7215. }
  7216. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7217. $legend .= Display:: return_message(
  7218. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7219. );
  7220. }
  7221. $legend .= '</legend>';
  7222. $return = '<form method="POST">';
  7223. $return .= $legend;
  7224. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7225. $return .= '<tr>';
  7226. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7227. $return .= '<td class="input">';
  7228. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7229. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7230. $arrHide = [
  7231. $id,
  7232. ];
  7233. if (count($arrLP) > 0) {
  7234. for ($i = 0; $i < count($arrLP); $i++) {
  7235. if ($action != 'add') {
  7236. if ($arrLP[$i]['item_type'] == 'dir' &&
  7237. !in_array($arrLP[$i]['id'], $arrHide) &&
  7238. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7239. ) {
  7240. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7241. } else {
  7242. $arrHide[] = $arrLP[$i]['id'];
  7243. }
  7244. } else {
  7245. if ($arrLP[$i]['item_type'] == 'dir') {
  7246. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7247. }
  7248. }
  7249. }
  7250. reset($arrLP);
  7251. }
  7252. $return .= '</select>';
  7253. $return .= '</td>';
  7254. $return .= '</tr>';
  7255. $return .= '<tr>';
  7256. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7257. $return .= '<td class="input">';
  7258. $return .= '<select id="previous" name="previous" size="1">';
  7259. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7260. for ($i = 0; $i < count($arrLP); $i++) {
  7261. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7262. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7263. $selected = 'selected="selected" ';
  7264. } elseif ($action == 'add') {
  7265. $selected = 'selected="selected" ';
  7266. } else {
  7267. $selected = '';
  7268. }
  7269. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7270. }
  7271. }
  7272. $return .= '</select>';
  7273. $return .= '</td>';
  7274. $return .= '</tr>';
  7275. if ($action != 'move') {
  7276. $return .= '<tr>';
  7277. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7278. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7279. $return .= '</tr>';
  7280. $id_prerequisite = 0;
  7281. if (is_array($arrLP) && count($arrLP) > 0) {
  7282. foreach ($arrLP as $key => $value) {
  7283. if ($value['id'] == $id) {
  7284. $id_prerequisite = $value['prerequisite'];
  7285. break;
  7286. }
  7287. }
  7288. $arrHide = [];
  7289. for ($i = 0; $i < count($arrLP); $i++) {
  7290. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7291. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7292. }
  7293. }
  7294. }
  7295. }
  7296. $return .= '<tr>';
  7297. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7298. get_lang('SaveHotpotatoes').'</button></td>';
  7299. $return .= '</tr>';
  7300. $return .= '</table>';
  7301. if ($action == 'move') {
  7302. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7303. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7304. }
  7305. if (is_numeric($extra_info)) {
  7306. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7307. } elseif (is_array($extra_info)) {
  7308. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7309. }
  7310. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7311. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7312. $return .= '</form>';
  7313. return $return;
  7314. }
  7315. /**
  7316. * Return the form to display the forum edit/add option.
  7317. *
  7318. * @param string $action
  7319. * @param int $id ID of the lp_item if already exists
  7320. * @param string $extra_info
  7321. *
  7322. * @throws Exception
  7323. *
  7324. * @return string HTML form
  7325. */
  7326. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7327. {
  7328. $course_id = api_get_course_int_id();
  7329. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7330. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7331. if ($id != 0 && is_array($extra_info)) {
  7332. $item_title = stripslashes($extra_info['title']);
  7333. } elseif (is_numeric($extra_info)) {
  7334. $sql = "SELECT forum_title as title, forum_comment as comment
  7335. FROM ".$tbl_forum."
  7336. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7337. $result = Database::query($sql);
  7338. $row = Database::fetch_array($result);
  7339. $item_title = $row['title'];
  7340. $item_description = $row['comment'];
  7341. } else {
  7342. $item_title = '';
  7343. $item_description = '';
  7344. }
  7345. if ($id != 0 && is_array($extra_info)) {
  7346. $parent = $extra_info['parent_item_id'];
  7347. } else {
  7348. $parent = 0;
  7349. }
  7350. $sql = "SELECT * FROM $tbl_lp_item
  7351. WHERE
  7352. c_id = $course_id AND
  7353. lp_id = ".$this->lp_id;
  7354. $result = Database::query($sql);
  7355. $arrLP = [];
  7356. while ($row = Database::fetch_array($result)) {
  7357. $arrLP[] = [
  7358. 'id' => $row['iid'],
  7359. 'item_type' => $row['item_type'],
  7360. 'title' => $row['title'],
  7361. 'path' => $row['path'],
  7362. 'description' => $row['description'],
  7363. 'parent_item_id' => $row['parent_item_id'],
  7364. 'previous_item_id' => $row['previous_item_id'],
  7365. 'next_item_id' => $row['next_item_id'],
  7366. 'display_order' => $row['display_order'],
  7367. 'max_score' => $row['max_score'],
  7368. 'min_score' => $row['min_score'],
  7369. 'mastery_score' => $row['mastery_score'],
  7370. 'prerequisite' => $row['prerequisite'],
  7371. ];
  7372. }
  7373. $this->tree_array($arrLP);
  7374. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7375. unset($this->arrMenu);
  7376. if ($action == 'add') {
  7377. $legend = get_lang('CreateTheForum');
  7378. } elseif ($action == 'move') {
  7379. $legend = get_lang('MoveTheCurrentForum');
  7380. } else {
  7381. $legend = get_lang('EditCurrentForum');
  7382. }
  7383. $form = new FormValidator(
  7384. 'forum_form',
  7385. 'POST',
  7386. $this->getCurrentBuildingModeURL()
  7387. );
  7388. $defaults = [];
  7389. $form->addHeader($legend);
  7390. if ($action != 'move') {
  7391. $form->addText(
  7392. 'title',
  7393. get_lang('Title'),
  7394. true,
  7395. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7396. );
  7397. $defaults['title'] = $item_title;
  7398. }
  7399. $selectParent = $form->addSelect(
  7400. 'parent',
  7401. get_lang('Parent'),
  7402. [],
  7403. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7404. );
  7405. $selectParent->addOption($this->name, 0);
  7406. $arrHide = [
  7407. $id,
  7408. ];
  7409. for ($i = 0; $i < count($arrLP); $i++) {
  7410. if ($action != 'add') {
  7411. if ($arrLP[$i]['item_type'] == 'dir' &&
  7412. !in_array($arrLP[$i]['id'], $arrHide) &&
  7413. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7414. ) {
  7415. $selectParent->addOption(
  7416. $arrLP[$i]['title'],
  7417. $arrLP[$i]['id'],
  7418. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7419. );
  7420. if ($parent == $arrLP[$i]['id']) {
  7421. $selectParent->setSelected($arrLP[$i]['id']);
  7422. }
  7423. } else {
  7424. $arrHide[] = $arrLP[$i]['id'];
  7425. }
  7426. } else {
  7427. if ($arrLP[$i]['item_type'] == 'dir') {
  7428. $selectParent->addOption(
  7429. $arrLP[$i]['title'],
  7430. $arrLP[$i]['id'],
  7431. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7432. );
  7433. if ($parent == $arrLP[$i]['id']) {
  7434. $selectParent->setSelected($arrLP[$i]['id']);
  7435. }
  7436. }
  7437. }
  7438. }
  7439. if (is_array($arrLP)) {
  7440. reset($arrLP);
  7441. }
  7442. $selectPrevious = $form->addSelect(
  7443. 'previous',
  7444. get_lang('Position'),
  7445. [],
  7446. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7447. );
  7448. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7449. for ($i = 0; $i < count($arrLP); $i++) {
  7450. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7451. $arrLP[$i]['id'] != $id
  7452. ) {
  7453. $selectPrevious->addOption(
  7454. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7455. $arrLP[$i]['id']
  7456. );
  7457. if (isset($extra_info['previous_item_id']) &&
  7458. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7459. ) {
  7460. $selectPrevious->setSelected($arrLP[$i]['id']);
  7461. } elseif ($action == 'add') {
  7462. $selectPrevious->setSelected($arrLP[$i]['id']);
  7463. }
  7464. }
  7465. }
  7466. if ($action != 'move') {
  7467. $id_prerequisite = 0;
  7468. if (is_array($arrLP)) {
  7469. foreach ($arrLP as $key => $value) {
  7470. if ($value['id'] == $id) {
  7471. $id_prerequisite = $value['prerequisite'];
  7472. break;
  7473. }
  7474. }
  7475. }
  7476. $arrHide = [];
  7477. for ($i = 0; $i < count($arrLP); $i++) {
  7478. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7479. if (isset($extra_info['previous_item_id']) &&
  7480. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7481. ) {
  7482. $s_selected_position = $arrLP[$i]['id'];
  7483. } elseif ($action == 'add') {
  7484. $s_selected_position = 0;
  7485. }
  7486. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7487. }
  7488. }
  7489. }
  7490. if ($action == 'add') {
  7491. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7492. } else {
  7493. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7494. }
  7495. if ($action == 'move') {
  7496. $form->addHidden('title', $item_title);
  7497. $form->addHidden('description', $item_description);
  7498. }
  7499. if (is_numeric($extra_info)) {
  7500. $form->addHidden('path', $extra_info);
  7501. } elseif (is_array($extra_info)) {
  7502. $form->addHidden('path', $extra_info['path']);
  7503. }
  7504. $form->addHidden('type', TOOL_FORUM);
  7505. $form->addHidden('post_time', time());
  7506. $form->setDefaults($defaults);
  7507. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7508. }
  7509. /**
  7510. * Return HTML form to add/edit forum threads.
  7511. *
  7512. * @param string $action
  7513. * @param int $id Item ID if already exists in learning path
  7514. * @param string $extra_info
  7515. *
  7516. * @throws Exception
  7517. *
  7518. * @return string HTML form
  7519. */
  7520. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7521. {
  7522. $course_id = api_get_course_int_id();
  7523. if (empty($course_id)) {
  7524. return null;
  7525. }
  7526. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7527. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7528. if ($id != 0 && is_array($extra_info)) {
  7529. $item_title = stripslashes($extra_info['title']);
  7530. } elseif (is_numeric($extra_info)) {
  7531. $sql = "SELECT thread_title as title FROM $tbl_forum
  7532. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7533. $result = Database::query($sql);
  7534. $row = Database::fetch_array($result);
  7535. $item_title = $row['title'];
  7536. $item_description = '';
  7537. } else {
  7538. $item_title = '';
  7539. $item_description = '';
  7540. }
  7541. if ($id != 0 && is_array($extra_info)) {
  7542. $parent = $extra_info['parent_item_id'];
  7543. } else {
  7544. $parent = 0;
  7545. }
  7546. $sql = "SELECT * FROM $tbl_lp_item
  7547. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7548. $result = Database::query($sql);
  7549. $arrLP = [];
  7550. while ($row = Database::fetch_array($result)) {
  7551. $arrLP[] = [
  7552. 'id' => $row['iid'],
  7553. 'item_type' => $row['item_type'],
  7554. 'title' => $row['title'],
  7555. 'path' => $row['path'],
  7556. 'description' => $row['description'],
  7557. 'parent_item_id' => $row['parent_item_id'],
  7558. 'previous_item_id' => $row['previous_item_id'],
  7559. 'next_item_id' => $row['next_item_id'],
  7560. 'display_order' => $row['display_order'],
  7561. 'max_score' => $row['max_score'],
  7562. 'min_score' => $row['min_score'],
  7563. 'mastery_score' => $row['mastery_score'],
  7564. 'prerequisite' => $row['prerequisite'],
  7565. ];
  7566. }
  7567. $this->tree_array($arrLP);
  7568. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7569. unset($this->arrMenu);
  7570. $form = new FormValidator(
  7571. 'thread_form',
  7572. 'POST',
  7573. $this->getCurrentBuildingModeURL()
  7574. );
  7575. $defaults = [];
  7576. if ($action == 'add') {
  7577. $legend = get_lang('CreateTheForum');
  7578. } elseif ($action == 'move') {
  7579. $legend = get_lang('MoveTheCurrentForum');
  7580. } else {
  7581. $legend = get_lang('EditCurrentForum');
  7582. }
  7583. $form->addHeader($legend);
  7584. $selectParent = $form->addSelect(
  7585. 'parent',
  7586. get_lang('Parent'),
  7587. [],
  7588. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7589. );
  7590. $selectParent->addOption($this->name, 0);
  7591. $arrHide = [
  7592. $id,
  7593. ];
  7594. for ($i = 0; $i < count($arrLP); $i++) {
  7595. if ($action != 'add') {
  7596. if (
  7597. ($arrLP[$i]['item_type'] == 'dir') &&
  7598. !in_array($arrLP[$i]['id'], $arrHide) &&
  7599. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7600. ) {
  7601. $selectParent->addOption(
  7602. $arrLP[$i]['title'],
  7603. $arrLP[$i]['id'],
  7604. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7605. );
  7606. if ($parent == $arrLP[$i]['id']) {
  7607. $selectParent->setSelected($arrLP[$i]['id']);
  7608. }
  7609. } else {
  7610. $arrHide[] = $arrLP[$i]['id'];
  7611. }
  7612. } else {
  7613. if ($arrLP[$i]['item_type'] == 'dir') {
  7614. $selectParent->addOption(
  7615. $arrLP[$i]['title'],
  7616. $arrLP[$i]['id'],
  7617. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7618. );
  7619. if ($parent == $arrLP[$i]['id']) {
  7620. $selectParent->setSelected($arrLP[$i]['id']);
  7621. }
  7622. }
  7623. }
  7624. }
  7625. if ($arrLP != null) {
  7626. reset($arrLP);
  7627. }
  7628. $selectPrevious = $form->addSelect(
  7629. 'previous',
  7630. get_lang('Position'),
  7631. [],
  7632. ['id' => 'previous']
  7633. );
  7634. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7635. for ($i = 0; $i < count($arrLP); $i++) {
  7636. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7637. $selectPrevious->addOption(
  7638. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7639. $arrLP[$i]['id']
  7640. );
  7641. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7642. $selectPrevious->setSelected($arrLP[$i]['id']);
  7643. } elseif ($action == 'add') {
  7644. $selectPrevious->setSelected($arrLP[$i]['id']);
  7645. }
  7646. }
  7647. }
  7648. if ($action != 'move') {
  7649. $form->addText(
  7650. 'title',
  7651. get_lang('Title'),
  7652. true,
  7653. ['id' => 'idTitle']
  7654. );
  7655. $defaults['title'] = $item_title;
  7656. $id_prerequisite = 0;
  7657. if ($arrLP != null) {
  7658. foreach ($arrLP as $key => $value) {
  7659. if ($value['id'] == $id) {
  7660. $id_prerequisite = $value['prerequisite'];
  7661. break;
  7662. }
  7663. }
  7664. }
  7665. $arrHide = [];
  7666. $s_selected_position = 0;
  7667. for ($i = 0; $i < count($arrLP); $i++) {
  7668. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7669. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7670. $s_selected_position = $arrLP[$i]['id'];
  7671. } elseif ($action == 'add') {
  7672. $s_selected_position = 0;
  7673. }
  7674. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7675. }
  7676. }
  7677. $selectPrerequisites = $form->addSelect(
  7678. 'prerequisites',
  7679. get_lang('LearnpathPrerequisites'),
  7680. [],
  7681. ['id' => 'prerequisites']
  7682. );
  7683. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7684. foreach ($arrHide as $key => $value) {
  7685. $selectPrerequisites->addOption($value['value'], $key);
  7686. if ($key == $s_selected_position && $action == 'add') {
  7687. $selectPrerequisites->setSelected($key);
  7688. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7689. $selectPrerequisites->setSelected($key);
  7690. }
  7691. }
  7692. }
  7693. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7694. if ($action == 'move') {
  7695. $form->addHidden('title', $item_title);
  7696. $form->addHidden('description', $item_description);
  7697. }
  7698. if (is_numeric($extra_info)) {
  7699. $form->addHidden('path', $extra_info);
  7700. } elseif (is_array($extra_info)) {
  7701. $form->addHidden('path', $extra_info['path']);
  7702. }
  7703. $form->addHidden('type', TOOL_THREAD);
  7704. $form->addHidden('post_time', time());
  7705. $form->setDefaults($defaults);
  7706. return $form->returnForm();
  7707. }
  7708. /**
  7709. * Return the HTML form to display an item (generally a dir item).
  7710. *
  7711. * @param string $item_type
  7712. * @param string $title
  7713. * @param string $action
  7714. * @param int $id
  7715. * @param string $extra_info
  7716. *
  7717. * @throws Exception
  7718. * @throws HTML_QuickForm_Error
  7719. *
  7720. * @return string HTML form
  7721. */
  7722. public function display_item_form(
  7723. $item_type,
  7724. $title = '',
  7725. $action = 'add_item',
  7726. $id = 0,
  7727. $extra_info = 'new'
  7728. ) {
  7729. $_course = api_get_course_info();
  7730. global $charset;
  7731. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7732. $item_title = '';
  7733. $item_description = '';
  7734. $item_path_fck = '';
  7735. if ($id != 0 && is_array($extra_info)) {
  7736. $item_title = $extra_info['title'];
  7737. $item_description = $extra_info['description'];
  7738. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7739. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7740. }
  7741. $parent = 0;
  7742. if ($id != 0 && is_array($extra_info)) {
  7743. $parent = $extra_info['parent_item_id'];
  7744. }
  7745. $id = (int) $id;
  7746. $sql = "SELECT * FROM $tbl_lp_item
  7747. WHERE
  7748. lp_id = ".$this->lp_id." AND
  7749. iid != $id";
  7750. if ($item_type == 'dir') {
  7751. $sql .= " AND parent_item_id = 0";
  7752. }
  7753. $result = Database::query($sql);
  7754. $arrLP = [];
  7755. while ($row = Database::fetch_array($result)) {
  7756. $arrLP[] = [
  7757. 'id' => $row['iid'],
  7758. 'item_type' => $row['item_type'],
  7759. 'title' => $row['title'],
  7760. 'path' => $row['path'],
  7761. 'description' => $row['description'],
  7762. 'parent_item_id' => $row['parent_item_id'],
  7763. 'previous_item_id' => $row['previous_item_id'],
  7764. 'next_item_id' => $row['next_item_id'],
  7765. 'max_score' => $row['max_score'],
  7766. 'min_score' => $row['min_score'],
  7767. 'mastery_score' => $row['mastery_score'],
  7768. 'prerequisite' => $row['prerequisite'],
  7769. 'display_order' => $row['display_order'],
  7770. ];
  7771. }
  7772. $this->tree_array($arrLP);
  7773. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7774. unset($this->arrMenu);
  7775. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7776. $form = new FormValidator('form', 'POST', $url);
  7777. $defaults['title'] = api_html_entity_decode(
  7778. $item_title,
  7779. ENT_QUOTES,
  7780. $charset
  7781. );
  7782. $defaults['description'] = $item_description;
  7783. $form->addHeader($title);
  7784. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7785. $arrHide[0]['padding'] = 20;
  7786. $charset = api_get_system_encoding();
  7787. for ($i = 0; $i < count($arrLP); $i++) {
  7788. if ($action != 'add') {
  7789. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7790. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7791. ) {
  7792. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7793. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7794. if ($parent == $arrLP[$i]['id']) {
  7795. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7796. }
  7797. }
  7798. } else {
  7799. if ($arrLP[$i]['item_type'] == 'dir') {
  7800. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7801. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7802. if ($parent == $arrLP[$i]['id']) {
  7803. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7804. }
  7805. }
  7806. }
  7807. }
  7808. if ($action != 'move') {
  7809. $form->addElement('text', 'title', get_lang('Title'));
  7810. $form->applyFilter('title', 'html_filter');
  7811. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7812. } else {
  7813. $form->addElement('hidden', 'title');
  7814. }
  7815. $parentSelect = $form->addElement(
  7816. 'select',
  7817. 'parent',
  7818. get_lang('Parent'),
  7819. '',
  7820. [
  7821. 'id' => 'idParent',
  7822. 'onchange' => "javascript: load_cbo(this.value);",
  7823. ]
  7824. );
  7825. foreach ($arrHide as $key => $value) {
  7826. $parentSelect->addOption(
  7827. $value['value'],
  7828. $key,
  7829. 'style="padding-left:'.$value['padding'].'px;"'
  7830. );
  7831. $lastPosition = $key;
  7832. }
  7833. if (!empty($s_selected_parent)) {
  7834. $parentSelect->setSelected($s_selected_parent);
  7835. }
  7836. if (is_array($arrLP)) {
  7837. reset($arrLP);
  7838. }
  7839. $arrHide = [];
  7840. // POSITION
  7841. for ($i = 0; $i < count($arrLP); $i++) {
  7842. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7843. //this is the same!
  7844. if (isset($extra_info['previous_item_id']) &&
  7845. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7846. ) {
  7847. $s_selected_position = $arrLP[$i]['id'];
  7848. } elseif ($action == 'add') {
  7849. $s_selected_position = $arrLP[$i]['id'];
  7850. }
  7851. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7852. }
  7853. }
  7854. $position = $form->addElement(
  7855. 'select',
  7856. 'previous',
  7857. get_lang('Position'),
  7858. '',
  7859. ['id' => 'previous']
  7860. );
  7861. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7862. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7863. $lastPosition = null;
  7864. foreach ($arrHide as $key => $value) {
  7865. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7866. $lastPosition = $key;
  7867. }
  7868. if (!empty($s_selected_position)) {
  7869. $position->setSelected($s_selected_position);
  7870. }
  7871. // When new chapter add at the end
  7872. if ($action == 'add_item') {
  7873. $position->setSelected($lastPosition);
  7874. }
  7875. if (is_array($arrLP)) {
  7876. reset($arrLP);
  7877. }
  7878. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7879. //fix in order to use the tab
  7880. if ($item_type == 'dir') {
  7881. $form->addElement('hidden', 'type', 'dir');
  7882. }
  7883. $extension = null;
  7884. if (!empty($item_path)) {
  7885. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7886. }
  7887. //assets can't be modified
  7888. //$item_type == 'asset' ||
  7889. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7890. if ($item_type == 'sco') {
  7891. $form->addElement(
  7892. 'html',
  7893. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7894. );
  7895. }
  7896. $renderer = $form->defaultRenderer();
  7897. $renderer->setElementTemplate(
  7898. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7899. 'content_lp'
  7900. );
  7901. $relative_prefix = '';
  7902. $editor_config = [
  7903. 'ToolbarSet' => 'LearningPathDocuments',
  7904. 'Width' => '100%',
  7905. 'Height' => '500',
  7906. 'FullPage' => true,
  7907. 'CreateDocumentDir' => $relative_prefix,
  7908. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7909. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7910. ];
  7911. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7912. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7913. $defaults['content_lp'] = file_get_contents($content_path);
  7914. }
  7915. if (!empty($id)) {
  7916. $form->addHidden('id', $id);
  7917. }
  7918. $form->addElement('hidden', 'type', $item_type);
  7919. $form->addElement('hidden', 'post_time', time());
  7920. $form->setDefaults($defaults);
  7921. return $form->returnForm();
  7922. }
  7923. /**
  7924. * @return string
  7925. */
  7926. public function getCurrentBuildingModeURL()
  7927. {
  7928. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7929. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7930. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7931. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7932. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7933. return $currentUrl;
  7934. }
  7935. /**
  7936. * Returns the form to update or create a document.
  7937. *
  7938. * @param string $action (add/edit)
  7939. * @param int $id ID of the lp_item (if already exists)
  7940. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7941. *
  7942. * @throws Exception
  7943. * @throws HTML_QuickForm_Error
  7944. *
  7945. * @return string HTML form
  7946. */
  7947. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7948. {
  7949. $course_id = api_get_course_int_id();
  7950. $_course = api_get_course_info();
  7951. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7952. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7953. $no_display_edit_textarea = false;
  7954. $item_description = '';
  7955. //If action==edit document
  7956. //We don't display the document form if it's not an editable document (html or txt file)
  7957. if ($action == 'edit') {
  7958. if (is_array($extra_info)) {
  7959. $path_parts = pathinfo($extra_info['dir']);
  7960. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7961. $no_display_edit_textarea = true;
  7962. }
  7963. }
  7964. }
  7965. $no_display_add = false;
  7966. // If action==add an existing document
  7967. // We don't display the document form if it's not an editable document (html or txt file).
  7968. if ($action == 'add') {
  7969. if (is_numeric($extra_info)) {
  7970. $extra_info = (int) $extra_info;
  7971. $sql_doc = "SELECT path FROM $tbl_doc
  7972. WHERE c_id = $course_id AND iid = ".$extra_info;
  7973. $result = Database::query($sql_doc);
  7974. $path_file = Database::result($result, 0, 0);
  7975. $path_parts = pathinfo($path_file);
  7976. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7977. $no_display_add = true;
  7978. }
  7979. }
  7980. }
  7981. if ($id != 0 && is_array($extra_info)) {
  7982. $item_title = stripslashes($extra_info['title']);
  7983. $item_description = stripslashes($extra_info['description']);
  7984. if (empty($item_title)) {
  7985. $path_parts = pathinfo($extra_info['path']);
  7986. $item_title = stripslashes($path_parts['filename']);
  7987. }
  7988. } elseif (is_numeric($extra_info)) {
  7989. $sql = "SELECT path, title FROM $tbl_doc
  7990. WHERE
  7991. c_id = ".$course_id." AND
  7992. iid = ".intval($extra_info);
  7993. $result = Database::query($sql);
  7994. $row = Database::fetch_array($result);
  7995. $item_title = $row['title'];
  7996. $item_title = str_replace('_', ' ', $item_title);
  7997. if (empty($item_title)) {
  7998. $path_parts = pathinfo($row['path']);
  7999. $item_title = stripslashes($path_parts['filename']);
  8000. }
  8001. } else {
  8002. $item_title = '';
  8003. $item_description = '';
  8004. }
  8005. $return = '<legend>';
  8006. $parent = 0;
  8007. if ($id != 0 && is_array($extra_info)) {
  8008. $parent = $extra_info['parent_item_id'];
  8009. }
  8010. $sql = "SELECT * FROM $tbl_lp_item
  8011. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8012. $result = Database::query($sql);
  8013. $arrLP = [];
  8014. while ($row = Database::fetch_array($result)) {
  8015. $arrLP[] = [
  8016. 'id' => $row['iid'],
  8017. 'item_type' => $row['item_type'],
  8018. 'title' => $row['title'],
  8019. 'path' => $row['path'],
  8020. 'description' => $row['description'],
  8021. 'parent_item_id' => $row['parent_item_id'],
  8022. 'previous_item_id' => $row['previous_item_id'],
  8023. 'next_item_id' => $row['next_item_id'],
  8024. 'display_order' => $row['display_order'],
  8025. 'max_score' => $row['max_score'],
  8026. 'min_score' => $row['min_score'],
  8027. 'mastery_score' => $row['mastery_score'],
  8028. 'prerequisite' => $row['prerequisite'],
  8029. ];
  8030. }
  8031. $this->tree_array($arrLP);
  8032. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8033. unset($this->arrMenu);
  8034. if ($action == 'add') {
  8035. $return .= get_lang('CreateTheDocument');
  8036. } elseif ($action == 'move') {
  8037. $return .= get_lang('MoveTheCurrentDocument');
  8038. } else {
  8039. $return .= get_lang('EditTheCurrentDocument');
  8040. }
  8041. $return .= '</legend>';
  8042. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8043. $return .= Display::return_message(
  8044. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8045. false
  8046. );
  8047. }
  8048. $form = new FormValidator(
  8049. 'form',
  8050. 'POST',
  8051. $this->getCurrentBuildingModeURL(),
  8052. '',
  8053. ['enctype' => 'multipart/form-data']
  8054. );
  8055. $defaults['title'] = Security::remove_XSS($item_title);
  8056. if (empty($item_title)) {
  8057. $defaults['title'] = Security::remove_XSS($item_title);
  8058. }
  8059. $defaults['description'] = $item_description;
  8060. $form->addElement('html', $return);
  8061. if ($action != 'move') {
  8062. $data = $this->generate_lp_folder($_course);
  8063. if ($action != 'edit') {
  8064. $folders = DocumentManager::get_all_document_folders(
  8065. $_course,
  8066. 0,
  8067. true
  8068. );
  8069. DocumentManager::build_directory_selector(
  8070. $folders,
  8071. '',
  8072. [],
  8073. true,
  8074. $form,
  8075. 'directory_parent_id'
  8076. );
  8077. }
  8078. if (isset($data['id'])) {
  8079. $defaults['directory_parent_id'] = $data['id'];
  8080. }
  8081. $form->addElement(
  8082. 'text',
  8083. 'title',
  8084. get_lang('Title'),
  8085. ['id' => 'idTitle', 'class' => 'col-md-4']
  8086. );
  8087. $form->applyFilter('title', 'html_filter');
  8088. }
  8089. $arrHide[0]['value'] = $this->name;
  8090. $arrHide[0]['padding'] = 20;
  8091. for ($i = 0; $i < count($arrLP); $i++) {
  8092. if ($action != 'add') {
  8093. if ($arrLP[$i]['item_type'] == 'dir' &&
  8094. !in_array($arrLP[$i]['id'], $arrHide) &&
  8095. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8096. ) {
  8097. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8098. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8099. }
  8100. } else {
  8101. if ($arrLP[$i]['item_type'] == 'dir') {
  8102. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8103. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8104. }
  8105. }
  8106. }
  8107. $parentSelect = $form->addSelect(
  8108. 'parent',
  8109. get_lang('Parent'),
  8110. [],
  8111. [
  8112. 'id' => 'idParent',
  8113. 'onchange' => 'javascript: load_cbo(this.value);',
  8114. ]
  8115. );
  8116. $my_count = 0;
  8117. foreach ($arrHide as $key => $value) {
  8118. if ($my_count != 0) {
  8119. // The LP name is also the first section and is not in the same charset like the other sections.
  8120. $value['value'] = Security::remove_XSS($value['value']);
  8121. $parentSelect->addOption(
  8122. $value['value'],
  8123. $key,
  8124. 'style="padding-left:'.$value['padding'].'px;"'
  8125. );
  8126. } else {
  8127. $value['value'] = Security::remove_XSS($value['value']);
  8128. $parentSelect->addOption(
  8129. $value['value'],
  8130. $key,
  8131. 'style="padding-left:'.$value['padding'].'px;"'
  8132. );
  8133. }
  8134. $my_count++;
  8135. }
  8136. if (!empty($id)) {
  8137. $parentSelect->setSelected($parent);
  8138. } else {
  8139. $parent_item_id = Session::read('parent_item_id', 0);
  8140. $parentSelect->setSelected($parent_item_id);
  8141. }
  8142. if (is_array($arrLP)) {
  8143. reset($arrLP);
  8144. }
  8145. $arrHide = [];
  8146. // POSITION
  8147. for ($i = 0; $i < count($arrLP); $i++) {
  8148. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8149. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8150. ) {
  8151. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8152. }
  8153. }
  8154. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8155. $position = $form->addSelect(
  8156. 'previous',
  8157. get_lang('Position'),
  8158. [],
  8159. ['id' => 'previous']
  8160. );
  8161. $position->addOption(get_lang('FirstPosition'), 0);
  8162. foreach ($arrHide as $key => $value) {
  8163. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8164. $position->addOption(
  8165. $value['value'],
  8166. $key,
  8167. 'style="padding-left:'.$padding.'px;"'
  8168. );
  8169. }
  8170. $position->setSelected($selectedPosition);
  8171. if (is_array($arrLP)) {
  8172. reset($arrLP);
  8173. }
  8174. if ($action != 'move') {
  8175. $arrHide = [];
  8176. for ($i = 0; $i < count($arrLP); $i++) {
  8177. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8178. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8179. ) {
  8180. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8181. }
  8182. }
  8183. if (!$no_display_add) {
  8184. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8185. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8186. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8187. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8188. ) {
  8189. if (isset($_POST['content'])) {
  8190. $content = stripslashes($_POST['content']);
  8191. } elseif (is_array($extra_info)) {
  8192. //If it's an html document or a text file
  8193. if (!$no_display_edit_textarea) {
  8194. $content = $this->display_document(
  8195. $extra_info['path'],
  8196. false,
  8197. false
  8198. );
  8199. }
  8200. } elseif (is_numeric($extra_info)) {
  8201. $content = $this->display_document(
  8202. $extra_info,
  8203. false,
  8204. false
  8205. );
  8206. } else {
  8207. $content = '';
  8208. }
  8209. if (!$no_display_edit_textarea) {
  8210. // We need to calculate here some specific settings for the online editor.
  8211. // The calculated settings work for documents in the Documents tool
  8212. // (on the root or in subfolders).
  8213. // For documents in native scorm packages it is unclear whether the
  8214. // online editor should be activated or not.
  8215. // A new document, it is in the root of the repository.
  8216. $relative_path = '';
  8217. $relative_prefix = '';
  8218. if (is_array($extra_info) && $extra_info != 'new') {
  8219. // The document already exists. Whe have to determine its relative path towards the repository root.
  8220. $relative_path = explode('/', $extra_info['dir']);
  8221. $cnt = count($relative_path) - 2;
  8222. if ($cnt < 0) {
  8223. $cnt = 0;
  8224. }
  8225. $relative_prefix = str_repeat('../', $cnt);
  8226. $relative_path = array_slice($relative_path, 1, $cnt);
  8227. $relative_path = implode('/', $relative_path);
  8228. if (strlen($relative_path) > 0) {
  8229. $relative_path = $relative_path.'/';
  8230. }
  8231. } else {
  8232. $result = $this->generate_lp_folder($_course);
  8233. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8234. $relative_prefix = '../../';
  8235. }
  8236. $editor_config = [
  8237. 'ToolbarSet' => 'LearningPathDocuments',
  8238. 'Width' => '100%',
  8239. 'Height' => '500',
  8240. 'FullPage' => true,
  8241. 'CreateDocumentDir' => $relative_prefix,
  8242. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8243. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8244. ];
  8245. if ($_GET['action'] == 'add_item') {
  8246. $class = 'add';
  8247. $text = get_lang('LPCreateDocument');
  8248. } else {
  8249. if ($_GET['action'] == 'edit_item') {
  8250. $class = 'save';
  8251. $text = get_lang('SaveDocument');
  8252. }
  8253. }
  8254. $form->addButtonSave($text, 'submit_button');
  8255. $renderer = $form->defaultRenderer();
  8256. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8257. $form->addElement('html', '<div class="editor-lp">');
  8258. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8259. $form->addElement('html', '</div>');
  8260. $defaults['content_lp'] = $content;
  8261. }
  8262. } elseif (is_numeric($extra_info)) {
  8263. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8264. $return = $this->display_document($extra_info, true, true, true);
  8265. $form->addElement('html', $return);
  8266. }
  8267. }
  8268. }
  8269. if (isset($extra_info['item_type']) &&
  8270. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8271. ) {
  8272. $parentSelect->freeze();
  8273. $position->freeze();
  8274. }
  8275. if ($action == 'move') {
  8276. $form->addElement('hidden', 'title', $item_title);
  8277. $form->addElement('hidden', 'description', $item_description);
  8278. }
  8279. if (is_numeric($extra_info)) {
  8280. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8281. $form->addElement('hidden', 'path', $extra_info);
  8282. } elseif (is_array($extra_info)) {
  8283. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8284. $form->addElement('hidden', 'path', $extra_info['path']);
  8285. }
  8286. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8287. $form->addElement('hidden', 'post_time', time());
  8288. $form->setDefaults($defaults);
  8289. return $form->returnForm();
  8290. }
  8291. /**
  8292. * Return HTML form to add/edit a link item.
  8293. *
  8294. * @param string $action (add/edit)
  8295. * @param int $id Item ID if exists
  8296. * @param mixed $extra_info
  8297. *
  8298. * @throws Exception
  8299. * @throws HTML_QuickForm_Error
  8300. *
  8301. * @return string HTML form
  8302. */
  8303. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8304. {
  8305. $course_id = api_get_course_int_id();
  8306. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8307. $tbl_link = Database::get_course_table(TABLE_LINK);
  8308. if ($id != 0 && is_array($extra_info)) {
  8309. $item_title = stripslashes($extra_info['title']);
  8310. $item_description = stripslashes($extra_info['description']);
  8311. $item_url = stripslashes($extra_info['url']);
  8312. } elseif (is_numeric($extra_info)) {
  8313. $extra_info = intval($extra_info);
  8314. $sql = "SELECT title, description, url FROM ".$tbl_link."
  8315. WHERE c_id = ".$course_id." AND id = ".$extra_info;
  8316. $result = Database::query($sql);
  8317. $row = Database::fetch_array($result);
  8318. $item_title = $row['title'];
  8319. $item_description = $row['description'];
  8320. $item_url = $row['url'];
  8321. } else {
  8322. $item_title = '';
  8323. $item_description = '';
  8324. $item_url = '';
  8325. }
  8326. $form = new FormValidator(
  8327. 'edit_link',
  8328. 'POST',
  8329. $this->getCurrentBuildingModeURL()
  8330. );
  8331. $defaults = [];
  8332. if ($id != 0 && is_array($extra_info)) {
  8333. $parent = $extra_info['parent_item_id'];
  8334. } else {
  8335. $parent = 0;
  8336. }
  8337. $sql = "SELECT * FROM $tbl_lp_item
  8338. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8339. $result = Database::query($sql);
  8340. $arrLP = [];
  8341. while ($row = Database::fetch_array($result)) {
  8342. $arrLP[] = [
  8343. 'id' => $row['id'],
  8344. 'item_type' => $row['item_type'],
  8345. 'title' => $row['title'],
  8346. 'path' => $row['path'],
  8347. 'description' => $row['description'],
  8348. 'parent_item_id' => $row['parent_item_id'],
  8349. 'previous_item_id' => $row['previous_item_id'],
  8350. 'next_item_id' => $row['next_item_id'],
  8351. 'display_order' => $row['display_order'],
  8352. 'max_score' => $row['max_score'],
  8353. 'min_score' => $row['min_score'],
  8354. 'mastery_score' => $row['mastery_score'],
  8355. 'prerequisite' => $row['prerequisite'],
  8356. ];
  8357. }
  8358. $this->tree_array($arrLP);
  8359. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8360. unset($this->arrMenu);
  8361. if ($action == 'add') {
  8362. $legend = get_lang('CreateTheLink');
  8363. } elseif ($action == 'move') {
  8364. $legend = get_lang('MoveCurrentLink');
  8365. } else {
  8366. $legend = get_lang('EditCurrentLink');
  8367. }
  8368. $form->addHeader($legend);
  8369. if ($action != 'move') {
  8370. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8371. $defaults['title'] = $item_title;
  8372. }
  8373. $selectParent = $form->addSelect(
  8374. 'parent',
  8375. get_lang('Parent'),
  8376. [],
  8377. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8378. );
  8379. $selectParent->addOption($this->name, 0);
  8380. $arrHide = [
  8381. $id,
  8382. ];
  8383. $parent_item_id = Session::read('parent_item_id', 0);
  8384. for ($i = 0; $i < count($arrLP); $i++) {
  8385. if ($action != 'add') {
  8386. if (
  8387. ($arrLP[$i]['item_type'] == 'dir') &&
  8388. !in_array($arrLP[$i]['id'], $arrHide) &&
  8389. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8390. ) {
  8391. $selectParent->addOption(
  8392. $arrLP[$i]['title'],
  8393. $arrLP[$i]['id'],
  8394. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8395. );
  8396. if ($parent == $arrLP[$i]['id']) {
  8397. $selectParent->setSelected($arrLP[$i]['id']);
  8398. }
  8399. } else {
  8400. $arrHide[] = $arrLP[$i]['id'];
  8401. }
  8402. } else {
  8403. if ($arrLP[$i]['item_type'] == 'dir') {
  8404. $selectParent->addOption(
  8405. $arrLP[$i]['title'],
  8406. $arrLP[$i]['id'],
  8407. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8408. );
  8409. if ($parent_item_id == $arrLP[$i]['id']) {
  8410. $selectParent->setSelected($arrLP[$i]['id']);
  8411. }
  8412. }
  8413. }
  8414. }
  8415. if (is_array($arrLP)) {
  8416. reset($arrLP);
  8417. }
  8418. $selectPrevious = $form->addSelect(
  8419. 'previous',
  8420. get_lang('Position'),
  8421. [],
  8422. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8423. );
  8424. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8425. for ($i = 0; $i < count($arrLP); $i++) {
  8426. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8427. $selectPrevious->addOption(
  8428. $arrLP[$i]['title'],
  8429. $arrLP[$i]['id']
  8430. );
  8431. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8432. $selectPrevious->setSelected($arrLP[$i]['id']);
  8433. } elseif ($action == 'add') {
  8434. $selectPrevious->setSelected($arrLP[$i]['id']);
  8435. }
  8436. }
  8437. }
  8438. if ($action != 'move') {
  8439. $urlAttributes = ['class' => 'learnpath_item_form'];
  8440. if (is_numeric($extra_info)) {
  8441. $urlAttributes['disabled'] = 'disabled';
  8442. }
  8443. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8444. $defaults['url'] = $item_url;
  8445. $arrHide = [];
  8446. for ($i = 0; $i < count($arrLP); $i++) {
  8447. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8448. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8449. }
  8450. }
  8451. }
  8452. if ($action == 'add') {
  8453. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8454. } else {
  8455. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8456. }
  8457. if ($action == 'move') {
  8458. $form->addHidden('title', $item_title);
  8459. $form->addHidden('description', $item_description);
  8460. }
  8461. if (is_numeric($extra_info)) {
  8462. $form->addHidden('path', $extra_info);
  8463. } elseif (is_array($extra_info)) {
  8464. $form->addHidden('path', $extra_info['path']);
  8465. }
  8466. $form->addHidden('type', TOOL_LINK);
  8467. $form->addHidden('post_time', time());
  8468. $form->setDefaults($defaults);
  8469. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8470. }
  8471. /**
  8472. * Return HTML form to add/edit a student publication (work).
  8473. *
  8474. * @param string $action
  8475. * @param int $id Item ID if already exists
  8476. * @param string $extra_info
  8477. *
  8478. * @throws Exception
  8479. *
  8480. * @return string HTML form
  8481. */
  8482. public function display_student_publication_form(
  8483. $action = 'add',
  8484. $id = 0,
  8485. $extra_info = ''
  8486. ) {
  8487. $course_id = api_get_course_int_id();
  8488. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8489. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8490. $item_title = get_lang('Student_publication');
  8491. if ($id != 0 && is_array($extra_info)) {
  8492. $item_title = stripslashes($extra_info['title']);
  8493. $item_description = stripslashes($extra_info['description']);
  8494. } elseif (is_numeric($extra_info)) {
  8495. $extra_info = (int) $extra_info;
  8496. $sql = "SELECT title, description
  8497. FROM $tbl_publication
  8498. WHERE c_id = $course_id AND id = ".$extra_info;
  8499. $result = Database::query($sql);
  8500. $row = Database::fetch_array($result);
  8501. if ($row) {
  8502. $item_title = $row['title'];
  8503. }
  8504. }
  8505. $parent = 0;
  8506. if ($id != 0 && is_array($extra_info)) {
  8507. $parent = $extra_info['parent_item_id'];
  8508. }
  8509. $sql = "SELECT * FROM $tbl_lp_item
  8510. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8511. $result = Database::query($sql);
  8512. $arrLP = [];
  8513. while ($row = Database::fetch_array($result)) {
  8514. $arrLP[] = [
  8515. 'id' => $row['iid'],
  8516. 'item_type' => $row['item_type'],
  8517. 'title' => $row['title'],
  8518. 'path' => $row['path'],
  8519. 'description' => $row['description'],
  8520. 'parent_item_id' => $row['parent_item_id'],
  8521. 'previous_item_id' => $row['previous_item_id'],
  8522. 'next_item_id' => $row['next_item_id'],
  8523. 'display_order' => $row['display_order'],
  8524. 'max_score' => $row['max_score'],
  8525. 'min_score' => $row['min_score'],
  8526. 'mastery_score' => $row['mastery_score'],
  8527. 'prerequisite' => $row['prerequisite'],
  8528. ];
  8529. }
  8530. $this->tree_array($arrLP);
  8531. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8532. unset($this->arrMenu);
  8533. $form = new FormValidator('frm_student_publication', 'post', '#');
  8534. if ($action == 'add') {
  8535. $form->addHeader(get_lang('Student_publication'));
  8536. } elseif ($action == 'move') {
  8537. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8538. } else {
  8539. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8540. }
  8541. if ($action != 'move') {
  8542. $form->addText(
  8543. 'title',
  8544. get_lang('Title'),
  8545. true,
  8546. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  8547. );
  8548. }
  8549. $parentSelect = $form->addSelect(
  8550. 'parent',
  8551. get_lang('Parent'),
  8552. ['0' => $this->name],
  8553. [
  8554. 'onchange' => 'javascript: load_cbo(this.value);',
  8555. 'class' => 'learnpath_item_form',
  8556. 'id' => 'idParent',
  8557. ]
  8558. );
  8559. $arrHide = [$id];
  8560. for ($i = 0; $i < count($arrLP); $i++) {
  8561. if ($action != 'add') {
  8562. if (
  8563. ($arrLP[$i]['item_type'] == 'dir') &&
  8564. !in_array($arrLP[$i]['id'], $arrHide) &&
  8565. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8566. ) {
  8567. $parentSelect->addOption(
  8568. $arrLP[$i]['title'],
  8569. $arrLP[$i]['id'],
  8570. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8571. );
  8572. if ($parent == $arrLP[$i]['id']) {
  8573. $parentSelect->setSelected($arrLP[$i]['id']);
  8574. }
  8575. } else {
  8576. $arrHide[] = $arrLP[$i]['id'];
  8577. }
  8578. } else {
  8579. if ($arrLP[$i]['item_type'] == 'dir') {
  8580. $parentSelect->addOption(
  8581. $arrLP[$i]['title'],
  8582. $arrLP[$i]['id'],
  8583. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8584. );
  8585. if ($parent == $arrLP[$i]['id']) {
  8586. $parentSelect->setSelected($arrLP[$i]['id']);
  8587. }
  8588. }
  8589. }
  8590. }
  8591. if (is_array($arrLP)) {
  8592. reset($arrLP);
  8593. }
  8594. $previousSelect = $form->addSelect(
  8595. 'previous',
  8596. get_lang('Position'),
  8597. ['0' => get_lang('FirstPosition')],
  8598. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8599. );
  8600. for ($i = 0; $i < count($arrLP); $i++) {
  8601. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8602. $previousSelect->addOption(
  8603. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8604. $arrLP[$i]['id']
  8605. );
  8606. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8607. $previousSelect->setSelected($arrLP[$i]['id']);
  8608. } elseif ($action == 'add') {
  8609. $previousSelect->setSelected($arrLP[$i]['id']);
  8610. }
  8611. }
  8612. }
  8613. if ($action == 'add') {
  8614. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8615. } else {
  8616. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8617. }
  8618. if ($action == 'move') {
  8619. $form->addHidden('title', $item_title);
  8620. $form->addHidden('description', $item_description);
  8621. }
  8622. if (is_numeric($extra_info)) {
  8623. $form->addHidden('path', $extra_info);
  8624. } elseif (is_array($extra_info)) {
  8625. $form->addHidden('path', $extra_info['path']);
  8626. }
  8627. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8628. $form->addHidden('post_time', time());
  8629. $form->setDefaults(['title' => $item_title]);
  8630. $return = '<div class="sectioncomment">';
  8631. $return .= $form->returnForm();
  8632. $return .= '</div>';
  8633. return $return;
  8634. }
  8635. /**
  8636. * Displays the menu for manipulating a step.
  8637. *
  8638. * @param id $item_id
  8639. * @param string $item_type
  8640. *
  8641. * @return string
  8642. */
  8643. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8644. {
  8645. $_course = api_get_course_info();
  8646. $course_code = api_get_course_id();
  8647. $return = '<div class="actions">';
  8648. switch ($item_type) {
  8649. case 'dir':
  8650. // Commented the message cause should not show it.
  8651. //$lang = get_lang('TitleManipulateChapter');
  8652. break;
  8653. case TOOL_LP_FINAL_ITEM:
  8654. case TOOL_DOCUMENT:
  8655. // Commented the message cause should not show it.
  8656. //$lang = get_lang('TitleManipulateDocument');
  8657. break;
  8658. case TOOL_LINK:
  8659. case 'link':
  8660. // Commented the message cause should not show it.
  8661. //$lang = get_lang('TitleManipulateLink');
  8662. break;
  8663. case TOOL_QUIZ:
  8664. // Commented the message cause should not show it.
  8665. //$lang = get_lang('TitleManipulateQuiz');
  8666. break;
  8667. case TOOL_STUDENTPUBLICATION:
  8668. // Commented the message cause should not show it.
  8669. //$lang = get_lang('TitleManipulateStudentPublication');
  8670. break;
  8671. }
  8672. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8673. $item_id = (int) $item_id;
  8674. $sql = "SELECT * FROM $tbl_lp_item
  8675. WHERE iid = ".$item_id;
  8676. $result = Database::query($sql);
  8677. $row = Database::fetch_assoc($result);
  8678. $audio_player = null;
  8679. // We display an audio player if needed.
  8680. if (!empty($row['audio'])) {
  8681. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  8682. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  8683. .'<audio src="'.$webAudioPath.'" controls>'
  8684. .'</div><br>';
  8685. }
  8686. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8687. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8688. $return .= Display::url(
  8689. Display::return_icon(
  8690. 'edit.png',
  8691. get_lang('Edit'),
  8692. [],
  8693. ICON_SIZE_SMALL
  8694. ),
  8695. $url.'&action=edit_item&path_item='.$row['path']
  8696. );
  8697. $return .= Display::url(
  8698. Display::return_icon(
  8699. 'move.png',
  8700. get_lang('Move'),
  8701. [],
  8702. ICON_SIZE_SMALL
  8703. ),
  8704. $url.'&action=move_item'
  8705. );
  8706. }
  8707. // Commented for now as prerequisites cannot be added to chapters.
  8708. if ($item_type != 'dir') {
  8709. $return .= Display::url(
  8710. Display::return_icon(
  8711. 'accept.png',
  8712. get_lang('LearnpathPrerequisites'),
  8713. [],
  8714. ICON_SIZE_SMALL
  8715. ),
  8716. $url.'&action=edit_item_prereq'
  8717. );
  8718. }
  8719. $return .= Display::url(
  8720. Display::return_icon(
  8721. 'delete.png',
  8722. get_lang('Delete'),
  8723. [],
  8724. ICON_SIZE_SMALL
  8725. ),
  8726. $url.'&action=delete_item'
  8727. );
  8728. if ($item_type == TOOL_HOTPOTATOES) {
  8729. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8730. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8731. }
  8732. if ($item_type == TOOL_DOCUMENT || $item_type == TOOL_LP_FINAL_ITEM) {
  8733. $document_data = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8734. $return .= get_lang('File').': '.$document_data['absolute_path_from_document'];
  8735. }
  8736. $return .= '</div>';
  8737. if (!empty($audio_player)) {
  8738. $return .= $audio_player;
  8739. }
  8740. return $return;
  8741. }
  8742. /**
  8743. * Creates the javascript needed for filling up the checkboxes without page reload.
  8744. *
  8745. * @return string
  8746. */
  8747. public function get_js_dropdown_array()
  8748. {
  8749. $course_id = api_get_course_int_id();
  8750. $return = 'var child_name = new Array();'."\n";
  8751. $return .= 'var child_value = new Array();'."\n\n";
  8752. $return .= 'child_name[0] = new Array();'."\n";
  8753. $return .= 'child_value[0] = new Array();'."\n\n";
  8754. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8755. $sql = "SELECT * FROM ".$tbl_lp_item."
  8756. WHERE
  8757. c_id = $course_id AND
  8758. lp_id = ".$this->lp_id." AND
  8759. parent_item_id = 0
  8760. ORDER BY display_order ASC";
  8761. $res_zero = Database::query($sql);
  8762. $i = 0;
  8763. while ($row_zero = Database::fetch_array($res_zero)) {
  8764. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8765. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8766. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8767. }
  8768. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8769. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8770. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8771. }
  8772. }
  8773. $return .= "\n";
  8774. $sql = "SELECT * FROM $tbl_lp_item
  8775. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8776. $res = Database::query($sql);
  8777. while ($row = Database::fetch_array($res)) {
  8778. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8779. WHERE
  8780. c_id = ".$course_id." AND
  8781. parent_item_id = ".$row['iid']."
  8782. ORDER BY display_order ASC";
  8783. $res_parent = Database::query($sql_parent);
  8784. $i = 0;
  8785. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8786. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8787. while ($row_parent = Database::fetch_array($res_parent)) {
  8788. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  8789. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8790. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8791. }
  8792. $return .= "\n";
  8793. }
  8794. $return .= "
  8795. function load_cbo(id) {
  8796. if (!id) {
  8797. return false;
  8798. }
  8799. var cbo = document.getElementById('previous');
  8800. for(var i = cbo.length - 1; i > 0; i--) {
  8801. cbo.options[i] = null;
  8802. }
  8803. var k=0;
  8804. for(var i = 1; i <= child_name[id].length; i++){
  8805. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  8806. option.style.paddingLeft = '40px';
  8807. cbo.options[i] = option;
  8808. k = i;
  8809. }
  8810. cbo.options[k].selected = true;
  8811. $('#previous').selectpicker('refresh');
  8812. }";
  8813. return $return;
  8814. }
  8815. /**
  8816. * Display the form to allow moving an item.
  8817. *
  8818. * @param int $item_id Item ID
  8819. *
  8820. * @throws Exception
  8821. * @throws HTML_QuickForm_Error
  8822. *
  8823. * @return string HTML form
  8824. */
  8825. public function display_move_item($item_id)
  8826. {
  8827. $return = '';
  8828. if (is_numeric($item_id)) {
  8829. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8830. $sql = "SELECT * FROM $tbl_lp_item
  8831. WHERE iid = $item_id";
  8832. $res = Database::query($sql);
  8833. $row = Database::fetch_array($res);
  8834. switch ($row['item_type']) {
  8835. case 'dir':
  8836. case 'asset':
  8837. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8838. $return .= $this->display_item_form(
  8839. $row['item_type'],
  8840. get_lang('MoveCurrentChapter'),
  8841. 'move',
  8842. $item_id,
  8843. $row
  8844. );
  8845. break;
  8846. case TOOL_DOCUMENT:
  8847. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8848. $return .= $this->display_document_form('move', $item_id, $row);
  8849. break;
  8850. case TOOL_LINK:
  8851. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8852. $return .= $this->display_link_form('move', $item_id, $row);
  8853. break;
  8854. case TOOL_HOTPOTATOES:
  8855. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8856. $return .= $this->display_link_form('move', $item_id, $row);
  8857. break;
  8858. case TOOL_QUIZ:
  8859. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8860. $return .= $this->display_quiz_form('move', $item_id, $row);
  8861. break;
  8862. case TOOL_STUDENTPUBLICATION:
  8863. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8864. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8865. break;
  8866. case TOOL_FORUM:
  8867. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8868. $return .= $this->display_forum_form('move', $item_id, $row);
  8869. break;
  8870. case TOOL_THREAD:
  8871. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8872. $return .= $this->display_forum_form('move', $item_id, $row);
  8873. break;
  8874. }
  8875. }
  8876. return $return;
  8877. }
  8878. /**
  8879. * Return HTML form to allow prerequisites selection.
  8880. *
  8881. * @todo use FormValidator
  8882. *
  8883. * @param int Item ID
  8884. *
  8885. * @return string HTML form
  8886. */
  8887. public function display_item_prerequisites_form($item_id = 0)
  8888. {
  8889. $course_id = api_get_course_int_id();
  8890. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8891. $item_id = intval($item_id);
  8892. /* Current prerequisite */
  8893. $sql = "SELECT * FROM $tbl_lp_item
  8894. WHERE iid = $item_id";
  8895. $result = Database::query($sql);
  8896. $row = Database::fetch_array($result);
  8897. $prerequisiteId = $row['prerequisite'];
  8898. $return = '<legend>';
  8899. $return .= get_lang('AddEditPrerequisites');
  8900. $return .= '</legend>';
  8901. $return .= '<form method="POST">';
  8902. $return .= '<div class="table-responsive">';
  8903. $return .= '<table class="table table-hover">';
  8904. $return .= '<thead>';
  8905. $return .= '<tr>';
  8906. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8907. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8908. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8909. $return .= '</tr>';
  8910. $return .= '</thead>';
  8911. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8912. $return .= '<tbody>';
  8913. $return .= '<tr>';
  8914. $return .= '<td colspan="3">';
  8915. $return .= '<div class="radio learnpath"><label for="idNone">';
  8916. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8917. $return .= get_lang('None').'</label>';
  8918. $return .= '</div>';
  8919. $return .= '</tr>';
  8920. $sql = "SELECT * FROM $tbl_lp_item
  8921. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8922. $result = Database::query($sql);
  8923. $arrLP = [];
  8924. $selectedMinScore = [];
  8925. $selectedMaxScore = [];
  8926. while ($row = Database::fetch_array($result)) {
  8927. if ($row['id'] == $item_id) {
  8928. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8929. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8930. }
  8931. $arrLP[] = [
  8932. 'id' => $row['iid'],
  8933. 'item_type' => $row['item_type'],
  8934. 'title' => $row['title'],
  8935. 'ref' => $row['ref'],
  8936. 'description' => $row['description'],
  8937. 'parent_item_id' => $row['parent_item_id'],
  8938. 'previous_item_id' => $row['previous_item_id'],
  8939. 'next_item_id' => $row['next_item_id'],
  8940. 'max_score' => $row['max_score'],
  8941. 'min_score' => $row['min_score'],
  8942. 'mastery_score' => $row['mastery_score'],
  8943. 'prerequisite' => $row['prerequisite'],
  8944. 'display_order' => $row['display_order'],
  8945. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  8946. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  8947. ];
  8948. }
  8949. $this->tree_array($arrLP);
  8950. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8951. unset($this->arrMenu);
  8952. for ($i = 0; $i < count($arrLP); $i++) {
  8953. $item = $arrLP[$i];
  8954. if ($item['id'] == $item_id) {
  8955. break;
  8956. }
  8957. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8958. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8959. $return .= '<tr>';
  8960. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8961. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8962. $return .= '<label for="id'.$item['id'].'">';
  8963. $return .= '<input'.(in_array($prerequisiteId, [$item['id'], $item['ref']]) ? ' checked="checked" ' : '').($item['item_type'] == 'dir' ? ' disabled="disabled" ' : ' ').'id="id'.$item['id'].'" name="prerequisites" type="radio" value="'.$item['id'].'" />';
  8964. $icon_name = str_replace(' ', '', $item['item_type']);
  8965. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8966. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8967. } else {
  8968. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8969. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8970. } else {
  8971. $return .= Display::return_icon('folder_document.png');
  8972. }
  8973. }
  8974. $return .= $item['title'].'</label>';
  8975. $return .= '</div>';
  8976. $return .= '</td>';
  8977. if ($item['item_type'] == TOOL_QUIZ) {
  8978. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8979. $lpItemObj = new LpItem($course_id, $item['id']);
  8980. $exercise = new Exercise($course_id);
  8981. $exercise->read($lpItemObj->path);
  8982. $lpItemObj->max_score = $exercise->get_max_score();
  8983. $lpItemObj->update();
  8984. $item['max_score'] = $lpItemObj->max_score;
  8985. $return .= '<td>';
  8986. $return .= '<input
  8987. class="form-control"
  8988. size="4" maxlength="3"
  8989. name="min_'.$item['id'].'"
  8990. type="number"
  8991. min="0"
  8992. step="1"
  8993. max="'.$item['max_score'].'"
  8994. value="'.$selectedMinScoreValue.'"
  8995. />';
  8996. $return .= '</td>';
  8997. $return .= '<td>';
  8998. $return .= '<input
  8999. class="form-control"
  9000. size="4"
  9001. maxlength="3"
  9002. name="max_'.$item['id'].'"
  9003. type="number"
  9004. min="0"
  9005. step="1"
  9006. max="'.$item['max_score'].'"
  9007. value="'.$selectedMaxScoreValue.'"
  9008. />';
  9009. $return .= '</td>';
  9010. }
  9011. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9012. $return .= '<td>';
  9013. $return .= '<input
  9014. size="4"
  9015. maxlength="3"
  9016. name="min_'.$item['id'].'"
  9017. type="number"
  9018. min="0"
  9019. step="1"
  9020. max="'.$item['max_score'].'"
  9021. value="'.$selectedMinScoreValue.'"
  9022. />';
  9023. $return .= '</td>';
  9024. $return .= '<td>';
  9025. $return .= '<input
  9026. size="4"
  9027. maxlength="3"
  9028. name="max_'.$item['id'].'"
  9029. type="number"
  9030. min="0"
  9031. step="1"
  9032. max="'.$item['max_score'].'"
  9033. value="'.$selectedMaxScoreValue.'"
  9034. />';
  9035. $return .= '</td>';
  9036. }
  9037. $return .= '</tr>';
  9038. }
  9039. $return .= '<tr>';
  9040. $return .= '</tr>';
  9041. $return .= '</tbody>';
  9042. $return .= '</table>';
  9043. $return .= '</div>';
  9044. $return .= '<div class="form-group">';
  9045. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9046. get_lang('ModifyPrerequisites').'</button>';
  9047. $return .= '</form>';
  9048. return $return;
  9049. }
  9050. /**
  9051. * Return HTML list to allow prerequisites selection for lp.
  9052. *
  9053. * @return string HTML form
  9054. */
  9055. public function display_lp_prerequisites_list()
  9056. {
  9057. $course_id = api_get_course_int_id();
  9058. $lp_id = $this->lp_id;
  9059. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9060. // get current prerequisite
  9061. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9062. $result = Database::query($sql);
  9063. $row = Database::fetch_array($result);
  9064. $prerequisiteId = $row['prerequisite'];
  9065. $session_id = api_get_session_id();
  9066. $session_condition = api_get_session_condition($session_id, true, true);
  9067. $sql = "SELECT * FROM $tbl_lp
  9068. WHERE c_id = $course_id $session_condition
  9069. ORDER BY display_order ";
  9070. $rs = Database::query($sql);
  9071. $return = '';
  9072. $return .= '<select name="prerequisites" class="form-control">';
  9073. $return .= '<option value="0">'.get_lang('None').'</option>';
  9074. if (Database::num_rows($rs) > 0) {
  9075. while ($row = Database::fetch_array($rs)) {
  9076. if ($row['id'] == $lp_id) {
  9077. continue;
  9078. }
  9079. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9080. }
  9081. }
  9082. $return .= '</select>';
  9083. return $return;
  9084. }
  9085. /**
  9086. * Creates a list with all the documents in it.
  9087. *
  9088. * @param bool $showInvisibleFiles
  9089. *
  9090. * @throws Exception
  9091. * @throws HTML_QuickForm_Error
  9092. *
  9093. * @return string
  9094. */
  9095. public function get_documents($showInvisibleFiles = false)
  9096. {
  9097. $course_info = api_get_course_info();
  9098. $sessionId = api_get_session_id();
  9099. $documentTree = DocumentManager::get_document_preview(
  9100. $course_info,
  9101. $this->lp_id,
  9102. null,
  9103. $sessionId,
  9104. true,
  9105. null,
  9106. null,
  9107. $showInvisibleFiles,
  9108. true
  9109. );
  9110. $headers = [
  9111. get_lang('Files'),
  9112. get_lang('CreateTheDocument'),
  9113. get_lang('Upload'),
  9114. ];
  9115. $form = new FormValidator(
  9116. 'form_upload',
  9117. 'POST',
  9118. $this->getCurrentBuildingModeURL(),
  9119. '',
  9120. ['enctype' => 'multipart/form-data']
  9121. );
  9122. $folders = DocumentManager::get_all_document_folders(
  9123. api_get_course_info(),
  9124. 0,
  9125. true
  9126. );
  9127. DocumentManager::build_directory_selector(
  9128. $folders,
  9129. '',
  9130. [],
  9131. true,
  9132. $form,
  9133. 'directory_parent_id'
  9134. );
  9135. $group = [
  9136. $form->createElement(
  9137. 'radio',
  9138. 'if_exists',
  9139. get_lang("UplWhatIfFileExists"),
  9140. get_lang('UplDoNothing'),
  9141. 'nothing'
  9142. ),
  9143. $form->createElement(
  9144. 'radio',
  9145. 'if_exists',
  9146. null,
  9147. get_lang('UplOverwriteLong'),
  9148. 'overwrite'
  9149. ),
  9150. $form->createElement(
  9151. 'radio',
  9152. 'if_exists',
  9153. null,
  9154. get_lang('UplRenameLong'),
  9155. 'rename'
  9156. ),
  9157. ];
  9158. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9159. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9160. $defaultFileExistsOption = 'rename';
  9161. if (!empty($fileExistsOption)) {
  9162. $defaultFileExistsOption = $fileExistsOption;
  9163. }
  9164. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9165. // Check box options
  9166. $form->addElement(
  9167. 'checkbox',
  9168. 'unzip',
  9169. get_lang('Options'),
  9170. get_lang('Uncompress')
  9171. );
  9172. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9173. $form->addMultipleUpload($url);
  9174. $new = $this->display_document_form('add', 0);
  9175. $tabs = Display::tabs(
  9176. $headers,
  9177. [$documentTree, $new, $form->returnForm()],
  9178. 'subtab'
  9179. );
  9180. return $tabs;
  9181. }
  9182. /**
  9183. * Creates a list with all the exercises (quiz) in it.
  9184. *
  9185. * @return string
  9186. */
  9187. public function get_exercises()
  9188. {
  9189. $course_id = api_get_course_int_id();
  9190. $session_id = api_get_session_id();
  9191. $userInfo = api_get_user_info();
  9192. // New for hotpotatoes.
  9193. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9194. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9195. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9196. $condition_session = api_get_session_condition($session_id, true, true);
  9197. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9198. $activeCondition = ' active <> -1 ';
  9199. if ($setting) {
  9200. $activeCondition = ' active = 1 ';
  9201. }
  9202. $sql_quiz = "SELECT * FROM $tbl_quiz
  9203. WHERE c_id = $course_id AND $activeCondition $condition_session
  9204. ORDER BY title ASC";
  9205. $sql_hot = "SELECT * FROM $tbl_doc
  9206. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9207. ORDER BY id ASC";
  9208. $res_quiz = Database::query($sql_quiz);
  9209. $res_hot = Database::query($sql_hot);
  9210. $return = '<ul class="lp_resource">';
  9211. $return .= '<li class="lp_resource_element">';
  9212. $return .= Display::return_icon('new_exercice.png');
  9213. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9214. get_lang('NewExercise').'</a>';
  9215. $return .= '</li>';
  9216. $previewIcon = Display::return_icon(
  9217. 'preview_view.png',
  9218. get_lang('Preview')
  9219. );
  9220. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9221. // Display hotpotatoes
  9222. while ($row_hot = Database::fetch_array($res_hot)) {
  9223. $link = Display::url(
  9224. $previewIcon,
  9225. $exerciseUrl.'&file='.$row_hot['path'],
  9226. ['target' => '_blank']
  9227. );
  9228. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9229. $return .= '<a class="moved" href="#">';
  9230. $return .= Display::return_icon(
  9231. 'move_everywhere.png',
  9232. get_lang('Move'),
  9233. [],
  9234. ICON_SIZE_TINY
  9235. );
  9236. $return .= '</a> ';
  9237. $return .= Display::return_icon('hotpotatoes_s.png');
  9238. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9239. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9240. $return .= '</li>';
  9241. }
  9242. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9243. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9244. $title = strip_tags(
  9245. api_html_entity_decode($row_quiz['title'])
  9246. );
  9247. $link = Display::url(
  9248. $previewIcon,
  9249. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9250. ['target' => '_blank']
  9251. );
  9252. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9253. $return .= '<a class="moved" href="#">';
  9254. $return .= Display::return_icon(
  9255. 'move_everywhere.png',
  9256. get_lang('Move'),
  9257. [],
  9258. ICON_SIZE_TINY
  9259. );
  9260. $return .= '</a> ';
  9261. $return .= Display::return_icon(
  9262. 'quiz.png',
  9263. '',
  9264. [],
  9265. ICON_SIZE_TINY
  9266. );
  9267. $sessionStar = api_get_session_image(
  9268. $row_quiz['session_id'],
  9269. $userInfo['status']
  9270. );
  9271. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id.'">'.
  9272. Security::remove_XSS(cut($title, 80)).$link.$sessionStar.
  9273. '</a>';
  9274. $return .= '</li>';
  9275. }
  9276. $return .= '</ul>';
  9277. return $return;
  9278. }
  9279. /**
  9280. * Creates a list with all the links in it.
  9281. *
  9282. * @return string
  9283. */
  9284. public function get_links()
  9285. {
  9286. $selfUrl = api_get_self();
  9287. $courseIdReq = api_get_cidreq();
  9288. $course = api_get_course_info();
  9289. $userInfo = api_get_user_info();
  9290. $course_id = $course['real_id'];
  9291. $tbl_link = Database::get_course_table(TABLE_LINK);
  9292. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9293. $moveEverywhereIcon = Display::return_icon(
  9294. 'move_everywhere.png',
  9295. get_lang('Move'),
  9296. [],
  9297. ICON_SIZE_TINY
  9298. );
  9299. $session_id = api_get_session_id();
  9300. $condition_session = api_get_session_condition(
  9301. $session_id,
  9302. true,
  9303. true,
  9304. "link.session_id"
  9305. );
  9306. $sql = "SELECT
  9307. link.id as link_id,
  9308. link.title as link_title,
  9309. link.session_id as link_session_id,
  9310. link.category_id as category_id,
  9311. link_category.category_title as category_title
  9312. FROM $tbl_link as link
  9313. LEFT JOIN $linkCategoryTable as link_category
  9314. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9315. WHERE link.c_id = ".$course_id." $condition_session
  9316. ORDER BY link_category.category_title ASC, link.title ASC";
  9317. $result = Database::query($sql);
  9318. $categorizedLinks = [];
  9319. $categories = [];
  9320. while ($link = Database::fetch_array($result)) {
  9321. if (!$link['category_id']) {
  9322. $link['category_title'] = get_lang('Uncategorized');
  9323. }
  9324. $categories[$link['category_id']] = $link['category_title'];
  9325. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9326. }
  9327. $linksHtmlCode =
  9328. '<script>
  9329. function toggle_tool(tool, id) {
  9330. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9331. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9332. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9333. } else {
  9334. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9335. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9336. }
  9337. }
  9338. </script>
  9339. <ul class="lp_resource">
  9340. <li class="lp_resource_element">
  9341. '.Display::return_icon('linksnew.gif').'
  9342. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9343. get_lang('LinkAdd').'
  9344. </a>
  9345. </li>';
  9346. foreach ($categorizedLinks as $categoryId => $links) {
  9347. $linkNodes = null;
  9348. foreach ($links as $key => $linkInfo) {
  9349. $title = $linkInfo['link_title'];
  9350. $linkSessionId = $linkInfo['link_session_id'];
  9351. $link = Display::url(
  9352. Display::return_icon('preview_view.png', get_lang('Preview')),
  9353. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9354. ['target' => '_blank']
  9355. );
  9356. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9357. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9358. $linkNodes .=
  9359. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9360. <a class="moved" href="#">'.
  9361. $moveEverywhereIcon.
  9362. '</a>
  9363. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9364. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9365. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9366. Security::remove_XSS($title).$sessionStar.$link.
  9367. '</a>
  9368. </li>';
  9369. }
  9370. }
  9371. $linksHtmlCode .=
  9372. '<li>
  9373. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9374. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9375. align="absbottom" />
  9376. </a>
  9377. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9378. </li>
  9379. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9380. }
  9381. $linksHtmlCode .= '</ul>';
  9382. return $linksHtmlCode;
  9383. }
  9384. /**
  9385. * Creates a list with all the student publications in it.
  9386. *
  9387. * @return string
  9388. */
  9389. public function get_student_publications()
  9390. {
  9391. $return = '<ul class="lp_resource">';
  9392. $return .= '<li class="lp_resource_element">';
  9393. $return .= Display::return_icon('works_new.gif');
  9394. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9395. get_lang('AddAssignmentPage').'</a>';
  9396. $return .= '</li>';
  9397. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9398. $works = getWorkListTeacher(0, 100, null, null, null);
  9399. if (!empty($works)) {
  9400. foreach ($works as $work) {
  9401. $link = Display::url(
  9402. Display::return_icon('preview_view.png', get_lang('Preview')),
  9403. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9404. ['target' => '_blank']
  9405. );
  9406. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9407. $return .= '<a class="moved" href="#">';
  9408. $return .= Display::return_icon(
  9409. 'move_everywhere.png',
  9410. get_lang('Move'),
  9411. [],
  9412. ICON_SIZE_TINY
  9413. );
  9414. $return .= '</a> ';
  9415. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9416. $return .= ' <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id.'">'.
  9417. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9418. </a>';
  9419. $return .= '</li>';
  9420. }
  9421. }
  9422. $return .= '</ul>';
  9423. return $return;
  9424. }
  9425. /**
  9426. * Creates a list with all the forums in it.
  9427. *
  9428. * @return string
  9429. */
  9430. public function get_forums()
  9431. {
  9432. require_once '../forum/forumfunction.inc.php';
  9433. require_once '../forum/forumconfig.inc.php';
  9434. $forumCategories = get_forum_categories();
  9435. $forumsInNoCategory = get_forums_in_category(0);
  9436. if (!empty($forumsInNoCategory)) {
  9437. $forumCategories = array_merge(
  9438. $forumCategories,
  9439. [
  9440. [
  9441. 'cat_id' => 0,
  9442. 'session_id' => 0,
  9443. 'visibility' => 1,
  9444. 'cat_comment' => null,
  9445. ],
  9446. ]
  9447. );
  9448. }
  9449. $forumList = get_forums();
  9450. $a_forums = [];
  9451. foreach ($forumCategories as $forumCategory) {
  9452. // The forums in this category.
  9453. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9454. if (!empty($forumsInCategory)) {
  9455. foreach ($forumList as $forum) {
  9456. if (isset($forum['forum_category']) &&
  9457. $forum['forum_category'] == $forumCategory['cat_id']
  9458. ) {
  9459. $a_forums[] = $forum;
  9460. }
  9461. }
  9462. }
  9463. }
  9464. $return = '<ul class="lp_resource">';
  9465. // First add link
  9466. $return .= '<li class="lp_resource_element">';
  9467. $return .= Display::return_icon('new_forum.png');
  9468. $return .= Display::url(
  9469. get_lang('CreateANewForum'),
  9470. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9471. 'action' => 'add',
  9472. 'content' => 'forum',
  9473. 'lp_id' => $this->lp_id,
  9474. ]),
  9475. ['title' => get_lang('CreateANewForum')]
  9476. );
  9477. $return .= '</li>';
  9478. $return .= '<script>
  9479. function toggle_forum(forum_id) {
  9480. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9481. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9482. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9483. } else {
  9484. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9485. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9486. }
  9487. }
  9488. </script>';
  9489. foreach ($a_forums as $forum) {
  9490. if (!empty($forum['forum_id'])) {
  9491. $link = Display::url(
  9492. Display::return_icon('preview_view.png', get_lang('Preview')),
  9493. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9494. ['target' => '_blank']
  9495. );
  9496. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9497. $return .= '<a class="moved" href="#">';
  9498. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9499. $return .= ' </a>';
  9500. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9501. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9502. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9503. </a>
  9504. <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_FORUM.'&forum_id='.$forum['forum_id'].'&lp_id='.$this->lp_id.'" style="vertical-align:middle">'.
  9505. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9506. $return .= '</li>';
  9507. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9508. $a_threads = get_threads($forum['forum_id']);
  9509. if (is_array($a_threads)) {
  9510. foreach ($a_threads as $thread) {
  9511. $link = Display::url(
  9512. Display::return_icon('preview_view.png', get_lang('Preview')),
  9513. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9514. ['target' => '_blank']
  9515. );
  9516. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9517. $return .= '&nbsp;<a class="moved" href="#">';
  9518. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9519. $return .= ' </a>';
  9520. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9521. $return .= '<a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_THREAD.'&thread_id='.$thread['thread_id'].'&lp_id='.$this->lp_id.'">'.
  9522. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9523. $return .= '</li>';
  9524. }
  9525. }
  9526. $return .= '</div>';
  9527. }
  9528. }
  9529. $return .= '</ul>';
  9530. return $return;
  9531. }
  9532. /**
  9533. * // TODO: The output encoding should be equal to the system encoding.
  9534. *
  9535. * Exports the learning path as a SCORM package. This is the main function that
  9536. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9537. * whole thing and returns the zip.
  9538. *
  9539. * This method needs to be called in PHP5, as it will fail with non-adequate
  9540. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9541. * you need to call it on a learnpath object.
  9542. *
  9543. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9544. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9545. * path has been modified, it should use the generic method here below.
  9546. *
  9547. * @return string Returns the zip package string, or null if error
  9548. */
  9549. public function scormExport()
  9550. {
  9551. api_set_more_memory_and_time_limits();
  9552. $_course = api_get_course_info();
  9553. $course_id = $_course['real_id'];
  9554. // Create the zip handler (this will remain available throughout the method).
  9555. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9556. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9557. $temp_dir_short = uniqid('scorm_export', true);
  9558. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9559. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9560. $zip_folder = new PclZip($temp_zip_file);
  9561. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9562. $root_path = $main_path = api_get_path(SYS_PATH);
  9563. $files_cleanup = [];
  9564. // Place to temporarily stash the zip file.
  9565. // create the temp dir if it doesn't exist
  9566. // or do a cleanup before creating the zip file.
  9567. if (!is_dir($temp_zip_dir)) {
  9568. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9569. } else {
  9570. // Cleanup: Check the temp dir for old files and delete them.
  9571. $handle = opendir($temp_zip_dir);
  9572. while (false !== ($file = readdir($handle))) {
  9573. if ($file != '.' && $file != '..') {
  9574. unlink("$temp_zip_dir/$file");
  9575. }
  9576. }
  9577. closedir($handle);
  9578. }
  9579. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9580. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9581. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9582. ) {
  9583. // Remove the possible . at the end of the path.
  9584. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9585. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9586. mkdir(
  9587. $dest_path_to_scorm_folder,
  9588. api_get_permissions_for_new_directories(),
  9589. true
  9590. );
  9591. copyr(
  9592. $current_course_path.'/scorm/'.$this->path,
  9593. $dest_path_to_scorm_folder,
  9594. ['imsmanifest'],
  9595. $zip_files
  9596. );
  9597. }
  9598. // Build a dummy imsmanifest structure.
  9599. // Do not add to the zip yet (we still need it).
  9600. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9601. // Aggregation Model official document, section "2.3 Content Packaging".
  9602. // We are going to build a UTF-8 encoded manifest.
  9603. // Later we will recode it to the desired (and supported) encoding.
  9604. $xmldoc = new DOMDocument('1.0');
  9605. $root = $xmldoc->createElement('manifest');
  9606. $root->setAttribute('identifier', 'SingleCourseManifest');
  9607. $root->setAttribute('version', '1.1');
  9608. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9609. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9610. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9611. $root->setAttribute(
  9612. 'xsi:schemaLocation',
  9613. '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'
  9614. );
  9615. // Build mandatory sub-root container elements.
  9616. $metadata = $xmldoc->createElement('metadata');
  9617. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9618. $metadata->appendChild($md_schema);
  9619. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9620. $metadata->appendChild($md_schemaversion);
  9621. $root->appendChild($metadata);
  9622. $organizations = $xmldoc->createElement('organizations');
  9623. $resources = $xmldoc->createElement('resources');
  9624. // Build the only organization we will use in building our learnpaths.
  9625. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9626. $organization = $xmldoc->createElement('organization');
  9627. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9628. // To set the title of the SCORM entity (=organization), we take the name given
  9629. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9630. // learning path charset) as it is the encoding that defines how it is stored
  9631. // in the database. Then we convert it to HTML entities again as the "&" character
  9632. // alone is not authorized in XML (must be &amp;).
  9633. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9634. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9635. $organization->appendChild($org_title);
  9636. $folder_name = 'document';
  9637. // Removes the learning_path/scorm_folder path when exporting see #4841
  9638. $path_to_remove = '';
  9639. $path_to_replace = '';
  9640. $result = $this->generate_lp_folder($_course);
  9641. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9642. $path_to_remove = 'document'.$result['dir'];
  9643. $path_to_replace = $folder_name.'/';
  9644. }
  9645. // Fixes chamilo scorm exports
  9646. if ($this->ref === 'chamilo_scorm_export') {
  9647. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9648. }
  9649. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9650. $link_updates = [];
  9651. $links_to_create = [];
  9652. foreach ($this->ordered_items as $index => $itemId) {
  9653. /** @var learnpathItem $item */
  9654. $item = $this->items[$itemId];
  9655. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9656. // Get included documents from this item.
  9657. if ($item->type === 'sco') {
  9658. $inc_docs = $item->get_resources_from_source(
  9659. null,
  9660. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  9661. );
  9662. } else {
  9663. $inc_docs = $item->get_resources_from_source();
  9664. }
  9665. // Give a child element <item> to the <organization> element.
  9666. $my_item_id = $item->get_id();
  9667. $my_item = $xmldoc->createElement('item');
  9668. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9669. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9670. $my_item->setAttribute('isvisible', 'true');
  9671. // Give a child element <title> to the <item> element.
  9672. $my_title = $xmldoc->createElement(
  9673. 'title',
  9674. htmlspecialchars(
  9675. api_utf8_encode($item->get_title()),
  9676. ENT_QUOTES,
  9677. 'UTF-8'
  9678. )
  9679. );
  9680. $my_item->appendChild($my_title);
  9681. // Give a child element <adlcp:prerequisites> to the <item> element.
  9682. $my_prereqs = $xmldoc->createElement(
  9683. 'adlcp:prerequisites',
  9684. $this->get_scorm_prereq_string($my_item_id)
  9685. );
  9686. $my_prereqs->setAttribute('type', 'aicc_script');
  9687. $my_item->appendChild($my_prereqs);
  9688. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9689. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9690. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9691. //$xmldoc->createElement('adlcp:timelimitaction','');
  9692. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9693. //$xmldoc->createElement('adlcp:datafromlms','');
  9694. // Give a child element <adlcp:masteryscore> to the <item> element.
  9695. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9696. $my_item->appendChild($my_masteryscore);
  9697. // Attach this item to the organization element or hits parent if there is one.
  9698. if (!empty($item->parent) && $item->parent != 0) {
  9699. $children = $organization->childNodes;
  9700. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9701. if (is_object($possible_parent)) {
  9702. $possible_parent->appendChild($my_item);
  9703. } else {
  9704. if ($this->debug > 0) {
  9705. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9706. }
  9707. }
  9708. } else {
  9709. if ($this->debug > 0) {
  9710. error_log('No parent');
  9711. }
  9712. $organization->appendChild($my_item);
  9713. }
  9714. // Get the path of the file(s) from the course directory root.
  9715. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9716. $my_xml_file_path = $my_file_path;
  9717. if (!empty($path_to_remove)) {
  9718. // From docs
  9719. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9720. // From quiz
  9721. if ($this->ref === 'chamilo_scorm_export') {
  9722. $path_to_remove = 'scorm/'.$this->path.'/';
  9723. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9724. }
  9725. }
  9726. $my_sub_dir = dirname($my_file_path);
  9727. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9728. $my_xml_sub_dir = $my_sub_dir;
  9729. // Give a <resource> child to the <resources> element
  9730. $my_resource = $xmldoc->createElement('resource');
  9731. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9732. $my_resource->setAttribute('type', 'webcontent');
  9733. $my_resource->setAttribute('href', $my_xml_file_path);
  9734. // adlcp:scormtype can be either 'sco' or 'asset'.
  9735. if ($item->type === 'sco') {
  9736. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9737. } else {
  9738. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9739. }
  9740. // xml:base is the base directory to find the files declared in this resource.
  9741. $my_resource->setAttribute('xml:base', '');
  9742. // Give a <file> child to the <resource> element.
  9743. $my_file = $xmldoc->createElement('file');
  9744. $my_file->setAttribute('href', $my_xml_file_path);
  9745. $my_resource->appendChild($my_file);
  9746. // Dependency to other files - not yet supported.
  9747. $i = 1;
  9748. if ($inc_docs) {
  9749. foreach ($inc_docs as $doc_info) {
  9750. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9751. continue;
  9752. }
  9753. $my_dep = $xmldoc->createElement('resource');
  9754. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9755. $my_dep->setAttribute('identifier', $res_id);
  9756. $my_dep->setAttribute('type', 'webcontent');
  9757. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9758. $my_dep_file = $xmldoc->createElement('file');
  9759. // Check type of URL.
  9760. if ($doc_info[1] == 'remote') {
  9761. // Remote file. Save url as is.
  9762. $my_dep_file->setAttribute('href', $doc_info[0]);
  9763. $my_dep->setAttribute('xml:base', '');
  9764. } elseif ($doc_info[1] === 'local') {
  9765. switch ($doc_info[2]) {
  9766. case 'url':
  9767. // Local URL - save path as url for now, don't zip file.
  9768. $abs_path = api_get_path(SYS_PATH).
  9769. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9770. $current_dir = dirname($abs_path);
  9771. $current_dir = str_replace('\\', '/', $current_dir);
  9772. $file_path = realpath($abs_path);
  9773. $file_path = str_replace('\\', '/', $file_path);
  9774. $my_dep_file->setAttribute('href', $file_path);
  9775. $my_dep->setAttribute('xml:base', '');
  9776. if (strstr($file_path, $main_path) !== false) {
  9777. // The calculated real path is really inside Chamilo's root path.
  9778. // Reduce file path to what's under the DocumentRoot.
  9779. $replace = $file_path;
  9780. $file_path = substr($file_path, strlen($root_path) - 1);
  9781. $destinationFile = $file_path;
  9782. if (strstr($file_path, 'upload/users') !== false) {
  9783. $pos = strpos($file_path, 'my_files/');
  9784. if ($pos !== false) {
  9785. $onlyDirectory = str_replace(
  9786. 'upload/users/',
  9787. '',
  9788. substr($file_path, $pos, strlen($file_path))
  9789. );
  9790. }
  9791. $replace = $onlyDirectory;
  9792. $destinationFile = $replace;
  9793. }
  9794. $zip_files_abs[] = $file_path;
  9795. $link_updates[$my_file_path][] = [
  9796. 'orig' => $doc_info[0],
  9797. 'dest' => $destinationFile,
  9798. 'replace' => $replace,
  9799. ];
  9800. $my_dep_file->setAttribute('href', $file_path);
  9801. $my_dep->setAttribute('xml:base', '');
  9802. } elseif (empty($file_path)) {
  9803. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9804. $file_path = str_replace('//', '/', $file_path);
  9805. if (file_exists($file_path)) {
  9806. // We get the relative path.
  9807. $file_path = substr($file_path, strlen($current_dir));
  9808. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9809. $link_updates[$my_file_path][] = [
  9810. 'orig' => $doc_info[0],
  9811. 'dest' => $file_path,
  9812. ];
  9813. $my_dep_file->setAttribute('href', $file_path);
  9814. $my_dep->setAttribute('xml:base', '');
  9815. }
  9816. }
  9817. break;
  9818. case 'abs':
  9819. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9820. $my_dep_file->setAttribute('href', $doc_info[0]);
  9821. $my_dep->setAttribute('xml:base', '');
  9822. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9823. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9824. $abs_img_path_without_subdir = $doc_info[0];
  9825. $relp = api_get_path(REL_PATH); // The url-append config param.
  9826. $pos = strpos($abs_img_path_without_subdir, $relp);
  9827. if ($pos === 0) {
  9828. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  9829. }
  9830. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9831. $file_path = str_replace(['\\', '//'], '/', $file_path);
  9832. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9833. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9834. // Check if the current document is in that path.
  9835. if (strstr($file_path, $cur_path) !== false) {
  9836. $destinationFile = substr($file_path, strlen($cur_path));
  9837. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  9838. $fileToTest = $cur_path.$my_file_path;
  9839. if (!empty($path_to_remove)) {
  9840. $fileToTest = str_replace(
  9841. $path_to_remove.'/',
  9842. $path_to_replace,
  9843. $cur_path.$my_file_path
  9844. );
  9845. }
  9846. $relative_path = api_get_relative_path($fileToTest, $file_path);
  9847. // Put the current document in the zip (this array is the array
  9848. // that will manage documents already in the course folder - relative).
  9849. $zip_files[] = $filePathNoCoursePart;
  9850. // Update the links to the current document in the
  9851. // containing document (make them relative).
  9852. $link_updates[$my_file_path][] = [
  9853. 'orig' => $doc_info[0],
  9854. 'dest' => $destinationFile,
  9855. 'replace' => $relative_path,
  9856. ];
  9857. $my_dep_file->setAttribute('href', $file_path);
  9858. $my_dep->setAttribute('xml:base', '');
  9859. } elseif (strstr($file_path, $main_path) !== false) {
  9860. // The calculated real path is really inside Chamilo's root path.
  9861. // Reduce file path to what's under the DocumentRoot.
  9862. $file_path = substr($file_path, strlen($root_path));
  9863. $zip_files_abs[] = $file_path;
  9864. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9865. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9866. $my_dep->setAttribute('xml:base', '');
  9867. } elseif (empty($file_path)) {
  9868. // Probably this is an image inside "/main" directory
  9869. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  9870. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9871. if (file_exists($file_path)) {
  9872. if (strstr($file_path, 'main/default_course_document') !== false) {
  9873. // We get the relative path.
  9874. $pos = strpos($file_path, 'main/default_course_document/');
  9875. if ($pos !== false) {
  9876. $onlyDirectory = str_replace(
  9877. 'main/default_course_document/',
  9878. '',
  9879. substr($file_path, $pos, strlen($file_path))
  9880. );
  9881. }
  9882. $destinationFile = 'default_course_document/'.$onlyDirectory;
  9883. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  9884. $zip_files_abs[] = $fileAbs;
  9885. $link_updates[$my_file_path][] = [
  9886. 'orig' => $doc_info[0],
  9887. 'dest' => $destinationFile,
  9888. ];
  9889. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9890. $my_dep->setAttribute('xml:base', '');
  9891. }
  9892. }
  9893. }
  9894. break;
  9895. case 'rel':
  9896. // Path relative to the current document.
  9897. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9898. if (substr($doc_info[0], 0, 2) === '..') {
  9899. // Relative path going up.
  9900. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9901. $current_dir = str_replace('\\', '/', $current_dir);
  9902. $file_path = realpath($current_dir.$doc_info[0]);
  9903. $file_path = str_replace('\\', '/', $file_path);
  9904. if (strstr($file_path, $main_path) !== false) {
  9905. // The calculated real path is really inside Chamilo's root path.
  9906. // Reduce file path to what's under the DocumentRoot.
  9907. $file_path = substr($file_path, strlen($root_path));
  9908. $zip_files_abs[] = $file_path;
  9909. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9910. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9911. $my_dep->setAttribute('xml:base', '');
  9912. }
  9913. } else {
  9914. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9915. $my_dep_file->setAttribute('href', $doc_info[0]);
  9916. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9917. }
  9918. break;
  9919. default:
  9920. $my_dep_file->setAttribute('href', $doc_info[0]);
  9921. $my_dep->setAttribute('xml:base', '');
  9922. break;
  9923. }
  9924. }
  9925. $my_dep->appendChild($my_dep_file);
  9926. $resources->appendChild($my_dep);
  9927. $dependency = $xmldoc->createElement('dependency');
  9928. $dependency->setAttribute('identifierref', $res_id);
  9929. $my_resource->appendChild($dependency);
  9930. $i++;
  9931. }
  9932. }
  9933. $resources->appendChild($my_resource);
  9934. $zip_files[] = $my_file_path;
  9935. } else {
  9936. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9937. switch ($item->type) {
  9938. case TOOL_LINK:
  9939. $my_item = $xmldoc->createElement('item');
  9940. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9941. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9942. $my_item->setAttribute('isvisible', 'true');
  9943. // Give a child element <title> to the <item> element.
  9944. $my_title = $xmldoc->createElement(
  9945. 'title',
  9946. htmlspecialchars(
  9947. api_utf8_encode($item->get_title()),
  9948. ENT_QUOTES,
  9949. 'UTF-8'
  9950. )
  9951. );
  9952. $my_item->appendChild($my_title);
  9953. // Give a child element <adlcp:prerequisites> to the <item> element.
  9954. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9955. $my_prereqs->setAttribute('type', 'aicc_script');
  9956. $my_item->appendChild($my_prereqs);
  9957. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9958. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9959. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9960. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9961. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9962. //$xmldoc->createElement('adlcp:datafromlms', '');
  9963. // Give a child element <adlcp:masteryscore> to the <item> element.
  9964. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9965. $my_item->appendChild($my_masteryscore);
  9966. // Attach this item to the organization element or its parent if there is one.
  9967. if (!empty($item->parent) && $item->parent != 0) {
  9968. $children = $organization->childNodes;
  9969. for ($i = 0; $i < $children->length; $i++) {
  9970. $item_temp = $children->item($i);
  9971. if ($item_temp->nodeName == 'item') {
  9972. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9973. $item_temp->appendChild($my_item);
  9974. }
  9975. }
  9976. }
  9977. } else {
  9978. $organization->appendChild($my_item);
  9979. }
  9980. $my_file_path = 'link_'.$item->get_id().'.html';
  9981. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9982. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  9983. $rs = Database::query($sql);
  9984. if ($link = Database::fetch_array($rs)) {
  9985. $url = $link['url'];
  9986. $title = stripslashes($link['title']);
  9987. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9988. $my_xml_file_path = $my_file_path;
  9989. $my_sub_dir = dirname($my_file_path);
  9990. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9991. $my_xml_sub_dir = $my_sub_dir;
  9992. // Give a <resource> child to the <resources> element.
  9993. $my_resource = $xmldoc->createElement('resource');
  9994. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9995. $my_resource->setAttribute('type', 'webcontent');
  9996. $my_resource->setAttribute('href', $my_xml_file_path);
  9997. // adlcp:scormtype can be either 'sco' or 'asset'.
  9998. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9999. // xml:base is the base directory to find the files declared in this resource.
  10000. $my_resource->setAttribute('xml:base', '');
  10001. // give a <file> child to the <resource> element.
  10002. $my_file = $xmldoc->createElement('file');
  10003. $my_file->setAttribute('href', $my_xml_file_path);
  10004. $my_resource->appendChild($my_file);
  10005. $resources->appendChild($my_resource);
  10006. }
  10007. break;
  10008. case TOOL_QUIZ:
  10009. $exe_id = $item->path;
  10010. // Should be using ref when everything will be cleaned up in this regard.
  10011. $exe = new Exercise();
  10012. $exe->read($exe_id);
  10013. $my_item = $xmldoc->createElement('item');
  10014. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10015. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10016. $my_item->setAttribute('isvisible', 'true');
  10017. // Give a child element <title> to the <item> element.
  10018. $my_title = $xmldoc->createElement(
  10019. 'title',
  10020. htmlspecialchars(
  10021. api_utf8_encode($item->get_title()),
  10022. ENT_QUOTES,
  10023. 'UTF-8'
  10024. )
  10025. );
  10026. $my_item->appendChild($my_title);
  10027. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10028. $my_item->appendChild($my_max_score);
  10029. // Give a child element <adlcp:prerequisites> to the <item> element.
  10030. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10031. $my_prereqs->setAttribute('type', 'aicc_script');
  10032. $my_item->appendChild($my_prereqs);
  10033. // Give a child element <adlcp:masteryscore> to the <item> element.
  10034. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10035. $my_item->appendChild($my_masteryscore);
  10036. // Attach this item to the organization element or hits parent if there is one.
  10037. if (!empty($item->parent) && $item->parent != 0) {
  10038. $children = $organization->childNodes;
  10039. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10040. if ($possible_parent) {
  10041. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10042. $possible_parent->appendChild($my_item);
  10043. }
  10044. }
  10045. } else {
  10046. $organization->appendChild($my_item);
  10047. }
  10048. // Get the path of the file(s) from the course directory root
  10049. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10050. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10051. // Write the contents of the exported exercise into a (big) html file
  10052. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10053. $scormExercise = new ScormExercise($exe, true);
  10054. $contents = $scormExercise->export();
  10055. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10056. $res = file_put_contents($tmp_file_path, $contents);
  10057. if ($res === false) {
  10058. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10059. }
  10060. $files_cleanup[] = $tmp_file_path;
  10061. $my_xml_file_path = $my_file_path;
  10062. $my_sub_dir = dirname($my_file_path);
  10063. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10064. $my_xml_sub_dir = $my_sub_dir;
  10065. // Give a <resource> child to the <resources> element.
  10066. $my_resource = $xmldoc->createElement('resource');
  10067. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10068. $my_resource->setAttribute('type', 'webcontent');
  10069. $my_resource->setAttribute('href', $my_xml_file_path);
  10070. // adlcp:scormtype can be either 'sco' or 'asset'.
  10071. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10072. // xml:base is the base directory to find the files declared in this resource.
  10073. $my_resource->setAttribute('xml:base', '');
  10074. // Give a <file> child to the <resource> element.
  10075. $my_file = $xmldoc->createElement('file');
  10076. $my_file->setAttribute('href', $my_xml_file_path);
  10077. $my_resource->appendChild($my_file);
  10078. // Get included docs.
  10079. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10080. // Dependency to other files - not yet supported.
  10081. $i = 1;
  10082. foreach ($inc_docs as $doc_info) {
  10083. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10084. continue;
  10085. }
  10086. $my_dep = $xmldoc->createElement('resource');
  10087. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10088. $my_dep->setAttribute('identifier', $res_id);
  10089. $my_dep->setAttribute('type', 'webcontent');
  10090. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10091. $my_dep_file = $xmldoc->createElement('file');
  10092. // Check type of URL.
  10093. if ($doc_info[1] == 'remote') {
  10094. // Remote file. Save url as is.
  10095. $my_dep_file->setAttribute('href', $doc_info[0]);
  10096. $my_dep->setAttribute('xml:base', '');
  10097. } elseif ($doc_info[1] == 'local') {
  10098. switch ($doc_info[2]) {
  10099. case 'url': // Local URL - save path as url for now, don't zip file.
  10100. // Save file but as local file (retrieve from URL).
  10101. $abs_path = api_get_path(SYS_PATH).
  10102. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10103. $current_dir = dirname($abs_path);
  10104. $current_dir = str_replace('\\', '/', $current_dir);
  10105. $file_path = realpath($abs_path);
  10106. $file_path = str_replace('\\', '/', $file_path);
  10107. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10108. $my_dep->setAttribute('xml:base', '');
  10109. if (strstr($file_path, $main_path) !== false) {
  10110. // The calculated real path is really inside the chamilo root path.
  10111. // Reduce file path to what's under the DocumentRoot.
  10112. $file_path = substr($file_path, strlen($root_path));
  10113. $zip_files_abs[] = $file_path;
  10114. $link_updates[$my_file_path][] = [
  10115. 'orig' => $doc_info[0],
  10116. 'dest' => 'document/'.$file_path,
  10117. ];
  10118. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10119. $my_dep->setAttribute('xml:base', '');
  10120. } elseif (empty($file_path)) {
  10121. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10122. $file_path = str_replace('//', '/', $file_path);
  10123. if (file_exists($file_path)) {
  10124. $file_path = substr($file_path, strlen($current_dir));
  10125. // We get the relative path.
  10126. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10127. $link_updates[$my_file_path][] = [
  10128. 'orig' => $doc_info[0],
  10129. 'dest' => 'document/'.$file_path,
  10130. ];
  10131. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10132. $my_dep->setAttribute('xml:base', '');
  10133. }
  10134. }
  10135. break;
  10136. case 'abs':
  10137. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10138. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10139. $current_dir = str_replace('\\', '/', $current_dir);
  10140. $file_path = realpath($doc_info[0]);
  10141. $file_path = str_replace('\\', '/', $file_path);
  10142. $my_dep_file->setAttribute('href', $file_path);
  10143. $my_dep->setAttribute('xml:base', '');
  10144. if (strstr($file_path, $main_path) !== false) {
  10145. // The calculated real path is really inside the chamilo root path.
  10146. // Reduce file path to what's under the DocumentRoot.
  10147. $file_path = substr($file_path, strlen($root_path));
  10148. $zip_files_abs[] = $file_path;
  10149. $link_updates[$my_file_path][] = [
  10150. 'orig' => $doc_info[0],
  10151. 'dest' => $file_path,
  10152. ];
  10153. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10154. $my_dep->setAttribute('xml:base', '');
  10155. } elseif (empty($file_path)) {
  10156. $docSysPartPath = str_replace(
  10157. api_get_path(REL_COURSE_PATH),
  10158. '',
  10159. $doc_info[0]
  10160. );
  10161. $docSysPartPathNoCourseCode = str_replace(
  10162. $_course['directory'].'/',
  10163. '',
  10164. $docSysPartPath
  10165. );
  10166. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10167. if (file_exists($docSysPath)) {
  10168. $file_path = $docSysPartPathNoCourseCode;
  10169. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10170. $link_updates[$my_file_path][] = [
  10171. 'orig' => $doc_info[0],
  10172. 'dest' => $file_path,
  10173. ];
  10174. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10175. $my_dep->setAttribute('xml:base', '');
  10176. }
  10177. }
  10178. break;
  10179. case 'rel':
  10180. // Path relative to the current document. Save xml:base as current document's
  10181. // directory and save file in zip as subdir.file_path
  10182. if (substr($doc_info[0], 0, 2) === '..') {
  10183. // Relative path going up.
  10184. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10185. $current_dir = str_replace('\\', '/', $current_dir);
  10186. $file_path = realpath($current_dir.$doc_info[0]);
  10187. $file_path = str_replace('\\', '/', $file_path);
  10188. //error_log($file_path.' <-> '.$main_path, 0);
  10189. if (strstr($file_path, $main_path) !== false) {
  10190. // The calculated real path is really inside Chamilo's root path.
  10191. // Reduce file path to what's under the DocumentRoot.
  10192. $file_path = substr($file_path, strlen($root_path));
  10193. $file_path_dest = $file_path;
  10194. // File path is courses/CHAMILO/document/....
  10195. $info_file_path = explode('/', $file_path);
  10196. if ($info_file_path[0] == 'courses') {
  10197. // Add character "/" in file path.
  10198. $file_path_dest = 'document/'.$file_path;
  10199. }
  10200. $zip_files_abs[] = $file_path;
  10201. $link_updates[$my_file_path][] = [
  10202. 'orig' => $doc_info[0],
  10203. 'dest' => $file_path_dest,
  10204. ];
  10205. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10206. $my_dep->setAttribute('xml:base', '');
  10207. }
  10208. } else {
  10209. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10210. $my_dep_file->setAttribute('href', $doc_info[0]);
  10211. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10212. }
  10213. break;
  10214. default:
  10215. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10216. $my_dep->setAttribute('xml:base', '');
  10217. break;
  10218. }
  10219. }
  10220. $my_dep->appendChild($my_dep_file);
  10221. $resources->appendChild($my_dep);
  10222. $dependency = $xmldoc->createElement('dependency');
  10223. $dependency->setAttribute('identifierref', $res_id);
  10224. $my_resource->appendChild($dependency);
  10225. $i++;
  10226. }
  10227. $resources->appendChild($my_resource);
  10228. $zip_files[] = $my_file_path;
  10229. break;
  10230. default:
  10231. // Get the path of the file(s) from the course directory root
  10232. $my_file_path = 'non_exportable.html';
  10233. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10234. $my_xml_file_path = $my_file_path;
  10235. $my_sub_dir = dirname($my_file_path);
  10236. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10237. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10238. $my_xml_sub_dir = $my_sub_dir;
  10239. // Give a <resource> child to the <resources> element.
  10240. $my_resource = $xmldoc->createElement('resource');
  10241. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10242. $my_resource->setAttribute('type', 'webcontent');
  10243. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10244. // adlcp:scormtype can be either 'sco' or 'asset'.
  10245. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10246. // xml:base is the base directory to find the files declared in this resource.
  10247. $my_resource->setAttribute('xml:base', '');
  10248. // Give a <file> child to the <resource> element.
  10249. $my_file = $xmldoc->createElement('file');
  10250. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10251. $my_resource->appendChild($my_file);
  10252. $resources->appendChild($my_resource);
  10253. break;
  10254. }
  10255. }
  10256. }
  10257. $organizations->appendChild($organization);
  10258. $root->appendChild($organizations);
  10259. $root->appendChild($resources);
  10260. $xmldoc->appendChild($root);
  10261. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10262. // then add the file to the zip, then destroy the file (this is done automatically).
  10263. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10264. foreach ($zip_files as $file_path) {
  10265. if (empty($file_path)) {
  10266. continue;
  10267. }
  10268. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10269. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10270. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10271. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10272. }
  10273. $this->create_path($dest_file);
  10274. @copy($filePath, $dest_file);
  10275. // Check if the file needs a link update.
  10276. if (in_array($file_path, array_keys($link_updates))) {
  10277. $string = file_get_contents($dest_file);
  10278. unlink($dest_file);
  10279. foreach ($link_updates[$file_path] as $old_new) {
  10280. // This is an ugly hack that allows .flv files to be found by the flv player that
  10281. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10282. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10283. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10284. if (substr($old_new['dest'], -3) === 'flv' &&
  10285. substr($old_new['dest'], 0, 5) === 'main/'
  10286. ) {
  10287. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10288. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10289. substr($old_new['dest'], 0, 6) === 'video/'
  10290. ) {
  10291. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10292. }
  10293. // Fix to avoid problems with default_course_document
  10294. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10295. $newDestination = $old_new['dest'];
  10296. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10297. $newDestination = $old_new['replace'];
  10298. }
  10299. } else {
  10300. $newDestination = str_replace('document/', '', $old_new['dest']);
  10301. }
  10302. $string = str_replace($old_new['orig'], $newDestination, $string);
  10303. // Add files inside the HTMLs
  10304. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10305. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10306. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10307. copy(
  10308. $sys_course_path.$new_path,
  10309. $destinationFile
  10310. );
  10311. }
  10312. }
  10313. file_put_contents($dest_file, $string);
  10314. }
  10315. if (file_exists($filePath) && $copyAll) {
  10316. $extension = $this->get_extension($filePath);
  10317. if (in_array($extension, ['html', 'html'])) {
  10318. $containerOrigin = dirname($filePath);
  10319. $containerDestination = dirname($dest_file);
  10320. $finder = new Finder();
  10321. $finder->files()->in($containerOrigin)
  10322. ->notName('*_DELETED_*')
  10323. ->exclude('share_folder')
  10324. ->exclude('chat_files')
  10325. ->exclude('certificates')
  10326. ;
  10327. if (is_dir($containerOrigin) &&
  10328. is_dir($containerDestination)
  10329. ) {
  10330. $fs = new Filesystem();
  10331. $fs->mirror(
  10332. $containerOrigin,
  10333. $containerDestination,
  10334. $finder
  10335. );
  10336. }
  10337. }
  10338. }
  10339. }
  10340. foreach ($zip_files_abs as $file_path) {
  10341. if (empty($file_path)) {
  10342. continue;
  10343. }
  10344. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10345. continue;
  10346. }
  10347. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10348. if (strstr($file_path, 'upload/users') !== false) {
  10349. $pos = strpos($file_path, 'my_files/');
  10350. if ($pos !== false) {
  10351. $onlyDirectory = str_replace(
  10352. 'upload/users/',
  10353. '',
  10354. substr($file_path, $pos, strlen($file_path))
  10355. );
  10356. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10357. }
  10358. }
  10359. if (strstr($file_path, 'default_course_document/') !== false) {
  10360. $replace = str_replace('/main', '', $file_path);
  10361. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10362. }
  10363. if (empty($dest_file)) {
  10364. continue;
  10365. }
  10366. $this->create_path($dest_file);
  10367. copy($main_path.$file_path, $dest_file);
  10368. // Check if the file needs a link update.
  10369. if (in_array($file_path, array_keys($link_updates))) {
  10370. $string = file_get_contents($dest_file);
  10371. unlink($dest_file);
  10372. foreach ($link_updates[$file_path] as $old_new) {
  10373. // This is an ugly hack that allows .flv files to be found by the flv player that
  10374. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10375. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10376. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10377. if (substr($old_new['dest'], -3) == 'flv' &&
  10378. substr($old_new['dest'], 0, 5) == 'main/'
  10379. ) {
  10380. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10381. }
  10382. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10383. }
  10384. file_put_contents($dest_file, $string);
  10385. }
  10386. }
  10387. if (is_array($links_to_create)) {
  10388. foreach ($links_to_create as $file => $link) {
  10389. $content = '<!DOCTYPE html><head>
  10390. <meta charset="'.api_get_language_isocode().'" />
  10391. <title>'.$link['title'].'</title>
  10392. </head>
  10393. <body dir="'.api_get_text_direction().'">
  10394. <div style="text-align:center">
  10395. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10396. </body>
  10397. </html>';
  10398. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10399. }
  10400. }
  10401. // Add non exportable message explanation.
  10402. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10403. $file_content = '<!DOCTYPE html><head>
  10404. <meta charset="'.api_get_language_isocode().'" />
  10405. <title>'.$lang_not_exportable.'</title>
  10406. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10407. </head>
  10408. <body dir="'.api_get_text_direction().'">';
  10409. $file_content .=
  10410. <<<EOD
  10411. <style>
  10412. .error-message {
  10413. font-family: arial, verdana, helvetica, sans-serif;
  10414. border-width: 1px;
  10415. border-style: solid;
  10416. left: 50%;
  10417. margin: 10px auto;
  10418. min-height: 30px;
  10419. padding: 5px;
  10420. right: 50%;
  10421. width: 500px;
  10422. background-color: #FFD1D1;
  10423. border-color: #FF0000;
  10424. color: #000;
  10425. }
  10426. </style>
  10427. <body>
  10428. <div class="error-message">
  10429. $lang_not_exportable
  10430. </div>
  10431. </body>
  10432. </html>
  10433. EOD;
  10434. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10435. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10436. }
  10437. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10438. // Add the extra files that go along with a SCORM package.
  10439. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10440. $fs = new Filesystem();
  10441. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10442. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10443. $manifest = @$xmldoc->saveXML();
  10444. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10445. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10446. $zip_folder->add(
  10447. $archivePath.'/'.$temp_dir_short,
  10448. PCLZIP_OPT_REMOVE_PATH,
  10449. $archivePath.'/'.$temp_dir_short.'/'
  10450. );
  10451. // Clean possible temporary files.
  10452. foreach ($files_cleanup as $file) {
  10453. $res = unlink($file);
  10454. if ($res === false) {
  10455. error_log(
  10456. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10457. 0
  10458. );
  10459. }
  10460. }
  10461. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10462. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10463. }
  10464. /**
  10465. * @param int $lp_id
  10466. *
  10467. * @return bool
  10468. */
  10469. public function scorm_export_to_pdf($lp_id)
  10470. {
  10471. $lp_id = (int) $lp_id;
  10472. $files_to_export = [];
  10473. $course_data = api_get_course_info($this->cc);
  10474. if (!empty($course_data)) {
  10475. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10476. $list = self::get_flat_ordered_items_list($lp_id);
  10477. if (!empty($list)) {
  10478. foreach ($list as $item_id) {
  10479. $item = $this->items[$item_id];
  10480. switch ($item->type) {
  10481. case 'document':
  10482. //Getting documents from a LP with chamilo documents
  10483. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10484. // Try loading document from the base course.
  10485. if (empty($file_data) && !empty($sessionId)) {
  10486. $file_data = DocumentManager::get_document_data_by_id(
  10487. $item->path,
  10488. $this->cc,
  10489. false,
  10490. 0
  10491. );
  10492. }
  10493. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10494. if (file_exists($file_path)) {
  10495. $files_to_export[] = [
  10496. 'title' => $item->get_title(),
  10497. 'path' => $file_path,
  10498. ];
  10499. }
  10500. break;
  10501. case 'asset': //commes from a scorm package generated by chamilo
  10502. case 'sco':
  10503. $file_path = $scorm_path.'/'.$item->path;
  10504. if (file_exists($file_path)) {
  10505. $files_to_export[] = [
  10506. 'title' => $item->get_title(),
  10507. 'path' => $file_path,
  10508. ];
  10509. }
  10510. break;
  10511. case 'dir':
  10512. $files_to_export[] = [
  10513. 'title' => $item->get_title(),
  10514. 'path' => null,
  10515. ];
  10516. break;
  10517. }
  10518. }
  10519. }
  10520. $pdf = new PDF();
  10521. $result = $pdf->html_to_pdf(
  10522. $files_to_export,
  10523. $this->name,
  10524. $this->cc,
  10525. true
  10526. );
  10527. return $result;
  10528. }
  10529. return false;
  10530. }
  10531. /**
  10532. * Temp function to be moved in main_api or the best place around for this.
  10533. * Creates a file path if it doesn't exist.
  10534. *
  10535. * @param string $path
  10536. */
  10537. public function create_path($path)
  10538. {
  10539. $path_bits = explode('/', dirname($path));
  10540. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10541. $path_built = IS_WINDOWS_OS ? '' : '/';
  10542. foreach ($path_bits as $bit) {
  10543. if (!empty($bit)) {
  10544. $new_path = $path_built.$bit;
  10545. if (is_dir($new_path)) {
  10546. $path_built = $new_path.'/';
  10547. } else {
  10548. mkdir($new_path, api_get_permissions_for_new_directories());
  10549. $path_built = $new_path.'/';
  10550. }
  10551. }
  10552. }
  10553. }
  10554. /**
  10555. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10556. *
  10557. * @return bool The results of the unlink function, or false if there was no image to start with
  10558. */
  10559. public function delete_lp_image()
  10560. {
  10561. $img = $this->get_preview_image();
  10562. if ($img != '') {
  10563. $del_file = $this->get_preview_image_path(null, 'sys');
  10564. if (isset($del_file) && file_exists($del_file)) {
  10565. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10566. if (file_exists($del_file_2)) {
  10567. unlink($del_file_2);
  10568. }
  10569. $this->set_preview_image('');
  10570. return @unlink($del_file);
  10571. }
  10572. }
  10573. return false;
  10574. }
  10575. /**
  10576. * Uploads an author image to the upload/learning_path/images directory.
  10577. *
  10578. * @param array The image array, coming from the $_FILES superglobal
  10579. *
  10580. * @return bool True on success, false on error
  10581. */
  10582. public function upload_image($image_array)
  10583. {
  10584. if (!empty($image_array['name'])) {
  10585. $upload_ok = process_uploaded_file($image_array);
  10586. $has_attachment = true;
  10587. }
  10588. if ($upload_ok && $has_attachment) {
  10589. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10590. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10591. $updir = $sys_course_path.$courseDir;
  10592. // Try to add an extension to the file if it hasn't one.
  10593. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10594. if (filter_extension($new_file_name)) {
  10595. $file_extension = explode('.', $image_array['name']);
  10596. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10597. $filename = uniqid('');
  10598. $new_file_name = $filename.'.'.$file_extension;
  10599. $new_path = $updir.'/'.$new_file_name;
  10600. // Resize the image.
  10601. $temp = new Image($image_array['tmp_name']);
  10602. $temp->resize(104);
  10603. $result = $temp->send_image($new_path);
  10604. // Storing the image filename.
  10605. if ($result) {
  10606. $this->set_preview_image($new_file_name);
  10607. //Resize to 64px to use on course homepage
  10608. $temp->resize(64);
  10609. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10610. return true;
  10611. }
  10612. }
  10613. }
  10614. return false;
  10615. }
  10616. /**
  10617. * @param int $lp_id
  10618. * @param string $status
  10619. */
  10620. public function set_autolaunch($lp_id, $status)
  10621. {
  10622. $course_id = api_get_course_int_id();
  10623. $lp_id = intval($lp_id);
  10624. $status = intval($status);
  10625. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10626. // Setting everything to autolaunch = 0
  10627. $attributes['autolaunch'] = 0;
  10628. $where = [
  10629. 'session_id = ? AND c_id = ? ' => [
  10630. api_get_session_id(),
  10631. $course_id,
  10632. ],
  10633. ];
  10634. Database::update($lp_table, $attributes, $where);
  10635. if ($status == 1) {
  10636. //Setting my lp_id to autolaunch = 1
  10637. $attributes['autolaunch'] = 1;
  10638. $where = [
  10639. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10640. $lp_id,
  10641. api_get_session_id(),
  10642. $course_id,
  10643. ],
  10644. ];
  10645. Database::update($lp_table, $attributes, $where);
  10646. }
  10647. }
  10648. /**
  10649. * Gets previous_item_id for the next element of the lp_item table.
  10650. *
  10651. * @author Isaac flores paz
  10652. *
  10653. * @return int Previous item ID
  10654. */
  10655. public function select_previous_item_id()
  10656. {
  10657. $course_id = api_get_course_int_id();
  10658. if ($this->debug > 0) {
  10659. error_log('In learnpath::select_previous_item_id()', 0);
  10660. }
  10661. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10662. // Get the max order of the items
  10663. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10664. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10665. $rs_max_order = Database::query($sql);
  10666. $row_max_order = Database::fetch_object($rs_max_order);
  10667. $max_order = $row_max_order->display_order;
  10668. // Get the previous item ID
  10669. $sql = "SELECT iid as previous FROM $table_lp_item
  10670. WHERE
  10671. c_id = $course_id AND
  10672. lp_id = ".$this->lp_id." AND
  10673. display_order = '$max_order' ";
  10674. $rs_max = Database::query($sql);
  10675. $row_max = Database::fetch_object($rs_max);
  10676. // Return the previous item ID
  10677. return $row_max->previous;
  10678. }
  10679. /**
  10680. * Copies an LP.
  10681. */
  10682. public function copy()
  10683. {
  10684. // Course builder
  10685. $cb = new CourseBuilder();
  10686. //Setting tools that will be copied
  10687. $cb->set_tools_to_build(['learnpaths']);
  10688. //Setting elements that will be copied
  10689. $cb->set_tools_specific_id_list(
  10690. ['learnpaths' => [$this->lp_id]]
  10691. );
  10692. $course = $cb->build();
  10693. //Course restorer
  10694. $course_restorer = new CourseRestorer($course);
  10695. $course_restorer->set_add_text_in_items(true);
  10696. $course_restorer->set_tool_copy_settings(
  10697. ['learnpaths' => ['reset_dates' => true]]
  10698. );
  10699. $course_restorer->restore(
  10700. api_get_course_id(),
  10701. api_get_session_id(),
  10702. false,
  10703. false
  10704. );
  10705. }
  10706. /**
  10707. * Verify document size.
  10708. *
  10709. * @param string $s
  10710. *
  10711. * @return bool
  10712. */
  10713. public static function verify_document_size($s)
  10714. {
  10715. $post_max = ini_get('post_max_size');
  10716. if (substr($post_max, -1, 1) == 'M') {
  10717. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10718. } elseif (substr($post_max, -1, 1) == 'G') {
  10719. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10720. }
  10721. $upl_max = ini_get('upload_max_filesize');
  10722. if (substr($upl_max, -1, 1) == 'M') {
  10723. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10724. } elseif (substr($upl_max, -1, 1) == 'G') {
  10725. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10726. }
  10727. $documents_total_space = DocumentManager::documents_total_space();
  10728. $course_max_space = DocumentManager::get_course_quota();
  10729. $total_size = filesize($s) + $documents_total_space;
  10730. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10731. return true;
  10732. } else {
  10733. return false;
  10734. }
  10735. }
  10736. /**
  10737. * Clear LP prerequisites.
  10738. */
  10739. public function clear_prerequisites()
  10740. {
  10741. $course_id = $this->get_course_int_id();
  10742. if ($this->debug > 0) {
  10743. error_log('In learnpath::clear_prerequisites()', 0);
  10744. }
  10745. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10746. $lp_id = $this->get_id();
  10747. //Cleaning prerequisites
  10748. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10749. WHERE c_id = $course_id AND lp_id = $lp_id";
  10750. Database::query($sql);
  10751. //Cleaning mastery score for exercises
  10752. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10753. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10754. Database::query($sql);
  10755. }
  10756. public function set_previous_step_as_prerequisite_for_all_items()
  10757. {
  10758. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10759. $course_id = $this->get_course_int_id();
  10760. $lp_id = $this->get_id();
  10761. if (!empty($this->items)) {
  10762. $previous_item_id = null;
  10763. $previous_item_max = 0;
  10764. $previous_item_type = null;
  10765. $last_item_not_dir = null;
  10766. $last_item_not_dir_type = null;
  10767. $last_item_not_dir_max = null;
  10768. foreach ($this->ordered_items as $itemId) {
  10769. $item = $this->getItem($itemId);
  10770. // if there was a previous item... (otherwise jump to set it)
  10771. if (!empty($previous_item_id)) {
  10772. $current_item_id = $item->get_id(); //save current id
  10773. if ($item->get_type() != 'dir') {
  10774. // Current item is not a folder, so it qualifies to get a prerequisites
  10775. if ($last_item_not_dir_type == 'quiz') {
  10776. // if previous is quiz, mark its max score as default score to be achieved
  10777. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10778. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10779. Database::query($sql);
  10780. }
  10781. // now simply update the prerequisite to set it to the last non-chapter item
  10782. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10783. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10784. Database::query($sql);
  10785. // record item as 'non-chapter' reference
  10786. $last_item_not_dir = $item->get_id();
  10787. $last_item_not_dir_type = $item->get_type();
  10788. $last_item_not_dir_max = $item->get_max();
  10789. }
  10790. } else {
  10791. if ($item->get_type() != 'dir') {
  10792. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10793. $last_item_not_dir = $item->get_id();
  10794. $last_item_not_dir_type = $item->get_type();
  10795. $last_item_not_dir_max = $item->get_max();
  10796. }
  10797. }
  10798. // Saving the item as "previous item" for the next loop
  10799. $previous_item_id = $item->get_id();
  10800. $previous_item_max = $item->get_max();
  10801. $previous_item_type = $item->get_type();
  10802. }
  10803. }
  10804. }
  10805. /**
  10806. * @param array $params
  10807. *
  10808. * @throws \Doctrine\ORM\OptimisticLockException
  10809. *
  10810. * @return int
  10811. */
  10812. public static function createCategory($params)
  10813. {
  10814. $em = Database::getManager();
  10815. $item = new CLpCategory();
  10816. $item->setName($params['name']);
  10817. $item->setCId($params['c_id']);
  10818. $em->persist($item);
  10819. $em->flush();
  10820. api_item_property_update(
  10821. api_get_course_info(),
  10822. TOOL_LEARNPATH_CATEGORY,
  10823. $item->getId(),
  10824. 'visible',
  10825. api_get_user_id()
  10826. );
  10827. return $item->getId();
  10828. }
  10829. /**
  10830. * @param array $params
  10831. *
  10832. * @throws \Doctrine\ORM\ORMException
  10833. * @throws \Doctrine\ORM\OptimisticLockException
  10834. * @throws \Doctrine\ORM\TransactionRequiredException
  10835. */
  10836. public static function updateCategory($params)
  10837. {
  10838. $em = Database::getManager();
  10839. /** @var CLpCategory $item */
  10840. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10841. if ($item) {
  10842. $item->setName($params['name']);
  10843. $em->merge($item);
  10844. $em->flush();
  10845. }
  10846. }
  10847. /**
  10848. * @param int $id
  10849. *
  10850. * @throws \Doctrine\ORM\ORMException
  10851. * @throws \Doctrine\ORM\OptimisticLockException
  10852. * @throws \Doctrine\ORM\TransactionRequiredException
  10853. */
  10854. public static function moveUpCategory($id)
  10855. {
  10856. $id = (int) $id;
  10857. $em = Database::getManager();
  10858. /** @var CLpCategory $item */
  10859. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10860. if ($item) {
  10861. $position = $item->getPosition() - 1;
  10862. $item->setPosition($position);
  10863. $em->persist($item);
  10864. $em->flush();
  10865. }
  10866. }
  10867. /**
  10868. * @param int $id
  10869. *
  10870. * @throws \Doctrine\ORM\ORMException
  10871. * @throws \Doctrine\ORM\OptimisticLockException
  10872. * @throws \Doctrine\ORM\TransactionRequiredException
  10873. */
  10874. public static function moveDownCategory($id)
  10875. {
  10876. $id = (int) $id;
  10877. $em = Database::getManager();
  10878. /** @var CLpCategory $item */
  10879. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10880. if ($item) {
  10881. $position = $item->getPosition() + 1;
  10882. $item->setPosition($position);
  10883. $em->persist($item);
  10884. $em->flush();
  10885. }
  10886. }
  10887. /**
  10888. * @param int $courseId
  10889. *
  10890. * @throws \Doctrine\ORM\Query\QueryException
  10891. *
  10892. * @return int|mixed
  10893. */
  10894. public static function getCountCategories($courseId)
  10895. {
  10896. if (empty($course_id)) {
  10897. return 0;
  10898. }
  10899. $em = Database::getManager();
  10900. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10901. $query->setParameter('id', $courseId);
  10902. return $query->getSingleScalarResult();
  10903. }
  10904. /**
  10905. * @param int $courseId
  10906. *
  10907. * @return mixed
  10908. */
  10909. public static function getCategories($courseId)
  10910. {
  10911. $em = Database::getManager();
  10912. //Default behaviour
  10913. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10914. array('cId' => $course_id),
  10915. array('name' => 'ASC')
  10916. );*/
  10917. // Using doctrine extensions
  10918. /** @var SortableRepository $repo */
  10919. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10920. $items = $repo
  10921. ->getBySortableGroupsQuery(['cId' => $courseId])
  10922. ->getResult();
  10923. return $items;
  10924. }
  10925. /**
  10926. * @param int $id
  10927. *
  10928. * @throws \Doctrine\ORM\ORMException
  10929. * @throws \Doctrine\ORM\OptimisticLockException
  10930. * @throws \Doctrine\ORM\TransactionRequiredException
  10931. *
  10932. * @return CLpCategory
  10933. */
  10934. public static function getCategory($id)
  10935. {
  10936. $id = (int) $id;
  10937. $em = Database::getManager();
  10938. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10939. return $item;
  10940. }
  10941. /**
  10942. * @param int $courseId
  10943. *
  10944. * @return array
  10945. */
  10946. public static function getCategoryByCourse($courseId)
  10947. {
  10948. $em = Database::getManager();
  10949. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10950. ['cId' => $courseId]
  10951. );
  10952. return $items;
  10953. }
  10954. /**
  10955. * @param int $id
  10956. *
  10957. * @throws \Doctrine\ORM\ORMException
  10958. * @throws \Doctrine\ORM\OptimisticLockException
  10959. * @throws \Doctrine\ORM\TransactionRequiredException
  10960. *
  10961. * @return mixed
  10962. */
  10963. public static function deleteCategory($id)
  10964. {
  10965. $em = Database::getManager();
  10966. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10967. if ($item) {
  10968. $courseId = $item->getCId();
  10969. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10970. $query->setParameter('id', $courseId);
  10971. $query->setParameter('catId', $item->getId());
  10972. $lps = $query->getResult();
  10973. // Setting category = 0.
  10974. if ($lps) {
  10975. foreach ($lps as $lpItem) {
  10976. $lpItem->setCategoryId(0);
  10977. }
  10978. }
  10979. // Removing category.
  10980. $em->remove($item);
  10981. $em->flush();
  10982. $courseInfo = api_get_course_info_by_id($courseId);
  10983. $sessionId = api_get_session_id();
  10984. // Delete link tool
  10985. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10986. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10987. // Delete tools
  10988. $sql = "DELETE FROM $tbl_tool
  10989. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10990. Database::query($sql);
  10991. }
  10992. }
  10993. /**
  10994. * @param int $courseId
  10995. * @param bool $addSelectOption
  10996. *
  10997. * @return mixed
  10998. */
  10999. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11000. {
  11001. $items = self::getCategoryByCourse($courseId);
  11002. $cats = [];
  11003. if ($addSelectOption) {
  11004. $cats = [get_lang('SelectACategory')];
  11005. }
  11006. if (!empty($items)) {
  11007. foreach ($items as $cat) {
  11008. $cats[$cat->getId()] = $cat->getName();
  11009. }
  11010. }
  11011. return $cats;
  11012. }
  11013. /**
  11014. * @param string $courseCode
  11015. * @param int $lpId
  11016. * @param int $user_id
  11017. *
  11018. * @return learnpath
  11019. */
  11020. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11021. {
  11022. $debug = 0;
  11023. $learnPath = null;
  11024. $lpObject = Session::read('lpobject');
  11025. if ($lpObject !== null) {
  11026. $learnPath = unserialize($lpObject);
  11027. if ($debug) {
  11028. error_log('getLpFromSession: unserialize');
  11029. error_log('------getLpFromSession------');
  11030. error_log('------unserialize------');
  11031. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11032. error_log("api_get_sessionid: ".api_get_session_id());
  11033. }
  11034. }
  11035. if (!is_object($learnPath)) {
  11036. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11037. if ($debug) {
  11038. error_log('------getLpFromSession------');
  11039. error_log('getLpFromSession: create new learnpath');
  11040. error_log("create new LP with $courseCode - $lpId - $user_id");
  11041. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11042. error_log("api_get_sessionid: ".api_get_session_id());
  11043. }
  11044. }
  11045. return $learnPath;
  11046. }
  11047. /**
  11048. * @param int $itemId
  11049. *
  11050. * @return learnpathItem|false
  11051. */
  11052. public function getItem($itemId)
  11053. {
  11054. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11055. return $this->items[$itemId];
  11056. }
  11057. return false;
  11058. }
  11059. /**
  11060. * @return int
  11061. */
  11062. public function getCategoryId()
  11063. {
  11064. return (int) $this->categoryId;
  11065. }
  11066. /**
  11067. * @param int $categoryId
  11068. *
  11069. * @return bool
  11070. */
  11071. public function setCategoryId($categoryId)
  11072. {
  11073. $this->categoryId = (int) $categoryId;
  11074. $table = Database::get_course_table(TABLE_LP_MAIN);
  11075. $lp_id = $this->get_id();
  11076. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11077. WHERE iid = $lp_id";
  11078. Database::query($sql);
  11079. return true;
  11080. }
  11081. /**
  11082. * Get whether this is a learning path with the possibility to subscribe
  11083. * users or not.
  11084. *
  11085. * @return int
  11086. */
  11087. public function getSubscribeUsers()
  11088. {
  11089. return $this->subscribeUsers;
  11090. }
  11091. /**
  11092. * Set whether this is a learning path with the possibility to subscribe
  11093. * users or not.
  11094. *
  11095. * @param int $value (0 = false, 1 = true)
  11096. *
  11097. * @return bool
  11098. */
  11099. public function setSubscribeUsers($value)
  11100. {
  11101. if ($this->debug > 0) {
  11102. error_log('In learnpath::set_subscribe_users()', 0);
  11103. }
  11104. $this->subscribeUsers = (int) $value;
  11105. $table = Database::get_course_table(TABLE_LP_MAIN);
  11106. $lp_id = $this->get_id();
  11107. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11108. WHERE iid = $lp_id";
  11109. Database::query($sql);
  11110. return true;
  11111. }
  11112. /**
  11113. * Calculate the count of stars for a user in this LP
  11114. * This calculation is based on the following rules:
  11115. * - the student gets one star when he gets to 50% of the learning path
  11116. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11117. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11118. * - the student gets the final star when the score for the *last* test is >= 80%.
  11119. *
  11120. * @param int $sessionId Optional. The session ID
  11121. *
  11122. * @return int The count of stars
  11123. */
  11124. public function getCalculateStars($sessionId = 0)
  11125. {
  11126. $stars = 0;
  11127. $progress = self::getProgress(
  11128. $this->lp_id,
  11129. $this->user_id,
  11130. $this->course_int_id,
  11131. $sessionId
  11132. );
  11133. if ($progress >= 50) {
  11134. $stars++;
  11135. }
  11136. // Calculate stars chapters evaluation
  11137. $exercisesItems = $this->getExercisesItems();
  11138. if (!empty($exercisesItems)) {
  11139. $totalResult = 0;
  11140. foreach ($exercisesItems as $exerciseItem) {
  11141. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11142. $this->user_id,
  11143. $exerciseItem->path,
  11144. $this->course_int_id,
  11145. $sessionId,
  11146. $this->lp_id,
  11147. $exerciseItem->db_id
  11148. );
  11149. $exerciseResultInfo = end($exerciseResultInfo);
  11150. if (!$exerciseResultInfo) {
  11151. continue;
  11152. }
  11153. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11154. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11155. } else {
  11156. $exerciseResult = 0;
  11157. }
  11158. $totalResult += $exerciseResult;
  11159. }
  11160. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11161. if ($totalExerciseAverage >= 50) {
  11162. $stars++;
  11163. }
  11164. if ($totalExerciseAverage >= 80) {
  11165. $stars++;
  11166. }
  11167. }
  11168. // Calculate star for final evaluation
  11169. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11170. if (!empty($finalEvaluationItem)) {
  11171. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11172. $this->user_id,
  11173. $finalEvaluationItem->path,
  11174. $this->course_int_id,
  11175. $sessionId,
  11176. $this->lp_id,
  11177. $finalEvaluationItem->db_id
  11178. );
  11179. $evaluationResultInfo = end($evaluationResultInfo);
  11180. if ($evaluationResultInfo) {
  11181. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11182. if ($evaluationResult >= 80) {
  11183. $stars++;
  11184. }
  11185. }
  11186. }
  11187. return $stars;
  11188. }
  11189. /**
  11190. * Get the items of exercise type.
  11191. *
  11192. * @return array The items. Otherwise return false
  11193. */
  11194. public function getExercisesItems()
  11195. {
  11196. $exercises = [];
  11197. foreach ($this->items as $item) {
  11198. if ($item->type != 'quiz') {
  11199. continue;
  11200. }
  11201. $exercises[] = $item;
  11202. }
  11203. array_pop($exercises);
  11204. return $exercises;
  11205. }
  11206. /**
  11207. * Get the item of exercise type (evaluation type).
  11208. *
  11209. * @return array The final evaluation. Otherwise return false
  11210. */
  11211. public function getFinalEvaluationItem()
  11212. {
  11213. $exercises = [];
  11214. foreach ($this->items as $item) {
  11215. if ($item->type != 'quiz') {
  11216. continue;
  11217. }
  11218. $exercises[] = $item;
  11219. }
  11220. return array_pop($exercises);
  11221. }
  11222. /**
  11223. * Calculate the total points achieved for the current user in this learning path.
  11224. *
  11225. * @param int $sessionId Optional. The session Id
  11226. *
  11227. * @return int
  11228. */
  11229. public function getCalculateScore($sessionId = 0)
  11230. {
  11231. // Calculate stars chapters evaluation
  11232. $exercisesItems = $this->getExercisesItems();
  11233. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11234. $totalExercisesResult = 0;
  11235. $totalEvaluationResult = 0;
  11236. if ($exercisesItems !== false) {
  11237. foreach ($exercisesItems as $exerciseItem) {
  11238. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11239. $this->user_id,
  11240. $exerciseItem->path,
  11241. $this->course_int_id,
  11242. $sessionId,
  11243. $this->lp_id,
  11244. $exerciseItem->db_id
  11245. );
  11246. $exerciseResultInfo = end($exerciseResultInfo);
  11247. if (!$exerciseResultInfo) {
  11248. continue;
  11249. }
  11250. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11251. }
  11252. }
  11253. if (!empty($finalEvaluationItem)) {
  11254. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11255. $this->user_id,
  11256. $finalEvaluationItem->path,
  11257. $this->course_int_id,
  11258. $sessionId,
  11259. $this->lp_id,
  11260. $finalEvaluationItem->db_id
  11261. );
  11262. $evaluationResultInfo = end($evaluationResultInfo);
  11263. if ($evaluationResultInfo) {
  11264. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11265. }
  11266. }
  11267. return $totalExercisesResult + $totalEvaluationResult;
  11268. }
  11269. /**
  11270. * Check if URL is not allowed to be show in a iframe.
  11271. *
  11272. * @param string $src
  11273. *
  11274. * @return string
  11275. */
  11276. public function fixBlockedLinks($src)
  11277. {
  11278. $urlInfo = parse_url($src);
  11279. $platformProtocol = 'https';
  11280. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11281. $platformProtocol = 'http';
  11282. }
  11283. $protocolFixApplied = false;
  11284. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11285. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11286. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11287. if ($platformProtocol != $scheme) {
  11288. Session::write('x_frame_source', $src);
  11289. $src = 'blank.php?error=x_frames_options';
  11290. $protocolFixApplied = true;
  11291. }
  11292. if ($protocolFixApplied == false) {
  11293. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11294. // Check X-Frame-Options
  11295. $ch = curl_init();
  11296. $options = [
  11297. CURLOPT_URL => $src,
  11298. CURLOPT_RETURNTRANSFER => true,
  11299. CURLOPT_HEADER => true,
  11300. CURLOPT_FOLLOWLOCATION => true,
  11301. CURLOPT_ENCODING => "",
  11302. CURLOPT_AUTOREFERER => true,
  11303. CURLOPT_CONNECTTIMEOUT => 120,
  11304. CURLOPT_TIMEOUT => 120,
  11305. CURLOPT_MAXREDIRS => 10,
  11306. ];
  11307. $proxySettings = api_get_configuration_value('proxy_settings');
  11308. if (!empty($proxySettings) &&
  11309. isset($proxySettings['curl_setopt_array'])
  11310. ) {
  11311. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11312. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11313. }
  11314. curl_setopt_array($ch, $options);
  11315. $response = curl_exec($ch);
  11316. $httpCode = curl_getinfo($ch);
  11317. $headers = substr($response, 0, $httpCode['header_size']);
  11318. $error = false;
  11319. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11320. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11321. ) {
  11322. $error = true;
  11323. }
  11324. if ($error) {
  11325. Session::write('x_frame_source', $src);
  11326. $src = 'blank.php?error=x_frames_options';
  11327. }
  11328. }
  11329. }
  11330. return $src;
  11331. }
  11332. /**
  11333. * Check if this LP has a created forum in the basis course.
  11334. *
  11335. * @return bool
  11336. */
  11337. public function lpHasForum()
  11338. {
  11339. $forumTable = Database::get_course_table(TABLE_FORUM);
  11340. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11341. $fakeFrom = "
  11342. $forumTable f
  11343. INNER JOIN $itemProperty ip
  11344. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11345. ";
  11346. $resultData = Database::select(
  11347. 'COUNT(f.iid) AS qty',
  11348. $fakeFrom,
  11349. [
  11350. 'where' => [
  11351. 'ip.visibility != ? AND ' => 2,
  11352. 'ip.tool = ? AND ' => TOOL_FORUM,
  11353. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11354. 'f.lp_id = ?' => intval($this->lp_id),
  11355. ],
  11356. ],
  11357. 'first'
  11358. );
  11359. return $resultData['qty'] > 0;
  11360. }
  11361. /**
  11362. * Get the forum for this learning path.
  11363. *
  11364. * @param int $sessionId
  11365. *
  11366. * @return bool
  11367. */
  11368. public function getForum($sessionId = 0)
  11369. {
  11370. $forumTable = Database::get_course_table(TABLE_FORUM);
  11371. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11372. $fakeFrom = "$forumTable f
  11373. INNER JOIN $itemProperty ip ";
  11374. if ($this->lp_session_id == 0) {
  11375. $fakeFrom .= "
  11376. ON (
  11377. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11378. f.session_id = ip.session_id OR ip.session_id IS NULL
  11379. )
  11380. )
  11381. ";
  11382. } else {
  11383. $fakeFrom .= "
  11384. ON (
  11385. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11386. )
  11387. ";
  11388. }
  11389. $resultData = Database::select(
  11390. 'f.*',
  11391. $fakeFrom,
  11392. [
  11393. 'where' => [
  11394. 'ip.visibility != ? AND ' => 2,
  11395. 'ip.tool = ? AND ' => TOOL_FORUM,
  11396. 'f.session_id = ? AND ' => $sessionId,
  11397. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11398. 'f.lp_id = ?' => intval($this->lp_id),
  11399. ],
  11400. ],
  11401. 'first'
  11402. );
  11403. if (empty($resultData)) {
  11404. return false;
  11405. }
  11406. return $resultData;
  11407. }
  11408. /**
  11409. * Create a forum for this learning path.
  11410. *
  11411. * @param int $forumCategoryId
  11412. *
  11413. * @return int The forum ID if was created. Otherwise return false
  11414. */
  11415. public function createForum($forumCategoryId)
  11416. {
  11417. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11418. $forumId = store_forum(
  11419. [
  11420. 'lp_id' => $this->lp_id,
  11421. 'forum_title' => $this->name,
  11422. 'forum_comment' => null,
  11423. 'forum_category' => intval($forumCategoryId),
  11424. 'students_can_edit_group' => ['students_can_edit' => 0],
  11425. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11426. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11427. 'group_forum' => 0,
  11428. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11429. ],
  11430. [],
  11431. true
  11432. );
  11433. return $forumId;
  11434. }
  11435. /**
  11436. * Get the LP Final Item form.
  11437. *
  11438. * @throws Exception
  11439. * @throws HTML_QuickForm_Error
  11440. *
  11441. * @return string
  11442. */
  11443. public function getFinalItemForm()
  11444. {
  11445. $finalItem = $this->getFinalItem();
  11446. $title = '';
  11447. if ($finalItem) {
  11448. $title = $finalItem->get_title();
  11449. $buttonText = get_lang('Save');
  11450. $content = $this->getSavedFinalItem();
  11451. } else {
  11452. $buttonText = get_lang('LPCreateDocument');
  11453. $content = $this->getFinalItemTemplate();
  11454. }
  11455. $courseInfo = api_get_course_info();
  11456. $result = $this->generate_lp_folder($courseInfo);
  11457. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11458. $relative_prefix = '../../';
  11459. $editorConfig = [
  11460. 'ToolbarSet' => 'LearningPathDocuments',
  11461. 'Width' => '100%',
  11462. 'Height' => '500',
  11463. 'FullPage' => true,
  11464. 'CreateDocumentDir' => $relative_prefix,
  11465. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11466. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11467. ];
  11468. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11469. 'type' => 'document',
  11470. 'lp_id' => $this->lp_id,
  11471. ]);
  11472. $form = new FormValidator('final_item', 'POST', $url);
  11473. $form->addText('title', get_lang('Title'));
  11474. $form->addButtonSave($buttonText);
  11475. $form->addHtml(
  11476. Display::return_message(
  11477. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11478. 'normal',
  11479. false
  11480. )
  11481. );
  11482. $renderer = $form->defaultRenderer();
  11483. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11484. $form->addHtmlEditor(
  11485. 'content_lp_certificate',
  11486. null,
  11487. true,
  11488. false,
  11489. $editorConfig,
  11490. true
  11491. );
  11492. $form->addHidden('action', 'add_final_item');
  11493. $form->addHidden('path', Session::read('pathItem'));
  11494. $form->addHidden('previous', $this->get_last());
  11495. $form->setDefaults(
  11496. ['title' => $title, 'content_lp_certificate' => $content]
  11497. );
  11498. if ($form->validate()) {
  11499. $values = $form->exportValues();
  11500. $lastItemId = $this->get_last();
  11501. if (!$finalItem) {
  11502. $documentId = $this->create_document(
  11503. $this->course_info,
  11504. $values['content_lp_certificate'],
  11505. $values['title']
  11506. );
  11507. $this->add_item(
  11508. 0,
  11509. $lastItemId,
  11510. 'final_item',
  11511. $documentId,
  11512. $values['title'],
  11513. ''
  11514. );
  11515. Display::addFlash(
  11516. Display::return_message(get_lang('Added'))
  11517. );
  11518. } else {
  11519. $this->edit_document($this->course_info);
  11520. }
  11521. }
  11522. return $form->returnForm();
  11523. }
  11524. /**
  11525. * Check if the current lp item is first, both, last or none from lp list.
  11526. *
  11527. * @param int $currentItemId
  11528. *
  11529. * @return string
  11530. */
  11531. public function isFirstOrLastItem($currentItemId)
  11532. {
  11533. if ($this->debug > 0) {
  11534. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  11535. }
  11536. $lpItemId = [];
  11537. $typeListNotToVerify = self::getChapterTypes();
  11538. // Using get_toc() function instead $this->items because returns the correct order of the items
  11539. foreach ($this->get_toc() as $item) {
  11540. if (!in_array($item['type'], $typeListNotToVerify)) {
  11541. $lpItemId[] = $item['id'];
  11542. }
  11543. }
  11544. $lastLpItemIndex = count($lpItemId) - 1;
  11545. $position = array_search($currentItemId, $lpItemId);
  11546. switch ($position) {
  11547. case 0:
  11548. if (!$lastLpItemIndex) {
  11549. $answer = 'both';
  11550. break;
  11551. }
  11552. $answer = 'first';
  11553. break;
  11554. case $lastLpItemIndex:
  11555. $answer = 'last';
  11556. break;
  11557. default:
  11558. $answer = 'none';
  11559. }
  11560. return $answer;
  11561. }
  11562. /**
  11563. * Get whether this is a learning path with the accumulated SCORM time or not.
  11564. *
  11565. * @return int
  11566. */
  11567. public function getAccumulateScormTime()
  11568. {
  11569. return $this->accumulateScormTime;
  11570. }
  11571. /**
  11572. * Set whether this is a learning path with the accumulated SCORM time or not.
  11573. *
  11574. * @param int $value (0 = false, 1 = true)
  11575. *
  11576. * @return bool Always returns true
  11577. */
  11578. public function setAccumulateScormTime($value)
  11579. {
  11580. if ($this->debug > 0) {
  11581. error_log('In learnpath::setAccumulateScormTime()', 0);
  11582. }
  11583. $this->accumulateScormTime = intval($value);
  11584. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11585. $lp_id = $this->get_id();
  11586. $sql = "UPDATE $lp_table
  11587. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11588. WHERE iid = $lp_id";
  11589. Database::query($sql);
  11590. return true;
  11591. }
  11592. /**
  11593. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11594. * the new learning path tool.
  11595. *
  11596. * The function is a big switch on tool type.
  11597. * In each case, we query the corresponding table for information and build the link
  11598. * with that information.
  11599. *
  11600. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11601. * previous work (display_addedresource_link_in_learnpath())
  11602. *
  11603. * @param int $course_id Course code
  11604. * @param int $learningPathId The learning path ID (in lp table)
  11605. * @param int $id_in_path the unique index in the items table
  11606. * @param int $lpViewId
  11607. *
  11608. * @return string
  11609. */
  11610. public static function rl_get_resource_link_for_learnpath(
  11611. $course_id,
  11612. $learningPathId,
  11613. $id_in_path,
  11614. $lpViewId
  11615. ) {
  11616. $session_id = api_get_session_id();
  11617. $course_info = api_get_course_info_by_id($course_id);
  11618. $learningPathId = (int) $learningPathId;
  11619. $id_in_path = (int) $id_in_path;
  11620. $lpViewId = (int) $lpViewId;
  11621. $em = Database::getManager();
  11622. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11623. /** @var CLpItem $rowItem */
  11624. $rowItem = $lpItemRepo->findOneBy([
  11625. 'cId' => $course_id,
  11626. 'lpId' => $learningPathId,
  11627. 'iid' => $id_in_path,
  11628. ]);
  11629. if (!$rowItem) {
  11630. // Try one more time with "id"
  11631. /** @var CLpItem $rowItem */
  11632. $rowItem = $lpItemRepo->findOneBy([
  11633. 'cId' => $course_id,
  11634. 'lpId' => $learningPathId,
  11635. 'id' => $id_in_path,
  11636. ]);
  11637. if (!$rowItem) {
  11638. return -1;
  11639. }
  11640. }
  11641. $course_code = $course_info['code'];
  11642. $type = $rowItem->getItemType();
  11643. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11644. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11645. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11646. $link = '';
  11647. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11648. switch ($type) {
  11649. case 'dir':
  11650. return $main_dir_path.'lp/blank.php';
  11651. case TOOL_CALENDAR_EVENT:
  11652. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11653. case TOOL_ANNOUNCEMENT:
  11654. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11655. case TOOL_LINK:
  11656. $linkInfo = Link::getLinkInfo($id);
  11657. if (isset($linkInfo['url'])) {
  11658. return $linkInfo['url'];
  11659. }
  11660. return '';
  11661. case TOOL_QUIZ:
  11662. if (empty($id)) {
  11663. return '';
  11664. }
  11665. // Get the lp_item_view with the highest view_count.
  11666. $learnpathItemViewResult = $em
  11667. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11668. ->findBy(
  11669. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11670. ['viewCount' => 'DESC'],
  11671. 1
  11672. );
  11673. /** @var CLpItemView $learnpathItemViewData */
  11674. $learnpathItemViewData = current($learnpathItemViewResult);
  11675. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11676. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11677. .http_build_query([
  11678. 'lp_init' => 1,
  11679. 'learnpath_item_view_id' => $learnpathItemViewId,
  11680. 'learnpath_id' => $learningPathId,
  11681. 'learnpath_item_id' => $id_in_path,
  11682. 'exerciseId' => $id,
  11683. ]);
  11684. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11685. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11686. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11687. $myrow = Database::fetch_array($result);
  11688. $path = $myrow['path'];
  11689. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11690. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11691. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11692. case TOOL_FORUM:
  11693. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11694. case TOOL_THREAD:
  11695. // forum post
  11696. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11697. if (empty($id)) {
  11698. return '';
  11699. }
  11700. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11701. $result = Database::query($sql);
  11702. $myrow = Database::fetch_array($result);
  11703. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11704. .$extraParams;
  11705. case TOOL_POST:
  11706. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11707. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11708. $myrow = Database::fetch_array($result);
  11709. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11710. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11711. case TOOL_DOCUMENT:
  11712. $document = $em
  11713. ->getRepository('ChamiloCourseBundle:CDocument')
  11714. ->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11715. if (empty($document)) {
  11716. // Try with normal id
  11717. $document = $em
  11718. ->getRepository('ChamiloCourseBundle:CDocument')
  11719. ->findOneBy(['cId' => $course_id, 'id' => $id]);
  11720. if (empty($document)) {
  11721. return '';
  11722. }
  11723. }
  11724. $documentPathInfo = pathinfo($document->getPath());
  11725. $jplayer_supported_files = ['mp4', 'ogv', 'flv', 'm4v'];
  11726. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11727. $showDirectUrl = !in_array($extension, $jplayer_supported_files);
  11728. $openmethod = 2;
  11729. $officedoc = false;
  11730. Session::write('openmethod', $openmethod);
  11731. Session::write('officedoc', $officedoc);
  11732. if ($showDirectUrl) {
  11733. return $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11734. }
  11735. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11736. case TOOL_LP_FINAL_ITEM:
  11737. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11738. .$extraParams;
  11739. case 'assignments':
  11740. return $main_dir_path.'work/work.php?'.$extraParams;
  11741. case TOOL_DROPBOX:
  11742. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11743. case 'introduction_text': //DEPRECATED
  11744. return '';
  11745. case TOOL_COURSE_DESCRIPTION:
  11746. return $main_dir_path.'course_description?'.$extraParams;
  11747. case TOOL_GROUP:
  11748. return $main_dir_path.'group/group.php?'.$extraParams;
  11749. case TOOL_USER:
  11750. return $main_dir_path.'user/user.php?'.$extraParams;
  11751. case TOOL_STUDENTPUBLICATION:
  11752. if (!empty($rowItem->getPath())) {
  11753. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11754. }
  11755. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11756. } //end switch
  11757. return $link;
  11758. }
  11759. /**
  11760. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11761. *
  11762. * @author Yannick Warnier <ywarnier@beeznest.org>
  11763. *
  11764. * @param string $course_code Course code
  11765. * @param int $learningPathId
  11766. * @param int $id_in_path The resource ID
  11767. *
  11768. * @return string
  11769. */
  11770. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11771. {
  11772. $_course = api_get_course_info($course_code);
  11773. $course_id = $_course['real_id'];
  11774. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11775. $learningPathId = (int) $learningPathId;
  11776. $id_in_path = (int) $id_in_path;
  11777. $sql = "SELECT item_type, title, ref
  11778. FROM $tbl_lp_item
  11779. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11780. $res_item = Database::query($sql);
  11781. if (Database::num_rows($res_item) < 1) {
  11782. return '';
  11783. }
  11784. $row_item = Database::fetch_array($res_item);
  11785. $type = strtolower($row_item['item_type']);
  11786. $id = $row_item['ref'];
  11787. $output = '';
  11788. switch ($type) {
  11789. case TOOL_CALENDAR_EVENT:
  11790. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11791. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11792. $myrow = Database::fetch_array($result);
  11793. $output = $myrow['title'];
  11794. break;
  11795. case TOOL_ANNOUNCEMENT:
  11796. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11797. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11798. $myrow = Database::fetch_array($result);
  11799. $output = $myrow['title'];
  11800. break;
  11801. case TOOL_LINK:
  11802. // Doesn't take $target into account.
  11803. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11804. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11805. $myrow = Database::fetch_array($result);
  11806. $output = $myrow['title'];
  11807. break;
  11808. case TOOL_QUIZ:
  11809. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11810. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  11811. $myrow = Database::fetch_array($result);
  11812. $output = $myrow['title'];
  11813. break;
  11814. case TOOL_FORUM:
  11815. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11816. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  11817. $myrow = Database::fetch_array($result);
  11818. $output = $myrow['forum_name'];
  11819. break;
  11820. case TOOL_THREAD: //=topics
  11821. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11822. // Grabbing the title of the post.
  11823. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11824. $result_title = Database::query($sql_title);
  11825. $myrow_title = Database::fetch_array($result_title);
  11826. $output = $myrow_title['post_title'];
  11827. break;
  11828. case TOOL_POST:
  11829. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11830. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  11831. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11832. $result = Database::query($sql);
  11833. $post = Database::fetch_array($result);
  11834. $output = $post['post_title'];
  11835. break;
  11836. case 'dir':
  11837. $title = $row_item['title'];
  11838. if (!empty($title)) {
  11839. $output = $title;
  11840. } else {
  11841. $output = '-';
  11842. }
  11843. break;
  11844. case TOOL_DOCUMENT:
  11845. $title = $row_item['title'];
  11846. if (!empty($title)) {
  11847. $output = $title;
  11848. } else {
  11849. $output = '-';
  11850. }
  11851. break;
  11852. case 'hotpotatoes':
  11853. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11854. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11855. $myrow = Database::fetch_array($result);
  11856. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11857. $last = count($pathname) - 1; // Making a correct name for the link.
  11858. $filename = $pathname[$last]; // Making a correct name for the link.
  11859. $ext = explode('.', $filename);
  11860. $ext = strtolower($ext[sizeof($ext) - 1]);
  11861. $myrow['path'] = rawurlencode($myrow['path']);
  11862. $output = $filename;
  11863. break;
  11864. }
  11865. return stripslashes($output);
  11866. }
  11867. /**
  11868. * Get the parent names for the current item.
  11869. *
  11870. * @param int $newItemId Optional. The item ID
  11871. *
  11872. * @return array
  11873. */
  11874. public function getCurrentItemParentNames($newItemId = 0)
  11875. {
  11876. $newItemId = $newItemId ?: $this->get_current_item_id();
  11877. $return = [];
  11878. $item = $this->getItem($newItemId);
  11879. $parent = $this->getItem($item->get_parent());
  11880. while ($parent) {
  11881. $return[] = $parent->get_title();
  11882. $parent = $this->getItem($parent->get_parent());
  11883. }
  11884. return array_reverse($return);
  11885. }
  11886. /**
  11887. * Reads and process "lp_subscription_settings" setting.
  11888. *
  11889. * @return array
  11890. */
  11891. public static function getSubscriptionSettings()
  11892. {
  11893. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11894. if (empty($subscriptionSettings)) {
  11895. // By default allow both settings
  11896. $subscriptionSettings = [
  11897. 'allow_add_users_to_lp' => true,
  11898. 'allow_add_users_to_lp_category' => true,
  11899. ];
  11900. } else {
  11901. $subscriptionSettings = $subscriptionSettings['options'];
  11902. }
  11903. return $subscriptionSettings;
  11904. }
  11905. /**
  11906. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  11907. */
  11908. public function exportToCourseBuildFormat()
  11909. {
  11910. if (!api_is_allowed_to_edit()) {
  11911. return false;
  11912. }
  11913. $courseBuilder = new CourseBuilder();
  11914. $itemList = [];
  11915. /** @var learnpathItem $item */
  11916. foreach ($this->items as $item) {
  11917. $itemList[$item->get_type()][] = $item->get_path();
  11918. }
  11919. if (empty($itemList)) {
  11920. return false;
  11921. }
  11922. if (isset($itemList['document'])) {
  11923. // Get parents
  11924. foreach ($itemList['document'] as $documentId) {
  11925. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  11926. if (!empty($documentInfo['parents'])) {
  11927. foreach ($documentInfo['parents'] as $parentInfo) {
  11928. if (in_array($parentInfo['iid'], $itemList['document'])) {
  11929. continue;
  11930. }
  11931. $itemList['document'][] = $parentInfo['iid'];
  11932. }
  11933. }
  11934. }
  11935. $courseInfo = api_get_course_info();
  11936. foreach ($itemList['document'] as $documentId) {
  11937. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  11938. $items = DocumentManager::get_resources_from_source_html(
  11939. $documentInfo['absolute_path'],
  11940. true,
  11941. TOOL_DOCUMENT
  11942. );
  11943. if (!empty($items)) {
  11944. foreach ($items as $item) {
  11945. // Get information about source url
  11946. $url = $item[0]; // url
  11947. $scope = $item[1]; // scope (local, remote)
  11948. $type = $item[2]; // type (rel, abs, url)
  11949. $origParseUrl = parse_url($url);
  11950. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  11951. if ($scope == 'local') {
  11952. if ($type == 'abs' || $type == 'rel') {
  11953. $documentFile = strstr($realOrigPath, 'document');
  11954. if (strpos($realOrigPath, $documentFile) !== false) {
  11955. $documentFile = str_replace('document', '', $documentFile);
  11956. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  11957. // Document found! Add it to the list
  11958. if ($itemDocumentId) {
  11959. $itemList['document'][] = $itemDocumentId;
  11960. }
  11961. }
  11962. }
  11963. }
  11964. }
  11965. }
  11966. }
  11967. $courseBuilder->build_documents(
  11968. api_get_session_id(),
  11969. $this->get_course_int_id(),
  11970. true,
  11971. $itemList['document']
  11972. );
  11973. }
  11974. if (isset($itemList['quiz'])) {
  11975. $courseBuilder->build_quizzes(
  11976. api_get_session_id(),
  11977. $this->get_course_int_id(),
  11978. true,
  11979. $itemList['quiz']
  11980. );
  11981. }
  11982. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  11983. /*if (!empty($itemList['thread'])) {
  11984. $postList = [];
  11985. foreach ($itemList['thread'] as $postId) {
  11986. $post = get_post_information($postId);
  11987. if ($post) {
  11988. if (!isset($itemList['forum'])) {
  11989. $itemList['forum'] = [];
  11990. }
  11991. $itemList['forum'][] = $post['forum_id'];
  11992. $postList[] = $postId;
  11993. }
  11994. }
  11995. if (!empty($postList)) {
  11996. $courseBuilder->build_forum_posts(
  11997. $this->get_course_int_id(),
  11998. null,
  11999. null,
  12000. $postList
  12001. );
  12002. }
  12003. }*/
  12004. if (!empty($itemList['thread'])) {
  12005. $threadList = [];
  12006. $em = Database::getManager();
  12007. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12008. foreach ($itemList['thread'] as $threadId) {
  12009. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12010. $thread = $repo->find($threadId);
  12011. if ($thread) {
  12012. $itemList['forum'][] = $thread->getForumId();
  12013. $threadList[] = $thread->getIid();
  12014. }
  12015. }
  12016. if (!empty($threadList)) {
  12017. $courseBuilder->build_forum_topics(
  12018. api_get_session_id(),
  12019. $this->get_course_int_id(),
  12020. null,
  12021. $threadList
  12022. );
  12023. }
  12024. }
  12025. $forumCategoryList = [];
  12026. if (isset($itemList['forum'])) {
  12027. foreach ($itemList['forum'] as $forumId) {
  12028. $forumInfo = get_forums($forumId);
  12029. $forumCategoryList[] = $forumInfo['forum_category'];
  12030. }
  12031. }
  12032. if (!empty($forumCategoryList)) {
  12033. $courseBuilder->build_forum_category(
  12034. api_get_session_id(),
  12035. $this->get_course_int_id(),
  12036. true,
  12037. $forumCategoryList
  12038. );
  12039. }
  12040. if (!empty($itemList['forum'])) {
  12041. $courseBuilder->build_forums(
  12042. api_get_session_id(),
  12043. $this->get_course_int_id(),
  12044. true,
  12045. $itemList['forum']
  12046. );
  12047. }
  12048. if (isset($itemList['link'])) {
  12049. $courseBuilder->build_links(
  12050. api_get_session_id(),
  12051. $this->get_course_int_id(),
  12052. true,
  12053. $itemList['link']
  12054. );
  12055. }
  12056. if (!empty($itemList['student_publication'])) {
  12057. $courseBuilder->build_works(
  12058. api_get_session_id(),
  12059. $this->get_course_int_id(),
  12060. true,
  12061. $itemList['student_publication']
  12062. );
  12063. }
  12064. $courseBuilder->build_learnpaths(
  12065. api_get_session_id(),
  12066. $this->get_course_int_id(),
  12067. true,
  12068. [$this->get_id()],
  12069. false
  12070. );
  12071. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12072. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12073. $result = DocumentManager::file_send_for_download(
  12074. $zipPath,
  12075. true,
  12076. $this->get_name().'.zip'
  12077. );
  12078. if ($result) {
  12079. api_not_allowed();
  12080. }
  12081. return true;
  12082. }
  12083. /**
  12084. * Get the depth level of LP item.
  12085. *
  12086. * @param array $items
  12087. * @param int $currentItemId
  12088. *
  12089. * @return int
  12090. */
  12091. private static function get_level_for_item($items, $currentItemId)
  12092. {
  12093. $parentItemId = 0;
  12094. if (isset($items[$currentItemId])) {
  12095. $parentItemId = $items[$currentItemId]->parent;
  12096. }
  12097. if ($parentItemId == 0) {
  12098. return 0;
  12099. } else {
  12100. return self::get_level_for_item($items, $parentItemId) + 1;
  12101. }
  12102. }
  12103. /**
  12104. * Generate the link for a learnpath category as course tool.
  12105. *
  12106. * @param int $categoryId
  12107. *
  12108. * @return string
  12109. */
  12110. private static function getCategoryLinkForTool($categoryId)
  12111. {
  12112. $categoryId = (int) $categoryId;
  12113. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12114. .http_build_query(
  12115. [
  12116. 'action' => 'view_category',
  12117. 'id' => $categoryId,
  12118. ]
  12119. );
  12120. return $link;
  12121. }
  12122. /**
  12123. * Return the scorm item type object with spaces replaced with _
  12124. * The return result is use to build a css classname like scorm_type_$return.
  12125. *
  12126. * @param $in_type
  12127. *
  12128. * @return mixed
  12129. */
  12130. private static function format_scorm_type_item($in_type)
  12131. {
  12132. return str_replace(' ', '_', $in_type);
  12133. }
  12134. /**
  12135. * Check and obtain the lp final item if exist.
  12136. *
  12137. * @return learnpathItem
  12138. */
  12139. private function getFinalItem()
  12140. {
  12141. if (empty($this->items)) {
  12142. return null;
  12143. }
  12144. foreach ($this->items as $item) {
  12145. if ($item->type !== 'final_item') {
  12146. continue;
  12147. }
  12148. return $item;
  12149. }
  12150. }
  12151. /**
  12152. * Get the LP Final Item Template.
  12153. *
  12154. * @return string
  12155. */
  12156. private function getFinalItemTemplate()
  12157. {
  12158. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12159. }
  12160. /**
  12161. * Get the LP Final Item Url.
  12162. *
  12163. * @return string
  12164. */
  12165. private function getSavedFinalItem()
  12166. {
  12167. $finalItem = $this->getFinalItem();
  12168. $doc = DocumentManager::get_document_data_by_id(
  12169. $finalItem->path,
  12170. $this->cc
  12171. );
  12172. if ($doc && file_exists($doc['absolute_path'])) {
  12173. return file_get_contents($doc['absolute_path']);
  12174. }
  12175. return '';
  12176. }
  12177. }