learnpath.class.php 532 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. if ($debug) {
  241. error_log('learnpath::__construct() '.__LINE__.' - query lp items: '.$sql);
  242. error_log('-- Start while--');
  243. }
  244. $lp_item_id_list = [];
  245. while ($row = Database::fetch_array($res)) {
  246. $lp_item_id_list[] = $row['iid'];
  247. switch ($this->type) {
  248. case 3: //aicc
  249. $oItem = new aiccItem('db', $row['iid'], $course_id);
  250. if (is_object($oItem)) {
  251. $my_item_id = $oItem->get_id();
  252. $oItem->set_lp_view($this->lp_view_id, $course_id);
  253. $oItem->set_prevent_reinit($this->prevent_reinit);
  254. // Don't use reference here as the next loop will make the pointed object change.
  255. $this->items[$my_item_id] = $oItem;
  256. $this->refs_list[$oItem->ref] = $my_item_id;
  257. if ($debug) {
  258. error_log(
  259. 'learnpath::__construct() - '.
  260. 'aicc object with id '.$my_item_id.
  261. ' set in items[]',
  262. 0
  263. );
  264. }
  265. }
  266. break;
  267. case 2:
  268. $oItem = new scormItem('db', $row['iid'], $course_id);
  269. if (is_object($oItem)) {
  270. $my_item_id = $oItem->get_id();
  271. $oItem->set_lp_view($this->lp_view_id, $course_id);
  272. $oItem->set_prevent_reinit($this->prevent_reinit);
  273. // Don't use reference here as the next loop will make the pointed object change.
  274. $this->items[$my_item_id] = $oItem;
  275. $this->refs_list[$oItem->ref] = $my_item_id;
  276. if ($debug) {
  277. error_log('object with id '.$my_item_id.' set in items[]');
  278. }
  279. }
  280. break;
  281. case 1:
  282. default:
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  285. }
  286. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  287. if ($debug) {
  288. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  289. }
  290. if (is_object($oItem)) {
  291. $my_item_id = $oItem->get_id();
  292. // Moved down to when we are sure the item_view exists.
  293. //$oItem->set_lp_view($this->lp_view_id);
  294. $oItem->set_prevent_reinit($this->prevent_reinit);
  295. // Don't use reference here as the next loop will make the pointed object change.
  296. $this->items[$my_item_id] = $oItem;
  297. $this->refs_list[$my_item_id] = $my_item_id;
  298. if ($debug) {
  299. error_log(
  300. 'learnpath::__construct() '.__LINE__.
  301. ' - object with id '.$my_item_id.' set in items[]'
  302. );
  303. }
  304. }
  305. break;
  306. }
  307. // Setting the object level with variable $this->items[$i][parent]
  308. foreach ($this->items as $itemLPObject) {
  309. $level = self::get_level_for_item(
  310. $this->items,
  311. $itemLPObject->db_id
  312. );
  313. $itemLPObject->level = $level;
  314. }
  315. // Setting the view in the item object.
  316. if (is_object($this->items[$row['iid']])) {
  317. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  318. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  319. $this->items[$row['iid']]->current_start_time = 0;
  320. $this->items[$row['iid']]->current_stop_time = 0;
  321. }
  322. }
  323. }
  324. if ($debug) {
  325. error_log('learnpath::__construct() '.__LINE__.' ----- end while ----');
  326. }
  327. if (!empty($lp_item_id_list)) {
  328. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  329. if (!empty($lp_item_id_list_to_string)) {
  330. // Get last viewing vars.
  331. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  332. // This query should only return one or zero result.
  333. $sql = "SELECT lp_item_id, status
  334. FROM $itemViewTable
  335. WHERE
  336. c_id = $course_id AND
  337. lp_view_id = ".$this->lp_view_id." AND
  338. lp_item_id IN ('".$lp_item_id_list_to_string."')
  339. ORDER BY view_count DESC ";
  340. if ($debug) {
  341. error_log(
  342. 'learnpath::__construct() - Selecting item_views: '.$sql,
  343. 0
  344. );
  345. }
  346. $status_list = [];
  347. $res = Database::query($sql);
  348. while ($row = Database:: fetch_array($res)) {
  349. $status_list[$row['lp_item_id']] = $row['status'];
  350. }
  351. foreach ($lp_item_id_list as $item_id) {
  352. if (isset($status_list[$item_id])) {
  353. $status = $status_list[$item_id];
  354. if (is_object($this->items[$item_id])) {
  355. $this->items[$item_id]->set_status($status);
  356. if (empty($status)) {
  357. $this->items[$item_id]->set_status(
  358. $this->default_status
  359. );
  360. }
  361. }
  362. } else {
  363. if (!api_is_invitee()) {
  364. if (is_object($this->items[$item_id])) {
  365. $this->items[$item_id]->set_status(
  366. $this->default_status
  367. );
  368. }
  369. if (!empty($this->lp_view_id)) {
  370. // Add that row to the lp_item_view table so that
  371. // we have something to show in the stats page.
  372. $params = [
  373. 'c_id' => $course_id,
  374. 'lp_item_id' => $item_id,
  375. 'lp_view_id' => $this->lp_view_id,
  376. 'view_count' => 1,
  377. 'status' => 'not attempted',
  378. 'start_time' => time(),
  379. 'total_time' => 0,
  380. 'score' => 0,
  381. ];
  382. $insertId = Database::insert($itemViewTable, $params);
  383. if ($insertId) {
  384. $sql = "UPDATE $itemViewTable SET id = iid
  385. WHERE iid = $insertId";
  386. Database::query($sql);
  387. }
  388. $this->items[$item_id]->set_lp_view(
  389. $this->lp_view_id,
  390. $course_id
  391. );
  392. }
  393. }
  394. }
  395. }
  396. }
  397. }
  398. $this->ordered_items = self::get_flat_ordered_items_list(
  399. $this->get_id(),
  400. 0,
  401. $course_id
  402. );
  403. $this->max_ordered_items = 0;
  404. foreach ($this->ordered_items as $index => $dummy) {
  405. if ($index > $this->max_ordered_items && !empty($dummy)) {
  406. $this->max_ordered_items = $index;
  407. }
  408. }
  409. // TODO: Define the current item better.
  410. $this->first();
  411. if ($debug) {
  412. error_log('lp_view_session_id '.$this->lp_view_session_id);
  413. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  414. }
  415. } else {
  416. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  417. }
  418. }
  419. }
  420. /**
  421. * @return string
  422. */
  423. public function getCourseCode()
  424. {
  425. return $this->cc;
  426. }
  427. /**
  428. * @return int
  429. */
  430. public function get_course_int_id()
  431. {
  432. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  433. }
  434. /**
  435. * @param $course_id
  436. *
  437. * @return int
  438. */
  439. public function set_course_int_id($course_id)
  440. {
  441. return $this->course_int_id = (int) $course_id;
  442. }
  443. /**
  444. * Function rewritten based on old_add_item() from Yannick Warnier.
  445. * Due the fact that users can decide where the item should come, I had to overlook this function and
  446. * I found it better to rewrite it. Old function is still available.
  447. * Added also the possibility to add a description.
  448. *
  449. * @param int $parent
  450. * @param int $previous
  451. * @param string $type
  452. * @param int $id resource ID (ref)
  453. * @param string $title
  454. * @param string $description
  455. * @param int $prerequisites
  456. * @param int $max_time_allowed
  457. * @param int $userId
  458. *
  459. * @return int
  460. */
  461. public function add_item(
  462. $parent,
  463. $previous,
  464. $type = 'dir',
  465. $id,
  466. $title,
  467. $description,
  468. $prerequisites = 0,
  469. $max_time_allowed = 0,
  470. $userId = 0
  471. ) {
  472. $course_id = $this->course_info['real_id'];
  473. if ($this->debug > 0) {
  474. error_log('In learnpath::add_item('.$parent.','.$previous.','.$type.','.$id.','.$title.')');
  475. }
  476. if (empty($course_id)) {
  477. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  478. $this->course_info = api_get_course_info($this->cc);
  479. $course_id = $this->course_info['real_id'];
  480. }
  481. $userId = empty($userId) ? api_get_user_id() : $userId;
  482. $sessionId = api_get_session_id();
  483. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  484. $_course = $this->course_info;
  485. $parent = (int) $parent;
  486. $previous = (int) $previous;
  487. $id = (int) $id;
  488. $max_time_allowed = htmlentities($max_time_allowed);
  489. if (empty($max_time_allowed)) {
  490. $max_time_allowed = 0;
  491. }
  492. $sql = "SELECT COUNT(iid) AS num
  493. FROM $tbl_lp_item
  494. WHERE
  495. c_id = $course_id AND
  496. lp_id = ".$this->get_id()." AND
  497. parent_item_id = ".$parent;
  498. $res_count = Database::query($sql);
  499. $row = Database::fetch_array($res_count);
  500. $num = $row['num'];
  501. $tmp_previous = 0;
  502. $display_order = 0;
  503. $next = 0;
  504. if ($num > 0) {
  505. if (empty($previous)) {
  506. $sql = "SELECT iid, next_item_id, display_order
  507. FROM $tbl_lp_item
  508. WHERE
  509. c_id = $course_id AND
  510. lp_id = ".$this->get_id()." AND
  511. parent_item_id = $parent AND
  512. previous_item_id = 0 OR
  513. previous_item_id = $parent";
  514. $result = Database::query($sql);
  515. $row = Database::fetch_array($result);
  516. if ($row) {
  517. $next = $row['iid'];
  518. }
  519. } else {
  520. $previous = (int) $previous;
  521. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  522. FROM $tbl_lp_item
  523. WHERE
  524. c_id = $course_id AND
  525. lp_id = ".$this->get_id()." AND
  526. id = $previous";
  527. $result = Database::query($sql);
  528. $row = Database::fetch_array($result);
  529. if ($row) {
  530. $tmp_previous = $row['iid'];
  531. $next = $row['next_item_id'];
  532. $display_order = $row['display_order'];
  533. }
  534. }
  535. }
  536. $id = (int) $id;
  537. $typeCleaned = Database::escape_string($type);
  538. $max_score = 100;
  539. if ($type === 'quiz') {
  540. $sql = 'SELECT SUM(ponderation)
  541. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  542. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  543. ON
  544. quiz_question.id = quiz_rel_question.question_id AND
  545. quiz_question.c_id = quiz_rel_question.c_id
  546. WHERE
  547. quiz_rel_question.exercice_id = '.$id." AND
  548. quiz_question.c_id = $course_id AND
  549. quiz_rel_question.c_id = $course_id ";
  550. $rsQuiz = Database::query($sql);
  551. $max_score = Database::result($rsQuiz, 0, 0);
  552. // Disabling the exercise if we add it inside a LP
  553. $exercise = new Exercise($course_id);
  554. $exercise->read($id);
  555. $exercise->disable();
  556. $exercise->save();
  557. }
  558. $params = [
  559. 'c_id' => $course_id,
  560. 'lp_id' => $this->get_id(),
  561. 'item_type' => $typeCleaned,
  562. 'ref' => '',
  563. 'title' => $title,
  564. 'description' => $description,
  565. 'path' => $id,
  566. 'max_score' => $max_score,
  567. 'parent_item_id' => $parent,
  568. 'previous_item_id' => $previous,
  569. 'next_item_id' => (int) $next,
  570. 'display_order' => $display_order + 1,
  571. 'prerequisite' => $prerequisites,
  572. 'max_time_allowed' => $max_time_allowed,
  573. 'min_score' => 0,
  574. 'launch_data' => '',
  575. ];
  576. if ($prerequisites != 0) {
  577. $params['prerequisite'] = $prerequisites;
  578. }
  579. $new_item_id = Database::insert($tbl_lp_item, $params);
  580. if ($new_item_id) {
  581. if ($this->debug > 2) {
  582. error_log('Inserting dir/chapter: '.$new_item_id, 0);
  583. }
  584. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  585. Database::query($sql);
  586. if (!empty($next)) {
  587. $sql = "UPDATE $tbl_lp_item
  588. SET previous_item_id = $new_item_id
  589. WHERE c_id = $course_id AND id = $next";
  590. Database::query($sql);
  591. }
  592. // Update the item that should be before the new item.
  593. if (!empty($tmp_previous)) {
  594. $sql = "UPDATE $tbl_lp_item
  595. SET next_item_id = $new_item_id
  596. WHERE c_id = $course_id AND id = $tmp_previous";
  597. Database::query($sql);
  598. }
  599. // Update all the items after the new item.
  600. $sql = "UPDATE $tbl_lp_item
  601. SET display_order = display_order + 1
  602. WHERE
  603. c_id = $course_id AND
  604. lp_id = ".$this->get_id()." AND
  605. iid <> $new_item_id AND
  606. parent_item_id = $parent AND
  607. display_order > $display_order";
  608. Database::query($sql);
  609. // Update the item that should come after the new item.
  610. $sql = "UPDATE $tbl_lp_item
  611. SET ref = $new_item_id
  612. WHERE c_id = $course_id AND iid = $new_item_id";
  613. Database::query($sql);
  614. // Upload audio.
  615. if (!empty($_FILES['mp3']['name'])) {
  616. // Create the audio folder if it does not exist yet.
  617. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  618. if (!is_dir($filepath.'audio')) {
  619. mkdir(
  620. $filepath.'audio',
  621. api_get_permissions_for_new_directories()
  622. );
  623. $audio_id = add_document(
  624. $_course,
  625. '/audio',
  626. 'folder',
  627. 0,
  628. 'audio',
  629. '',
  630. 0,
  631. true,
  632. null,
  633. $sessionId,
  634. $userId
  635. );
  636. api_item_property_update(
  637. $_course,
  638. TOOL_DOCUMENT,
  639. $audio_id,
  640. 'FolderCreated',
  641. $userId,
  642. null,
  643. null,
  644. null,
  645. null,
  646. $sessionId
  647. );
  648. api_item_property_update(
  649. $_course,
  650. TOOL_DOCUMENT,
  651. $audio_id,
  652. 'invisible',
  653. $userId,
  654. null,
  655. null,
  656. null,
  657. null,
  658. $sessionId
  659. );
  660. }
  661. $file_path = handle_uploaded_document(
  662. $_course,
  663. $_FILES['mp3'],
  664. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  665. '/audio',
  666. $userId,
  667. '',
  668. '',
  669. '',
  670. '',
  671. false
  672. );
  673. // Getting the filename only.
  674. $file_components = explode('/', $file_path);
  675. $file = $file_components[count($file_components) - 1];
  676. // Store the mp3 file in the lp_item table.
  677. $sql = "UPDATE $tbl_lp_item SET
  678. audio = '".Database::escape_string($file)."'
  679. WHERE iid = '".intval($new_item_id)."'";
  680. Database::query($sql);
  681. }
  682. }
  683. return $new_item_id;
  684. }
  685. /**
  686. * Static admin function allowing addition of a learnpath to a course.
  687. *
  688. * @param string $courseCode
  689. * @param string $name
  690. * @param string $description
  691. * @param string $learnpath
  692. * @param string $origin
  693. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  694. * @param string $publicated_on
  695. * @param string $expired_on
  696. * @param int $categoryId
  697. * @param int $userId
  698. *
  699. * @return int The new learnpath ID on success, 0 on failure
  700. */
  701. public static function add_lp(
  702. $courseCode,
  703. $name,
  704. $description = '',
  705. $learnpath = 'guess',
  706. $origin = 'zip',
  707. $zipname = '',
  708. $publicated_on = '',
  709. $expired_on = '',
  710. $categoryId = 0,
  711. $userId = 0
  712. ) {
  713. global $charset;
  714. if (!empty($courseCode)) {
  715. $courseInfo = api_get_course_info($courseCode);
  716. $course_id = $courseInfo['real_id'];
  717. } else {
  718. $course_id = api_get_course_int_id();
  719. $courseInfo = api_get_course_info();
  720. }
  721. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  722. // Check course code exists.
  723. // Check lp_name doesn't exist, otherwise append something.
  724. $i = 0;
  725. $name = Database::escape_string($name);
  726. $categoryId = (int) $categoryId;
  727. // Session id.
  728. $session_id = api_get_session_id();
  729. $userId = empty($userId) ? api_get_user_id() : $userId;
  730. $check_name = "SELECT * FROM $tbl_lp
  731. WHERE c_id = $course_id AND name = '$name'";
  732. $res_name = Database::query($check_name);
  733. if (empty($publicated_on)) {
  734. $publicated_on = null;
  735. } else {
  736. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  737. }
  738. if (empty($expired_on)) {
  739. $expired_on = null;
  740. } else {
  741. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  742. }
  743. while (Database::num_rows($res_name)) {
  744. // There is already one such name, update the current one a bit.
  745. $i++;
  746. $name = $name.' - '.$i;
  747. $check_name = "SELECT * FROM $tbl_lp
  748. WHERE c_id = $course_id AND name = '$name'";
  749. $res_name = Database::query($check_name);
  750. }
  751. // New name does not exist yet; keep it.
  752. // Escape description.
  753. // Kevin: added htmlentities().
  754. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  755. $type = 1;
  756. switch ($learnpath) {
  757. case 'guess':
  758. break;
  759. case 'dokeos':
  760. case 'chamilo':
  761. $type = 1;
  762. break;
  763. case 'aicc':
  764. break;
  765. }
  766. switch ($origin) {
  767. case 'zip':
  768. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  769. break;
  770. case 'manual':
  771. default:
  772. $get_max = "SELECT MAX(display_order)
  773. FROM $tbl_lp WHERE c_id = $course_id";
  774. $res_max = Database::query($get_max);
  775. if (Database::num_rows($res_max) < 1) {
  776. $dsp = 1;
  777. } else {
  778. $row = Database::fetch_array($res_max);
  779. $dsp = $row[0] + 1;
  780. }
  781. $params = [
  782. 'c_id' => $course_id,
  783. 'lp_type' => $type,
  784. 'name' => $name,
  785. 'description' => $description,
  786. 'path' => '',
  787. 'default_view_mod' => 'embedded',
  788. 'default_encoding' => 'UTF-8',
  789. 'display_order' => $dsp,
  790. 'content_maker' => 'Chamilo',
  791. 'content_local' => 'local',
  792. 'js_lib' => '',
  793. 'session_id' => $session_id,
  794. 'created_on' => api_get_utc_datetime(),
  795. 'modified_on' => api_get_utc_datetime(),
  796. 'publicated_on' => $publicated_on,
  797. 'expired_on' => $expired_on,
  798. 'category_id' => $categoryId,
  799. 'force_commit' => 0,
  800. 'content_license' => '',
  801. 'debug' => 0,
  802. 'theme' => '',
  803. 'preview_image' => '',
  804. 'author' => '',
  805. 'prerequisite' => 0,
  806. 'hide_toc_frame' => 0,
  807. 'seriousgame_mode' => 0,
  808. 'autolaunch' => 0,
  809. 'max_attempts' => 0,
  810. 'subscribe_users' => 0,
  811. 'accumulate_scorm_time' => 1,
  812. ];
  813. $id = Database::insert($tbl_lp, $params);
  814. if ($id > 0) {
  815. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  816. Database::query($sql);
  817. // Insert into item_property.
  818. api_item_property_update(
  819. $courseInfo,
  820. TOOL_LEARNPATH,
  821. $id,
  822. 'LearnpathAdded',
  823. $userId
  824. );
  825. api_set_default_visibility(
  826. $id,
  827. TOOL_LEARNPATH,
  828. 0,
  829. $courseInfo,
  830. $session_id,
  831. $userId
  832. );
  833. return $id;
  834. }
  835. break;
  836. }
  837. }
  838. /**
  839. * Auto completes the parents of an item in case it's been completed or passed.
  840. *
  841. * @param int $item Optional ID of the item from which to look for parents
  842. */
  843. public function autocomplete_parents($item)
  844. {
  845. $debug = $this->debug;
  846. if ($debug) {
  847. error_log('Learnpath::autocomplete_parents()');
  848. }
  849. if (empty($item)) {
  850. $item = $this->current;
  851. }
  852. $currentItem = $this->getItem($item);
  853. if ($currentItem) {
  854. $parent_id = $currentItem->get_parent();
  855. $parent = $this->getItem($parent_id);
  856. if ($parent) {
  857. // if $item points to an object and there is a parent.
  858. if ($debug) {
  859. error_log(
  860. 'Autocompleting parent of item '.$item.' '.
  861. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  862. 0
  863. );
  864. }
  865. // New experiment including failed and browsed in completed status.
  866. //$current_status = $currentItem->get_status();
  867. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  868. // Fixes chapter auto complete
  869. if (true) {
  870. // If the current item is completed or passes or succeeded.
  871. $updateParentStatus = true;
  872. if ($debug) {
  873. error_log('Status of current item is alright');
  874. }
  875. foreach ($parent->get_children() as $childItemId) {
  876. $childItem = $this->getItem($childItemId);
  877. // If children was not set try to get the info
  878. if (empty($childItem->db_item_view_id)) {
  879. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  880. }
  881. // Check all his brothers (parent's children) for completion status.
  882. if ($childItemId != $item) {
  883. if ($debug) {
  884. error_log(
  885. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  886. 0
  887. );
  888. }
  889. // Trying completing parents of failed and browsed items as well.
  890. if ($childItem->status_is(
  891. [
  892. 'completed',
  893. 'passed',
  894. 'succeeded',
  895. 'browsed',
  896. 'failed',
  897. ]
  898. )
  899. ) {
  900. // Keep completion status to true.
  901. continue;
  902. } else {
  903. if ($debug > 2) {
  904. error_log(
  905. '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,
  906. 0
  907. );
  908. }
  909. $updateParentStatus = false;
  910. break;
  911. }
  912. }
  913. }
  914. if ($updateParentStatus) {
  915. // If all the children were completed:
  916. $parent->set_status('completed');
  917. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  918. // Force the status to "completed"
  919. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  920. $this->update_queue[$parent->get_id()] = 'completed';
  921. if ($debug) {
  922. error_log(
  923. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  924. print_r($this->update_queue, 1),
  925. 0
  926. );
  927. }
  928. // Recursive call.
  929. $this->autocomplete_parents($parent->get_id());
  930. }
  931. }
  932. } else {
  933. if ($debug) {
  934. error_log("Parent #$parent_id does not exists");
  935. }
  936. }
  937. } else {
  938. if ($debug) {
  939. error_log("#$item is an item that doesn't have parents");
  940. }
  941. }
  942. }
  943. /**
  944. * Closes the current resource.
  945. *
  946. * Stops the timer
  947. * Saves into the database if required
  948. * Clears the current resource data from this object
  949. *
  950. * @return bool True on success, false on failure
  951. */
  952. public function close()
  953. {
  954. if ($this->debug > 0) {
  955. error_log('In learnpath::close()', 0);
  956. }
  957. if (empty($this->lp_id)) {
  958. $this->error = 'Trying to close this learnpath but no ID is set';
  959. return false;
  960. }
  961. $this->current_time_stop = time();
  962. $this->ordered_items = [];
  963. $this->index = 0;
  964. unset($this->lp_id);
  965. //unset other stuff
  966. return true;
  967. }
  968. /**
  969. * Static admin function allowing removal of a learnpath.
  970. *
  971. * @param array $courseInfo
  972. * @param int $id Learnpath ID
  973. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  974. *
  975. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  976. */
  977. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  978. {
  979. $course_id = api_get_course_int_id();
  980. if (!empty($courseInfo)) {
  981. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  982. }
  983. // TODO: Implement a way of getting this to work when the current object is not set.
  984. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  985. // If an ID is specifically given and the current LP is not the same, prevent delete.
  986. if (!empty($id) && ($id != $this->lp_id)) {
  987. return false;
  988. }
  989. $lp = Database::get_course_table(TABLE_LP_MAIN);
  990. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  991. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  992. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  993. // Delete lp item id.
  994. foreach ($this->items as $lpItemId => $dummy) {
  995. $sql = "DELETE FROM $lp_item_view
  996. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  997. Database::query($sql);
  998. }
  999. // Proposed by Christophe (nickname: clefevre)
  1000. $sql = "DELETE FROM $lp_item
  1001. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1002. Database::query($sql);
  1003. $sql = "DELETE FROM $lp_view
  1004. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  1005. Database::query($sql);
  1006. self::toggle_publish($this->lp_id, 'i');
  1007. if ($this->type == 2 || $this->type == 3) {
  1008. // This is a scorm learning path, delete the files as well.
  1009. $sql = "SELECT path FROM $lp
  1010. WHERE iid = ".$this->lp_id;
  1011. $res = Database::query($sql);
  1012. if (Database::num_rows($res) > 0) {
  1013. $row = Database::fetch_array($res);
  1014. $path = $row['path'];
  1015. $sql = "SELECT id FROM $lp
  1016. WHERE
  1017. c_id = $course_id AND
  1018. path = '$path' AND
  1019. iid != ".$this->lp_id;
  1020. $res = Database::query($sql);
  1021. if (Database::num_rows($res) > 0) {
  1022. // Another learning path uses this directory, so don't delete it.
  1023. if ($this->debug > 2) {
  1024. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1025. }
  1026. } else {
  1027. // No other LP uses that directory, delete it.
  1028. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1029. // The absolute system path for this course.
  1030. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1031. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1032. if ($this->debug > 2) {
  1033. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1034. }
  1035. // Proposed by Christophe (clefevre).
  1036. if (strcmp(substr($path, -2), "/.") == 0) {
  1037. $path = substr($path, 0, -1); // Remove "." at the end.
  1038. }
  1039. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1040. rmdirr($course_scorm_dir.$path);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1046. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1047. // Delete tools
  1048. $sql = "DELETE FROM $tbl_tool
  1049. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1050. Database::query($sql);
  1051. $sql = "DELETE FROM $lp
  1052. WHERE iid = ".$this->lp_id;
  1053. Database::query($sql);
  1054. // Updates the display order of all lps.
  1055. $this->update_display_order();
  1056. api_item_property_update(
  1057. api_get_course_info(),
  1058. TOOL_LEARNPATH,
  1059. $this->lp_id,
  1060. 'delete',
  1061. api_get_user_id()
  1062. );
  1063. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1064. api_get_course_id(),
  1065. 4,
  1066. $id,
  1067. api_get_session_id()
  1068. );
  1069. if ($link_info !== false) {
  1070. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1071. }
  1072. if (api_get_setting('search_enabled') == 'true') {
  1073. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1074. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1075. }
  1076. }
  1077. /**
  1078. * Removes all the children of one item - dangerous!
  1079. *
  1080. * @param int $id Element ID of which children have to be removed
  1081. *
  1082. * @return int Total number of children removed
  1083. */
  1084. public function delete_children_items($id)
  1085. {
  1086. $course_id = $this->course_info['real_id'];
  1087. if ($this->debug > 0) {
  1088. error_log('In learnpath::delete_children_items('.$id.')', 0);
  1089. }
  1090. $num = 0;
  1091. if (empty($id) || $id != strval(intval($id))) {
  1092. return false;
  1093. }
  1094. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1095. $sql = "SELECT * FROM $lp_item
  1096. WHERE c_id = ".$course_id." AND parent_item_id = $id";
  1097. $res = Database::query($sql);
  1098. while ($row = Database::fetch_array($res)) {
  1099. $num += $this->delete_children_items($row['iid']);
  1100. $sql = "DELETE FROM $lp_item
  1101. WHERE c_id = ".$course_id." AND iid = ".$row['iid'];
  1102. Database::query($sql);
  1103. $num++;
  1104. }
  1105. return $num;
  1106. }
  1107. /**
  1108. * Removes an item from the current learnpath.
  1109. *
  1110. * @param int $id Elem ID (0 if first)
  1111. *
  1112. * @return int Number of elements moved
  1113. *
  1114. * @todo implement resource removal
  1115. */
  1116. public function delete_item($id)
  1117. {
  1118. $course_id = api_get_course_int_id();
  1119. if ($this->debug > 0) {
  1120. error_log('In learnpath::delete_item()', 0);
  1121. }
  1122. // TODO: Implement the resource removal.
  1123. if (empty($id) || $id != strval(intval($id))) {
  1124. return false;
  1125. }
  1126. // First select item to get previous, next, and display order.
  1127. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1128. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1129. $res_sel = Database::query($sql_sel);
  1130. if (Database::num_rows($res_sel) < 1) {
  1131. return false;
  1132. }
  1133. $row = Database::fetch_array($res_sel);
  1134. $previous = $row['previous_item_id'];
  1135. $next = $row['next_item_id'];
  1136. $display = $row['display_order'];
  1137. $parent = $row['parent_item_id'];
  1138. $lp = $row['lp_id'];
  1139. // Delete children items.
  1140. $num = $this->delete_children_items($id);
  1141. if ($this->debug > 2) {
  1142. error_log('learnpath::delete_item() - deleted '.$num.' children of element '.$id, 0);
  1143. }
  1144. // Now delete the item.
  1145. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1146. if ($this->debug > 2) {
  1147. error_log('Deleting item: '.$sql_del, 0);
  1148. }
  1149. Database::query($sql_del);
  1150. // Now update surrounding items.
  1151. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1152. WHERE iid = $previous";
  1153. Database::query($sql_upd);
  1154. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1155. WHERE iid = $next";
  1156. Database::query($sql_upd);
  1157. // Now update all following items with new display order.
  1158. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1159. WHERE
  1160. c_id = $course_id AND
  1161. lp_id = $lp AND
  1162. parent_item_id = $parent AND
  1163. display_order > $display";
  1164. Database::query($sql_all);
  1165. //Removing prerequisites since the item will not longer exist
  1166. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1167. WHERE c_id = $course_id AND prerequisite = $id";
  1168. Database::query($sql_all);
  1169. // Remove from search engine if enabled.
  1170. if (api_get_setting('search_enabled') === 'true') {
  1171. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1172. $sql = 'SELECT * FROM %s
  1173. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1174. LIMIT 1';
  1175. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1176. $res = Database::query($sql);
  1177. if (Database::num_rows($res) > 0) {
  1178. $row2 = Database::fetch_array($res);
  1179. $di = new ChamiloIndexer();
  1180. $di->remove_document($row2['search_did']);
  1181. }
  1182. $sql = 'DELETE FROM %s
  1183. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1184. LIMIT 1';
  1185. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1186. Database::query($sql);
  1187. }
  1188. }
  1189. /**
  1190. * Updates an item's content in place.
  1191. *
  1192. * @param int $id Element ID
  1193. * @param int $parent Parent item ID
  1194. * @param int $previous Previous item ID
  1195. * @param string $title Item title
  1196. * @param string $description Item description
  1197. * @param string $prerequisites Prerequisites (optional)
  1198. * @param array $audio The array resulting of the $_FILES[mp3] element
  1199. * @param int $max_time_allowed
  1200. * @param string $url
  1201. *
  1202. * @return bool True on success, false on error
  1203. */
  1204. public function edit_item(
  1205. $id,
  1206. $parent,
  1207. $previous,
  1208. $title,
  1209. $description,
  1210. $prerequisites = '0',
  1211. $audio = [],
  1212. $max_time_allowed = 0,
  1213. $url = ''
  1214. ) {
  1215. $course_id = api_get_course_int_id();
  1216. $_course = api_get_course_info();
  1217. if ($this->debug > 0) {
  1218. error_log('In learnpath::edit_item()', 0);
  1219. }
  1220. if (empty($max_time_allowed)) {
  1221. $max_time_allowed = 0;
  1222. }
  1223. if (empty($id) || ($id != strval(intval($id))) || empty($title)) {
  1224. return false;
  1225. }
  1226. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1227. $sql = "SELECT * FROM $tbl_lp_item
  1228. WHERE iid = $id";
  1229. $res_select = Database::query($sql);
  1230. $row_select = Database::fetch_array($res_select);
  1231. $audio_update_sql = '';
  1232. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1233. // Create the audio folder if it does not exist yet.
  1234. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1235. if (!is_dir($filepath.'audio')) {
  1236. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1237. $audio_id = add_document(
  1238. $_course,
  1239. '/audio',
  1240. 'folder',
  1241. 0,
  1242. 'audio'
  1243. );
  1244. api_item_property_update(
  1245. $_course,
  1246. TOOL_DOCUMENT,
  1247. $audio_id,
  1248. 'FolderCreated',
  1249. api_get_user_id(),
  1250. null,
  1251. null,
  1252. null,
  1253. null,
  1254. api_get_session_id()
  1255. );
  1256. api_item_property_update(
  1257. $_course,
  1258. TOOL_DOCUMENT,
  1259. $audio_id,
  1260. 'invisible',
  1261. api_get_user_id(),
  1262. null,
  1263. null,
  1264. null,
  1265. null,
  1266. api_get_session_id()
  1267. );
  1268. }
  1269. // Upload file in documents.
  1270. $pi = pathinfo($audio['name']);
  1271. if ($pi['extension'] == 'mp3') {
  1272. $c_det = api_get_course_info($this->cc);
  1273. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1274. $path = handle_uploaded_document(
  1275. $c_det,
  1276. $audio,
  1277. $bp,
  1278. '/audio',
  1279. api_get_user_id(),
  1280. 0,
  1281. null,
  1282. 0,
  1283. 'rename',
  1284. false,
  1285. 0
  1286. );
  1287. $path = substr($path, 7);
  1288. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1289. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1290. }
  1291. }
  1292. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1293. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1294. // TODO: htmlspecialchars to be checked for encoding related problems.
  1295. if ($same_parent && $same_previous) {
  1296. // Only update title and description.
  1297. $sql = "UPDATE $tbl_lp_item
  1298. SET title = '".Database::escape_string($title)."',
  1299. prerequisite = '".$prerequisites."',
  1300. description = '".Database::escape_string($description)."'
  1301. ".$audio_update_sql.",
  1302. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1303. WHERE iid = $id";
  1304. Database::query($sql);
  1305. } else {
  1306. $old_parent = $row_select['parent_item_id'];
  1307. $old_previous = $row_select['previous_item_id'];
  1308. $old_next = $row_select['next_item_id'];
  1309. $old_order = $row_select['display_order'];
  1310. $old_prerequisite = $row_select['prerequisite'];
  1311. $old_max_time_allowed = $row_select['max_time_allowed'];
  1312. /* BEGIN -- virtually remove the current item id */
  1313. /* for the next and previous item it is like the current item doesn't exist anymore */
  1314. if ($old_previous != 0) {
  1315. // Next
  1316. $sql = "UPDATE $tbl_lp_item
  1317. SET next_item_id = $old_next
  1318. WHERE iid = $old_previous";
  1319. Database::query($sql);
  1320. }
  1321. if (!empty($old_next)) {
  1322. // Previous
  1323. $sql = "UPDATE $tbl_lp_item
  1324. SET previous_item_id = $old_previous
  1325. WHERE iid = $old_next";
  1326. Database::query($sql);
  1327. }
  1328. // display_order - 1 for every item with a display_order
  1329. // bigger then the display_order of the current item.
  1330. $sql = "UPDATE $tbl_lp_item
  1331. SET display_order = display_order - 1
  1332. WHERE
  1333. c_id = $course_id AND
  1334. display_order > $old_order AND
  1335. lp_id = ".$this->lp_id." AND
  1336. parent_item_id = $old_parent";
  1337. Database::query($sql);
  1338. /* END -- virtually remove the current item id */
  1339. /* BEGIN -- update the current item id to his new location */
  1340. if ($previous == 0) {
  1341. // Select the data of the item that should come after the current item.
  1342. $sql = "SELECT id, display_order
  1343. FROM $tbl_lp_item
  1344. WHERE
  1345. c_id = $course_id AND
  1346. lp_id = ".$this->lp_id." AND
  1347. parent_item_id = $parent AND
  1348. previous_item_id = $previous";
  1349. $res_select_old = Database::query($sql);
  1350. $row_select_old = Database::fetch_array($res_select_old);
  1351. // If the new parent didn't have children before.
  1352. if (Database::num_rows($res_select_old) == 0) {
  1353. $new_next = 0;
  1354. $new_order = 1;
  1355. } else {
  1356. $new_next = $row_select_old['id'];
  1357. $new_order = $row_select_old['display_order'];
  1358. }
  1359. } else {
  1360. // Select the data of the item that should come before the current item.
  1361. $sql = "SELECT next_item_id, display_order
  1362. FROM $tbl_lp_item
  1363. WHERE iid = $previous";
  1364. $res_select_old = Database::query($sql);
  1365. $row_select_old = Database::fetch_array($res_select_old);
  1366. $new_next = $row_select_old['next_item_id'];
  1367. $new_order = $row_select_old['display_order'] + 1;
  1368. }
  1369. // TODO: htmlspecialchars to be checked for encoding related problems.
  1370. // Update the current item with the new data.
  1371. $sql = "UPDATE $tbl_lp_item
  1372. SET
  1373. title = '".Database::escape_string($title)."',
  1374. description = '".Database::escape_string($description)."',
  1375. parent_item_id = $parent,
  1376. previous_item_id = $previous,
  1377. next_item_id = $new_next,
  1378. display_order = $new_order
  1379. $audio_update_sql
  1380. WHERE iid = $id";
  1381. Database::query($sql);
  1382. if ($previous != 0) {
  1383. // Update the previous item's next_item_id.
  1384. $sql = "UPDATE $tbl_lp_item
  1385. SET next_item_id = $id
  1386. WHERE iid = $previous";
  1387. Database::query($sql);
  1388. }
  1389. if (!empty($new_next)) {
  1390. // Update the next item's previous_item_id.
  1391. $sql = "UPDATE $tbl_lp_item
  1392. SET previous_item_id = $id
  1393. WHERE iid = $new_next";
  1394. Database::query($sql);
  1395. }
  1396. if ($old_prerequisite != $prerequisites) {
  1397. $sql = "UPDATE $tbl_lp_item
  1398. SET prerequisite = '$prerequisites'
  1399. WHERE iid = $id";
  1400. Database::query($sql);
  1401. }
  1402. if ($old_max_time_allowed != $max_time_allowed) {
  1403. // update max time allowed
  1404. $sql = "UPDATE $tbl_lp_item
  1405. SET max_time_allowed = $max_time_allowed
  1406. WHERE iid = $id";
  1407. Database::query($sql);
  1408. }
  1409. // Update all the items with the same or a bigger display_order than the current item.
  1410. $sql = "UPDATE $tbl_lp_item
  1411. SET display_order = display_order + 1
  1412. WHERE
  1413. c_id = $course_id AND
  1414. lp_id = ".$this->get_id()." AND
  1415. iid <> $id AND
  1416. parent_item_id = $parent AND
  1417. display_order >= $new_order";
  1418. Database::query($sql);
  1419. }
  1420. if ($row_select['item_type'] == 'link') {
  1421. $link = new Link();
  1422. $linkId = $row_select['path'];
  1423. $link->updateLink($linkId, $url);
  1424. }
  1425. }
  1426. /**
  1427. * Updates an item's prereq in place.
  1428. *
  1429. * @param int $id Element ID
  1430. * @param string $prerequisite_id Prerequisite Element ID
  1431. * @param int $minScore Prerequisite min score
  1432. * @param int $maxScore Prerequisite max score
  1433. *
  1434. * @return bool True on success, false on error
  1435. */
  1436. public function edit_item_prereq(
  1437. $id,
  1438. $prerequisite_id,
  1439. $minScore = 0,
  1440. $maxScore = 100
  1441. ) {
  1442. if ($this->debug > 0) {
  1443. error_log('In learnpath::edit_item_prereq('.$id.','.$prerequisite_id.','.$minScore.','.$maxScore.')', 0);
  1444. }
  1445. $id = (int) $id;
  1446. $prerequisite_id = (int) $prerequisite_id;
  1447. if (empty($id)) {
  1448. return false;
  1449. }
  1450. if (empty($minScore) || $minScore < 0) {
  1451. $minScore = 0;
  1452. }
  1453. if (empty($maxScore) || $maxScore < 0) {
  1454. $maxScore = 100;
  1455. }
  1456. $minScore = floatval($minScore);
  1457. $maxScore = floatval($maxScore);
  1458. if (empty($prerequisite_id)) {
  1459. $prerequisite_id = 'NULL';
  1460. $minScore = 0;
  1461. $maxScore = 100;
  1462. }
  1463. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1464. $sql = " UPDATE $tbl_lp_item
  1465. SET
  1466. prerequisite = $prerequisite_id ,
  1467. prerequisite_min_score = $minScore ,
  1468. prerequisite_max_score = $maxScore
  1469. WHERE iid = $id";
  1470. Database::query($sql);
  1471. return true;
  1472. }
  1473. /**
  1474. * Gets all the chapters belonging to the same parent as the item/chapter given
  1475. * Can also be called as abstract method.
  1476. *
  1477. * @param int $id Item ID
  1478. *
  1479. * @return array A list of all the "brother items" (or an empty array on failure)
  1480. */
  1481. public function getSiblingDirectories($id)
  1482. {
  1483. $course_id = api_get_course_int_id();
  1484. if ($this->debug > 0) {
  1485. error_log('In learnpath::getSiblingDirectories()', 0);
  1486. }
  1487. if (empty($id) || $id != strval(intval($id))) {
  1488. return [];
  1489. }
  1490. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1491. $sql_parent = "SELECT * FROM $lp_item
  1492. WHERE iid = $id AND item_type='dir'";
  1493. $res_parent = Database::query($sql_parent);
  1494. if (Database::num_rows($res_parent) > 0) {
  1495. $row_parent = Database::fetch_array($res_parent);
  1496. $parent = $row_parent['parent_item_id'];
  1497. $sql = "SELECT * FROM $lp_item
  1498. WHERE
  1499. parent_item_id = $parent AND
  1500. iid = $id AND
  1501. item_type='dir'
  1502. ORDER BY display_order";
  1503. $res_bros = Database::query($sql);
  1504. $list = [];
  1505. while ($row_bro = Database::fetch_array($res_bros)) {
  1506. $list[] = $row_bro;
  1507. }
  1508. return $list;
  1509. }
  1510. return [];
  1511. }
  1512. /**
  1513. * Gets all the items belonging to the same parent as the item given
  1514. * Can also be called as abstract method.
  1515. *
  1516. * @param int $id Item ID
  1517. *
  1518. * @return array A list of all the "brother items" (or an empty array on failure)
  1519. */
  1520. public function get_brother_items($id)
  1521. {
  1522. $course_id = api_get_course_int_id();
  1523. if ($this->debug > 0) {
  1524. error_log('In learnpath::get_brother_items('.$id.')', 0);
  1525. }
  1526. if (empty($id) || $id != strval(intval($id))) {
  1527. return [];
  1528. }
  1529. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1530. $sql_parent = "SELECT * FROM $lp_item
  1531. WHERE iid = $id";
  1532. $res_parent = Database::query($sql_parent);
  1533. if (Database::num_rows($res_parent) > 0) {
  1534. $row_parent = Database::fetch_array($res_parent);
  1535. $parent = $row_parent['parent_item_id'];
  1536. $sql = "SELECT * FROM $lp_item
  1537. WHERE c_id = $course_id AND parent_item_id = $parent
  1538. ORDER BY display_order";
  1539. $res_bros = Database::query($sql);
  1540. $list = [];
  1541. while ($row_bro = Database::fetch_array($res_bros)) {
  1542. $list[] = $row_bro;
  1543. }
  1544. return $list;
  1545. }
  1546. return [];
  1547. }
  1548. /**
  1549. * Get the specific prefix index terms of this learning path.
  1550. *
  1551. * @param string $prefix
  1552. *
  1553. * @return array Array of terms
  1554. */
  1555. public function get_common_index_terms_by_prefix($prefix)
  1556. {
  1557. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1558. $terms = get_specific_field_values_list_by_prefix(
  1559. $prefix,
  1560. $this->cc,
  1561. TOOL_LEARNPATH,
  1562. $this->lp_id
  1563. );
  1564. $prefix_terms = [];
  1565. if (!empty($terms)) {
  1566. foreach ($terms as $term) {
  1567. $prefix_terms[] = $term['value'];
  1568. }
  1569. }
  1570. return $prefix_terms;
  1571. }
  1572. /**
  1573. * Gets the number of items currently completed.
  1574. *
  1575. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1576. *
  1577. * @return int The number of items currently completed
  1578. */
  1579. public function get_complete_items_count($failedStatusException = false)
  1580. {
  1581. if ($this->debug > 0) {
  1582. error_log('In learnpath::get_complete_items_count()', 0);
  1583. }
  1584. $i = 0;
  1585. $completedStatusList = [
  1586. 'completed',
  1587. 'passed',
  1588. 'succeeded',
  1589. 'browsed',
  1590. ];
  1591. if (!$failedStatusException) {
  1592. $completedStatusList[] = 'failed';
  1593. }
  1594. foreach ($this->items as $id => $dummy) {
  1595. // Trying failed and browsed considered "progressed" as well.
  1596. if ($this->items[$id]->status_is($completedStatusList) &&
  1597. $this->items[$id]->get_type() != 'dir'
  1598. ) {
  1599. $i++;
  1600. }
  1601. }
  1602. return $i;
  1603. }
  1604. /**
  1605. * Gets the current item ID.
  1606. *
  1607. * @return int The current learnpath item id
  1608. */
  1609. public function get_current_item_id()
  1610. {
  1611. $current = 0;
  1612. if ($this->debug > 0) {
  1613. error_log('In learnpath::get_current_item_id()', 0);
  1614. }
  1615. if (!empty($this->current)) {
  1616. $current = $this->current;
  1617. }
  1618. if ($this->debug > 2) {
  1619. error_log('In learnpath::get_current_item_id() - Returning '.$current, 0);
  1620. }
  1621. return $current;
  1622. }
  1623. /**
  1624. * Force to get the first learnpath item id.
  1625. *
  1626. * @return int The current learnpath item id
  1627. */
  1628. public function get_first_item_id()
  1629. {
  1630. $current = 0;
  1631. if (is_array($this->ordered_items)) {
  1632. $current = $this->ordered_items[0];
  1633. }
  1634. return $current;
  1635. }
  1636. /**
  1637. * Gets the total number of items available for viewing in this SCORM.
  1638. *
  1639. * @return int The total number of items
  1640. */
  1641. public function get_total_items_count()
  1642. {
  1643. if ($this->debug > 0) {
  1644. error_log('In learnpath::get_total_items_count()', 0);
  1645. }
  1646. return count($this->items);
  1647. }
  1648. /**
  1649. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1650. *
  1651. * @return int The total no-chapters number of items
  1652. */
  1653. public function getTotalItemsCountWithoutDirs()
  1654. {
  1655. if ($this->debug > 0) {
  1656. error_log('In learnpath::getTotalItemsCountWithoutDirs()', 0);
  1657. }
  1658. $total = 0;
  1659. $typeListNotToCount = self::getChapterTypes();
  1660. foreach ($this->items as $temp2) {
  1661. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1662. $total++;
  1663. }
  1664. }
  1665. return $total;
  1666. }
  1667. /**
  1668. * Sets the first element URL.
  1669. */
  1670. public function first()
  1671. {
  1672. if ($this->debug > 0) {
  1673. error_log('In learnpath::first()', 0);
  1674. error_log('$this->last_item_seen '.$this->last_item_seen);
  1675. }
  1676. // Test if the last_item_seen exists and is not a dir.
  1677. if (count($this->ordered_items) == 0) {
  1678. $this->index = 0;
  1679. }
  1680. if (!empty($this->last_item_seen) &&
  1681. !empty($this->items[$this->last_item_seen]) &&
  1682. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1683. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1684. //&& !$this->items[$this->last_item_seen]->is_done()
  1685. ) {
  1686. if ($this->debug > 2) {
  1687. error_log(
  1688. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1689. $this->items[$this->last_item_seen]->get_type()
  1690. );
  1691. }
  1692. $index = -1;
  1693. foreach ($this->ordered_items as $myindex => $item_id) {
  1694. if ($item_id == $this->last_item_seen) {
  1695. $index = $myindex;
  1696. break;
  1697. }
  1698. }
  1699. if ($index == -1) {
  1700. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1701. if ($this->debug > 2) {
  1702. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1703. }
  1704. return false;
  1705. } else {
  1706. $this->last = $this->last_item_seen;
  1707. $this->current = $this->last_item_seen;
  1708. $this->index = $index;
  1709. }
  1710. } else {
  1711. if ($this->debug > 2) {
  1712. error_log('In learnpath::first() - No last item seen', 0);
  1713. }
  1714. $index = 0;
  1715. // Loop through all ordered items and stop at the first item that is
  1716. // not a directory *and* that has not been completed yet.
  1717. while (!empty($this->ordered_items[$index]) &&
  1718. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1719. (
  1720. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1721. $this->items[$this->ordered_items[$index]]->is_done() === true
  1722. ) && $index < $this->max_ordered_items) {
  1723. $index++;
  1724. }
  1725. $this->last = $this->current;
  1726. // current is
  1727. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1728. $this->index = $index;
  1729. if ($this->debug > 2) {
  1730. error_log('$index '.$index);
  1731. error_log('In learnpath::first() - No last item seen');
  1732. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1733. }
  1734. }
  1735. if ($this->debug > 2) {
  1736. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1737. }
  1738. }
  1739. /**
  1740. * Gets the information about an item in a format usable as JavaScript to update
  1741. * the JS API by just printing this content into the <head> section of the message frame.
  1742. *
  1743. * @param int $item_id
  1744. *
  1745. * @return string
  1746. */
  1747. public function get_js_info($item_id = 0)
  1748. {
  1749. if ($this->debug > 0) {
  1750. error_log('In learnpath::get_js_info('.$item_id.')', 0);
  1751. }
  1752. $info = '';
  1753. $item_id = intval($item_id);
  1754. if (!empty($item_id) && is_object($this->items[$item_id])) {
  1755. //if item is defined, return values from DB
  1756. $oItem = $this->items[$item_id];
  1757. $info .= '<script language="javascript">';
  1758. $info .= "top.set_score(".$oItem->get_score().");\n";
  1759. $info .= "top.set_max(".$oItem->get_max().");\n";
  1760. $info .= "top.set_min(".$oItem->get_min().");\n";
  1761. $info .= "top.set_lesson_status('".$oItem->get_status()."');";
  1762. $info .= "top.set_session_time('".$oItem->get_scorm_time('js')."');";
  1763. $info .= "top.set_suspend_data('".$oItem->get_suspend_data()."');";
  1764. $info .= "top.set_saved_lesson_status('".$oItem->get_status()."');";
  1765. $info .= "top.set_flag_synchronized();";
  1766. $info .= '</script>';
  1767. if ($this->debug > 2) {
  1768. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1769. }
  1770. return $info;
  1771. } else {
  1772. // If item_id is empty, just update to default SCORM data.
  1773. $info .= '<script language="javascript">';
  1774. $info .= "top.set_score(".learnpathItem::get_score().");\n";
  1775. $info .= "top.set_max(".learnpathItem::get_max().");\n";
  1776. $info .= "top.set_min(".learnpathItem::get_min().");\n";
  1777. $info .= "top.set_lesson_status('".learnpathItem::get_status()."');";
  1778. $info .= "top.set_session_time('".learnpathItem::getScormTimeFromParameter('js')."');";
  1779. $info .= "top.set_suspend_data('".learnpathItem::get_suspend_data()."');";
  1780. $info .= "top.set_saved_lesson_status('".learnpathItem::get_status()."');";
  1781. $info .= "top.set_flag_synchronized();";
  1782. $info .= '</script>';
  1783. if ($this->debug > 2) {
  1784. error_log('in learnpath::get_js_info('.$item_id.') - returning: '.$info, 0);
  1785. }
  1786. return $info;
  1787. }
  1788. }
  1789. /**
  1790. * Gets the js library from the database.
  1791. *
  1792. * @return string The name of the javascript library to be used
  1793. */
  1794. public function get_js_lib()
  1795. {
  1796. $lib = '';
  1797. if (!empty($this->js_lib)) {
  1798. $lib = $this->js_lib;
  1799. }
  1800. return $lib;
  1801. }
  1802. /**
  1803. * Gets the learnpath database ID.
  1804. *
  1805. * @return int Learnpath ID in the lp table
  1806. */
  1807. public function get_id()
  1808. {
  1809. if (!empty($this->lp_id)) {
  1810. return $this->lp_id;
  1811. } else {
  1812. return 0;
  1813. }
  1814. }
  1815. /**
  1816. * Gets the last element URL.
  1817. *
  1818. * @return string URL to load into the viewer
  1819. */
  1820. public function get_last()
  1821. {
  1822. if ($this->debug > 0) {
  1823. error_log('In learnpath::get_last()', 0);
  1824. }
  1825. //This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1826. if (count($this->ordered_items) > 0) {
  1827. $this->index = count($this->ordered_items) - 1;
  1828. return $this->ordered_items[$this->index];
  1829. }
  1830. return false;
  1831. }
  1832. /**
  1833. * Gets the navigation bar for the learnpath display screen.
  1834. *
  1835. * @return string The HTML string to use as a navigation bar
  1836. */
  1837. public function get_navigation_bar($idBar = null, $display = null)
  1838. {
  1839. if ($this->debug > 0) {
  1840. error_log('In learnpath::get_navigation_bar()', 0);
  1841. }
  1842. if (empty($idBar)) {
  1843. $idBar = 'control-top';
  1844. }
  1845. $lpId = $this->lp_id;
  1846. $mycurrentitemid = $this->get_current_item_id();
  1847. $reportingText = get_lang('Reporting');
  1848. $previousText = get_lang('ScormPrevious');
  1849. $nextText = get_lang('ScormNext');
  1850. $fullScreenText = get_lang('ScormExitFullScreen');
  1851. $settings = api_get_configuration_value('lp_view_settings');
  1852. $display = isset($settings['display']) ? $settings['display'] : false;
  1853. $reportingIcon = '
  1854. <a class="icon-toolbar"
  1855. id="stats_link"
  1856. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1857. onclick="window.parent.API.save_asset(); return true;"
  1858. target="content_name" title="'.$reportingText.'">
  1859. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1860. </a>';
  1861. if (!empty($display)) {
  1862. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1863. if ($showReporting == false) {
  1864. $reportingIcon = '';
  1865. }
  1866. }
  1867. $hideArrows = false;
  1868. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1869. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1870. }
  1871. $previousIcon = '';
  1872. $nextIcon = '';
  1873. if ($hideArrows === false) {
  1874. $previousIcon = '
  1875. <a class="icon-toolbar" id="scorm-previous" href="#"
  1876. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1877. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1878. </a>';
  1879. $nextIcon = '
  1880. <a class="icon-toolbar" id="scorm-next" href="#"
  1881. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1882. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1883. </a>';
  1884. }
  1885. if ($this->mode === 'fullscreen') {
  1886. $navbar = '
  1887. <span id="'.$idBar.'" class="buttons">
  1888. '.$reportingIcon.'
  1889. '.$previousIcon.'
  1890. '.$nextIcon.'
  1891. <a class="icon-toolbar" id="view-embedded"
  1892. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1893. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1894. </a>
  1895. </span>';
  1896. } else {
  1897. $navbar = '
  1898. <span id="'.$idBar.'" class="buttons text-right">
  1899. '.$reportingIcon.'
  1900. '.$previousIcon.'
  1901. '.$nextIcon.'
  1902. </span>';
  1903. }
  1904. return $navbar;
  1905. }
  1906. /**
  1907. * Gets the next resource in queue (url).
  1908. *
  1909. * @return string URL to load into the viewer
  1910. */
  1911. public function get_next_index()
  1912. {
  1913. if ($this->debug > 0) {
  1914. error_log('In learnpath::get_next_index()', 0);
  1915. }
  1916. // TODO
  1917. $index = $this->index;
  1918. $index++;
  1919. if ($this->debug > 2) {
  1920. error_log('Now looking at ordered_items['.($index).'] - type is '.$this->items[$this->ordered_items[$index]]->type, 0);
  1921. }
  1922. while (
  1923. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1924. $index < $this->max_ordered_items
  1925. ) {
  1926. $index++;
  1927. if ($index == $this->max_ordered_items) {
  1928. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1929. return $this->index;
  1930. } else {
  1931. return $index;
  1932. }
  1933. }
  1934. }
  1935. if (empty($this->ordered_items[$index])) {
  1936. return $this->index;
  1937. }
  1938. if ($this->debug > 2) {
  1939. error_log('index is now '.$index, 0);
  1940. }
  1941. return $index;
  1942. }
  1943. /**
  1944. * Gets item_id for the next element.
  1945. *
  1946. * @return int Next item (DB) ID
  1947. */
  1948. public function get_next_item_id()
  1949. {
  1950. if ($this->debug > 0) {
  1951. error_log('In learnpath::get_next_item_id()', 0);
  1952. }
  1953. $new_index = $this->get_next_index();
  1954. if (!empty($new_index)) {
  1955. if (isset($this->ordered_items[$new_index])) {
  1956. if ($this->debug > 2) {
  1957. error_log('In learnpath::get_next_index() - Returning '.$this->ordered_items[$new_index], 0);
  1958. }
  1959. return $this->ordered_items[$new_index];
  1960. }
  1961. }
  1962. if ($this->debug > 2) {
  1963. error_log('In learnpath::get_next_index() - Problem - Returning 0', 0);
  1964. }
  1965. return 0;
  1966. }
  1967. /**
  1968. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1969. *
  1970. * Generally, the package provided is in the form of a zip file, so the function
  1971. * has been written to test a zip file. If not a zip, the function will return the
  1972. * default return value: ''
  1973. *
  1974. * @param string $file_path the path to the file
  1975. * @param string $file_name the original name of the file
  1976. *
  1977. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1978. */
  1979. public static function get_package_type($file_path, $file_name)
  1980. {
  1981. // Get name of the zip file without the extension.
  1982. $file_info = pathinfo($file_name);
  1983. $extension = $file_info['extension']; // Extension only.
  1984. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1985. 'dll',
  1986. 'exe',
  1987. ])) {
  1988. return 'oogie';
  1989. }
  1990. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1991. 'dll',
  1992. 'exe',
  1993. ])) {
  1994. return 'woogie';
  1995. }
  1996. $zipFile = new PclZip($file_path);
  1997. // Check the zip content (real size and file extension).
  1998. $zipContentArray = $zipFile->listContent();
  1999. $package_type = '';
  2000. $manifest = '';
  2001. $aicc_match_crs = 0;
  2002. $aicc_match_au = 0;
  2003. $aicc_match_des = 0;
  2004. $aicc_match_cst = 0;
  2005. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  2006. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  2007. foreach ($zipContentArray as $thisContent) {
  2008. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  2009. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  2010. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  2011. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  2012. $package_type = 'scorm';
  2013. break; // Exit the foreach loop.
  2014. } elseif (
  2015. preg_match('/aicc\//i', $thisContent['filename']) ||
  2016. in_array(
  2017. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  2018. ['crs', 'au', 'des', 'cst']
  2019. )
  2020. ) {
  2021. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  2022. switch ($ext) {
  2023. case 'crs':
  2024. $aicc_match_crs = 1;
  2025. break;
  2026. case 'au':
  2027. $aicc_match_au = 1;
  2028. break;
  2029. case 'des':
  2030. $aicc_match_des = 1;
  2031. break;
  2032. case 'cst':
  2033. $aicc_match_cst = 1;
  2034. break;
  2035. default:
  2036. break;
  2037. }
  2038. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  2039. } else {
  2040. $package_type = '';
  2041. }
  2042. }
  2043. }
  2044. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  2045. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  2046. $package_type = 'aicc';
  2047. }
  2048. // Try with chamilo course builder
  2049. if (empty($package_type)) {
  2050. $package_type = 'chamilo';
  2051. }
  2052. return $package_type;
  2053. }
  2054. /**
  2055. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  2056. *
  2057. * @return string URL to load into the viewer
  2058. */
  2059. public function get_previous_index()
  2060. {
  2061. if ($this->debug > 0) {
  2062. error_log('In learnpath::get_previous_index()', 0);
  2063. }
  2064. $index = $this->index;
  2065. if (isset($this->ordered_items[$index - 1])) {
  2066. $index--;
  2067. while (isset($this->ordered_items[$index]) &&
  2068. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  2069. ) {
  2070. $index--;
  2071. if ($index < 0) {
  2072. return $this->index;
  2073. }
  2074. }
  2075. } else {
  2076. if ($this->debug > 2) {
  2077. error_log('get_previous_index() - there was no previous index available, reusing '.$index, 0);
  2078. }
  2079. // There is no previous item.
  2080. }
  2081. return $index;
  2082. }
  2083. /**
  2084. * Gets item_id for the next element.
  2085. *
  2086. * @return int Previous item (DB) ID
  2087. */
  2088. public function get_previous_item_id()
  2089. {
  2090. if ($this->debug > 0) {
  2091. error_log('In learnpath::get_previous_item_id()', 0);
  2092. }
  2093. $new_index = $this->get_previous_index();
  2094. return $this->ordered_items[$new_index];
  2095. }
  2096. /**
  2097. * Returns the HTML necessary to print a mediaplayer block inside a page.
  2098. *
  2099. * @param int $lpItemId
  2100. * @param string $autostart
  2101. *
  2102. * @return string The mediaplayer HTML
  2103. */
  2104. public function get_mediaplayer($lpItemId, $autostart = 'true')
  2105. {
  2106. $course_id = api_get_course_int_id();
  2107. $_course = api_get_course_info();
  2108. if (empty($_course)) {
  2109. return '';
  2110. }
  2111. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2112. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  2113. $lpItemId = (int) $lpItemId;
  2114. /** @var learnpathItem $item */
  2115. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2116. $itemViewId = 0;
  2117. if ($item) {
  2118. $itemViewId = (int) $item->db_item_view_id;
  2119. }
  2120. // Getting all the information about the item.
  2121. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2122. FROM $tbl_lp_item as lpi
  2123. INNER JOIN $tbl_lp_item_view as lp_view
  2124. ON (lpi.iid = lp_view.lp_item_id)
  2125. WHERE
  2126. lp_view.iid = $itemViewId AND
  2127. lpi.iid = $lpItemId AND
  2128. lp_view.c_id = $course_id";
  2129. $result = Database::query($sql);
  2130. $row = Database::fetch_assoc($result);
  2131. $output = '';
  2132. if (!empty($row['audio'])) {
  2133. $list = $_SESSION['oLP']->get_toc();
  2134. switch ($row['item_type']) {
  2135. case 'quiz':
  2136. $type_quiz = false;
  2137. foreach ($list as $toc) {
  2138. if ($toc['id'] == $_SESSION['oLP']->current) {
  2139. $type_quiz = true;
  2140. }
  2141. }
  2142. if ($type_quiz) {
  2143. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2144. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2145. } else {
  2146. $autostart_audio = $autostart;
  2147. }
  2148. }
  2149. break;
  2150. case TOOL_READOUT_TEXT:;
  2151. $autostart_audio = 'false';
  2152. break;
  2153. default:
  2154. $autostart_audio = 'true';
  2155. }
  2156. $courseInfo = api_get_course_info();
  2157. $audio = $row['audio'];
  2158. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2159. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2160. if (!file_exists($file)) {
  2161. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2162. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2163. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2164. }
  2165. $player = Display::getMediaPlayer(
  2166. $file,
  2167. [
  2168. 'id' => 'lp_audio_media_player',
  2169. 'url' => $url,
  2170. 'autoplay' => $autostart_audio,
  2171. 'width' => '100%',
  2172. ]
  2173. );
  2174. // The mp3 player.
  2175. $output = '<div id="container">';
  2176. $output .= $player;
  2177. $output .= '</div>';
  2178. }
  2179. return $output;
  2180. }
  2181. /**
  2182. * @param int $studentId
  2183. * @param int $prerequisite
  2184. * @param array $courseInfo
  2185. * @param int $sessionId
  2186. *
  2187. * @return bool
  2188. */
  2189. public static function isBlockedByPrerequisite(
  2190. $studentId,
  2191. $prerequisite,
  2192. $courseInfo,
  2193. $sessionId
  2194. ) {
  2195. if (empty($courseInfo)) {
  2196. return false;
  2197. }
  2198. $courseId = $courseInfo['real_id'];
  2199. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2200. if ($allow) {
  2201. if (api_is_allowed_to_edit() ||
  2202. api_is_platform_admin(true) ||
  2203. api_is_drh() ||
  2204. api_is_coach($sessionId, $courseId, false)
  2205. ) {
  2206. return false;
  2207. }
  2208. }
  2209. $isBlocked = false;
  2210. if (!empty($prerequisite)) {
  2211. $progress = self::getProgress(
  2212. $prerequisite,
  2213. $studentId,
  2214. $courseId,
  2215. $sessionId
  2216. );
  2217. if ($progress < 100) {
  2218. $isBlocked = true;
  2219. }
  2220. if (Tracking::minimunTimeAvailable($sessionId, $courseId)) {
  2221. // Block if it does not exceed minimum time
  2222. // Minimum time (in minutes) to pass the learning path
  2223. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2224. if ($accumulateWorkTime > 0) {
  2225. // Total time in course (sum of times in learning paths from course)
  2226. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2227. // Connect with the plugin_licences_course_session table
  2228. // which indicates what percentage of the time applies
  2229. // Minimum connection percentage
  2230. $perc = 100;
  2231. // Time from the course
  2232. $tc = $accumulateWorkTimeTotal;
  2233. // Percentage of the learning paths
  2234. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2235. // Minimum time for each learning path
  2236. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2237. // Spent time (in seconds) so far in the learning path
  2238. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2239. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2240. if ($lpTime < ($accumulateWorkTime * 60)) {
  2241. $isBlocked = true;
  2242. }
  2243. }
  2244. }
  2245. }
  2246. return $isBlocked;
  2247. }
  2248. /**
  2249. * Checks if the learning path is visible for student after the progress
  2250. * of its prerequisite is completed, considering the time availability and
  2251. * the LP visibility.
  2252. *
  2253. * @param int $lp_id
  2254. * @param int $student_id
  2255. * @param null $courseCode
  2256. * @param int $sessionId
  2257. *
  2258. * @return bool
  2259. */
  2260. public static function is_lp_visible_for_student(
  2261. $lp_id,
  2262. $student_id,
  2263. $courseCode = null,
  2264. $sessionId = 0
  2265. ) {
  2266. $courseInfo = api_get_course_info($courseCode);
  2267. $lp_id = (int) $lp_id;
  2268. $sessionId = (int) $sessionId;
  2269. if (empty($courseInfo)) {
  2270. return false;
  2271. }
  2272. if (empty($sessionId)) {
  2273. $sessionId = api_get_session_id();
  2274. }
  2275. $itemInfo = api_get_item_property_info(
  2276. $courseInfo['real_id'],
  2277. TOOL_LEARNPATH,
  2278. $lp_id,
  2279. $sessionId
  2280. );
  2281. // If the item was deleted.
  2282. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2283. return false;
  2284. }
  2285. // @todo remove this query and load the row info as a parameter
  2286. $table = Database::get_course_table(TABLE_LP_MAIN);
  2287. // Get current prerequisite
  2288. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2289. FROM $table
  2290. WHERE iid = $lp_id";
  2291. $rs = Database::query($sql);
  2292. $now = time();
  2293. if (Database::num_rows($rs) > 0) {
  2294. $row = Database::fetch_array($rs, 'ASSOC');
  2295. $prerequisite = $row['prerequisite'];
  2296. $is_visible = true;
  2297. $isBlocked = self::isBlockedByPrerequisite(
  2298. $student_id,
  2299. $prerequisite,
  2300. $courseInfo,
  2301. $sessionId
  2302. );
  2303. if ($isBlocked) {
  2304. $is_visible = false;
  2305. }
  2306. // Also check the time availability of the LP
  2307. if ($is_visible) {
  2308. // Adding visibility restrictions
  2309. if (!empty($row['publicated_on'])) {
  2310. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2311. $is_visible = false;
  2312. }
  2313. }
  2314. // Blocking empty start times see BT#2800
  2315. global $_custom;
  2316. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2317. $_custom['lps_hidden_when_no_start_date']
  2318. ) {
  2319. if (empty($row['publicated_on'])) {
  2320. $is_visible = false;
  2321. }
  2322. }
  2323. if (!empty($row['expired_on'])) {
  2324. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2325. $is_visible = false;
  2326. }
  2327. }
  2328. }
  2329. if ($is_visible) {
  2330. $subscriptionSettings = self::getSubscriptionSettings();
  2331. // Check if the subscription users/group to a LP is ON
  2332. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2333. $subscriptionSettings['allow_add_users_to_lp'] === true
  2334. ) {
  2335. // Try group
  2336. $is_visible = false;
  2337. // Checking only the user visibility
  2338. $userVisibility = api_get_item_visibility(
  2339. $courseInfo,
  2340. 'learnpath',
  2341. $row['id'],
  2342. $sessionId,
  2343. $student_id,
  2344. 'LearnpathSubscription'
  2345. );
  2346. if ($userVisibility == 1) {
  2347. $is_visible = true;
  2348. } else {
  2349. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id);
  2350. if (!empty($userGroups)) {
  2351. foreach ($userGroups as $groupInfo) {
  2352. $groupId = $groupInfo['iid'];
  2353. $userVisibility = api_get_item_visibility(
  2354. $courseInfo,
  2355. 'learnpath',
  2356. $row['id'],
  2357. $sessionId,
  2358. null,
  2359. 'LearnpathSubscription',
  2360. $groupId
  2361. );
  2362. if ($userVisibility == 1) {
  2363. $is_visible = true;
  2364. break;
  2365. }
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. return $is_visible;
  2372. }
  2373. return false;
  2374. }
  2375. /**
  2376. * @param int $lpId
  2377. * @param int $userId
  2378. * @param int $courseId
  2379. * @param int $sessionId
  2380. *
  2381. * @return int
  2382. */
  2383. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2384. {
  2385. $lpId = (int) $lpId;
  2386. $userId = (int) $userId;
  2387. $courseId = (int) $courseId;
  2388. $sessionId = (int) $sessionId;
  2389. $sessionCondition = api_get_session_condition($sessionId);
  2390. $table = Database::get_course_table(TABLE_LP_VIEW);
  2391. $sql = "SELECT * FROM $table
  2392. WHERE
  2393. c_id = $courseId AND
  2394. lp_id = $lpId AND
  2395. user_id = $userId $sessionCondition ";
  2396. $res = Database::query($sql);
  2397. $progress = 0;
  2398. if (Database::num_rows($res) > 0) {
  2399. $row = Database:: fetch_array($res);
  2400. $progress = (int) $row['progress'];
  2401. }
  2402. return $progress;
  2403. }
  2404. /**
  2405. * Displays a progress bar
  2406. * completed so far.
  2407. *
  2408. * @param int $percentage Progress value to display
  2409. * @param string $text_add Text to display near the progress value
  2410. *
  2411. * @return string HTML string containing the progress bar
  2412. */
  2413. public static function get_progress_bar($percentage = -1, $text_add = '')
  2414. {
  2415. $text = $percentage.$text_add;
  2416. $output = '<div class="progress">
  2417. <div id="progress_bar_value"
  2418. class="progress-bar progress-bar-success" role="progressbar"
  2419. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2420. '.$text.'
  2421. </div>
  2422. </div>';
  2423. return $output;
  2424. }
  2425. /**
  2426. * @param string $mode can be '%' or 'abs'
  2427. * otherwise this value will be used $this->progress_bar_mode
  2428. *
  2429. * @return string
  2430. */
  2431. public function getProgressBar($mode = null)
  2432. {
  2433. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2434. return self::get_progress_bar($percentage, $text_add);
  2435. }
  2436. /**
  2437. * Gets the progress bar info to display inside the progress bar.
  2438. * Also used by scorm_api.php.
  2439. *
  2440. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2441. * we display a number of completed elements per total elements
  2442. * @param int $add Additional steps to fake as completed
  2443. *
  2444. * @return array Percentage or number and symbol (% or /xx)
  2445. */
  2446. public function get_progress_bar_text($mode = '', $add = 0)
  2447. {
  2448. if ($this->debug > 0) {
  2449. error_log('In learnpath::get_progress_bar_text()', 0);
  2450. }
  2451. if (empty($mode)) {
  2452. $mode = $this->progress_bar_mode;
  2453. }
  2454. $total_items = $this->getTotalItemsCountWithoutDirs();
  2455. if ($this->debug > 2) {
  2456. error_log('Total items available in this learnpath: '.$total_items, 0);
  2457. }
  2458. $completeItems = $this->get_complete_items_count();
  2459. if ($this->debug > 2) {
  2460. error_log('Items completed so far: '.$completeItems, 0);
  2461. }
  2462. if ($add != 0) {
  2463. $completeItems += $add;
  2464. if ($this->debug > 2) {
  2465. error_log('Items completed so far (+modifier): '.$completeItems, 0);
  2466. }
  2467. }
  2468. $text = '';
  2469. if ($completeItems > $total_items) {
  2470. $completeItems = $total_items;
  2471. }
  2472. $percentage = 0;
  2473. if ($mode == '%') {
  2474. if ($total_items > 0) {
  2475. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2476. } else {
  2477. $percentage = 0;
  2478. }
  2479. $percentage = number_format($percentage, 0);
  2480. $text = '%';
  2481. } elseif ($mode == 'abs') {
  2482. $percentage = $completeItems;
  2483. $text = '/'.$total_items;
  2484. }
  2485. return [
  2486. $percentage,
  2487. $text,
  2488. ];
  2489. }
  2490. /**
  2491. * Gets the progress bar mode.
  2492. *
  2493. * @return string The progress bar mode attribute
  2494. */
  2495. public function get_progress_bar_mode()
  2496. {
  2497. if ($this->debug > 0) {
  2498. error_log('In learnpath::get_progress_bar_mode()', 0);
  2499. }
  2500. if (!empty($this->progress_bar_mode)) {
  2501. return $this->progress_bar_mode;
  2502. } else {
  2503. return '%';
  2504. }
  2505. }
  2506. /**
  2507. * Gets the learnpath theme (remote or local).
  2508. *
  2509. * @return string Learnpath theme
  2510. */
  2511. public function get_theme()
  2512. {
  2513. if ($this->debug > 0) {
  2514. error_log('In learnpath::get_theme()', 0);
  2515. }
  2516. if (!empty($this->theme)) {
  2517. return $this->theme;
  2518. } else {
  2519. return '';
  2520. }
  2521. }
  2522. /**
  2523. * Gets the learnpath session id.
  2524. *
  2525. * @return int
  2526. */
  2527. public function get_lp_session_id()
  2528. {
  2529. if ($this->debug > 0) {
  2530. error_log('In learnpath::get_lp_session_id()', 0);
  2531. }
  2532. if (!empty($this->lp_session_id)) {
  2533. return (int) $this->lp_session_id;
  2534. } else {
  2535. return 0;
  2536. }
  2537. }
  2538. /**
  2539. * Gets the learnpath image.
  2540. *
  2541. * @return string Web URL of the LP image
  2542. */
  2543. public function get_preview_image()
  2544. {
  2545. if ($this->debug > 0) {
  2546. error_log('In learnpath::get_preview_image()', 0);
  2547. }
  2548. if (!empty($this->preview_image)) {
  2549. return $this->preview_image;
  2550. } else {
  2551. return '';
  2552. }
  2553. }
  2554. /**
  2555. * @param string $size
  2556. * @param string $path_type
  2557. *
  2558. * @return bool|string
  2559. */
  2560. public function get_preview_image_path($size = null, $path_type = 'web')
  2561. {
  2562. $preview_image = $this->get_preview_image();
  2563. if (isset($preview_image) && !empty($preview_image)) {
  2564. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2565. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2566. if (isset($size)) {
  2567. $info = pathinfo($preview_image);
  2568. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2569. if (file_exists($image_sys_path.$image_custom_size)) {
  2570. if ($path_type == 'web') {
  2571. return $image_path.$image_custom_size;
  2572. } else {
  2573. return $image_sys_path.$image_custom_size;
  2574. }
  2575. }
  2576. } else {
  2577. if ($path_type == 'web') {
  2578. return $image_path.$preview_image;
  2579. } else {
  2580. return $image_sys_path.$preview_image;
  2581. }
  2582. }
  2583. }
  2584. return false;
  2585. }
  2586. /**
  2587. * Gets the learnpath author.
  2588. *
  2589. * @return string LP's author
  2590. */
  2591. public function get_author()
  2592. {
  2593. if ($this->debug > 0) {
  2594. error_log('In learnpath::get_author()', 0);
  2595. }
  2596. if (!empty($this->author)) {
  2597. return $this->author;
  2598. } else {
  2599. return '';
  2600. }
  2601. }
  2602. /**
  2603. * Gets hide table of contents.
  2604. *
  2605. * @return int
  2606. */
  2607. public function getHideTableOfContents()
  2608. {
  2609. return (int) $this->hide_toc_frame;
  2610. }
  2611. /**
  2612. * Generate a new prerequisites string for a given item. If this item was a sco and
  2613. * its prerequisites were strings (instead of IDs), then transform those strings into
  2614. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2615. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2616. * same rule as the scormExport() method.
  2617. *
  2618. * @param int $item_id Item ID
  2619. *
  2620. * @return string Prerequisites string ready for the export as SCORM
  2621. */
  2622. public function get_scorm_prereq_string($item_id)
  2623. {
  2624. if ($this->debug > 0) {
  2625. error_log('In learnpath::get_scorm_prereq_string()');
  2626. }
  2627. if (!is_object($this->items[$item_id])) {
  2628. return false;
  2629. }
  2630. /** @var learnpathItem $oItem */
  2631. $oItem = $this->items[$item_id];
  2632. $prereq = $oItem->get_prereq_string();
  2633. if (empty($prereq)) {
  2634. return '';
  2635. }
  2636. if (preg_match('/^\d+$/', $prereq) &&
  2637. isset($this->items[$prereq]) &&
  2638. is_object($this->items[$prereq])
  2639. ) {
  2640. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2641. // then simply return it (with the ITEM_ prefix).
  2642. //return 'ITEM_' . $prereq;
  2643. return $this->items[$prereq]->ref;
  2644. } else {
  2645. if (isset($this->refs_list[$prereq])) {
  2646. // It's a simple string item from which the ID can be found in the refs list,
  2647. // so we can transform it directly to an ID for export.
  2648. return $this->items[$this->refs_list[$prereq]]->ref;
  2649. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2650. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2651. } else {
  2652. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2653. // and replace them, one by one, by the internal IDs (chamilo db)
  2654. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2655. // by a space as well.
  2656. $find = [
  2657. '&',
  2658. '|',
  2659. '~',
  2660. '=',
  2661. '<>',
  2662. '{',
  2663. '}',
  2664. '*',
  2665. '(',
  2666. ')',
  2667. ];
  2668. $replace = [
  2669. ' ',
  2670. ' ',
  2671. ' ',
  2672. ' ',
  2673. ' ',
  2674. ' ',
  2675. ' ',
  2676. ' ',
  2677. ' ',
  2678. ' ',
  2679. ];
  2680. $prereq_mod = str_replace($find, $replace, $prereq);
  2681. $ids = explode(' ', $prereq_mod);
  2682. foreach ($ids as $id) {
  2683. $id = trim($id);
  2684. if (isset($this->refs_list[$id])) {
  2685. $prereq = preg_replace(
  2686. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2687. 'ITEM_'.$this->refs_list[$id],
  2688. $prereq
  2689. );
  2690. }
  2691. }
  2692. return $prereq;
  2693. }
  2694. }
  2695. }
  2696. /**
  2697. * Returns the XML DOM document's node.
  2698. *
  2699. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2700. * @param string $id The identifier to look for
  2701. *
  2702. * @return mixed The reference to the element found with that identifier. False if not found
  2703. */
  2704. public function get_scorm_xml_node(&$children, $id)
  2705. {
  2706. for ($i = 0; $i < $children->length; $i++) {
  2707. $item_temp = $children->item($i);
  2708. if ($item_temp->nodeName == 'item') {
  2709. if ($item_temp->getAttribute('identifier') == $id) {
  2710. return $item_temp;
  2711. }
  2712. }
  2713. $subchildren = $item_temp->childNodes;
  2714. if ($subchildren && $subchildren->length > 0) {
  2715. $val = $this->get_scorm_xml_node($subchildren, $id);
  2716. if (is_object($val)) {
  2717. return $val;
  2718. }
  2719. }
  2720. }
  2721. return false;
  2722. }
  2723. /**
  2724. * Gets the status list for all LP's items.
  2725. *
  2726. * @return array Array of [index] => [item ID => current status]
  2727. */
  2728. public function get_items_status_list()
  2729. {
  2730. if ($this->debug > 0) {
  2731. error_log('In learnpath::get_items_status_list()', 0);
  2732. }
  2733. $list = [];
  2734. foreach ($this->ordered_items as $item_id) {
  2735. $list[] = [
  2736. $item_id => $this->items[$item_id]->get_status(),
  2737. ];
  2738. }
  2739. return $list;
  2740. }
  2741. /**
  2742. * Return the number of interactions for the given learnpath Item View ID.
  2743. * This method can be used as static.
  2744. *
  2745. * @param int $lp_iv_id Item View ID
  2746. * @param int $course_id course id
  2747. *
  2748. * @return int
  2749. */
  2750. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2751. {
  2752. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2753. $lp_iv_id = (int) $lp_iv_id;
  2754. $course_id = (int) $course_id;
  2755. $sql = "SELECT count(*) FROM $table
  2756. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2757. $res = Database::query($sql);
  2758. $num = 0;
  2759. if (Database::num_rows($res)) {
  2760. $row = Database::fetch_array($res);
  2761. $num = $row[0];
  2762. }
  2763. return $num;
  2764. }
  2765. /**
  2766. * Return the interactions as an array for the given lp_iv_id.
  2767. * This method can be used as static.
  2768. *
  2769. * @param int $lp_iv_id Learnpath Item View ID
  2770. *
  2771. * @return array
  2772. *
  2773. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2774. */
  2775. public static function get_iv_interactions_array($lp_iv_id)
  2776. {
  2777. $course_id = api_get_course_int_id();
  2778. $list = [];
  2779. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2780. if (empty($lp_iv_id)) {
  2781. return [];
  2782. }
  2783. $sql = "SELECT * FROM $table
  2784. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2785. ORDER BY order_id ASC";
  2786. $res = Database::query($sql);
  2787. $num = Database::num_rows($res);
  2788. if ($num > 0) {
  2789. $list[] = [
  2790. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2791. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2792. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2793. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2794. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2795. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2796. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2797. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2798. ];
  2799. while ($row = Database::fetch_array($res)) {
  2800. $list[] = [
  2801. 'order_id' => ($row['order_id'] + 1),
  2802. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2803. 'type' => $row['interaction_type'],
  2804. 'time' => $row['completion_time'],
  2805. //'correct_responses' => $row['correct_responses'],
  2806. 'correct_responses' => '', // Hide correct responses from students.
  2807. 'student_response' => $row['student_response'],
  2808. 'result' => $row['result'],
  2809. 'latency' => $row['latency'],
  2810. ];
  2811. }
  2812. }
  2813. return $list;
  2814. }
  2815. /**
  2816. * Return the number of objectives for the given learnpath Item View ID.
  2817. * This method can be used as static.
  2818. *
  2819. * @param int $lp_iv_id Item View ID
  2820. * @param int $course_id Course ID
  2821. *
  2822. * @return int Number of objectives
  2823. */
  2824. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2825. {
  2826. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2827. $course_id = (int) $course_id;
  2828. $lp_iv_id = (int) $lp_iv_id;
  2829. $sql = "SELECT count(*) FROM $table
  2830. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2831. //@todo seems that this always returns 0
  2832. $res = Database::query($sql);
  2833. $num = 0;
  2834. if (Database::num_rows($res)) {
  2835. $row = Database::fetch_array($res);
  2836. $num = $row[0];
  2837. }
  2838. return $num;
  2839. }
  2840. /**
  2841. * Return the objectives as an array for the given lp_iv_id.
  2842. * This method can be used as static.
  2843. *
  2844. * @param int $lpItemViewId Learnpath Item View ID
  2845. *
  2846. * @return array
  2847. *
  2848. * @todo Translate labels
  2849. */
  2850. public static function get_iv_objectives_array($lpItemViewId = 0)
  2851. {
  2852. $course_id = api_get_course_int_id();
  2853. $lpItemViewId = (int) $lpItemViewId;
  2854. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2855. $sql = "SELECT * FROM $table
  2856. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2857. ORDER BY order_id ASC";
  2858. $res = Database::query($sql);
  2859. $num = Database::num_rows($res);
  2860. $list = [];
  2861. if ($num > 0) {
  2862. $list[] = [
  2863. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2864. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2865. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2866. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2867. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2868. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2869. ];
  2870. while ($row = Database::fetch_array($res)) {
  2871. $list[] = [
  2872. 'order_id' => ($row['order_id'] + 1),
  2873. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2874. 'score_raw' => $row['score_raw'],
  2875. 'score_max' => $row['score_max'],
  2876. 'score_min' => $row['score_min'],
  2877. 'status' => $row['status'],
  2878. ];
  2879. }
  2880. }
  2881. return $list;
  2882. }
  2883. /**
  2884. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2885. * used by get_html_toc() to be ready to display.
  2886. *
  2887. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2888. */
  2889. public function get_toc()
  2890. {
  2891. if ($this->debug > 0) {
  2892. error_log('learnpath::get_toc()', 0);
  2893. }
  2894. $toc = [];
  2895. foreach ($this->ordered_items as $item_id) {
  2896. if ($this->debug > 2) {
  2897. error_log('learnpath::get_toc(): getting info for item '.$item_id, 0);
  2898. }
  2899. // TODO: Change this link generation and use new function instead.
  2900. $toc[] = [
  2901. 'id' => $item_id,
  2902. 'title' => $this->items[$item_id]->get_title(),
  2903. 'status' => $this->items[$item_id]->get_status(),
  2904. 'level' => $this->items[$item_id]->get_level(),
  2905. 'type' => $this->items[$item_id]->get_type(),
  2906. 'description' => $this->items[$item_id]->get_description(),
  2907. 'path' => $this->items[$item_id]->get_path(),
  2908. 'parent' => $this->items[$item_id]->get_parent(),
  2909. ];
  2910. }
  2911. if ($this->debug > 2) {
  2912. error_log('In learnpath::get_toc() - TOC array: '.print_r($toc, true), 0);
  2913. }
  2914. return $toc;
  2915. }
  2916. /**
  2917. * Generate and return the table of contents for this learnpath. The JS
  2918. * table returned is used inside of scorm_api.php.
  2919. *
  2920. * @param string $varname
  2921. *
  2922. * @return string A JS array variable construction
  2923. */
  2924. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2925. {
  2926. if ($this->debug > 0) {
  2927. error_log('In learnpath::get_items_details_as_js()', 0);
  2928. }
  2929. $toc = $varname.' = new Array();';
  2930. foreach ($this->ordered_items as $item_id) {
  2931. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2932. }
  2933. if ($this->debug > 2) {
  2934. error_log('In learnpath::get_items_details_as_js() - TOC array: '.print_r($toc, true), 0);
  2935. }
  2936. return $toc;
  2937. }
  2938. /**
  2939. * Gets the learning path type.
  2940. *
  2941. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2942. *
  2943. * @return mixed Type ID or name, depending on the parameter
  2944. */
  2945. public function get_type($get_name = false)
  2946. {
  2947. $res = false;
  2948. if ($this->debug > 0) {
  2949. error_log('In learnpath::get_type()', 0);
  2950. }
  2951. if (!empty($this->type) && (!$get_name)) {
  2952. $res = $this->type;
  2953. }
  2954. if ($this->debug > 2) {
  2955. error_log('In learnpath::get_type() - Returning '.($res ? $res : 'false'), 0);
  2956. }
  2957. return $res;
  2958. }
  2959. /**
  2960. * Gets the learning path type as static method.
  2961. *
  2962. * @param int $lp_id
  2963. *
  2964. * @return mixed Type ID or name, depending on the parameter
  2965. */
  2966. public static function get_type_static($lp_id = 0)
  2967. {
  2968. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2969. $lp_id = (int) $lp_id;
  2970. $sql = "SELECT lp_type FROM $tbl_lp
  2971. WHERE iid = $lp_id";
  2972. $res = Database::query($sql);
  2973. if ($res === false) {
  2974. return null;
  2975. }
  2976. if (Database::num_rows($res) <= 0) {
  2977. return null;
  2978. }
  2979. $row = Database::fetch_array($res);
  2980. return $row['lp_type'];
  2981. }
  2982. /**
  2983. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2984. * This method can be used as abstract and is recursive.
  2985. *
  2986. * @param int $lp Learnpath ID
  2987. * @param int $parent Parent ID of the items to look for
  2988. * @param int $course_id
  2989. *
  2990. * @return array Ordered list of item IDs (empty array on error)
  2991. */
  2992. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2993. {
  2994. if (empty($course_id)) {
  2995. $course_id = api_get_course_int_id();
  2996. } else {
  2997. $course_id = (int) $course_id;
  2998. }
  2999. $list = [];
  3000. if (empty($lp)) {
  3001. return $list;
  3002. }
  3003. $lp = (int) $lp;
  3004. $parent = (int) $parent;
  3005. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3006. $sql = "SELECT iid FROM $tbl_lp_item
  3007. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  3008. ORDER BY display_order";
  3009. $res = Database::query($sql);
  3010. while ($row = Database::fetch_array($res)) {
  3011. $sublist = self::get_flat_ordered_items_list(
  3012. $lp,
  3013. $row['iid'],
  3014. $course_id
  3015. );
  3016. $list[] = $row['iid'];
  3017. foreach ($sublist as $item) {
  3018. $list[] = $item;
  3019. }
  3020. }
  3021. return $list;
  3022. }
  3023. /**
  3024. * @return array
  3025. */
  3026. public static function getChapterTypes()
  3027. {
  3028. return [
  3029. 'dir',
  3030. ];
  3031. }
  3032. /**
  3033. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3034. *
  3035. * @param $tree
  3036. *
  3037. * @return array HTML TOC ready to display
  3038. */
  3039. public function getParentToc($tree)
  3040. {
  3041. if ($this->debug > 0) {
  3042. error_log('In learnpath::get_html_toc()', 0);
  3043. }
  3044. if (empty($tree)) {
  3045. $tree = $this->get_toc();
  3046. }
  3047. $dirTypes = self::getChapterTypes();
  3048. $myCurrentId = $this->get_current_item_id();
  3049. $listParent = [];
  3050. $listChildren = [];
  3051. $listNotParent = [];
  3052. $list = [];
  3053. foreach ($tree as $subtree) {
  3054. if (in_array($subtree['type'], $dirTypes)) {
  3055. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  3056. $subtree['children'] = $listChildren;
  3057. if (!empty($subtree['children'])) {
  3058. foreach ($subtree['children'] as $subItem) {
  3059. if ($subItem['id'] == $this->current) {
  3060. $subtree['parent_current'] = 'in';
  3061. $subtree['current'] = 'on';
  3062. }
  3063. }
  3064. }
  3065. $listParent[] = $subtree;
  3066. }
  3067. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  3068. $classStatus = [
  3069. 'not attempted' => 'scorm_not_attempted',
  3070. 'incomplete' => 'scorm_not_attempted',
  3071. 'failed' => 'scorm_failed',
  3072. 'completed' => 'scorm_completed',
  3073. 'passed' => 'scorm_completed',
  3074. 'succeeded' => 'scorm_completed',
  3075. 'browsed' => 'scorm_completed',
  3076. ];
  3077. if (isset($classStatus[$subtree['status']])) {
  3078. $cssStatus = $classStatus[$subtree['status']];
  3079. }
  3080. $title = Security::remove_XSS($subtree['title']);
  3081. unset($subtree['title']);
  3082. if (empty($title)) {
  3083. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3084. }
  3085. $classStyle = null;
  3086. if ($subtree['id'] == $this->current) {
  3087. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3088. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3089. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3090. }
  3091. $subtree['title'] = $title;
  3092. $subtree['class'] = $classStyle.' '.$cssStatus;
  3093. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3094. $subtree['current_id'] = $myCurrentId;
  3095. $listNotParent[] = $subtree;
  3096. }
  3097. }
  3098. $list['are_parents'] = $listParent;
  3099. $list['not_parents'] = $listNotParent;
  3100. return $list;
  3101. }
  3102. /**
  3103. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  3104. *
  3105. * @param array $tree
  3106. * @param int $id
  3107. * @param bool $parent
  3108. *
  3109. * @return array HTML TOC ready to display
  3110. */
  3111. public function getChildrenToc($tree, $id, $parent = true)
  3112. {
  3113. if ($this->debug > 0) {
  3114. error_log('In learnpath::get_html_toc()', 0);
  3115. }
  3116. if (empty($tree)) {
  3117. $tree = $this->get_toc();
  3118. }
  3119. $dirTypes = self::getChapterTypes();
  3120. $mycurrentitemid = $this->get_current_item_id();
  3121. $list = [];
  3122. $classStatus = [
  3123. 'not attempted' => 'scorm_not_attempted',
  3124. 'incomplete' => 'scorm_not_attempted',
  3125. 'failed' => 'scorm_failed',
  3126. 'completed' => 'scorm_completed',
  3127. 'passed' => 'scorm_completed',
  3128. 'succeeded' => 'scorm_completed',
  3129. 'browsed' => 'scorm_completed',
  3130. ];
  3131. foreach ($tree as $subtree) {
  3132. $subtree['tree'] = null;
  3133. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3134. if ($subtree['id'] == $this->current) {
  3135. $subtree['current'] = 'active';
  3136. } else {
  3137. $subtree['current'] = null;
  3138. }
  3139. if (isset($classStatus[$subtree['status']])) {
  3140. $cssStatus = $classStatus[$subtree['status']];
  3141. }
  3142. $title = Security::remove_XSS($subtree['title']);
  3143. unset($subtree['title']);
  3144. if (empty($title)) {
  3145. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3146. }
  3147. $classStyle = null;
  3148. if ($subtree['id'] == $this->current) {
  3149. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3150. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3151. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3152. }
  3153. if (in_array($subtree['type'], $dirTypes)) {
  3154. $subtree['title'] = stripslashes($title);
  3155. } else {
  3156. $subtree['title'] = $title;
  3157. $subtree['class'] = $classStyle.' '.$cssStatus;
  3158. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3159. $subtree['current_id'] = $mycurrentitemid;
  3160. }
  3161. $list[] = $subtree;
  3162. }
  3163. }
  3164. return $list;
  3165. }
  3166. /**
  3167. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3168. *
  3169. * @param array $toc_list
  3170. *
  3171. * @return array HTML TOC ready to display
  3172. */
  3173. public function getListArrayToc($toc_list = [])
  3174. {
  3175. if ($this->debug > 0) {
  3176. error_log('In learnpath::get_html_toc()', 0);
  3177. }
  3178. if (empty($toc_list)) {
  3179. $toc_list = $this->get_toc();
  3180. }
  3181. // Temporary variables.
  3182. $mycurrentitemid = $this->get_current_item_id();
  3183. $list = [];
  3184. $arrayList = [];
  3185. $classStatus = [
  3186. 'not attempted' => 'scorm_not_attempted',
  3187. 'incomplete' => 'scorm_not_attempted',
  3188. 'failed' => 'scorm_failed',
  3189. 'completed' => 'scorm_completed',
  3190. 'passed' => 'scorm_completed',
  3191. 'succeeded' => 'scorm_completed',
  3192. 'browsed' => 'scorm_completed',
  3193. ];
  3194. foreach ($toc_list as $item) {
  3195. $list['id'] = $item['id'];
  3196. $list['status'] = $item['status'];
  3197. $cssStatus = null;
  3198. if (isset($classStatus[$item['status']])) {
  3199. $cssStatus = $classStatus[$item['status']];
  3200. }
  3201. $classStyle = ' ';
  3202. $dirTypes = self::getChapterTypes();
  3203. if (in_array($item['type'], $dirTypes)) {
  3204. $classStyle = 'scorm_item_section ';
  3205. }
  3206. if ($item['id'] == $this->current) {
  3207. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3208. } elseif (!in_array($item['type'], $dirTypes)) {
  3209. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3210. }
  3211. $title = $item['title'];
  3212. if (empty($title)) {
  3213. $title = self::rl_get_resource_name(
  3214. api_get_course_id(),
  3215. $this->get_id(),
  3216. $item['id']
  3217. );
  3218. }
  3219. $title = Security::remove_XSS($item['title']);
  3220. if (empty($item['description'])) {
  3221. $list['description'] = $title;
  3222. } else {
  3223. $list['description'] = $item['description'];
  3224. }
  3225. $list['class'] = $classStyle.' '.$cssStatus;
  3226. $list['level'] = $item['level'];
  3227. $list['type'] = $item['type'];
  3228. if (in_array($item['type'], $dirTypes)) {
  3229. $list['css_level'] = 'level_'.$item['level'];
  3230. } else {
  3231. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3232. }
  3233. if (in_array($item['type'], $dirTypes)) {
  3234. $list['title'] = stripslashes($title);
  3235. } else {
  3236. $list['title'] = stripslashes($title);
  3237. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3238. $list['current_id'] = $mycurrentitemid;
  3239. }
  3240. $arrayList[] = $list;
  3241. }
  3242. return $arrayList;
  3243. }
  3244. /**
  3245. * Returns an HTML-formatted string ready to display with teacher buttons
  3246. * in LP view menu.
  3247. *
  3248. * @return string HTML TOC ready to display
  3249. */
  3250. public function get_teacher_toc_buttons()
  3251. {
  3252. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3253. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3254. $html = '';
  3255. if ($isAllow && $hideIcons == false) {
  3256. if ($this->get_lp_session_id() == api_get_session_id()) {
  3257. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3258. $html .= '<div class="btn-group">';
  3259. $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'>".
  3260. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3261. $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'>".
  3262. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3263. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3264. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3265. $html .= '</div>';
  3266. $html .= '</div>';
  3267. }
  3268. }
  3269. return $html;
  3270. }
  3271. /**
  3272. * Gets the learnpath maker name - generally the editor's name.
  3273. *
  3274. * @return string Learnpath maker name
  3275. */
  3276. public function get_maker()
  3277. {
  3278. if ($this->debug > 0) {
  3279. error_log('In learnpath::get_maker()', 0);
  3280. }
  3281. if (!empty($this->maker)) {
  3282. return $this->maker;
  3283. } else {
  3284. return '';
  3285. }
  3286. }
  3287. /**
  3288. * Gets the learnpath name/title.
  3289. *
  3290. * @return string Learnpath name/title
  3291. */
  3292. public function get_name()
  3293. {
  3294. if ($this->debug > 0) {
  3295. error_log('In learnpath::get_name()', 0);
  3296. }
  3297. if (!empty($this->name)) {
  3298. return $this->name;
  3299. } else {
  3300. return 'N/A';
  3301. }
  3302. }
  3303. /**
  3304. * Gets a link to the resource from the present location, depending on item ID.
  3305. *
  3306. * @param string $type Type of link expected
  3307. * @param int $item_id Learnpath item ID
  3308. * @param bool $provided_toc
  3309. *
  3310. * @return string $provided_toc Link to the lp_item resource
  3311. */
  3312. public function get_link($type = 'http', $item_id = null, $provided_toc = false)
  3313. {
  3314. $course_id = $this->get_course_int_id();
  3315. if ($this->debug > 0) {
  3316. error_log('In learnpath::get_link('.$type.','.$item_id.')', 0);
  3317. }
  3318. if (empty($item_id)) {
  3319. if ($this->debug > 2) {
  3320. error_log('In learnpath::get_link() - no item id given in learnpath::get_link()');
  3321. error_log('using current: '.$this->get_current_item_id(), 0);
  3322. }
  3323. $item_id = $this->get_current_item_id();
  3324. if (empty($item_id)) {
  3325. if ($this->debug > 2) {
  3326. error_log('In learnpath::get_link() - no current item id found in learnpath object', 0);
  3327. }
  3328. //still empty, this means there was no item_id given and we are not in an object context or
  3329. //the object property is empty, return empty link
  3330. $this->first();
  3331. return '';
  3332. }
  3333. }
  3334. $file = '';
  3335. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3336. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3337. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3338. $item_id = (int) $item_id;
  3339. $sql = "SELECT
  3340. l.lp_type as ltype,
  3341. l.path as lpath,
  3342. li.item_type as litype,
  3343. li.path as lipath,
  3344. li.parameters as liparams
  3345. FROM $lp_table l
  3346. INNER JOIN $lp_item_table li
  3347. ON (li.lp_id = l.iid)
  3348. WHERE
  3349. li.iid = $item_id
  3350. ";
  3351. if ($this->debug > 2) {
  3352. error_log('In learnpath::get_link() - selecting item '.$sql, 0);
  3353. }
  3354. $res = Database::query($sql);
  3355. if (Database::num_rows($res) > 0) {
  3356. $row = Database::fetch_array($res);
  3357. $lp_type = $row['ltype'];
  3358. $lp_path = $row['lpath'];
  3359. $lp_item_type = $row['litype'];
  3360. $lp_item_path = $row['lipath'];
  3361. $lp_item_params = $row['liparams'];
  3362. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3363. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3364. }
  3365. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3366. if ($type === 'http') {
  3367. //web path
  3368. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3369. } else {
  3370. $course_path = $sys_course_path; //system path
  3371. }
  3372. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3373. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3374. if (in_array(
  3375. $lp_item_type,
  3376. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3377. )
  3378. ) {
  3379. $lp_type = 1;
  3380. }
  3381. if ($this->debug > 2) {
  3382. error_log('In learnpath::get_link() - $lp_type '.$lp_type, 0);
  3383. error_log('In learnpath::get_link() - $lp_item_type '.$lp_item_type, 0);
  3384. }
  3385. // Now go through the specific cases to get the end of the path
  3386. // @todo Use constants instead of int values.
  3387. switch ($lp_type) {
  3388. case 1:
  3389. $file = self::rl_get_resource_link_for_learnpath(
  3390. $course_id,
  3391. $this->get_id(),
  3392. $item_id,
  3393. $this->get_view_id()
  3394. );
  3395. if ($this->debug > 0) {
  3396. error_log('rl_get_resource_link_for_learnpath - file: '.$file, 0);
  3397. }
  3398. switch ($lp_item_type) {
  3399. case 'document':
  3400. // Shows a button to download the file instead of just downloading the file directly.
  3401. $documentPathInfo = pathinfo($file);
  3402. if (isset($documentPathInfo['extension'])) {
  3403. $parsed = parse_url($documentPathInfo['extension']);
  3404. if (isset($parsed['path'])) {
  3405. $extension = $parsed['path'];
  3406. $extensionsToDownload = [
  3407. 'zip',
  3408. 'ppt',
  3409. 'pptx',
  3410. 'ods',
  3411. 'xlsx',
  3412. 'xls',
  3413. 'csv',
  3414. 'doc',
  3415. 'docx',
  3416. 'dot',
  3417. ];
  3418. if (in_array($extension, $extensionsToDownload)) {
  3419. $file = api_get_path(WEB_CODE_PATH).
  3420. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3421. }
  3422. }
  3423. }
  3424. break;
  3425. case 'dir':
  3426. $file = 'lp_content.php?type=dir';
  3427. break;
  3428. case 'link':
  3429. if (Link::is_youtube_link($file)) {
  3430. $src = Link::get_youtube_video_id($file);
  3431. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3432. } elseif (Link::isVimeoLink($file)) {
  3433. $src = Link::getVimeoLinkId($file);
  3434. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3435. } else {
  3436. // If the current site is HTTPS and the link is
  3437. // HTTP, browsers will refuse opening the link
  3438. $urlId = api_get_current_access_url_id();
  3439. $url = api_get_access_url($urlId, false);
  3440. $protocol = substr($url['url'], 0, 5);
  3441. if ($protocol === 'https') {
  3442. $linkProtocol = substr($file, 0, 5);
  3443. if ($linkProtocol === 'http:') {
  3444. //this is the special intervention case
  3445. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3446. }
  3447. }
  3448. }
  3449. break;
  3450. case 'quiz':
  3451. // Check how much attempts of a exercise exits in lp
  3452. $lp_item_id = $this->get_current_item_id();
  3453. $lp_view_id = $this->get_view_id();
  3454. $prevent_reinit = null;
  3455. if (isset($this->items[$this->current])) {
  3456. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3457. }
  3458. if (empty($provided_toc)) {
  3459. if ($this->debug > 0) {
  3460. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3461. }
  3462. $list = $this->get_toc();
  3463. } else {
  3464. if ($this->debug > 0) {
  3465. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3466. }
  3467. $list = $provided_toc;
  3468. }
  3469. $type_quiz = false;
  3470. foreach ($list as $toc) {
  3471. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3472. $type_quiz = true;
  3473. }
  3474. }
  3475. if ($type_quiz) {
  3476. $lp_item_id = (int) $lp_item_id;
  3477. $lp_view_id = (int) $lp_view_id;
  3478. $sql = "SELECT count(*) FROM $lp_item_view_table
  3479. WHERE
  3480. c_id = $course_id AND
  3481. lp_item_id='".$lp_item_id."' AND
  3482. lp_view_id ='".$lp_view_id."' AND
  3483. status='completed'";
  3484. $result = Database::query($sql);
  3485. $row_count = Database:: fetch_row($result);
  3486. $count_item_view = (int) $row_count[0];
  3487. $not_multiple_attempt = 0;
  3488. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3489. $not_multiple_attempt = 1;
  3490. }
  3491. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3492. }
  3493. break;
  3494. }
  3495. $tmp_array = explode('/', $file);
  3496. $document_name = $tmp_array[count($tmp_array) - 1];
  3497. if (strpos($document_name, '_DELETED_')) {
  3498. $file = 'blank.php?error=document_deleted';
  3499. }
  3500. break;
  3501. case 2:
  3502. if ($this->debug > 2) {
  3503. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3504. }
  3505. if ($lp_item_type != 'dir') {
  3506. // Quite complex here:
  3507. // We want to make sure 'http://' (and similar) links can
  3508. // be loaded as is (withouth the Chamilo path in front) but
  3509. // some contents use this form: resource.htm?resource=http://blablabla
  3510. // which means we have to find a protocol at the path's start, otherwise
  3511. // it should not be considered as an external URL.
  3512. // if ($this->prerequisites_match($item_id)) {
  3513. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3514. if ($this->debug > 2) {
  3515. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3516. }
  3517. // Distant url, return as is.
  3518. $file = $lp_item_path;
  3519. } else {
  3520. if ($this->debug > 2) {
  3521. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3522. }
  3523. // Prevent getting untranslatable urls.
  3524. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3525. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3526. // Prepare the path.
  3527. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3528. // TODO: Fix this for urls with protocol header.
  3529. $file = str_replace('//', '/', $file);
  3530. $file = str_replace(':/', '://', $file);
  3531. if (substr($lp_path, -1) == '/') {
  3532. $lp_path = substr($lp_path, 0, -1);
  3533. }
  3534. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3535. // if file not found.
  3536. $decoded = html_entity_decode($lp_item_path);
  3537. list($decoded) = explode('?', $decoded);
  3538. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3539. $file = self::rl_get_resource_link_for_learnpath(
  3540. $course_id,
  3541. $this->get_id(),
  3542. $item_id,
  3543. $this->get_view_id()
  3544. );
  3545. if (empty($file)) {
  3546. $file = 'blank.php?error=document_not_found';
  3547. } else {
  3548. $tmp_array = explode('/', $file);
  3549. $document_name = $tmp_array[count($tmp_array) - 1];
  3550. if (strpos($document_name, '_DELETED_')) {
  3551. $file = 'blank.php?error=document_deleted';
  3552. } else {
  3553. $file = 'blank.php?error=document_not_found';
  3554. }
  3555. }
  3556. } else {
  3557. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3558. }
  3559. }
  3560. }
  3561. // We want to use parameters if they were defined in the imsmanifest
  3562. if (strpos($file, 'blank.php') === false) {
  3563. $lp_item_params = ltrim($lp_item_params, '?');
  3564. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3565. }
  3566. } else {
  3567. $file = 'lp_content.php?type=dir';
  3568. }
  3569. break;
  3570. case 3:
  3571. if ($this->debug > 2) {
  3572. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3573. }
  3574. // Formatting AICC HACP append URL.
  3575. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3576. if (!empty($lp_item_params)) {
  3577. $aicc_append .= $lp_item_params.'&';
  3578. }
  3579. if ($lp_item_type != 'dir') {
  3580. // Quite complex here:
  3581. // We want to make sure 'http://' (and similar) links can
  3582. // be loaded as is (withouth the Chamilo path in front) but
  3583. // some contents use this form: resource.htm?resource=http://blablabla
  3584. // which means we have to find a protocol at the path's start, otherwise
  3585. // it should not be considered as an external URL.
  3586. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3587. if ($this->debug > 2) {
  3588. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3589. }
  3590. // Distant url, return as is.
  3591. $file = $lp_item_path;
  3592. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3593. /*
  3594. if (stristr($file,'<servername>') !== false) {
  3595. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3596. }
  3597. */
  3598. if (stripos($file, '<servername>') !== false) {
  3599. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3600. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3601. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3602. }
  3603. $file .= $aicc_append;
  3604. } else {
  3605. if ($this->debug > 2) {
  3606. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3607. }
  3608. // Prevent getting untranslatable urls.
  3609. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3610. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3611. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3612. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3613. // TODO: Fix this for urls with protocol header.
  3614. $file = str_replace('//', '/', $file);
  3615. $file = str_replace(':/', '://', $file);
  3616. $file .= $aicc_append;
  3617. }
  3618. } else {
  3619. $file = 'lp_content.php?type=dir';
  3620. }
  3621. break;
  3622. case 4:
  3623. break;
  3624. default:
  3625. break;
  3626. }
  3627. // Replace &amp; by & because &amp; will break URL with params
  3628. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3629. }
  3630. if ($this->debug > 2) {
  3631. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3632. }
  3633. return $file;
  3634. }
  3635. /**
  3636. * Gets the latest usable view or generate a new one.
  3637. *
  3638. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3639. *
  3640. * @return int DB lp_view id
  3641. */
  3642. public function get_view($attempt_num = 0)
  3643. {
  3644. if ($this->debug > 0) {
  3645. error_log('In learnpath::get_view()', 0);
  3646. }
  3647. $search = '';
  3648. // Use $attempt_num to enable multi-views management (disabled so far).
  3649. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3650. $search = 'AND view_count = '.$attempt_num;
  3651. }
  3652. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3653. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3654. $course_id = api_get_course_int_id();
  3655. $sessionId = api_get_session_id();
  3656. $sql = "SELECT iid, view_count FROM $lp_view_table
  3657. WHERE
  3658. c_id = $course_id AND
  3659. lp_id = ".$this->get_id()." AND
  3660. user_id = ".$this->get_user_id()." AND
  3661. session_id = $sessionId
  3662. $search
  3663. ORDER BY view_count DESC";
  3664. $res = Database::query($sql);
  3665. if (Database::num_rows($res) > 0) {
  3666. $row = Database::fetch_array($res);
  3667. $this->lp_view_id = $row['iid'];
  3668. } elseif (!api_is_invitee()) {
  3669. // There is no database record, create one.
  3670. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3671. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3672. Database::query($sql);
  3673. $id = Database::insert_id();
  3674. $this->lp_view_id = $id;
  3675. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3676. Database::query($sql);
  3677. }
  3678. return $this->lp_view_id;
  3679. }
  3680. /**
  3681. * Gets the current view id.
  3682. *
  3683. * @return int View ID (from lp_view)
  3684. */
  3685. public function get_view_id()
  3686. {
  3687. if ($this->debug > 0) {
  3688. error_log('In learnpath::get_view_id()', 0);
  3689. }
  3690. if (!empty($this->lp_view_id)) {
  3691. return $this->lp_view_id;
  3692. } else {
  3693. return 0;
  3694. }
  3695. }
  3696. /**
  3697. * Gets the update queue.
  3698. *
  3699. * @return array Array containing IDs of items to be updated by JavaScript
  3700. */
  3701. public function get_update_queue()
  3702. {
  3703. if ($this->debug > 0) {
  3704. error_log('In learnpath::get_update_queue()', 0);
  3705. }
  3706. return $this->update_queue;
  3707. }
  3708. /**
  3709. * Gets the user ID.
  3710. *
  3711. * @return int User ID
  3712. */
  3713. public function get_user_id()
  3714. {
  3715. if ($this->debug > 0) {
  3716. error_log('In learnpath::get_user_id()', 0);
  3717. }
  3718. if (!empty($this->user_id)) {
  3719. return $this->user_id;
  3720. } else {
  3721. return false;
  3722. }
  3723. }
  3724. /**
  3725. * Checks if any of the items has an audio element attached.
  3726. *
  3727. * @return bool True or false
  3728. */
  3729. public function has_audio()
  3730. {
  3731. if ($this->debug > 1) {
  3732. error_log('In learnpath::has_audio()', 0);
  3733. }
  3734. $has = false;
  3735. foreach ($this->items as $i => $item) {
  3736. if (!empty($this->items[$i]->audio)) {
  3737. $has = true;
  3738. break;
  3739. }
  3740. }
  3741. return $has;
  3742. }
  3743. /**
  3744. * Moves an item up and down at its level.
  3745. *
  3746. * @param int $id Item to move up and down
  3747. * @param string $direction Direction 'up' or 'down'
  3748. *
  3749. * @return bool|int
  3750. */
  3751. public function move_item($id, $direction)
  3752. {
  3753. $course_id = api_get_course_int_id();
  3754. if ($this->debug > 0) {
  3755. error_log('In learnpath::move_item('.$id.','.$direction.')', 0);
  3756. }
  3757. if (empty($id) || empty($direction)) {
  3758. return false;
  3759. }
  3760. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3761. $sql_sel = "SELECT *
  3762. FROM $tbl_lp_item
  3763. WHERE
  3764. iid = $id
  3765. ";
  3766. $res_sel = Database::query($sql_sel);
  3767. // Check if elem exists.
  3768. if (Database::num_rows($res_sel) < 1) {
  3769. return false;
  3770. }
  3771. // Gather data.
  3772. $row = Database::fetch_array($res_sel);
  3773. $previous = $row['previous_item_id'];
  3774. $next = $row['next_item_id'];
  3775. $display = $row['display_order'];
  3776. $parent = $row['parent_item_id'];
  3777. $lp = $row['lp_id'];
  3778. // Update the item (switch with previous/next one).
  3779. switch ($direction) {
  3780. case 'up':
  3781. if ($this->debug > 2) {
  3782. error_log('Movement up detected', 0);
  3783. }
  3784. if ($display > 1) {
  3785. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3786. WHERE iid = $previous";
  3787. if ($this->debug > 2) {
  3788. error_log('Selecting previous: '.$sql_sel2, 0);
  3789. }
  3790. $res_sel2 = Database::query($sql_sel2);
  3791. if (Database::num_rows($res_sel2) < 1) {
  3792. $previous_previous = 0;
  3793. }
  3794. // Gather data.
  3795. $row2 = Database::fetch_array($res_sel2);
  3796. $previous_previous = $row2['previous_item_id'];
  3797. // Update previous_previous item (switch "next" with current).
  3798. if ($previous_previous != 0) {
  3799. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3800. next_item_id = $id
  3801. WHERE iid = $previous_previous";
  3802. if ($this->debug > 2) {
  3803. error_log($sql_upd2, 0);
  3804. }
  3805. Database::query($sql_upd2);
  3806. }
  3807. // Update previous item (switch with current).
  3808. if ($previous != 0) {
  3809. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3810. next_item_id = $next,
  3811. previous_item_id = $id,
  3812. display_order = display_order +1
  3813. WHERE iid = $previous";
  3814. if ($this->debug > 2) {
  3815. error_log($sql_upd2, 0);
  3816. }
  3817. Database::query($sql_upd2);
  3818. }
  3819. // Update current item (switch with previous).
  3820. if ($id != 0) {
  3821. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3822. next_item_id = $previous,
  3823. previous_item_id = $previous_previous,
  3824. display_order = display_order-1
  3825. WHERE c_id = ".$course_id." AND id = $id";
  3826. if ($this->debug > 2) {
  3827. error_log($sql_upd2, 0);
  3828. }
  3829. Database::query($sql_upd2);
  3830. }
  3831. // Update next item (new previous item).
  3832. if (!empty($next)) {
  3833. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3834. WHERE iid = $next";
  3835. if ($this->debug > 2) {
  3836. error_log($sql_upd2, 0);
  3837. }
  3838. Database::query($sql_upd2);
  3839. }
  3840. $display = $display - 1;
  3841. }
  3842. break;
  3843. case 'down':
  3844. if ($this->debug > 2) {
  3845. error_log('Movement down detected', 0);
  3846. }
  3847. if ($next != 0) {
  3848. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3849. WHERE iid = $next";
  3850. if ($this->debug > 2) {
  3851. error_log('Selecting next: '.$sql_sel2, 0);
  3852. }
  3853. $res_sel2 = Database::query($sql_sel2);
  3854. if (Database::num_rows($res_sel2) < 1) {
  3855. $next_next = 0;
  3856. }
  3857. // Gather data.
  3858. $row2 = Database::fetch_array($res_sel2);
  3859. $next_next = $row2['next_item_id'];
  3860. // Update previous item (switch with current).
  3861. if ($previous != 0) {
  3862. $sql_upd2 = "UPDATE $tbl_lp_item
  3863. SET next_item_id = $next
  3864. WHERE iid = $previous";
  3865. Database::query($sql_upd2);
  3866. }
  3867. // Update current item (switch with previous).
  3868. if ($id != 0) {
  3869. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3870. previous_item_id = $next,
  3871. next_item_id = $next_next,
  3872. display_order = display_order + 1
  3873. WHERE iid = $id";
  3874. Database::query($sql_upd2);
  3875. }
  3876. // Update next item (new previous item).
  3877. if ($next != 0) {
  3878. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3879. previous_item_id = $previous,
  3880. next_item_id = $id,
  3881. display_order = display_order-1
  3882. WHERE iid = $next";
  3883. Database::query($sql_upd2);
  3884. }
  3885. // Update next_next item (switch "previous" with current).
  3886. if ($next_next != 0) {
  3887. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3888. previous_item_id = $id
  3889. WHERE iid = $next_next";
  3890. Database::query($sql_upd2);
  3891. }
  3892. $display = $display + 1;
  3893. }
  3894. break;
  3895. default:
  3896. return false;
  3897. }
  3898. return $display;
  3899. }
  3900. /**
  3901. * Move a LP up (display_order).
  3902. *
  3903. * @param int $lp_id Learnpath ID
  3904. * @param int $categoryId Category ID
  3905. *
  3906. * @return bool
  3907. */
  3908. public static function move_up($lp_id, $categoryId = 0)
  3909. {
  3910. $courseId = api_get_course_int_id();
  3911. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3912. $categoryCondition = '';
  3913. if (!empty($categoryId)) {
  3914. $categoryId = (int) $categoryId;
  3915. $categoryCondition = " AND category_id = $categoryId";
  3916. }
  3917. $sql = "SELECT * FROM $lp_table
  3918. WHERE c_id = $courseId
  3919. $categoryCondition
  3920. ORDER BY display_order";
  3921. $res = Database::query($sql);
  3922. if ($res === false) {
  3923. return false;
  3924. }
  3925. $lps = [];
  3926. $lp_order = [];
  3927. $num = Database::num_rows($res);
  3928. // First check the order is correct, globally (might be wrong because
  3929. // of versions < 1.8.4)
  3930. if ($num > 0) {
  3931. $i = 1;
  3932. while ($row = Database::fetch_array($res)) {
  3933. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3934. $sql = "UPDATE $lp_table SET display_order = $i
  3935. WHERE iid = ".$row['iid'];
  3936. Database::query($sql);
  3937. }
  3938. $row['display_order'] = $i;
  3939. $lps[$row['iid']] = $row;
  3940. $lp_order[$i] = $row['iid'];
  3941. $i++;
  3942. }
  3943. }
  3944. if ($num > 1) { // If there's only one element, no need to sort.
  3945. $order = $lps[$lp_id]['display_order'];
  3946. if ($order > 1) { // If it's the first element, no need to move up.
  3947. $sql = "UPDATE $lp_table SET display_order = $order
  3948. WHERE iid = ".$lp_order[$order - 1];
  3949. Database::query($sql);
  3950. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3951. WHERE iid = $lp_id";
  3952. Database::query($sql);
  3953. }
  3954. }
  3955. return true;
  3956. }
  3957. /**
  3958. * Move a learnpath down (display_order).
  3959. *
  3960. * @param int $lp_id Learnpath ID
  3961. * @param int $categoryId Category ID
  3962. *
  3963. * @return bool
  3964. */
  3965. public static function move_down($lp_id, $categoryId = 0)
  3966. {
  3967. $courseId = api_get_course_int_id();
  3968. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3969. $categoryCondition = '';
  3970. if (!empty($categoryId)) {
  3971. $categoryId = (int) $categoryId;
  3972. $categoryCondition = " AND category_id = $categoryId";
  3973. }
  3974. $sql = "SELECT * FROM $lp_table
  3975. WHERE c_id = $courseId
  3976. $categoryCondition
  3977. ORDER BY display_order";
  3978. $res = Database::query($sql);
  3979. if ($res === false) {
  3980. return false;
  3981. }
  3982. $lps = [];
  3983. $lp_order = [];
  3984. $num = Database::num_rows($res);
  3985. $max = 0;
  3986. // First check the order is correct, globally (might be wrong because
  3987. // of versions < 1.8.4).
  3988. if ($num > 0) {
  3989. $i = 1;
  3990. while ($row = Database::fetch_array($res)) {
  3991. $max = $i;
  3992. if ($row['display_order'] != $i) {
  3993. // If we find a gap in the order, we need to fix it.
  3994. $sql = "UPDATE $lp_table SET display_order = $i
  3995. WHERE iid = ".$row['iid'];
  3996. Database::query($sql);
  3997. }
  3998. $row['display_order'] = $i;
  3999. $lps[$row['iid']] = $row;
  4000. $lp_order[$i] = $row['iid'];
  4001. $i++;
  4002. }
  4003. }
  4004. if ($num > 1) { // If there's only one element, no need to sort.
  4005. $order = $lps[$lp_id]['display_order'];
  4006. if ($order < $max) { // If it's the first element, no need to move up.
  4007. $sql = "UPDATE $lp_table SET display_order = $order
  4008. WHERE iid = ".$lp_order[$order + 1];
  4009. Database::query($sql);
  4010. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  4011. WHERE iid = $lp_id";
  4012. Database::query($sql);
  4013. }
  4014. }
  4015. return true;
  4016. }
  4017. /**
  4018. * Updates learnpath attributes to point to the next element
  4019. * The last part is similar to set_current_item but processing the other way around.
  4020. */
  4021. public function next()
  4022. {
  4023. if ($this->debug > 0) {
  4024. error_log('In learnpath::next()', 0);
  4025. }
  4026. $this->last = $this->get_current_item_id();
  4027. $this->items[$this->last]->save(
  4028. false,
  4029. $this->prerequisites_match($this->last)
  4030. );
  4031. $this->autocomplete_parents($this->last);
  4032. $new_index = $this->get_next_index();
  4033. if ($this->debug > 2) {
  4034. error_log('New index: '.$new_index, 0);
  4035. }
  4036. $this->index = $new_index;
  4037. if ($this->debug > 2) {
  4038. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  4039. }
  4040. $this->current = $this->ordered_items[$new_index];
  4041. if ($this->debug > 2) {
  4042. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  4043. }
  4044. }
  4045. /**
  4046. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  4047. * class, this might be redefined to allow several behaviours depending on the document type.
  4048. *
  4049. * @param int $id Resource ID
  4050. */
  4051. public function open($id)
  4052. {
  4053. if ($this->debug > 0) {
  4054. error_log('In learnpath::open()', 0);
  4055. }
  4056. // TODO:
  4057. // set the current resource attribute to this resource
  4058. // switch on element type (redefine in child class?)
  4059. // set status for this item to "opened"
  4060. // start timer
  4061. // initialise score
  4062. $this->index = 0; //or = the last item seen (see $this->last)
  4063. }
  4064. /**
  4065. * Check that all prerequisites are fulfilled. Returns true and an
  4066. * empty string on success, returns false
  4067. * and the prerequisite string on error.
  4068. * This function is based on the rules for aicc_script language as
  4069. * described in the SCORM 1.2 CAM documentation page 108.
  4070. *
  4071. * @param int $itemId Optional item ID. If none given, uses the current open item.
  4072. *
  4073. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  4074. * string otherwise
  4075. */
  4076. public function prerequisites_match($itemId = null)
  4077. {
  4078. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  4079. if ($allow) {
  4080. if (api_is_allowed_to_edit() ||
  4081. api_is_platform_admin(true) ||
  4082. api_is_drh() ||
  4083. api_is_coach(api_get_session_id(), api_get_course_int_id())
  4084. ) {
  4085. return true;
  4086. }
  4087. }
  4088. $debug = $this->debug;
  4089. if ($debug > 0) {
  4090. error_log('In learnpath::prerequisites_match()', 0);
  4091. }
  4092. if (empty($itemId)) {
  4093. $itemId = $this->current;
  4094. }
  4095. $currentItem = $this->getItem($itemId);
  4096. if ($currentItem) {
  4097. if ($this->type == 2) {
  4098. // Getting prereq from scorm
  4099. $prereq_string = $this->get_scorm_prereq_string($itemId);
  4100. } else {
  4101. $prereq_string = $currentItem->get_prereq_string();
  4102. }
  4103. if (empty($prereq_string)) {
  4104. if ($debug > 0) {
  4105. error_log('Found prereq_string is empty return true');
  4106. }
  4107. return true;
  4108. }
  4109. // Clean spaces.
  4110. $prereq_string = str_replace(' ', '', $prereq_string);
  4111. if ($debug > 0) {
  4112. error_log('Found prereq_string: '.$prereq_string, 0);
  4113. }
  4114. // Now send to the parse_prereq() function that will check this component's prerequisites.
  4115. $result = $currentItem->parse_prereq(
  4116. $prereq_string,
  4117. $this->items,
  4118. $this->refs_list,
  4119. $this->get_user_id()
  4120. );
  4121. if ($result === false) {
  4122. $this->set_error_msg($currentItem->prereq_alert);
  4123. }
  4124. } else {
  4125. $result = true;
  4126. if ($debug > 1) {
  4127. error_log('$this->items['.$itemId.'] was not an object', 0);
  4128. }
  4129. }
  4130. if ($debug > 1) {
  4131. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  4132. }
  4133. return $result;
  4134. }
  4135. /**
  4136. * Updates learnpath attributes to point to the previous element
  4137. * The last part is similar to set_current_item but processing the other way around.
  4138. */
  4139. public function previous()
  4140. {
  4141. if ($this->debug > 0) {
  4142. error_log('In learnpath::previous()', 0);
  4143. }
  4144. $this->last = $this->get_current_item_id();
  4145. $this->items[$this->last]->save(
  4146. false,
  4147. $this->prerequisites_match($this->last)
  4148. );
  4149. $this->autocomplete_parents($this->last);
  4150. $new_index = $this->get_previous_index();
  4151. $this->index = $new_index;
  4152. $this->current = $this->ordered_items[$new_index];
  4153. }
  4154. /**
  4155. * Publishes a learnpath. This basically means show or hide the learnpath
  4156. * to normal users.
  4157. * Can be used as abstract.
  4158. *
  4159. * @param int $lp_id Learnpath ID
  4160. * @param int $set_visibility New visibility
  4161. *
  4162. * @return bool
  4163. */
  4164. public static function toggle_visibility($lp_id, $set_visibility = 1)
  4165. {
  4166. $action = 'visible';
  4167. if ($set_visibility != 1) {
  4168. $action = 'invisible';
  4169. self::toggle_publish($lp_id, 'i');
  4170. }
  4171. return api_item_property_update(
  4172. api_get_course_info(),
  4173. TOOL_LEARNPATH,
  4174. $lp_id,
  4175. $action,
  4176. api_get_user_id()
  4177. );
  4178. }
  4179. /**
  4180. * Publishes a learnpath category.
  4181. * This basically means show or hide the learnpath category to normal users.
  4182. *
  4183. * @param int $id
  4184. * @param int $visibility
  4185. *
  4186. * @throws \Doctrine\ORM\NonUniqueResultException
  4187. * @throws \Doctrine\ORM\ORMException
  4188. * @throws \Doctrine\ORM\OptimisticLockException
  4189. * @throws \Doctrine\ORM\TransactionRequiredException
  4190. *
  4191. * @return bool
  4192. */
  4193. public static function toggleCategoryVisibility($id, $visibility = 1)
  4194. {
  4195. $action = 'visible';
  4196. if ($visibility != 1) {
  4197. $action = 'invisible';
  4198. $list = new LearnpathList(
  4199. api_get_user_id(),
  4200. null,
  4201. null,
  4202. null,
  4203. false,
  4204. $id
  4205. );
  4206. $lpList = $list->get_flat_list();
  4207. foreach ($lpList as $lp) {
  4208. self::toggle_visibility($lp['iid'], 0);
  4209. }
  4210. self::toggleCategoryPublish($id, 0);
  4211. }
  4212. return api_item_property_update(
  4213. api_get_course_info(),
  4214. TOOL_LEARNPATH_CATEGORY,
  4215. $id,
  4216. $action,
  4217. api_get_user_id()
  4218. );
  4219. }
  4220. /**
  4221. * Publishes a learnpath. This basically means show or hide the learnpath
  4222. * on the course homepage
  4223. * Can be used as abstract.
  4224. *
  4225. * @param int $lp_id Learnpath id
  4226. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4227. *
  4228. * @return bool
  4229. */
  4230. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4231. {
  4232. $course_id = api_get_course_int_id();
  4233. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4234. $lp_id = (int) $lp_id;
  4235. $sql = "SELECT * FROM $tbl_lp
  4236. WHERE iid = $lp_id";
  4237. $result = Database::query($sql);
  4238. if (Database::num_rows($result)) {
  4239. $row = Database::fetch_array($result);
  4240. $name = Database::escape_string($row['name']);
  4241. if ($set_visibility == 'i') {
  4242. $v = 0;
  4243. }
  4244. if ($set_visibility == 'v') {
  4245. $v = 1;
  4246. }
  4247. $session_id = api_get_session_id();
  4248. $session_condition = api_get_session_condition($session_id);
  4249. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4250. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4251. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4252. $sql = "SELECT * FROM $tbl_tool
  4253. WHERE
  4254. c_id = $course_id AND
  4255. (link = '$link' OR link = '$oldLink') AND
  4256. image = 'scormbuilder.gif' AND
  4257. (
  4258. link LIKE '$link%' OR
  4259. link LIKE '$oldLink%'
  4260. )
  4261. $session_condition
  4262. ";
  4263. $result = Database::query($sql);
  4264. $num = Database::num_rows($result);
  4265. if ($set_visibility == 'i' && $num > 0) {
  4266. $sql = "DELETE FROM $tbl_tool
  4267. WHERE
  4268. c_id = $course_id AND
  4269. (link = '$link' OR link = '$oldLink') AND
  4270. image='scormbuilder.gif'
  4271. $session_condition";
  4272. Database::query($sql);
  4273. } elseif ($set_visibility == 'v' && $num == 0) {
  4274. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4275. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4276. Database::query($sql);
  4277. $insertId = Database::insert_id();
  4278. if ($insertId) {
  4279. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4280. Database::query($sql);
  4281. }
  4282. } elseif ($set_visibility == 'v' && $num > 0) {
  4283. $sql = "UPDATE $tbl_tool SET
  4284. c_id = $course_id,
  4285. name = '$name',
  4286. link = '$link',
  4287. image = 'scormbuilder.gif',
  4288. visibility = '$v',
  4289. admin = '0',
  4290. address = 'pastillegris.gif',
  4291. added_tool = 0,
  4292. session_id = $session_id
  4293. WHERE
  4294. c_id = ".$course_id." AND
  4295. (link = '$link' OR link = '$oldLink') AND
  4296. image='scormbuilder.gif'
  4297. $session_condition
  4298. ";
  4299. Database::query($sql);
  4300. } else {
  4301. // Parameter and database incompatible, do nothing, exit.
  4302. return false;
  4303. }
  4304. } else {
  4305. return false;
  4306. }
  4307. }
  4308. /**
  4309. * Publishes a learnpath.
  4310. * Show or hide the learnpath category on the course homepage.
  4311. *
  4312. * @param int $id
  4313. * @param int $setVisibility
  4314. *
  4315. * @throws \Doctrine\ORM\NonUniqueResultException
  4316. * @throws \Doctrine\ORM\ORMException
  4317. * @throws \Doctrine\ORM\OptimisticLockException
  4318. * @throws \Doctrine\ORM\TransactionRequiredException
  4319. *
  4320. * @return bool
  4321. */
  4322. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4323. {
  4324. $courseId = api_get_course_int_id();
  4325. $sessionId = api_get_session_id();
  4326. $sessionCondition = api_get_session_condition(
  4327. $sessionId,
  4328. true,
  4329. false,
  4330. 't.sessionId'
  4331. );
  4332. $em = Database::getManager();
  4333. /** @var CLpCategory $category */
  4334. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4335. if (!$category) {
  4336. return false;
  4337. }
  4338. if (empty($courseId)) {
  4339. return false;
  4340. }
  4341. $link = self::getCategoryLinkForTool($id);
  4342. /** @var CTool $tool */
  4343. $tool = $em->createQuery("
  4344. SELECT t FROM ChamiloCourseBundle:CTool t
  4345. WHERE
  4346. t.cId = :course AND
  4347. t.link = :link1 AND
  4348. t.image = 'lp_category.gif' AND
  4349. t.link LIKE :link2
  4350. $sessionCondition
  4351. ")
  4352. ->setParameters([
  4353. 'course' => (int) $courseId,
  4354. 'link1' => $link,
  4355. 'link2' => "$link%",
  4356. ])
  4357. ->getOneOrNullResult();
  4358. if ($setVisibility == 0 && $tool) {
  4359. $em->remove($tool);
  4360. $em->flush();
  4361. return true;
  4362. }
  4363. if ($setVisibility == 1 && !$tool) {
  4364. $tool = new CTool();
  4365. $tool
  4366. ->setCategory('authoring')
  4367. ->setCId($courseId)
  4368. ->setName(strip_tags($category->getName()))
  4369. ->setLink($link)
  4370. ->setImage('lp_category.gif')
  4371. ->setVisibility(1)
  4372. ->setAdmin(0)
  4373. ->setAddress('pastillegris.gif')
  4374. ->setAddedTool(0)
  4375. ->setSessionId($sessionId)
  4376. ->setTarget('_self');
  4377. $em->persist($tool);
  4378. $em->flush();
  4379. $tool->setId($tool->getIid());
  4380. $em->persist($tool);
  4381. $em->flush();
  4382. return true;
  4383. }
  4384. if ($setVisibility == 1 && $tool) {
  4385. $tool
  4386. ->setName(strip_tags($category->getName()))
  4387. ->setVisibility(1);
  4388. $em->persist($tool);
  4389. $em->flush();
  4390. return true;
  4391. }
  4392. return false;
  4393. }
  4394. /**
  4395. * Check if the learnpath category is visible for a user.
  4396. *
  4397. * @param CLpCategory $category
  4398. * @param User $user
  4399. *
  4400. * @return bool
  4401. */
  4402. public static function categoryIsVisibleForStudent(
  4403. CLpCategory $category,
  4404. User $user
  4405. ) {
  4406. $subscriptionSettings = self::getSubscriptionSettings();
  4407. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4408. return true;
  4409. }
  4410. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4411. if ($isAllowedToEdit) {
  4412. return true;
  4413. }
  4414. if (empty($category)) {
  4415. return false;
  4416. }
  4417. $users = $category->getUsers();
  4418. if (empty($users) || !$users->count()) {
  4419. return true;
  4420. }
  4421. if ($category->hasUserAdded($user)) {
  4422. return true;
  4423. }
  4424. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4425. if (!empty($groups)) {
  4426. $em = Database::getManager();
  4427. /** @var ItemPropertyRepository $itemRepo */
  4428. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4429. /** @var CourseRepository $courseRepo */
  4430. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4431. $sessionId = api_get_session_id();
  4432. $session = null;
  4433. if (!empty($sessionId)) {
  4434. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4435. }
  4436. $course = $courseRepo->find(api_get_course_int_id());
  4437. // Subscribed groups to a LP
  4438. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4439. TOOL_LEARNPATH_CATEGORY,
  4440. $category->getId(),
  4441. $course,
  4442. $session
  4443. );
  4444. if (!empty($subscribedGroupsInLp)) {
  4445. $groups = array_column($groups, 'iid');
  4446. /** @var CItemProperty $item */
  4447. foreach ($subscribedGroupsInLp as $item) {
  4448. if ($item->getGroup() &&
  4449. in_array($item->getGroup()->getId(), $groups)
  4450. ) {
  4451. return true;
  4452. }
  4453. }
  4454. }
  4455. }
  4456. return false;
  4457. }
  4458. /**
  4459. * Check if a learnpath category is published as course tool.
  4460. *
  4461. * @param CLpCategory $category
  4462. * @param int $courseId
  4463. *
  4464. * @return bool
  4465. */
  4466. public static function categoryIsPublished(
  4467. CLpCategory $category,
  4468. $courseId
  4469. ) {
  4470. $link = self::getCategoryLinkForTool($category->getId());
  4471. $em = Database::getManager();
  4472. $tools = $em
  4473. ->createQuery("
  4474. SELECT t FROM ChamiloCourseBundle:CTool t
  4475. WHERE t.cId = :course AND
  4476. t.name = :name AND
  4477. t.image = 'lp_category.gif' AND
  4478. t.link LIKE :link
  4479. ")
  4480. ->setParameters([
  4481. 'course' => $courseId,
  4482. 'name' => strip_tags($category->getName()),
  4483. 'link' => "$link%",
  4484. ])
  4485. ->getResult();
  4486. /** @var CTool $tool */
  4487. $tool = current($tools);
  4488. return $tool ? $tool->getVisibility() : false;
  4489. }
  4490. /**
  4491. * Restart the whole learnpath. Return the URL of the first element.
  4492. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4493. * To use a similar method statically, use the create_new_attempt() method.
  4494. *
  4495. * @return bool
  4496. */
  4497. public function restart()
  4498. {
  4499. if ($this->debug > 0) {
  4500. error_log('In learnpath::restart()', 0);
  4501. }
  4502. // TODO
  4503. // Call autosave method to save the current progress.
  4504. //$this->index = 0;
  4505. if (api_is_invitee()) {
  4506. return false;
  4507. }
  4508. $session_id = api_get_session_id();
  4509. $course_id = api_get_course_int_id();
  4510. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4511. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4512. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4513. if ($this->debug > 2) {
  4514. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4515. }
  4516. Database::query($sql);
  4517. $view_id = Database::insert_id();
  4518. if ($view_id) {
  4519. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4520. Database::query($sql);
  4521. $this->lp_view_id = $view_id;
  4522. $this->attempt = $this->attempt + 1;
  4523. } else {
  4524. $this->error = 'Could not insert into item_view table...';
  4525. return false;
  4526. }
  4527. $this->autocomplete_parents($this->current);
  4528. foreach ($this->items as $index => $dummy) {
  4529. $this->items[$index]->restart();
  4530. $this->items[$index]->set_lp_view($this->lp_view_id);
  4531. }
  4532. $this->first();
  4533. return true;
  4534. }
  4535. /**
  4536. * Saves the current item.
  4537. *
  4538. * @return bool
  4539. */
  4540. public function save_current()
  4541. {
  4542. $debug = $this->debug;
  4543. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4544. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4545. if ($debug) {
  4546. error_log('save_current() saving item '.$this->current, 0);
  4547. error_log(''.print_r($this->items, true), 0);
  4548. }
  4549. if (isset($this->items[$this->current]) &&
  4550. is_object($this->items[$this->current])
  4551. ) {
  4552. if ($debug) {
  4553. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4554. }
  4555. $res = $this->items[$this->current]->save(
  4556. false,
  4557. $this->prerequisites_match($this->current)
  4558. );
  4559. $this->autocomplete_parents($this->current);
  4560. $status = $this->items[$this->current]->get_status();
  4561. $this->update_queue[$this->current] = $status;
  4562. if ($debug) {
  4563. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4564. }
  4565. return $res;
  4566. }
  4567. return false;
  4568. }
  4569. /**
  4570. * Saves the given item.
  4571. *
  4572. * @param int $item_id Optional (will take from $_REQUEST if null)
  4573. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4574. *
  4575. * @return bool
  4576. */
  4577. public function save_item($item_id = null, $from_outside = true)
  4578. {
  4579. $debug = $this->debug;
  4580. if ($debug) {
  4581. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4582. }
  4583. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4584. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4585. if (empty($item_id)) {
  4586. $item_id = (int) $_REQUEST['id'];
  4587. }
  4588. if (empty($item_id)) {
  4589. $item_id = $this->get_current_item_id();
  4590. }
  4591. if (isset($this->items[$item_id]) &&
  4592. is_object($this->items[$item_id])
  4593. ) {
  4594. if ($debug) {
  4595. error_log('Object exists');
  4596. }
  4597. // Saving the item.
  4598. $res = $this->items[$item_id]->save(
  4599. $from_outside,
  4600. $this->prerequisites_match($item_id)
  4601. );
  4602. if ($debug) {
  4603. error_log('update_queue before:');
  4604. error_log(print_r($this->update_queue, 1));
  4605. }
  4606. $this->autocomplete_parents($item_id);
  4607. $status = $this->items[$item_id]->get_status();
  4608. $this->update_queue[$item_id] = $status;
  4609. if ($debug) {
  4610. error_log('get_status(): '.$status);
  4611. error_log('update_queue after:');
  4612. error_log(print_r($this->update_queue, 1));
  4613. }
  4614. return $res;
  4615. }
  4616. return false;
  4617. }
  4618. /**
  4619. * Saves the last item seen's ID only in case.
  4620. */
  4621. public function save_last()
  4622. {
  4623. $course_id = api_get_course_int_id();
  4624. $debug = $this->debug;
  4625. if ($debug) {
  4626. error_log('In learnpath::save_last()', 0);
  4627. }
  4628. $session_condition = api_get_session_condition(
  4629. api_get_session_id(),
  4630. true,
  4631. false
  4632. );
  4633. $table = Database::get_course_table(TABLE_LP_VIEW);
  4634. if (isset($this->current) && !api_is_invitee()) {
  4635. if ($debug) {
  4636. error_log('Saving current item ('.$this->current.') for later review', 0);
  4637. }
  4638. $sql = "UPDATE $table SET
  4639. last_item = ".intval($this->get_current_item_id())."
  4640. WHERE
  4641. c_id = $course_id AND
  4642. lp_id = ".$this->get_id()." AND
  4643. user_id = ".$this->get_user_id()." ".$session_condition;
  4644. if ($debug) {
  4645. error_log('Saving last item seen : '.$sql, 0);
  4646. }
  4647. Database::query($sql);
  4648. }
  4649. if (!api_is_invitee()) {
  4650. // Save progress.
  4651. list($progress) = $this->get_progress_bar_text('%');
  4652. if ($progress >= 0 && $progress <= 100) {
  4653. $progress = (int) $progress;
  4654. $sql = "UPDATE $table SET
  4655. progress = $progress
  4656. WHERE
  4657. c_id = $course_id AND
  4658. lp_id = ".$this->get_id()." AND
  4659. user_id = ".$this->get_user_id()." ".$session_condition;
  4660. // Ignore errors as some tables might not have the progress field just yet.
  4661. Database::query($sql);
  4662. if ($debug) {
  4663. error_log($sql);
  4664. }
  4665. $this->progress_db = $progress;
  4666. }
  4667. }
  4668. }
  4669. /**
  4670. * Sets the current item ID (checks if valid and authorized first).
  4671. *
  4672. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4673. */
  4674. public function set_current_item($item_id = null)
  4675. {
  4676. $debug = $this->debug;
  4677. if ($debug) {
  4678. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4679. }
  4680. if (empty($item_id)) {
  4681. if ($debug) {
  4682. error_log('No new current item given, ignore...', 0);
  4683. }
  4684. // Do nothing.
  4685. } else {
  4686. if ($debug) {
  4687. error_log('New current item given is '.$item_id.'...', 0);
  4688. }
  4689. if (is_numeric($item_id)) {
  4690. $item_id = (int) $item_id;
  4691. // TODO: Check in database here.
  4692. $this->last = $this->current;
  4693. $this->current = $item_id;
  4694. // TODO: Update $this->index as well.
  4695. foreach ($this->ordered_items as $index => $item) {
  4696. if ($item == $this->current) {
  4697. $this->index = $index;
  4698. break;
  4699. }
  4700. }
  4701. if ($debug) {
  4702. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4703. }
  4704. } else {
  4705. if ($debug) {
  4706. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4707. }
  4708. }
  4709. }
  4710. }
  4711. /**
  4712. * Sets the encoding.
  4713. *
  4714. * @param string $enc New encoding
  4715. *
  4716. * @return bool
  4717. *
  4718. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4719. */
  4720. public function set_encoding($enc = 'UTF-8')
  4721. {
  4722. if ($this->debug > 0) {
  4723. error_log('In learnpath::set_encoding()', 0);
  4724. }
  4725. $enc = api_refine_encoding_id($enc);
  4726. if (empty($enc)) {
  4727. $enc = api_get_system_encoding();
  4728. }
  4729. if (api_is_encoding_supported($enc)) {
  4730. $lp = $this->get_id();
  4731. if ($lp != 0) {
  4732. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4733. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4734. WHERE iid = ".$lp;
  4735. $res = Database::query($sql);
  4736. return $res;
  4737. }
  4738. }
  4739. return false;
  4740. }
  4741. /**
  4742. * Sets the JS lib setting in the database directly.
  4743. * This is the JavaScript library file this lp needs to load on startup.
  4744. *
  4745. * @param string $lib Proximity setting
  4746. *
  4747. * @return bool True on update success. False otherwise.
  4748. */
  4749. public function set_jslib($lib = '')
  4750. {
  4751. if ($this->debug > 0) {
  4752. error_log('In learnpath::set_jslib()', 0);
  4753. }
  4754. $lp = $this->get_id();
  4755. if ($lp != 0) {
  4756. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4757. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4758. WHERE iid = $lp";
  4759. $res = Database::query($sql);
  4760. return $res;
  4761. } else {
  4762. return false;
  4763. }
  4764. }
  4765. /**
  4766. * Sets the name of the LP maker (publisher) (and save).
  4767. *
  4768. * @param string $name Optional string giving the new content_maker of this learnpath
  4769. *
  4770. * @return bool True
  4771. */
  4772. public function set_maker($name = '')
  4773. {
  4774. if ($this->debug > 0) {
  4775. error_log('In learnpath::set_maker()', 0);
  4776. }
  4777. if (empty($name)) {
  4778. return false;
  4779. }
  4780. $this->maker = $name;
  4781. $table = Database::get_course_table(TABLE_LP_MAIN);
  4782. $lp_id = $this->get_id();
  4783. $sql = "UPDATE $table SET
  4784. content_maker = '".Database::escape_string($this->maker)."'
  4785. WHERE iid = $lp_id";
  4786. if ($this->debug > 2) {
  4787. error_log('lp updated with new content_maker : '.$this->maker, 0);
  4788. }
  4789. Database::query($sql);
  4790. return true;
  4791. }
  4792. /**
  4793. * Sets the name of the current learnpath (and save).
  4794. *
  4795. * @param string $name Optional string giving the new name of this learnpath
  4796. *
  4797. * @return bool True/False
  4798. */
  4799. public function set_name($name = null)
  4800. {
  4801. if ($this->debug > 0) {
  4802. error_log('In learnpath::set_name()', 0);
  4803. }
  4804. if (empty($name)) {
  4805. return false;
  4806. }
  4807. $this->name = Database::escape_string($name);
  4808. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4809. $lp_id = $this->get_id();
  4810. $course_id = $this->course_info['real_id'];
  4811. $sql = "UPDATE $lp_table SET
  4812. name = '".Database::escape_string($this->name)."'
  4813. WHERE iid = $lp_id";
  4814. if ($this->debug > 2) {
  4815. error_log('lp updated with new name : '.$this->name, 0);
  4816. }
  4817. $result = Database::query($sql);
  4818. // If the lp is visible on the homepage, change his name there.
  4819. if (Database::affected_rows($result)) {
  4820. $session_id = api_get_session_id();
  4821. $session_condition = api_get_session_condition($session_id);
  4822. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4823. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4824. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4825. WHERE
  4826. c_id = $course_id AND
  4827. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4828. Database::query($sql);
  4829. return true;
  4830. } else {
  4831. return false;
  4832. }
  4833. }
  4834. /**
  4835. * Set index specified prefix terms for all items in this path.
  4836. *
  4837. * @param string $terms_string Comma-separated list of terms
  4838. * @param string $prefix Xapian term prefix
  4839. *
  4840. * @return bool False on error, true otherwise
  4841. */
  4842. public function set_terms_by_prefix($terms_string, $prefix)
  4843. {
  4844. $course_id = api_get_course_int_id();
  4845. if (api_get_setting('search_enabled') !== 'true') {
  4846. return false;
  4847. }
  4848. if (!extension_loaded('xapian')) {
  4849. return false;
  4850. }
  4851. $terms_string = trim($terms_string);
  4852. $terms = explode(',', $terms_string);
  4853. array_walk($terms, 'trim_value');
  4854. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4855. // Don't do anything if no change, verify only at DB, not the search engine.
  4856. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4857. return false;
  4858. }
  4859. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4860. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4861. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4862. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4863. $lp_id = (int) $_POST['lp_id'];
  4864. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4865. $result = Database::query($sql);
  4866. $di = new ChamiloIndexer();
  4867. while ($lp_item = Database::fetch_array($result)) {
  4868. // Get search_did.
  4869. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4870. $sql = 'SELECT * FROM %s
  4871. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4872. LIMIT 1';
  4873. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4874. //echo $sql; echo '<br>';
  4875. $res = Database::query($sql);
  4876. if (Database::num_rows($res) > 0) {
  4877. $se_ref = Database::fetch_array($res);
  4878. // Compare terms.
  4879. $doc = $di->get_document($se_ref['search_did']);
  4880. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4881. $xterms = [];
  4882. foreach ($xapian_terms as $xapian_term) {
  4883. $xterms[] = substr($xapian_term['name'], 1);
  4884. }
  4885. $dterms = $terms;
  4886. $missing_terms = array_diff($dterms, $xterms);
  4887. $deprecated_terms = array_diff($xterms, $dterms);
  4888. // Save it to search engine.
  4889. foreach ($missing_terms as $term) {
  4890. $doc->add_term($prefix.$term, 1);
  4891. }
  4892. foreach ($deprecated_terms as $term) {
  4893. $doc->remove_term($prefix.$term);
  4894. }
  4895. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4896. $di->getDb()->flush();
  4897. }
  4898. }
  4899. return true;
  4900. }
  4901. /**
  4902. * Sets the theme of the LP (local/remote) (and save).
  4903. *
  4904. * @param string $name Optional string giving the new theme of this learnpath
  4905. *
  4906. * @return bool Returns true if theme name is not empty
  4907. */
  4908. public function set_theme($name = '')
  4909. {
  4910. if ($this->debug > 0) {
  4911. error_log('In learnpath::set_theme()', 0);
  4912. }
  4913. $this->theme = $name;
  4914. $table = Database::get_course_table(TABLE_LP_MAIN);
  4915. $lp_id = $this->get_id();
  4916. $sql = "UPDATE $table
  4917. SET theme = '".Database::escape_string($this->theme)."'
  4918. WHERE iid = $lp_id";
  4919. if ($this->debug > 2) {
  4920. error_log('lp updated with new theme : '.$this->theme, 0);
  4921. }
  4922. Database::query($sql);
  4923. return true;
  4924. }
  4925. /**
  4926. * Sets the image of an LP (and save).
  4927. *
  4928. * @param string $name Optional string giving the new image of this learnpath
  4929. *
  4930. * @return bool Returns true if theme name is not empty
  4931. */
  4932. public function set_preview_image($name = '')
  4933. {
  4934. if ($this->debug > 0) {
  4935. error_log('In learnpath::set_preview_image()', 0);
  4936. }
  4937. $this->preview_image = $name;
  4938. $table = Database::get_course_table(TABLE_LP_MAIN);
  4939. $lp_id = $this->get_id();
  4940. $sql = "UPDATE $table SET
  4941. preview_image = '".Database::escape_string($this->preview_image)."'
  4942. WHERE iid = $lp_id";
  4943. if ($this->debug > 2) {
  4944. error_log('lp updated with new preview image : '.$this->preview_image, 0);
  4945. }
  4946. Database::query($sql);
  4947. return true;
  4948. }
  4949. /**
  4950. * Sets the author of a LP (and save).
  4951. *
  4952. * @param string $name Optional string giving the new author of this learnpath
  4953. *
  4954. * @return bool Returns true if author's name is not empty
  4955. */
  4956. public function set_author($name = '')
  4957. {
  4958. if ($this->debug > 0) {
  4959. error_log('In learnpath::set_author()', 0);
  4960. }
  4961. $this->author = $name;
  4962. $table = Database::get_course_table(TABLE_LP_MAIN);
  4963. $lp_id = $this->get_id();
  4964. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4965. WHERE iid = $lp_id";
  4966. if ($this->debug > 2) {
  4967. error_log('lp updated with new preview author : '.$this->author, 0);
  4968. }
  4969. Database::query($sql);
  4970. return true;
  4971. }
  4972. /**
  4973. * Sets the hide_toc_frame parameter of a LP (and save).
  4974. *
  4975. * @param int $hide 1 if frame is hidden 0 then else
  4976. *
  4977. * @return bool Returns true if author's name is not empty
  4978. */
  4979. public function set_hide_toc_frame($hide)
  4980. {
  4981. if ($this->debug > 0) {
  4982. error_log('In learnpath::set_hide_toc_frame()', 0);
  4983. }
  4984. if (intval($hide) == $hide) {
  4985. $this->hide_toc_frame = $hide;
  4986. $table = Database::get_course_table(TABLE_LP_MAIN);
  4987. $lp_id = $this->get_id();
  4988. $sql = "UPDATE $table SET
  4989. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4990. WHERE iid = $lp_id";
  4991. if ($this->debug > 2) {
  4992. error_log('lp updated with new preview hide_toc_frame : '.$this->author, 0);
  4993. }
  4994. Database::query($sql);
  4995. return true;
  4996. } else {
  4997. return false;
  4998. }
  4999. }
  5000. /**
  5001. * Sets the prerequisite of a LP (and save).
  5002. *
  5003. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  5004. *
  5005. * @return bool returns true if prerequisite is not empty
  5006. */
  5007. public function set_prerequisite($prerequisite)
  5008. {
  5009. if ($this->debug > 0) {
  5010. error_log('In learnpath::set_prerequisite()', 0);
  5011. }
  5012. $this->prerequisite = (int) $prerequisite;
  5013. $table = Database::get_course_table(TABLE_LP_MAIN);
  5014. $lp_id = $this->get_id();
  5015. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  5016. WHERE iid = $lp_id";
  5017. if ($this->debug > 2) {
  5018. error_log('lp updated with new preview requisite : '.$this->requisite, 0);
  5019. }
  5020. Database::query($sql);
  5021. return true;
  5022. }
  5023. /**
  5024. * Sets the location/proximity of the LP (local/remote) (and save).
  5025. *
  5026. * @param string $name Optional string giving the new location of this learnpath
  5027. *
  5028. * @return bool True on success / False on error
  5029. */
  5030. public function set_proximity($name = '')
  5031. {
  5032. if ($this->debug > 0) {
  5033. error_log('In learnpath::set_proximity()', 0);
  5034. }
  5035. if (empty($name)) {
  5036. return false;
  5037. }
  5038. $this->proximity = $name;
  5039. $table = Database::get_course_table(TABLE_LP_MAIN);
  5040. $lp_id = $this->get_id();
  5041. $sql = "UPDATE $table SET
  5042. content_local = '".Database::escape_string($name)."'
  5043. WHERE iid = $lp_id";
  5044. if ($this->debug > 2) {
  5045. error_log('lp updated with new proximity : '.$this->proximity, 0);
  5046. }
  5047. Database::query($sql);
  5048. return true;
  5049. }
  5050. /**
  5051. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  5052. *
  5053. * @param int $id DB ID of the item
  5054. */
  5055. public function set_previous_item($id)
  5056. {
  5057. if ($this->debug > 0) {
  5058. error_log('In learnpath::set_previous_item()', 0);
  5059. }
  5060. $this->last = $id;
  5061. }
  5062. /**
  5063. * Sets use_max_score.
  5064. *
  5065. * @param int $use_max_score Optional string giving the new location of this learnpath
  5066. *
  5067. * @return bool True on success / False on error
  5068. */
  5069. public function set_use_max_score($use_max_score = 1)
  5070. {
  5071. if ($this->debug > 0) {
  5072. error_log('In learnpath::set_use_max_score()', 0);
  5073. }
  5074. $use_max_score = (int) $use_max_score;
  5075. $this->use_max_score = $use_max_score;
  5076. $table = Database::get_course_table(TABLE_LP_MAIN);
  5077. $lp_id = $this->get_id();
  5078. $sql = "UPDATE $table SET
  5079. use_max_score = '".$this->use_max_score."'
  5080. WHERE iid = $lp_id";
  5081. if ($this->debug > 2) {
  5082. error_log('lp updated with new use_max_score : '.$this->use_max_score, 0);
  5083. }
  5084. Database::query($sql);
  5085. return true;
  5086. }
  5087. /**
  5088. * Sets and saves the expired_on date.
  5089. *
  5090. * @param string $expired_on Optional string giving the new author of this learnpath
  5091. *
  5092. * @throws \Doctrine\ORM\OptimisticLockException
  5093. *
  5094. * @return bool Returns true if author's name is not empty
  5095. */
  5096. public function set_expired_on($expired_on)
  5097. {
  5098. if ($this->debug > 0) {
  5099. error_log('In learnpath::set_expired_on()', 0);
  5100. }
  5101. $em = Database::getManager();
  5102. /** @var CLp $lp */
  5103. $lp = $em
  5104. ->getRepository('ChamiloCourseBundle:CLp')
  5105. ->findOneBy(
  5106. [
  5107. 'iid' => $this->get_id(),
  5108. ]
  5109. );
  5110. if (!$lp) {
  5111. return false;
  5112. }
  5113. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  5114. $lp->setExpiredOn($this->expired_on);
  5115. $em->persist($lp);
  5116. $em->flush();
  5117. if ($this->debug > 2) {
  5118. error_log('lp updated with new expired_on : '.$this->expired_on, 0);
  5119. }
  5120. return true;
  5121. }
  5122. /**
  5123. * Sets and saves the publicated_on date.
  5124. *
  5125. * @param string $publicated_on Optional string giving the new author of this learnpath
  5126. *
  5127. * @throws \Doctrine\ORM\OptimisticLockException
  5128. *
  5129. * @return bool Returns true if author's name is not empty
  5130. */
  5131. public function set_publicated_on($publicated_on)
  5132. {
  5133. if ($this->debug > 0) {
  5134. error_log('In learnpath::set_expired_on()', 0);
  5135. }
  5136. $em = Database::getManager();
  5137. /** @var CLp $lp */
  5138. $lp = $em
  5139. ->getRepository('ChamiloCourseBundle:CLp')
  5140. ->findOneBy(
  5141. [
  5142. 'iid' => $this->get_id(),
  5143. ]
  5144. );
  5145. if (!$lp) {
  5146. return false;
  5147. }
  5148. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  5149. $lp->setPublicatedOn($this->publicated_on);
  5150. $em->persist($lp);
  5151. $em->flush();
  5152. if ($this->debug > 2) {
  5153. error_log('lp updated with new publicated_on : '.$this->publicated_on, 0);
  5154. }
  5155. return true;
  5156. }
  5157. /**
  5158. * Sets and saves the expired_on date.
  5159. *
  5160. * @return bool Returns true if author's name is not empty
  5161. */
  5162. public function set_modified_on()
  5163. {
  5164. if ($this->debug > 0) {
  5165. error_log('In learnpath::set_expired_on()', 0);
  5166. }
  5167. $this->modified_on = api_get_utc_datetime();
  5168. $table = Database::get_course_table(TABLE_LP_MAIN);
  5169. $lp_id = $this->get_id();
  5170. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  5171. WHERE iid = $lp_id";
  5172. if ($this->debug > 2) {
  5173. error_log('lp updated with new expired_on : '.$this->modified_on, 0);
  5174. }
  5175. Database::query($sql);
  5176. return true;
  5177. }
  5178. /**
  5179. * Sets the object's error message.
  5180. *
  5181. * @param string $error Error message. If empty, reinits the error string
  5182. */
  5183. public function set_error_msg($error = '')
  5184. {
  5185. if ($this->debug > 0) {
  5186. error_log('In learnpath::set_error_msg()', 0);
  5187. }
  5188. if (empty($error)) {
  5189. $this->error = '';
  5190. } else {
  5191. $this->error .= $error;
  5192. }
  5193. }
  5194. /**
  5195. * Launches the current item if not 'sco'
  5196. * (starts timer and make sure there is a record ready in the DB).
  5197. *
  5198. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  5199. *
  5200. * @return bool
  5201. */
  5202. public function start_current_item($allow_new_attempt = false)
  5203. {
  5204. $debug = $this->debug;
  5205. if ($debug) {
  5206. error_log('In learnpath::start_current_item()');
  5207. error_log('current: '.$this->current);
  5208. }
  5209. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  5210. $type = $this->get_type();
  5211. $item_type = $this->items[$this->current]->get_type();
  5212. if (($type == 2 && $item_type != 'sco') ||
  5213. ($type == 3 && $item_type != 'au') ||
  5214. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  5215. ) {
  5216. if ($debug) {
  5217. error_log('item type: '.$item_type);
  5218. error_log('lp type: '.$type);
  5219. }
  5220. $this->items[$this->current]->open($allow_new_attempt);
  5221. $this->autocomplete_parents($this->current);
  5222. $prereq_check = $this->prerequisites_match($this->current);
  5223. if ($debug) {
  5224. error_log('start_current_item will save item with prereq: '.$prereq_check);
  5225. }
  5226. $this->items[$this->current]->save(false, $prereq_check);
  5227. }
  5228. // If sco, then it is supposed to have been updated by some other call.
  5229. if ($item_type == 'sco') {
  5230. $this->items[$this->current]->restart();
  5231. }
  5232. }
  5233. if ($debug) {
  5234. error_log('lp_view_session_id');
  5235. error_log($this->lp_view_session_id);
  5236. error_log('api session id');
  5237. error_log(api_get_session_id());
  5238. error_log('End of learnpath::start_current_item()');
  5239. }
  5240. return true;
  5241. }
  5242. /**
  5243. * Stops the processing and counters for the old item (as held in $this->last).
  5244. *
  5245. * @return bool True/False
  5246. */
  5247. public function stop_previous_item()
  5248. {
  5249. $debug = $this->debug;
  5250. if ($debug) {
  5251. error_log('In learnpath::stop_previous_item()', 0);
  5252. }
  5253. if ($this->last != 0 && $this->last != $this->current &&
  5254. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  5255. ) {
  5256. if ($debug) {
  5257. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  5258. }
  5259. switch ($this->get_type()) {
  5260. case '3':
  5261. if ($this->items[$this->last]->get_type() != 'au') {
  5262. if ($debug) {
  5263. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  5264. }
  5265. $this->items[$this->last]->close();
  5266. } else {
  5267. if ($debug) {
  5268. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  5269. }
  5270. }
  5271. break;
  5272. case '2':
  5273. if ($this->items[$this->last]->get_type() != 'sco') {
  5274. if ($debug) {
  5275. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  5276. }
  5277. $this->items[$this->last]->close();
  5278. } else {
  5279. if ($debug) {
  5280. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5281. }
  5282. }
  5283. break;
  5284. case '1':
  5285. default:
  5286. if ($debug) {
  5287. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5288. }
  5289. $this->items[$this->last]->close();
  5290. break;
  5291. }
  5292. } else {
  5293. if ($debug) {
  5294. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5295. }
  5296. return false;
  5297. }
  5298. return true;
  5299. }
  5300. /**
  5301. * Updates the default view mode from fullscreen to embedded and inversely.
  5302. *
  5303. * @return string The current default view mode ('fullscreen' or 'embedded')
  5304. */
  5305. public function update_default_view_mode()
  5306. {
  5307. if ($this->debug > 0) {
  5308. error_log('In learnpath::update_default_view_mode()', 0);
  5309. }
  5310. $table = Database::get_course_table(TABLE_LP_MAIN);
  5311. $sql = "SELECT * FROM $table
  5312. WHERE iid = ".$this->get_id();
  5313. $res = Database::query($sql);
  5314. if (Database::num_rows($res) > 0) {
  5315. $row = Database::fetch_array($res);
  5316. $default_view_mode = $row['default_view_mod'];
  5317. $view_mode = $default_view_mode;
  5318. switch ($default_view_mode) {
  5319. case 'fullscreen': // default with popup
  5320. $view_mode = 'embedded';
  5321. break;
  5322. case 'embedded': // default view with left menu
  5323. $view_mode = 'embedframe';
  5324. break;
  5325. case 'embedframe': //folded menu
  5326. $view_mode = 'impress';
  5327. break;
  5328. case 'impress':
  5329. $view_mode = 'fullscreen';
  5330. break;
  5331. }
  5332. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5333. WHERE iid = ".$this->get_id();
  5334. Database::query($sql);
  5335. $this->mode = $view_mode;
  5336. return $view_mode;
  5337. } else {
  5338. if ($this->debug > 2) {
  5339. error_log('Problem in update_default_view() - could not find LP '.$this->get_id().' in DB', 0);
  5340. }
  5341. }
  5342. return -1;
  5343. }
  5344. /**
  5345. * Updates the default behaviour about auto-commiting SCORM updates.
  5346. *
  5347. * @return bool True if auto-commit has been set to 'on', false otherwise
  5348. */
  5349. public function update_default_scorm_commit()
  5350. {
  5351. if ($this->debug > 0) {
  5352. error_log('In learnpath::update_default_scorm_commit()', 0);
  5353. }
  5354. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5355. $sql = "SELECT * FROM $lp_table
  5356. WHERE iid = ".$this->get_id();
  5357. $res = Database::query($sql);
  5358. if (Database::num_rows($res) > 0) {
  5359. $row = Database::fetch_array($res);
  5360. $force = $row['force_commit'];
  5361. if ($force == 1) {
  5362. $force = 0;
  5363. $force_return = false;
  5364. } elseif ($force == 0) {
  5365. $force = 1;
  5366. $force_return = true;
  5367. }
  5368. $sql = "UPDATE $lp_table SET force_commit = $force
  5369. WHERE iid = ".$this->get_id();
  5370. Database::query($sql);
  5371. $this->force_commit = $force_return;
  5372. return $force_return;
  5373. } else {
  5374. if ($this->debug > 2) {
  5375. error_log('Problem in update_default_scorm_commit() - could not find LP '.$this->get_id().' in DB', 0);
  5376. }
  5377. }
  5378. return -1;
  5379. }
  5380. /**
  5381. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5382. *
  5383. * @return bool True on success, false on failure
  5384. */
  5385. public function update_display_order()
  5386. {
  5387. $course_id = api_get_course_int_id();
  5388. $table = Database::get_course_table(TABLE_LP_MAIN);
  5389. $sql = "SELECT * FROM $table
  5390. WHERE c_id = $course_id
  5391. ORDER BY display_order";
  5392. $res = Database::query($sql);
  5393. if ($res === false) {
  5394. return false;
  5395. }
  5396. $num = Database::num_rows($res);
  5397. // First check the order is correct, globally (might be wrong because
  5398. // of versions < 1.8.4).
  5399. if ($num > 0) {
  5400. $i = 1;
  5401. while ($row = Database::fetch_array($res)) {
  5402. if ($row['display_order'] != $i) {
  5403. // If we find a gap in the order, we need to fix it.
  5404. $sql = "UPDATE $table SET display_order = $i
  5405. WHERE iid = ".$row['iid'];
  5406. Database::query($sql);
  5407. }
  5408. $i++;
  5409. }
  5410. }
  5411. return true;
  5412. }
  5413. /**
  5414. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5415. *
  5416. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5417. */
  5418. public function update_reinit()
  5419. {
  5420. if ($this->debug > 0) {
  5421. error_log('In learnpath::update_reinit()', 0);
  5422. }
  5423. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5424. $sql = "SELECT * FROM $lp_table
  5425. WHERE iid = ".$this->get_id();
  5426. $res = Database::query($sql);
  5427. if (Database::num_rows($res) > 0) {
  5428. $row = Database::fetch_array($res);
  5429. $force = $row['prevent_reinit'];
  5430. if ($force == 1) {
  5431. $force = 0;
  5432. } elseif ($force == 0) {
  5433. $force = 1;
  5434. }
  5435. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5436. WHERE iid = ".$this->get_id();
  5437. Database::query($sql);
  5438. $this->prevent_reinit = $force;
  5439. return $force;
  5440. } else {
  5441. if ($this->debug > 2) {
  5442. error_log('Problem in update_reinit() - could not find LP '.$this->get_id().' in DB', 0);
  5443. }
  5444. }
  5445. return -1;
  5446. }
  5447. /**
  5448. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5449. *
  5450. * @return string 'single', 'multi' or 'seriousgame'
  5451. *
  5452. * @author ndiechburg <noel@cblue.be>
  5453. */
  5454. public function get_attempt_mode()
  5455. {
  5456. //Set default value for seriousgame_mode
  5457. if (!isset($this->seriousgame_mode)) {
  5458. $this->seriousgame_mode = 0;
  5459. }
  5460. // Set default value for prevent_reinit
  5461. if (!isset($this->prevent_reinit)) {
  5462. $this->prevent_reinit = 1;
  5463. }
  5464. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5465. return 'seriousgame';
  5466. }
  5467. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5468. return 'single';
  5469. }
  5470. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5471. return 'multiple';
  5472. }
  5473. return 'single';
  5474. }
  5475. /**
  5476. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5477. *
  5478. * @param string 'seriousgame', 'single' or 'multiple'
  5479. *
  5480. * @return bool
  5481. *
  5482. * @author ndiechburg <noel@cblue.be>
  5483. */
  5484. public function set_attempt_mode($mode)
  5485. {
  5486. switch ($mode) {
  5487. case 'seriousgame':
  5488. $sg_mode = 1;
  5489. $prevent_reinit = 1;
  5490. break;
  5491. case 'single':
  5492. $sg_mode = 0;
  5493. $prevent_reinit = 1;
  5494. break;
  5495. case 'multiple':
  5496. $sg_mode = 0;
  5497. $prevent_reinit = 0;
  5498. break;
  5499. default:
  5500. $sg_mode = 0;
  5501. $prevent_reinit = 0;
  5502. break;
  5503. }
  5504. $this->prevent_reinit = $prevent_reinit;
  5505. $this->seriousgame_mode = $sg_mode;
  5506. $table = Database::get_course_table(TABLE_LP_MAIN);
  5507. $sql = "UPDATE $table SET
  5508. prevent_reinit = $prevent_reinit ,
  5509. seriousgame_mode = $sg_mode
  5510. WHERE iid = ".$this->get_id();
  5511. $res = Database::query($sql);
  5512. if ($res) {
  5513. return true;
  5514. } else {
  5515. return false;
  5516. }
  5517. }
  5518. /**
  5519. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5520. *
  5521. * @author ndiechburg <noel@cblue.be>
  5522. */
  5523. public function switch_attempt_mode()
  5524. {
  5525. if ($this->debug > 0) {
  5526. error_log('In learnpath::switch_attempt_mode()', 0);
  5527. }
  5528. $mode = $this->get_attempt_mode();
  5529. switch ($mode) {
  5530. case 'single':
  5531. $next_mode = 'multiple';
  5532. break;
  5533. case 'multiple':
  5534. $next_mode = 'seriousgame';
  5535. break;
  5536. case 'seriousgame':
  5537. $next_mode = 'single';
  5538. break;
  5539. default:
  5540. $next_mode = 'single';
  5541. break;
  5542. }
  5543. $this->set_attempt_mode($next_mode);
  5544. }
  5545. /**
  5546. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5547. * but possibility to do again a completed item.
  5548. *
  5549. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5550. *
  5551. * @author ndiechburg <noel@cblue.be>
  5552. */
  5553. public function set_seriousgame_mode()
  5554. {
  5555. if ($this->debug > 0) {
  5556. error_log('In learnpath::set_seriousgame_mode()', 0);
  5557. }
  5558. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5559. $sql = "SELECT * FROM $lp_table
  5560. WHERE iid = ".$this->get_id();
  5561. $res = Database::query($sql);
  5562. if (Database::num_rows($res) > 0) {
  5563. $row = Database::fetch_array($res);
  5564. $force = $row['seriousgame_mode'];
  5565. if ($force == 1) {
  5566. $force = 0;
  5567. } elseif ($force == 0) {
  5568. $force = 1;
  5569. }
  5570. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5571. WHERE iid = ".$this->get_id();
  5572. Database::query($sql);
  5573. $this->seriousgame_mode = $force;
  5574. return $force;
  5575. } else {
  5576. if ($this->debug > 2) {
  5577. error_log('Problem in set_seriousgame_mode() - could not find LP '.$this->get_id().' in DB', 0);
  5578. }
  5579. }
  5580. return -1;
  5581. }
  5582. /**
  5583. * Updates the "scorm_debug" value that shows or hide the debug window.
  5584. *
  5585. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5586. */
  5587. public function update_scorm_debug()
  5588. {
  5589. if ($this->debug > 0) {
  5590. error_log('In learnpath::update_scorm_debug()', 0);
  5591. }
  5592. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5593. $sql = "SELECT * FROM $lp_table
  5594. WHERE iid = ".$this->get_id();
  5595. $res = Database::query($sql);
  5596. if (Database::num_rows($res) > 0) {
  5597. $row = Database::fetch_array($res);
  5598. $force = $row['debug'];
  5599. if ($force == 1) {
  5600. $force = 0;
  5601. } elseif ($force == 0) {
  5602. $force = 1;
  5603. }
  5604. $sql = "UPDATE $lp_table SET debug = $force
  5605. WHERE iid = ".$this->get_id();
  5606. Database::query($sql);
  5607. $this->scorm_debug = $force;
  5608. return $force;
  5609. } else {
  5610. if ($this->debug > 2) {
  5611. error_log('Problem in update_scorm_debug() - could not find LP '.$this->get_id().' in DB', 0);
  5612. }
  5613. }
  5614. return -1;
  5615. }
  5616. /**
  5617. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5618. *
  5619. * @author Kevin Van Den Haute
  5620. *
  5621. * @param array
  5622. */
  5623. public function tree_array($array)
  5624. {
  5625. if ($this->debug > 1) {
  5626. error_log('In learnpath::tree_array()', 0);
  5627. }
  5628. $array = $this->sort_tree_array($array);
  5629. $this->create_tree_array($array);
  5630. }
  5631. /**
  5632. * Creates an array with the elements of the learning path tree in it.
  5633. *
  5634. * @author Kevin Van Den Haute
  5635. *
  5636. * @param array $array
  5637. * @param int $parent
  5638. * @param int $depth
  5639. * @param array $tmp
  5640. */
  5641. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5642. {
  5643. if ($this->debug > 1) {
  5644. error_log('In learnpath::create_tree_array())', 0);
  5645. }
  5646. if (is_array($array)) {
  5647. for ($i = 0; $i < count($array); $i++) {
  5648. if ($array[$i]['parent_item_id'] == $parent) {
  5649. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5650. $tmp[] = $array[$i]['parent_item_id'];
  5651. $depth++;
  5652. }
  5653. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5654. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5655. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5656. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5657. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5658. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5659. $this->arrMenu[] = [
  5660. 'id' => $array[$i]['id'],
  5661. 'ref' => $ref,
  5662. 'item_type' => $array[$i]['item_type'],
  5663. 'title' => $array[$i]['title'],
  5664. 'path' => $path,
  5665. 'description' => $array[$i]['description'],
  5666. 'parent_item_id' => $array[$i]['parent_item_id'],
  5667. 'previous_item_id' => $array[$i]['previous_item_id'],
  5668. 'next_item_id' => $array[$i]['next_item_id'],
  5669. 'min_score' => $array[$i]['min_score'],
  5670. 'max_score' => $array[$i]['max_score'],
  5671. 'mastery_score' => $array[$i]['mastery_score'],
  5672. 'display_order' => $array[$i]['display_order'],
  5673. 'prerequisite' => $preq,
  5674. 'depth' => $depth,
  5675. 'audio' => $audio,
  5676. 'prerequisite_min_score' => $prerequisiteMinScore,
  5677. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5678. ];
  5679. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5680. }
  5681. }
  5682. }
  5683. }
  5684. /**
  5685. * Sorts a multi dimensional array by parent id and display order.
  5686. *
  5687. * @author Kevin Van Den Haute
  5688. *
  5689. * @param array $array (array with al the learning path items in it)
  5690. *
  5691. * @return array
  5692. */
  5693. public function sort_tree_array($array)
  5694. {
  5695. foreach ($array as $key => $row) {
  5696. $parent[$key] = $row['parent_item_id'];
  5697. $position[$key] = $row['display_order'];
  5698. }
  5699. if (count($array) > 0) {
  5700. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5701. }
  5702. return $array;
  5703. }
  5704. /**
  5705. * Function that creates a html list of learning path items so that we can add audio files to them.
  5706. *
  5707. * @author Kevin Van Den Haute
  5708. *
  5709. * @return string
  5710. */
  5711. public function overview()
  5712. {
  5713. if ($this->debug > 0) {
  5714. error_log('In learnpath::overview()', 0);
  5715. }
  5716. $return = '';
  5717. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5718. // we need to start a form when we want to update all the mp3 files
  5719. if ($update_audio == 'true') {
  5720. $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">';
  5721. }
  5722. $return .= '<div id="message"></div>';
  5723. if (count($this->items) == 0) {
  5724. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5725. } else {
  5726. $return_audio = '<table class="data_table">';
  5727. $return_audio .= '<tr>';
  5728. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5729. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5730. $return_audio .= '</tr>';
  5731. if ($update_audio != 'true') {
  5732. $return .= '<div class="col-md-12">';
  5733. $return .= self::return_new_tree($update_audio);
  5734. $return .= '</div>';
  5735. $return .= Display::div(
  5736. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5737. ['style' => 'float:left; margin-top:15px;width:100%']
  5738. );
  5739. } else {
  5740. $return_audio .= self::return_new_tree($update_audio);
  5741. $return .= $return_audio.'</table>';
  5742. }
  5743. // We need to close the form when we are updating the mp3 files.
  5744. if ($update_audio == 'true') {
  5745. $return .= '<div class="footer-audio">';
  5746. $return .= Display::button(
  5747. 'save_audio',
  5748. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5749. ['class' => 'btn btn-primary', 'type' => 'submit']
  5750. );
  5751. $return .= '</div>';
  5752. }
  5753. }
  5754. // We need to close the form when we are updating the mp3 files.
  5755. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5756. $return .= '</form>';
  5757. }
  5758. return $return;
  5759. }
  5760. /**
  5761. * @param string $update_audio
  5762. *
  5763. * @return array
  5764. */
  5765. public function processBuildMenuElements($update_audio = 'false')
  5766. {
  5767. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5768. $course_id = api_get_course_int_id();
  5769. $table = Database::get_course_table(TABLE_LP_ITEM);
  5770. $sql = "SELECT * FROM $table
  5771. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  5772. $result = Database::query($sql);
  5773. $arrLP = [];
  5774. while ($row = Database::fetch_array($result)) {
  5775. $arrLP[] = [
  5776. 'id' => $row['iid'],
  5777. 'item_type' => $row['item_type'],
  5778. 'title' => Security::remove_XSS($row['title']),
  5779. 'path' => $row['path'],
  5780. 'description' => Security::remove_XSS($row['description']),
  5781. 'parent_item_id' => $row['parent_item_id'],
  5782. 'previous_item_id' => $row['previous_item_id'],
  5783. 'next_item_id' => $row['next_item_id'],
  5784. 'max_score' => $row['max_score'],
  5785. 'min_score' => $row['min_score'],
  5786. 'mastery_score' => $row['mastery_score'],
  5787. 'prerequisite' => $row['prerequisite'],
  5788. 'display_order' => $row['display_order'],
  5789. 'audio' => $row['audio'],
  5790. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  5791. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  5792. ];
  5793. }
  5794. $this->tree_array($arrLP);
  5795. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5796. unset($this->arrMenu);
  5797. $default_data = null;
  5798. $default_content = null;
  5799. $elements = [];
  5800. $return_audio = null;
  5801. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5802. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5803. for ($i = 0; $i < count($arrLP); $i++) {
  5804. $title = $arrLP[$i]['title'];
  5805. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5806. // Link for the documents
  5807. if ($arrLP[$i]['item_type'] == 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5808. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5809. $title_cut = Display::url(
  5810. $title_cut,
  5811. $url,
  5812. [
  5813. 'class' => 'ajax moved',
  5814. 'data-title' => $title,
  5815. 'title' => $title,
  5816. ]
  5817. );
  5818. }
  5819. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5820. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5821. Session::write('pathItem', $arrLP[$i]['path']);
  5822. }
  5823. if (($i % 2) == 0) {
  5824. $oddClass = 'row_odd';
  5825. } else {
  5826. $oddClass = 'row_even';
  5827. }
  5828. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5829. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5830. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5831. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5832. } else {
  5833. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5834. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5835. } else {
  5836. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5837. $icon = Display::return_icon('certificate.png');
  5838. } else {
  5839. $icon = Display::return_icon('folder_document.gif');
  5840. }
  5841. }
  5842. }
  5843. // The audio column.
  5844. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5845. $audio = '';
  5846. if (!$update_audio || $update_audio != 'true') {
  5847. if (empty($arrLP[$i]['audio'])) {
  5848. $audio .= '';
  5849. }
  5850. } else {
  5851. $types = self::getChapterTypes();
  5852. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5853. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5854. if (!empty($arrLP[$i]['audio'])) {
  5855. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5856. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5857. }
  5858. }
  5859. }
  5860. $return_audio .= Display::span($icon.' '.$title).
  5861. Display::tag(
  5862. 'td',
  5863. $audio,
  5864. ['style' => '']
  5865. );
  5866. $return_audio .= '</td>';
  5867. $move_icon = '';
  5868. $move_item_icon = '';
  5869. $edit_icon = '';
  5870. $delete_icon = '';
  5871. $audio_icon = '';
  5872. $prerequisities_icon = '';
  5873. $forumIcon = '';
  5874. $previewIcon = '';
  5875. $pluginCalendarIcon = '';
  5876. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5877. $plugin = null;
  5878. if ($pluginCalendar) {
  5879. $plugin = LearningCalendarPlugin::create();
  5880. }
  5881. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5882. if ($is_allowed_to_edit) {
  5883. if (!$update_audio || $update_audio != 'true') {
  5884. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5885. $move_icon .= '<a class="moved" href="#">';
  5886. $move_icon .= Display::return_icon(
  5887. 'move_everywhere.png',
  5888. get_lang('Move'),
  5889. [],
  5890. ICON_SIZE_TINY
  5891. );
  5892. $move_icon .= '</a>';
  5893. }
  5894. }
  5895. // No edit for this item types
  5896. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5897. if ($arrLP[$i]['item_type'] != 'dir') {
  5898. $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">';
  5899. $edit_icon .= Display::return_icon(
  5900. 'edit.png',
  5901. get_lang('LearnpathEditModule'),
  5902. [],
  5903. ICON_SIZE_TINY
  5904. );
  5905. $edit_icon .= '</a>';
  5906. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5907. $forumThread = null;
  5908. if (isset($this->items[$arrLP[$i]['id']])) {
  5909. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5910. $this->course_int_id,
  5911. $this->lp_session_id
  5912. );
  5913. }
  5914. if ($forumThread) {
  5915. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5916. 'action' => 'dissociate_forum',
  5917. 'id' => $arrLP[$i]['id'],
  5918. 'lp_id' => $this->lp_id,
  5919. ]);
  5920. $forumIcon = Display::url(
  5921. Display::return_icon(
  5922. 'forum.png',
  5923. get_lang('DissociateForumToLPItem'),
  5924. [],
  5925. ICON_SIZE_TINY
  5926. ),
  5927. $forumIconUrl,
  5928. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5929. );
  5930. } else {
  5931. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5932. 'action' => 'create_forum',
  5933. 'id' => $arrLP[$i]['id'],
  5934. 'lp_id' => $this->lp_id,
  5935. ]);
  5936. $forumIcon = Display::url(
  5937. Display::return_icon(
  5938. 'forum.png',
  5939. get_lang('AssociateForumToLPItem'),
  5940. [],
  5941. ICON_SIZE_TINY
  5942. ),
  5943. $forumIconUrl,
  5944. ['class' => 'btn btn-default lp-btn-associate-forum']
  5945. );
  5946. }
  5947. }
  5948. } else {
  5949. $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">';
  5950. $edit_icon .= Display::return_icon(
  5951. 'edit.png',
  5952. get_lang('LearnpathEditModule'),
  5953. [],
  5954. ICON_SIZE_TINY
  5955. );
  5956. $edit_icon .= '</a>';
  5957. }
  5958. } else {
  5959. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5960. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5961. $edit_icon .= Display::return_icon(
  5962. 'edit.png',
  5963. get_lang('Edit'),
  5964. [],
  5965. ICON_SIZE_TINY
  5966. );
  5967. $edit_icon .= '</a>';
  5968. }
  5969. }
  5970. if ($pluginCalendar) {
  5971. $pluginLink = $pluginUrl.
  5972. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5973. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5974. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5975. if ($itemInfo && $itemInfo['value'] == 1) {
  5976. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5977. }
  5978. $pluginCalendarIcon = Display::url(
  5979. $iconCalendar,
  5980. $pluginLink,
  5981. ['class' => 'btn btn-default']
  5982. );
  5983. }
  5984. $delete_icon .= ' <a
  5985. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5986. onclick="return confirmation(\''.addslashes($title).'\');"
  5987. class="btn btn-default">';
  5988. $delete_icon .= Display::return_icon(
  5989. 'delete.png',
  5990. get_lang('LearnpathDeleteModule'),
  5991. [],
  5992. ICON_SIZE_TINY
  5993. );
  5994. $delete_icon .= '</a>';
  5995. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5996. $previewImage = Display::return_icon(
  5997. 'preview_view.png',
  5998. get_lang('Preview'),
  5999. [],
  6000. ICON_SIZE_TINY
  6001. );
  6002. switch ($arrLP[$i]['item_type']) {
  6003. case TOOL_DOCUMENT:
  6004. case TOOL_LP_FINAL_ITEM:
  6005. case TOOL_READOUT_TEXT:
  6006. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  6007. $previewIcon = Display::url(
  6008. $previewImage,
  6009. $urlPreviewLink,
  6010. [
  6011. 'target' => '_blank',
  6012. 'class' => 'btn btn-default',
  6013. 'data-title' => $arrLP[$i]['title'],
  6014. 'title' => $arrLP[$i]['title'],
  6015. ]
  6016. );
  6017. break;
  6018. case TOOL_THREAD:
  6019. case TOOL_FORUM:
  6020. case TOOL_QUIZ:
  6021. case TOOL_STUDENTPUBLICATION:
  6022. case TOOL_LP_FINAL_ITEM:
  6023. case TOOL_LINK:
  6024. //$target = '';
  6025. //$class = 'btn btn-default ajax';
  6026. //if ($arrLP[$i]['item_type'] == TOOL_LINK) {
  6027. $class = 'btn btn-default';
  6028. $target = '_blank';
  6029. //}
  6030. $link = self::rl_get_resource_link_for_learnpath(
  6031. $this->course_int_id,
  6032. $this->lp_id,
  6033. $arrLP[$i]['id'],
  6034. 0
  6035. );
  6036. $previewIcon = Display::url(
  6037. $previewImage,
  6038. $link,
  6039. [
  6040. 'class' => $class,
  6041. 'data-title' => $arrLP[$i]['title'],
  6042. 'title' => $arrLP[$i]['title'],
  6043. 'target' => $target,
  6044. ]
  6045. );
  6046. break;
  6047. default:
  6048. $previewIcon = Display::url(
  6049. $previewImage,
  6050. $url.'&action=view_item',
  6051. ['class' => 'btn btn-default', 'target' => '_blank']
  6052. );
  6053. break;
  6054. }
  6055. if ($arrLP[$i]['item_type'] != 'dir') {
  6056. $prerequisities_icon = Display::url(
  6057. Display::return_icon(
  6058. 'accept.png',
  6059. get_lang('LearnpathPrerequisites'),
  6060. [],
  6061. ICON_SIZE_TINY
  6062. ),
  6063. $url.'&action=edit_item_prereq',
  6064. ['class' => 'btn btn-default']
  6065. );
  6066. if ($arrLP[$i]['item_type'] != 'final_item') {
  6067. $move_item_icon = Display::url(
  6068. Display::return_icon(
  6069. 'move.png',
  6070. get_lang('Move'),
  6071. [],
  6072. ICON_SIZE_TINY
  6073. ),
  6074. $url.'&action=move_item',
  6075. ['class' => 'btn btn-default']
  6076. );
  6077. }
  6078. $audio_icon = Display::url(
  6079. Display::return_icon(
  6080. 'audio.png',
  6081. get_lang('UplUpload'),
  6082. [],
  6083. ICON_SIZE_TINY
  6084. ),
  6085. $url.'&action=add_audio',
  6086. ['class' => 'btn btn-default']
  6087. );
  6088. }
  6089. }
  6090. if ($update_audio != 'true') {
  6091. $row = $move_icon.' '.$icon.
  6092. Display::span($title_cut).
  6093. Display::tag(
  6094. 'div',
  6095. "<div class=\"btn-group btn-group-xs\">
  6096. $previewIcon
  6097. $audio
  6098. $edit_icon
  6099. $pluginCalendarIcon
  6100. $forumIcon
  6101. $prerequisities_icon
  6102. $move_item_icon
  6103. $audio_icon
  6104. $delete_icon
  6105. </div>",
  6106. ['class' => 'btn-toolbar button_actions']
  6107. );
  6108. } else {
  6109. $row =
  6110. Display::span($title.$icon).
  6111. Display::span($audio, ['class' => 'button_actions']);
  6112. }
  6113. $parent_id = $arrLP[$i]['parent_item_id'];
  6114. $default_data[$arrLP[$i]['id']] = $row;
  6115. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  6116. if (empty($parent_id)) {
  6117. $elements[$arrLP[$i]['id']]['data'] = $row;
  6118. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6119. } else {
  6120. $parent_arrays = [];
  6121. if ($arrLP[$i]['depth'] > 1) {
  6122. //Getting list of parents
  6123. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  6124. foreach ($arrLP as $item) {
  6125. if ($item['id'] == $parent_id) {
  6126. if ($item['parent_item_id'] == 0) {
  6127. $parent_id = $item['id'];
  6128. break;
  6129. } else {
  6130. $parent_id = $item['parent_item_id'];
  6131. if (empty($parent_arrays)) {
  6132. $parent_arrays[] = intval($item['id']);
  6133. }
  6134. $parent_arrays[] = $parent_id;
  6135. break;
  6136. }
  6137. }
  6138. }
  6139. }
  6140. }
  6141. if (!empty($parent_arrays)) {
  6142. $parent_arrays = array_reverse($parent_arrays);
  6143. $val = '$elements';
  6144. $x = 0;
  6145. foreach ($parent_arrays as $item) {
  6146. if ($x != count($parent_arrays) - 1) {
  6147. $val .= '["'.$item.'"]["children"]';
  6148. } else {
  6149. $val .= '["'.$item.'"]["children"]';
  6150. }
  6151. $x++;
  6152. }
  6153. $val .= "";
  6154. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  6155. eval($code_str);
  6156. } else {
  6157. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  6158. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  6159. }
  6160. }
  6161. }
  6162. return [
  6163. 'elements' => $elements,
  6164. 'default_data' => $default_data,
  6165. 'default_content' => $default_content,
  6166. 'return_audio' => $return_audio,
  6167. ];
  6168. }
  6169. /**
  6170. * @param string $updateAudio true/false strings
  6171. *
  6172. * @return string
  6173. */
  6174. public function returnLpItemList($updateAudio)
  6175. {
  6176. $result = $this->processBuildMenuElements($updateAudio);
  6177. $html = self::print_recursive(
  6178. $result['elements'],
  6179. $result['default_data'],
  6180. $result['default_content']
  6181. );
  6182. if (!empty($html)) {
  6183. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6184. }
  6185. return $html;
  6186. }
  6187. /**
  6188. * @param string $update_audio
  6189. * @param bool $drop_element_here
  6190. *
  6191. * @return string
  6192. */
  6193. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  6194. {
  6195. $return = '';
  6196. $result = $this->processBuildMenuElements($update_audio);
  6197. $list = '<ul id="lp_item_list">';
  6198. $tree = $this->print_recursive(
  6199. $result['elements'],
  6200. $result['default_data'],
  6201. $result['default_content']
  6202. );
  6203. if (!empty($tree)) {
  6204. $list .= $tree;
  6205. } else {
  6206. if ($drop_element_here) {
  6207. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  6208. }
  6209. }
  6210. $list .= '</ul>';
  6211. $return .= Display::panelCollapse(
  6212. $this->name,
  6213. $list,
  6214. 'scorm-list',
  6215. null,
  6216. 'scorm-list-accordion',
  6217. 'scorm-list-collapse'
  6218. );
  6219. if ($update_audio === 'true') {
  6220. $return = $result['return_audio'];
  6221. }
  6222. return $return;
  6223. }
  6224. /**
  6225. * @param array $elements
  6226. * @param array $default_data
  6227. * @param array $default_content
  6228. *
  6229. * @return string
  6230. */
  6231. public function print_recursive($elements, $default_data, $default_content)
  6232. {
  6233. $return = '';
  6234. foreach ($elements as $key => $item) {
  6235. if (isset($item['load_data']) || empty($item['data'])) {
  6236. $item['data'] = $default_data[$item['load_data']];
  6237. $item['type'] = $default_content[$item['load_data']]['item_type'];
  6238. }
  6239. $sub_list = '';
  6240. if (isset($item['type']) && $item['type'] == 'dir') {
  6241. // empty value
  6242. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  6243. }
  6244. if (empty($item['children'])) {
  6245. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6246. $active = null;
  6247. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  6248. $active = 'active';
  6249. }
  6250. $return .= Display::tag(
  6251. 'li',
  6252. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  6253. ['id' => $key, 'class' => 'record li_container']
  6254. );
  6255. } else {
  6256. // Sections
  6257. $data = '';
  6258. if (isset($item['children'])) {
  6259. $data = self::print_recursive($item['children'], $default_data, $default_content);
  6260. }
  6261. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  6262. $return .= Display::tag(
  6263. 'li',
  6264. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  6265. ['id' => $key, 'class' => 'record li_container']
  6266. );
  6267. }
  6268. }
  6269. return $return;
  6270. }
  6271. /**
  6272. * This function builds the action menu.
  6273. *
  6274. * @param bool $returnContent Optional
  6275. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  6276. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  6277. * @param bool $allowExpand Optional. Allow show the expand/contract button
  6278. *
  6279. * @return string
  6280. */
  6281. public function build_action_menu(
  6282. $returnContent = false,
  6283. $showRequirementButtons = true,
  6284. $isConfigPage = false,
  6285. $allowExpand = true
  6286. ) {
  6287. $actionsLeft = '';
  6288. $actionsRight = '';
  6289. $actionsLeft .= Display::url(
  6290. Display::return_icon(
  6291. 'back.png',
  6292. get_lang('ReturnToLearningPaths'),
  6293. '',
  6294. ICON_SIZE_MEDIUM
  6295. ),
  6296. 'lp_controller.php?'.api_get_cidreq()
  6297. );
  6298. $actionsLeft .= Display::url(
  6299. Display::return_icon(
  6300. 'preview_view.png',
  6301. get_lang('Preview'),
  6302. '',
  6303. ICON_SIZE_MEDIUM
  6304. ),
  6305. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6306. 'action' => 'view',
  6307. 'lp_id' => $this->lp_id,
  6308. 'isStudentView' => 'true',
  6309. ])
  6310. );
  6311. $actionsLeft .= Display::url(
  6312. Display::return_icon(
  6313. 'upload_audio.png',
  6314. get_lang('UpdateAllAudioFragments'),
  6315. '',
  6316. ICON_SIZE_MEDIUM
  6317. ),
  6318. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6319. 'action' => 'admin_view',
  6320. 'lp_id' => $this->lp_id,
  6321. 'updateaudio' => 'true',
  6322. ])
  6323. );
  6324. if (!$isConfigPage) {
  6325. $actionsLeft .= Display::url(
  6326. Display::return_icon(
  6327. 'settings.png',
  6328. get_lang('CourseSettings'),
  6329. '',
  6330. ICON_SIZE_MEDIUM
  6331. ),
  6332. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6333. 'action' => 'edit',
  6334. 'lp_id' => $this->lp_id,
  6335. ])
  6336. );
  6337. } else {
  6338. $actionsLeft .= Display::url(
  6339. Display::return_icon(
  6340. 'edit.png',
  6341. get_lang('Edit'),
  6342. '',
  6343. ICON_SIZE_MEDIUM
  6344. ),
  6345. 'lp_controller.php?'.http_build_query([
  6346. 'action' => 'build',
  6347. 'lp_id' => $this->lp_id,
  6348. ]).'&'.api_get_cidreq()
  6349. );
  6350. }
  6351. if ($allowExpand) {
  6352. $actionsLeft .= Display::url(
  6353. Display::return_icon(
  6354. 'expand.png',
  6355. get_lang('Expand'),
  6356. ['id' => 'expand'],
  6357. ICON_SIZE_MEDIUM
  6358. ).
  6359. Display::return_icon(
  6360. 'contract.png',
  6361. get_lang('Collapse'),
  6362. ['id' => 'contract', 'class' => 'hide'],
  6363. ICON_SIZE_MEDIUM
  6364. ),
  6365. '#',
  6366. ['role' => 'button', 'id' => 'hide_bar_template']
  6367. );
  6368. }
  6369. if ($showRequirementButtons) {
  6370. $buttons = [
  6371. [
  6372. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6373. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6374. 'action' => 'set_previous_step_as_prerequisite',
  6375. 'lp_id' => $this->lp_id,
  6376. ]),
  6377. ],
  6378. [
  6379. 'title' => get_lang('ClearAllPrerequisites'),
  6380. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6381. 'action' => 'clear_prerequisites',
  6382. 'lp_id' => $this->lp_id,
  6383. ]),
  6384. ],
  6385. ];
  6386. $actionsRight = Display::groupButtonWithDropDown(
  6387. get_lang('PrerequisitesOptions'),
  6388. $buttons,
  6389. true
  6390. );
  6391. }
  6392. $toolbar = Display::toolbarAction(
  6393. 'actions-lp-controller',
  6394. [$actionsLeft, $actionsRight]
  6395. );
  6396. if ($returnContent) {
  6397. return $toolbar;
  6398. }
  6399. echo $toolbar;
  6400. }
  6401. /**
  6402. * Creates the default learning path folder.
  6403. *
  6404. * @param array $course
  6405. * @param int $creatorId
  6406. *
  6407. * @return bool
  6408. */
  6409. public static function generate_learning_path_folder($course, $creatorId = 0)
  6410. {
  6411. // Creating learning_path folder
  6412. $dir = '/learning_path';
  6413. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6414. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6415. $folder = false;
  6416. if (!is_dir($filepath.'/'.$dir)) {
  6417. $folderData = create_unexisting_directory(
  6418. $course,
  6419. $creatorId,
  6420. 0,
  6421. null,
  6422. 0,
  6423. $filepath,
  6424. $dir,
  6425. get_lang('LearningPaths'),
  6426. 0
  6427. );
  6428. if (!empty($folderData)) {
  6429. $folder = true;
  6430. }
  6431. } else {
  6432. $folder = true;
  6433. }
  6434. return $folder;
  6435. }
  6436. /**
  6437. * @param array $course
  6438. * @param string $lp_name
  6439. * @param int $creatorId
  6440. *
  6441. * @return array
  6442. */
  6443. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6444. {
  6445. $filepath = '';
  6446. $dir = '/learning_path/';
  6447. if (empty($lp_name)) {
  6448. $lp_name = $this->name;
  6449. }
  6450. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6451. $folder = self::generate_learning_path_folder($course, $creatorId);
  6452. // Limits title size
  6453. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6454. $dir = $dir.$title;
  6455. // Creating LP folder
  6456. $documentId = null;
  6457. if ($folder) {
  6458. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6459. if (!is_dir($filepath.'/'.$dir)) {
  6460. $folderData = create_unexisting_directory(
  6461. $course,
  6462. $creatorId,
  6463. 0,
  6464. 0,
  6465. 0,
  6466. $filepath,
  6467. $dir,
  6468. $lp_name
  6469. );
  6470. if (!empty($folderData)) {
  6471. $folder = true;
  6472. }
  6473. $documentId = $folderData['id'];
  6474. } else {
  6475. $folder = true;
  6476. }
  6477. $dir = $dir.'/';
  6478. if ($folder) {
  6479. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6480. }
  6481. }
  6482. if (empty($documentId)) {
  6483. $dir = api_remove_trailing_slash($dir);
  6484. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6485. }
  6486. $array = [
  6487. 'dir' => $dir,
  6488. 'filepath' => $filepath,
  6489. 'folder' => $folder,
  6490. 'id' => $documentId,
  6491. ];
  6492. return $array;
  6493. }
  6494. /**
  6495. * Create a new document //still needs some finetuning.
  6496. *
  6497. * @param array $courseInfo
  6498. * @param string $content
  6499. * @param string $title
  6500. * @param string $extension
  6501. * @param int $parentId
  6502. * @param int $creatorId creator id
  6503. *
  6504. * @return int
  6505. */
  6506. public function create_document(
  6507. $courseInfo,
  6508. $content = '',
  6509. $title = '',
  6510. $extension = 'html',
  6511. $parentId = 0,
  6512. $creatorId = 0
  6513. ) {
  6514. if (!empty($courseInfo)) {
  6515. $course_id = $courseInfo['real_id'];
  6516. } else {
  6517. $course_id = api_get_course_int_id();
  6518. }
  6519. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6520. $sessionId = api_get_session_id();
  6521. // Generates folder
  6522. $result = $this->generate_lp_folder($courseInfo);
  6523. $dir = $result['dir'];
  6524. if (empty($parentId) || $parentId == '/') {
  6525. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6526. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6527. if ($parentId === '/') {
  6528. $dir = '/';
  6529. }
  6530. // Please, do not modify this dirname formatting.
  6531. if (strstr($dir, '..')) {
  6532. $dir = '/';
  6533. }
  6534. if (!empty($dir[0]) && $dir[0] == '.') {
  6535. $dir = substr($dir, 1);
  6536. }
  6537. if (!empty($dir[0]) && $dir[0] != '/') {
  6538. $dir = '/'.$dir;
  6539. }
  6540. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6541. $dir .= '/';
  6542. }
  6543. } else {
  6544. $parentInfo = DocumentManager::get_document_data_by_id(
  6545. $parentId,
  6546. $courseInfo['code']
  6547. );
  6548. if (!empty($parentInfo)) {
  6549. $dir = $parentInfo['path'].'/';
  6550. }
  6551. }
  6552. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6553. if (!is_dir($filepath)) {
  6554. $dir = '/';
  6555. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6556. }
  6557. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6558. // is already escaped twice when it gets here.
  6559. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6560. if (!empty($title)) {
  6561. $title = api_replace_dangerous_char(stripslashes($title));
  6562. } else {
  6563. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6564. }
  6565. $title = disable_dangerous_file($title);
  6566. $filename = $title;
  6567. $content = !empty($content) ? $content : $_POST['content_lp'];
  6568. $tmp_filename = $filename;
  6569. $i = 0;
  6570. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6571. $tmp_filename = $filename.'_'.++$i;
  6572. }
  6573. $filename = $tmp_filename.'.'.$extension;
  6574. if ($extension == 'html') {
  6575. $content = stripslashes($content);
  6576. $content = str_replace(
  6577. api_get_path(WEB_COURSE_PATH),
  6578. api_get_path(REL_PATH).'courses/',
  6579. $content
  6580. );
  6581. // Change the path of mp3 to absolute.
  6582. // The first regexp deals with :// urls.
  6583. $content = preg_replace(
  6584. "|(flashvars=\"file=)([^:/]+)/|",
  6585. "$1".api_get_path(
  6586. REL_COURSE_PATH
  6587. ).$courseInfo['path'].'/document/',
  6588. $content
  6589. );
  6590. // The second regexp deals with audio/ urls.
  6591. $content = preg_replace(
  6592. "|(flashvars=\"file=)([^/]+)/|",
  6593. "$1".api_get_path(
  6594. REL_COURSE_PATH
  6595. ).$courseInfo['path'].'/document/$2/',
  6596. $content
  6597. );
  6598. // For flv player: To prevent edition problem with firefox,
  6599. // we have to use a strange tip (don't blame me please).
  6600. $content = str_replace(
  6601. '</body>',
  6602. '<style type="text/css">body{}</style></body>',
  6603. $content
  6604. );
  6605. }
  6606. if (!file_exists($filepath.$filename)) {
  6607. if ($fp = @fopen($filepath.$filename, 'w')) {
  6608. fputs($fp, $content);
  6609. fclose($fp);
  6610. $file_size = filesize($filepath.$filename);
  6611. $save_file_path = $dir.$filename;
  6612. $document_id = add_document(
  6613. $courseInfo,
  6614. $save_file_path,
  6615. 'file',
  6616. $file_size,
  6617. $tmp_filename,
  6618. '',
  6619. 0, //readonly
  6620. true,
  6621. null,
  6622. $sessionId,
  6623. $creatorId
  6624. );
  6625. if ($document_id) {
  6626. api_item_property_update(
  6627. $courseInfo,
  6628. TOOL_DOCUMENT,
  6629. $document_id,
  6630. 'DocumentAdded',
  6631. $creatorId,
  6632. null,
  6633. null,
  6634. null,
  6635. null,
  6636. $sessionId
  6637. );
  6638. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6639. $new_title = $originalTitle;
  6640. if ($new_comment || $new_title) {
  6641. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6642. $ct = '';
  6643. if ($new_comment) {
  6644. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6645. }
  6646. if ($new_title) {
  6647. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6648. }
  6649. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6650. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6651. Database::query($sql);
  6652. }
  6653. }
  6654. return $document_id;
  6655. }
  6656. }
  6657. }
  6658. /**
  6659. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6660. *
  6661. * @param array $_course array
  6662. */
  6663. public function edit_document($_course)
  6664. {
  6665. $course_id = api_get_course_int_id();
  6666. $urlAppend = api_get_configuration_value('url_append');
  6667. // Please, do not modify this dirname formatting.
  6668. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6669. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6670. if (strstr($dir, '..')) {
  6671. $dir = '/';
  6672. }
  6673. if (isset($dir[0]) && $dir[0] == '.') {
  6674. $dir = substr($dir, 1);
  6675. }
  6676. if (isset($dir[0]) && $dir[0] != '/') {
  6677. $dir = '/'.$dir;
  6678. }
  6679. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6680. $dir .= '/';
  6681. }
  6682. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6683. if (!is_dir($filepath)) {
  6684. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6685. }
  6686. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6687. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6688. $document_id = (int) $_POST['path'];
  6689. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6690. if (empty($documentInfo)) {
  6691. // Try with iid
  6692. $table = Database::get_course_table(TABLE_DOCUMENT);
  6693. $sql = "SELECT id, path FROM $table
  6694. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6695. $res_doc = Database::query($sql);
  6696. $row = Database::fetch_array($res_doc);
  6697. if ($row) {
  6698. $document_id = $row['id'];
  6699. $documentPath = $row['path'];
  6700. }
  6701. } else {
  6702. $documentPath = $documentInfo['path'];
  6703. }
  6704. $content = stripslashes($_POST['content_lp']);
  6705. $file = $filepath.$documentPath;
  6706. if (!file_exists($file)) {
  6707. return false;
  6708. }
  6709. if ($fp = @fopen($file, 'w')) {
  6710. $content = str_replace(
  6711. api_get_path(WEB_COURSE_PATH),
  6712. $urlAppend.api_get_path(REL_COURSE_PATH),
  6713. $content
  6714. );
  6715. // Change the path of mp3 to absolute.
  6716. // The first regexp deals with :// urls.
  6717. $content = preg_replace(
  6718. "|(flashvars=\"file=)([^:/]+)/|",
  6719. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6720. $content
  6721. );
  6722. // The second regexp deals with audio/ urls.
  6723. $content = preg_replace(
  6724. "|(flashvars=\"file=)([^:/]+)/|",
  6725. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6726. $content
  6727. );
  6728. fputs($fp, $content);
  6729. fclose($fp);
  6730. $sql = "UPDATE $table_doc SET
  6731. title='".Database::escape_string($_POST['title'])."'
  6732. WHERE c_id = $course_id AND id = ".$document_id;
  6733. Database::query($sql);
  6734. }
  6735. }
  6736. }
  6737. /**
  6738. * Displays the selected item, with a panel for manipulating the item.
  6739. *
  6740. * @param int $item_id
  6741. * @param string $msg
  6742. * @param bool $show_actions
  6743. *
  6744. * @return string
  6745. */
  6746. public function display_item($item_id, $msg = null, $show_actions = true)
  6747. {
  6748. $course_id = api_get_course_int_id();
  6749. $return = '';
  6750. if (is_numeric($item_id)) {
  6751. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6752. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6753. WHERE lp.iid = ".intval($item_id);
  6754. $result = Database::query($sql);
  6755. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6756. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6757. // Prevents wrong parent selection for document, see Bug#1251.
  6758. if ($row['item_type'] != 'dir') {
  6759. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6760. }
  6761. if ($show_actions) {
  6762. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6763. }
  6764. $return .= '<div style="padding:10px;">';
  6765. if ($msg != '') {
  6766. $return .= $msg;
  6767. }
  6768. $return .= '<h3>'.$row['title'].'</h3>';
  6769. switch ($row['item_type']) {
  6770. case TOOL_THREAD:
  6771. $link = $this->rl_get_resource_link_for_learnpath(
  6772. $course_id,
  6773. $row['lp_id'],
  6774. $item_id,
  6775. 0
  6776. );
  6777. $return .= Display::url(
  6778. get_lang('GoToThread'),
  6779. $link,
  6780. ['class' => 'btn btn-primary']
  6781. );
  6782. break;
  6783. case TOOL_FORUM:
  6784. $return .= Display::url(
  6785. get_lang('GoToForum'),
  6786. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6787. ['class' => 'btn btn-primary']
  6788. );
  6789. break;
  6790. case TOOL_QUIZ:
  6791. if (!empty($row['path'])) {
  6792. $exercise = new Exercise();
  6793. $exercise->read($row['path']);
  6794. $return .= $exercise->description.'<br />';
  6795. $return .= Display::url(
  6796. get_lang('GoToExercise'),
  6797. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6798. ['class' => 'btn btn-primary']
  6799. );
  6800. }
  6801. break;
  6802. case TOOL_LP_FINAL_ITEM:
  6803. $return .= $this->getSavedFinalItem();
  6804. break;
  6805. case TOOL_DOCUMENT:
  6806. case TOOL_READOUT_TEXT:
  6807. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6808. $sql_doc = "SELECT path FROM $tbl_doc
  6809. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6810. $result = Database::query($sql_doc);
  6811. $path_file = Database::result($result, 0, 0);
  6812. $path_parts = pathinfo($path_file);
  6813. // TODO: Correct the following naive comparisons.
  6814. if (in_array($path_parts['extension'], [
  6815. 'html',
  6816. 'txt',
  6817. 'png',
  6818. 'jpg',
  6819. 'JPG',
  6820. 'jpeg',
  6821. 'JPEG',
  6822. 'gif',
  6823. 'swf',
  6824. 'pdf',
  6825. 'htm',
  6826. ])) {
  6827. $return .= $this->display_document($row['path'], true, true);
  6828. }
  6829. break;
  6830. case TOOL_HOTPOTATOES:
  6831. $return .= $this->display_document($row['path'], false, true);
  6832. break;
  6833. }
  6834. $return .= '</div>';
  6835. }
  6836. }
  6837. return $return;
  6838. }
  6839. /**
  6840. * Shows the needed forms for editing a specific item.
  6841. *
  6842. * @param int $item_id
  6843. *
  6844. * @throws Exception
  6845. * @throws HTML_QuickForm_Error
  6846. *
  6847. * @return string
  6848. */
  6849. public function display_edit_item($item_id)
  6850. {
  6851. $course_id = api_get_course_int_id();
  6852. $return = '';
  6853. $item_id = (int) $item_id;
  6854. if (empty($item_id)) {
  6855. return '';
  6856. }
  6857. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6858. $sql = "SELECT * FROM $tbl_lp_item
  6859. WHERE iid = ".$item_id;
  6860. $res = Database::query($sql);
  6861. $row = Database::fetch_array($res);
  6862. switch ($row['item_type']) {
  6863. case 'dir':
  6864. case 'asset':
  6865. case 'sco':
  6866. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6867. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6868. $return .= $this->display_item_form(
  6869. $row['item_type'],
  6870. get_lang('EditCurrentChapter').' :',
  6871. 'edit',
  6872. $item_id,
  6873. $row
  6874. );
  6875. } else {
  6876. $return .= $this->display_item_form(
  6877. $row['item_type'],
  6878. get_lang('EditCurrentChapter').' :',
  6879. 'edit_item',
  6880. $item_id,
  6881. $row
  6882. );
  6883. }
  6884. break;
  6885. case TOOL_DOCUMENT:
  6886. case TOOL_READOUT_TEXT:
  6887. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6888. $sql = "SELECT lp.*, doc.path as dir
  6889. FROM $tbl_lp_item as lp
  6890. LEFT JOIN $tbl_doc as doc
  6891. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6892. WHERE
  6893. doc.c_id = $course_id AND
  6894. lp.iid = ".$item_id;
  6895. $res_step = Database::query($sql);
  6896. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6897. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6898. if ($row['item_type'] === TOOL_DOCUMENT) {
  6899. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6900. }
  6901. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6902. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6903. }
  6904. break;
  6905. case TOOL_LINK:
  6906. $linkId = (int) $row['path'];
  6907. if (!empty($linkId)) {
  6908. $table = Database::get_course_table(TABLE_LINK);
  6909. $sql = 'SELECT url FROM '.$table.'
  6910. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6911. $res_link = Database::query($sql);
  6912. $row_link = Database::fetch_array($res_link);
  6913. if (empty($row_link)) {
  6914. // Try with id
  6915. $sql = 'SELECT url FROM '.$table.'
  6916. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6917. $res_link = Database::query($sql);
  6918. $row_link = Database::fetch_array($res_link);
  6919. }
  6920. if (is_array($row_link)) {
  6921. $row['url'] = $row_link['url'];
  6922. }
  6923. }
  6924. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6925. $return .= $this->display_link_form('edit', $item_id, $row);
  6926. break;
  6927. case TOOL_LP_FINAL_ITEM:
  6928. Session::write('finalItem', true);
  6929. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6930. $sql = "SELECT lp.*, doc.path as dir
  6931. FROM $tbl_lp_item as lp
  6932. LEFT JOIN $tbl_doc as doc
  6933. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6934. WHERE
  6935. doc.c_id = $course_id AND
  6936. lp.iid = ".$item_id;
  6937. $res_step = Database::query($sql);
  6938. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6939. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6940. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6941. break;
  6942. case TOOL_QUIZ:
  6943. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6944. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6945. break;
  6946. case TOOL_HOTPOTATOES:
  6947. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6948. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6949. break;
  6950. case TOOL_STUDENTPUBLICATION:
  6951. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6952. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6953. break;
  6954. case TOOL_FORUM:
  6955. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6956. $return .= $this->display_forum_form('edit', $item_id, $row);
  6957. break;
  6958. case TOOL_THREAD:
  6959. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6960. $return .= $this->display_thread_form('edit', $item_id, $row);
  6961. break;
  6962. }
  6963. return $return;
  6964. }
  6965. /**
  6966. * Function that displays a list with al the resources that
  6967. * could be added to the learning path.
  6968. *
  6969. * @throws Exception
  6970. * @throws HTML_QuickForm_Error
  6971. *
  6972. * @return bool
  6973. */
  6974. public function display_resources()
  6975. {
  6976. $course_code = api_get_course_id();
  6977. // Get all the docs.
  6978. $documents = $this->get_documents(true);
  6979. // Get all the exercises.
  6980. $exercises = $this->get_exercises();
  6981. // Get all the links.
  6982. $links = $this->get_links();
  6983. // Get all the student publications.
  6984. $works = $this->get_student_publications();
  6985. // Get all the forums.
  6986. $forums = $this->get_forums(null, $course_code);
  6987. // Get the final item form (see BT#11048) .
  6988. $finish = $this->getFinalItemForm();
  6989. $headers = [
  6990. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6991. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6992. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6993. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6994. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6995. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6996. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6997. ];
  6998. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6999. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  7000. echo Display::tabs(
  7001. $headers,
  7002. [
  7003. $documents,
  7004. $exercises,
  7005. $links,
  7006. $works,
  7007. $forums,
  7008. $dir,
  7009. $finish,
  7010. ],
  7011. 'resource_tab'
  7012. );
  7013. return true;
  7014. }
  7015. /**
  7016. * Returns the extension of a document.
  7017. *
  7018. * @param string $filename
  7019. *
  7020. * @return string Extension (part after the last dot)
  7021. */
  7022. public function get_extension($filename)
  7023. {
  7024. $explode = explode('.', $filename);
  7025. return $explode[count($explode) - 1];
  7026. }
  7027. /**
  7028. * Displays a document by id.
  7029. *
  7030. * @param int $id
  7031. * @param bool $show_title
  7032. * @param bool $iframe
  7033. * @param bool $edit_link
  7034. *
  7035. * @return string
  7036. */
  7037. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  7038. {
  7039. $_course = api_get_course_info();
  7040. $course_id = api_get_course_int_id();
  7041. $id = (int) $id;
  7042. $return = '';
  7043. $table = Database::get_course_table(TABLE_DOCUMENT);
  7044. $sql_doc = "SELECT * FROM $table
  7045. WHERE c_id = $course_id AND iid = $id";
  7046. $res_doc = Database::query($sql_doc);
  7047. $row_doc = Database::fetch_array($res_doc);
  7048. // TODO: Add a path filter.
  7049. if ($iframe) {
  7050. $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>';
  7051. } else {
  7052. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  7053. }
  7054. return $return;
  7055. }
  7056. /**
  7057. * Return HTML form to add/edit a quiz.
  7058. *
  7059. * @param string $action Action (add/edit)
  7060. * @param int $id Item ID if already exists
  7061. * @param mixed $extra_info Extra information (quiz ID if integer)
  7062. *
  7063. * @throws Exception
  7064. *
  7065. * @return string HTML form
  7066. */
  7067. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  7068. {
  7069. $course_id = api_get_course_int_id();
  7070. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7071. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  7072. if ($id != 0 && is_array($extra_info)) {
  7073. $item_title = $extra_info['title'];
  7074. $item_description = $extra_info['description'];
  7075. } elseif (is_numeric($extra_info)) {
  7076. $sql = "SELECT title, description
  7077. FROM $tbl_quiz
  7078. WHERE c_id = $course_id AND iid = ".$extra_info;
  7079. $result = Database::query($sql);
  7080. $row = Database::fetch_array($result);
  7081. $item_title = $row['title'];
  7082. $item_description = $row['description'];
  7083. } else {
  7084. $item_title = '';
  7085. $item_description = '';
  7086. }
  7087. $item_title = Security::remove_XSS($item_title);
  7088. $item_description = Security::remove_XSS($item_description);
  7089. if ($id != 0 && is_array($extra_info)) {
  7090. $parent = $extra_info['parent_item_id'];
  7091. } else {
  7092. $parent = 0;
  7093. }
  7094. $sql = "SELECT * FROM $tbl_lp_item
  7095. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7096. $result = Database::query($sql);
  7097. $arrLP = [];
  7098. while ($row = Database::fetch_array($result)) {
  7099. $arrLP[] = [
  7100. 'id' => $row['iid'],
  7101. 'item_type' => $row['item_type'],
  7102. 'title' => $row['title'],
  7103. 'path' => $row['path'],
  7104. 'description' => $row['description'],
  7105. 'parent_item_id' => $row['parent_item_id'],
  7106. 'previous_item_id' => $row['previous_item_id'],
  7107. 'next_item_id' => $row['next_item_id'],
  7108. 'display_order' => $row['display_order'],
  7109. 'max_score' => $row['max_score'],
  7110. 'min_score' => $row['min_score'],
  7111. 'mastery_score' => $row['mastery_score'],
  7112. 'prerequisite' => $row['prerequisite'],
  7113. 'max_time_allowed' => $row['max_time_allowed'],
  7114. ];
  7115. }
  7116. $this->tree_array($arrLP);
  7117. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7118. unset($this->arrMenu);
  7119. $form = new FormValidator(
  7120. 'quiz_form',
  7121. 'POST',
  7122. $this->getCurrentBuildingModeURL()
  7123. );
  7124. $defaults = [];
  7125. if ($action == 'add') {
  7126. $legend = get_lang('CreateTheExercise');
  7127. } elseif ($action == 'move') {
  7128. $legend = get_lang('MoveTheCurrentExercise');
  7129. } else {
  7130. $legend = get_lang('EditCurrentExecice');
  7131. }
  7132. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7133. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  7134. }
  7135. $form->addHeader($legend);
  7136. if ($action != 'move') {
  7137. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle']);
  7138. $defaults['title'] = $item_title;
  7139. }
  7140. // Select for Parent item, root or chapter
  7141. $selectParent = $form->addSelect(
  7142. 'parent',
  7143. get_lang('Parent'),
  7144. [],
  7145. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7146. );
  7147. $selectParent->addOption($this->name, 0);
  7148. $arrHide = [
  7149. $id,
  7150. ];
  7151. for ($i = 0; $i < count($arrLP); $i++) {
  7152. if ($action != 'add') {
  7153. if (
  7154. ($arrLP[$i]['item_type'] == 'dir') &&
  7155. !in_array($arrLP[$i]['id'], $arrHide) &&
  7156. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7157. ) {
  7158. $selectParent->addOption(
  7159. $arrLP[$i]['title'],
  7160. $arrLP[$i]['id'],
  7161. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7162. );
  7163. if ($parent == $arrLP[$i]['id']) {
  7164. $selectParent->setSelected($arrLP[$i]['id']);
  7165. }
  7166. } else {
  7167. $arrHide[] = $arrLP[$i]['id'];
  7168. }
  7169. } else {
  7170. if ($arrLP[$i]['item_type'] == 'dir') {
  7171. $selectParent->addOption(
  7172. $arrLP[$i]['title'],
  7173. $arrLP[$i]['id'],
  7174. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7175. );
  7176. if ($parent == $arrLP[$i]['id']) {
  7177. $selectParent->setSelected($arrLP[$i]['id']);
  7178. }
  7179. }
  7180. }
  7181. }
  7182. if (is_array($arrLP)) {
  7183. reset($arrLP);
  7184. }
  7185. $selectPrevious = $form->addSelect(
  7186. 'previous',
  7187. get_lang('Position'),
  7188. [],
  7189. ['id' => 'previous']
  7190. );
  7191. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7192. for ($i = 0; $i < count($arrLP); $i++) {
  7193. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7194. $arrLP[$i]['id'] != $id
  7195. ) {
  7196. $selectPrevious->addOption(
  7197. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7198. $arrLP[$i]['id']
  7199. );
  7200. if (is_array($extra_info)) {
  7201. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7202. $selectPrevious->setSelected($arrLP[$i]['id']);
  7203. }
  7204. } elseif ($action == 'add') {
  7205. $selectPrevious->setSelected($arrLP[$i]['id']);
  7206. }
  7207. }
  7208. }
  7209. if ($action != 'move') {
  7210. $arrHide = [];
  7211. for ($i = 0; $i < count($arrLP); $i++) {
  7212. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7213. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7214. }
  7215. }
  7216. }
  7217. if ($action == 'add') {
  7218. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  7219. } else {
  7220. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  7221. }
  7222. if ($action == 'move') {
  7223. $form->addHidden('title', $item_title);
  7224. $form->addHidden('description', $item_description);
  7225. }
  7226. if (is_numeric($extra_info)) {
  7227. $form->addHidden('path', $extra_info);
  7228. } elseif (is_array($extra_info)) {
  7229. $form->addHidden('path', $extra_info['path']);
  7230. }
  7231. $form->addHidden('type', TOOL_QUIZ);
  7232. $form->addHidden('post_time', time());
  7233. $form->setDefaults($defaults);
  7234. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7235. }
  7236. /**
  7237. * Addition of Hotpotatoes tests.
  7238. *
  7239. * @param string $action
  7240. * @param int $id Internal ID of the item
  7241. * @param string $extra_info
  7242. *
  7243. * @return string HTML structure to display the hotpotatoes addition formular
  7244. */
  7245. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  7246. {
  7247. $course_id = api_get_course_int_id();
  7248. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  7249. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7250. if ($id != 0 && is_array($extra_info)) {
  7251. $item_title = stripslashes($extra_info['title']);
  7252. $item_description = stripslashes($extra_info['description']);
  7253. } elseif (is_numeric($extra_info)) {
  7254. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  7255. $sql = "SELECT * FROM ".$TBL_DOCUMENT."
  7256. WHERE
  7257. c_id = ".$course_id." AND
  7258. path LIKE '".$uploadPath."/%/%htm%' AND
  7259. iid = ".(int) $extra_info."
  7260. ORDER BY iid ASC";
  7261. $res_hot = Database::query($sql);
  7262. $row = Database::fetch_array($res_hot);
  7263. $item_title = $row['title'];
  7264. $item_description = $row['description'];
  7265. if (!empty($row['comment'])) {
  7266. $item_title = $row['comment'];
  7267. }
  7268. } else {
  7269. $item_title = '';
  7270. $item_description = '';
  7271. }
  7272. if ($id != 0 && is_array($extra_info)) {
  7273. $parent = $extra_info['parent_item_id'];
  7274. } else {
  7275. $parent = 0;
  7276. }
  7277. $sql = "SELECT * FROM $tbl_lp_item
  7278. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7279. $result = Database::query($sql);
  7280. $arrLP = [];
  7281. while ($row = Database::fetch_array($result)) {
  7282. $arrLP[] = [
  7283. 'id' => $row['id'],
  7284. 'item_type' => $row['item_type'],
  7285. 'title' => $row['title'],
  7286. 'path' => $row['path'],
  7287. 'description' => $row['description'],
  7288. 'parent_item_id' => $row['parent_item_id'],
  7289. 'previous_item_id' => $row['previous_item_id'],
  7290. 'next_item_id' => $row['next_item_id'],
  7291. 'display_order' => $row['display_order'],
  7292. 'max_score' => $row['max_score'],
  7293. 'min_score' => $row['min_score'],
  7294. 'mastery_score' => $row['mastery_score'],
  7295. 'prerequisite' => $row['prerequisite'],
  7296. 'max_time_allowed' => $row['max_time_allowed'],
  7297. ];
  7298. }
  7299. $legend = '<legend>';
  7300. if ($action == 'add') {
  7301. $legend .= get_lang('CreateTheExercise');
  7302. } elseif ($action == 'move') {
  7303. $legend .= get_lang('MoveTheCurrentExercise');
  7304. } else {
  7305. $legend .= get_lang('EditCurrentExecice');
  7306. }
  7307. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7308. $legend .= Display:: return_message(
  7309. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  7310. );
  7311. }
  7312. $legend .= '</legend>';
  7313. $return = '<form method="POST">';
  7314. $return .= $legend;
  7315. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  7316. $return .= '<tr>';
  7317. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  7318. $return .= '<td class="input">';
  7319. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  7320. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  7321. $arrHide = [
  7322. $id,
  7323. ];
  7324. if (count($arrLP) > 0) {
  7325. for ($i = 0; $i < count($arrLP); $i++) {
  7326. if ($action != 'add') {
  7327. if ($arrLP[$i]['item_type'] == 'dir' &&
  7328. !in_array($arrLP[$i]['id'], $arrHide) &&
  7329. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7330. ) {
  7331. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7332. } else {
  7333. $arrHide[] = $arrLP[$i]['id'];
  7334. }
  7335. } else {
  7336. if ($arrLP[$i]['item_type'] == 'dir') {
  7337. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  7338. }
  7339. }
  7340. }
  7341. reset($arrLP);
  7342. }
  7343. $return .= '</select>';
  7344. $return .= '</td>';
  7345. $return .= '</tr>';
  7346. $return .= '<tr>';
  7347. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  7348. $return .= '<td class="input">';
  7349. $return .= '<select id="previous" name="previous" size="1">';
  7350. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  7351. for ($i = 0; $i < count($arrLP); $i++) {
  7352. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7353. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7354. $selected = 'selected="selected" ';
  7355. } elseif ($action == 'add') {
  7356. $selected = 'selected="selected" ';
  7357. } else {
  7358. $selected = '';
  7359. }
  7360. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  7361. }
  7362. }
  7363. $return .= '</select>';
  7364. $return .= '</td>';
  7365. $return .= '</tr>';
  7366. if ($action != 'move') {
  7367. $return .= '<tr>';
  7368. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7369. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7370. $return .= '</tr>';
  7371. $id_prerequisite = 0;
  7372. if (is_array($arrLP) && count($arrLP) > 0) {
  7373. foreach ($arrLP as $key => $value) {
  7374. if ($value['id'] == $id) {
  7375. $id_prerequisite = $value['prerequisite'];
  7376. break;
  7377. }
  7378. }
  7379. $arrHide = [];
  7380. for ($i = 0; $i < count($arrLP); $i++) {
  7381. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7382. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7383. }
  7384. }
  7385. }
  7386. }
  7387. $return .= '<tr>';
  7388. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7389. get_lang('SaveHotpotatoes').'</button></td>';
  7390. $return .= '</tr>';
  7391. $return .= '</table>';
  7392. if ($action == 'move') {
  7393. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7394. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7395. }
  7396. if (is_numeric($extra_info)) {
  7397. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7398. } elseif (is_array($extra_info)) {
  7399. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7400. }
  7401. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7402. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7403. $return .= '</form>';
  7404. return $return;
  7405. }
  7406. /**
  7407. * Return the form to display the forum edit/add option.
  7408. *
  7409. * @param string $action
  7410. * @param int $id ID of the lp_item if already exists
  7411. * @param string $extra_info
  7412. *
  7413. * @throws Exception
  7414. *
  7415. * @return string HTML form
  7416. */
  7417. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7418. {
  7419. $course_id = api_get_course_int_id();
  7420. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7421. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7422. if ($id != 0 && is_array($extra_info)) {
  7423. $item_title = stripslashes($extra_info['title']);
  7424. } elseif (is_numeric($extra_info)) {
  7425. $sql = "SELECT forum_title as title, forum_comment as comment
  7426. FROM ".$tbl_forum."
  7427. WHERE c_id = ".$course_id." AND forum_id = ".$extra_info;
  7428. $result = Database::query($sql);
  7429. $row = Database::fetch_array($result);
  7430. $item_title = $row['title'];
  7431. $item_description = $row['comment'];
  7432. } else {
  7433. $item_title = '';
  7434. $item_description = '';
  7435. }
  7436. if ($id != 0 && is_array($extra_info)) {
  7437. $parent = $extra_info['parent_item_id'];
  7438. } else {
  7439. $parent = 0;
  7440. }
  7441. $sql = "SELECT * FROM $tbl_lp_item
  7442. WHERE
  7443. c_id = $course_id AND
  7444. lp_id = ".$this->lp_id;
  7445. $result = Database::query($sql);
  7446. $arrLP = [];
  7447. while ($row = Database::fetch_array($result)) {
  7448. $arrLP[] = [
  7449. 'id' => $row['iid'],
  7450. 'item_type' => $row['item_type'],
  7451. 'title' => $row['title'],
  7452. 'path' => $row['path'],
  7453. 'description' => $row['description'],
  7454. 'parent_item_id' => $row['parent_item_id'],
  7455. 'previous_item_id' => $row['previous_item_id'],
  7456. 'next_item_id' => $row['next_item_id'],
  7457. 'display_order' => $row['display_order'],
  7458. 'max_score' => $row['max_score'],
  7459. 'min_score' => $row['min_score'],
  7460. 'mastery_score' => $row['mastery_score'],
  7461. 'prerequisite' => $row['prerequisite'],
  7462. ];
  7463. }
  7464. $this->tree_array($arrLP);
  7465. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7466. unset($this->arrMenu);
  7467. if ($action == 'add') {
  7468. $legend = get_lang('CreateTheForum');
  7469. } elseif ($action == 'move') {
  7470. $legend = get_lang('MoveTheCurrentForum');
  7471. } else {
  7472. $legend = get_lang('EditCurrentForum');
  7473. }
  7474. $form = new FormValidator(
  7475. 'forum_form',
  7476. 'POST',
  7477. $this->getCurrentBuildingModeURL()
  7478. );
  7479. $defaults = [];
  7480. $form->addHeader($legend);
  7481. if ($action != 'move') {
  7482. $form->addText(
  7483. 'title',
  7484. get_lang('Title'),
  7485. true,
  7486. ['id' => 'idTitle', 'class' => 'learnpath_item_form']
  7487. );
  7488. $defaults['title'] = $item_title;
  7489. }
  7490. $selectParent = $form->addSelect(
  7491. 'parent',
  7492. get_lang('Parent'),
  7493. [],
  7494. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7495. );
  7496. $selectParent->addOption($this->name, 0);
  7497. $arrHide = [
  7498. $id,
  7499. ];
  7500. for ($i = 0; $i < count($arrLP); $i++) {
  7501. if ($action != 'add') {
  7502. if ($arrLP[$i]['item_type'] == 'dir' &&
  7503. !in_array($arrLP[$i]['id'], $arrHide) &&
  7504. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7505. ) {
  7506. $selectParent->addOption(
  7507. $arrLP[$i]['title'],
  7508. $arrLP[$i]['id'],
  7509. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7510. );
  7511. if ($parent == $arrLP[$i]['id']) {
  7512. $selectParent->setSelected($arrLP[$i]['id']);
  7513. }
  7514. } else {
  7515. $arrHide[] = $arrLP[$i]['id'];
  7516. }
  7517. } else {
  7518. if ($arrLP[$i]['item_type'] == 'dir') {
  7519. $selectParent->addOption(
  7520. $arrLP[$i]['title'],
  7521. $arrLP[$i]['id'],
  7522. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7523. );
  7524. if ($parent == $arrLP[$i]['id']) {
  7525. $selectParent->setSelected($arrLP[$i]['id']);
  7526. }
  7527. }
  7528. }
  7529. }
  7530. if (is_array($arrLP)) {
  7531. reset($arrLP);
  7532. }
  7533. $selectPrevious = $form->addSelect(
  7534. 'previous',
  7535. get_lang('Position'),
  7536. [],
  7537. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7538. );
  7539. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7540. for ($i = 0; $i < count($arrLP); $i++) {
  7541. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7542. $arrLP[$i]['id'] != $id
  7543. ) {
  7544. $selectPrevious->addOption(
  7545. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7546. $arrLP[$i]['id']
  7547. );
  7548. if (isset($extra_info['previous_item_id']) &&
  7549. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7550. ) {
  7551. $selectPrevious->setSelected($arrLP[$i]['id']);
  7552. } elseif ($action == 'add') {
  7553. $selectPrevious->setSelected($arrLP[$i]['id']);
  7554. }
  7555. }
  7556. }
  7557. if ($action != 'move') {
  7558. $id_prerequisite = 0;
  7559. if (is_array($arrLP)) {
  7560. foreach ($arrLP as $key => $value) {
  7561. if ($value['id'] == $id) {
  7562. $id_prerequisite = $value['prerequisite'];
  7563. break;
  7564. }
  7565. }
  7566. }
  7567. $arrHide = [];
  7568. for ($i = 0; $i < count($arrLP); $i++) {
  7569. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7570. if (isset($extra_info['previous_item_id']) &&
  7571. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7572. ) {
  7573. $s_selected_position = $arrLP[$i]['id'];
  7574. } elseif ($action == 'add') {
  7575. $s_selected_position = 0;
  7576. }
  7577. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7578. }
  7579. }
  7580. }
  7581. if ($action == 'add') {
  7582. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7583. } else {
  7584. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7585. }
  7586. if ($action == 'move') {
  7587. $form->addHidden('title', $item_title);
  7588. $form->addHidden('description', $item_description);
  7589. }
  7590. if (is_numeric($extra_info)) {
  7591. $form->addHidden('path', $extra_info);
  7592. } elseif (is_array($extra_info)) {
  7593. $form->addHidden('path', $extra_info['path']);
  7594. }
  7595. $form->addHidden('type', TOOL_FORUM);
  7596. $form->addHidden('post_time', time());
  7597. $form->setDefaults($defaults);
  7598. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7599. }
  7600. /**
  7601. * Return HTML form to add/edit forum threads.
  7602. *
  7603. * @param string $action
  7604. * @param int $id Item ID if already exists in learning path
  7605. * @param string $extra_info
  7606. *
  7607. * @throws Exception
  7608. *
  7609. * @return string HTML form
  7610. */
  7611. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7612. {
  7613. $course_id = api_get_course_int_id();
  7614. if (empty($course_id)) {
  7615. return null;
  7616. }
  7617. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7618. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7619. if ($id != 0 && is_array($extra_info)) {
  7620. $item_title = stripslashes($extra_info['title']);
  7621. } elseif (is_numeric($extra_info)) {
  7622. $sql = "SELECT thread_title as title FROM $tbl_forum
  7623. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7624. $result = Database::query($sql);
  7625. $row = Database::fetch_array($result);
  7626. $item_title = $row['title'];
  7627. $item_description = '';
  7628. } else {
  7629. $item_title = '';
  7630. $item_description = '';
  7631. }
  7632. if ($id != 0 && is_array($extra_info)) {
  7633. $parent = $extra_info['parent_item_id'];
  7634. } else {
  7635. $parent = 0;
  7636. }
  7637. $sql = "SELECT * FROM $tbl_lp_item
  7638. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  7639. $result = Database::query($sql);
  7640. $arrLP = [];
  7641. while ($row = Database::fetch_array($result)) {
  7642. $arrLP[] = [
  7643. 'id' => $row['iid'],
  7644. 'item_type' => $row['item_type'],
  7645. 'title' => $row['title'],
  7646. 'path' => $row['path'],
  7647. 'description' => $row['description'],
  7648. 'parent_item_id' => $row['parent_item_id'],
  7649. 'previous_item_id' => $row['previous_item_id'],
  7650. 'next_item_id' => $row['next_item_id'],
  7651. 'display_order' => $row['display_order'],
  7652. 'max_score' => $row['max_score'],
  7653. 'min_score' => $row['min_score'],
  7654. 'mastery_score' => $row['mastery_score'],
  7655. 'prerequisite' => $row['prerequisite'],
  7656. ];
  7657. }
  7658. $this->tree_array($arrLP);
  7659. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7660. unset($this->arrMenu);
  7661. $form = new FormValidator(
  7662. 'thread_form',
  7663. 'POST',
  7664. $this->getCurrentBuildingModeURL()
  7665. );
  7666. $defaults = [];
  7667. if ($action == 'add') {
  7668. $legend = get_lang('CreateTheForum');
  7669. } elseif ($action == 'move') {
  7670. $legend = get_lang('MoveTheCurrentForum');
  7671. } else {
  7672. $legend = get_lang('EditCurrentForum');
  7673. }
  7674. $form->addHeader($legend);
  7675. $selectParent = $form->addSelect(
  7676. 'parent',
  7677. get_lang('Parent'),
  7678. [],
  7679. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7680. );
  7681. $selectParent->addOption($this->name, 0);
  7682. $arrHide = [
  7683. $id,
  7684. ];
  7685. for ($i = 0; $i < count($arrLP); $i++) {
  7686. if ($action != 'add') {
  7687. if (
  7688. ($arrLP[$i]['item_type'] == 'dir') &&
  7689. !in_array($arrLP[$i]['id'], $arrHide) &&
  7690. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7691. ) {
  7692. $selectParent->addOption(
  7693. $arrLP[$i]['title'],
  7694. $arrLP[$i]['id'],
  7695. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7696. );
  7697. if ($parent == $arrLP[$i]['id']) {
  7698. $selectParent->setSelected($arrLP[$i]['id']);
  7699. }
  7700. } else {
  7701. $arrHide[] = $arrLP[$i]['id'];
  7702. }
  7703. } else {
  7704. if ($arrLP[$i]['item_type'] == 'dir') {
  7705. $selectParent->addOption(
  7706. $arrLP[$i]['title'],
  7707. $arrLP[$i]['id'],
  7708. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7709. );
  7710. if ($parent == $arrLP[$i]['id']) {
  7711. $selectParent->setSelected($arrLP[$i]['id']);
  7712. }
  7713. }
  7714. }
  7715. }
  7716. if ($arrLP != null) {
  7717. reset($arrLP);
  7718. }
  7719. $selectPrevious = $form->addSelect(
  7720. 'previous',
  7721. get_lang('Position'),
  7722. [],
  7723. ['id' => 'previous']
  7724. );
  7725. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7726. for ($i = 0; $i < count($arrLP); $i++) {
  7727. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7728. $selectPrevious->addOption(
  7729. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7730. $arrLP[$i]['id']
  7731. );
  7732. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7733. $selectPrevious->setSelected($arrLP[$i]['id']);
  7734. } elseif ($action == 'add') {
  7735. $selectPrevious->setSelected($arrLP[$i]['id']);
  7736. }
  7737. }
  7738. }
  7739. if ($action != 'move') {
  7740. $form->addText(
  7741. 'title',
  7742. get_lang('Title'),
  7743. true,
  7744. ['id' => 'idTitle']
  7745. );
  7746. $defaults['title'] = $item_title;
  7747. $id_prerequisite = 0;
  7748. if ($arrLP != null) {
  7749. foreach ($arrLP as $key => $value) {
  7750. if ($value['id'] == $id) {
  7751. $id_prerequisite = $value['prerequisite'];
  7752. break;
  7753. }
  7754. }
  7755. }
  7756. $arrHide = [];
  7757. $s_selected_position = 0;
  7758. for ($i = 0; $i < count($arrLP); $i++) {
  7759. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7760. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7761. $s_selected_position = $arrLP[$i]['id'];
  7762. } elseif ($action == 'add') {
  7763. $s_selected_position = 0;
  7764. }
  7765. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7766. }
  7767. }
  7768. $selectPrerequisites = $form->addSelect(
  7769. 'prerequisites',
  7770. get_lang('LearnpathPrerequisites'),
  7771. [],
  7772. ['id' => 'prerequisites']
  7773. );
  7774. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7775. foreach ($arrHide as $key => $value) {
  7776. $selectPrerequisites->addOption($value['value'], $key);
  7777. if ($key == $s_selected_position && $action == 'add') {
  7778. $selectPrerequisites->setSelected($key);
  7779. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7780. $selectPrerequisites->setSelected($key);
  7781. }
  7782. }
  7783. }
  7784. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7785. if ($action == 'move') {
  7786. $form->addHidden('title', $item_title);
  7787. $form->addHidden('description', $item_description);
  7788. }
  7789. if (is_numeric($extra_info)) {
  7790. $form->addHidden('path', $extra_info);
  7791. } elseif (is_array($extra_info)) {
  7792. $form->addHidden('path', $extra_info['path']);
  7793. }
  7794. $form->addHidden('type', TOOL_THREAD);
  7795. $form->addHidden('post_time', time());
  7796. $form->setDefaults($defaults);
  7797. return $form->returnForm();
  7798. }
  7799. /**
  7800. * Return the HTML form to display an item (generally a dir item).
  7801. *
  7802. * @param string $item_type
  7803. * @param string $title
  7804. * @param string $action
  7805. * @param int $id
  7806. * @param string $extra_info
  7807. *
  7808. * @throws Exception
  7809. * @throws HTML_QuickForm_Error
  7810. *
  7811. * @return string HTML form
  7812. */
  7813. public function display_item_form(
  7814. $item_type,
  7815. $title = '',
  7816. $action = 'add_item',
  7817. $id = 0,
  7818. $extra_info = 'new'
  7819. ) {
  7820. $_course = api_get_course_info();
  7821. global $charset;
  7822. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7823. $item_title = '';
  7824. $item_description = '';
  7825. $item_path_fck = '';
  7826. if ($id != 0 && is_array($extra_info)) {
  7827. $item_title = $extra_info['title'];
  7828. $item_description = $extra_info['description'];
  7829. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7830. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7831. }
  7832. $parent = 0;
  7833. if ($id != 0 && is_array($extra_info)) {
  7834. $parent = $extra_info['parent_item_id'];
  7835. }
  7836. $id = (int) $id;
  7837. $sql = "SELECT * FROM $tbl_lp_item
  7838. WHERE
  7839. lp_id = ".$this->lp_id." AND
  7840. iid != $id";
  7841. if ($item_type == 'dir') {
  7842. $sql .= " AND parent_item_id = 0";
  7843. }
  7844. $result = Database::query($sql);
  7845. $arrLP = [];
  7846. while ($row = Database::fetch_array($result)) {
  7847. $arrLP[] = [
  7848. 'id' => $row['iid'],
  7849. 'item_type' => $row['item_type'],
  7850. 'title' => $row['title'],
  7851. 'path' => $row['path'],
  7852. 'description' => $row['description'],
  7853. 'parent_item_id' => $row['parent_item_id'],
  7854. 'previous_item_id' => $row['previous_item_id'],
  7855. 'next_item_id' => $row['next_item_id'],
  7856. 'max_score' => $row['max_score'],
  7857. 'min_score' => $row['min_score'],
  7858. 'mastery_score' => $row['mastery_score'],
  7859. 'prerequisite' => $row['prerequisite'],
  7860. 'display_order' => $row['display_order'],
  7861. ];
  7862. }
  7863. $this->tree_array($arrLP);
  7864. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7865. unset($this->arrMenu);
  7866. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7867. $form = new FormValidator('form', 'POST', $url);
  7868. $defaults['title'] = api_html_entity_decode(
  7869. $item_title,
  7870. ENT_QUOTES,
  7871. $charset
  7872. );
  7873. $defaults['description'] = $item_description;
  7874. $form->addHeader($title);
  7875. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7876. $arrHide[0]['padding'] = 20;
  7877. $charset = api_get_system_encoding();
  7878. for ($i = 0; $i < count($arrLP); $i++) {
  7879. if ($action != 'add') {
  7880. if ($arrLP[$i]['item_type'] == 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7881. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7882. ) {
  7883. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7884. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7885. if ($parent == $arrLP[$i]['id']) {
  7886. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7887. }
  7888. }
  7889. } else {
  7890. if ($arrLP[$i]['item_type'] == 'dir') {
  7891. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7892. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7893. if ($parent == $arrLP[$i]['id']) {
  7894. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7895. }
  7896. }
  7897. }
  7898. }
  7899. if ($action != 'move') {
  7900. $form->addElement('text', 'title', get_lang('Title'));
  7901. $form->applyFilter('title', 'html_filter');
  7902. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  7903. } else {
  7904. $form->addElement('hidden', 'title');
  7905. }
  7906. $parentSelect = $form->addElement(
  7907. 'select',
  7908. 'parent',
  7909. get_lang('Parent'),
  7910. '',
  7911. [
  7912. 'id' => 'idParent',
  7913. 'onchange' => "javascript: load_cbo(this.value);",
  7914. ]
  7915. );
  7916. foreach ($arrHide as $key => $value) {
  7917. $parentSelect->addOption(
  7918. $value['value'],
  7919. $key,
  7920. 'style="padding-left:'.$value['padding'].'px;"'
  7921. );
  7922. $lastPosition = $key;
  7923. }
  7924. if (!empty($s_selected_parent)) {
  7925. $parentSelect->setSelected($s_selected_parent);
  7926. }
  7927. if (is_array($arrLP)) {
  7928. reset($arrLP);
  7929. }
  7930. $arrHide = [];
  7931. // POSITION
  7932. for ($i = 0; $i < count($arrLP); $i++) {
  7933. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7934. //this is the same!
  7935. if (isset($extra_info['previous_item_id']) &&
  7936. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7937. ) {
  7938. $s_selected_position = $arrLP[$i]['id'];
  7939. } elseif ($action == 'add') {
  7940. $s_selected_position = $arrLP[$i]['id'];
  7941. }
  7942. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7943. }
  7944. }
  7945. $position = $form->addElement(
  7946. 'select',
  7947. 'previous',
  7948. get_lang('Position'),
  7949. '',
  7950. ['id' => 'previous']
  7951. );
  7952. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7953. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7954. $lastPosition = null;
  7955. foreach ($arrHide as $key => $value) {
  7956. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7957. $lastPosition = $key;
  7958. }
  7959. if (!empty($s_selected_position)) {
  7960. $position->setSelected($s_selected_position);
  7961. }
  7962. // When new chapter add at the end
  7963. if ($action == 'add_item') {
  7964. $position->setSelected($lastPosition);
  7965. }
  7966. if (is_array($arrLP)) {
  7967. reset($arrLP);
  7968. }
  7969. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7970. //fix in order to use the tab
  7971. if ($item_type == 'dir') {
  7972. $form->addElement('hidden', 'type', 'dir');
  7973. }
  7974. $extension = null;
  7975. if (!empty($item_path)) {
  7976. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7977. }
  7978. //assets can't be modified
  7979. //$item_type == 'asset' ||
  7980. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7981. if ($item_type == 'sco') {
  7982. $form->addElement(
  7983. 'html',
  7984. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7985. );
  7986. }
  7987. $renderer = $form->defaultRenderer();
  7988. $renderer->setElementTemplate(
  7989. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7990. 'content_lp'
  7991. );
  7992. $relative_prefix = '';
  7993. $editor_config = [
  7994. 'ToolbarSet' => 'LearningPathDocuments',
  7995. 'Width' => '100%',
  7996. 'Height' => '500',
  7997. 'FullPage' => true,
  7998. 'CreateDocumentDir' => $relative_prefix,
  7999. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  8000. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  8001. ];
  8002. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  8003. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  8004. $defaults['content_lp'] = file_get_contents($content_path);
  8005. }
  8006. if (!empty($id)) {
  8007. $form->addHidden('id', $id);
  8008. }
  8009. $form->addElement('hidden', 'type', $item_type);
  8010. $form->addElement('hidden', 'post_time', time());
  8011. $form->setDefaults($defaults);
  8012. return $form->returnForm();
  8013. }
  8014. /**
  8015. * @return string
  8016. */
  8017. public function getCurrentBuildingModeURL()
  8018. {
  8019. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  8020. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  8021. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  8022. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  8023. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  8024. return $currentUrl;
  8025. }
  8026. /**
  8027. * Returns the form to update or create a document.
  8028. *
  8029. * @param string $action (add/edit)
  8030. * @param int $id ID of the lp_item (if already exists)
  8031. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8032. *
  8033. * @throws Exception
  8034. * @throws HTML_QuickForm_Error
  8035. *
  8036. * @return string HTML form
  8037. */
  8038. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  8039. {
  8040. $course_id = api_get_course_int_id();
  8041. $_course = api_get_course_info();
  8042. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8043. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8044. $no_display_edit_textarea = false;
  8045. $item_description = '';
  8046. //If action==edit document
  8047. //We don't display the document form if it's not an editable document (html or txt file)
  8048. if ($action === 'edit') {
  8049. if (is_array($extra_info)) {
  8050. $path_parts = pathinfo($extra_info['dir']);
  8051. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8052. $no_display_edit_textarea = true;
  8053. }
  8054. }
  8055. }
  8056. $no_display_add = false;
  8057. // If action==add an existing document
  8058. // We don't display the document form if it's not an editable document (html or txt file).
  8059. if ($action === 'add') {
  8060. if (is_numeric($extra_info)) {
  8061. $extra_info = (int) $extra_info;
  8062. $sql_doc = "SELECT path FROM $tbl_doc
  8063. WHERE c_id = $course_id AND iid = ".$extra_info;
  8064. $result = Database::query($sql_doc);
  8065. $path_file = Database::result($result, 0, 0);
  8066. $path_parts = pathinfo($path_file);
  8067. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  8068. $no_display_add = true;
  8069. }
  8070. }
  8071. }
  8072. if ($id != 0 && is_array($extra_info)) {
  8073. $item_title = stripslashes($extra_info['title']);
  8074. $item_description = stripslashes($extra_info['description']);
  8075. if (empty($item_title)) {
  8076. $path_parts = pathinfo($extra_info['path']);
  8077. $item_title = stripslashes($path_parts['filename']);
  8078. }
  8079. } elseif (is_numeric($extra_info)) {
  8080. $sql = "SELECT path, title FROM $tbl_doc
  8081. WHERE
  8082. c_id = ".$course_id." AND
  8083. iid = ".intval($extra_info);
  8084. $result = Database::query($sql);
  8085. $row = Database::fetch_array($result);
  8086. $item_title = $row['title'];
  8087. $item_title = str_replace('_', ' ', $item_title);
  8088. if (empty($item_title)) {
  8089. $path_parts = pathinfo($row['path']);
  8090. $item_title = stripslashes($path_parts['filename']);
  8091. }
  8092. } else {
  8093. $item_title = '';
  8094. $item_description = '';
  8095. }
  8096. $return = '<legend>';
  8097. $parent = 0;
  8098. if ($id != 0 && is_array($extra_info)) {
  8099. $parent = $extra_info['parent_item_id'];
  8100. }
  8101. $sql = "SELECT * FROM $tbl_lp_item
  8102. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8103. $result = Database::query($sql);
  8104. $arrLP = [];
  8105. while ($row = Database::fetch_array($result)) {
  8106. $arrLP[] = [
  8107. 'id' => $row['iid'],
  8108. 'item_type' => $row['item_type'],
  8109. 'title' => $row['title'],
  8110. 'path' => $row['path'],
  8111. 'description' => $row['description'],
  8112. 'parent_item_id' => $row['parent_item_id'],
  8113. 'previous_item_id' => $row['previous_item_id'],
  8114. 'next_item_id' => $row['next_item_id'],
  8115. 'display_order' => $row['display_order'],
  8116. 'max_score' => $row['max_score'],
  8117. 'min_score' => $row['min_score'],
  8118. 'mastery_score' => $row['mastery_score'],
  8119. 'prerequisite' => $row['prerequisite'],
  8120. ];
  8121. }
  8122. $this->tree_array($arrLP);
  8123. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8124. unset($this->arrMenu);
  8125. if ($action == 'add') {
  8126. $return .= get_lang('CreateTheDocument');
  8127. } elseif ($action == 'move') {
  8128. $return .= get_lang('MoveTheCurrentDocument');
  8129. } else {
  8130. $return .= get_lang('EditTheCurrentDocument');
  8131. }
  8132. $return .= '</legend>';
  8133. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  8134. $return .= Display::return_message(
  8135. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  8136. false
  8137. );
  8138. }
  8139. $form = new FormValidator(
  8140. 'form',
  8141. 'POST',
  8142. $this->getCurrentBuildingModeURL(),
  8143. '',
  8144. ['enctype' => 'multipart/form-data']
  8145. );
  8146. $defaults['title'] = Security::remove_XSS($item_title);
  8147. if (empty($item_title)) {
  8148. $defaults['title'] = Security::remove_XSS($item_title);
  8149. }
  8150. $defaults['description'] = $item_description;
  8151. $form->addElement('html', $return);
  8152. if ($action != 'move') {
  8153. $data = $this->generate_lp_folder($_course);
  8154. if ($action != 'edit') {
  8155. $folders = DocumentManager::get_all_document_folders(
  8156. $_course,
  8157. 0,
  8158. true
  8159. );
  8160. DocumentManager::build_directory_selector(
  8161. $folders,
  8162. '',
  8163. [],
  8164. true,
  8165. $form,
  8166. 'directory_parent_id'
  8167. );
  8168. }
  8169. if (isset($data['id'])) {
  8170. $defaults['directory_parent_id'] = $data['id'];
  8171. }
  8172. $form->addElement(
  8173. 'text',
  8174. 'title',
  8175. get_lang('Title'),
  8176. ['id' => 'idTitle', 'class' => 'col-md-4']
  8177. );
  8178. $form->applyFilter('title', 'html_filter');
  8179. }
  8180. $arrHide[0]['value'] = $this->name;
  8181. $arrHide[0]['padding'] = 20;
  8182. for ($i = 0; $i < count($arrLP); $i++) {
  8183. if ($action != 'add') {
  8184. if ($arrLP[$i]['item_type'] == 'dir' &&
  8185. !in_array($arrLP[$i]['id'], $arrHide) &&
  8186. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8187. ) {
  8188. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8189. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8190. }
  8191. } else {
  8192. if ($arrLP[$i]['item_type'] == 'dir') {
  8193. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8194. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8195. }
  8196. }
  8197. }
  8198. $parentSelect = $form->addSelect(
  8199. 'parent',
  8200. get_lang('Parent'),
  8201. [],
  8202. [
  8203. 'id' => 'idParent',
  8204. 'onchange' => 'javascript: load_cbo(this.value);',
  8205. ]
  8206. );
  8207. $my_count = 0;
  8208. foreach ($arrHide as $key => $value) {
  8209. if ($my_count != 0) {
  8210. // The LP name is also the first section and is not in the same charset like the other sections.
  8211. $value['value'] = Security::remove_XSS($value['value']);
  8212. $parentSelect->addOption(
  8213. $value['value'],
  8214. $key,
  8215. 'style="padding-left:'.$value['padding'].'px;"'
  8216. );
  8217. } else {
  8218. $value['value'] = Security::remove_XSS($value['value']);
  8219. $parentSelect->addOption(
  8220. $value['value'],
  8221. $key,
  8222. 'style="padding-left:'.$value['padding'].'px;"'
  8223. );
  8224. }
  8225. $my_count++;
  8226. }
  8227. if (!empty($id)) {
  8228. $parentSelect->setSelected($parent);
  8229. } else {
  8230. $parent_item_id = Session::read('parent_item_id', 0);
  8231. $parentSelect->setSelected($parent_item_id);
  8232. }
  8233. if (is_array($arrLP)) {
  8234. reset($arrLP);
  8235. }
  8236. $arrHide = [];
  8237. // POSITION
  8238. for ($i = 0; $i < count($arrLP); $i++) {
  8239. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8240. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8241. ) {
  8242. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8243. }
  8244. }
  8245. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  8246. $position = $form->addSelect(
  8247. 'previous',
  8248. get_lang('Position'),
  8249. [],
  8250. ['id' => 'previous']
  8251. );
  8252. $position->addOption(get_lang('FirstPosition'), 0);
  8253. foreach ($arrHide as $key => $value) {
  8254. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8255. $position->addOption(
  8256. $value['value'],
  8257. $key,
  8258. 'style="padding-left:'.$padding.'px;"'
  8259. );
  8260. }
  8261. $position->setSelected($selectedPosition);
  8262. if (is_array($arrLP)) {
  8263. reset($arrLP);
  8264. }
  8265. if ($action != 'move') {
  8266. $arrHide = [];
  8267. for ($i = 0; $i < count($arrLP); $i++) {
  8268. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8269. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8270. ) {
  8271. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8272. }
  8273. }
  8274. if (!$no_display_add) {
  8275. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8276. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8277. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  8278. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  8279. ) {
  8280. if (isset($_POST['content'])) {
  8281. $content = stripslashes($_POST['content']);
  8282. } elseif (is_array($extra_info)) {
  8283. //If it's an html document or a text file
  8284. if (!$no_display_edit_textarea) {
  8285. $content = $this->display_document(
  8286. $extra_info['path'],
  8287. false,
  8288. false
  8289. );
  8290. }
  8291. } elseif (is_numeric($extra_info)) {
  8292. $content = $this->display_document(
  8293. $extra_info,
  8294. false,
  8295. false
  8296. );
  8297. } else {
  8298. $content = '';
  8299. }
  8300. if (!$no_display_edit_textarea) {
  8301. // We need to calculate here some specific settings for the online editor.
  8302. // The calculated settings work for documents in the Documents tool
  8303. // (on the root or in subfolders).
  8304. // For documents in native scorm packages it is unclear whether the
  8305. // online editor should be activated or not.
  8306. // A new document, it is in the root of the repository.
  8307. $relative_path = '';
  8308. $relative_prefix = '';
  8309. if (is_array($extra_info) && $extra_info != 'new') {
  8310. // The document already exists. Whe have to determine its relative path towards the repository root.
  8311. $relative_path = explode('/', $extra_info['dir']);
  8312. $cnt = count($relative_path) - 2;
  8313. if ($cnt < 0) {
  8314. $cnt = 0;
  8315. }
  8316. $relative_prefix = str_repeat('../', $cnt);
  8317. $relative_path = array_slice($relative_path, 1, $cnt);
  8318. $relative_path = implode('/', $relative_path);
  8319. if (strlen($relative_path) > 0) {
  8320. $relative_path = $relative_path.'/';
  8321. }
  8322. } else {
  8323. $result = $this->generate_lp_folder($_course);
  8324. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  8325. $relative_prefix = '../../';
  8326. }
  8327. $editor_config = [
  8328. 'ToolbarSet' => 'LearningPathDocuments',
  8329. 'Width' => '100%',
  8330. 'Height' => '500',
  8331. 'FullPage' => true,
  8332. 'CreateDocumentDir' => $relative_prefix,
  8333. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  8334. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  8335. ];
  8336. if ($_GET['action'] == 'add_item') {
  8337. $class = 'add';
  8338. $text = get_lang('LPCreateDocument');
  8339. } else {
  8340. if ($_GET['action'] == 'edit_item') {
  8341. $class = 'save';
  8342. $text = get_lang('SaveDocument');
  8343. }
  8344. }
  8345. $form->addButtonSave($text, 'submit_button');
  8346. $renderer = $form->defaultRenderer();
  8347. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  8348. $form->addElement('html', '<div class="editor-lp">');
  8349. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  8350. $form->addElement('html', '</div>');
  8351. $defaults['content_lp'] = $content;
  8352. }
  8353. } elseif (is_numeric($extra_info)) {
  8354. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8355. $return = $this->display_document($extra_info, true, true, true);
  8356. $form->addElement('html', $return);
  8357. }
  8358. }
  8359. }
  8360. if (isset($extra_info['item_type']) &&
  8361. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  8362. ) {
  8363. $parentSelect->freeze();
  8364. $position->freeze();
  8365. }
  8366. if ($action == 'move') {
  8367. $form->addElement('hidden', 'title', $item_title);
  8368. $form->addElement('hidden', 'description', $item_description);
  8369. }
  8370. if (is_numeric($extra_info)) {
  8371. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8372. $form->addElement('hidden', 'path', $extra_info);
  8373. } elseif (is_array($extra_info)) {
  8374. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8375. $form->addElement('hidden', 'path', $extra_info['path']);
  8376. }
  8377. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  8378. $form->addElement('hidden', 'post_time', time());
  8379. $form->setDefaults($defaults);
  8380. return $form->returnForm();
  8381. }
  8382. /**
  8383. * Returns the form to update or create a read-out text.
  8384. *
  8385. * @param string $action "add" or "edit"
  8386. * @param int $id ID of the lp_item (if already exists)
  8387. * @param mixed $extra_info Integer if document ID, string if info ('new')
  8388. *
  8389. * @throws Exception
  8390. * @throws HTML_QuickForm_Error
  8391. *
  8392. * @return string HTML form
  8393. */
  8394. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  8395. {
  8396. $course_id = api_get_course_int_id();
  8397. $_course = api_get_course_info();
  8398. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8399. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  8400. $no_display_edit_textarea = false;
  8401. $item_description = '';
  8402. //If action==edit document
  8403. //We don't display the document form if it's not an editable document (html or txt file)
  8404. if ($action == 'edit') {
  8405. if (is_array($extra_info)) {
  8406. $path_parts = pathinfo($extra_info['dir']);
  8407. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  8408. $no_display_edit_textarea = true;
  8409. }
  8410. }
  8411. }
  8412. $no_display_add = false;
  8413. if ($id != 0 && is_array($extra_info)) {
  8414. $item_title = stripslashes($extra_info['title']);
  8415. $item_description = stripslashes($extra_info['description']);
  8416. $item_terms = stripslashes($extra_info['terms']);
  8417. if (empty($item_title)) {
  8418. $path_parts = pathinfo($extra_info['path']);
  8419. $item_title = stripslashes($path_parts['filename']);
  8420. }
  8421. } elseif (is_numeric($extra_info)) {
  8422. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  8423. $result = Database::query($sql);
  8424. $row = Database::fetch_array($result);
  8425. $item_title = $row['title'];
  8426. $item_title = str_replace('_', ' ', $item_title);
  8427. if (empty($item_title)) {
  8428. $path_parts = pathinfo($row['path']);
  8429. $item_title = stripslashes($path_parts['filename']);
  8430. }
  8431. } else {
  8432. $item_title = '';
  8433. $item_description = '';
  8434. }
  8435. if ($id != 0 && is_array($extra_info)) {
  8436. $parent = $extra_info['parent_item_id'];
  8437. } else {
  8438. $parent = 0;
  8439. }
  8440. $sql = "SELECT * FROM $tbl_lp_item WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8441. $result = Database::query($sql);
  8442. $arrLP = [];
  8443. while ($row = Database::fetch_array($result)) {
  8444. $arrLP[] = [
  8445. 'id' => $row['iid'],
  8446. 'item_type' => $row['item_type'],
  8447. 'title' => $row['title'],
  8448. 'path' => $row['path'],
  8449. 'description' => $row['description'],
  8450. 'parent_item_id' => $row['parent_item_id'],
  8451. 'previous_item_id' => $row['previous_item_id'],
  8452. 'next_item_id' => $row['next_item_id'],
  8453. 'display_order' => $row['display_order'],
  8454. 'max_score' => $row['max_score'],
  8455. 'min_score' => $row['min_score'],
  8456. 'mastery_score' => $row['mastery_score'],
  8457. 'prerequisite' => $row['prerequisite'],
  8458. ];
  8459. }
  8460. $this->tree_array($arrLP);
  8461. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8462. unset($this->arrMenu);
  8463. if ($action == 'add') {
  8464. $formHeader = get_lang('CreateTheDocument');
  8465. } else {
  8466. $formHeader = get_lang('EditTheCurrentDocument');
  8467. }
  8468. if ('edit' === $action) {
  8469. $urlAudioIcon = Display::url(
  8470. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8471. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8472. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8473. );
  8474. } else {
  8475. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8476. }
  8477. $form = new FormValidator(
  8478. 'frm_add_reading',
  8479. 'POST',
  8480. $this->getCurrentBuildingModeURL(),
  8481. '',
  8482. ['enctype' => 'multipart/form-data']
  8483. );
  8484. $form->addHeader($formHeader);
  8485. $form->addHtml(
  8486. Display::return_message(
  8487. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8488. 'normal',
  8489. false
  8490. )
  8491. );
  8492. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8493. $defaults['description'] = $item_description;
  8494. $data = $this->generate_lp_folder($_course);
  8495. if ($action != 'edit') {
  8496. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8497. DocumentManager::build_directory_selector(
  8498. $folders,
  8499. '',
  8500. [],
  8501. true,
  8502. $form,
  8503. 'directory_parent_id'
  8504. );
  8505. }
  8506. if (isset($data['id'])) {
  8507. $defaults['directory_parent_id'] = $data['id'];
  8508. }
  8509. $form->addElement(
  8510. 'text',
  8511. 'title',
  8512. get_lang('Title')
  8513. );
  8514. $form->applyFilter('title', 'trim');
  8515. $form->applyFilter('title', 'html_filter');
  8516. $arrHide[0]['value'] = $this->name;
  8517. $arrHide[0]['padding'] = 20;
  8518. for ($i = 0; $i < count($arrLP); $i++) {
  8519. if ($action != 'add') {
  8520. if ($arrLP[$i]['item_type'] == 'dir' &&
  8521. !in_array($arrLP[$i]['id'], $arrHide) &&
  8522. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8523. ) {
  8524. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8525. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8526. }
  8527. } else {
  8528. if ($arrLP[$i]['item_type'] == 'dir') {
  8529. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8530. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8531. }
  8532. }
  8533. }
  8534. $parent_select = $form->addSelect(
  8535. 'parent',
  8536. get_lang('Parent'),
  8537. [],
  8538. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8539. );
  8540. $my_count = 0;
  8541. foreach ($arrHide as $key => $value) {
  8542. if ($my_count != 0) {
  8543. // The LP name is also the first section and is not in the same charset like the other sections.
  8544. $value['value'] = Security::remove_XSS($value['value']);
  8545. $parent_select->addOption(
  8546. $value['value'],
  8547. $key,
  8548. 'style="padding-left:'.$value['padding'].'px;"'
  8549. );
  8550. } else {
  8551. $value['value'] = Security::remove_XSS($value['value']);
  8552. $parent_select->addOption(
  8553. $value['value'],
  8554. $key,
  8555. 'style="padding-left:'.$value['padding'].'px;"'
  8556. );
  8557. }
  8558. $my_count++;
  8559. }
  8560. if (!empty($id)) {
  8561. $parent_select->setSelected($parent);
  8562. } else {
  8563. $parent_item_id = Session::read('parent_item_id', 0);
  8564. $parent_select->setSelected($parent_item_id);
  8565. }
  8566. if (is_array($arrLP)) {
  8567. reset($arrLP);
  8568. }
  8569. $arrHide = [];
  8570. $s_selected_position = null;
  8571. // POSITION
  8572. $lastPosition = null;
  8573. for ($i = 0; $i < count($arrLP); $i++) {
  8574. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  8575. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  8576. ) {
  8577. if ((isset($extra_info['previous_item_id']) &&
  8578. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8579. ) {
  8580. $s_selected_position = $arrLP[$i]['id'];
  8581. }
  8582. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8583. }
  8584. $lastPosition = $arrLP[$i]['id'];
  8585. }
  8586. if (empty($s_selected_position)) {
  8587. $s_selected_position = $lastPosition;
  8588. }
  8589. $position = $form->addSelect(
  8590. 'previous',
  8591. get_lang('Position'),
  8592. []
  8593. );
  8594. $position->addOption(get_lang('FirstPosition'), 0);
  8595. foreach ($arrHide as $key => $value) {
  8596. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8597. $position->addOption(
  8598. $value['value'],
  8599. $key,
  8600. 'style="padding-left:'.$padding.'px;"'
  8601. );
  8602. }
  8603. $position->setSelected($s_selected_position);
  8604. if (is_array($arrLP)) {
  8605. reset($arrLP);
  8606. }
  8607. $arrHide = [];
  8608. for ($i = 0; $i < count($arrLP); $i++) {
  8609. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8610. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8611. ) {
  8612. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8613. }
  8614. }
  8615. if (!$no_display_add) {
  8616. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8617. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8618. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8619. if (!$no_display_edit_textarea) {
  8620. $content = '';
  8621. if (isset($_POST['content'])) {
  8622. $content = stripslashes($_POST['content']);
  8623. } elseif (is_array($extra_info)) {
  8624. $content = $this->display_document($extra_info['path'], false, false);
  8625. } elseif (is_numeric($extra_info)) {
  8626. $content = $this->display_document($extra_info, false, false);
  8627. }
  8628. // A new document, it is in the root of the repository.
  8629. if (is_array($extra_info) && $extra_info != 'new') {
  8630. } else {
  8631. $this->generate_lp_folder($_course);
  8632. }
  8633. if ($_GET['action'] == 'add_item') {
  8634. $text = get_lang('LPCreateDocument');
  8635. } else {
  8636. $text = get_lang('SaveDocument');
  8637. }
  8638. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8639. $form
  8640. ->defaultRenderer()
  8641. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8642. $form->addButtonSave($text, 'submit_button');
  8643. $defaults['content_lp'] = $content;
  8644. }
  8645. } elseif (is_numeric($extra_info)) {
  8646. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8647. $return = $this->display_document($extra_info, true, true, true);
  8648. $form->addElement('html', $return);
  8649. }
  8650. }
  8651. if (is_numeric($extra_info)) {
  8652. $form->addElement('hidden', 'path', $extra_info);
  8653. } elseif (is_array($extra_info)) {
  8654. $form->addElement('hidden', 'path', $extra_info['path']);
  8655. }
  8656. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8657. $form->addElement('hidden', 'post_time', time());
  8658. $form->setDefaults($defaults);
  8659. return $form->returnForm();
  8660. }
  8661. /**
  8662. * @param array $courseInfo
  8663. * @param string $content
  8664. * @param string $title
  8665. * @param int $parentId
  8666. *
  8667. * @throws \Doctrine\ORM\ORMException
  8668. * @throws \Doctrine\ORM\OptimisticLockException
  8669. * @throws \Doctrine\ORM\TransactionRequiredException
  8670. *
  8671. * @return int
  8672. */
  8673. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8674. {
  8675. $creatorId = api_get_user_id();
  8676. $sessionId = api_get_session_id();
  8677. // Generates folder
  8678. $result = $this->generate_lp_folder($courseInfo);
  8679. $dir = $result['dir'];
  8680. if (empty($parentId) || $parentId == '/') {
  8681. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8682. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8683. if ($parentId === '/') {
  8684. $dir = '/';
  8685. }
  8686. // Please, do not modify this dirname formatting.
  8687. if (strstr($dir, '..')) {
  8688. $dir = '/';
  8689. }
  8690. if (!empty($dir[0]) && $dir[0] == '.') {
  8691. $dir = substr($dir, 1);
  8692. }
  8693. if (!empty($dir[0]) && $dir[0] != '/') {
  8694. $dir = '/'.$dir;
  8695. }
  8696. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8697. $dir .= '/';
  8698. }
  8699. } else {
  8700. $parentInfo = DocumentManager::get_document_data_by_id(
  8701. $parentId,
  8702. $courseInfo['code']
  8703. );
  8704. if (!empty($parentInfo)) {
  8705. $dir = $parentInfo['path'].'/';
  8706. }
  8707. }
  8708. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8709. if (!is_dir($filepath)) {
  8710. $dir = '/';
  8711. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8712. }
  8713. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8714. if (!empty($title)) {
  8715. $title = api_replace_dangerous_char(stripslashes($title));
  8716. } else {
  8717. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8718. }
  8719. $title = disable_dangerous_file($title);
  8720. $filename = $title;
  8721. $content = !empty($content) ? $content : $_POST['content_lp'];
  8722. $tmpFileName = $filename;
  8723. $i = 0;
  8724. while (file_exists($filepath.$tmpFileName.'.html')) {
  8725. $tmpFileName = $filename.'_'.++$i;
  8726. }
  8727. $filename = $tmpFileName.'.html';
  8728. $content = stripslashes($content);
  8729. if (file_exists($filepath.$filename)) {
  8730. return 0;
  8731. }
  8732. $putContent = file_put_contents($filepath.$filename, $content);
  8733. if ($putContent === false) {
  8734. return 0;
  8735. }
  8736. $fileSize = filesize($filepath.$filename);
  8737. $saveFilePath = $dir.$filename;
  8738. $documentId = add_document(
  8739. $courseInfo,
  8740. $saveFilePath,
  8741. 'file',
  8742. $fileSize,
  8743. $tmpFileName,
  8744. '',
  8745. 0, //readonly
  8746. true,
  8747. null,
  8748. $sessionId,
  8749. $creatorId
  8750. );
  8751. if (!$documentId) {
  8752. return 0;
  8753. }
  8754. api_item_property_update(
  8755. $courseInfo,
  8756. TOOL_DOCUMENT,
  8757. $documentId,
  8758. 'DocumentAdded',
  8759. $creatorId,
  8760. null,
  8761. null,
  8762. null,
  8763. null,
  8764. $sessionId
  8765. );
  8766. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8767. $newTitle = $originalTitle;
  8768. if ($newComment || $newTitle) {
  8769. $em = Database::getManager();
  8770. /** @var CDocument $doc */
  8771. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8772. if ($newComment) {
  8773. $doc->setComment($newComment);
  8774. }
  8775. if ($newTitle) {
  8776. $doc->setTitle($newTitle);
  8777. }
  8778. $em->persist($doc);
  8779. $em->flush();
  8780. }
  8781. return $documentId;
  8782. }
  8783. /**
  8784. * Return HTML form to add/edit a link item.
  8785. *
  8786. * @param string $action (add/edit)
  8787. * @param int $id Item ID if exists
  8788. * @param mixed $extra_info
  8789. *
  8790. * @throws Exception
  8791. * @throws HTML_QuickForm_Error
  8792. *
  8793. * @return string HTML form
  8794. */
  8795. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8796. {
  8797. $course_id = api_get_course_int_id();
  8798. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8799. $tbl_link = Database::get_course_table(TABLE_LINK);
  8800. $item_title = '';
  8801. $item_description = '';
  8802. $item_url = '';
  8803. if ($id != 0 && is_array($extra_info)) {
  8804. $item_title = stripslashes($extra_info['title']);
  8805. $item_description = stripslashes($extra_info['description']);
  8806. $item_url = stripslashes($extra_info['url']);
  8807. } elseif (is_numeric($extra_info)) {
  8808. $extra_info = (int) $extra_info;
  8809. $sql = "SELECT title, description, url
  8810. FROM $tbl_link
  8811. WHERE c_id = $course_id AND iid = $extra_info";
  8812. $result = Database::query($sql);
  8813. $row = Database::fetch_array($result);
  8814. $item_title = $row['title'];
  8815. $item_description = $row['description'];
  8816. $item_url = $row['url'];
  8817. }
  8818. $form = new FormValidator(
  8819. 'edit_link',
  8820. 'POST',
  8821. $this->getCurrentBuildingModeURL()
  8822. );
  8823. $defaults = [];
  8824. $parent = 0;
  8825. if ($id != 0 && is_array($extra_info)) {
  8826. $parent = $extra_info['parent_item_id'];
  8827. }
  8828. $sql = "SELECT * FROM $tbl_lp_item
  8829. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8830. $result = Database::query($sql);
  8831. $arrLP = [];
  8832. while ($row = Database::fetch_array($result)) {
  8833. $arrLP[] = [
  8834. 'id' => $row['id'],
  8835. 'item_type' => $row['item_type'],
  8836. 'title' => $row['title'],
  8837. 'path' => $row['path'],
  8838. 'description' => $row['description'],
  8839. 'parent_item_id' => $row['parent_item_id'],
  8840. 'previous_item_id' => $row['previous_item_id'],
  8841. 'next_item_id' => $row['next_item_id'],
  8842. 'display_order' => $row['display_order'],
  8843. 'max_score' => $row['max_score'],
  8844. 'min_score' => $row['min_score'],
  8845. 'mastery_score' => $row['mastery_score'],
  8846. 'prerequisite' => $row['prerequisite'],
  8847. ];
  8848. }
  8849. $this->tree_array($arrLP);
  8850. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8851. unset($this->arrMenu);
  8852. if ($action == 'add') {
  8853. $legend = get_lang('CreateTheLink');
  8854. } elseif ($action == 'move') {
  8855. $legend = get_lang('MoveCurrentLink');
  8856. } else {
  8857. $legend = get_lang('EditCurrentLink');
  8858. }
  8859. $form->addHeader($legend);
  8860. if ($action != 'move') {
  8861. $form->addText('title', get_lang('Title'), true, ['class' => 'learnpath_item_form']);
  8862. $defaults['title'] = $item_title;
  8863. }
  8864. $selectParent = $form->addSelect(
  8865. 'parent',
  8866. get_lang('Parent'),
  8867. [],
  8868. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8869. );
  8870. $selectParent->addOption($this->name, 0);
  8871. $arrHide = [
  8872. $id,
  8873. ];
  8874. $parent_item_id = Session::read('parent_item_id', 0);
  8875. for ($i = 0; $i < count($arrLP); $i++) {
  8876. if ($action != 'add') {
  8877. if (
  8878. ($arrLP[$i]['item_type'] == 'dir') &&
  8879. !in_array($arrLP[$i]['id'], $arrHide) &&
  8880. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8881. ) {
  8882. $selectParent->addOption(
  8883. $arrLP[$i]['title'],
  8884. $arrLP[$i]['id'],
  8885. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8886. );
  8887. if ($parent == $arrLP[$i]['id']) {
  8888. $selectParent->setSelected($arrLP[$i]['id']);
  8889. }
  8890. } else {
  8891. $arrHide[] = $arrLP[$i]['id'];
  8892. }
  8893. } else {
  8894. if ($arrLP[$i]['item_type'] == 'dir') {
  8895. $selectParent->addOption(
  8896. $arrLP[$i]['title'],
  8897. $arrLP[$i]['id'],
  8898. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8899. );
  8900. if ($parent_item_id == $arrLP[$i]['id']) {
  8901. $selectParent->setSelected($arrLP[$i]['id']);
  8902. }
  8903. }
  8904. }
  8905. }
  8906. if (is_array($arrLP)) {
  8907. reset($arrLP);
  8908. }
  8909. $selectPrevious = $form->addSelect(
  8910. 'previous',
  8911. get_lang('Position'),
  8912. [],
  8913. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8914. );
  8915. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8916. for ($i = 0; $i < count($arrLP); $i++) {
  8917. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8918. $selectPrevious->addOption(
  8919. $arrLP[$i]['title'],
  8920. $arrLP[$i]['id']
  8921. );
  8922. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8923. $selectPrevious->setSelected($arrLP[$i]['id']);
  8924. } elseif ($action == 'add') {
  8925. $selectPrevious->setSelected($arrLP[$i]['id']);
  8926. }
  8927. }
  8928. }
  8929. if ($action != 'move') {
  8930. $urlAttributes = ['class' => 'learnpath_item_form'];
  8931. if (is_numeric($extra_info)) {
  8932. $urlAttributes['disabled'] = 'disabled';
  8933. }
  8934. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8935. $defaults['url'] = $item_url;
  8936. $arrHide = [];
  8937. for ($i = 0; $i < count($arrLP); $i++) {
  8938. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8939. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8940. }
  8941. }
  8942. }
  8943. if ($action == 'add') {
  8944. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8945. } else {
  8946. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8947. }
  8948. if ($action == 'move') {
  8949. $form->addHidden('title', $item_title);
  8950. $form->addHidden('description', $item_description);
  8951. }
  8952. if (is_numeric($extra_info)) {
  8953. $form->addHidden('path', $extra_info);
  8954. } elseif (is_array($extra_info)) {
  8955. $form->addHidden('path', $extra_info['path']);
  8956. }
  8957. $form->addHidden('type', TOOL_LINK);
  8958. $form->addHidden('post_time', time());
  8959. $form->setDefaults($defaults);
  8960. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8961. }
  8962. /**
  8963. * Return HTML form to add/edit a student publication (work).
  8964. *
  8965. * @param string $action
  8966. * @param int $id Item ID if already exists
  8967. * @param string $extra_info
  8968. *
  8969. * @throws Exception
  8970. *
  8971. * @return string HTML form
  8972. */
  8973. public function display_student_publication_form(
  8974. $action = 'add',
  8975. $id = 0,
  8976. $extra_info = ''
  8977. ) {
  8978. $course_id = api_get_course_int_id();
  8979. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8980. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8981. $item_title = get_lang('Student_publication');
  8982. if ($id != 0 && is_array($extra_info)) {
  8983. $item_title = stripslashes($extra_info['title']);
  8984. $item_description = stripslashes($extra_info['description']);
  8985. } elseif (is_numeric($extra_info)) {
  8986. $extra_info = (int) $extra_info;
  8987. $sql = "SELECT title, description
  8988. FROM $tbl_publication
  8989. WHERE c_id = $course_id AND id = ".$extra_info;
  8990. $result = Database::query($sql);
  8991. $row = Database::fetch_array($result);
  8992. if ($row) {
  8993. $item_title = $row['title'];
  8994. }
  8995. }
  8996. $parent = 0;
  8997. if ($id != 0 && is_array($extra_info)) {
  8998. $parent = $extra_info['parent_item_id'];
  8999. }
  9000. $sql = "SELECT * FROM $tbl_lp_item
  9001. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9002. $result = Database::query($sql);
  9003. $arrLP = [];
  9004. while ($row = Database::fetch_array($result)) {
  9005. $arrLP[] = [
  9006. 'id' => $row['iid'],
  9007. 'item_type' => $row['item_type'],
  9008. 'title' => $row['title'],
  9009. 'path' => $row['path'],
  9010. 'description' => $row['description'],
  9011. 'parent_item_id' => $row['parent_item_id'],
  9012. 'previous_item_id' => $row['previous_item_id'],
  9013. 'next_item_id' => $row['next_item_id'],
  9014. 'display_order' => $row['display_order'],
  9015. 'max_score' => $row['max_score'],
  9016. 'min_score' => $row['min_score'],
  9017. 'mastery_score' => $row['mastery_score'],
  9018. 'prerequisite' => $row['prerequisite'],
  9019. ];
  9020. }
  9021. $this->tree_array($arrLP);
  9022. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9023. unset($this->arrMenu);
  9024. $form = new FormValidator('frm_student_publication', 'post', '#');
  9025. if ($action == 'add') {
  9026. $form->addHeader(get_lang('Student_publication'));
  9027. } elseif ($action == 'move') {
  9028. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  9029. } else {
  9030. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  9031. }
  9032. if ($action != 'move') {
  9033. $form->addText(
  9034. 'title',
  9035. get_lang('Title'),
  9036. true,
  9037. ['class' => 'learnpath_item_form', 'id' => 'idTitle']
  9038. );
  9039. }
  9040. $parentSelect = $form->addSelect(
  9041. 'parent',
  9042. get_lang('Parent'),
  9043. ['0' => $this->name],
  9044. [
  9045. 'onchange' => 'javascript: load_cbo(this.value);',
  9046. 'class' => 'learnpath_item_form',
  9047. 'id' => 'idParent',
  9048. ]
  9049. );
  9050. $arrHide = [$id];
  9051. for ($i = 0; $i < count($arrLP); $i++) {
  9052. if ($action != 'add') {
  9053. if (
  9054. ($arrLP[$i]['item_type'] == 'dir') &&
  9055. !in_array($arrLP[$i]['id'], $arrHide) &&
  9056. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  9057. ) {
  9058. $parentSelect->addOption(
  9059. $arrLP[$i]['title'],
  9060. $arrLP[$i]['id'],
  9061. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9062. );
  9063. if ($parent == $arrLP[$i]['id']) {
  9064. $parentSelect->setSelected($arrLP[$i]['id']);
  9065. }
  9066. } else {
  9067. $arrHide[] = $arrLP[$i]['id'];
  9068. }
  9069. } else {
  9070. if ($arrLP[$i]['item_type'] == 'dir') {
  9071. $parentSelect->addOption(
  9072. $arrLP[$i]['title'],
  9073. $arrLP[$i]['id'],
  9074. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  9075. );
  9076. if ($parent == $arrLP[$i]['id']) {
  9077. $parentSelect->setSelected($arrLP[$i]['id']);
  9078. }
  9079. }
  9080. }
  9081. }
  9082. if (is_array($arrLP)) {
  9083. reset($arrLP);
  9084. }
  9085. $previousSelect = $form->addSelect(
  9086. 'previous',
  9087. get_lang('Position'),
  9088. ['0' => get_lang('FirstPosition')],
  9089. ['id' => 'previous', 'class' => 'learnpath_item_form']
  9090. );
  9091. for ($i = 0; $i < count($arrLP); $i++) {
  9092. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  9093. $previousSelect->addOption(
  9094. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  9095. $arrLP[$i]['id']
  9096. );
  9097. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  9098. $previousSelect->setSelected($arrLP[$i]['id']);
  9099. } elseif ($action == 'add') {
  9100. $previousSelect->setSelected($arrLP[$i]['id']);
  9101. }
  9102. }
  9103. }
  9104. if ($action == 'add') {
  9105. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  9106. } else {
  9107. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  9108. }
  9109. if ($action == 'move') {
  9110. $form->addHidden('title', $item_title);
  9111. $form->addHidden('description', $item_description);
  9112. }
  9113. if (is_numeric($extra_info)) {
  9114. $form->addHidden('path', $extra_info);
  9115. } elseif (is_array($extra_info)) {
  9116. $form->addHidden('path', $extra_info['path']);
  9117. }
  9118. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  9119. $form->addHidden('post_time', time());
  9120. $form->setDefaults(['title' => $item_title]);
  9121. $return = '<div class="sectioncomment">';
  9122. $return .= $form->returnForm();
  9123. $return .= '</div>';
  9124. return $return;
  9125. }
  9126. /**
  9127. * Displays the menu for manipulating a step.
  9128. *
  9129. * @param id $item_id
  9130. * @param string $item_type
  9131. *
  9132. * @return string
  9133. */
  9134. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  9135. {
  9136. $_course = api_get_course_info();
  9137. $course_code = api_get_course_id();
  9138. $return = '<div class="actions">';
  9139. switch ($item_type) {
  9140. case 'dir':
  9141. // Commented the message cause should not show it.
  9142. //$lang = get_lang('TitleManipulateChapter');
  9143. break;
  9144. case TOOL_LP_FINAL_ITEM:
  9145. case TOOL_DOCUMENT:
  9146. // Commented the message cause should not show it.
  9147. //$lang = get_lang('TitleManipulateDocument');
  9148. break;
  9149. case TOOL_LINK:
  9150. case 'link':
  9151. // Commented the message cause should not show it.
  9152. //$lang = get_lang('TitleManipulateLink');
  9153. break;
  9154. case TOOL_QUIZ:
  9155. // Commented the message cause should not show it.
  9156. //$lang = get_lang('TitleManipulateQuiz');
  9157. break;
  9158. case TOOL_STUDENTPUBLICATION:
  9159. // Commented the message cause should not show it.
  9160. //$lang = get_lang('TitleManipulateStudentPublication');
  9161. break;
  9162. }
  9163. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9164. $item_id = (int) $item_id;
  9165. $sql = "SELECT * FROM $tbl_lp_item
  9166. WHERE iid = ".$item_id;
  9167. $result = Database::query($sql);
  9168. $row = Database::fetch_assoc($result);
  9169. $audio_player = null;
  9170. // We display an audio player if needed.
  9171. if (!empty($row['audio'])) {
  9172. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  9173. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  9174. .'<audio src="'.$webAudioPath.'" controls>'
  9175. .'</div><br>';
  9176. }
  9177. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  9178. if ($item_type != TOOL_LP_FINAL_ITEM) {
  9179. $return .= Display::url(
  9180. Display::return_icon(
  9181. 'edit.png',
  9182. get_lang('Edit'),
  9183. [],
  9184. ICON_SIZE_SMALL
  9185. ),
  9186. $url.'&action=edit_item&path_item='.$row['path']
  9187. );
  9188. $return .= Display::url(
  9189. Display::return_icon(
  9190. 'move.png',
  9191. get_lang('Move'),
  9192. [],
  9193. ICON_SIZE_SMALL
  9194. ),
  9195. $url.'&action=move_item'
  9196. );
  9197. }
  9198. // Commented for now as prerequisites cannot be added to chapters.
  9199. if ($item_type != 'dir') {
  9200. $return .= Display::url(
  9201. Display::return_icon(
  9202. 'accept.png',
  9203. get_lang('LearnpathPrerequisites'),
  9204. [],
  9205. ICON_SIZE_SMALL
  9206. ),
  9207. $url.'&action=edit_item_prereq'
  9208. );
  9209. }
  9210. $return .= Display::url(
  9211. Display::return_icon(
  9212. 'delete.png',
  9213. get_lang('Delete'),
  9214. [],
  9215. ICON_SIZE_SMALL
  9216. ),
  9217. $url.'&action=delete_item'
  9218. );
  9219. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  9220. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  9221. if (empty($documentData)) {
  9222. // Try with iid
  9223. $table = Database::get_course_table(TABLE_DOCUMENT);
  9224. $sql = "SELECT path FROM $table
  9225. WHERE
  9226. c_id = ".api_get_course_int_id()." AND
  9227. iid = ".$row['path']." AND
  9228. path NOT LIKE '%_DELETED_%'";
  9229. $result = Database::query($sql);
  9230. $documentData = Database::fetch_array($result);
  9231. if ($documentData) {
  9232. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  9233. }
  9234. }
  9235. if (isset($documentData['absolute_path_from_document'])) {
  9236. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  9237. }
  9238. }
  9239. $return .= '</div>';
  9240. if (!empty($audio_player)) {
  9241. $return .= $audio_player;
  9242. }
  9243. return $return;
  9244. }
  9245. /**
  9246. * Creates the javascript needed for filling up the checkboxes without page reload.
  9247. *
  9248. * @return string
  9249. */
  9250. public function get_js_dropdown_array()
  9251. {
  9252. $course_id = api_get_course_int_id();
  9253. $return = 'var child_name = new Array();'."\n";
  9254. $return .= 'var child_value = new Array();'."\n\n";
  9255. $return .= 'child_name[0] = new Array();'."\n";
  9256. $return .= 'child_value[0] = new Array();'."\n\n";
  9257. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9258. $sql = "SELECT * FROM ".$tbl_lp_item."
  9259. WHERE
  9260. c_id = $course_id AND
  9261. lp_id = ".$this->lp_id." AND
  9262. parent_item_id = 0
  9263. ORDER BY display_order ASC";
  9264. $res_zero = Database::query($sql);
  9265. $i = 0;
  9266. while ($row_zero = Database::fetch_array($res_zero)) {
  9267. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  9268. if ($row_zero['item_type'] == TOOL_QUIZ) {
  9269. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  9270. }
  9271. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  9272. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  9273. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  9274. }
  9275. }
  9276. $return .= "\n";
  9277. $sql = "SELECT * FROM $tbl_lp_item
  9278. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9279. $res = Database::query($sql);
  9280. while ($row = Database::fetch_array($res)) {
  9281. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  9282. WHERE
  9283. c_id = ".$course_id." AND
  9284. parent_item_id = ".$row['iid']."
  9285. ORDER BY display_order ASC";
  9286. $res_parent = Database::query($sql_parent);
  9287. $i = 0;
  9288. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  9289. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  9290. while ($row_parent = Database::fetch_array($res_parent)) {
  9291. $js_var = json_encode(get_lang('After').' '.$row_parent['title']);
  9292. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  9293. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  9294. }
  9295. $return .= "\n";
  9296. }
  9297. $return .= "
  9298. function load_cbo(id) {
  9299. if (!id) {
  9300. return false;
  9301. }
  9302. var cbo = document.getElementById('previous');
  9303. for(var i = cbo.length - 1; i > 0; i--) {
  9304. cbo.options[i] = null;
  9305. }
  9306. var k=0;
  9307. for(var i = 1; i <= child_name[id].length; i++){
  9308. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  9309. option.style.paddingLeft = '40px';
  9310. cbo.options[i] = option;
  9311. k = i;
  9312. }
  9313. cbo.options[k].selected = true;
  9314. $('#previous').selectpicker('refresh');
  9315. }";
  9316. return $return;
  9317. }
  9318. /**
  9319. * Display the form to allow moving an item.
  9320. *
  9321. * @param int $item_id Item ID
  9322. *
  9323. * @throws Exception
  9324. * @throws HTML_QuickForm_Error
  9325. *
  9326. * @return string HTML form
  9327. */
  9328. public function display_move_item($item_id)
  9329. {
  9330. $return = '';
  9331. if (is_numeric($item_id)) {
  9332. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9333. $sql = "SELECT * FROM $tbl_lp_item
  9334. WHERE iid = $item_id";
  9335. $res = Database::query($sql);
  9336. $row = Database::fetch_array($res);
  9337. switch ($row['item_type']) {
  9338. case 'dir':
  9339. case 'asset':
  9340. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9341. $return .= $this->display_item_form(
  9342. $row['item_type'],
  9343. get_lang('MoveCurrentChapter'),
  9344. 'move',
  9345. $item_id,
  9346. $row
  9347. );
  9348. break;
  9349. case TOOL_DOCUMENT:
  9350. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9351. $return .= $this->display_document_form('move', $item_id, $row);
  9352. break;
  9353. case TOOL_LINK:
  9354. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9355. $return .= $this->display_link_form('move', $item_id, $row);
  9356. break;
  9357. case TOOL_HOTPOTATOES:
  9358. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9359. $return .= $this->display_link_form('move', $item_id, $row);
  9360. break;
  9361. case TOOL_QUIZ:
  9362. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9363. $return .= $this->display_quiz_form('move', $item_id, $row);
  9364. break;
  9365. case TOOL_STUDENTPUBLICATION:
  9366. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9367. $return .= $this->display_student_publication_form('move', $item_id, $row);
  9368. break;
  9369. case TOOL_FORUM:
  9370. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9371. $return .= $this->display_forum_form('move', $item_id, $row);
  9372. break;
  9373. case TOOL_THREAD:
  9374. $return .= $this->display_manipulate($item_id, $row['item_type']);
  9375. $return .= $this->display_forum_form('move', $item_id, $row);
  9376. break;
  9377. }
  9378. }
  9379. return $return;
  9380. }
  9381. /**
  9382. * Return HTML form to allow prerequisites selection.
  9383. *
  9384. * @todo use FormValidator
  9385. *
  9386. * @param int Item ID
  9387. *
  9388. * @return string HTML form
  9389. */
  9390. public function display_item_prerequisites_form($item_id = 0)
  9391. {
  9392. $course_id = api_get_course_int_id();
  9393. $item_id = (int) $item_id;
  9394. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  9395. /* Current prerequisite */
  9396. $sql = "SELECT * FROM $tbl_lp_item
  9397. WHERE iid = $item_id";
  9398. $result = Database::query($sql);
  9399. $row = Database::fetch_array($result);
  9400. $prerequisiteId = $row['prerequisite'];
  9401. $return = '<legend>';
  9402. $return .= get_lang('AddEditPrerequisites');
  9403. $return .= '</legend>';
  9404. $return .= '<form method="POST">';
  9405. $return .= '<div class="table-responsive">';
  9406. $return .= '<table class="table table-hover">';
  9407. $return .= '<thead>';
  9408. $return .= '<tr>';
  9409. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  9410. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  9411. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  9412. $return .= '</tr>';
  9413. $return .= '</thead>';
  9414. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  9415. $return .= '<tbody>';
  9416. $return .= '<tr>';
  9417. $return .= '<td colspan="3">';
  9418. $return .= '<div class="radio learnpath"><label for="idNone">';
  9419. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  9420. $return .= get_lang('None').'</label>';
  9421. $return .= '</div>';
  9422. $return .= '</tr>';
  9423. $sql = "SELECT * FROM $tbl_lp_item
  9424. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  9425. $result = Database::query($sql);
  9426. $arrLP = [];
  9427. $selectedMinScore = [];
  9428. $selectedMaxScore = [];
  9429. $masteryScore = [];
  9430. while ($row = Database::fetch_array($result)) {
  9431. if ($row['iid'] == $item_id) {
  9432. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  9433. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  9434. }
  9435. $masteryScore[$row['iid']] = $row['mastery_score'];
  9436. $arrLP[] = [
  9437. 'id' => $row['iid'],
  9438. 'item_type' => $row['item_type'],
  9439. 'title' => $row['title'],
  9440. 'ref' => $row['ref'],
  9441. 'description' => $row['description'],
  9442. 'parent_item_id' => $row['parent_item_id'],
  9443. 'previous_item_id' => $row['previous_item_id'],
  9444. 'next_item_id' => $row['next_item_id'],
  9445. 'max_score' => $row['max_score'],
  9446. 'min_score' => $row['min_score'],
  9447. 'mastery_score' => $row['mastery_score'],
  9448. 'prerequisite' => $row['prerequisite'],
  9449. 'display_order' => $row['display_order'],
  9450. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  9451. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  9452. ];
  9453. }
  9454. $this->tree_array($arrLP);
  9455. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  9456. unset($this->arrMenu);
  9457. for ($i = 0; $i < count($arrLP); $i++) {
  9458. $item = $arrLP[$i];
  9459. if ($item['id'] == $item_id) {
  9460. break;
  9461. }
  9462. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  9463. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  9464. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  9465. $return .= '<tr>';
  9466. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  9467. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  9468. $return .= '<label for="id'.$item['id'].'">';
  9469. $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'].'" />';
  9470. $icon_name = str_replace(' ', '', $item['item_type']);
  9471. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9472. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9473. } else {
  9474. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  9475. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  9476. } else {
  9477. $return .= Display::return_icon('folder_document.png');
  9478. }
  9479. }
  9480. $return .= $item['title'].'</label>';
  9481. $return .= '</div>';
  9482. $return .= '</td>';
  9483. if ($item['item_type'] == TOOL_QUIZ) {
  9484. // lets update max_score Quiz information depending of the Quiz Advanced properties
  9485. $lpItemObj = new LpItem($course_id, $item['id']);
  9486. $exercise = new Exercise($course_id);
  9487. $exercise->read($lpItemObj->path);
  9488. $lpItemObj->max_score = $exercise->get_max_score();
  9489. $lpItemObj->update();
  9490. $item['max_score'] = $lpItemObj->max_score;
  9491. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  9492. // Backwards compatibility with 1.9.x use mastery_score as min value
  9493. $selectedMinScoreValue = $masteryScoreAsMinValue;
  9494. }
  9495. $return .= '<td>';
  9496. $return .= '<input
  9497. class="form-control"
  9498. size="4" maxlength="3"
  9499. name="min_'.$item['id'].'"
  9500. type="number"
  9501. min="0"
  9502. step="1"
  9503. max="'.$item['max_score'].'"
  9504. value="'.$selectedMinScoreValue.'"
  9505. />';
  9506. $return .= '</td>';
  9507. $return .= '<td>';
  9508. $return .= '<input
  9509. class="form-control"
  9510. size="4"
  9511. maxlength="3"
  9512. name="max_'.$item['id'].'"
  9513. type="number"
  9514. min="0"
  9515. step="1"
  9516. max="'.$item['max_score'].'"
  9517. value="'.$selectedMaxScoreValue.'"
  9518. />';
  9519. $return .= '</td>';
  9520. }
  9521. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  9522. $return .= '<td>';
  9523. $return .= '<input
  9524. size="4"
  9525. maxlength="3"
  9526. name="min_'.$item['id'].'"
  9527. type="number"
  9528. min="0"
  9529. step="1"
  9530. max="'.$item['max_score'].'"
  9531. value="'.$selectedMinScoreValue.'"
  9532. />';
  9533. $return .= '</td>';
  9534. $return .= '<td>';
  9535. $return .= '<input
  9536. size="4"
  9537. maxlength="3"
  9538. name="max_'.$item['id'].'"
  9539. type="number"
  9540. min="0"
  9541. step="1"
  9542. max="'.$item['max_score'].'"
  9543. value="'.$selectedMaxScoreValue.'"
  9544. />';
  9545. $return .= '</td>';
  9546. }
  9547. $return .= '</tr>';
  9548. }
  9549. $return .= '<tr>';
  9550. $return .= '</tr>';
  9551. $return .= '</tbody>';
  9552. $return .= '</table>';
  9553. $return .= '</div>';
  9554. $return .= '<div class="form-group">';
  9555. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  9556. get_lang('ModifyPrerequisites').'</button>';
  9557. $return .= '</form>';
  9558. return $return;
  9559. }
  9560. /**
  9561. * Return HTML list to allow prerequisites selection for lp.
  9562. *
  9563. * @return string HTML form
  9564. */
  9565. public function display_lp_prerequisites_list()
  9566. {
  9567. $course_id = api_get_course_int_id();
  9568. $lp_id = $this->lp_id;
  9569. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9570. // get current prerequisite
  9571. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9572. $result = Database::query($sql);
  9573. $row = Database::fetch_array($result);
  9574. $prerequisiteId = $row['prerequisite'];
  9575. $session_id = api_get_session_id();
  9576. $session_condition = api_get_session_condition($session_id, true, true);
  9577. $sql = "SELECT * FROM $tbl_lp
  9578. WHERE c_id = $course_id $session_condition
  9579. ORDER BY display_order ";
  9580. $rs = Database::query($sql);
  9581. $return = '';
  9582. $return .= '<select name="prerequisites" class="form-control">';
  9583. $return .= '<option value="0">'.get_lang('None').'</option>';
  9584. if (Database::num_rows($rs) > 0) {
  9585. while ($row = Database::fetch_array($rs)) {
  9586. if ($row['id'] == $lp_id) {
  9587. continue;
  9588. }
  9589. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9590. }
  9591. }
  9592. $return .= '</select>';
  9593. return $return;
  9594. }
  9595. /**
  9596. * Creates a list with all the documents in it.
  9597. *
  9598. * @param bool $showInvisibleFiles
  9599. *
  9600. * @throws Exception
  9601. * @throws HTML_QuickForm_Error
  9602. *
  9603. * @return string
  9604. */
  9605. public function get_documents($showInvisibleFiles = false)
  9606. {
  9607. $course_info = api_get_course_info();
  9608. $sessionId = api_get_session_id();
  9609. $documentTree = DocumentManager::get_document_preview(
  9610. $course_info,
  9611. $this->lp_id,
  9612. null,
  9613. $sessionId,
  9614. true,
  9615. null,
  9616. null,
  9617. $showInvisibleFiles,
  9618. true
  9619. );
  9620. $headers = [
  9621. get_lang('Files'),
  9622. get_lang('CreateTheDocument'),
  9623. get_lang('CreateReadOutText'),
  9624. get_lang('Upload'),
  9625. ];
  9626. $form = new FormValidator(
  9627. 'form_upload',
  9628. 'POST',
  9629. $this->getCurrentBuildingModeURL(),
  9630. '',
  9631. ['enctype' => 'multipart/form-data']
  9632. );
  9633. $folders = DocumentManager::get_all_document_folders(
  9634. api_get_course_info(),
  9635. 0,
  9636. true
  9637. );
  9638. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9639. DocumentManager::build_directory_selector(
  9640. $folders,
  9641. $lpPathInfo['id'],
  9642. [],
  9643. true,
  9644. $form,
  9645. 'directory_parent_id'
  9646. );
  9647. $group = [
  9648. $form->createElement(
  9649. 'radio',
  9650. 'if_exists',
  9651. get_lang("UplWhatIfFileExists"),
  9652. get_lang('UplDoNothing'),
  9653. 'nothing'
  9654. ),
  9655. $form->createElement(
  9656. 'radio',
  9657. 'if_exists',
  9658. null,
  9659. get_lang('UplOverwriteLong'),
  9660. 'overwrite'
  9661. ),
  9662. $form->createElement(
  9663. 'radio',
  9664. 'if_exists',
  9665. null,
  9666. get_lang('UplRenameLong'),
  9667. 'rename'
  9668. ),
  9669. ];
  9670. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9671. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9672. $defaultFileExistsOption = 'rename';
  9673. if (!empty($fileExistsOption)) {
  9674. $defaultFileExistsOption = $fileExistsOption;
  9675. }
  9676. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9677. // Check box options
  9678. $form->addElement(
  9679. 'checkbox',
  9680. 'unzip',
  9681. get_lang('Options'),
  9682. get_lang('Uncompress')
  9683. );
  9684. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9685. $form->addMultipleUpload($url);
  9686. $new = $this->display_document_form('add', 0);
  9687. $frmReadOutText = $this->displayFrmReadOutText('add');
  9688. $tabs = Display::tabs(
  9689. $headers,
  9690. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9691. 'subtab'
  9692. );
  9693. return $tabs;
  9694. }
  9695. /**
  9696. * Creates a list with all the exercises (quiz) in it.
  9697. *
  9698. * @return string
  9699. */
  9700. public function get_exercises()
  9701. {
  9702. $course_id = api_get_course_int_id();
  9703. $session_id = api_get_session_id();
  9704. $userInfo = api_get_user_info();
  9705. // New for hotpotatoes.
  9706. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9707. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9708. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9709. $condition_session = api_get_session_condition($session_id, true, true);
  9710. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9711. $activeCondition = ' active <> -1 ';
  9712. if ($setting) {
  9713. $activeCondition = ' active = 1 ';
  9714. }
  9715. $sql_quiz = "SELECT * FROM $tbl_quiz
  9716. WHERE c_id = $course_id AND $activeCondition $condition_session
  9717. ORDER BY title ASC";
  9718. $sql_hot = "SELECT * FROM $tbl_doc
  9719. WHERE c_id = $course_id AND path LIKE '".$uploadPath."/%/%htm%' $condition_session
  9720. ORDER BY id ASC";
  9721. $res_quiz = Database::query($sql_quiz);
  9722. $res_hot = Database::query($sql_hot);
  9723. $return = '<ul class="lp_resource">';
  9724. $return .= '<li class="lp_resource_element">';
  9725. $return .= Display::return_icon('new_exercice.png');
  9726. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9727. get_lang('NewExercise').'</a>';
  9728. $return .= '</li>';
  9729. $previewIcon = Display::return_icon(
  9730. 'preview_view.png',
  9731. get_lang('Preview')
  9732. );
  9733. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9734. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9735. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9736. // Display hotpotatoes
  9737. while ($row_hot = Database::fetch_array($res_hot)) {
  9738. $link = Display::url(
  9739. $previewIcon,
  9740. $exerciseUrl.'&file='.$row_hot['path'],
  9741. ['target' => '_blank']
  9742. );
  9743. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9744. $return .= '<a class="moved" href="#">';
  9745. $return .= Display::return_icon(
  9746. 'move_everywhere.png',
  9747. get_lang('Move'),
  9748. [],
  9749. ICON_SIZE_TINY
  9750. );
  9751. $return .= '</a> ';
  9752. $return .= Display::return_icon('hotpotatoes_s.png');
  9753. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9754. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9755. $return .= '</li>';
  9756. }
  9757. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9758. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9759. $title = strip_tags(
  9760. api_html_entity_decode($row_quiz['title'])
  9761. );
  9762. $visibility = api_get_item_visibility(
  9763. ['real_id' => $course_id],
  9764. TOOL_QUIZ,
  9765. $row_quiz['iid'],
  9766. $session_id
  9767. );
  9768. $link = Display::url(
  9769. $previewIcon,
  9770. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9771. ['target' => '_blank']
  9772. );
  9773. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9774. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9775. $return .= $quizIcon;
  9776. $sessionStar = api_get_session_image(
  9777. $row_quiz['session_id'],
  9778. $userInfo['status']
  9779. );
  9780. $return .= Display::url(
  9781. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9782. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9783. [
  9784. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9785. ]
  9786. );
  9787. $return .= '</li>';
  9788. }
  9789. $return .= '</ul>';
  9790. return $return;
  9791. }
  9792. /**
  9793. * Creates a list with all the links in it.
  9794. *
  9795. * @return string
  9796. */
  9797. public function get_links()
  9798. {
  9799. $selfUrl = api_get_self();
  9800. $courseIdReq = api_get_cidreq();
  9801. $course = api_get_course_info();
  9802. $userInfo = api_get_user_info();
  9803. $course_id = $course['real_id'];
  9804. $tbl_link = Database::get_course_table(TABLE_LINK);
  9805. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9806. $moveEverywhereIcon = Display::return_icon(
  9807. 'move_everywhere.png',
  9808. get_lang('Move'),
  9809. [],
  9810. ICON_SIZE_TINY
  9811. );
  9812. $session_id = api_get_session_id();
  9813. $condition_session = api_get_session_condition(
  9814. $session_id,
  9815. true,
  9816. true,
  9817. "link.session_id"
  9818. );
  9819. $sql = "SELECT
  9820. link.id as link_id,
  9821. link.title as link_title,
  9822. link.session_id as link_session_id,
  9823. link.category_id as category_id,
  9824. link_category.category_title as category_title
  9825. FROM $tbl_link as link
  9826. LEFT JOIN $linkCategoryTable as link_category
  9827. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9828. WHERE link.c_id = ".$course_id." $condition_session
  9829. ORDER BY link_category.category_title ASC, link.title ASC";
  9830. $result = Database::query($sql);
  9831. $categorizedLinks = [];
  9832. $categories = [];
  9833. while ($link = Database::fetch_array($result)) {
  9834. if (!$link['category_id']) {
  9835. $link['category_title'] = get_lang('Uncategorized');
  9836. }
  9837. $categories[$link['category_id']] = $link['category_title'];
  9838. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9839. }
  9840. $linksHtmlCode =
  9841. '<script>
  9842. function toggle_tool(tool, id) {
  9843. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9844. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9845. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9846. } else {
  9847. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9848. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9849. }
  9850. }
  9851. </script>
  9852. <ul class="lp_resource">
  9853. <li class="lp_resource_element">
  9854. '.Display::return_icon('linksnew.gif').'
  9855. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9856. get_lang('LinkAdd').'
  9857. </a>
  9858. </li>';
  9859. foreach ($categorizedLinks as $categoryId => $links) {
  9860. $linkNodes = null;
  9861. foreach ($links as $key => $linkInfo) {
  9862. $title = $linkInfo['link_title'];
  9863. $linkSessionId = $linkInfo['link_session_id'];
  9864. $link = Display::url(
  9865. Display::return_icon('preview_view.png', get_lang('Preview')),
  9866. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9867. ['target' => '_blank']
  9868. );
  9869. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9870. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9871. $linkNodes .=
  9872. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9873. <a class="moved" href="#">'.
  9874. $moveEverywhereIcon.
  9875. '</a>
  9876. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9877. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9878. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9879. Security::remove_XSS($title).$sessionStar.$link.
  9880. '</a>
  9881. </li>';
  9882. }
  9883. }
  9884. $linksHtmlCode .=
  9885. '<li>
  9886. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9887. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9888. align="absbottom" />
  9889. </a>
  9890. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9891. </li>
  9892. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9893. }
  9894. $linksHtmlCode .= '</ul>';
  9895. return $linksHtmlCode;
  9896. }
  9897. /**
  9898. * Creates a list with all the student publications in it.
  9899. *
  9900. * @return string
  9901. */
  9902. public function get_student_publications()
  9903. {
  9904. $return = '<ul class="lp_resource">';
  9905. $return .= '<li class="lp_resource_element">';
  9906. $return .= Display::return_icon('works_new.gif');
  9907. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9908. get_lang('AddAssignmentPage').'</a>';
  9909. $return .= '</li>';
  9910. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9911. $works = getWorkListTeacher(0, 100, null, null, null);
  9912. if (!empty($works)) {
  9913. foreach ($works as $work) {
  9914. $link = Display::url(
  9915. Display::return_icon('preview_view.png', get_lang('Preview')),
  9916. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9917. ['target' => '_blank']
  9918. );
  9919. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9920. $return .= '<a class="moved" href="#">';
  9921. $return .= Display::return_icon(
  9922. 'move_everywhere.png',
  9923. get_lang('Move'),
  9924. [],
  9925. ICON_SIZE_TINY
  9926. );
  9927. $return .= '</a> ';
  9928. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9929. $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.'">'.
  9930. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9931. </a>';
  9932. $return .= '</li>';
  9933. }
  9934. }
  9935. $return .= '</ul>';
  9936. return $return;
  9937. }
  9938. /**
  9939. * Creates a list with all the forums in it.
  9940. *
  9941. * @return string
  9942. */
  9943. public function get_forums()
  9944. {
  9945. require_once '../forum/forumfunction.inc.php';
  9946. $forumCategories = get_forum_categories();
  9947. $forumsInNoCategory = get_forums_in_category(0);
  9948. if (!empty($forumsInNoCategory)) {
  9949. $forumCategories = array_merge(
  9950. $forumCategories,
  9951. [
  9952. [
  9953. 'cat_id' => 0,
  9954. 'session_id' => 0,
  9955. 'visibility' => 1,
  9956. 'cat_comment' => null,
  9957. ],
  9958. ]
  9959. );
  9960. }
  9961. $forumList = get_forums();
  9962. $a_forums = [];
  9963. foreach ($forumCategories as $forumCategory) {
  9964. // The forums in this category.
  9965. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9966. if (!empty($forumsInCategory)) {
  9967. foreach ($forumList as $forum) {
  9968. if (isset($forum['forum_category']) &&
  9969. $forum['forum_category'] == $forumCategory['cat_id']
  9970. ) {
  9971. $a_forums[] = $forum;
  9972. }
  9973. }
  9974. }
  9975. }
  9976. $return = '<ul class="lp_resource">';
  9977. // First add link
  9978. $return .= '<li class="lp_resource_element">';
  9979. $return .= Display::return_icon('new_forum.png');
  9980. $return .= Display::url(
  9981. get_lang('CreateANewForum'),
  9982. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9983. 'action' => 'add',
  9984. 'content' => 'forum',
  9985. 'lp_id' => $this->lp_id,
  9986. ]),
  9987. ['title' => get_lang('CreateANewForum')]
  9988. );
  9989. $return .= '</li>';
  9990. $return .= '<script>
  9991. function toggle_forum(forum_id) {
  9992. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9993. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9994. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9995. } else {
  9996. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9997. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9998. }
  9999. }
  10000. </script>';
  10001. foreach ($a_forums as $forum) {
  10002. if (!empty($forum['forum_id'])) {
  10003. $link = Display::url(
  10004. Display::return_icon('preview_view.png', get_lang('Preview')),
  10005. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  10006. ['target' => '_blank']
  10007. );
  10008. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  10009. $return .= '<a class="moved" href="#">';
  10010. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10011. $return .= ' </a>';
  10012. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  10013. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  10014. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  10015. </a>
  10016. <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">'.
  10017. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  10018. $return .= '</li>';
  10019. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  10020. $a_threads = get_threads($forum['forum_id']);
  10021. if (is_array($a_threads)) {
  10022. foreach ($a_threads as $thread) {
  10023. $link = Display::url(
  10024. Display::return_icon('preview_view.png', get_lang('Preview')),
  10025. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  10026. ['target' => '_blank']
  10027. );
  10028. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  10029. $return .= '&nbsp;<a class="moved" href="#">';
  10030. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  10031. $return .= ' </a>';
  10032. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  10033. $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.'">'.
  10034. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  10035. $return .= '</li>';
  10036. }
  10037. }
  10038. $return .= '</div>';
  10039. }
  10040. }
  10041. $return .= '</ul>';
  10042. return $return;
  10043. }
  10044. /**
  10045. * // TODO: The output encoding should be equal to the system encoding.
  10046. *
  10047. * Exports the learning path as a SCORM package. This is the main function that
  10048. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  10049. * whole thing and returns the zip.
  10050. *
  10051. * This method needs to be called in PHP5, as it will fail with non-adequate
  10052. * XML package (like the ones for PHP4), and it is *not* a static method, so
  10053. * you need to call it on a learnpath object.
  10054. *
  10055. * @TODO The method might be redefined later on in the scorm class itself to avoid
  10056. * creating a SCORM structure if there is one already. However, if the initial SCORM
  10057. * path has been modified, it should use the generic method here below.
  10058. *
  10059. * @return string Returns the zip package string, or null if error
  10060. */
  10061. public function scormExport()
  10062. {
  10063. api_set_more_memory_and_time_limits();
  10064. $_course = api_get_course_info();
  10065. $course_id = $_course['real_id'];
  10066. // Create the zip handler (this will remain available throughout the method).
  10067. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  10068. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10069. $temp_dir_short = uniqid('scorm_export', true);
  10070. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  10071. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  10072. $zip_folder = new PclZip($temp_zip_file);
  10073. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  10074. $root_path = $main_path = api_get_path(SYS_PATH);
  10075. $files_cleanup = [];
  10076. // Place to temporarily stash the zip file.
  10077. // create the temp dir if it doesn't exist
  10078. // or do a cleanup before creating the zip file.
  10079. if (!is_dir($temp_zip_dir)) {
  10080. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  10081. } else {
  10082. // Cleanup: Check the temp dir for old files and delete them.
  10083. $handle = opendir($temp_zip_dir);
  10084. while (false !== ($file = readdir($handle))) {
  10085. if ($file != '.' && $file != '..') {
  10086. unlink("$temp_zip_dir/$file");
  10087. }
  10088. }
  10089. closedir($handle);
  10090. }
  10091. $zip_files = $zip_files_abs = $zip_files_dist = [];
  10092. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  10093. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  10094. ) {
  10095. // Remove the possible . at the end of the path.
  10096. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  10097. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  10098. mkdir(
  10099. $dest_path_to_scorm_folder,
  10100. api_get_permissions_for_new_directories(),
  10101. true
  10102. );
  10103. copyr(
  10104. $current_course_path.'/scorm/'.$this->path,
  10105. $dest_path_to_scorm_folder,
  10106. ['imsmanifest'],
  10107. $zip_files
  10108. );
  10109. }
  10110. // Build a dummy imsmanifest structure.
  10111. // Do not add to the zip yet (we still need it).
  10112. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  10113. // Aggregation Model official document, section "2.3 Content Packaging".
  10114. // We are going to build a UTF-8 encoded manifest.
  10115. // Later we will recode it to the desired (and supported) encoding.
  10116. $xmldoc = new DOMDocument('1.0');
  10117. $root = $xmldoc->createElement('manifest');
  10118. $root->setAttribute('identifier', 'SingleCourseManifest');
  10119. $root->setAttribute('version', '1.1');
  10120. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  10121. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  10122. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  10123. $root->setAttribute(
  10124. 'xsi:schemaLocation',
  10125. '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'
  10126. );
  10127. // Build mandatory sub-root container elements.
  10128. $metadata = $xmldoc->createElement('metadata');
  10129. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  10130. $metadata->appendChild($md_schema);
  10131. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  10132. $metadata->appendChild($md_schemaversion);
  10133. $root->appendChild($metadata);
  10134. $organizations = $xmldoc->createElement('organizations');
  10135. $resources = $xmldoc->createElement('resources');
  10136. // Build the only organization we will use in building our learnpaths.
  10137. $organizations->setAttribute('default', 'chamilo_scorm_export');
  10138. $organization = $xmldoc->createElement('organization');
  10139. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  10140. // To set the title of the SCORM entity (=organization), we take the name given
  10141. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  10142. // learning path charset) as it is the encoding that defines how it is stored
  10143. // in the database. Then we convert it to HTML entities again as the "&" character
  10144. // alone is not authorized in XML (must be &amp;).
  10145. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  10146. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  10147. $organization->appendChild($org_title);
  10148. $folder_name = 'document';
  10149. // Removes the learning_path/scorm_folder path when exporting see #4841
  10150. $path_to_remove = '';
  10151. $path_to_replace = '';
  10152. $result = $this->generate_lp_folder($_course);
  10153. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  10154. $path_to_remove = 'document'.$result['dir'];
  10155. $path_to_replace = $folder_name.'/';
  10156. }
  10157. // Fixes chamilo scorm exports
  10158. if ($this->ref === 'chamilo_scorm_export') {
  10159. $path_to_remove = 'scorm/'.$this->path.'/document/';
  10160. }
  10161. // For each element, add it to the imsmanifest structure, then add it to the zip.
  10162. $link_updates = [];
  10163. $links_to_create = [];
  10164. foreach ($this->ordered_items as $index => $itemId) {
  10165. /** @var learnpathItem $item */
  10166. $item = $this->items[$itemId];
  10167. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  10168. // Get included documents from this item.
  10169. if ($item->type === 'sco') {
  10170. $inc_docs = $item->get_resources_from_source(
  10171. null,
  10172. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  10173. );
  10174. } else {
  10175. $inc_docs = $item->get_resources_from_source();
  10176. }
  10177. // Give a child element <item> to the <organization> element.
  10178. $my_item_id = $item->get_id();
  10179. $my_item = $xmldoc->createElement('item');
  10180. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  10181. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  10182. $my_item->setAttribute('isvisible', 'true');
  10183. // Give a child element <title> to the <item> element.
  10184. $my_title = $xmldoc->createElement(
  10185. 'title',
  10186. htmlspecialchars(
  10187. api_utf8_encode($item->get_title()),
  10188. ENT_QUOTES,
  10189. 'UTF-8'
  10190. )
  10191. );
  10192. $my_item->appendChild($my_title);
  10193. // Give a child element <adlcp:prerequisites> to the <item> element.
  10194. $my_prereqs = $xmldoc->createElement(
  10195. 'adlcp:prerequisites',
  10196. $this->get_scorm_prereq_string($my_item_id)
  10197. );
  10198. $my_prereqs->setAttribute('type', 'aicc_script');
  10199. $my_item->appendChild($my_prereqs);
  10200. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10201. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  10202. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10203. //$xmldoc->createElement('adlcp:timelimitaction','');
  10204. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10205. //$xmldoc->createElement('adlcp:datafromlms','');
  10206. // Give a child element <adlcp:masteryscore> to the <item> element.
  10207. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10208. $my_item->appendChild($my_masteryscore);
  10209. // Attach this item to the organization element or hits parent if there is one.
  10210. if (!empty($item->parent) && $item->parent != 0) {
  10211. $children = $organization->childNodes;
  10212. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10213. if (is_object($possible_parent)) {
  10214. $possible_parent->appendChild($my_item);
  10215. } else {
  10216. if ($this->debug > 0) {
  10217. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  10218. }
  10219. }
  10220. } else {
  10221. if ($this->debug > 0) {
  10222. error_log('No parent');
  10223. }
  10224. $organization->appendChild($my_item);
  10225. }
  10226. // Get the path of the file(s) from the course directory root.
  10227. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10228. $my_xml_file_path = $my_file_path;
  10229. if (!empty($path_to_remove)) {
  10230. // From docs
  10231. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  10232. // From quiz
  10233. if ($this->ref === 'chamilo_scorm_export') {
  10234. $path_to_remove = 'scorm/'.$this->path.'/';
  10235. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  10236. }
  10237. }
  10238. $my_sub_dir = dirname($my_file_path);
  10239. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10240. $my_xml_sub_dir = $my_sub_dir;
  10241. // Give a <resource> child to the <resources> element
  10242. $my_resource = $xmldoc->createElement('resource');
  10243. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10244. $my_resource->setAttribute('type', 'webcontent');
  10245. $my_resource->setAttribute('href', $my_xml_file_path);
  10246. // adlcp:scormtype can be either 'sco' or 'asset'.
  10247. if ($item->type === 'sco') {
  10248. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10249. } else {
  10250. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10251. }
  10252. // xml:base is the base directory to find the files declared in this resource.
  10253. $my_resource->setAttribute('xml:base', '');
  10254. // Give a <file> child to the <resource> element.
  10255. $my_file = $xmldoc->createElement('file');
  10256. $my_file->setAttribute('href', $my_xml_file_path);
  10257. $my_resource->appendChild($my_file);
  10258. // Dependency to other files - not yet supported.
  10259. $i = 1;
  10260. if ($inc_docs) {
  10261. foreach ($inc_docs as $doc_info) {
  10262. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10263. continue;
  10264. }
  10265. $my_dep = $xmldoc->createElement('resource');
  10266. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10267. $my_dep->setAttribute('identifier', $res_id);
  10268. $my_dep->setAttribute('type', 'webcontent');
  10269. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10270. $my_dep_file = $xmldoc->createElement('file');
  10271. // Check type of URL.
  10272. if ($doc_info[1] == 'remote') {
  10273. // Remote file. Save url as is.
  10274. $my_dep_file->setAttribute('href', $doc_info[0]);
  10275. $my_dep->setAttribute('xml:base', '');
  10276. } elseif ($doc_info[1] === 'local') {
  10277. switch ($doc_info[2]) {
  10278. case 'url':
  10279. // Local URL - save path as url for now, don't zip file.
  10280. $abs_path = api_get_path(SYS_PATH).
  10281. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10282. $current_dir = dirname($abs_path);
  10283. $current_dir = str_replace('\\', '/', $current_dir);
  10284. $file_path = realpath($abs_path);
  10285. $file_path = str_replace('\\', '/', $file_path);
  10286. $my_dep_file->setAttribute('href', $file_path);
  10287. $my_dep->setAttribute('xml:base', '');
  10288. if (strstr($file_path, $main_path) !== false) {
  10289. // The calculated real path is really inside Chamilo's root path.
  10290. // Reduce file path to what's under the DocumentRoot.
  10291. $replace = $file_path;
  10292. $file_path = substr($file_path, strlen($root_path) - 1);
  10293. $destinationFile = $file_path;
  10294. if (strstr($file_path, 'upload/users') !== false) {
  10295. $pos = strpos($file_path, 'my_files/');
  10296. if ($pos !== false) {
  10297. $onlyDirectory = str_replace(
  10298. 'upload/users/',
  10299. '',
  10300. substr($file_path, $pos, strlen($file_path))
  10301. );
  10302. }
  10303. $replace = $onlyDirectory;
  10304. $destinationFile = $replace;
  10305. }
  10306. $zip_files_abs[] = $file_path;
  10307. $link_updates[$my_file_path][] = [
  10308. 'orig' => $doc_info[0],
  10309. 'dest' => $destinationFile,
  10310. 'replace' => $replace,
  10311. ];
  10312. $my_dep_file->setAttribute('href', $file_path);
  10313. $my_dep->setAttribute('xml:base', '');
  10314. } elseif (empty($file_path)) {
  10315. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10316. $file_path = str_replace('//', '/', $file_path);
  10317. if (file_exists($file_path)) {
  10318. // We get the relative path.
  10319. $file_path = substr($file_path, strlen($current_dir));
  10320. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10321. $link_updates[$my_file_path][] = [
  10322. 'orig' => $doc_info[0],
  10323. 'dest' => $file_path,
  10324. ];
  10325. $my_dep_file->setAttribute('href', $file_path);
  10326. $my_dep->setAttribute('xml:base', '');
  10327. }
  10328. }
  10329. break;
  10330. case 'abs':
  10331. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10332. $my_dep_file->setAttribute('href', $doc_info[0]);
  10333. $my_dep->setAttribute('xml:base', '');
  10334. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  10335. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  10336. $abs_img_path_without_subdir = $doc_info[0];
  10337. $relp = api_get_path(REL_PATH); // The url-append config param.
  10338. $pos = strpos($abs_img_path_without_subdir, $relp);
  10339. if ($pos === 0) {
  10340. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  10341. }
  10342. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  10343. $file_path = str_replace(['\\', '//'], '/', $file_path);
  10344. // Prepare the current directory path (until just under 'document') with a trailing slash.
  10345. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  10346. // Check if the current document is in that path.
  10347. if (strstr($file_path, $cur_path) !== false) {
  10348. $destinationFile = substr($file_path, strlen($cur_path));
  10349. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  10350. $fileToTest = $cur_path.$my_file_path;
  10351. if (!empty($path_to_remove)) {
  10352. $fileToTest = str_replace(
  10353. $path_to_remove.'/',
  10354. $path_to_replace,
  10355. $cur_path.$my_file_path
  10356. );
  10357. }
  10358. $relative_path = api_get_relative_path($fileToTest, $file_path);
  10359. // Put the current document in the zip (this array is the array
  10360. // that will manage documents already in the course folder - relative).
  10361. $zip_files[] = $filePathNoCoursePart;
  10362. // Update the links to the current document in the
  10363. // containing document (make them relative).
  10364. $link_updates[$my_file_path][] = [
  10365. 'orig' => $doc_info[0],
  10366. 'dest' => $destinationFile,
  10367. 'replace' => $relative_path,
  10368. ];
  10369. $my_dep_file->setAttribute('href', $file_path);
  10370. $my_dep->setAttribute('xml:base', '');
  10371. } elseif (strstr($file_path, $main_path) !== false) {
  10372. // The calculated real path is really inside Chamilo's root path.
  10373. // Reduce file path to what's under the DocumentRoot.
  10374. $file_path = substr($file_path, strlen($root_path));
  10375. $zip_files_abs[] = $file_path;
  10376. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10377. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10378. $my_dep->setAttribute('xml:base', '');
  10379. } elseif (empty($file_path)) {
  10380. // Probably this is an image inside "/main" directory
  10381. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  10382. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10383. if (file_exists($file_path)) {
  10384. if (strstr($file_path, 'main/default_course_document') !== false) {
  10385. // We get the relative path.
  10386. $pos = strpos($file_path, 'main/default_course_document/');
  10387. if ($pos !== false) {
  10388. $onlyDirectory = str_replace(
  10389. 'main/default_course_document/',
  10390. '',
  10391. substr($file_path, $pos, strlen($file_path))
  10392. );
  10393. }
  10394. $destinationFile = 'default_course_document/'.$onlyDirectory;
  10395. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  10396. $zip_files_abs[] = $fileAbs;
  10397. $link_updates[$my_file_path][] = [
  10398. 'orig' => $doc_info[0],
  10399. 'dest' => $destinationFile,
  10400. ];
  10401. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10402. $my_dep->setAttribute('xml:base', '');
  10403. }
  10404. }
  10405. }
  10406. break;
  10407. case 'rel':
  10408. // Path relative to the current document.
  10409. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  10410. if (substr($doc_info[0], 0, 2) === '..') {
  10411. // Relative path going up.
  10412. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10413. $current_dir = str_replace('\\', '/', $current_dir);
  10414. $file_path = realpath($current_dir.$doc_info[0]);
  10415. $file_path = str_replace('\\', '/', $file_path);
  10416. if (strstr($file_path, $main_path) !== false) {
  10417. // The calculated real path is really inside Chamilo's root path.
  10418. // Reduce file path to what's under the DocumentRoot.
  10419. $file_path = substr($file_path, strlen($root_path));
  10420. $zip_files_abs[] = $file_path;
  10421. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  10422. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10423. $my_dep->setAttribute('xml:base', '');
  10424. }
  10425. } else {
  10426. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10427. $my_dep_file->setAttribute('href', $doc_info[0]);
  10428. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10429. }
  10430. break;
  10431. default:
  10432. $my_dep_file->setAttribute('href', $doc_info[0]);
  10433. $my_dep->setAttribute('xml:base', '');
  10434. break;
  10435. }
  10436. }
  10437. $my_dep->appendChild($my_dep_file);
  10438. $resources->appendChild($my_dep);
  10439. $dependency = $xmldoc->createElement('dependency');
  10440. $dependency->setAttribute('identifierref', $res_id);
  10441. $my_resource->appendChild($dependency);
  10442. $i++;
  10443. }
  10444. }
  10445. $resources->appendChild($my_resource);
  10446. $zip_files[] = $my_file_path;
  10447. } else {
  10448. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  10449. switch ($item->type) {
  10450. case TOOL_LINK:
  10451. $my_item = $xmldoc->createElement('item');
  10452. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10453. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10454. $my_item->setAttribute('isvisible', 'true');
  10455. // Give a child element <title> to the <item> element.
  10456. $my_title = $xmldoc->createElement(
  10457. 'title',
  10458. htmlspecialchars(
  10459. api_utf8_encode($item->get_title()),
  10460. ENT_QUOTES,
  10461. 'UTF-8'
  10462. )
  10463. );
  10464. $my_item->appendChild($my_title);
  10465. // Give a child element <adlcp:prerequisites> to the <item> element.
  10466. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10467. $my_prereqs->setAttribute('type', 'aicc_script');
  10468. $my_item->appendChild($my_prereqs);
  10469. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  10470. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  10471. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  10472. //$xmldoc->createElement('adlcp:timelimitaction', '');
  10473. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  10474. //$xmldoc->createElement('adlcp:datafromlms', '');
  10475. // Give a child element <adlcp:masteryscore> to the <item> element.
  10476. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10477. $my_item->appendChild($my_masteryscore);
  10478. // Attach this item to the organization element or its parent if there is one.
  10479. if (!empty($item->parent) && $item->parent != 0) {
  10480. $children = $organization->childNodes;
  10481. for ($i = 0; $i < $children->length; $i++) {
  10482. $item_temp = $children->item($i);
  10483. if ($item_temp->nodeName == 'item') {
  10484. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  10485. $item_temp->appendChild($my_item);
  10486. }
  10487. }
  10488. }
  10489. } else {
  10490. $organization->appendChild($my_item);
  10491. }
  10492. $my_file_path = 'link_'.$item->get_id().'.html';
  10493. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  10494. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  10495. $rs = Database::query($sql);
  10496. if ($link = Database::fetch_array($rs)) {
  10497. $url = $link['url'];
  10498. $title = stripslashes($link['title']);
  10499. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  10500. $my_xml_file_path = $my_file_path;
  10501. $my_sub_dir = dirname($my_file_path);
  10502. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10503. $my_xml_sub_dir = $my_sub_dir;
  10504. // Give a <resource> child to the <resources> element.
  10505. $my_resource = $xmldoc->createElement('resource');
  10506. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10507. $my_resource->setAttribute('type', 'webcontent');
  10508. $my_resource->setAttribute('href', $my_xml_file_path);
  10509. // adlcp:scormtype can be either 'sco' or 'asset'.
  10510. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10511. // xml:base is the base directory to find the files declared in this resource.
  10512. $my_resource->setAttribute('xml:base', '');
  10513. // give a <file> child to the <resource> element.
  10514. $my_file = $xmldoc->createElement('file');
  10515. $my_file->setAttribute('href', $my_xml_file_path);
  10516. $my_resource->appendChild($my_file);
  10517. $resources->appendChild($my_resource);
  10518. }
  10519. break;
  10520. case TOOL_QUIZ:
  10521. $exe_id = $item->path;
  10522. // Should be using ref when everything will be cleaned up in this regard.
  10523. $exe = new Exercise();
  10524. $exe->read($exe_id);
  10525. $my_item = $xmldoc->createElement('item');
  10526. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10527. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10528. $my_item->setAttribute('isvisible', 'true');
  10529. // Give a child element <title> to the <item> element.
  10530. $my_title = $xmldoc->createElement(
  10531. 'title',
  10532. htmlspecialchars(
  10533. api_utf8_encode($item->get_title()),
  10534. ENT_QUOTES,
  10535. 'UTF-8'
  10536. )
  10537. );
  10538. $my_item->appendChild($my_title);
  10539. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10540. $my_item->appendChild($my_max_score);
  10541. // Give a child element <adlcp:prerequisites> to the <item> element.
  10542. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10543. $my_prereqs->setAttribute('type', 'aicc_script');
  10544. $my_item->appendChild($my_prereqs);
  10545. // Give a child element <adlcp:masteryscore> to the <item> element.
  10546. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10547. $my_item->appendChild($my_masteryscore);
  10548. // Attach this item to the organization element or hits parent if there is one.
  10549. if (!empty($item->parent) && $item->parent != 0) {
  10550. $children = $organization->childNodes;
  10551. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10552. if ($possible_parent) {
  10553. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10554. $possible_parent->appendChild($my_item);
  10555. }
  10556. }
  10557. } else {
  10558. $organization->appendChild($my_item);
  10559. }
  10560. // Get the path of the file(s) from the course directory root
  10561. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10562. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10563. // Write the contents of the exported exercise into a (big) html file
  10564. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10565. $scormExercise = new ScormExercise($exe, true);
  10566. $contents = $scormExercise->export();
  10567. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10568. $res = file_put_contents($tmp_file_path, $contents);
  10569. if ($res === false) {
  10570. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10571. }
  10572. $files_cleanup[] = $tmp_file_path;
  10573. $my_xml_file_path = $my_file_path;
  10574. $my_sub_dir = dirname($my_file_path);
  10575. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10576. $my_xml_sub_dir = $my_sub_dir;
  10577. // Give a <resource> child to the <resources> element.
  10578. $my_resource = $xmldoc->createElement('resource');
  10579. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10580. $my_resource->setAttribute('type', 'webcontent');
  10581. $my_resource->setAttribute('href', $my_xml_file_path);
  10582. // adlcp:scormtype can be either 'sco' or 'asset'.
  10583. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10584. // xml:base is the base directory to find the files declared in this resource.
  10585. $my_resource->setAttribute('xml:base', '');
  10586. // Give a <file> child to the <resource> element.
  10587. $my_file = $xmldoc->createElement('file');
  10588. $my_file->setAttribute('href', $my_xml_file_path);
  10589. $my_resource->appendChild($my_file);
  10590. // Get included docs.
  10591. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10592. // Dependency to other files - not yet supported.
  10593. $i = 1;
  10594. foreach ($inc_docs as $doc_info) {
  10595. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10596. continue;
  10597. }
  10598. $my_dep = $xmldoc->createElement('resource');
  10599. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10600. $my_dep->setAttribute('identifier', $res_id);
  10601. $my_dep->setAttribute('type', 'webcontent');
  10602. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10603. $my_dep_file = $xmldoc->createElement('file');
  10604. // Check type of URL.
  10605. if ($doc_info[1] == 'remote') {
  10606. // Remote file. Save url as is.
  10607. $my_dep_file->setAttribute('href', $doc_info[0]);
  10608. $my_dep->setAttribute('xml:base', '');
  10609. } elseif ($doc_info[1] == 'local') {
  10610. switch ($doc_info[2]) {
  10611. case 'url': // Local URL - save path as url for now, don't zip file.
  10612. // Save file but as local file (retrieve from URL).
  10613. $abs_path = api_get_path(SYS_PATH).
  10614. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10615. $current_dir = dirname($abs_path);
  10616. $current_dir = str_replace('\\', '/', $current_dir);
  10617. $file_path = realpath($abs_path);
  10618. $file_path = str_replace('\\', '/', $file_path);
  10619. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10620. $my_dep->setAttribute('xml:base', '');
  10621. if (strstr($file_path, $main_path) !== false) {
  10622. // The calculated real path is really inside the chamilo root path.
  10623. // Reduce file path to what's under the DocumentRoot.
  10624. $file_path = substr($file_path, strlen($root_path));
  10625. $zip_files_abs[] = $file_path;
  10626. $link_updates[$my_file_path][] = [
  10627. 'orig' => $doc_info[0],
  10628. 'dest' => 'document/'.$file_path,
  10629. ];
  10630. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10631. $my_dep->setAttribute('xml:base', '');
  10632. } elseif (empty($file_path)) {
  10633. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10634. $file_path = str_replace('//', '/', $file_path);
  10635. if (file_exists($file_path)) {
  10636. $file_path = substr($file_path, strlen($current_dir));
  10637. // We get the relative path.
  10638. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10639. $link_updates[$my_file_path][] = [
  10640. 'orig' => $doc_info[0],
  10641. 'dest' => 'document/'.$file_path,
  10642. ];
  10643. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10644. $my_dep->setAttribute('xml:base', '');
  10645. }
  10646. }
  10647. break;
  10648. case 'abs':
  10649. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10650. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10651. $current_dir = str_replace('\\', '/', $current_dir);
  10652. $file_path = realpath($doc_info[0]);
  10653. $file_path = str_replace('\\', '/', $file_path);
  10654. $my_dep_file->setAttribute('href', $file_path);
  10655. $my_dep->setAttribute('xml:base', '');
  10656. if (strstr($file_path, $main_path) !== false) {
  10657. // The calculated real path is really inside the chamilo root path.
  10658. // Reduce file path to what's under the DocumentRoot.
  10659. $file_path = substr($file_path, strlen($root_path));
  10660. $zip_files_abs[] = $file_path;
  10661. $link_updates[$my_file_path][] = [
  10662. 'orig' => $doc_info[0],
  10663. 'dest' => $file_path,
  10664. ];
  10665. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10666. $my_dep->setAttribute('xml:base', '');
  10667. } elseif (empty($file_path)) {
  10668. $docSysPartPath = str_replace(
  10669. api_get_path(REL_COURSE_PATH),
  10670. '',
  10671. $doc_info[0]
  10672. );
  10673. $docSysPartPathNoCourseCode = str_replace(
  10674. $_course['directory'].'/',
  10675. '',
  10676. $docSysPartPath
  10677. );
  10678. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10679. if (file_exists($docSysPath)) {
  10680. $file_path = $docSysPartPathNoCourseCode;
  10681. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10682. $link_updates[$my_file_path][] = [
  10683. 'orig' => $doc_info[0],
  10684. 'dest' => $file_path,
  10685. ];
  10686. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10687. $my_dep->setAttribute('xml:base', '');
  10688. }
  10689. }
  10690. break;
  10691. case 'rel':
  10692. // Path relative to the current document. Save xml:base as current document's
  10693. // directory and save file in zip as subdir.file_path
  10694. if (substr($doc_info[0], 0, 2) === '..') {
  10695. // Relative path going up.
  10696. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10697. $current_dir = str_replace('\\', '/', $current_dir);
  10698. $file_path = realpath($current_dir.$doc_info[0]);
  10699. $file_path = str_replace('\\', '/', $file_path);
  10700. //error_log($file_path.' <-> '.$main_path, 0);
  10701. if (strstr($file_path, $main_path) !== false) {
  10702. // The calculated real path is really inside Chamilo's root path.
  10703. // Reduce file path to what's under the DocumentRoot.
  10704. $file_path = substr($file_path, strlen($root_path));
  10705. $file_path_dest = $file_path;
  10706. // File path is courses/CHAMILO/document/....
  10707. $info_file_path = explode('/', $file_path);
  10708. if ($info_file_path[0] == 'courses') {
  10709. // Add character "/" in file path.
  10710. $file_path_dest = 'document/'.$file_path;
  10711. }
  10712. $zip_files_abs[] = $file_path;
  10713. $link_updates[$my_file_path][] = [
  10714. 'orig' => $doc_info[0],
  10715. 'dest' => $file_path_dest,
  10716. ];
  10717. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10718. $my_dep->setAttribute('xml:base', '');
  10719. }
  10720. } else {
  10721. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10722. $my_dep_file->setAttribute('href', $doc_info[0]);
  10723. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10724. }
  10725. break;
  10726. default:
  10727. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10728. $my_dep->setAttribute('xml:base', '');
  10729. break;
  10730. }
  10731. }
  10732. $my_dep->appendChild($my_dep_file);
  10733. $resources->appendChild($my_dep);
  10734. $dependency = $xmldoc->createElement('dependency');
  10735. $dependency->setAttribute('identifierref', $res_id);
  10736. $my_resource->appendChild($dependency);
  10737. $i++;
  10738. }
  10739. $resources->appendChild($my_resource);
  10740. $zip_files[] = $my_file_path;
  10741. break;
  10742. default:
  10743. // Get the path of the file(s) from the course directory root
  10744. $my_file_path = 'non_exportable.html';
  10745. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10746. $my_xml_file_path = $my_file_path;
  10747. $my_sub_dir = dirname($my_file_path);
  10748. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10749. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10750. $my_xml_sub_dir = $my_sub_dir;
  10751. // Give a <resource> child to the <resources> element.
  10752. $my_resource = $xmldoc->createElement('resource');
  10753. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10754. $my_resource->setAttribute('type', 'webcontent');
  10755. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10756. // adlcp:scormtype can be either 'sco' or 'asset'.
  10757. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10758. // xml:base is the base directory to find the files declared in this resource.
  10759. $my_resource->setAttribute('xml:base', '');
  10760. // Give a <file> child to the <resource> element.
  10761. $my_file = $xmldoc->createElement('file');
  10762. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10763. $my_resource->appendChild($my_file);
  10764. $resources->appendChild($my_resource);
  10765. break;
  10766. }
  10767. }
  10768. }
  10769. $organizations->appendChild($organization);
  10770. $root->appendChild($organizations);
  10771. $root->appendChild($resources);
  10772. $xmldoc->appendChild($root);
  10773. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10774. // then add the file to the zip, then destroy the file (this is done automatically).
  10775. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10776. foreach ($zip_files as $file_path) {
  10777. if (empty($file_path)) {
  10778. continue;
  10779. }
  10780. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10781. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10782. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10783. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10784. }
  10785. $this->create_path($dest_file);
  10786. @copy($filePath, $dest_file);
  10787. // Check if the file needs a link update.
  10788. if (in_array($file_path, array_keys($link_updates))) {
  10789. $string = file_get_contents($dest_file);
  10790. unlink($dest_file);
  10791. foreach ($link_updates[$file_path] as $old_new) {
  10792. // This is an ugly hack that allows .flv files to be found by the flv player that
  10793. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10794. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10795. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10796. if (substr($old_new['dest'], -3) === 'flv' &&
  10797. substr($old_new['dest'], 0, 5) === 'main/'
  10798. ) {
  10799. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10800. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10801. substr($old_new['dest'], 0, 6) === 'video/'
  10802. ) {
  10803. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10804. }
  10805. // Fix to avoid problems with default_course_document
  10806. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10807. $newDestination = $old_new['dest'];
  10808. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10809. $newDestination = $old_new['replace'];
  10810. }
  10811. } else {
  10812. $newDestination = str_replace('document/', '', $old_new['dest']);
  10813. }
  10814. $string = str_replace($old_new['orig'], $newDestination, $string);
  10815. // Add files inside the HTMLs
  10816. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10817. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10818. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10819. copy(
  10820. $sys_course_path.$new_path,
  10821. $destinationFile
  10822. );
  10823. }
  10824. }
  10825. file_put_contents($dest_file, $string);
  10826. }
  10827. if (file_exists($filePath) && $copyAll) {
  10828. $extension = $this->get_extension($filePath);
  10829. if (in_array($extension, ['html', 'html'])) {
  10830. $containerOrigin = dirname($filePath);
  10831. $containerDestination = dirname($dest_file);
  10832. $finder = new Finder();
  10833. $finder->files()->in($containerOrigin)
  10834. ->notName('*_DELETED_*')
  10835. ->exclude('share_folder')
  10836. ->exclude('chat_files')
  10837. ->exclude('certificates')
  10838. ;
  10839. if (is_dir($containerOrigin) &&
  10840. is_dir($containerDestination)
  10841. ) {
  10842. $fs = new Filesystem();
  10843. $fs->mirror(
  10844. $containerOrigin,
  10845. $containerDestination,
  10846. $finder
  10847. );
  10848. }
  10849. }
  10850. }
  10851. }
  10852. foreach ($zip_files_abs as $file_path) {
  10853. if (empty($file_path)) {
  10854. continue;
  10855. }
  10856. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10857. continue;
  10858. }
  10859. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10860. if (strstr($file_path, 'upload/users') !== false) {
  10861. $pos = strpos($file_path, 'my_files/');
  10862. if ($pos !== false) {
  10863. $onlyDirectory = str_replace(
  10864. 'upload/users/',
  10865. '',
  10866. substr($file_path, $pos, strlen($file_path))
  10867. );
  10868. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10869. }
  10870. }
  10871. if (strstr($file_path, 'default_course_document/') !== false) {
  10872. $replace = str_replace('/main', '', $file_path);
  10873. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10874. }
  10875. if (empty($dest_file)) {
  10876. continue;
  10877. }
  10878. $this->create_path($dest_file);
  10879. copy($main_path.$file_path, $dest_file);
  10880. // Check if the file needs a link update.
  10881. if (in_array($file_path, array_keys($link_updates))) {
  10882. $string = file_get_contents($dest_file);
  10883. unlink($dest_file);
  10884. foreach ($link_updates[$file_path] as $old_new) {
  10885. // This is an ugly hack that allows .flv files to be found by the flv player that
  10886. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10887. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10888. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10889. if (substr($old_new['dest'], -3) == 'flv' &&
  10890. substr($old_new['dest'], 0, 5) == 'main/'
  10891. ) {
  10892. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10893. }
  10894. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10895. }
  10896. file_put_contents($dest_file, $string);
  10897. }
  10898. }
  10899. if (is_array($links_to_create)) {
  10900. foreach ($links_to_create as $file => $link) {
  10901. $content = '<!DOCTYPE html><head>
  10902. <meta charset="'.api_get_language_isocode().'" />
  10903. <title>'.$link['title'].'</title>
  10904. </head>
  10905. <body dir="'.api_get_text_direction().'">
  10906. <div style="text-align:center">
  10907. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10908. </body>
  10909. </html>';
  10910. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10911. }
  10912. }
  10913. // Add non exportable message explanation.
  10914. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10915. $file_content = '<!DOCTYPE html><head>
  10916. <meta charset="'.api_get_language_isocode().'" />
  10917. <title>'.$lang_not_exportable.'</title>
  10918. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10919. </head>
  10920. <body dir="'.api_get_text_direction().'">';
  10921. $file_content .=
  10922. <<<EOD
  10923. <style>
  10924. .error-message {
  10925. font-family: arial, verdana, helvetica, sans-serif;
  10926. border-width: 1px;
  10927. border-style: solid;
  10928. left: 50%;
  10929. margin: 10px auto;
  10930. min-height: 30px;
  10931. padding: 5px;
  10932. right: 50%;
  10933. width: 500px;
  10934. background-color: #FFD1D1;
  10935. border-color: #FF0000;
  10936. color: #000;
  10937. }
  10938. </style>
  10939. <body>
  10940. <div class="error-message">
  10941. $lang_not_exportable
  10942. </div>
  10943. </body>
  10944. </html>
  10945. EOD;
  10946. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10947. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10948. }
  10949. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10950. // Add the extra files that go along with a SCORM package.
  10951. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10952. $fs = new Filesystem();
  10953. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10954. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10955. $manifest = @$xmldoc->saveXML();
  10956. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10957. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10958. $zip_folder->add(
  10959. $archivePath.'/'.$temp_dir_short,
  10960. PCLZIP_OPT_REMOVE_PATH,
  10961. $archivePath.'/'.$temp_dir_short.'/'
  10962. );
  10963. // Clean possible temporary files.
  10964. foreach ($files_cleanup as $file) {
  10965. $res = unlink($file);
  10966. if ($res === false) {
  10967. error_log(
  10968. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10969. 0
  10970. );
  10971. }
  10972. }
  10973. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10974. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10975. }
  10976. /**
  10977. * @param int $lp_id
  10978. *
  10979. * @return bool
  10980. */
  10981. public function scorm_export_to_pdf($lp_id)
  10982. {
  10983. $lp_id = (int) $lp_id;
  10984. $files_to_export = [];
  10985. $course_data = api_get_course_info($this->cc);
  10986. if (!empty($course_data)) {
  10987. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10988. $list = self::get_flat_ordered_items_list($lp_id);
  10989. if (!empty($list)) {
  10990. foreach ($list as $item_id) {
  10991. $item = $this->items[$item_id];
  10992. switch ($item->type) {
  10993. case 'document':
  10994. //Getting documents from a LP with chamilo documents
  10995. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10996. // Try loading document from the base course.
  10997. if (empty($file_data) && !empty($sessionId)) {
  10998. $file_data = DocumentManager::get_document_data_by_id(
  10999. $item->path,
  11000. $this->cc,
  11001. false,
  11002. 0
  11003. );
  11004. }
  11005. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  11006. if (file_exists($file_path)) {
  11007. $files_to_export[] = [
  11008. 'title' => $item->get_title(),
  11009. 'path' => $file_path,
  11010. ];
  11011. }
  11012. break;
  11013. case 'asset': //commes from a scorm package generated by chamilo
  11014. case 'sco':
  11015. $file_path = $scorm_path.'/'.$item->path;
  11016. if (file_exists($file_path)) {
  11017. $files_to_export[] = [
  11018. 'title' => $item->get_title(),
  11019. 'path' => $file_path,
  11020. ];
  11021. }
  11022. break;
  11023. case 'dir':
  11024. $files_to_export[] = [
  11025. 'title' => $item->get_title(),
  11026. 'path' => null,
  11027. ];
  11028. break;
  11029. }
  11030. }
  11031. }
  11032. $pdf = new PDF();
  11033. $result = $pdf->html_to_pdf(
  11034. $files_to_export,
  11035. $this->name,
  11036. $this->cc,
  11037. true
  11038. );
  11039. return $result;
  11040. }
  11041. return false;
  11042. }
  11043. /**
  11044. * Temp function to be moved in main_api or the best place around for this.
  11045. * Creates a file path if it doesn't exist.
  11046. *
  11047. * @param string $path
  11048. */
  11049. public function create_path($path)
  11050. {
  11051. $path_bits = explode('/', dirname($path));
  11052. // IS_WINDOWS_OS has been defined in main_api.lib.php
  11053. $path_built = IS_WINDOWS_OS ? '' : '/';
  11054. foreach ($path_bits as $bit) {
  11055. if (!empty($bit)) {
  11056. $new_path = $path_built.$bit;
  11057. if (is_dir($new_path)) {
  11058. $path_built = $new_path.'/';
  11059. } else {
  11060. mkdir($new_path, api_get_permissions_for_new_directories());
  11061. $path_built = $new_path.'/';
  11062. }
  11063. }
  11064. }
  11065. }
  11066. /**
  11067. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  11068. *
  11069. * @return bool The results of the unlink function, or false if there was no image to start with
  11070. */
  11071. public function delete_lp_image()
  11072. {
  11073. $img = $this->get_preview_image();
  11074. if ($img != '') {
  11075. $del_file = $this->get_preview_image_path(null, 'sys');
  11076. if (isset($del_file) && file_exists($del_file)) {
  11077. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  11078. if (file_exists($del_file_2)) {
  11079. unlink($del_file_2);
  11080. }
  11081. $this->set_preview_image('');
  11082. return @unlink($del_file);
  11083. }
  11084. }
  11085. return false;
  11086. }
  11087. /**
  11088. * Uploads an author image to the upload/learning_path/images directory.
  11089. *
  11090. * @param array The image array, coming from the $_FILES superglobal
  11091. *
  11092. * @return bool True on success, false on error
  11093. */
  11094. public function upload_image($image_array)
  11095. {
  11096. if (!empty($image_array['name'])) {
  11097. $upload_ok = process_uploaded_file($image_array);
  11098. $has_attachment = true;
  11099. }
  11100. if ($upload_ok && $has_attachment) {
  11101. $courseDir = api_get_course_path().'/upload/learning_path/images';
  11102. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  11103. $updir = $sys_course_path.$courseDir;
  11104. // Try to add an extension to the file if it hasn't one.
  11105. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  11106. if (filter_extension($new_file_name)) {
  11107. $file_extension = explode('.', $image_array['name']);
  11108. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  11109. $filename = uniqid('');
  11110. $new_file_name = $filename.'.'.$file_extension;
  11111. $new_path = $updir.'/'.$new_file_name;
  11112. // Resize the image.
  11113. $temp = new Image($image_array['tmp_name']);
  11114. $temp->resize(104);
  11115. $result = $temp->send_image($new_path);
  11116. // Storing the image filename.
  11117. if ($result) {
  11118. $this->set_preview_image($new_file_name);
  11119. //Resize to 64px to use on course homepage
  11120. $temp->resize(64);
  11121. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  11122. return true;
  11123. }
  11124. }
  11125. }
  11126. return false;
  11127. }
  11128. /**
  11129. * @param int $lp_id
  11130. * @param string $status
  11131. */
  11132. public function set_autolaunch($lp_id, $status)
  11133. {
  11134. $course_id = api_get_course_int_id();
  11135. $lp_id = intval($lp_id);
  11136. $status = intval($status);
  11137. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11138. // Setting everything to autolaunch = 0
  11139. $attributes['autolaunch'] = 0;
  11140. $where = [
  11141. 'session_id = ? AND c_id = ? ' => [
  11142. api_get_session_id(),
  11143. $course_id,
  11144. ],
  11145. ];
  11146. Database::update($lp_table, $attributes, $where);
  11147. if ($status == 1) {
  11148. //Setting my lp_id to autolaunch = 1
  11149. $attributes['autolaunch'] = 1;
  11150. $where = [
  11151. 'iid = ? AND session_id = ? AND c_id = ?' => [
  11152. $lp_id,
  11153. api_get_session_id(),
  11154. $course_id,
  11155. ],
  11156. ];
  11157. Database::update($lp_table, $attributes, $where);
  11158. }
  11159. }
  11160. /**
  11161. * Gets previous_item_id for the next element of the lp_item table.
  11162. *
  11163. * @author Isaac flores paz
  11164. *
  11165. * @return int Previous item ID
  11166. */
  11167. public function select_previous_item_id()
  11168. {
  11169. $course_id = api_get_course_int_id();
  11170. if ($this->debug > 0) {
  11171. error_log('In learnpath::select_previous_item_id()', 0);
  11172. }
  11173. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11174. // Get the max order of the items
  11175. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  11176. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  11177. $rs_max_order = Database::query($sql);
  11178. $row_max_order = Database::fetch_object($rs_max_order);
  11179. $max_order = $row_max_order->display_order;
  11180. // Get the previous item ID
  11181. $sql = "SELECT iid as previous FROM $table_lp_item
  11182. WHERE
  11183. c_id = $course_id AND
  11184. lp_id = ".$this->lp_id." AND
  11185. display_order = '$max_order' ";
  11186. $rs_max = Database::query($sql);
  11187. $row_max = Database::fetch_object($rs_max);
  11188. // Return the previous item ID
  11189. return $row_max->previous;
  11190. }
  11191. /**
  11192. * Copies an LP.
  11193. */
  11194. public function copy()
  11195. {
  11196. // Course builder
  11197. $cb = new CourseBuilder();
  11198. //Setting tools that will be copied
  11199. $cb->set_tools_to_build(['learnpaths']);
  11200. //Setting elements that will be copied
  11201. $cb->set_tools_specific_id_list(
  11202. ['learnpaths' => [$this->lp_id]]
  11203. );
  11204. $course = $cb->build();
  11205. //Course restorer
  11206. $course_restorer = new CourseRestorer($course);
  11207. $course_restorer->set_add_text_in_items(true);
  11208. $course_restorer->set_tool_copy_settings(
  11209. ['learnpaths' => ['reset_dates' => true]]
  11210. );
  11211. $course_restorer->restore(
  11212. api_get_course_id(),
  11213. api_get_session_id(),
  11214. false,
  11215. false
  11216. );
  11217. }
  11218. /**
  11219. * Verify document size.
  11220. *
  11221. * @param string $s
  11222. *
  11223. * @return bool
  11224. */
  11225. public static function verify_document_size($s)
  11226. {
  11227. $post_max = ini_get('post_max_size');
  11228. if (substr($post_max, -1, 1) == 'M') {
  11229. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  11230. } elseif (substr($post_max, -1, 1) == 'G') {
  11231. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  11232. }
  11233. $upl_max = ini_get('upload_max_filesize');
  11234. if (substr($upl_max, -1, 1) == 'M') {
  11235. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  11236. } elseif (substr($upl_max, -1, 1) == 'G') {
  11237. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  11238. }
  11239. $documents_total_space = DocumentManager::documents_total_space();
  11240. $course_max_space = DocumentManager::get_course_quota();
  11241. $total_size = filesize($s) + $documents_total_space;
  11242. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  11243. return true;
  11244. } else {
  11245. return false;
  11246. }
  11247. }
  11248. /**
  11249. * Clear LP prerequisites.
  11250. */
  11251. public function clear_prerequisites()
  11252. {
  11253. $course_id = $this->get_course_int_id();
  11254. if ($this->debug > 0) {
  11255. error_log('In learnpath::clear_prerequisites()', 0);
  11256. }
  11257. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11258. $lp_id = $this->get_id();
  11259. //Cleaning prerequisites
  11260. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  11261. WHERE c_id = $course_id AND lp_id = $lp_id";
  11262. Database::query($sql);
  11263. //Cleaning mastery score for exercises
  11264. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  11265. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  11266. Database::query($sql);
  11267. }
  11268. public function set_previous_step_as_prerequisite_for_all_items()
  11269. {
  11270. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11271. $course_id = $this->get_course_int_id();
  11272. $lp_id = $this->get_id();
  11273. if (!empty($this->items)) {
  11274. $previous_item_id = null;
  11275. $previous_item_max = 0;
  11276. $previous_item_type = null;
  11277. $last_item_not_dir = null;
  11278. $last_item_not_dir_type = null;
  11279. $last_item_not_dir_max = null;
  11280. foreach ($this->ordered_items as $itemId) {
  11281. $item = $this->getItem($itemId);
  11282. // if there was a previous item... (otherwise jump to set it)
  11283. if (!empty($previous_item_id)) {
  11284. $current_item_id = $item->get_id(); //save current id
  11285. if ($item->get_type() != 'dir') {
  11286. // Current item is not a folder, so it qualifies to get a prerequisites
  11287. if ($last_item_not_dir_type == 'quiz') {
  11288. // if previous is quiz, mark its max score as default score to be achieved
  11289. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  11290. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  11291. Database::query($sql);
  11292. }
  11293. // now simply update the prerequisite to set it to the last non-chapter item
  11294. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  11295. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  11296. Database::query($sql);
  11297. // record item as 'non-chapter' reference
  11298. $last_item_not_dir = $item->get_id();
  11299. $last_item_not_dir_type = $item->get_type();
  11300. $last_item_not_dir_max = $item->get_max();
  11301. }
  11302. } else {
  11303. if ($item->get_type() != 'dir') {
  11304. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  11305. $last_item_not_dir = $item->get_id();
  11306. $last_item_not_dir_type = $item->get_type();
  11307. $last_item_not_dir_max = $item->get_max();
  11308. }
  11309. }
  11310. // Saving the item as "previous item" for the next loop
  11311. $previous_item_id = $item->get_id();
  11312. $previous_item_max = $item->get_max();
  11313. $previous_item_type = $item->get_type();
  11314. }
  11315. }
  11316. }
  11317. /**
  11318. * @param array $params
  11319. *
  11320. * @throws \Doctrine\ORM\OptimisticLockException
  11321. *
  11322. * @return int
  11323. */
  11324. public static function createCategory($params)
  11325. {
  11326. $em = Database::getManager();
  11327. $item = new CLpCategory();
  11328. $item->setName($params['name']);
  11329. $item->setCId($params['c_id']);
  11330. $em->persist($item);
  11331. $em->flush();
  11332. api_item_property_update(
  11333. api_get_course_info(),
  11334. TOOL_LEARNPATH_CATEGORY,
  11335. $item->getId(),
  11336. 'visible',
  11337. api_get_user_id()
  11338. );
  11339. return $item->getId();
  11340. }
  11341. /**
  11342. * @param array $params
  11343. *
  11344. * @throws \Doctrine\ORM\ORMException
  11345. * @throws \Doctrine\ORM\OptimisticLockException
  11346. * @throws \Doctrine\ORM\TransactionRequiredException
  11347. */
  11348. public static function updateCategory($params)
  11349. {
  11350. $em = Database::getManager();
  11351. /** @var CLpCategory $item */
  11352. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  11353. if ($item) {
  11354. $item->setName($params['name']);
  11355. $em->merge($item);
  11356. $em->flush();
  11357. }
  11358. }
  11359. /**
  11360. * @param int $id
  11361. *
  11362. * @throws \Doctrine\ORM\ORMException
  11363. * @throws \Doctrine\ORM\OptimisticLockException
  11364. * @throws \Doctrine\ORM\TransactionRequiredException
  11365. */
  11366. public static function moveUpCategory($id)
  11367. {
  11368. $id = (int) $id;
  11369. $em = Database::getManager();
  11370. /** @var CLpCategory $item */
  11371. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11372. if ($item) {
  11373. $position = $item->getPosition() - 1;
  11374. $item->setPosition($position);
  11375. $em->persist($item);
  11376. $em->flush();
  11377. }
  11378. }
  11379. /**
  11380. * @param int $id
  11381. *
  11382. * @throws \Doctrine\ORM\ORMException
  11383. * @throws \Doctrine\ORM\OptimisticLockException
  11384. * @throws \Doctrine\ORM\TransactionRequiredException
  11385. */
  11386. public static function moveDownCategory($id)
  11387. {
  11388. $id = (int) $id;
  11389. $em = Database::getManager();
  11390. /** @var CLpCategory $item */
  11391. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11392. if ($item) {
  11393. $position = $item->getPosition() + 1;
  11394. $item->setPosition($position);
  11395. $em->persist($item);
  11396. $em->flush();
  11397. }
  11398. }
  11399. /**
  11400. * @param int $courseId
  11401. *
  11402. * @throws \Doctrine\ORM\Query\QueryException
  11403. *
  11404. * @return int|mixed
  11405. */
  11406. public static function getCountCategories($courseId)
  11407. {
  11408. if (empty($courseId)) {
  11409. return 0;
  11410. }
  11411. $em = Database::getManager();
  11412. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  11413. $query->setParameter('id', $courseId);
  11414. return $query->getSingleScalarResult();
  11415. }
  11416. /**
  11417. * @param int $courseId
  11418. *
  11419. * @return mixed
  11420. */
  11421. public static function getCategories($courseId)
  11422. {
  11423. $em = Database::getManager();
  11424. //Default behaviour
  11425. /*$items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11426. array('cId' => $course_id),
  11427. array('name' => 'ASC')
  11428. );*/
  11429. // Using doctrine extensions
  11430. /** @var SortableRepository $repo */
  11431. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  11432. $items = $repo
  11433. ->getBySortableGroupsQuery(['cId' => $courseId])
  11434. ->getResult();
  11435. return $items;
  11436. }
  11437. /**
  11438. * @param int $id
  11439. *
  11440. * @throws \Doctrine\ORM\ORMException
  11441. * @throws \Doctrine\ORM\OptimisticLockException
  11442. * @throws \Doctrine\ORM\TransactionRequiredException
  11443. *
  11444. * @return CLpCategory
  11445. */
  11446. public static function getCategory($id)
  11447. {
  11448. $id = (int) $id;
  11449. $em = Database::getManager();
  11450. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11451. return $item;
  11452. }
  11453. /**
  11454. * @param int $courseId
  11455. *
  11456. * @return array
  11457. */
  11458. public static function getCategoryByCourse($courseId)
  11459. {
  11460. $em = Database::getManager();
  11461. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  11462. ['cId' => $courseId]
  11463. );
  11464. return $items;
  11465. }
  11466. /**
  11467. * @param int $id
  11468. *
  11469. * @throws \Doctrine\ORM\ORMException
  11470. * @throws \Doctrine\ORM\OptimisticLockException
  11471. * @throws \Doctrine\ORM\TransactionRequiredException
  11472. *
  11473. * @return mixed
  11474. */
  11475. public static function deleteCategory($id)
  11476. {
  11477. $em = Database::getManager();
  11478. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  11479. if ($item) {
  11480. $courseId = $item->getCId();
  11481. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  11482. $query->setParameter('id', $courseId);
  11483. $query->setParameter('catId', $item->getId());
  11484. $lps = $query->getResult();
  11485. // Setting category = 0.
  11486. if ($lps) {
  11487. foreach ($lps as $lpItem) {
  11488. $lpItem->setCategoryId(0);
  11489. }
  11490. }
  11491. // Removing category.
  11492. $em->remove($item);
  11493. $em->flush();
  11494. $courseInfo = api_get_course_info_by_id($courseId);
  11495. $sessionId = api_get_session_id();
  11496. // Delete link tool
  11497. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  11498. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  11499. // Delete tools
  11500. $sql = "DELETE FROM $tbl_tool
  11501. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  11502. Database::query($sql);
  11503. return true;
  11504. }
  11505. return false;
  11506. }
  11507. /**
  11508. * @param int $courseId
  11509. * @param bool $addSelectOption
  11510. *
  11511. * @return mixed
  11512. */
  11513. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  11514. {
  11515. $items = self::getCategoryByCourse($courseId);
  11516. $cats = [];
  11517. if ($addSelectOption) {
  11518. $cats = [get_lang('SelectACategory')];
  11519. }
  11520. if (!empty($items)) {
  11521. foreach ($items as $cat) {
  11522. $cats[$cat->getId()] = $cat->getName();
  11523. }
  11524. }
  11525. return $cats;
  11526. }
  11527. /**
  11528. * @param string $courseCode
  11529. * @param int $lpId
  11530. * @param int $user_id
  11531. *
  11532. * @return learnpath
  11533. */
  11534. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11535. {
  11536. $debug = 0;
  11537. $learnPath = null;
  11538. $lpObject = Session::read('lpobject');
  11539. if ($lpObject !== null) {
  11540. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11541. if ($debug) {
  11542. error_log('getLpFromSession: unserialize');
  11543. error_log('------getLpFromSession------');
  11544. error_log('------unserialize------');
  11545. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11546. error_log("api_get_sessionid: ".api_get_session_id());
  11547. }
  11548. }
  11549. if (!is_object($learnPath)) {
  11550. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11551. if ($debug) {
  11552. error_log('------getLpFromSession------');
  11553. error_log('getLpFromSession: create new learnpath');
  11554. error_log("create new LP with $courseCode - $lpId - $user_id");
  11555. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11556. error_log("api_get_sessionid: ".api_get_session_id());
  11557. }
  11558. }
  11559. return $learnPath;
  11560. }
  11561. /**
  11562. * @param int $itemId
  11563. *
  11564. * @return learnpathItem|false
  11565. */
  11566. public function getItem($itemId)
  11567. {
  11568. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11569. return $this->items[$itemId];
  11570. }
  11571. return false;
  11572. }
  11573. /**
  11574. * @return int
  11575. */
  11576. public function getCategoryId()
  11577. {
  11578. return (int) $this->categoryId;
  11579. }
  11580. /**
  11581. * @param int $categoryId
  11582. *
  11583. * @return bool
  11584. */
  11585. public function setCategoryId($categoryId)
  11586. {
  11587. $this->categoryId = (int) $categoryId;
  11588. $table = Database::get_course_table(TABLE_LP_MAIN);
  11589. $lp_id = $this->get_id();
  11590. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11591. WHERE iid = $lp_id";
  11592. Database::query($sql);
  11593. return true;
  11594. }
  11595. /**
  11596. * Get whether this is a learning path with the possibility to subscribe
  11597. * users or not.
  11598. *
  11599. * @return int
  11600. */
  11601. public function getSubscribeUsers()
  11602. {
  11603. return $this->subscribeUsers;
  11604. }
  11605. /**
  11606. * Set whether this is a learning path with the possibility to subscribe
  11607. * users or not.
  11608. *
  11609. * @param int $value (0 = false, 1 = true)
  11610. *
  11611. * @return bool
  11612. */
  11613. public function setSubscribeUsers($value)
  11614. {
  11615. if ($this->debug > 0) {
  11616. error_log('In learnpath::set_subscribe_users()', 0);
  11617. }
  11618. $this->subscribeUsers = (int) $value;
  11619. $table = Database::get_course_table(TABLE_LP_MAIN);
  11620. $lp_id = $this->get_id();
  11621. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11622. WHERE iid = $lp_id";
  11623. Database::query($sql);
  11624. return true;
  11625. }
  11626. /**
  11627. * Calculate the count of stars for a user in this LP
  11628. * This calculation is based on the following rules:
  11629. * - the student gets one star when he gets to 50% of the learning path
  11630. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11631. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11632. * - the student gets the final star when the score for the *last* test is >= 80%.
  11633. *
  11634. * @param int $sessionId Optional. The session ID
  11635. *
  11636. * @return int The count of stars
  11637. */
  11638. public function getCalculateStars($sessionId = 0)
  11639. {
  11640. $stars = 0;
  11641. $progress = self::getProgress(
  11642. $this->lp_id,
  11643. $this->user_id,
  11644. $this->course_int_id,
  11645. $sessionId
  11646. );
  11647. if ($progress >= 50) {
  11648. $stars++;
  11649. }
  11650. // Calculate stars chapters evaluation
  11651. $exercisesItems = $this->getExercisesItems();
  11652. if (!empty($exercisesItems)) {
  11653. $totalResult = 0;
  11654. foreach ($exercisesItems as $exerciseItem) {
  11655. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11656. $this->user_id,
  11657. $exerciseItem->path,
  11658. $this->course_int_id,
  11659. $sessionId,
  11660. $this->lp_id,
  11661. $exerciseItem->db_id
  11662. );
  11663. $exerciseResultInfo = end($exerciseResultInfo);
  11664. if (!$exerciseResultInfo) {
  11665. continue;
  11666. }
  11667. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11668. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11669. } else {
  11670. $exerciseResult = 0;
  11671. }
  11672. $totalResult += $exerciseResult;
  11673. }
  11674. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11675. if ($totalExerciseAverage >= 50) {
  11676. $stars++;
  11677. }
  11678. if ($totalExerciseAverage >= 80) {
  11679. $stars++;
  11680. }
  11681. }
  11682. // Calculate star for final evaluation
  11683. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11684. if (!empty($finalEvaluationItem)) {
  11685. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11686. $this->user_id,
  11687. $finalEvaluationItem->path,
  11688. $this->course_int_id,
  11689. $sessionId,
  11690. $this->lp_id,
  11691. $finalEvaluationItem->db_id
  11692. );
  11693. $evaluationResultInfo = end($evaluationResultInfo);
  11694. if ($evaluationResultInfo) {
  11695. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11696. if ($evaluationResult >= 80) {
  11697. $stars++;
  11698. }
  11699. }
  11700. }
  11701. return $stars;
  11702. }
  11703. /**
  11704. * Get the items of exercise type.
  11705. *
  11706. * @return array The items. Otherwise return false
  11707. */
  11708. public function getExercisesItems()
  11709. {
  11710. $exercises = [];
  11711. foreach ($this->items as $item) {
  11712. if ($item->type != 'quiz') {
  11713. continue;
  11714. }
  11715. $exercises[] = $item;
  11716. }
  11717. array_pop($exercises);
  11718. return $exercises;
  11719. }
  11720. /**
  11721. * Get the item of exercise type (evaluation type).
  11722. *
  11723. * @return array The final evaluation. Otherwise return false
  11724. */
  11725. public function getFinalEvaluationItem()
  11726. {
  11727. $exercises = [];
  11728. foreach ($this->items as $item) {
  11729. if ($item->type != 'quiz') {
  11730. continue;
  11731. }
  11732. $exercises[] = $item;
  11733. }
  11734. return array_pop($exercises);
  11735. }
  11736. /**
  11737. * Calculate the total points achieved for the current user in this learning path.
  11738. *
  11739. * @param int $sessionId Optional. The session Id
  11740. *
  11741. * @return int
  11742. */
  11743. public function getCalculateScore($sessionId = 0)
  11744. {
  11745. // Calculate stars chapters evaluation
  11746. $exercisesItems = $this->getExercisesItems();
  11747. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11748. $totalExercisesResult = 0;
  11749. $totalEvaluationResult = 0;
  11750. if ($exercisesItems !== false) {
  11751. foreach ($exercisesItems as $exerciseItem) {
  11752. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11753. $this->user_id,
  11754. $exerciseItem->path,
  11755. $this->course_int_id,
  11756. $sessionId,
  11757. $this->lp_id,
  11758. $exerciseItem->db_id
  11759. );
  11760. $exerciseResultInfo = end($exerciseResultInfo);
  11761. if (!$exerciseResultInfo) {
  11762. continue;
  11763. }
  11764. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11765. }
  11766. }
  11767. if (!empty($finalEvaluationItem)) {
  11768. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11769. $this->user_id,
  11770. $finalEvaluationItem->path,
  11771. $this->course_int_id,
  11772. $sessionId,
  11773. $this->lp_id,
  11774. $finalEvaluationItem->db_id
  11775. );
  11776. $evaluationResultInfo = end($evaluationResultInfo);
  11777. if ($evaluationResultInfo) {
  11778. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11779. }
  11780. }
  11781. return $totalExercisesResult + $totalEvaluationResult;
  11782. }
  11783. /**
  11784. * Check if URL is not allowed to be show in a iframe.
  11785. *
  11786. * @param string $src
  11787. *
  11788. * @return string
  11789. */
  11790. public function fixBlockedLinks($src)
  11791. {
  11792. $urlInfo = parse_url($src);
  11793. $platformProtocol = 'https';
  11794. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11795. $platformProtocol = 'http';
  11796. }
  11797. $protocolFixApplied = false;
  11798. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11799. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11800. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11801. if ($platformProtocol != $scheme) {
  11802. Session::write('x_frame_source', $src);
  11803. $src = 'blank.php?error=x_frames_options';
  11804. $protocolFixApplied = true;
  11805. }
  11806. if ($protocolFixApplied == false) {
  11807. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11808. // Check X-Frame-Options
  11809. $ch = curl_init();
  11810. $options = [
  11811. CURLOPT_URL => $src,
  11812. CURLOPT_RETURNTRANSFER => true,
  11813. CURLOPT_HEADER => true,
  11814. CURLOPT_FOLLOWLOCATION => true,
  11815. CURLOPT_ENCODING => "",
  11816. CURLOPT_AUTOREFERER => true,
  11817. CURLOPT_CONNECTTIMEOUT => 120,
  11818. CURLOPT_TIMEOUT => 120,
  11819. CURLOPT_MAXREDIRS => 10,
  11820. ];
  11821. $proxySettings = api_get_configuration_value('proxy_settings');
  11822. if (!empty($proxySettings) &&
  11823. isset($proxySettings['curl_setopt_array'])
  11824. ) {
  11825. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11826. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11827. }
  11828. curl_setopt_array($ch, $options);
  11829. $response = curl_exec($ch);
  11830. $httpCode = curl_getinfo($ch);
  11831. $headers = substr($response, 0, $httpCode['header_size']);
  11832. $error = false;
  11833. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11834. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11835. ) {
  11836. $error = true;
  11837. }
  11838. if ($error) {
  11839. Session::write('x_frame_source', $src);
  11840. $src = 'blank.php?error=x_frames_options';
  11841. }
  11842. }
  11843. }
  11844. return $src;
  11845. }
  11846. /**
  11847. * Check if this LP has a created forum in the basis course.
  11848. *
  11849. * @return bool
  11850. */
  11851. public function lpHasForum()
  11852. {
  11853. $forumTable = Database::get_course_table(TABLE_FORUM);
  11854. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11855. $fakeFrom = "
  11856. $forumTable f
  11857. INNER JOIN $itemProperty ip
  11858. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11859. ";
  11860. $resultData = Database::select(
  11861. 'COUNT(f.iid) AS qty',
  11862. $fakeFrom,
  11863. [
  11864. 'where' => [
  11865. 'ip.visibility != ? AND ' => 2,
  11866. 'ip.tool = ? AND ' => TOOL_FORUM,
  11867. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11868. 'f.lp_id = ?' => intval($this->lp_id),
  11869. ],
  11870. ],
  11871. 'first'
  11872. );
  11873. return $resultData['qty'] > 0;
  11874. }
  11875. /**
  11876. * Get the forum for this learning path.
  11877. *
  11878. * @param int $sessionId
  11879. *
  11880. * @return bool
  11881. */
  11882. public function getForum($sessionId = 0)
  11883. {
  11884. $forumTable = Database::get_course_table(TABLE_FORUM);
  11885. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11886. $fakeFrom = "$forumTable f
  11887. INNER JOIN $itemProperty ip ";
  11888. if ($this->lp_session_id == 0) {
  11889. $fakeFrom .= "
  11890. ON (
  11891. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11892. f.session_id = ip.session_id OR ip.session_id IS NULL
  11893. )
  11894. )
  11895. ";
  11896. } else {
  11897. $fakeFrom .= "
  11898. ON (
  11899. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11900. )
  11901. ";
  11902. }
  11903. $resultData = Database::select(
  11904. 'f.*',
  11905. $fakeFrom,
  11906. [
  11907. 'where' => [
  11908. 'ip.visibility != ? AND ' => 2,
  11909. 'ip.tool = ? AND ' => TOOL_FORUM,
  11910. 'f.session_id = ? AND ' => $sessionId,
  11911. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11912. 'f.lp_id = ?' => intval($this->lp_id),
  11913. ],
  11914. ],
  11915. 'first'
  11916. );
  11917. if (empty($resultData)) {
  11918. return false;
  11919. }
  11920. return $resultData;
  11921. }
  11922. /**
  11923. * Create a forum for this learning path.
  11924. *
  11925. * @param int $forumCategoryId
  11926. *
  11927. * @return int The forum ID if was created. Otherwise return false
  11928. */
  11929. public function createForum($forumCategoryId)
  11930. {
  11931. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11932. $forumId = store_forum(
  11933. [
  11934. 'lp_id' => $this->lp_id,
  11935. 'forum_title' => $this->name,
  11936. 'forum_comment' => null,
  11937. 'forum_category' => intval($forumCategoryId),
  11938. 'students_can_edit_group' => ['students_can_edit' => 0],
  11939. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11940. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11941. 'group_forum' => 0,
  11942. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11943. ],
  11944. [],
  11945. true
  11946. );
  11947. return $forumId;
  11948. }
  11949. /**
  11950. * Get the LP Final Item form.
  11951. *
  11952. * @throws Exception
  11953. * @throws HTML_QuickForm_Error
  11954. *
  11955. * @return string
  11956. */
  11957. public function getFinalItemForm()
  11958. {
  11959. $finalItem = $this->getFinalItem();
  11960. $title = '';
  11961. if ($finalItem) {
  11962. $title = $finalItem->get_title();
  11963. $buttonText = get_lang('Save');
  11964. $content = $this->getSavedFinalItem();
  11965. } else {
  11966. $buttonText = get_lang('LPCreateDocument');
  11967. $content = $this->getFinalItemTemplate();
  11968. }
  11969. $courseInfo = api_get_course_info();
  11970. $result = $this->generate_lp_folder($courseInfo);
  11971. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11972. $relative_prefix = '../../';
  11973. $editorConfig = [
  11974. 'ToolbarSet' => 'LearningPathDocuments',
  11975. 'Width' => '100%',
  11976. 'Height' => '500',
  11977. 'FullPage' => true,
  11978. 'CreateDocumentDir' => $relative_prefix,
  11979. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11980. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11981. ];
  11982. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11983. 'type' => 'document',
  11984. 'lp_id' => $this->lp_id,
  11985. ]);
  11986. $form = new FormValidator('final_item', 'POST', $url);
  11987. $form->addText('title', get_lang('Title'));
  11988. $form->addButtonSave($buttonText);
  11989. $form->addHtml(
  11990. Display::return_message(
  11991. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11992. 'normal',
  11993. false
  11994. )
  11995. );
  11996. $renderer = $form->defaultRenderer();
  11997. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11998. $form->addHtmlEditor(
  11999. 'content_lp_certificate',
  12000. null,
  12001. true,
  12002. false,
  12003. $editorConfig,
  12004. true
  12005. );
  12006. $form->addHidden('action', 'add_final_item');
  12007. $form->addHidden('path', Session::read('pathItem'));
  12008. $form->addHidden('previous', $this->get_last());
  12009. $form->setDefaults(
  12010. ['title' => $title, 'content_lp_certificate' => $content]
  12011. );
  12012. if ($form->validate()) {
  12013. $values = $form->exportValues();
  12014. $lastItemId = $this->get_last();
  12015. if (!$finalItem) {
  12016. $documentId = $this->create_document(
  12017. $this->course_info,
  12018. $values['content_lp_certificate'],
  12019. $values['title']
  12020. );
  12021. $this->add_item(
  12022. 0,
  12023. $lastItemId,
  12024. 'final_item',
  12025. $documentId,
  12026. $values['title'],
  12027. ''
  12028. );
  12029. Display::addFlash(
  12030. Display::return_message(get_lang('Added'))
  12031. );
  12032. } else {
  12033. $this->edit_document($this->course_info);
  12034. }
  12035. }
  12036. return $form->returnForm();
  12037. }
  12038. /**
  12039. * Check if the current lp item is first, both, last or none from lp list.
  12040. *
  12041. * @param int $currentItemId
  12042. *
  12043. * @return string
  12044. */
  12045. public function isFirstOrLastItem($currentItemId)
  12046. {
  12047. if ($this->debug > 0) {
  12048. error_log('In learnpath::isFirstOrLastItem('.$currentItemId.')', 0);
  12049. }
  12050. $lpItemId = [];
  12051. $typeListNotToVerify = self::getChapterTypes();
  12052. // Using get_toc() function instead $this->items because returns the correct order of the items
  12053. foreach ($this->get_toc() as $item) {
  12054. if (!in_array($item['type'], $typeListNotToVerify)) {
  12055. $lpItemId[] = $item['id'];
  12056. }
  12057. }
  12058. $lastLpItemIndex = count($lpItemId) - 1;
  12059. $position = array_search($currentItemId, $lpItemId);
  12060. switch ($position) {
  12061. case 0:
  12062. if (!$lastLpItemIndex) {
  12063. $answer = 'both';
  12064. break;
  12065. }
  12066. $answer = 'first';
  12067. break;
  12068. case $lastLpItemIndex:
  12069. $answer = 'last';
  12070. break;
  12071. default:
  12072. $answer = 'none';
  12073. }
  12074. return $answer;
  12075. }
  12076. /**
  12077. * Get whether this is a learning path with the accumulated SCORM time or not.
  12078. *
  12079. * @return int
  12080. */
  12081. public function getAccumulateScormTime()
  12082. {
  12083. return $this->accumulateScormTime;
  12084. }
  12085. /**
  12086. * Set whether this is a learning path with the accumulated SCORM time or not.
  12087. *
  12088. * @param int $value (0 = false, 1 = true)
  12089. *
  12090. * @return bool Always returns true
  12091. */
  12092. public function setAccumulateScormTime($value)
  12093. {
  12094. if ($this->debug > 0) {
  12095. error_log('In learnpath::setAccumulateScormTime()', 0);
  12096. }
  12097. $this->accumulateScormTime = intval($value);
  12098. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  12099. $lp_id = $this->get_id();
  12100. $sql = "UPDATE $lp_table
  12101. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  12102. WHERE iid = $lp_id";
  12103. Database::query($sql);
  12104. return true;
  12105. }
  12106. /**
  12107. * Returns an HTML-formatted link to a resource, to incorporate directly into
  12108. * the new learning path tool.
  12109. *
  12110. * The function is a big switch on tool type.
  12111. * In each case, we query the corresponding table for information and build the link
  12112. * with that information.
  12113. *
  12114. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  12115. * previous work (display_addedresource_link_in_learnpath())
  12116. *
  12117. * @param int $course_id Course code
  12118. * @param int $learningPathId The learning path ID (in lp table)
  12119. * @param int $id_in_path the unique index in the items table
  12120. * @param int $lpViewId
  12121. *
  12122. * @return string
  12123. */
  12124. public static function rl_get_resource_link_for_learnpath(
  12125. $course_id,
  12126. $learningPathId,
  12127. $id_in_path,
  12128. $lpViewId
  12129. ) {
  12130. $session_id = api_get_session_id();
  12131. $course_info = api_get_course_info_by_id($course_id);
  12132. $learningPathId = (int) $learningPathId;
  12133. $id_in_path = (int) $id_in_path;
  12134. $lpViewId = (int) $lpViewId;
  12135. $em = Database::getManager();
  12136. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  12137. /** @var CLpItem $rowItem */
  12138. $rowItem = $lpItemRepo->findOneBy([
  12139. 'cId' => $course_id,
  12140. 'lpId' => $learningPathId,
  12141. 'iid' => $id_in_path,
  12142. ]);
  12143. if (!$rowItem) {
  12144. // Try one more time with "id"
  12145. /** @var CLpItem $rowItem */
  12146. $rowItem = $lpItemRepo->findOneBy([
  12147. 'cId' => $course_id,
  12148. 'lpId' => $learningPathId,
  12149. 'id' => $id_in_path,
  12150. ]);
  12151. if (!$rowItem) {
  12152. return -1;
  12153. }
  12154. }
  12155. $course_code = $course_info['code'];
  12156. $type = $rowItem->getItemType();
  12157. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  12158. $main_dir_path = api_get_path(WEB_CODE_PATH);
  12159. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  12160. $link = '';
  12161. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  12162. switch ($type) {
  12163. case 'dir':
  12164. return $main_dir_path.'lp/blank.php';
  12165. case TOOL_CALENDAR_EVENT:
  12166. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  12167. case TOOL_ANNOUNCEMENT:
  12168. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  12169. case TOOL_LINK:
  12170. $linkInfo = Link::getLinkInfo($id);
  12171. if (isset($linkInfo['url'])) {
  12172. return $linkInfo['url'];
  12173. }
  12174. return '';
  12175. case TOOL_QUIZ:
  12176. if (empty($id)) {
  12177. return '';
  12178. }
  12179. // Get the lp_item_view with the highest view_count.
  12180. $learnpathItemViewResult = $em
  12181. ->getRepository('ChamiloCourseBundle:CLpItemView')
  12182. ->findBy(
  12183. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  12184. ['viewCount' => 'DESC'],
  12185. 1
  12186. );
  12187. /** @var CLpItemView $learnpathItemViewData */
  12188. $learnpathItemViewData = current($learnpathItemViewResult);
  12189. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  12190. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  12191. .http_build_query([
  12192. 'lp_init' => 1,
  12193. 'learnpath_item_view_id' => $learnpathItemViewId,
  12194. 'learnpath_id' => $learningPathId,
  12195. 'learnpath_item_id' => $id_in_path,
  12196. 'exerciseId' => $id,
  12197. ]);
  12198. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  12199. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  12200. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  12201. $myrow = Database::fetch_array($result);
  12202. $path = $myrow['path'];
  12203. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  12204. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  12205. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  12206. case TOOL_FORUM:
  12207. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  12208. case TOOL_THREAD:
  12209. // forum post
  12210. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  12211. if (empty($id)) {
  12212. return '';
  12213. }
  12214. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  12215. $result = Database::query($sql);
  12216. $myrow = Database::fetch_array($result);
  12217. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  12218. .$extraParams;
  12219. case TOOL_POST:
  12220. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12221. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  12222. $myrow = Database::fetch_array($result);
  12223. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  12224. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  12225. case TOOL_READOUT_TEXT:
  12226. return api_get_path(WEB_CODE_PATH).
  12227. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  12228. case TOOL_DOCUMENT:
  12229. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  12230. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  12231. if (empty($document)) {
  12232. // Try with normal id
  12233. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  12234. if (empty($document)) {
  12235. return '';
  12236. }
  12237. }
  12238. $documentPathInfo = pathinfo($document->getPath());
  12239. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  12240. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  12241. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  12242. $openmethod = 2;
  12243. $officedoc = false;
  12244. Session::write('openmethod', $openmethod);
  12245. Session::write('officedoc', $officedoc);
  12246. if ($showDirectUrl) {
  12247. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  12248. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  12249. if (Link::isPdfLink($file)) {
  12250. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  12251. return $pdfUrl;
  12252. }
  12253. }
  12254. return $file;
  12255. }
  12256. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  12257. case TOOL_LP_FINAL_ITEM:
  12258. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  12259. .$extraParams;
  12260. case 'assignments':
  12261. return $main_dir_path.'work/work.php?'.$extraParams;
  12262. case TOOL_DROPBOX:
  12263. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  12264. case 'introduction_text': //DEPRECATED
  12265. return '';
  12266. case TOOL_COURSE_DESCRIPTION:
  12267. return $main_dir_path.'course_description?'.$extraParams;
  12268. case TOOL_GROUP:
  12269. return $main_dir_path.'group/group.php?'.$extraParams;
  12270. case TOOL_USER:
  12271. return $main_dir_path.'user/user.php?'.$extraParams;
  12272. case TOOL_STUDENTPUBLICATION:
  12273. if (!empty($rowItem->getPath())) {
  12274. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  12275. }
  12276. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  12277. }
  12278. return $link;
  12279. }
  12280. /**
  12281. * Gets the name of a resource (generally used in learnpath when no name is provided).
  12282. *
  12283. * @author Yannick Warnier <ywarnier@beeznest.org>
  12284. *
  12285. * @param string $course_code Course code
  12286. * @param int $learningPathId
  12287. * @param int $id_in_path The resource ID
  12288. *
  12289. * @return string
  12290. */
  12291. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  12292. {
  12293. $_course = api_get_course_info($course_code);
  12294. $course_id = $_course['real_id'];
  12295. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12296. $learningPathId = (int) $learningPathId;
  12297. $id_in_path = (int) $id_in_path;
  12298. $sql = "SELECT item_type, title, ref
  12299. FROM $tbl_lp_item
  12300. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  12301. $res_item = Database::query($sql);
  12302. if (Database::num_rows($res_item) < 1) {
  12303. return '';
  12304. }
  12305. $row_item = Database::fetch_array($res_item);
  12306. $type = strtolower($row_item['item_type']);
  12307. $id = $row_item['ref'];
  12308. $output = '';
  12309. switch ($type) {
  12310. case TOOL_CALENDAR_EVENT:
  12311. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  12312. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  12313. $myrow = Database::fetch_array($result);
  12314. $output = $myrow['title'];
  12315. break;
  12316. case TOOL_ANNOUNCEMENT:
  12317. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  12318. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  12319. $myrow = Database::fetch_array($result);
  12320. $output = $myrow['title'];
  12321. break;
  12322. case TOOL_LINK:
  12323. // Doesn't take $target into account.
  12324. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  12325. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  12326. $myrow = Database::fetch_array($result);
  12327. $output = $myrow['title'];
  12328. break;
  12329. case TOOL_QUIZ:
  12330. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  12331. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  12332. $myrow = Database::fetch_array($result);
  12333. $output = $myrow['title'];
  12334. break;
  12335. case TOOL_FORUM:
  12336. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  12337. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  12338. $myrow = Database::fetch_array($result);
  12339. $output = $myrow['forum_name'];
  12340. break;
  12341. case TOOL_THREAD: //=topics
  12342. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12343. // Grabbing the title of the post.
  12344. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  12345. $result_title = Database::query($sql_title);
  12346. $myrow_title = Database::fetch_array($result_title);
  12347. $output = $myrow_title['post_title'];
  12348. break;
  12349. case TOOL_POST:
  12350. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  12351. //$tbl_post_text = Database::get_course_table(FORUM_POST_TEXT_TABLE);
  12352. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  12353. $result = Database::query($sql);
  12354. $post = Database::fetch_array($result);
  12355. $output = $post['post_title'];
  12356. break;
  12357. case 'dir':
  12358. $title = $row_item['title'];
  12359. if (!empty($title)) {
  12360. $output = $title;
  12361. } else {
  12362. $output = '-';
  12363. }
  12364. break;
  12365. case TOOL_DOCUMENT:
  12366. $title = $row_item['title'];
  12367. if (!empty($title)) {
  12368. $output = $title;
  12369. } else {
  12370. $output = '-';
  12371. }
  12372. break;
  12373. case 'hotpotatoes':
  12374. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  12375. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  12376. $myrow = Database::fetch_array($result);
  12377. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  12378. $last = count($pathname) - 1; // Making a correct name for the link.
  12379. $filename = $pathname[$last]; // Making a correct name for the link.
  12380. $ext = explode('.', $filename);
  12381. $ext = strtolower($ext[sizeof($ext) - 1]);
  12382. $myrow['path'] = rawurlencode($myrow['path']);
  12383. $output = $filename;
  12384. break;
  12385. }
  12386. return stripslashes($output);
  12387. }
  12388. /**
  12389. * Get the parent names for the current item.
  12390. *
  12391. * @param int $newItemId Optional. The item ID
  12392. *
  12393. * @return array
  12394. */
  12395. public function getCurrentItemParentNames($newItemId = 0)
  12396. {
  12397. $newItemId = $newItemId ?: $this->get_current_item_id();
  12398. $return = [];
  12399. $item = $this->getItem($newItemId);
  12400. $parent = $this->getItem($item->get_parent());
  12401. while ($parent) {
  12402. $return[] = $parent->get_title();
  12403. $parent = $this->getItem($parent->get_parent());
  12404. }
  12405. return array_reverse($return);
  12406. }
  12407. /**
  12408. * Reads and process "lp_subscription_settings" setting.
  12409. *
  12410. * @return array
  12411. */
  12412. public static function getSubscriptionSettings()
  12413. {
  12414. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  12415. if (empty($subscriptionSettings)) {
  12416. // By default allow both settings
  12417. $subscriptionSettings = [
  12418. 'allow_add_users_to_lp' => true,
  12419. 'allow_add_users_to_lp_category' => true,
  12420. ];
  12421. } else {
  12422. $subscriptionSettings = $subscriptionSettings['options'];
  12423. }
  12424. return $subscriptionSettings;
  12425. }
  12426. /**
  12427. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  12428. */
  12429. public function exportToCourseBuildFormat()
  12430. {
  12431. if (!api_is_allowed_to_edit()) {
  12432. return false;
  12433. }
  12434. $courseBuilder = new CourseBuilder();
  12435. $itemList = [];
  12436. /** @var learnpathItem $item */
  12437. foreach ($this->items as $item) {
  12438. $itemList[$item->get_type()][] = $item->get_path();
  12439. }
  12440. if (empty($itemList)) {
  12441. return false;
  12442. }
  12443. if (isset($itemList['document'])) {
  12444. // Get parents
  12445. foreach ($itemList['document'] as $documentId) {
  12446. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  12447. if (!empty($documentInfo['parents'])) {
  12448. foreach ($documentInfo['parents'] as $parentInfo) {
  12449. if (in_array($parentInfo['iid'], $itemList['document'])) {
  12450. continue;
  12451. }
  12452. $itemList['document'][] = $parentInfo['iid'];
  12453. }
  12454. }
  12455. }
  12456. $courseInfo = api_get_course_info();
  12457. foreach ($itemList['document'] as $documentId) {
  12458. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  12459. $items = DocumentManager::get_resources_from_source_html(
  12460. $documentInfo['absolute_path'],
  12461. true,
  12462. TOOL_DOCUMENT
  12463. );
  12464. if (!empty($items)) {
  12465. foreach ($items as $item) {
  12466. // Get information about source url
  12467. $url = $item[0]; // url
  12468. $scope = $item[1]; // scope (local, remote)
  12469. $type = $item[2]; // type (rel, abs, url)
  12470. $origParseUrl = parse_url($url);
  12471. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  12472. if ($scope == 'local') {
  12473. if ($type == 'abs' || $type == 'rel') {
  12474. $documentFile = strstr($realOrigPath, 'document');
  12475. if (strpos($realOrigPath, $documentFile) !== false) {
  12476. $documentFile = str_replace('document', '', $documentFile);
  12477. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  12478. // Document found! Add it to the list
  12479. if ($itemDocumentId) {
  12480. $itemList['document'][] = $itemDocumentId;
  12481. }
  12482. }
  12483. }
  12484. }
  12485. }
  12486. }
  12487. }
  12488. $courseBuilder->build_documents(
  12489. api_get_session_id(),
  12490. $this->get_course_int_id(),
  12491. true,
  12492. $itemList['document']
  12493. );
  12494. }
  12495. if (isset($itemList['quiz'])) {
  12496. $courseBuilder->build_quizzes(
  12497. api_get_session_id(),
  12498. $this->get_course_int_id(),
  12499. true,
  12500. $itemList['quiz']
  12501. );
  12502. }
  12503. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  12504. /*if (!empty($itemList['thread'])) {
  12505. $postList = [];
  12506. foreach ($itemList['thread'] as $postId) {
  12507. $post = get_post_information($postId);
  12508. if ($post) {
  12509. if (!isset($itemList['forum'])) {
  12510. $itemList['forum'] = [];
  12511. }
  12512. $itemList['forum'][] = $post['forum_id'];
  12513. $postList[] = $postId;
  12514. }
  12515. }
  12516. if (!empty($postList)) {
  12517. $courseBuilder->build_forum_posts(
  12518. $this->get_course_int_id(),
  12519. null,
  12520. null,
  12521. $postList
  12522. );
  12523. }
  12524. }*/
  12525. if (!empty($itemList['thread'])) {
  12526. $threadList = [];
  12527. $em = Database::getManager();
  12528. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12529. foreach ($itemList['thread'] as $threadId) {
  12530. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12531. $thread = $repo->find($threadId);
  12532. if ($thread) {
  12533. $itemList['forum'][] = $thread->getForumId();
  12534. $threadList[] = $thread->getIid();
  12535. }
  12536. }
  12537. if (!empty($threadList)) {
  12538. $courseBuilder->build_forum_topics(
  12539. api_get_session_id(),
  12540. $this->get_course_int_id(),
  12541. null,
  12542. $threadList
  12543. );
  12544. }
  12545. }
  12546. $forumCategoryList = [];
  12547. if (isset($itemList['forum'])) {
  12548. foreach ($itemList['forum'] as $forumId) {
  12549. $forumInfo = get_forums($forumId);
  12550. $forumCategoryList[] = $forumInfo['forum_category'];
  12551. }
  12552. }
  12553. if (!empty($forumCategoryList)) {
  12554. $courseBuilder->build_forum_category(
  12555. api_get_session_id(),
  12556. $this->get_course_int_id(),
  12557. true,
  12558. $forumCategoryList
  12559. );
  12560. }
  12561. if (!empty($itemList['forum'])) {
  12562. $courseBuilder->build_forums(
  12563. api_get_session_id(),
  12564. $this->get_course_int_id(),
  12565. true,
  12566. $itemList['forum']
  12567. );
  12568. }
  12569. if (isset($itemList['link'])) {
  12570. $courseBuilder->build_links(
  12571. api_get_session_id(),
  12572. $this->get_course_int_id(),
  12573. true,
  12574. $itemList['link']
  12575. );
  12576. }
  12577. if (!empty($itemList['student_publication'])) {
  12578. $courseBuilder->build_works(
  12579. api_get_session_id(),
  12580. $this->get_course_int_id(),
  12581. true,
  12582. $itemList['student_publication']
  12583. );
  12584. }
  12585. $courseBuilder->build_learnpaths(
  12586. api_get_session_id(),
  12587. $this->get_course_int_id(),
  12588. true,
  12589. [$this->get_id()],
  12590. false
  12591. );
  12592. $courseBuilder->restoreDocumentsFromList();
  12593. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12594. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12595. $result = DocumentManager::file_send_for_download(
  12596. $zipPath,
  12597. true,
  12598. $this->get_name().'.zip'
  12599. );
  12600. if ($result) {
  12601. api_not_allowed();
  12602. }
  12603. return true;
  12604. }
  12605. /**
  12606. * Get whether this is a learning path with the accumulated work time or not.
  12607. *
  12608. * @return int
  12609. */
  12610. public function getAccumulateWorkTime()
  12611. {
  12612. return (int) $this->accumulateWorkTime;
  12613. }
  12614. /**
  12615. * Get whether this is a learning path with the accumulated work time or not.
  12616. *
  12617. * @return int
  12618. */
  12619. public function getAccumulateWorkTimeTotalCourse()
  12620. {
  12621. $table = Database::get_course_table(TABLE_LP_MAIN);
  12622. $sql = "SELECT SUM(accumulate_work_time) AS total
  12623. FROM $table
  12624. WHERE c_id = ".$this->course_int_id;
  12625. $result = Database::query($sql);
  12626. $row = Database::fetch_array($result);
  12627. return (int) $row['total'];
  12628. }
  12629. /**
  12630. * Set whether this is a learning path with the accumulated work time or not.
  12631. *
  12632. * @param int $value (0 = false, 1 = true)
  12633. *
  12634. * @return bool
  12635. */
  12636. public function setAccumulateWorkTime($value)
  12637. {
  12638. if (!api_get_configuration_value('lp_minimum_time')) {
  12639. return false;
  12640. }
  12641. $this->accumulateWorkTime = (int) $value;
  12642. $table = Database::get_course_table(TABLE_LP_MAIN);
  12643. $lp_id = $this->get_id();
  12644. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12645. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12646. Database::query($sql);
  12647. return true;
  12648. }
  12649. /**
  12650. * @param int $lpId
  12651. * @param int $courseId
  12652. *
  12653. * @return mixed
  12654. */
  12655. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12656. {
  12657. $lpId = (int) $lpId;
  12658. $courseId = (int) $courseId;
  12659. $table = Database::get_course_table(TABLE_LP_MAIN);
  12660. $sql = "SELECT accumulate_work_time
  12661. FROM $table
  12662. WHERE c_id = $courseId AND id = $lpId";
  12663. $result = Database::query($sql);
  12664. $row = Database::fetch_array($result);
  12665. return $row['accumulate_work_time'];
  12666. }
  12667. /**
  12668. * @param int $courseId
  12669. *
  12670. * @return int
  12671. */
  12672. public static function getAccumulateWorkTimeTotal($courseId)
  12673. {
  12674. $table = Database::get_course_table(TABLE_LP_MAIN);
  12675. $courseId = (int) $courseId;
  12676. $sql = "SELECT SUM(accumulate_work_time) AS total
  12677. FROM $table
  12678. WHERE c_id = $courseId";
  12679. $result = Database::query($sql);
  12680. $row = Database::fetch_array($result);
  12681. return (int) $row['total'];
  12682. }
  12683. /**
  12684. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12685. * and put the images in.
  12686. *
  12687. * @return array
  12688. */
  12689. public static function getIconSelect()
  12690. {
  12691. $theme = api_get_visual_theme();
  12692. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12693. $icons = ['' => get_lang('SelectAnOption')];
  12694. if (is_dir($path)) {
  12695. $finder = new Finder();
  12696. $finder->files()->in($path);
  12697. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12698. /** @var SplFileInfo $file */
  12699. foreach ($finder as $file) {
  12700. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12701. $icons[$file->getFilename()] = $file->getFilename();
  12702. }
  12703. }
  12704. }
  12705. return $icons;
  12706. }
  12707. /**
  12708. * @param int $lpId
  12709. *
  12710. * @return string
  12711. */
  12712. public static function getSelectedIcon($lpId)
  12713. {
  12714. $extraFieldValue = new ExtraFieldValue('lp');
  12715. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12716. $icon = '';
  12717. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12718. $icon = $lpIcon['value'];
  12719. }
  12720. return $icon;
  12721. }
  12722. public static function getSelectedIconHtml($lpId)
  12723. {
  12724. $icon = self::getSelectedIcon($lpId);
  12725. if (empty($icon)) {
  12726. return '';
  12727. }
  12728. $theme = api_get_visual_theme();
  12729. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12730. return Display::img($path);
  12731. }
  12732. /**
  12733. * Get the depth level of LP item.
  12734. *
  12735. * @param array $items
  12736. * @param int $currentItemId
  12737. *
  12738. * @return int
  12739. */
  12740. private static function get_level_for_item($items, $currentItemId)
  12741. {
  12742. $parentItemId = 0;
  12743. if (isset($items[$currentItemId])) {
  12744. $parentItemId = $items[$currentItemId]->parent;
  12745. }
  12746. if ($parentItemId == 0) {
  12747. return 0;
  12748. } else {
  12749. return self::get_level_for_item($items, $parentItemId) + 1;
  12750. }
  12751. }
  12752. /**
  12753. * Generate the link for a learnpath category as course tool.
  12754. *
  12755. * @param int $categoryId
  12756. *
  12757. * @return string
  12758. */
  12759. private static function getCategoryLinkForTool($categoryId)
  12760. {
  12761. $categoryId = (int) $categoryId;
  12762. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12763. .http_build_query(
  12764. [
  12765. 'action' => 'view_category',
  12766. 'id' => $categoryId,
  12767. ]
  12768. );
  12769. return $link;
  12770. }
  12771. /**
  12772. * Return the scorm item type object with spaces replaced with _
  12773. * The return result is use to build a css classname like scorm_type_$return.
  12774. *
  12775. * @param $in_type
  12776. *
  12777. * @return mixed
  12778. */
  12779. private static function format_scorm_type_item($in_type)
  12780. {
  12781. return str_replace(' ', '_', $in_type);
  12782. }
  12783. /**
  12784. * Check and obtain the lp final item if exist.
  12785. *
  12786. * @return learnpathItem
  12787. */
  12788. private function getFinalItem()
  12789. {
  12790. if (empty($this->items)) {
  12791. return null;
  12792. }
  12793. foreach ($this->items as $item) {
  12794. if ($item->type !== 'final_item') {
  12795. continue;
  12796. }
  12797. return $item;
  12798. }
  12799. }
  12800. /**
  12801. * Get the LP Final Item Template.
  12802. *
  12803. * @return string
  12804. */
  12805. private function getFinalItemTemplate()
  12806. {
  12807. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12808. }
  12809. /**
  12810. * Get the LP Final Item Url.
  12811. *
  12812. * @return string
  12813. */
  12814. private function getSavedFinalItem()
  12815. {
  12816. $finalItem = $this->getFinalItem();
  12817. $doc = DocumentManager::get_document_data_by_id(
  12818. $finalItem->path,
  12819. $this->cc
  12820. );
  12821. if ($doc && file_exists($doc['absolute_path'])) {
  12822. return file_get_contents($doc['absolute_path']);
  12823. }
  12824. return '';
  12825. }
  12826. }