learnpath.class.php 512 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Repository\CourseRepository;
  4. use Chamilo\CoreBundle\Entity\Repository\ItemPropertyRepository;
  5. use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
  6. use Chamilo\CourseBundle\Component\CourseCopy\CourseBuilder;
  7. use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;
  8. use Chamilo\CourseBundle\Entity\CDocument;
  9. use Chamilo\CourseBundle\Entity\CItemProperty;
  10. use Chamilo\CourseBundle\Entity\CLp;
  11. use Chamilo\CourseBundle\Entity\CLpCategory;
  12. use Chamilo\CourseBundle\Entity\CLpItem;
  13. use Chamilo\CourseBundle\Entity\CLpItemView;
  14. use Chamilo\CourseBundle\Entity\CTool;
  15. use Chamilo\UserBundle\Entity\User;
  16. use ChamiloSession as Session;
  17. use Gedmo\Sortable\Entity\Repository\SortableRepository;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\Finder\Finder;
  20. /**
  21. * Class learnpath
  22. * This class defines the parent attributes and methods for Chamilo learnpaths
  23. * and SCORM learnpaths. It is used by the scorm class.
  24. *
  25. * @todo decouple class
  26. *
  27. * @package chamilo.learnpath
  28. *
  29. * @author Yannick Warnier <ywarnier@beeznest.org>
  30. * @author Julio Montoya <gugli100@gmail.com> Several improvements and fixes
  31. */
  32. class learnpath
  33. {
  34. const MAX_LP_ITEM_TITLE_LENGTH = 32;
  35. public $attempt = 0; // The number for the current ID view.
  36. public $cc; // Course (code) this learnpath is located in. @todo change name for something more comprensible ...
  37. public $current; // Id of the current item the user is viewing.
  38. public $current_score; // The score of the current item.
  39. public $current_time_start; // The time the user loaded this resource (this does not mean he can see it yet).
  40. public $current_time_stop; // The time the user closed this resource.
  41. public $default_status = 'not attempted';
  42. public $encoding = 'UTF-8';
  43. public $error = '';
  44. public $force_commit = false; // For SCORM only- if true will send a scorm LMSCommit() request on each LMSSetValue()
  45. public $index; // The index of the active learnpath_item in $ordered_items array.
  46. public $items = [];
  47. public $last; // item_id of last item viewed in the learning path.
  48. public $last_item_seen = 0; // In case we have already come in this lp, reuse the last item seen if authorized.
  49. public $license; // Which license this course has been given - not used yet on 20060522.
  50. public $lp_id; // DB iid for this learnpath.
  51. public $lp_view_id; // DB ID for lp_view
  52. public $maker; // Which maker has conceived the content (ENI, Articulate, ...).
  53. public $message = '';
  54. public $mode = 'embedded'; // Holds the video display mode (fullscreen or embedded).
  55. public $name; // Learnpath name (they generally have one).
  56. public $ordered_items = []; // List of the learnpath items in the order they are to be read.
  57. public $path = ''; // Path inside the scorm directory (if scorm).
  58. public $theme; // The current theme of the learning path.
  59. public $preview_image; // The current image of the learning path.
  60. public $accumulateScormTime; // Flag to decide whether to accumulate SCORM time or not
  61. public $accumulateWorkTime; // The min time of learnpath
  62. // Tells if all the items of the learnpath can be tried again. Defaults to "no" (=1).
  63. public $prevent_reinit = 1;
  64. // Describes the mode of progress bar display.
  65. public $seriousgame_mode = 0;
  66. public $progress_bar_mode = '%';
  67. // Percentage progress as saved in the db.
  68. public $progress_db = 0;
  69. public $proximity; // Wether the content is distant or local or unknown.
  70. public $refs_list = []; //list of items by ref => db_id. Used only for prerequisites match.
  71. // !!!This array (refs_list) is built differently depending on the nature of the LP.
  72. // If SCORM, uses ref, if Chamilo, uses id to keep a unique value.
  73. public $type; //type of learnpath. Could be 'chamilo', 'scorm', 'scorm2004', 'aicc', ...
  74. // TODO: Check if this type variable is useful here (instead of just in the controller script).
  75. public $user_id; //ID of the user that is viewing/using the course
  76. public $update_queue = [];
  77. public $scorm_debug = 0;
  78. public $arrMenu = []; // Array for the menu items.
  79. public $debug = 0; // Logging level.
  80. public $lp_session_id = 0;
  81. public $lp_view_session_id = 0; // The specific view might be bound to a session.
  82. public $prerequisite = 0;
  83. public $use_max_score = 1; // 1 or 0
  84. public $subscribeUsers = 0; // Subscribe users or not
  85. public $created_on = '';
  86. public $modified_on = '';
  87. public $publicated_on = '';
  88. public $expired_on = '';
  89. public $ref = null;
  90. public $course_int_id;
  91. public $course_info = [];
  92. public $categoryId;
  93. /**
  94. * Constructor.
  95. * Needs a database handler, a course code and a learnpath id from the database.
  96. * Also builds the list of items into $this->items.
  97. *
  98. * @param string $course Course code
  99. * @param int $lp_id c_lp.iid
  100. * @param int $user_id
  101. */
  102. public function __construct($course, $lp_id, $user_id)
  103. {
  104. $debug = $this->debug;
  105. $this->encoding = api_get_system_encoding();
  106. if ($debug) {
  107. error_log('In learnpath::__construct('.$course.','.$lp_id.','.$user_id.')');
  108. }
  109. if (empty($course)) {
  110. $course = api_get_course_id();
  111. }
  112. $course_info = api_get_course_info($course);
  113. if (!empty($course_info)) {
  114. $this->cc = $course_info['code'];
  115. $this->course_info = $course_info;
  116. $course_id = $course_info['real_id'];
  117. } else {
  118. $this->error = 'Course code does not exist in database.';
  119. }
  120. $lp_id = (int) $lp_id;
  121. $course_id = (int) $course_id;
  122. $this->set_course_int_id($course_id);
  123. // Check learnpath ID.
  124. if (empty($lp_id) || empty($course_id)) {
  125. $this->error = "Parameter is empty: LpId:'$lp_id', courseId: '$lp_id'";
  126. } else {
  127. // TODO: Make it flexible to use any course_code (still using env course code here).
  128. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  129. $sql = "SELECT * FROM $lp_table
  130. WHERE iid = $lp_id";
  131. if ($debug) {
  132. error_log('learnpath::__construct() '.__LINE__.' - Querying lp: '.$sql, 0);
  133. }
  134. $res = Database::query($sql);
  135. if (Database::num_rows($res) > 0) {
  136. $this->lp_id = $lp_id;
  137. $row = Database::fetch_array($res);
  138. $this->type = $row['lp_type'];
  139. $this->name = stripslashes($row['name']);
  140. $this->proximity = $row['content_local'];
  141. $this->theme = $row['theme'];
  142. $this->maker = $row['content_maker'];
  143. $this->prevent_reinit = $row['prevent_reinit'];
  144. $this->seriousgame_mode = $row['seriousgame_mode'];
  145. $this->license = $row['content_license'];
  146. $this->scorm_debug = $row['debug'];
  147. $this->js_lib = $row['js_lib'];
  148. $this->path = $row['path'];
  149. $this->preview_image = $row['preview_image'];
  150. $this->author = $row['author'];
  151. $this->hide_toc_frame = $row['hide_toc_frame'];
  152. $this->lp_session_id = $row['session_id'];
  153. $this->use_max_score = $row['use_max_score'];
  154. $this->subscribeUsers = $row['subscribe_users'];
  155. $this->created_on = $row['created_on'];
  156. $this->modified_on = $row['modified_on'];
  157. $this->ref = $row['ref'];
  158. $this->categoryId = $row['category_id'];
  159. $this->accumulateScormTime = isset($row['accumulate_scorm_time']) ? $row['accumulate_scorm_time'] : 'true';
  160. $this->accumulateWorkTime = isset($row['accumulate_work_time']) ? $row['accumulate_work_time'] : 0;
  161. if (!empty($row['publicated_on'])) {
  162. $this->publicated_on = $row['publicated_on'];
  163. }
  164. if (!empty($row['expired_on'])) {
  165. $this->expired_on = $row['expired_on'];
  166. }
  167. if ($this->type == 2) {
  168. if ($row['force_commit'] == 1) {
  169. $this->force_commit = true;
  170. }
  171. }
  172. $this->mode = $row['default_view_mod'];
  173. // Check user ID.
  174. if (empty($user_id)) {
  175. $this->error = 'User ID is empty';
  176. } else {
  177. $userInfo = api_get_user_info($user_id);
  178. if (!empty($userInfo)) {
  179. $this->user_id = $userInfo['user_id'];
  180. } else {
  181. $this->error = 'User ID does not exist in database #'.$user_id;
  182. }
  183. }
  184. // End of variables checking.
  185. $session_id = api_get_session_id();
  186. // Get the session condition for learning paths of the base + session.
  187. $session = api_get_session_condition($session_id);
  188. // Now get the latest attempt from this user on this LP, if available, otherwise create a new one.
  189. $lp_table = Database::get_course_table(TABLE_LP_VIEW);
  190. // Selecting by view_count descending allows to get the highest view_count first.
  191. $sql = "SELECT * FROM $lp_table
  192. WHERE
  193. c_id = $course_id AND
  194. lp_id = $lp_id AND
  195. user_id = $user_id
  196. $session
  197. ORDER BY view_count DESC";
  198. $res = Database::query($sql);
  199. if ($debug) {
  200. error_log('learnpath::__construct() '.__LINE__.' - querying lp_view: '.$sql, 0);
  201. }
  202. if (Database::num_rows($res) > 0) {
  203. if ($debug) {
  204. error_log('learnpath::__construct() '.__LINE__.' - Found previous view');
  205. }
  206. $row = Database::fetch_array($res);
  207. $this->attempt = $row['view_count'];
  208. $this->lp_view_id = $row['id'];
  209. $this->last_item_seen = $row['last_item'];
  210. $this->progress_db = $row['progress'];
  211. $this->lp_view_session_id = $row['session_id'];
  212. } elseif (!api_is_invitee()) {
  213. if ($debug) {
  214. error_log('learnpath::__construct() '.__LINE__.' - NOT Found previous view');
  215. }
  216. $this->attempt = 1;
  217. $params = [
  218. 'c_id' => $course_id,
  219. 'lp_id' => $lp_id,
  220. 'user_id' => $user_id,
  221. 'view_count' => 1,
  222. 'session_id' => $session_id,
  223. 'last_item' => 0,
  224. ];
  225. $this->last_item_seen = 0;
  226. $this->lp_view_session_id = $session_id;
  227. $this->lp_view_id = Database::insert($lp_table, $params);
  228. if (!empty($this->lp_view_id)) {
  229. $sql = "UPDATE $lp_table SET id = iid
  230. WHERE iid = ".$this->lp_view_id;
  231. Database::query($sql);
  232. }
  233. }
  234. // Initialise items.
  235. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  236. $sql = "SELECT * FROM $lp_item_table
  237. WHERE c_id = $course_id AND lp_id = '".$this->lp_id."'
  238. ORDER BY parent_item_id, display_order";
  239. $res = Database::query($sql);
  240. $lp_item_id_list = [];
  241. while ($row = Database::fetch_array($res)) {
  242. $lp_item_id_list[] = $row['iid'];
  243. switch ($this->type) {
  244. case 3: //aicc
  245. $oItem = new aiccItem('db', $row['iid'], $course_id);
  246. if (is_object($oItem)) {
  247. $my_item_id = $oItem->get_id();
  248. $oItem->set_lp_view($this->lp_view_id, $course_id);
  249. $oItem->set_prevent_reinit($this->prevent_reinit);
  250. // Don't use reference here as the next loop will make the pointed object change.
  251. $this->items[$my_item_id] = $oItem;
  252. $this->refs_list[$oItem->ref] = $my_item_id;
  253. if ($debug) {
  254. error_log(
  255. 'learnpath::__construct() - '.
  256. 'aicc object with id '.$my_item_id.
  257. ' set in items[]',
  258. 0
  259. );
  260. }
  261. }
  262. break;
  263. case 2:
  264. $oItem = new scormItem('db', $row['iid'], $course_id);
  265. if (is_object($oItem)) {
  266. $my_item_id = $oItem->get_id();
  267. $oItem->set_lp_view($this->lp_view_id, $course_id);
  268. $oItem->set_prevent_reinit($this->prevent_reinit);
  269. // Don't use reference here as the next loop will make the pointed object change.
  270. $this->items[$my_item_id] = $oItem;
  271. $this->refs_list[$oItem->ref] = $my_item_id;
  272. if ($debug) {
  273. error_log('object with id '.$my_item_id.' set in items[]');
  274. }
  275. }
  276. break;
  277. case 1:
  278. default:
  279. if ($debug) {
  280. error_log('learnpath::__construct() '.__LINE__.' - calling learnpathItem');
  281. }
  282. $oItem = new learnpathItem($row['iid'], $user_id, $course_id, $row);
  283. if ($debug) {
  284. error_log('learnpath::__construct() '.__LINE__.' - end calling learnpathItem');
  285. }
  286. if (is_object($oItem)) {
  287. $my_item_id = $oItem->get_id();
  288. // Moved down to when we are sure the item_view exists.
  289. //$oItem->set_lp_view($this->lp_view_id);
  290. $oItem->set_prevent_reinit($this->prevent_reinit);
  291. // Don't use reference here as the next loop will make the pointed object change.
  292. $this->items[$my_item_id] = $oItem;
  293. $this->refs_list[$my_item_id] = $my_item_id;
  294. if ($debug) {
  295. error_log(
  296. 'learnpath::__construct() '.__LINE__.
  297. ' - object with id '.$my_item_id.' set in items[]'
  298. );
  299. }
  300. }
  301. break;
  302. }
  303. // Setting the object level with variable $this->items[$i][parent]
  304. foreach ($this->items as $itemLPObject) {
  305. $level = self::get_level_for_item(
  306. $this->items,
  307. $itemLPObject->db_id
  308. );
  309. $itemLPObject->level = $level;
  310. }
  311. // Setting the view in the item object.
  312. if (is_object($this->items[$row['iid']])) {
  313. $this->items[$row['iid']]->set_lp_view($this->lp_view_id, $course_id);
  314. if ($this->items[$row['iid']]->get_type() == TOOL_HOTPOTATOES) {
  315. $this->items[$row['iid']]->current_start_time = 0;
  316. $this->items[$row['iid']]->current_stop_time = 0;
  317. }
  318. }
  319. }
  320. if (!empty($lp_item_id_list)) {
  321. $lp_item_id_list_to_string = implode("','", $lp_item_id_list);
  322. if (!empty($lp_item_id_list_to_string)) {
  323. // Get last viewing vars.
  324. $itemViewTable = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  325. // This query should only return one or zero result.
  326. $sql = "SELECT lp_item_id, status
  327. FROM $itemViewTable
  328. WHERE
  329. c_id = $course_id AND
  330. lp_view_id = ".$this->get_view_id()." AND
  331. lp_item_id IN ('".$lp_item_id_list_to_string."')
  332. ORDER BY view_count DESC ";
  333. $status_list = [];
  334. $res = Database::query($sql);
  335. while ($row = Database:: fetch_array($res)) {
  336. $status_list[$row['lp_item_id']] = $row['status'];
  337. }
  338. foreach ($lp_item_id_list as $item_id) {
  339. if (isset($status_list[$item_id])) {
  340. $status = $status_list[$item_id];
  341. if (is_object($this->items[$item_id])) {
  342. $this->items[$item_id]->set_status($status);
  343. if (empty($status)) {
  344. $this->items[$item_id]->set_status(
  345. $this->default_status
  346. );
  347. }
  348. }
  349. } else {
  350. if (!api_is_invitee()) {
  351. if (is_object($this->items[$item_id])) {
  352. $this->items[$item_id]->set_status(
  353. $this->default_status
  354. );
  355. }
  356. if (!empty($this->lp_view_id)) {
  357. // Add that row to the lp_item_view table so that
  358. // we have something to show in the stats page.
  359. $params = [
  360. 'c_id' => $course_id,
  361. 'lp_item_id' => $item_id,
  362. 'lp_view_id' => $this->lp_view_id,
  363. 'view_count' => 1,
  364. 'status' => 'not attempted',
  365. 'start_time' => time(),
  366. 'total_time' => 0,
  367. 'score' => 0,
  368. ];
  369. $insertId = Database::insert($itemViewTable, $params);
  370. if ($insertId) {
  371. $sql = "UPDATE $itemViewTable SET id = iid
  372. WHERE iid = $insertId";
  373. Database::query($sql);
  374. }
  375. $this->items[$item_id]->set_lp_view(
  376. $this->lp_view_id,
  377. $course_id
  378. );
  379. }
  380. }
  381. }
  382. }
  383. }
  384. }
  385. $this->ordered_items = self::get_flat_ordered_items_list(
  386. $this->get_id(),
  387. 0,
  388. $course_id
  389. );
  390. $this->max_ordered_items = 0;
  391. foreach ($this->ordered_items as $index => $dummy) {
  392. if ($index > $this->max_ordered_items && !empty($dummy)) {
  393. $this->max_ordered_items = $index;
  394. }
  395. }
  396. // TODO: Define the current item better.
  397. $this->first();
  398. if ($debug) {
  399. error_log('lp_view_session_id '.$this->lp_view_session_id);
  400. error_log('End of learnpath constructor for learnpath '.$this->get_id());
  401. }
  402. } else {
  403. $this->error = 'Learnpath ID does not exist in database ('.$sql.')';
  404. }
  405. }
  406. }
  407. /**
  408. * @return string
  409. */
  410. public function getCourseCode()
  411. {
  412. return $this->cc;
  413. }
  414. /**
  415. * @return int
  416. */
  417. public function get_course_int_id()
  418. {
  419. return isset($this->course_int_id) ? $this->course_int_id : api_get_course_int_id();
  420. }
  421. /**
  422. * @param $course_id
  423. *
  424. * @return int
  425. */
  426. public function set_course_int_id($course_id)
  427. {
  428. return $this->course_int_id = (int) $course_id;
  429. }
  430. /**
  431. * Function rewritten based on old_add_item() from Yannick Warnier.
  432. * Due the fact that users can decide where the item should come, I had to overlook this function and
  433. * I found it better to rewrite it. Old function is still available.
  434. * Added also the possibility to add a description.
  435. *
  436. * @param int $parent
  437. * @param int $previous
  438. * @param string $type
  439. * @param int $id resource ID (ref)
  440. * @param string $title
  441. * @param string $description
  442. * @param int $prerequisites
  443. * @param int $max_time_allowed
  444. * @param int $userId
  445. *
  446. * @return int
  447. */
  448. public function add_item(
  449. $parent,
  450. $previous,
  451. $type = 'dir',
  452. $id,
  453. $title,
  454. $description,
  455. $prerequisites = 0,
  456. $max_time_allowed = 0,
  457. $userId = 0
  458. ) {
  459. $course_id = $this->course_info['real_id'];
  460. if (empty($course_id)) {
  461. // Sometimes Oogie doesn't catch the course info but sets $this->cc
  462. $this->course_info = api_get_course_info($this->cc);
  463. $course_id = $this->course_info['real_id'];
  464. }
  465. $userId = empty($userId) ? api_get_user_id() : $userId;
  466. $sessionId = api_get_session_id();
  467. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  468. $_course = $this->course_info;
  469. $parent = (int) $parent;
  470. $previous = (int) $previous;
  471. $id = (int) $id;
  472. $max_time_allowed = htmlentities($max_time_allowed);
  473. if (empty($max_time_allowed)) {
  474. $max_time_allowed = 0;
  475. }
  476. $sql = "SELECT COUNT(iid) AS num
  477. FROM $tbl_lp_item
  478. WHERE
  479. c_id = $course_id AND
  480. lp_id = ".$this->get_id()." AND
  481. parent_item_id = $parent ";
  482. $res_count = Database::query($sql);
  483. $row = Database::fetch_array($res_count);
  484. $num = $row['num'];
  485. $tmp_previous = 0;
  486. $display_order = 0;
  487. $next = 0;
  488. if ($num > 0) {
  489. if (empty($previous)) {
  490. $sql = "SELECT iid, next_item_id, display_order
  491. FROM $tbl_lp_item
  492. WHERE
  493. c_id = $course_id AND
  494. lp_id = ".$this->get_id()." AND
  495. parent_item_id = $parent AND
  496. previous_item_id = 0 OR
  497. previous_item_id = $parent";
  498. $result = Database::query($sql);
  499. $row = Database::fetch_array($result);
  500. if ($row) {
  501. $next = $row['iid'];
  502. }
  503. } else {
  504. $previous = (int) $previous;
  505. $sql = "SELECT iid, previous_item_id, next_item_id, display_order
  506. FROM $tbl_lp_item
  507. WHERE
  508. c_id = $course_id AND
  509. lp_id = ".$this->get_id()." AND
  510. id = $previous";
  511. $result = Database::query($sql);
  512. $row = Database::fetch_array($result);
  513. if ($row) {
  514. $tmp_previous = $row['iid'];
  515. $next = $row['next_item_id'];
  516. $display_order = $row['display_order'];
  517. }
  518. }
  519. }
  520. $id = (int) $id;
  521. $typeCleaned = Database::escape_string($type);
  522. $max_score = 100;
  523. if ($type === 'quiz') {
  524. $sql = 'SELECT SUM(ponderation)
  525. FROM '.Database::get_course_table(TABLE_QUIZ_QUESTION).' as quiz_question
  526. INNER JOIN '.Database::get_course_table(TABLE_QUIZ_TEST_QUESTION).' as quiz_rel_question
  527. ON
  528. quiz_question.id = quiz_rel_question.question_id AND
  529. quiz_question.c_id = quiz_rel_question.c_id
  530. WHERE
  531. quiz_rel_question.exercice_id = '.$id." AND
  532. quiz_question.c_id = $course_id AND
  533. quiz_rel_question.c_id = $course_id ";
  534. $rsQuiz = Database::query($sql);
  535. $max_score = Database::result($rsQuiz, 0, 0);
  536. // Disabling the exercise if we add it inside a LP
  537. $exercise = new Exercise($course_id);
  538. $exercise->read($id);
  539. $exercise->disable();
  540. $exercise->save();
  541. }
  542. $params = [
  543. 'c_id' => $course_id,
  544. 'lp_id' => $this->get_id(),
  545. 'item_type' => $typeCleaned,
  546. 'ref' => '',
  547. 'title' => $title,
  548. 'description' => $description,
  549. 'path' => $id,
  550. 'max_score' => $max_score,
  551. 'parent_item_id' => $parent,
  552. 'previous_item_id' => $previous,
  553. 'next_item_id' => (int) $next,
  554. 'display_order' => $display_order + 1,
  555. 'prerequisite' => $prerequisites,
  556. 'max_time_allowed' => $max_time_allowed,
  557. 'min_score' => 0,
  558. 'launch_data' => '',
  559. ];
  560. if ($prerequisites != 0) {
  561. $params['prerequisite'] = $prerequisites;
  562. }
  563. $new_item_id = Database::insert($tbl_lp_item, $params);
  564. if ($new_item_id) {
  565. $sql = "UPDATE $tbl_lp_item SET id = iid WHERE iid = $new_item_id";
  566. Database::query($sql);
  567. if (!empty($next)) {
  568. $sql = "UPDATE $tbl_lp_item
  569. SET previous_item_id = $new_item_id
  570. WHERE c_id = $course_id AND id = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  571. Database::query($sql);
  572. }
  573. // Update the item that should be before the new item.
  574. if (!empty($tmp_previous)) {
  575. $sql = "UPDATE $tbl_lp_item
  576. SET next_item_id = $new_item_id
  577. WHERE c_id = $course_id AND id = $tmp_previous";
  578. Database::query($sql);
  579. }
  580. // Update all the items after the new item.
  581. $sql = "UPDATE $tbl_lp_item
  582. SET display_order = display_order + 1
  583. WHERE
  584. c_id = $course_id AND
  585. lp_id = ".$this->get_id()." AND
  586. iid <> $new_item_id AND
  587. parent_item_id = $parent AND
  588. display_order > $display_order";
  589. Database::query($sql);
  590. // Update the item that should come after the new item.
  591. $sql = "UPDATE $tbl_lp_item
  592. SET ref = $new_item_id
  593. WHERE c_id = $course_id AND iid = $new_item_id";
  594. Database::query($sql);
  595. $sql = "UPDATE $tbl_lp_item
  596. SET previous_item_id = ".$this->getLastInFirstLevel()."
  597. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  598. Database::query($sql);
  599. // Upload audio.
  600. if (!empty($_FILES['mp3']['name'])) {
  601. // Create the audio folder if it does not exist yet.
  602. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  603. if (!is_dir($filepath.'audio')) {
  604. mkdir(
  605. $filepath.'audio',
  606. api_get_permissions_for_new_directories()
  607. );
  608. $audio_id = add_document(
  609. $_course,
  610. '/audio',
  611. 'folder',
  612. 0,
  613. 'audio',
  614. '',
  615. 0,
  616. true,
  617. null,
  618. $sessionId,
  619. $userId
  620. );
  621. api_item_property_update(
  622. $_course,
  623. TOOL_DOCUMENT,
  624. $audio_id,
  625. 'FolderCreated',
  626. $userId,
  627. null,
  628. null,
  629. null,
  630. null,
  631. $sessionId
  632. );
  633. api_item_property_update(
  634. $_course,
  635. TOOL_DOCUMENT,
  636. $audio_id,
  637. 'invisible',
  638. $userId,
  639. null,
  640. null,
  641. null,
  642. null,
  643. $sessionId
  644. );
  645. }
  646. $file_path = handle_uploaded_document(
  647. $_course,
  648. $_FILES['mp3'],
  649. api_get_path(SYS_COURSE_PATH).$_course['path'].'/document',
  650. '/audio',
  651. $userId,
  652. '',
  653. '',
  654. '',
  655. '',
  656. false
  657. );
  658. // Getting the filename only.
  659. $file_components = explode('/', $file_path);
  660. $file = $file_components[count($file_components) - 1];
  661. // Store the mp3 file in the lp_item table.
  662. $sql = "UPDATE $tbl_lp_item SET
  663. audio = '".Database::escape_string($file)."'
  664. WHERE iid = '".intval($new_item_id)."'";
  665. Database::query($sql);
  666. }
  667. }
  668. return $new_item_id;
  669. }
  670. /**
  671. * Static admin function allowing addition of a learnpath to a course.
  672. *
  673. * @param string $courseCode
  674. * @param string $name
  675. * @param string $description
  676. * @param string $learnpath
  677. * @param string $origin
  678. * @param string $zipname Zip file containing the learnpath or directory containing the learnpath
  679. * @param string $publicated_on
  680. * @param string $expired_on
  681. * @param int $categoryId
  682. * @param int $userId
  683. *
  684. * @return int The new learnpath ID on success, 0 on failure
  685. */
  686. public static function add_lp(
  687. $courseCode,
  688. $name,
  689. $description = '',
  690. $learnpath = 'guess',
  691. $origin = 'zip',
  692. $zipname = '',
  693. $publicated_on = '',
  694. $expired_on = '',
  695. $categoryId = 0,
  696. $userId = 0
  697. ) {
  698. global $charset;
  699. if (!empty($courseCode)) {
  700. $courseInfo = api_get_course_info($courseCode);
  701. $course_id = $courseInfo['real_id'];
  702. } else {
  703. $course_id = api_get_course_int_id();
  704. $courseInfo = api_get_course_info();
  705. }
  706. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  707. // Check course code exists.
  708. // Check lp_name doesn't exist, otherwise append something.
  709. $i = 0;
  710. $name = Database::escape_string($name);
  711. $categoryId = (int) $categoryId;
  712. // Session id.
  713. $session_id = api_get_session_id();
  714. $userId = empty($userId) ? api_get_user_id() : $userId;
  715. $check_name = "SELECT * FROM $tbl_lp
  716. WHERE c_id = $course_id AND name = '$name'";
  717. $res_name = Database::query($check_name);
  718. if (empty($publicated_on)) {
  719. $publicated_on = null;
  720. } else {
  721. $publicated_on = Database::escape_string(api_get_utc_datetime($publicated_on));
  722. }
  723. if (empty($expired_on)) {
  724. $expired_on = null;
  725. } else {
  726. $expired_on = Database::escape_string(api_get_utc_datetime($expired_on));
  727. }
  728. while (Database::num_rows($res_name)) {
  729. // There is already one such name, update the current one a bit.
  730. $i++;
  731. $name = $name.' - '.$i;
  732. $check_name = "SELECT * FROM $tbl_lp
  733. WHERE c_id = $course_id AND name = '$name'";
  734. $res_name = Database::query($check_name);
  735. }
  736. // New name does not exist yet; keep it.
  737. // Escape description.
  738. // Kevin: added htmlentities().
  739. $description = Database::escape_string(api_htmlentities($description, ENT_QUOTES, $charset));
  740. $type = 1;
  741. switch ($learnpath) {
  742. case 'guess':
  743. break;
  744. case 'dokeos':
  745. case 'chamilo':
  746. $type = 1;
  747. break;
  748. case 'aicc':
  749. break;
  750. }
  751. switch ($origin) {
  752. case 'zip':
  753. // Check zip name string. If empty, we are currently creating a new Chamilo learnpath.
  754. break;
  755. case 'manual':
  756. default:
  757. $get_max = "SELECT MAX(display_order)
  758. FROM $tbl_lp WHERE c_id = $course_id";
  759. $res_max = Database::query($get_max);
  760. if (Database::num_rows($res_max) < 1) {
  761. $dsp = 1;
  762. } else {
  763. $row = Database::fetch_array($res_max);
  764. $dsp = $row[0] + 1;
  765. }
  766. $params = [
  767. 'c_id' => $course_id,
  768. 'lp_type' => $type,
  769. 'name' => $name,
  770. 'description' => $description,
  771. 'path' => '',
  772. 'default_view_mod' => 'embedded',
  773. 'default_encoding' => 'UTF-8',
  774. 'display_order' => $dsp,
  775. 'content_maker' => 'Chamilo',
  776. 'content_local' => 'local',
  777. 'js_lib' => '',
  778. 'session_id' => $session_id,
  779. 'created_on' => api_get_utc_datetime(),
  780. 'modified_on' => api_get_utc_datetime(),
  781. 'publicated_on' => $publicated_on,
  782. 'expired_on' => $expired_on,
  783. 'category_id' => $categoryId,
  784. 'force_commit' => 0,
  785. 'content_license' => '',
  786. 'debug' => 0,
  787. 'theme' => '',
  788. 'preview_image' => '',
  789. 'author' => '',
  790. 'prerequisite' => 0,
  791. 'hide_toc_frame' => 0,
  792. 'seriousgame_mode' => 0,
  793. 'autolaunch' => 0,
  794. 'max_attempts' => 0,
  795. 'subscribe_users' => 0,
  796. 'accumulate_scorm_time' => 1,
  797. ];
  798. $id = Database::insert($tbl_lp, $params);
  799. if ($id > 0) {
  800. $sql = "UPDATE $tbl_lp SET id = iid WHERE iid = $id";
  801. Database::query($sql);
  802. // Insert into item_property.
  803. api_item_property_update(
  804. $courseInfo,
  805. TOOL_LEARNPATH,
  806. $id,
  807. 'LearnpathAdded',
  808. $userId
  809. );
  810. api_set_default_visibility(
  811. $id,
  812. TOOL_LEARNPATH,
  813. 0,
  814. $courseInfo,
  815. $session_id,
  816. $userId
  817. );
  818. return $id;
  819. }
  820. break;
  821. }
  822. }
  823. /**
  824. * Auto completes the parents of an item in case it's been completed or passed.
  825. *
  826. * @param int $item Optional ID of the item from which to look for parents
  827. */
  828. public function autocomplete_parents($item)
  829. {
  830. $debug = $this->debug;
  831. if (empty($item)) {
  832. $item = $this->current;
  833. }
  834. $currentItem = $this->getItem($item);
  835. if ($currentItem) {
  836. $parent_id = $currentItem->get_parent();
  837. $parent = $this->getItem($parent_id);
  838. if ($parent) {
  839. // if $item points to an object and there is a parent.
  840. if ($debug) {
  841. error_log(
  842. 'Autocompleting parent of item '.$item.' '.
  843. $currentItem->get_title().'" (item '.$parent_id.' "'.$parent->get_title().'") ',
  844. 0
  845. );
  846. }
  847. // New experiment including failed and browsed in completed status.
  848. //$current_status = $currentItem->get_status();
  849. //if ($currentItem->is_done() || $current_status == 'browsed' || $current_status == 'failed') {
  850. // Fixes chapter auto complete
  851. if (true) {
  852. // If the current item is completed or passes or succeeded.
  853. $updateParentStatus = true;
  854. if ($debug) {
  855. error_log('Status of current item is alright');
  856. }
  857. foreach ($parent->get_children() as $childItemId) {
  858. $childItem = $this->getItem($childItemId);
  859. // If children was not set try to get the info
  860. if (empty($childItem->db_item_view_id)) {
  861. $childItem->set_lp_view($this->lp_view_id, $this->course_int_id);
  862. }
  863. // Check all his brothers (parent's children) for completion status.
  864. if ($childItemId != $item) {
  865. if ($debug) {
  866. error_log(
  867. 'Looking at brother #'.$childItemId.' "'.$childItem->get_title().'", status is '.$childItem->get_status(),
  868. 0
  869. );
  870. }
  871. // Trying completing parents of failed and browsed items as well.
  872. if ($childItem->status_is(
  873. [
  874. 'completed',
  875. 'passed',
  876. 'succeeded',
  877. 'browsed',
  878. 'failed',
  879. ]
  880. )
  881. ) {
  882. // Keep completion status to true.
  883. continue;
  884. } else {
  885. if ($debug > 2) {
  886. error_log(
  887. 'Found one incomplete child of parent #'.$parent_id.': child #'.$childItemId.' "'.$childItem->get_title().'", is '.$childItem->get_status().' db_item_view_id:#'.$childItem->db_item_view_id,
  888. 0
  889. );
  890. }
  891. $updateParentStatus = false;
  892. break;
  893. }
  894. }
  895. }
  896. if ($updateParentStatus) {
  897. // If all the children were completed:
  898. $parent->set_status('completed');
  899. $parent->save(false, $this->prerequisites_match($parent->get_id()));
  900. // Force the status to "completed"
  901. //$this->update_queue[$parent->get_id()] = $parent->get_status();
  902. $this->update_queue[$parent->get_id()] = 'completed';
  903. if ($debug) {
  904. error_log(
  905. 'Added parent #'.$parent->get_id().' "'.$parent->get_title().'" to update queue status: completed '.
  906. print_r($this->update_queue, 1),
  907. 0
  908. );
  909. }
  910. // Recursive call.
  911. $this->autocomplete_parents($parent->get_id());
  912. }
  913. }
  914. } else {
  915. if ($debug) {
  916. error_log("Parent #$parent_id does not exists");
  917. }
  918. }
  919. } else {
  920. if ($debug) {
  921. error_log("#$item is an item that doesn't have parents");
  922. }
  923. }
  924. }
  925. /**
  926. * Closes the current resource.
  927. *
  928. * Stops the timer
  929. * Saves into the database if required
  930. * Clears the current resource data from this object
  931. *
  932. * @return bool True on success, false on failure
  933. */
  934. public function close()
  935. {
  936. if (empty($this->lp_id)) {
  937. $this->error = 'Trying to close this learnpath but no ID is set';
  938. return false;
  939. }
  940. $this->current_time_stop = time();
  941. $this->ordered_items = [];
  942. $this->index = 0;
  943. unset($this->lp_id);
  944. //unset other stuff
  945. return true;
  946. }
  947. /**
  948. * Static admin function allowing removal of a learnpath.
  949. *
  950. * @param array $courseInfo
  951. * @param int $id Learnpath ID
  952. * @param string $delete Whether to delete data or keep it (default: 'keep', others: 'remove')
  953. *
  954. * @return bool True on success, false on failure (might change that to return number of elements deleted)
  955. */
  956. public function delete($courseInfo = null, $id = null, $delete = 'keep')
  957. {
  958. $course_id = api_get_course_int_id();
  959. if (!empty($courseInfo)) {
  960. $course_id = isset($courseInfo['real_id']) ? $courseInfo['real_id'] : $course_id;
  961. }
  962. // TODO: Implement a way of getting this to work when the current object is not set.
  963. // In clear: implement this in the item class as well (abstract class) and use the given ID in queries.
  964. // If an ID is specifically given and the current LP is not the same, prevent delete.
  965. if (!empty($id) && ($id != $this->lp_id)) {
  966. return false;
  967. }
  968. $lp = Database::get_course_table(TABLE_LP_MAIN);
  969. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  970. $lp_view = Database::get_course_table(TABLE_LP_VIEW);
  971. $lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  972. // Delete lp item id.
  973. foreach ($this->items as $lpItemId => $dummy) {
  974. $sql = "DELETE FROM $lp_item_view
  975. WHERE c_id = $course_id AND lp_item_id = '".$lpItemId."'";
  976. Database::query($sql);
  977. }
  978. // Proposed by Christophe (nickname: clefevre)
  979. $sql = "DELETE FROM $lp_item
  980. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  981. Database::query($sql);
  982. $sql = "DELETE FROM $lp_view
  983. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  984. Database::query($sql);
  985. self::toggle_publish($this->lp_id, 'i');
  986. if ($this->type == 2 || $this->type == 3) {
  987. // This is a scorm learning path, delete the files as well.
  988. $sql = "SELECT path FROM $lp
  989. WHERE iid = ".$this->lp_id;
  990. $res = Database::query($sql);
  991. if (Database::num_rows($res) > 0) {
  992. $row = Database::fetch_array($res);
  993. $path = $row['path'];
  994. $sql = "SELECT id FROM $lp
  995. WHERE
  996. c_id = $course_id AND
  997. path = '$path' AND
  998. iid != ".$this->lp_id;
  999. $res = Database::query($sql);
  1000. if (Database::num_rows($res) > 0) {
  1001. // Another learning path uses this directory, so don't delete it.
  1002. if ($this->debug > 2) {
  1003. error_log('In learnpath::delete(), found other LP using path '.$path.', keeping directory', 0);
  1004. }
  1005. } else {
  1006. // No other LP uses that directory, delete it.
  1007. $course_rel_dir = api_get_course_path().'/scorm/'; // scorm dir web path starting from /courses
  1008. // The absolute system path for this course.
  1009. $course_scorm_dir = api_get_path(SYS_COURSE_PATH).$course_rel_dir;
  1010. if ($delete == 'remove' && is_dir($course_scorm_dir.$path) && !empty($course_scorm_dir)) {
  1011. if ($this->debug > 2) {
  1012. error_log('In learnpath::delete(), found SCORM, deleting directory: '.$course_scorm_dir.$path, 0);
  1013. }
  1014. // Proposed by Christophe (clefevre).
  1015. if (strcmp(substr($path, -2), "/.") == 0) {
  1016. $path = substr($path, 0, -1); // Remove "." at the end.
  1017. }
  1018. //exec('rm -rf ' . $course_scorm_dir . $path); // See Bug #5208, this is not OS-portable way.
  1019. rmdirr($course_scorm_dir.$path);
  1020. }
  1021. }
  1022. }
  1023. }
  1024. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  1025. $link = 'lp/lp_controller.php?action=view&lp_id='.$this->lp_id;
  1026. // Delete tools
  1027. $sql = "DELETE FROM $tbl_tool
  1028. WHERE c_id = $course_id AND (link LIKE '$link%' AND image='scormbuilder.gif')";
  1029. Database::query($sql);
  1030. $sql = "DELETE FROM $lp
  1031. WHERE iid = ".$this->lp_id;
  1032. Database::query($sql);
  1033. // Updates the display order of all lps.
  1034. $this->update_display_order();
  1035. api_item_property_update(
  1036. api_get_course_info(),
  1037. TOOL_LEARNPATH,
  1038. $this->lp_id,
  1039. 'delete',
  1040. api_get_user_id()
  1041. );
  1042. $link_info = GradebookUtils::isResourceInCourseGradebook(
  1043. api_get_course_id(),
  1044. 4,
  1045. $id,
  1046. api_get_session_id()
  1047. );
  1048. if ($link_info !== false) {
  1049. GradebookUtils::remove_resource_from_course_gradebook($link_info['id']);
  1050. }
  1051. if (api_get_setting('search_enabled') == 'true') {
  1052. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1053. delete_all_values_for_item($this->cc, TOOL_LEARNPATH, $this->lp_id);
  1054. }
  1055. }
  1056. /**
  1057. * Removes all the children of one item - dangerous!
  1058. *
  1059. * @param int $id Element ID of which children have to be removed
  1060. *
  1061. * @return int Total number of children removed
  1062. */
  1063. public function delete_children_items($id)
  1064. {
  1065. $course_id = $this->course_info['real_id'];
  1066. $num = 0;
  1067. $id = (int) $id;
  1068. if (empty($id) || empty($course_id)) {
  1069. return false;
  1070. }
  1071. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1072. $sql = "SELECT * FROM $lp_item
  1073. WHERE c_id = $course_id AND parent_item_id = $id";
  1074. $res = Database::query($sql);
  1075. while ($row = Database::fetch_array($res)) {
  1076. $num += $this->delete_children_items($row['iid']);
  1077. $sql = "DELETE FROM $lp_item
  1078. WHERE c_id = $course_id AND iid = ".$row['iid'];
  1079. Database::query($sql);
  1080. $num++;
  1081. }
  1082. return $num;
  1083. }
  1084. /**
  1085. * Removes an item from the current learnpath.
  1086. *
  1087. * @param int $id Elem ID (0 if first)
  1088. *
  1089. * @return int Number of elements moved
  1090. *
  1091. * @todo implement resource removal
  1092. */
  1093. public function delete_item($id)
  1094. {
  1095. $course_id = api_get_course_int_id();
  1096. $id = (int) $id;
  1097. // TODO: Implement the resource removal.
  1098. if (empty($id) || empty($course_id)) {
  1099. return false;
  1100. }
  1101. // First select item to get previous, next, and display order.
  1102. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1103. $sql_sel = "SELECT * FROM $lp_item WHERE iid = $id";
  1104. $res_sel = Database::query($sql_sel);
  1105. if (Database::num_rows($res_sel) < 1) {
  1106. return false;
  1107. }
  1108. $row = Database::fetch_array($res_sel);
  1109. $previous = $row['previous_item_id'];
  1110. $next = $row['next_item_id'];
  1111. $display = $row['display_order'];
  1112. $parent = $row['parent_item_id'];
  1113. $lp = $row['lp_id'];
  1114. // Delete children items.
  1115. $this->delete_children_items($id);
  1116. // Now delete the item.
  1117. $sql_del = "DELETE FROM $lp_item WHERE iid = $id";
  1118. Database::query($sql_del);
  1119. // Now update surrounding items.
  1120. $sql_upd = "UPDATE $lp_item SET next_item_id = $next
  1121. WHERE iid = $previous";
  1122. Database::query($sql_upd);
  1123. $sql_upd = "UPDATE $lp_item SET previous_item_id = $previous
  1124. WHERE iid = $next AND item_type != '".TOOL_LP_FINAL_ITEM."'";
  1125. Database::query($sql_upd);
  1126. // Now update all following items with new display order.
  1127. $sql_all = "UPDATE $lp_item SET display_order = display_order-1
  1128. WHERE
  1129. c_id = $course_id AND
  1130. lp_id = $lp AND
  1131. parent_item_id = $parent AND
  1132. display_order > $display";
  1133. Database::query($sql_all);
  1134. //Removing prerequisites since the item will not longer exist
  1135. $sql_all = "UPDATE $lp_item SET prerequisite = ''
  1136. WHERE c_id = $course_id AND prerequisite = $id";
  1137. Database::query($sql_all);
  1138. $sql = "UPDATE $lp_item
  1139. SET previous_item_id = ".$this->getLastInFirstLevel()."
  1140. WHERE c_id = $course_id AND lp_id = {$this->lp_id} AND item_type = '".TOOL_LP_FINAL_ITEM."'";
  1141. Database::query($sql);
  1142. // Remove from search engine if enabled.
  1143. if (api_get_setting('search_enabled') === 'true') {
  1144. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1145. $sql = 'SELECT * FROM %s
  1146. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1147. LIMIT 1';
  1148. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1149. $res = Database::query($sql);
  1150. if (Database::num_rows($res) > 0) {
  1151. $row2 = Database::fetch_array($res);
  1152. $di = new ChamiloIndexer();
  1153. $di->remove_document($row2['search_did']);
  1154. }
  1155. $sql = 'DELETE FROM %s
  1156. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  1157. LIMIT 1';
  1158. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp, $id);
  1159. Database::query($sql);
  1160. }
  1161. }
  1162. /**
  1163. * Updates an item's content in place.
  1164. *
  1165. * @param int $id Element ID
  1166. * @param int $parent Parent item ID
  1167. * @param int $previous Previous item ID
  1168. * @param string $title Item title
  1169. * @param string $description Item description
  1170. * @param string $prerequisites Prerequisites (optional)
  1171. * @param array $audio The array resulting of the $_FILES[mp3] element
  1172. * @param int $max_time_allowed
  1173. * @param string $url
  1174. *
  1175. * @return bool True on success, false on error
  1176. */
  1177. public function edit_item(
  1178. $id,
  1179. $parent,
  1180. $previous,
  1181. $title,
  1182. $description,
  1183. $prerequisites = '0',
  1184. $audio = [],
  1185. $max_time_allowed = 0,
  1186. $url = ''
  1187. ) {
  1188. $course_id = api_get_course_int_id();
  1189. $_course = api_get_course_info();
  1190. $id = (int) $id;
  1191. if (empty($max_time_allowed)) {
  1192. $max_time_allowed = 0;
  1193. }
  1194. if (empty($id) || empty($_course)) {
  1195. return false;
  1196. }
  1197. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1198. $sql = "SELECT * FROM $tbl_lp_item
  1199. WHERE iid = $id";
  1200. $res_select = Database::query($sql);
  1201. $row_select = Database::fetch_array($res_select);
  1202. $audio_update_sql = '';
  1203. if (is_array($audio) && !empty($audio['tmp_name']) && $audio['error'] === 0) {
  1204. // Create the audio folder if it does not exist yet.
  1205. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  1206. if (!is_dir($filepath.'audio')) {
  1207. mkdir($filepath.'audio', api_get_permissions_for_new_directories());
  1208. $audio_id = add_document(
  1209. $_course,
  1210. '/audio',
  1211. 'folder',
  1212. 0,
  1213. 'audio'
  1214. );
  1215. api_item_property_update(
  1216. $_course,
  1217. TOOL_DOCUMENT,
  1218. $audio_id,
  1219. 'FolderCreated',
  1220. api_get_user_id(),
  1221. null,
  1222. null,
  1223. null,
  1224. null,
  1225. api_get_session_id()
  1226. );
  1227. api_item_property_update(
  1228. $_course,
  1229. TOOL_DOCUMENT,
  1230. $audio_id,
  1231. 'invisible',
  1232. api_get_user_id(),
  1233. null,
  1234. null,
  1235. null,
  1236. null,
  1237. api_get_session_id()
  1238. );
  1239. }
  1240. // Upload file in documents.
  1241. $pi = pathinfo($audio['name']);
  1242. if ($pi['extension'] === 'mp3') {
  1243. $c_det = api_get_course_info($this->cc);
  1244. $bp = api_get_path(SYS_COURSE_PATH).$c_det['path'].'/document';
  1245. $path = handle_uploaded_document(
  1246. $c_det,
  1247. $audio,
  1248. $bp,
  1249. '/audio',
  1250. api_get_user_id(),
  1251. 0,
  1252. null,
  1253. 0,
  1254. 'rename',
  1255. false,
  1256. 0
  1257. );
  1258. $path = substr($path, 7);
  1259. // Update reference in lp_item - audio path is the path from inside de document/audio/ dir.
  1260. $audio_update_sql = ", audio = '".Database::escape_string($path)."' ";
  1261. }
  1262. }
  1263. $same_parent = $row_select['parent_item_id'] == $parent ? true : false;
  1264. $same_previous = $row_select['previous_item_id'] == $previous ? true : false;
  1265. // TODO: htmlspecialchars to be checked for encoding related problems.
  1266. if ($same_parent && $same_previous) {
  1267. // Only update title and description.
  1268. $sql = "UPDATE $tbl_lp_item
  1269. SET title = '".Database::escape_string($title)."',
  1270. prerequisite = '".$prerequisites."',
  1271. description = '".Database::escape_string($description)."'
  1272. ".$audio_update_sql.",
  1273. max_time_allowed = '".Database::escape_string($max_time_allowed)."'
  1274. WHERE iid = $id";
  1275. Database::query($sql);
  1276. } else {
  1277. $old_parent = $row_select['parent_item_id'];
  1278. $old_previous = $row_select['previous_item_id'];
  1279. $old_next = $row_select['next_item_id'];
  1280. $old_order = $row_select['display_order'];
  1281. $old_prerequisite = $row_select['prerequisite'];
  1282. $old_max_time_allowed = $row_select['max_time_allowed'];
  1283. /* BEGIN -- virtually remove the current item id */
  1284. /* for the next and previous item it is like the current item doesn't exist anymore */
  1285. if ($old_previous != 0) {
  1286. // Next
  1287. $sql = "UPDATE $tbl_lp_item
  1288. SET next_item_id = $old_next
  1289. WHERE iid = $old_previous";
  1290. Database::query($sql);
  1291. }
  1292. if (!empty($old_next)) {
  1293. // Previous
  1294. $sql = "UPDATE $tbl_lp_item
  1295. SET previous_item_id = $old_previous
  1296. WHERE iid = $old_next";
  1297. Database::query($sql);
  1298. }
  1299. // display_order - 1 for every item with a display_order
  1300. // bigger then the display_order of the current item.
  1301. $sql = "UPDATE $tbl_lp_item
  1302. SET display_order = display_order - 1
  1303. WHERE
  1304. c_id = $course_id AND
  1305. display_order > $old_order AND
  1306. lp_id = ".$this->lp_id." AND
  1307. parent_item_id = $old_parent";
  1308. Database::query($sql);
  1309. /* END -- virtually remove the current item id */
  1310. /* BEGIN -- update the current item id to his new location */
  1311. if ($previous == 0) {
  1312. // Select the data of the item that should come after the current item.
  1313. $sql = "SELECT id, display_order
  1314. FROM $tbl_lp_item
  1315. WHERE
  1316. c_id = $course_id AND
  1317. lp_id = ".$this->lp_id." AND
  1318. parent_item_id = $parent AND
  1319. previous_item_id = $previous";
  1320. $res_select_old = Database::query($sql);
  1321. $row_select_old = Database::fetch_array($res_select_old);
  1322. // If the new parent didn't have children before.
  1323. if (Database::num_rows($res_select_old) == 0) {
  1324. $new_next = 0;
  1325. $new_order = 1;
  1326. } else {
  1327. $new_next = $row_select_old['id'];
  1328. $new_order = $row_select_old['display_order'];
  1329. }
  1330. } else {
  1331. // Select the data of the item that should come before the current item.
  1332. $sql = "SELECT next_item_id, display_order
  1333. FROM $tbl_lp_item
  1334. WHERE iid = $previous";
  1335. $res_select_old = Database::query($sql);
  1336. $row_select_old = Database::fetch_array($res_select_old);
  1337. $new_next = $row_select_old['next_item_id'];
  1338. $new_order = $row_select_old['display_order'] + 1;
  1339. }
  1340. // TODO: htmlspecialchars to be checked for encoding related problems.
  1341. // Update the current item with the new data.
  1342. $sql = "UPDATE $tbl_lp_item
  1343. SET
  1344. title = '".Database::escape_string($title)."',
  1345. description = '".Database::escape_string($description)."',
  1346. parent_item_id = $parent,
  1347. previous_item_id = $previous,
  1348. next_item_id = $new_next,
  1349. display_order = $new_order
  1350. $audio_update_sql
  1351. WHERE iid = $id";
  1352. Database::query($sql);
  1353. if ($previous != 0) {
  1354. // Update the previous item's next_item_id.
  1355. $sql = "UPDATE $tbl_lp_item
  1356. SET next_item_id = $id
  1357. WHERE iid = $previous";
  1358. Database::query($sql);
  1359. }
  1360. if (!empty($new_next)) {
  1361. // Update the next item's previous_item_id.
  1362. $sql = "UPDATE $tbl_lp_item
  1363. SET previous_item_id = $id
  1364. WHERE iid = $new_next";
  1365. Database::query($sql);
  1366. }
  1367. if ($old_prerequisite != $prerequisites) {
  1368. $sql = "UPDATE $tbl_lp_item
  1369. SET prerequisite = '$prerequisites'
  1370. WHERE iid = $id";
  1371. Database::query($sql);
  1372. }
  1373. if ($old_max_time_allowed != $max_time_allowed) {
  1374. // update max time allowed
  1375. $sql = "UPDATE $tbl_lp_item
  1376. SET max_time_allowed = $max_time_allowed
  1377. WHERE iid = $id";
  1378. Database::query($sql);
  1379. }
  1380. // Update all the items with the same or a bigger display_order than the current item.
  1381. $sql = "UPDATE $tbl_lp_item
  1382. SET display_order = display_order + 1
  1383. WHERE
  1384. c_id = $course_id AND
  1385. lp_id = ".$this->get_id()." AND
  1386. iid <> $id AND
  1387. parent_item_id = $parent AND
  1388. display_order >= $new_order";
  1389. Database::query($sql);
  1390. }
  1391. if ($row_select['item_type'] == 'link') {
  1392. $link = new Link();
  1393. $linkId = $row_select['path'];
  1394. $link->updateLink($linkId, $url);
  1395. }
  1396. }
  1397. /**
  1398. * Updates an item's prereq in place.
  1399. *
  1400. * @param int $id Element ID
  1401. * @param string $prerequisite_id Prerequisite Element ID
  1402. * @param int $minScore Prerequisite min score
  1403. * @param int $maxScore Prerequisite max score
  1404. *
  1405. * @return bool True on success, false on error
  1406. */
  1407. public function edit_item_prereq(
  1408. $id,
  1409. $prerequisite_id,
  1410. $minScore = 0,
  1411. $maxScore = 100
  1412. ) {
  1413. $id = (int) $id;
  1414. $prerequisite_id = (int) $prerequisite_id;
  1415. if (empty($id)) {
  1416. return false;
  1417. }
  1418. if (empty($minScore) || $minScore < 0) {
  1419. $minScore = 0;
  1420. }
  1421. if (empty($maxScore) || $maxScore < 0) {
  1422. $maxScore = 100;
  1423. }
  1424. $minScore = floatval($minScore);
  1425. $maxScore = floatval($maxScore);
  1426. if (empty($prerequisite_id)) {
  1427. $prerequisite_id = 'NULL';
  1428. $minScore = 0;
  1429. $maxScore = 100;
  1430. }
  1431. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1432. $sql = " UPDATE $tbl_lp_item
  1433. SET
  1434. prerequisite = $prerequisite_id ,
  1435. prerequisite_min_score = $minScore ,
  1436. prerequisite_max_score = $maxScore
  1437. WHERE iid = $id";
  1438. Database::query($sql);
  1439. return true;
  1440. }
  1441. /**
  1442. * Gets all the chapters belonging to the same parent as the item/chapter given
  1443. * Can also be called as abstract method.
  1444. *
  1445. * @deprecated not used
  1446. *
  1447. * @param int $id Item ID
  1448. *
  1449. * @return array A list of all the "brother items" (or an empty array on failure)
  1450. */
  1451. public function getSiblingDirectories($id)
  1452. {
  1453. $course_id = api_get_course_int_id();
  1454. if (empty($id) || $id != strval(intval($id))) {
  1455. return [];
  1456. }
  1457. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1458. $sql_parent = "SELECT * FROM $lp_item
  1459. WHERE iid = $id AND item_type='dir'";
  1460. $res_parent = Database::query($sql_parent);
  1461. if (Database::num_rows($res_parent) > 0) {
  1462. $row_parent = Database::fetch_array($res_parent);
  1463. $parent = $row_parent['parent_item_id'];
  1464. $sql = "SELECT * FROM $lp_item
  1465. WHERE
  1466. parent_item_id = $parent AND
  1467. iid = $id AND
  1468. item_type='dir'
  1469. ORDER BY display_order";
  1470. $res_bros = Database::query($sql);
  1471. $list = [];
  1472. while ($row_bro = Database::fetch_array($res_bros)) {
  1473. $list[] = $row_bro;
  1474. }
  1475. return $list;
  1476. }
  1477. return [];
  1478. }
  1479. /**
  1480. * Gets all the items belonging to the same parent as the item given
  1481. * Can also be called as abstract method.
  1482. *
  1483. * @deprecated not used
  1484. *
  1485. * @param int $id Item ID
  1486. *
  1487. * @return array A list of all the "brother items" (or an empty array on failure)
  1488. */
  1489. public function get_brother_items($id)
  1490. {
  1491. $course_id = api_get_course_int_id();
  1492. if (empty($id) || $id != strval(intval($id))) {
  1493. return [];
  1494. }
  1495. $lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1496. $sql_parent = "SELECT * FROM $lp_item
  1497. WHERE iid = $id";
  1498. $res_parent = Database::query($sql_parent);
  1499. if (Database::num_rows($res_parent) > 0) {
  1500. $row_parent = Database::fetch_array($res_parent);
  1501. $parent = $row_parent['parent_item_id'];
  1502. $sql = "SELECT * FROM $lp_item
  1503. WHERE c_id = $course_id AND parent_item_id = $parent
  1504. ORDER BY display_order";
  1505. $res_bros = Database::query($sql);
  1506. $list = [];
  1507. while ($row_bro = Database::fetch_array($res_bros)) {
  1508. $list[] = $row_bro;
  1509. }
  1510. return $list;
  1511. }
  1512. return [];
  1513. }
  1514. /**
  1515. * Get the specific prefix index terms of this learning path.
  1516. *
  1517. * @param string $prefix
  1518. *
  1519. * @return array Array of terms
  1520. */
  1521. public function get_common_index_terms_by_prefix($prefix)
  1522. {
  1523. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  1524. $terms = get_specific_field_values_list_by_prefix(
  1525. $prefix,
  1526. $this->cc,
  1527. TOOL_LEARNPATH,
  1528. $this->lp_id
  1529. );
  1530. $prefix_terms = [];
  1531. if (!empty($terms)) {
  1532. foreach ($terms as $term) {
  1533. $prefix_terms[] = $term['value'];
  1534. }
  1535. }
  1536. return $prefix_terms;
  1537. }
  1538. /**
  1539. * Gets the number of items currently completed.
  1540. *
  1541. * @param bool $failedStatusException flag to determine the failed status is not considered progressed
  1542. *
  1543. * @return int The number of items currently completed
  1544. */
  1545. public function get_complete_items_count($failedStatusException = false)
  1546. {
  1547. $i = 0;
  1548. $completedStatusList = [
  1549. 'completed',
  1550. 'passed',
  1551. 'succeeded',
  1552. 'browsed',
  1553. ];
  1554. if (!$failedStatusException) {
  1555. $completedStatusList[] = 'failed';
  1556. }
  1557. foreach ($this->items as $id => $dummy) {
  1558. // Trying failed and browsed considered "progressed" as well.
  1559. if ($this->items[$id]->status_is($completedStatusList) &&
  1560. $this->items[$id]->get_type() != 'dir'
  1561. ) {
  1562. $i++;
  1563. }
  1564. }
  1565. return $i;
  1566. }
  1567. /**
  1568. * Gets the current item ID.
  1569. *
  1570. * @return int The current learnpath item id
  1571. */
  1572. public function get_current_item_id()
  1573. {
  1574. $current = 0;
  1575. if (!empty($this->current)) {
  1576. $current = (int) $this->current;
  1577. }
  1578. return $current;
  1579. }
  1580. /**
  1581. * Force to get the first learnpath item id.
  1582. *
  1583. * @return int The current learnpath item id
  1584. */
  1585. public function get_first_item_id()
  1586. {
  1587. $current = 0;
  1588. if (is_array($this->ordered_items)) {
  1589. $current = $this->ordered_items[0];
  1590. }
  1591. return $current;
  1592. }
  1593. /**
  1594. * Gets the total number of items available for viewing in this SCORM.
  1595. *
  1596. * @return int The total number of items
  1597. */
  1598. public function get_total_items_count()
  1599. {
  1600. return count($this->items);
  1601. }
  1602. /**
  1603. * Gets the total number of items available for viewing in this SCORM but without chapters.
  1604. *
  1605. * @return int The total no-chapters number of items
  1606. */
  1607. public function getTotalItemsCountWithoutDirs()
  1608. {
  1609. $total = 0;
  1610. $typeListNotToCount = self::getChapterTypes();
  1611. foreach ($this->items as $temp2) {
  1612. if (!in_array($temp2->get_type(), $typeListNotToCount)) {
  1613. $total++;
  1614. }
  1615. }
  1616. return $total;
  1617. }
  1618. /**
  1619. * Sets the first element URL.
  1620. */
  1621. public function first()
  1622. {
  1623. if ($this->debug > 0) {
  1624. error_log('In learnpath::first()', 0);
  1625. error_log('$this->last_item_seen '.$this->last_item_seen);
  1626. }
  1627. // Test if the last_item_seen exists and is not a dir.
  1628. if (count($this->ordered_items) == 0) {
  1629. $this->index = 0;
  1630. }
  1631. if (!empty($this->last_item_seen) &&
  1632. !empty($this->items[$this->last_item_seen]) &&
  1633. $this->items[$this->last_item_seen]->get_type() != 'dir'
  1634. //with this change (below) the LP will NOT go to the next item, it will take lp item we left
  1635. //&& !$this->items[$this->last_item_seen]->is_done()
  1636. ) {
  1637. if ($this->debug > 2) {
  1638. error_log(
  1639. 'In learnpath::first() - Last item seen is '.$this->last_item_seen.' of type '.
  1640. $this->items[$this->last_item_seen]->get_type()
  1641. );
  1642. }
  1643. $index = -1;
  1644. foreach ($this->ordered_items as $myindex => $item_id) {
  1645. if ($item_id == $this->last_item_seen) {
  1646. $index = $myindex;
  1647. break;
  1648. }
  1649. }
  1650. if ($index == -1) {
  1651. // Index hasn't changed, so item not found - panic (this shouldn't happen).
  1652. if ($this->debug > 2) {
  1653. error_log('Last item ('.$this->last_item_seen.') was found in items but not in ordered_items, panic!', 0);
  1654. }
  1655. return false;
  1656. } else {
  1657. $this->last = $this->last_item_seen;
  1658. $this->current = $this->last_item_seen;
  1659. $this->index = $index;
  1660. }
  1661. } else {
  1662. if ($this->debug > 2) {
  1663. error_log('In learnpath::first() - No last item seen', 0);
  1664. }
  1665. $index = 0;
  1666. // Loop through all ordered items and stop at the first item that is
  1667. // not a directory *and* that has not been completed yet.
  1668. while (!empty($this->ordered_items[$index]) &&
  1669. is_a($this->items[$this->ordered_items[$index]], 'learnpathItem') &&
  1670. (
  1671. $this->items[$this->ordered_items[$index]]->get_type() == 'dir' ||
  1672. $this->items[$this->ordered_items[$index]]->is_done() === true
  1673. ) && $index < $this->max_ordered_items) {
  1674. $index++;
  1675. }
  1676. $this->last = $this->current;
  1677. // current is
  1678. $this->current = isset($this->ordered_items[$index]) ? $this->ordered_items[$index] : null;
  1679. $this->index = $index;
  1680. if ($this->debug > 2) {
  1681. error_log('$index '.$index);
  1682. error_log('In learnpath::first() - No last item seen');
  1683. error_log('New last = '.$this->last.'('.$this->ordered_items[$index].')');
  1684. }
  1685. }
  1686. if ($this->debug > 2) {
  1687. error_log('In learnpath::first() - First item is '.$this->get_current_item_id());
  1688. }
  1689. }
  1690. /**
  1691. * Gets the js library from the database.
  1692. *
  1693. * @return string The name of the javascript library to be used
  1694. */
  1695. public function get_js_lib()
  1696. {
  1697. $lib = '';
  1698. if (!empty($this->js_lib)) {
  1699. $lib = $this->js_lib;
  1700. }
  1701. return $lib;
  1702. }
  1703. /**
  1704. * Gets the learnpath database ID.
  1705. *
  1706. * @return int Learnpath ID in the lp table
  1707. */
  1708. public function get_id()
  1709. {
  1710. if (!empty($this->lp_id)) {
  1711. return (int) $this->lp_id;
  1712. }
  1713. return 0;
  1714. }
  1715. /**
  1716. * Gets the last element URL.
  1717. *
  1718. * @return string URL to load into the viewer
  1719. */
  1720. public function get_last()
  1721. {
  1722. // This is just in case the lesson doesn't cointain a valid scheme, just to avoid "Notices"
  1723. if (count($this->ordered_items) > 0) {
  1724. $this->index = count($this->ordered_items) - 1;
  1725. return $this->ordered_items[$this->index];
  1726. }
  1727. return false;
  1728. }
  1729. /**
  1730. * Get the last element in the first level.
  1731. * Unlike learnpath::get_last this function doesn't consider the subsection' elements.
  1732. *
  1733. * @return mixed
  1734. */
  1735. public function getLastInFirstLevel()
  1736. {
  1737. try {
  1738. $lastId = Database::getManager()
  1739. ->createQuery('SELECT i.iid FROM ChamiloCourseBundle:CLpItem i
  1740. WHERE i.lpId = :lp AND i.parentItemId = 0 AND i.itemType != :type ORDER BY i.displayOrder DESC')
  1741. ->setMaxResults(1)
  1742. ->setParameters(['lp' => $this->lp_id, 'type' => TOOL_LP_FINAL_ITEM])
  1743. ->getSingleScalarResult();
  1744. return $lastId;
  1745. } catch (Exception $exception) {
  1746. return 0;
  1747. }
  1748. }
  1749. /**
  1750. * Gets the navigation bar for the learnpath display screen.
  1751. *
  1752. * @param string $barId
  1753. *
  1754. * @return string The HTML string to use as a navigation bar
  1755. */
  1756. public function get_navigation_bar($barId = '')
  1757. {
  1758. if (empty($barId)) {
  1759. $barId = 'control-top';
  1760. }
  1761. $lpId = $this->lp_id;
  1762. $mycurrentitemid = $this->get_current_item_id();
  1763. $reportingText = get_lang('Reporting');
  1764. $previousText = get_lang('ScormPrevious');
  1765. $nextText = get_lang('ScormNext');
  1766. $fullScreenText = get_lang('ScormExitFullScreen');
  1767. $settings = api_get_configuration_value('lp_view_settings');
  1768. $display = isset($settings['display']) ? $settings['display'] : false;
  1769. $reportingIcon = '
  1770. <a class="icon-toolbar"
  1771. id="stats_link"
  1772. href="lp_controller.php?action=stats&'.api_get_cidreq(true).'&lp_id='.$lpId.'"
  1773. onclick="window.parent.API.save_asset(); return true;"
  1774. target="content_name" title="'.$reportingText.'">
  1775. <span class="fa fa-info"></span><span class="sr-only">'.$reportingText.'</span>
  1776. </a>';
  1777. if (!empty($display)) {
  1778. $showReporting = isset($display['show_reporting_icon']) ? $display['show_reporting_icon'] : true;
  1779. if ($showReporting === false) {
  1780. $reportingIcon = '';
  1781. }
  1782. }
  1783. $hideArrows = false;
  1784. if (isset($settings['display']) && isset($settings['display']['hide_lp_arrow_navigation'])) {
  1785. $hideArrows = $settings['display']['hide_lp_arrow_navigation'];
  1786. }
  1787. $previousIcon = '';
  1788. $nextIcon = '';
  1789. if ($hideArrows === false) {
  1790. $previousIcon = '
  1791. <a class="icon-toolbar" id="scorm-previous" href="#"
  1792. onclick="switch_item('.$mycurrentitemid.',\'previous\');return false;" title="'.$previousText.'">
  1793. <span class="fa fa-chevron-left"></span><span class="sr-only">'.$previousText.'</span>
  1794. </a>';
  1795. $nextIcon = '
  1796. <a class="icon-toolbar" id="scorm-next" href="#"
  1797. onclick="switch_item('.$mycurrentitemid.',\'next\');return false;" title="'.$nextText.'">
  1798. <span class="fa fa-chevron-right"></span><span class="sr-only">'.$nextText.'</span>
  1799. </a>';
  1800. }
  1801. if ($this->mode === 'fullscreen') {
  1802. $navbar = '
  1803. <span id="'.$barId.'" class="buttons">
  1804. '.$reportingIcon.'
  1805. '.$previousIcon.'
  1806. '.$nextIcon.'
  1807. <a class="icon-toolbar" id="view-embedded"
  1808. href="lp_controller.php?action=mode&mode=embedded" target="_top" title="'.$fullScreenText.'">
  1809. <span class="fa fa-columns"></span><span class="sr-only">'.$fullScreenText.'</span>
  1810. </a>
  1811. </span>';
  1812. } else {
  1813. $navbar = '
  1814. <span id="'.$barId.'" class="buttons text-right">
  1815. '.$reportingIcon.'
  1816. '.$previousIcon.'
  1817. '.$nextIcon.'
  1818. </span>';
  1819. }
  1820. return $navbar;
  1821. }
  1822. /**
  1823. * Gets the next resource in queue (url).
  1824. *
  1825. * @return string URL to load into the viewer
  1826. */
  1827. public function get_next_index()
  1828. {
  1829. // TODO
  1830. $index = $this->index;
  1831. $index++;
  1832. while (
  1833. !empty($this->ordered_items[$index]) && ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') &&
  1834. $index < $this->max_ordered_items
  1835. ) {
  1836. $index++;
  1837. if ($index == $this->max_ordered_items) {
  1838. if ($this->items[$this->ordered_items[$index]]->get_type() == 'dir') {
  1839. return $this->index;
  1840. }
  1841. return $index;
  1842. }
  1843. }
  1844. if (empty($this->ordered_items[$index])) {
  1845. return $this->index;
  1846. }
  1847. return $index;
  1848. }
  1849. /**
  1850. * Gets item_id for the next element.
  1851. *
  1852. * @return int Next item (DB) ID
  1853. */
  1854. public function get_next_item_id()
  1855. {
  1856. $new_index = $this->get_next_index();
  1857. if (!empty($new_index)) {
  1858. if (isset($this->ordered_items[$new_index])) {
  1859. return $this->ordered_items[$new_index];
  1860. }
  1861. }
  1862. return 0;
  1863. }
  1864. /**
  1865. * Returns the package type ('scorm','aicc','scorm2004','dokeos','ppt'...).
  1866. *
  1867. * Generally, the package provided is in the form of a zip file, so the function
  1868. * has been written to test a zip file. If not a zip, the function will return the
  1869. * default return value: ''
  1870. *
  1871. * @param string $file_path the path to the file
  1872. * @param string $file_name the original name of the file
  1873. *
  1874. * @return string 'scorm','aicc','scorm2004','dokeos' or '' if the package cannot be recognized
  1875. */
  1876. public static function get_package_type($file_path, $file_name)
  1877. {
  1878. // Get name of the zip file without the extension.
  1879. $file_info = pathinfo($file_name);
  1880. $extension = $file_info['extension']; // Extension only.
  1881. if (!empty($_POST['ppt2lp']) && !in_array(strtolower($extension), [
  1882. 'dll',
  1883. 'exe',
  1884. ])) {
  1885. return 'oogie';
  1886. }
  1887. if (!empty($_POST['woogie']) && !in_array(strtolower($extension), [
  1888. 'dll',
  1889. 'exe',
  1890. ])) {
  1891. return 'woogie';
  1892. }
  1893. $zipFile = new PclZip($file_path);
  1894. // Check the zip content (real size and file extension).
  1895. $zipContentArray = $zipFile->listContent();
  1896. $package_type = '';
  1897. $manifest = '';
  1898. $aicc_match_crs = 0;
  1899. $aicc_match_au = 0;
  1900. $aicc_match_des = 0;
  1901. $aicc_match_cst = 0;
  1902. // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
  1903. if (is_array($zipContentArray) && count($zipContentArray) > 0) {
  1904. foreach ($zipContentArray as $thisContent) {
  1905. if (preg_match('~.(php.*|phtml)$~i', $thisContent['filename'])) {
  1906. // New behaviour: Don't do anything. These files will be removed in scorm::import_package.
  1907. } elseif (stristr($thisContent['filename'], 'imsmanifest.xml') !== false) {
  1908. $manifest = $thisContent['filename']; // Just the relative directory inside scorm/
  1909. $package_type = 'scorm';
  1910. break; // Exit the foreach loop.
  1911. } elseif (
  1912. preg_match('/aicc\//i', $thisContent['filename']) ||
  1913. in_array(
  1914. strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION)),
  1915. ['crs', 'au', 'des', 'cst']
  1916. )
  1917. ) {
  1918. $ext = strtolower(pathinfo($thisContent['filename'], PATHINFO_EXTENSION));
  1919. switch ($ext) {
  1920. case 'crs':
  1921. $aicc_match_crs = 1;
  1922. break;
  1923. case 'au':
  1924. $aicc_match_au = 1;
  1925. break;
  1926. case 'des':
  1927. $aicc_match_des = 1;
  1928. break;
  1929. case 'cst':
  1930. $aicc_match_cst = 1;
  1931. break;
  1932. default:
  1933. break;
  1934. }
  1935. //break; // Don't exit the loop, because if we find an imsmanifest afterwards, we want it, not the AICC.
  1936. } else {
  1937. $package_type = '';
  1938. }
  1939. }
  1940. }
  1941. if (empty($package_type) && 4 == ($aicc_match_crs + $aicc_match_au + $aicc_match_des + $aicc_match_cst)) {
  1942. // If found an aicc directory... (!= false means it cannot be false (error) or 0 (no match)).
  1943. $package_type = 'aicc';
  1944. }
  1945. // Try with chamilo course builder
  1946. if (empty($package_type)) {
  1947. $package_type = 'chamilo';
  1948. }
  1949. return $package_type;
  1950. }
  1951. /**
  1952. * Gets the previous resource in queue (url). Also initialises time values for this viewing.
  1953. *
  1954. * @return string URL to load into the viewer
  1955. */
  1956. public function get_previous_index()
  1957. {
  1958. $index = $this->index;
  1959. if (isset($this->ordered_items[$index - 1])) {
  1960. $index--;
  1961. while (isset($this->ordered_items[$index]) &&
  1962. ($this->items[$this->ordered_items[$index]]->get_type() == 'dir')
  1963. ) {
  1964. $index--;
  1965. if ($index < 0) {
  1966. return $this->index;
  1967. }
  1968. }
  1969. }
  1970. return $index;
  1971. }
  1972. /**
  1973. * Gets item_id for the next element.
  1974. *
  1975. * @return int Previous item (DB) ID
  1976. */
  1977. public function get_previous_item_id()
  1978. {
  1979. $index = $this->get_previous_index();
  1980. return $this->ordered_items[$index];
  1981. }
  1982. /**
  1983. * Returns the HTML necessary to print a mediaplayer block inside a page.
  1984. *
  1985. * @param int $lpItemId
  1986. * @param string $autostart
  1987. *
  1988. * @return string The mediaplayer HTML
  1989. */
  1990. public function get_mediaplayer($lpItemId, $autostart = 'true')
  1991. {
  1992. $course_id = api_get_course_int_id();
  1993. $_course = api_get_course_info();
  1994. if (empty($_course)) {
  1995. return '';
  1996. }
  1997. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  1998. $tbl_lp_item_view = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  1999. $lpItemId = (int) $lpItemId;
  2000. /** @var learnpathItem $item */
  2001. $item = isset($this->items[$lpItemId]) ? $this->items[$lpItemId] : null;
  2002. $itemViewId = 0;
  2003. if ($item) {
  2004. $itemViewId = (int) $item->db_item_view_id;
  2005. }
  2006. // Getting all the information about the item.
  2007. $sql = "SELECT lpi.audio, lpi.item_type, lp_view.status
  2008. FROM $tbl_lp_item as lpi
  2009. INNER JOIN $tbl_lp_item_view as lp_view
  2010. ON (lpi.iid = lp_view.lp_item_id)
  2011. WHERE
  2012. lp_view.iid = $itemViewId AND
  2013. lpi.iid = $lpItemId AND
  2014. lp_view.c_id = $course_id";
  2015. $result = Database::query($sql);
  2016. $row = Database::fetch_assoc($result);
  2017. $output = '';
  2018. if (!empty($row['audio'])) {
  2019. $list = $_SESSION['oLP']->get_toc();
  2020. switch ($row['item_type']) {
  2021. case 'quiz':
  2022. $type_quiz = false;
  2023. foreach ($list as $toc) {
  2024. if ($toc['id'] == $_SESSION['oLP']->current) {
  2025. $type_quiz = true;
  2026. }
  2027. }
  2028. if ($type_quiz) {
  2029. if ($_SESSION['oLP']->prevent_reinit == 1) {
  2030. $autostart_audio = $row['status'] === 'completed' ? 'false' : 'true';
  2031. } else {
  2032. $autostart_audio = $autostart;
  2033. }
  2034. }
  2035. break;
  2036. case TOOL_READOUT_TEXT:;
  2037. $autostart_audio = 'false';
  2038. break;
  2039. default:
  2040. $autostart_audio = 'true';
  2041. }
  2042. $courseInfo = api_get_course_info();
  2043. $audio = $row['audio'];
  2044. $file = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio;
  2045. $url = api_get_path(WEB_COURSE_PATH).$courseInfo['path'].'/document/audio/'.$audio.'?'.api_get_cidreq();
  2046. if (!file_exists($file)) {
  2047. $lpPathInfo = $_SESSION['oLP']->generate_lp_folder(api_get_course_info());
  2048. $file = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio;
  2049. $url = api_get_path(WEB_COURSE_PATH).$_course['path'].'/document'.$lpPathInfo['dir'].$audio.'?'.api_get_cidreq();
  2050. }
  2051. $player = Display::getMediaPlayer(
  2052. $file,
  2053. [
  2054. 'id' => 'lp_audio_media_player',
  2055. 'url' => $url,
  2056. 'autoplay' => $autostart_audio,
  2057. 'width' => '100%',
  2058. ]
  2059. );
  2060. // The mp3 player.
  2061. $output = '<div id="container">';
  2062. $output .= $player;
  2063. $output .= '</div>';
  2064. }
  2065. return $output;
  2066. }
  2067. /**
  2068. * @param int $studentId
  2069. * @param int $prerequisite
  2070. * @param array $courseInfo
  2071. * @param int $sessionId
  2072. *
  2073. * @return bool
  2074. */
  2075. public static function isBlockedByPrerequisite(
  2076. $studentId,
  2077. $prerequisite,
  2078. $courseInfo,
  2079. $sessionId
  2080. ) {
  2081. if (empty($courseInfo)) {
  2082. return false;
  2083. }
  2084. $courseId = $courseInfo['real_id'];
  2085. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  2086. if ($allow) {
  2087. if (api_is_allowed_to_edit() ||
  2088. api_is_platform_admin(true) ||
  2089. api_is_drh() ||
  2090. api_is_coach($sessionId, $courseId, false)
  2091. ) {
  2092. return false;
  2093. }
  2094. }
  2095. $isBlocked = false;
  2096. if (!empty($prerequisite)) {
  2097. $progress = self::getProgress(
  2098. $prerequisite,
  2099. $studentId,
  2100. $courseId,
  2101. $sessionId
  2102. );
  2103. if ($progress < 100) {
  2104. $isBlocked = true;
  2105. }
  2106. if (Tracking::minimumTimeAvailable($sessionId, $courseId)) {
  2107. // Block if it does not exceed minimum time
  2108. // Minimum time (in minutes) to pass the learning path
  2109. $accumulateWorkTime = self::getAccumulateWorkTimePrerequisite($prerequisite, $courseId);
  2110. if ($accumulateWorkTime > 0) {
  2111. // Total time in course (sum of times in learning paths from course)
  2112. $accumulateWorkTimeTotal = self::getAccumulateWorkTimeTotal($courseId);
  2113. // Connect with the plugin_licences_course_session table
  2114. // which indicates what percentage of the time applies
  2115. // Minimum connection percentage
  2116. $perc = 100;
  2117. // Time from the course
  2118. $tc = $accumulateWorkTimeTotal;
  2119. // Percentage of the learning paths
  2120. $pl = $accumulateWorkTime / $accumulateWorkTimeTotal;
  2121. // Minimum time for each learning path
  2122. $accumulateWorkTime = ($pl * $tc * $perc / 100);
  2123. // Spent time (in seconds) so far in the learning path
  2124. $lpTimeList = Tracking::getCalculateTime($studentId, $courseId, $sessionId);
  2125. $lpTime = isset($lpTimeList[TOOL_LEARNPATH][$prerequisite]) ? $lpTimeList[TOOL_LEARNPATH][$prerequisite] : 0;
  2126. if ($lpTime < ($accumulateWorkTime * 60)) {
  2127. $isBlocked = true;
  2128. }
  2129. }
  2130. }
  2131. }
  2132. return $isBlocked;
  2133. }
  2134. /**
  2135. * Checks if the learning path is visible for student after the progress
  2136. * of its prerequisite is completed, considering the time availability and
  2137. * the LP visibility.
  2138. *
  2139. * @param int $lp_id
  2140. * @param int $student_id
  2141. * @param array $courseInfo
  2142. * @param int $sessionId
  2143. *
  2144. * @return bool
  2145. */
  2146. public static function is_lp_visible_for_student(
  2147. $lp_id,
  2148. $student_id,
  2149. $courseInfo = [],
  2150. $sessionId = 0
  2151. ) {
  2152. $courseInfo = empty($courseInfo) ? api_get_course_info() : $courseInfo;
  2153. $lp_id = (int) $lp_id;
  2154. $sessionId = (int) $sessionId;
  2155. if (empty($courseInfo)) {
  2156. return false;
  2157. }
  2158. if (empty($sessionId)) {
  2159. $sessionId = api_get_session_id();
  2160. }
  2161. $courseId = $courseInfo['real_id'];
  2162. $itemInfo = api_get_item_property_info(
  2163. $courseId,
  2164. TOOL_LEARNPATH,
  2165. $lp_id,
  2166. $sessionId
  2167. );
  2168. // If the item was deleted.
  2169. if (isset($itemInfo['visibility']) && $itemInfo['visibility'] == 2) {
  2170. return false;
  2171. }
  2172. // @todo remove this query and load the row info as a parameter
  2173. $table = Database::get_course_table(TABLE_LP_MAIN);
  2174. // Get current prerequisite
  2175. $sql = "SELECT id, prerequisite, subscribe_users, publicated_on, expired_on
  2176. FROM $table
  2177. WHERE iid = $lp_id";
  2178. $rs = Database::query($sql);
  2179. $now = time();
  2180. if (Database::num_rows($rs) > 0) {
  2181. $row = Database::fetch_array($rs, 'ASSOC');
  2182. $prerequisite = $row['prerequisite'];
  2183. $is_visible = true;
  2184. $isBlocked = self::isBlockedByPrerequisite(
  2185. $student_id,
  2186. $prerequisite,
  2187. $courseInfo,
  2188. $sessionId
  2189. );
  2190. if ($isBlocked) {
  2191. $is_visible = false;
  2192. }
  2193. // Also check the time availability of the LP
  2194. if ($is_visible) {
  2195. // Adding visibility restrictions
  2196. if (!empty($row['publicated_on'])) {
  2197. if ($now < api_strtotime($row['publicated_on'], 'UTC')) {
  2198. $is_visible = false;
  2199. }
  2200. }
  2201. // Blocking empty start times see BT#2800
  2202. global $_custom;
  2203. if (isset($_custom['lps_hidden_when_no_start_date']) &&
  2204. $_custom['lps_hidden_when_no_start_date']
  2205. ) {
  2206. if (empty($row['publicated_on'])) {
  2207. $is_visible = false;
  2208. }
  2209. }
  2210. if (!empty($row['expired_on'])) {
  2211. if ($now > api_strtotime($row['expired_on'], 'UTC')) {
  2212. $is_visible = false;
  2213. }
  2214. }
  2215. }
  2216. if ($is_visible) {
  2217. $subscriptionSettings = self::getSubscriptionSettings();
  2218. // Check if the subscription users/group to a LP is ON
  2219. if (isset($row['subscribe_users']) && $row['subscribe_users'] == 1 &&
  2220. $subscriptionSettings['allow_add_users_to_lp'] === true
  2221. ) {
  2222. // Try group
  2223. $is_visible = false;
  2224. // Checking only the user visibility
  2225. $userVisibility = api_get_item_visibility(
  2226. $courseInfo,
  2227. 'learnpath',
  2228. $row['id'],
  2229. $sessionId,
  2230. $student_id,
  2231. 'LearnpathSubscription'
  2232. );
  2233. if ($userVisibility == 1) {
  2234. $is_visible = true;
  2235. } else {
  2236. $userGroups = GroupManager::getAllGroupPerUserSubscription($student_id, $courseId);
  2237. if (!empty($userGroups)) {
  2238. foreach ($userGroups as $groupInfo) {
  2239. $groupId = $groupInfo['iid'];
  2240. $userVisibility = api_get_item_visibility(
  2241. $courseInfo,
  2242. 'learnpath',
  2243. $row['id'],
  2244. $sessionId,
  2245. null,
  2246. 'LearnpathSubscription',
  2247. $groupId
  2248. );
  2249. if ($userVisibility == 1) {
  2250. $is_visible = true;
  2251. break;
  2252. }
  2253. }
  2254. }
  2255. }
  2256. }
  2257. }
  2258. return $is_visible;
  2259. }
  2260. return false;
  2261. }
  2262. /**
  2263. * @param int $lpId
  2264. * @param int $userId
  2265. * @param int $courseId
  2266. * @param int $sessionId
  2267. *
  2268. * @return int
  2269. */
  2270. public static function getProgress($lpId, $userId, $courseId, $sessionId = 0)
  2271. {
  2272. $lpId = (int) $lpId;
  2273. $userId = (int) $userId;
  2274. $courseId = (int) $courseId;
  2275. $sessionId = (int) $sessionId;
  2276. $sessionCondition = api_get_session_condition($sessionId);
  2277. $table = Database::get_course_table(TABLE_LP_VIEW);
  2278. $sql = "SELECT progress FROM $table
  2279. WHERE
  2280. c_id = $courseId AND
  2281. lp_id = $lpId AND
  2282. user_id = $userId $sessionCondition ";
  2283. $res = Database::query($sql);
  2284. $progress = 0;
  2285. if (Database::num_rows($res) > 0) {
  2286. $row = Database::fetch_array($res);
  2287. $progress = (int) $row['progress'];
  2288. }
  2289. return $progress;
  2290. }
  2291. /**
  2292. * @param array $lpList
  2293. * @param int $userId
  2294. * @param int $courseId
  2295. * @param int $sessionId
  2296. *
  2297. * @return array
  2298. */
  2299. public static function getProgressFromLpList($lpList, $userId, $courseId, $sessionId = 0)
  2300. {
  2301. $lpList = array_map('intval', $lpList);
  2302. if (empty($lpList)) {
  2303. return [];
  2304. }
  2305. $lpList = implode("','", $lpList);
  2306. $userId = (int) $userId;
  2307. $courseId = (int) $courseId;
  2308. $sessionId = (int) $sessionId;
  2309. $sessionCondition = api_get_session_condition($sessionId);
  2310. $table = Database::get_course_table(TABLE_LP_VIEW);
  2311. $sql = "SELECT lp_id, progress FROM $table
  2312. WHERE
  2313. c_id = $courseId AND
  2314. lp_id IN ('".$lpList."') AND
  2315. user_id = $userId $sessionCondition ";
  2316. $res = Database::query($sql);
  2317. if (Database::num_rows($res) > 0) {
  2318. $list = [];
  2319. while ($row = Database::fetch_array($res)) {
  2320. $list[$row['lp_id']] = $row['progress'];
  2321. }
  2322. return $list;
  2323. }
  2324. return [];
  2325. }
  2326. /**
  2327. * Displays a progress bar
  2328. * completed so far.
  2329. *
  2330. * @param int $percentage Progress value to display
  2331. * @param string $text_add Text to display near the progress value
  2332. *
  2333. * @return string HTML string containing the progress bar
  2334. */
  2335. public static function get_progress_bar($percentage = -1, $text_add = '')
  2336. {
  2337. $text = $percentage.$text_add;
  2338. $output = '<div class="progress">
  2339. <div id="progress_bar_value"
  2340. class="progress-bar progress-bar-success" role="progressbar"
  2341. aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$text.';">
  2342. '.$text.'
  2343. </div>
  2344. </div>';
  2345. return $output;
  2346. }
  2347. /**
  2348. * @param string $mode can be '%' or 'abs'
  2349. * otherwise this value will be used $this->progress_bar_mode
  2350. *
  2351. * @return string
  2352. */
  2353. public function getProgressBar($mode = null)
  2354. {
  2355. list($percentage, $text_add) = $this->get_progress_bar_text($mode);
  2356. return self::get_progress_bar($percentage, $text_add);
  2357. }
  2358. /**
  2359. * Gets the progress bar info to display inside the progress bar.
  2360. * Also used by scorm_api.php.
  2361. *
  2362. * @param string $mode Mode of display (can be '%' or 'abs').abs means
  2363. * we display a number of completed elements per total elements
  2364. * @param int $add Additional steps to fake as completed
  2365. *
  2366. * @return array Percentage or number and symbol (% or /xx)
  2367. */
  2368. public function get_progress_bar_text($mode = '', $add = 0)
  2369. {
  2370. if (empty($mode)) {
  2371. $mode = $this->progress_bar_mode;
  2372. }
  2373. $total_items = $this->getTotalItemsCountWithoutDirs();
  2374. $completeItems = $this->get_complete_items_count();
  2375. if ($add != 0) {
  2376. $completeItems += $add;
  2377. }
  2378. $text = '';
  2379. if ($completeItems > $total_items) {
  2380. $completeItems = $total_items;
  2381. }
  2382. $percentage = 0;
  2383. if ($mode == '%') {
  2384. if ($total_items > 0) {
  2385. $percentage = ((float) $completeItems / (float) $total_items) * 100;
  2386. }
  2387. $percentage = number_format($percentage, 0);
  2388. $text = '%';
  2389. } elseif ($mode === 'abs') {
  2390. $percentage = $completeItems;
  2391. $text = '/'.$total_items;
  2392. }
  2393. return [
  2394. $percentage,
  2395. $text,
  2396. ];
  2397. }
  2398. /**
  2399. * Gets the progress bar mode.
  2400. *
  2401. * @return string The progress bar mode attribute
  2402. */
  2403. public function get_progress_bar_mode()
  2404. {
  2405. if (!empty($this->progress_bar_mode)) {
  2406. return $this->progress_bar_mode;
  2407. }
  2408. return '%';
  2409. }
  2410. /**
  2411. * Gets the learnpath theme (remote or local).
  2412. *
  2413. * @return string Learnpath theme
  2414. */
  2415. public function get_theme()
  2416. {
  2417. if (!empty($this->theme)) {
  2418. return $this->theme;
  2419. }
  2420. return '';
  2421. }
  2422. /**
  2423. * Gets the learnpath session id.
  2424. *
  2425. * @return int
  2426. */
  2427. public function get_lp_session_id()
  2428. {
  2429. if (!empty($this->lp_session_id)) {
  2430. return (int) $this->lp_session_id;
  2431. }
  2432. return 0;
  2433. }
  2434. /**
  2435. * Gets the learnpath image.
  2436. *
  2437. * @return string Web URL of the LP image
  2438. */
  2439. public function get_preview_image()
  2440. {
  2441. if (!empty($this->preview_image)) {
  2442. return $this->preview_image;
  2443. }
  2444. return '';
  2445. }
  2446. /**
  2447. * @param string $size
  2448. * @param string $path_type
  2449. *
  2450. * @return bool|string
  2451. */
  2452. public function get_preview_image_path($size = null, $path_type = 'web')
  2453. {
  2454. $preview_image = $this->get_preview_image();
  2455. if (isset($preview_image) && !empty($preview_image)) {
  2456. $image_sys_path = api_get_path(SYS_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2457. $image_path = api_get_path(WEB_COURSE_PATH).$this->course_info['path'].'/upload/learning_path/images/';
  2458. if (isset($size)) {
  2459. $info = pathinfo($preview_image);
  2460. $image_custom_size = $info['filename'].'.'.$size.'.'.$info['extension'];
  2461. if (file_exists($image_sys_path.$image_custom_size)) {
  2462. if ($path_type == 'web') {
  2463. return $image_path.$image_custom_size;
  2464. } else {
  2465. return $image_sys_path.$image_custom_size;
  2466. }
  2467. }
  2468. } else {
  2469. if ($path_type == 'web') {
  2470. return $image_path.$preview_image;
  2471. } else {
  2472. return $image_sys_path.$preview_image;
  2473. }
  2474. }
  2475. }
  2476. return false;
  2477. }
  2478. /**
  2479. * Gets the learnpath author.
  2480. *
  2481. * @return string LP's author
  2482. */
  2483. public function get_author()
  2484. {
  2485. if (!empty($this->author)) {
  2486. return $this->author;
  2487. }
  2488. return '';
  2489. }
  2490. /**
  2491. * Gets hide table of contents.
  2492. *
  2493. * @return int
  2494. */
  2495. public function getHideTableOfContents()
  2496. {
  2497. return (int) $this->hide_toc_frame;
  2498. }
  2499. /**
  2500. * Generate a new prerequisites string for a given item. If this item was a sco and
  2501. * its prerequisites were strings (instead of IDs), then transform those strings into
  2502. * IDs, knowing that SCORM IDs are kept in the "ref" field of the lp_item table.
  2503. * Prefix all item IDs that end-up in the prerequisites string by "ITEM_" to use the
  2504. * same rule as the scormExport() method.
  2505. *
  2506. * @param int $item_id Item ID
  2507. *
  2508. * @return string Prerequisites string ready for the export as SCORM
  2509. */
  2510. public function get_scorm_prereq_string($item_id)
  2511. {
  2512. if ($this->debug > 0) {
  2513. error_log('In learnpath::get_scorm_prereq_string()');
  2514. }
  2515. if (!is_object($this->items[$item_id])) {
  2516. return false;
  2517. }
  2518. /** @var learnpathItem $oItem */
  2519. $oItem = $this->items[$item_id];
  2520. $prereq = $oItem->get_prereq_string();
  2521. if (empty($prereq)) {
  2522. return '';
  2523. }
  2524. if (preg_match('/^\d+$/', $prereq) &&
  2525. isset($this->items[$prereq]) &&
  2526. is_object($this->items[$prereq])
  2527. ) {
  2528. // If the prerequisite is a simple integer ID and this ID exists as an item ID,
  2529. // then simply return it (with the ITEM_ prefix).
  2530. //return 'ITEM_' . $prereq;
  2531. return $this->items[$prereq]->ref;
  2532. } else {
  2533. if (isset($this->refs_list[$prereq])) {
  2534. // It's a simple string item from which the ID can be found in the refs list,
  2535. // so we can transform it directly to an ID for export.
  2536. return $this->items[$this->refs_list[$prereq]]->ref;
  2537. } elseif (isset($this->refs_list['ITEM_'.$prereq])) {
  2538. return $this->items[$this->refs_list['ITEM_'.$prereq]]->ref;
  2539. } else {
  2540. // The last case, if it's a complex form, then find all the IDs (SCORM strings)
  2541. // and replace them, one by one, by the internal IDs (chamilo db)
  2542. // TODO: Modify the '*' replacement to replace the multiplier in front of it
  2543. // by a space as well.
  2544. $find = [
  2545. '&',
  2546. '|',
  2547. '~',
  2548. '=',
  2549. '<>',
  2550. '{',
  2551. '}',
  2552. '*',
  2553. '(',
  2554. ')',
  2555. ];
  2556. $replace = [
  2557. ' ',
  2558. ' ',
  2559. ' ',
  2560. ' ',
  2561. ' ',
  2562. ' ',
  2563. ' ',
  2564. ' ',
  2565. ' ',
  2566. ' ',
  2567. ];
  2568. $prereq_mod = str_replace($find, $replace, $prereq);
  2569. $ids = explode(' ', $prereq_mod);
  2570. foreach ($ids as $id) {
  2571. $id = trim($id);
  2572. if (isset($this->refs_list[$id])) {
  2573. $prereq = preg_replace(
  2574. '/[^a-zA-Z_0-9]('.$id.')[^a-zA-Z_0-9]/',
  2575. 'ITEM_'.$this->refs_list[$id],
  2576. $prereq
  2577. );
  2578. }
  2579. }
  2580. return $prereq;
  2581. }
  2582. }
  2583. }
  2584. /**
  2585. * Returns the XML DOM document's node.
  2586. *
  2587. * @param resource $children Reference to a list of objects to search for the given ITEM_*
  2588. * @param string $id The identifier to look for
  2589. *
  2590. * @return mixed The reference to the element found with that identifier. False if not found
  2591. */
  2592. public function get_scorm_xml_node(&$children, $id)
  2593. {
  2594. for ($i = 0; $i < $children->length; $i++) {
  2595. $item_temp = $children->item($i);
  2596. if ($item_temp->nodeName == 'item') {
  2597. if ($item_temp->getAttribute('identifier') == $id) {
  2598. return $item_temp;
  2599. }
  2600. }
  2601. $subchildren = $item_temp->childNodes;
  2602. if ($subchildren && $subchildren->length > 0) {
  2603. $val = $this->get_scorm_xml_node($subchildren, $id);
  2604. if (is_object($val)) {
  2605. return $val;
  2606. }
  2607. }
  2608. }
  2609. return false;
  2610. }
  2611. /**
  2612. * Gets the status list for all LP's items.
  2613. *
  2614. * @return array Array of [index] => [item ID => current status]
  2615. */
  2616. public function get_items_status_list()
  2617. {
  2618. $list = [];
  2619. foreach ($this->ordered_items as $item_id) {
  2620. $list[] = [
  2621. $item_id => $this->items[$item_id]->get_status(),
  2622. ];
  2623. }
  2624. return $list;
  2625. }
  2626. /**
  2627. * Return the number of interactions for the given learnpath Item View ID.
  2628. * This method can be used as static.
  2629. *
  2630. * @param int $lp_iv_id Item View ID
  2631. * @param int $course_id course id
  2632. *
  2633. * @return int
  2634. */
  2635. public static function get_interactions_count_from_db($lp_iv_id, $course_id)
  2636. {
  2637. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2638. $lp_iv_id = (int) $lp_iv_id;
  2639. $course_id = (int) $course_id;
  2640. $sql = "SELECT count(*) FROM $table
  2641. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2642. $res = Database::query($sql);
  2643. $num = 0;
  2644. if (Database::num_rows($res)) {
  2645. $row = Database::fetch_array($res);
  2646. $num = $row[0];
  2647. }
  2648. return $num;
  2649. }
  2650. /**
  2651. * Return the interactions as an array for the given lp_iv_id.
  2652. * This method can be used as static.
  2653. *
  2654. * @param int $lp_iv_id Learnpath Item View ID
  2655. *
  2656. * @return array
  2657. *
  2658. * @todo Transcode labels instead of switching to HTML (which requires to know the encoding of the LP)
  2659. */
  2660. public static function get_iv_interactions_array($lp_iv_id, $course_id = 0)
  2661. {
  2662. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2663. $list = [];
  2664. $table = Database::get_course_table(TABLE_LP_IV_INTERACTION);
  2665. $lp_iv_id = (int) $lp_iv_id;
  2666. if (empty($lp_iv_id) || empty($course_id)) {
  2667. return [];
  2668. }
  2669. $sql = "SELECT * FROM $table
  2670. WHERE c_id = ".$course_id." AND lp_iv_id = $lp_iv_id
  2671. ORDER BY order_id ASC";
  2672. $res = Database::query($sql);
  2673. $num = Database::num_rows($res);
  2674. if ($num > 0) {
  2675. $list[] = [
  2676. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2677. 'id' => api_htmlentities(get_lang('InteractionID'), ENT_QUOTES),
  2678. 'type' => api_htmlentities(get_lang('Type'), ENT_QUOTES),
  2679. 'time' => api_htmlentities(get_lang('TimeFinished'), ENT_QUOTES),
  2680. 'correct_responses' => api_htmlentities(get_lang('CorrectAnswers'), ENT_QUOTES),
  2681. 'student_response' => api_htmlentities(get_lang('StudentResponse'), ENT_QUOTES),
  2682. 'result' => api_htmlentities(get_lang('Result'), ENT_QUOTES),
  2683. 'latency' => api_htmlentities(get_lang('LatencyTimeSpent'), ENT_QUOTES),
  2684. 'student_response_formatted' => '',
  2685. ];
  2686. while ($row = Database::fetch_array($res)) {
  2687. $studentResponseFormatted = urldecode($row['student_response']);
  2688. $content_student_response = explode('__|', $studentResponseFormatted);
  2689. if (count($content_student_response) > 0) {
  2690. if (count($content_student_response) >= 3) {
  2691. // Pop the element off the end of array.
  2692. array_pop($content_student_response);
  2693. }
  2694. $studentResponseFormatted = implode(',', $content_student_response);
  2695. }
  2696. $list[] = [
  2697. 'order_id' => $row['order_id'] + 1,
  2698. 'id' => urldecode($row['interaction_id']), //urldecode because they often have %2F or stuff like that
  2699. 'type' => $row['interaction_type'],
  2700. 'time' => $row['completion_time'],
  2701. 'correct_responses' => '', // Hide correct responses from students.
  2702. 'student_response' => $row['student_response'],
  2703. 'result' => $row['result'],
  2704. 'latency' => $row['latency'],
  2705. 'student_response_formatted' => $studentResponseFormatted,
  2706. ];
  2707. }
  2708. }
  2709. return $list;
  2710. }
  2711. /**
  2712. * Return the number of objectives for the given learnpath Item View ID.
  2713. * This method can be used as static.
  2714. *
  2715. * @param int $lp_iv_id Item View ID
  2716. * @param int $course_id Course ID
  2717. *
  2718. * @return int Number of objectives
  2719. */
  2720. public static function get_objectives_count_from_db($lp_iv_id, $course_id)
  2721. {
  2722. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2723. $course_id = (int) $course_id;
  2724. $lp_iv_id = (int) $lp_iv_id;
  2725. $sql = "SELECT count(*) FROM $table
  2726. WHERE c_id = $course_id AND lp_iv_id = $lp_iv_id";
  2727. //@todo seems that this always returns 0
  2728. $res = Database::query($sql);
  2729. $num = 0;
  2730. if (Database::num_rows($res)) {
  2731. $row = Database::fetch_array($res);
  2732. $num = $row[0];
  2733. }
  2734. return $num;
  2735. }
  2736. /**
  2737. * Return the objectives as an array for the given lp_iv_id.
  2738. * This method can be used as static.
  2739. *
  2740. * @param int $lpItemViewId Learnpath Item View ID
  2741. * @param int $course_id
  2742. *
  2743. * @return array
  2744. *
  2745. * @todo Translate labels
  2746. */
  2747. public static function get_iv_objectives_array($lpItemViewId = 0, $course_id = 0)
  2748. {
  2749. $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
  2750. $lpItemViewId = (int) $lpItemViewId;
  2751. if (empty($course_id) || empty($lpItemViewId)) {
  2752. return [];
  2753. }
  2754. $table = Database::get_course_table(TABLE_LP_IV_OBJECTIVE);
  2755. $sql = "SELECT * FROM $table
  2756. WHERE c_id = $course_id AND lp_iv_id = $lpItemViewId
  2757. ORDER BY order_id ASC";
  2758. $res = Database::query($sql);
  2759. $num = Database::num_rows($res);
  2760. $list = [];
  2761. if ($num > 0) {
  2762. $list[] = [
  2763. 'order_id' => api_htmlentities(get_lang('Order'), ENT_QUOTES),
  2764. 'objective_id' => api_htmlentities(get_lang('ObjectiveID'), ENT_QUOTES),
  2765. 'score_raw' => api_htmlentities(get_lang('ObjectiveRawScore'), ENT_QUOTES),
  2766. 'score_max' => api_htmlentities(get_lang('ObjectiveMaxScore'), ENT_QUOTES),
  2767. 'score_min' => api_htmlentities(get_lang('ObjectiveMinScore'), ENT_QUOTES),
  2768. 'status' => api_htmlentities(get_lang('ObjectiveStatus'), ENT_QUOTES),
  2769. ];
  2770. while ($row = Database::fetch_array($res)) {
  2771. $list[] = [
  2772. 'order_id' => $row['order_id'] + 1,
  2773. 'objective_id' => urldecode($row['objective_id']), // urldecode() because they often have %2F
  2774. 'score_raw' => $row['score_raw'],
  2775. 'score_max' => $row['score_max'],
  2776. 'score_min' => $row['score_min'],
  2777. 'status' => $row['status'],
  2778. ];
  2779. }
  2780. }
  2781. return $list;
  2782. }
  2783. /**
  2784. * Generate and return the table of contents for this learnpath. The (flat) table returned can be
  2785. * used by get_html_toc() to be ready to display.
  2786. *
  2787. * @return array TOC as a table with 4 elements per row: title, link, status and level
  2788. */
  2789. public function get_toc()
  2790. {
  2791. $toc = [];
  2792. foreach ($this->ordered_items as $item_id) {
  2793. // TODO: Change this link generation and use new function instead.
  2794. $toc[] = [
  2795. 'id' => $item_id,
  2796. 'title' => $this->items[$item_id]->get_title(),
  2797. 'status' => $this->items[$item_id]->get_status(),
  2798. 'level' => $this->items[$item_id]->get_level(),
  2799. 'type' => $this->items[$item_id]->get_type(),
  2800. 'description' => $this->items[$item_id]->get_description(),
  2801. 'path' => $this->items[$item_id]->get_path(),
  2802. 'parent' => $this->items[$item_id]->get_parent(),
  2803. ];
  2804. }
  2805. return $toc;
  2806. }
  2807. /**
  2808. * Generate and return the table of contents for this learnpath. The JS
  2809. * table returned is used inside of scorm_api.php.
  2810. *
  2811. * @param string $varname
  2812. *
  2813. * @return string A JS array variable construction
  2814. */
  2815. public function get_items_details_as_js($varname = 'olms.lms_item_types')
  2816. {
  2817. $toc = $varname.' = new Array();';
  2818. foreach ($this->ordered_items as $item_id) {
  2819. $toc .= $varname."['i$item_id'] = '".$this->items[$item_id]->get_type()."';";
  2820. }
  2821. return $toc;
  2822. }
  2823. /**
  2824. * Gets the learning path type.
  2825. *
  2826. * @param bool $get_name Return the name? If false, return the ID. Default is false.
  2827. *
  2828. * @return mixed Type ID or name, depending on the parameter
  2829. */
  2830. public function get_type($get_name = false)
  2831. {
  2832. $res = false;
  2833. if (!empty($this->type) && (!$get_name)) {
  2834. $res = $this->type;
  2835. }
  2836. return $res;
  2837. }
  2838. /**
  2839. * Gets the learning path type as static method.
  2840. *
  2841. * @param int $lp_id
  2842. *
  2843. * @return mixed Type ID or name, depending on the parameter
  2844. */
  2845. public static function get_type_static($lp_id = 0)
  2846. {
  2847. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  2848. $lp_id = (int) $lp_id;
  2849. $sql = "SELECT lp_type FROM $tbl_lp
  2850. WHERE iid = $lp_id";
  2851. $res = Database::query($sql);
  2852. if ($res === false) {
  2853. return null;
  2854. }
  2855. if (Database::num_rows($res) <= 0) {
  2856. return null;
  2857. }
  2858. $row = Database::fetch_array($res);
  2859. return $row['lp_type'];
  2860. }
  2861. /**
  2862. * Gets a flat list of item IDs ordered for display (level by level ordered by order_display)
  2863. * This method can be used as abstract and is recursive.
  2864. *
  2865. * @param int $lp Learnpath ID
  2866. * @param int $parent Parent ID of the items to look for
  2867. * @param int $course_id
  2868. *
  2869. * @return array Ordered list of item IDs (empty array on error)
  2870. */
  2871. public static function get_flat_ordered_items_list($lp = 1, $parent = 0, $course_id = 0)
  2872. {
  2873. if (empty($course_id)) {
  2874. $course_id = api_get_course_int_id();
  2875. } else {
  2876. $course_id = (int) $course_id;
  2877. }
  2878. $list = [];
  2879. if (empty($lp)) {
  2880. return $list;
  2881. }
  2882. $lp = (int) $lp;
  2883. $parent = (int) $parent;
  2884. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  2885. $sql = "SELECT iid FROM $tbl_lp_item
  2886. WHERE c_id = $course_id AND lp_id = $lp AND parent_item_id = $parent
  2887. ORDER BY display_order";
  2888. $res = Database::query($sql);
  2889. while ($row = Database::fetch_array($res)) {
  2890. $sublist = self::get_flat_ordered_items_list(
  2891. $lp,
  2892. $row['iid'],
  2893. $course_id
  2894. );
  2895. $list[] = $row['iid'];
  2896. foreach ($sublist as $item) {
  2897. $list[] = $item;
  2898. }
  2899. }
  2900. return $list;
  2901. }
  2902. /**
  2903. * @return array
  2904. */
  2905. public static function getChapterTypes()
  2906. {
  2907. return [
  2908. 'dir',
  2909. ];
  2910. }
  2911. /**
  2912. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2913. *
  2914. * @param $tree
  2915. *
  2916. * @return array HTML TOC ready to display
  2917. */
  2918. public function getParentToc($tree)
  2919. {
  2920. if (empty($tree)) {
  2921. $tree = $this->get_toc();
  2922. }
  2923. $dirTypes = self::getChapterTypes();
  2924. $myCurrentId = $this->get_current_item_id();
  2925. $listParent = [];
  2926. $listChildren = [];
  2927. $listNotParent = [];
  2928. $list = [];
  2929. foreach ($tree as $subtree) {
  2930. if (in_array($subtree['type'], $dirTypes)) {
  2931. $listChildren = $this->getChildrenToc($tree, $subtree['id']);
  2932. $subtree['children'] = $listChildren;
  2933. if (!empty($subtree['children'])) {
  2934. foreach ($subtree['children'] as $subItem) {
  2935. if ($subItem['id'] == $this->current) {
  2936. $subtree['parent_current'] = 'in';
  2937. $subtree['current'] = 'on';
  2938. }
  2939. }
  2940. }
  2941. $listParent[] = $subtree;
  2942. }
  2943. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == null) {
  2944. $classStatus = [
  2945. 'not attempted' => 'scorm_not_attempted',
  2946. 'incomplete' => 'scorm_not_attempted',
  2947. 'failed' => 'scorm_failed',
  2948. 'completed' => 'scorm_completed',
  2949. 'passed' => 'scorm_completed',
  2950. 'succeeded' => 'scorm_completed',
  2951. 'browsed' => 'scorm_completed',
  2952. ];
  2953. if (isset($classStatus[$subtree['status']])) {
  2954. $cssStatus = $classStatus[$subtree['status']];
  2955. }
  2956. $title = Security::remove_XSS($subtree['title']);
  2957. unset($subtree['title']);
  2958. if (empty($title)) {
  2959. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  2960. }
  2961. $classStyle = null;
  2962. if ($subtree['id'] == $this->current) {
  2963. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  2964. } elseif (!in_array($subtree['type'], $dirTypes)) {
  2965. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  2966. }
  2967. $subtree['title'] = $title;
  2968. $subtree['class'] = $classStyle.' '.$cssStatus;
  2969. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  2970. $subtree['current_id'] = $myCurrentId;
  2971. $listNotParent[] = $subtree;
  2972. }
  2973. }
  2974. $list['are_parents'] = $listParent;
  2975. $list['not_parents'] = $listNotParent;
  2976. return $list;
  2977. }
  2978. /**
  2979. * Uses the table generated by get_toc() and returns an HTML-formattedstring ready to display.
  2980. *
  2981. * @param array $tree
  2982. * @param int $id
  2983. * @param bool $parent
  2984. *
  2985. * @return array HTML TOC ready to display
  2986. */
  2987. public function getChildrenToc($tree, $id, $parent = true)
  2988. {
  2989. if (empty($tree)) {
  2990. $tree = $this->get_toc();
  2991. }
  2992. $dirTypes = self::getChapterTypes();
  2993. $currentItemId = $this->get_current_item_id();
  2994. $list = [];
  2995. $classStatus = [
  2996. 'not attempted' => 'scorm_not_attempted',
  2997. 'incomplete' => 'scorm_not_attempted',
  2998. 'failed' => 'scorm_failed',
  2999. 'completed' => 'scorm_completed',
  3000. 'passed' => 'scorm_completed',
  3001. 'succeeded' => 'scorm_completed',
  3002. 'browsed' => 'scorm_completed',
  3003. ];
  3004. foreach ($tree as $subtree) {
  3005. $subtree['tree'] = null;
  3006. if (!in_array($subtree['type'], $dirTypes) && $subtree['parent'] == $id) {
  3007. if ($subtree['id'] == $this->current) {
  3008. $subtree['current'] = 'active';
  3009. } else {
  3010. $subtree['current'] = null;
  3011. }
  3012. if (isset($classStatus[$subtree['status']])) {
  3013. $cssStatus = $classStatus[$subtree['status']];
  3014. }
  3015. $title = Security::remove_XSS($subtree['title']);
  3016. unset($subtree['title']);
  3017. if (empty($title)) {
  3018. $title = self::rl_get_resource_name(api_get_course_id(), $this->get_id(), $subtree['id']);
  3019. }
  3020. $classStyle = null;
  3021. if ($subtree['id'] == $this->current) {
  3022. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3023. } elseif (!in_array($subtree['type'], $dirTypes)) {
  3024. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3025. }
  3026. if (in_array($subtree['type'], $dirTypes)) {
  3027. $subtree['title'] = stripslashes($title);
  3028. } else {
  3029. $subtree['title'] = $title;
  3030. $subtree['class'] = $classStyle.' '.$cssStatus;
  3031. $subtree['url'] = $this->get_link('http', $subtree['id'], $tree);
  3032. $subtree['current_id'] = $currentItemId;
  3033. }
  3034. $list[] = $subtree;
  3035. }
  3036. }
  3037. return $list;
  3038. }
  3039. /**
  3040. * Uses the table generated by get_toc() and returns an HTML-formatted string ready to display.
  3041. *
  3042. * @param array $toc_list
  3043. *
  3044. * @return array HTML TOC ready to display
  3045. */
  3046. public function getListArrayToc($toc_list = [])
  3047. {
  3048. if (empty($toc_list)) {
  3049. $toc_list = $this->get_toc();
  3050. }
  3051. // Temporary variables.
  3052. $currentItemId = $this->get_current_item_id();
  3053. $list = [];
  3054. $arrayList = [];
  3055. $classStatus = [
  3056. 'not attempted' => 'scorm_not_attempted',
  3057. 'incomplete' => 'scorm_not_attempted',
  3058. 'failed' => 'scorm_failed',
  3059. 'completed' => 'scorm_completed',
  3060. 'passed' => 'scorm_completed',
  3061. 'succeeded' => 'scorm_completed',
  3062. 'browsed' => 'scorm_completed',
  3063. ];
  3064. foreach ($toc_list as $item) {
  3065. $list['id'] = $item['id'];
  3066. $list['status'] = $item['status'];
  3067. $cssStatus = null;
  3068. if (isset($classStatus[$item['status']])) {
  3069. $cssStatus = $classStatus[$item['status']];
  3070. }
  3071. $classStyle = ' ';
  3072. $dirTypes = self::getChapterTypes();
  3073. if (in_array($item['type'], $dirTypes)) {
  3074. $classStyle = 'scorm_item_section ';
  3075. }
  3076. if ($item['id'] == $this->current) {
  3077. $classStyle = 'scorm_item_normal '.$classStyle.'scorm_highlight';
  3078. } elseif (!in_array($item['type'], $dirTypes)) {
  3079. $classStyle = 'scorm_item_normal '.$classStyle.' ';
  3080. }
  3081. $title = $item['title'];
  3082. if (empty($title)) {
  3083. $title = self::rl_get_resource_name(
  3084. api_get_course_id(),
  3085. $this->get_id(),
  3086. $item['id']
  3087. );
  3088. }
  3089. $title = Security::remove_XSS($item['title']);
  3090. if (empty($item['description'])) {
  3091. $list['description'] = $title;
  3092. } else {
  3093. $list['description'] = $item['description'];
  3094. }
  3095. $list['class'] = $classStyle.' '.$cssStatus;
  3096. $list['level'] = $item['level'];
  3097. $list['type'] = $item['type'];
  3098. if (in_array($item['type'], $dirTypes)) {
  3099. $list['css_level'] = 'level_'.$item['level'];
  3100. } else {
  3101. $list['css_level'] = 'level_'.$item['level'].' scorm_type_'.self::format_scorm_type_item($item['type']);
  3102. }
  3103. if (in_array($item['type'], $dirTypes)) {
  3104. $list['title'] = stripslashes($title);
  3105. } else {
  3106. $list['title'] = stripslashes($title);
  3107. $list['url'] = $this->get_link('http', $item['id'], $toc_list);
  3108. $list['current_id'] = $currentItemId;
  3109. }
  3110. $arrayList[] = $list;
  3111. }
  3112. return $arrayList;
  3113. }
  3114. /**
  3115. * Returns an HTML-formatted string ready to display with teacher buttons
  3116. * in LP view menu.
  3117. *
  3118. * @return string HTML TOC ready to display
  3119. */
  3120. public function get_teacher_toc_buttons()
  3121. {
  3122. $isAllow = api_is_allowed_to_edit(null, true, false, false);
  3123. $hideIcons = api_get_configuration_value('hide_teacher_icons_lp');
  3124. $html = '';
  3125. if ($isAllow && $hideIcons == false) {
  3126. if ($this->get_lp_session_id() == api_get_session_id()) {
  3127. $html .= '<div id="actions_lp" class="actions_lp"><hr>';
  3128. $html .= '<div class="btn-group">';
  3129. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=build&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3130. Display::returnFontAwesomeIcon('street-view').get_lang('Overview')."</a>";
  3131. $html .= "<a class='btn btn-sm btn-default' href='lp_controller.php?".api_get_cidreq()."&action=add_item&type=step&lp_id=".$this->lp_id."&isStudentView=false' target='_parent'>".
  3132. Display::returnFontAwesomeIcon('pencil').get_lang('Edit')."</a>";
  3133. $html .= '<a class="btn btn-sm btn-default" href="lp_controller.php?'.api_get_cidreq()."&action=edit&lp_id=".$this->lp_id.'&isStudentView=false">'.
  3134. Display::returnFontAwesomeIcon('cog').get_lang('Settings').'</a>';
  3135. $html .= '</div>';
  3136. $html .= '</div>';
  3137. }
  3138. }
  3139. return $html;
  3140. }
  3141. /**
  3142. * Gets the learnpath maker name - generally the editor's name.
  3143. *
  3144. * @return string Learnpath maker name
  3145. */
  3146. public function get_maker()
  3147. {
  3148. if (!empty($this->maker)) {
  3149. return $this->maker;
  3150. }
  3151. return '';
  3152. }
  3153. /**
  3154. * Gets the learnpath name/title.
  3155. *
  3156. * @return string Learnpath name/title
  3157. */
  3158. public function get_name()
  3159. {
  3160. if (!empty($this->name)) {
  3161. return $this->name;
  3162. }
  3163. return 'N/A';
  3164. }
  3165. /**
  3166. * @return string
  3167. */
  3168. public function getNameNoTags()
  3169. {
  3170. return strip_tags($this->get_name());
  3171. }
  3172. /**
  3173. * Gets a link to the resource from the present location, depending on item ID.
  3174. *
  3175. * @param string $type Type of link expected
  3176. * @param int $item_id Learnpath item ID
  3177. * @param bool $provided_toc
  3178. *
  3179. * @return string $provided_toc Link to the lp_item resource
  3180. */
  3181. public function get_link($type = 'http', $item_id = 0, $provided_toc = false)
  3182. {
  3183. $course_id = $this->get_course_int_id();
  3184. $item_id = (int) $item_id;
  3185. if (empty($item_id)) {
  3186. $item_id = $this->get_current_item_id();
  3187. if (empty($item_id)) {
  3188. //still empty, this means there was no item_id given and we are not in an object context or
  3189. //the object property is empty, return empty link
  3190. $this->first();
  3191. return '';
  3192. }
  3193. }
  3194. $file = '';
  3195. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3196. $lp_item_table = Database::get_course_table(TABLE_LP_ITEM);
  3197. $lp_item_view_table = Database::get_course_table(TABLE_LP_ITEM_VIEW);
  3198. $sql = "SELECT
  3199. l.lp_type as ltype,
  3200. l.path as lpath,
  3201. li.item_type as litype,
  3202. li.path as lipath,
  3203. li.parameters as liparams
  3204. FROM $lp_table l
  3205. INNER JOIN $lp_item_table li
  3206. ON (li.lp_id = l.iid)
  3207. WHERE
  3208. li.iid = $item_id
  3209. ";
  3210. $res = Database::query($sql);
  3211. if (Database::num_rows($res) > 0) {
  3212. $row = Database::fetch_array($res);
  3213. $lp_type = $row['ltype'];
  3214. $lp_path = $row['lpath'];
  3215. $lp_item_type = $row['litype'];
  3216. $lp_item_path = $row['lipath'];
  3217. $lp_item_params = $row['liparams'];
  3218. if (empty($lp_item_params) && strpos($lp_item_path, '?') !== false) {
  3219. list($lp_item_path, $lp_item_params) = explode('?', $lp_item_path);
  3220. }
  3221. $sys_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  3222. if ($type === 'http') {
  3223. //web path
  3224. $course_path = api_get_path(WEB_COURSE_PATH).api_get_course_path();
  3225. } else {
  3226. $course_path = $sys_course_path; //system path
  3227. }
  3228. // Fixed issue BT#1272 - If the item type is a Chamilo Item (quiz, link, etc),
  3229. // then change the lp type to thread it as a normal Chamilo LP not a SCO.
  3230. if (in_array(
  3231. $lp_item_type,
  3232. ['quiz', 'document', 'final_item', 'link', 'forum', 'thread', 'student_publication']
  3233. )
  3234. ) {
  3235. $lp_type = 1;
  3236. }
  3237. // Now go through the specific cases to get the end of the path
  3238. // @todo Use constants instead of int values.
  3239. switch ($lp_type) {
  3240. case 1:
  3241. $file = self::rl_get_resource_link_for_learnpath(
  3242. $course_id,
  3243. $this->get_id(),
  3244. $item_id,
  3245. $this->get_view_id()
  3246. );
  3247. switch ($lp_item_type) {
  3248. case 'document':
  3249. // Shows a button to download the file instead of just downloading the file directly.
  3250. $documentPathInfo = pathinfo($file);
  3251. if (isset($documentPathInfo['extension'])) {
  3252. $parsed = parse_url($documentPathInfo['extension']);
  3253. if (isset($parsed['path'])) {
  3254. $extension = $parsed['path'];
  3255. $extensionsToDownload = [
  3256. 'zip',
  3257. 'ppt',
  3258. 'pptx',
  3259. 'ods',
  3260. 'xlsx',
  3261. 'xls',
  3262. 'csv',
  3263. 'doc',
  3264. 'docx',
  3265. 'dot',
  3266. ];
  3267. if (in_array($extension, $extensionsToDownload)) {
  3268. $file = api_get_path(WEB_CODE_PATH).
  3269. 'lp/embed.php?type=download&source=file&lp_item_id='.$item_id.'&'.api_get_cidreq();
  3270. }
  3271. }
  3272. }
  3273. break;
  3274. case 'dir':
  3275. $file = 'lp_content.php?type=dir';
  3276. break;
  3277. case 'link':
  3278. if (Link::is_youtube_link($file)) {
  3279. $src = Link::get_youtube_video_id($file);
  3280. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=youtube&source='.$src;
  3281. } elseif (Link::isVimeoLink($file)) {
  3282. $src = Link::getVimeoLinkId($file);
  3283. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=vimeo&source='.$src;
  3284. } else {
  3285. // If the current site is HTTPS and the link is
  3286. // HTTP, browsers will refuse opening the link
  3287. $urlId = api_get_current_access_url_id();
  3288. $url = api_get_access_url($urlId, false);
  3289. $protocol = substr($url['url'], 0, 5);
  3290. if ($protocol === 'https') {
  3291. $linkProtocol = substr($file, 0, 5);
  3292. if ($linkProtocol === 'http:') {
  3293. //this is the special intervention case
  3294. $file = api_get_path(WEB_CODE_PATH).'lp/embed.php?type=nonhttps&source='.urlencode($file);
  3295. }
  3296. }
  3297. }
  3298. break;
  3299. case 'quiz':
  3300. // Check how much attempts of a exercise exits in lp
  3301. $lp_item_id = $this->get_current_item_id();
  3302. $lp_view_id = $this->get_view_id();
  3303. $prevent_reinit = null;
  3304. if (isset($this->items[$this->current])) {
  3305. $prevent_reinit = $this->items[$this->current]->get_prevent_reinit();
  3306. }
  3307. if (empty($provided_toc)) {
  3308. if ($this->debug > 0) {
  3309. error_log('In learnpath::get_link() Loading get_toc ', 0);
  3310. }
  3311. $list = $this->get_toc();
  3312. } else {
  3313. if ($this->debug > 0) {
  3314. error_log('In learnpath::get_link() Loading get_toc from "cache" ', 0);
  3315. }
  3316. $list = $provided_toc;
  3317. }
  3318. $type_quiz = false;
  3319. foreach ($list as $toc) {
  3320. if ($toc['id'] == $lp_item_id && $toc['type'] == 'quiz') {
  3321. $type_quiz = true;
  3322. }
  3323. }
  3324. if ($type_quiz) {
  3325. $lp_item_id = (int) $lp_item_id;
  3326. $lp_view_id = (int) $lp_view_id;
  3327. $sql = "SELECT count(*) FROM $lp_item_view_table
  3328. WHERE
  3329. c_id = $course_id AND
  3330. lp_item_id='".$lp_item_id."' AND
  3331. lp_view_id ='".$lp_view_id."' AND
  3332. status='completed'";
  3333. $result = Database::query($sql);
  3334. $row_count = Database:: fetch_row($result);
  3335. $count_item_view = (int) $row_count[0];
  3336. $not_multiple_attempt = 0;
  3337. if ($prevent_reinit === 1 && $count_item_view > 0) {
  3338. $not_multiple_attempt = 1;
  3339. }
  3340. $file .= '&not_multiple_attempt='.$not_multiple_attempt;
  3341. }
  3342. break;
  3343. }
  3344. $tmp_array = explode('/', $file);
  3345. $document_name = $tmp_array[count($tmp_array) - 1];
  3346. if (strpos($document_name, '_DELETED_')) {
  3347. $file = 'blank.php?error=document_deleted';
  3348. }
  3349. break;
  3350. case 2:
  3351. if ($this->debug > 2) {
  3352. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3353. }
  3354. if ($lp_item_type != 'dir') {
  3355. // Quite complex here:
  3356. // We want to make sure 'http://' (and similar) links can
  3357. // be loaded as is (withouth the Chamilo path in front) but
  3358. // some contents use this form: resource.htm?resource=http://blablabla
  3359. // which means we have to find a protocol at the path's start, otherwise
  3360. // it should not be considered as an external URL.
  3361. // if ($this->prerequisites_match($item_id)) {
  3362. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3363. if ($this->debug > 2) {
  3364. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3365. }
  3366. // Distant url, return as is.
  3367. $file = $lp_item_path;
  3368. } else {
  3369. if ($this->debug > 2) {
  3370. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3371. }
  3372. // Prevent getting untranslatable urls.
  3373. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3374. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3375. // Prepare the path.
  3376. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3377. // TODO: Fix this for urls with protocol header.
  3378. $file = str_replace('//', '/', $file);
  3379. $file = str_replace(':/', '://', $file);
  3380. if (substr($lp_path, -1) == '/') {
  3381. $lp_path = substr($lp_path, 0, -1);
  3382. }
  3383. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$lp_item_path))) {
  3384. // if file not found.
  3385. $decoded = html_entity_decode($lp_item_path);
  3386. list($decoded) = explode('?', $decoded);
  3387. if (!is_file(realpath($sys_course_path.'/scorm/'.$lp_path.'/'.$decoded))) {
  3388. $file = self::rl_get_resource_link_for_learnpath(
  3389. $course_id,
  3390. $this->get_id(),
  3391. $item_id,
  3392. $this->get_view_id()
  3393. );
  3394. if (empty($file)) {
  3395. $file = 'blank.php?error=document_not_found';
  3396. } else {
  3397. $tmp_array = explode('/', $file);
  3398. $document_name = $tmp_array[count($tmp_array) - 1];
  3399. if (strpos($document_name, '_DELETED_')) {
  3400. $file = 'blank.php?error=document_deleted';
  3401. } else {
  3402. $file = 'blank.php?error=document_not_found';
  3403. }
  3404. }
  3405. } else {
  3406. $file = $course_path.'/scorm/'.$lp_path.'/'.$decoded;
  3407. }
  3408. }
  3409. }
  3410. // We want to use parameters if they were defined in the imsmanifest
  3411. if (strpos($file, 'blank.php') === false) {
  3412. $lp_item_params = ltrim($lp_item_params, '?');
  3413. $file .= (strstr($file, '?') === false ? '?' : '').$lp_item_params;
  3414. }
  3415. } else {
  3416. $file = 'lp_content.php?type=dir';
  3417. }
  3418. break;
  3419. case 3:
  3420. if ($this->debug > 2) {
  3421. error_log('In learnpath::get_link() '.__LINE__.' - Item type: '.$lp_item_type, 0);
  3422. }
  3423. // Formatting AICC HACP append URL.
  3424. $aicc_append = '?aicc_sid='.urlencode(session_id()).'&aicc_url='.urlencode(api_get_path(WEB_CODE_PATH).'lp/aicc_hacp.php').'&';
  3425. if (!empty($lp_item_params)) {
  3426. $aicc_append .= $lp_item_params.'&';
  3427. }
  3428. if ($lp_item_type != 'dir') {
  3429. // Quite complex here:
  3430. // We want to make sure 'http://' (and similar) links can
  3431. // be loaded as is (withouth the Chamilo path in front) but
  3432. // some contents use this form: resource.htm?resource=http://blablabla
  3433. // which means we have to find a protocol at the path's start, otherwise
  3434. // it should not be considered as an external URL.
  3435. if (preg_match('#^[a-zA-Z]{2,5}://#', $lp_item_path) != 0) {
  3436. if ($this->debug > 2) {
  3437. error_log('In learnpath::get_link() '.__LINE__.' - Found match for protocol in '.$lp_item_path, 0);
  3438. }
  3439. // Distant url, return as is.
  3440. $file = $lp_item_path;
  3441. // Enabled and modified by Ivan Tcholakov, 16-OCT-2008.
  3442. /*
  3443. if (stristr($file,'<servername>') !== false) {
  3444. $file = str_replace('<servername>', $course_path.'/scorm/'.$lp_path.'/', $lp_item_path);
  3445. }
  3446. */
  3447. if (stripos($file, '<servername>') !== false) {
  3448. //$file = str_replace('<servername>',$course_path.'/scorm/'.$lp_path.'/',$lp_item_path);
  3449. $web_course_path = str_replace('https://', '', str_replace('http://', '', $course_path));
  3450. $file = str_replace('<servername>', $web_course_path.'/scorm/'.$lp_path, $lp_item_path);
  3451. }
  3452. $file .= $aicc_append;
  3453. } else {
  3454. if ($this->debug > 2) {
  3455. error_log('In learnpath::get_link() '.__LINE__.' - No starting protocol in '.$lp_item_path, 0);
  3456. }
  3457. // Prevent getting untranslatable urls.
  3458. $lp_item_path = preg_replace('/%2F/', '/', $lp_item_path);
  3459. $lp_item_path = preg_replace('/%3A/', ':', $lp_item_path);
  3460. // Prepare the path - lp_path might be unusable because it includes the "aicc" subdir name.
  3461. $file = $course_path.'/scorm/'.$lp_path.'/'.$lp_item_path;
  3462. // TODO: Fix this for urls with protocol header.
  3463. $file = str_replace('//', '/', $file);
  3464. $file = str_replace(':/', '://', $file);
  3465. $file .= $aicc_append;
  3466. }
  3467. } else {
  3468. $file = 'lp_content.php?type=dir';
  3469. }
  3470. break;
  3471. case 4:
  3472. break;
  3473. default:
  3474. break;
  3475. }
  3476. // Replace &amp; by & because &amp; will break URL with params
  3477. $file = !empty($file) ? str_replace('&amp;', '&', $file) : '';
  3478. }
  3479. if ($this->debug > 2) {
  3480. error_log('In learnpath::get_link() - returning "'.$file.'" from get_link', 0);
  3481. }
  3482. return $file;
  3483. }
  3484. /**
  3485. * Gets the latest usable view or generate a new one.
  3486. *
  3487. * @param int $attempt_num Optional attempt number. If none given, takes the highest from the lp_view table
  3488. *
  3489. * @return int DB lp_view id
  3490. */
  3491. public function get_view($attempt_num = 0)
  3492. {
  3493. $search = '';
  3494. // Use $attempt_num to enable multi-views management (disabled so far).
  3495. if ($attempt_num != 0 && intval(strval($attempt_num)) == $attempt_num) {
  3496. $search = 'AND view_count = '.$attempt_num;
  3497. }
  3498. // When missing $attempt_num, search for a unique lp_view record for this lp and user.
  3499. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  3500. $course_id = api_get_course_int_id();
  3501. $sessionId = api_get_session_id();
  3502. $sql = "SELECT iid, view_count FROM $lp_view_table
  3503. WHERE
  3504. c_id = $course_id AND
  3505. lp_id = ".$this->get_id()." AND
  3506. user_id = ".$this->get_user_id()." AND
  3507. session_id = $sessionId
  3508. $search
  3509. ORDER BY view_count DESC";
  3510. $res = Database::query($sql);
  3511. if (Database::num_rows($res) > 0) {
  3512. $row = Database::fetch_array($res);
  3513. $this->lp_view_id = $row['iid'];
  3514. } elseif (!api_is_invitee()) {
  3515. // There is no database record, create one.
  3516. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id) VALUES
  3517. ($course_id, ".$this->get_id().",".$this->get_user_id().", 1, $sessionId)";
  3518. Database::query($sql);
  3519. $id = Database::insert_id();
  3520. $this->lp_view_id = $id;
  3521. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $id";
  3522. Database::query($sql);
  3523. }
  3524. return $this->lp_view_id;
  3525. }
  3526. /**
  3527. * Gets the current view id.
  3528. *
  3529. * @return int View ID (from lp_view)
  3530. */
  3531. public function get_view_id()
  3532. {
  3533. if (!empty($this->lp_view_id)) {
  3534. return (int) $this->lp_view_id;
  3535. }
  3536. return 0;
  3537. }
  3538. /**
  3539. * Gets the update queue.
  3540. *
  3541. * @return array Array containing IDs of items to be updated by JavaScript
  3542. */
  3543. public function get_update_queue()
  3544. {
  3545. return $this->update_queue;
  3546. }
  3547. /**
  3548. * Gets the user ID.
  3549. *
  3550. * @return int User ID
  3551. */
  3552. public function get_user_id()
  3553. {
  3554. if (!empty($this->user_id)) {
  3555. return (int) $this->user_id;
  3556. }
  3557. return false;
  3558. }
  3559. /**
  3560. * Checks if any of the items has an audio element attached.
  3561. *
  3562. * @return bool True or false
  3563. */
  3564. public function has_audio()
  3565. {
  3566. $has = false;
  3567. foreach ($this->items as $i => $item) {
  3568. if (!empty($this->items[$i]->audio)) {
  3569. $has = true;
  3570. break;
  3571. }
  3572. }
  3573. return $has;
  3574. }
  3575. /**
  3576. * Moves an item up and down at its level.
  3577. *
  3578. * @param int $id Item to move up and down
  3579. * @param string $direction Direction 'up' or 'down'
  3580. *
  3581. * @return bool|int
  3582. */
  3583. public function move_item($id, $direction)
  3584. {
  3585. $course_id = api_get_course_int_id();
  3586. if (empty($id) || empty($direction)) {
  3587. return false;
  3588. }
  3589. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  3590. $sql_sel = "SELECT *
  3591. FROM $tbl_lp_item
  3592. WHERE
  3593. iid = $id
  3594. ";
  3595. $res_sel = Database::query($sql_sel);
  3596. // Check if elem exists.
  3597. if (Database::num_rows($res_sel) < 1) {
  3598. return false;
  3599. }
  3600. // Gather data.
  3601. $row = Database::fetch_array($res_sel);
  3602. $previous = $row['previous_item_id'];
  3603. $next = $row['next_item_id'];
  3604. $display = $row['display_order'];
  3605. $parent = $row['parent_item_id'];
  3606. $lp = $row['lp_id'];
  3607. // Update the item (switch with previous/next one).
  3608. switch ($direction) {
  3609. case 'up':
  3610. if ($display > 1) {
  3611. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3612. WHERE iid = $previous";
  3613. $res_sel2 = Database::query($sql_sel2);
  3614. if (Database::num_rows($res_sel2) < 1) {
  3615. $previous_previous = 0;
  3616. }
  3617. // Gather data.
  3618. $row2 = Database::fetch_array($res_sel2);
  3619. $previous_previous = $row2['previous_item_id'];
  3620. // Update previous_previous item (switch "next" with current).
  3621. if ($previous_previous != 0) {
  3622. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3623. next_item_id = $id
  3624. WHERE iid = $previous_previous";
  3625. Database::query($sql_upd2);
  3626. }
  3627. // Update previous item (switch with current).
  3628. if ($previous != 0) {
  3629. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3630. next_item_id = $next,
  3631. previous_item_id = $id,
  3632. display_order = display_order +1
  3633. WHERE iid = $previous";
  3634. Database::query($sql_upd2);
  3635. }
  3636. // Update current item (switch with previous).
  3637. if ($id != 0) {
  3638. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3639. next_item_id = $previous,
  3640. previous_item_id = $previous_previous,
  3641. display_order = display_order-1
  3642. WHERE c_id = ".$course_id." AND id = $id";
  3643. Database::query($sql_upd2);
  3644. }
  3645. // Update next item (new previous item).
  3646. if (!empty($next)) {
  3647. $sql_upd2 = "UPDATE $tbl_lp_item SET previous_item_id = $previous
  3648. WHERE iid = $next";
  3649. Database::query($sql_upd2);
  3650. }
  3651. $display = $display - 1;
  3652. }
  3653. break;
  3654. case 'down':
  3655. if ($next != 0) {
  3656. $sql_sel2 = "SELECT * FROM $tbl_lp_item
  3657. WHERE iid = $next";
  3658. $res_sel2 = Database::query($sql_sel2);
  3659. if (Database::num_rows($res_sel2) < 1) {
  3660. $next_next = 0;
  3661. }
  3662. // Gather data.
  3663. $row2 = Database::fetch_array($res_sel2);
  3664. $next_next = $row2['next_item_id'];
  3665. // Update previous item (switch with current).
  3666. if ($previous != 0) {
  3667. $sql_upd2 = "UPDATE $tbl_lp_item
  3668. SET next_item_id = $next
  3669. WHERE iid = $previous";
  3670. Database::query($sql_upd2);
  3671. }
  3672. // Update current item (switch with previous).
  3673. if ($id != 0) {
  3674. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3675. previous_item_id = $next,
  3676. next_item_id = $next_next,
  3677. display_order = display_order + 1
  3678. WHERE iid = $id";
  3679. Database::query($sql_upd2);
  3680. }
  3681. // Update next item (new previous item).
  3682. if ($next != 0) {
  3683. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3684. previous_item_id = $previous,
  3685. next_item_id = $id,
  3686. display_order = display_order-1
  3687. WHERE iid = $next";
  3688. Database::query($sql_upd2);
  3689. }
  3690. // Update next_next item (switch "previous" with current).
  3691. if ($next_next != 0) {
  3692. $sql_upd2 = "UPDATE $tbl_lp_item SET
  3693. previous_item_id = $id
  3694. WHERE iid = $next_next";
  3695. Database::query($sql_upd2);
  3696. }
  3697. $display = $display + 1;
  3698. }
  3699. break;
  3700. default:
  3701. return false;
  3702. }
  3703. return $display;
  3704. }
  3705. /**
  3706. * Move a LP up (display_order).
  3707. *
  3708. * @param int $lp_id Learnpath ID
  3709. * @param int $categoryId Category ID
  3710. *
  3711. * @return bool
  3712. */
  3713. public static function move_up($lp_id, $categoryId = 0)
  3714. {
  3715. $courseId = api_get_course_int_id();
  3716. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3717. $categoryCondition = '';
  3718. if (!empty($categoryId)) {
  3719. $categoryId = (int) $categoryId;
  3720. $categoryCondition = " AND category_id = $categoryId";
  3721. }
  3722. $sql = "SELECT * FROM $lp_table
  3723. WHERE c_id = $courseId
  3724. $categoryCondition
  3725. ORDER BY display_order";
  3726. $res = Database::query($sql);
  3727. if ($res === false) {
  3728. return false;
  3729. }
  3730. $lps = [];
  3731. $lp_order = [];
  3732. $num = Database::num_rows($res);
  3733. // First check the order is correct, globally (might be wrong because
  3734. // of versions < 1.8.4)
  3735. if ($num > 0) {
  3736. $i = 1;
  3737. while ($row = Database::fetch_array($res)) {
  3738. if ($row['display_order'] != $i) { // If we find a gap in the order, we need to fix it.
  3739. $sql = "UPDATE $lp_table SET display_order = $i
  3740. WHERE iid = ".$row['iid'];
  3741. Database::query($sql);
  3742. }
  3743. $row['display_order'] = $i;
  3744. $lps[$row['iid']] = $row;
  3745. $lp_order[$i] = $row['iid'];
  3746. $i++;
  3747. }
  3748. }
  3749. if ($num > 1) { // If there's only one element, no need to sort.
  3750. $order = $lps[$lp_id]['display_order'];
  3751. if ($order > 1) { // If it's the first element, no need to move up.
  3752. $sql = "UPDATE $lp_table SET display_order = $order
  3753. WHERE iid = ".$lp_order[$order - 1];
  3754. Database::query($sql);
  3755. $sql = "UPDATE $lp_table SET display_order = ".($order - 1)."
  3756. WHERE iid = $lp_id";
  3757. Database::query($sql);
  3758. }
  3759. }
  3760. return true;
  3761. }
  3762. /**
  3763. * Move a learnpath down (display_order).
  3764. *
  3765. * @param int $lp_id Learnpath ID
  3766. * @param int $categoryId Category ID
  3767. *
  3768. * @return bool
  3769. */
  3770. public static function move_down($lp_id, $categoryId = 0)
  3771. {
  3772. $courseId = api_get_course_int_id();
  3773. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  3774. $categoryCondition = '';
  3775. if (!empty($categoryId)) {
  3776. $categoryId = (int) $categoryId;
  3777. $categoryCondition = " AND category_id = $categoryId";
  3778. }
  3779. $sql = "SELECT * FROM $lp_table
  3780. WHERE c_id = $courseId
  3781. $categoryCondition
  3782. ORDER BY display_order";
  3783. $res = Database::query($sql);
  3784. if ($res === false) {
  3785. return false;
  3786. }
  3787. $lps = [];
  3788. $lp_order = [];
  3789. $num = Database::num_rows($res);
  3790. $max = 0;
  3791. // First check the order is correct, globally (might be wrong because
  3792. // of versions < 1.8.4).
  3793. if ($num > 0) {
  3794. $i = 1;
  3795. while ($row = Database::fetch_array($res)) {
  3796. $max = $i;
  3797. if ($row['display_order'] != $i) {
  3798. // If we find a gap in the order, we need to fix it.
  3799. $sql = "UPDATE $lp_table SET display_order = $i
  3800. WHERE iid = ".$row['iid'];
  3801. Database::query($sql);
  3802. }
  3803. $row['display_order'] = $i;
  3804. $lps[$row['iid']] = $row;
  3805. $lp_order[$i] = $row['iid'];
  3806. $i++;
  3807. }
  3808. }
  3809. if ($num > 1) { // If there's only one element, no need to sort.
  3810. $order = $lps[$lp_id]['display_order'];
  3811. if ($order < $max) { // If it's the first element, no need to move up.
  3812. $sql = "UPDATE $lp_table SET display_order = $order
  3813. WHERE iid = ".$lp_order[$order + 1];
  3814. Database::query($sql);
  3815. $sql = "UPDATE $lp_table SET display_order = ".($order + 1)."
  3816. WHERE iid = $lp_id";
  3817. Database::query($sql);
  3818. }
  3819. }
  3820. return true;
  3821. }
  3822. /**
  3823. * Updates learnpath attributes to point to the next element
  3824. * The last part is similar to set_current_item but processing the other way around.
  3825. */
  3826. public function next()
  3827. {
  3828. if ($this->debug > 0) {
  3829. error_log('In learnpath::next()', 0);
  3830. }
  3831. $this->last = $this->get_current_item_id();
  3832. $this->items[$this->last]->save(
  3833. false,
  3834. $this->prerequisites_match($this->last)
  3835. );
  3836. $this->autocomplete_parents($this->last);
  3837. $new_index = $this->get_next_index();
  3838. if ($this->debug > 2) {
  3839. error_log('New index: '.$new_index, 0);
  3840. }
  3841. $this->index = $new_index;
  3842. if ($this->debug > 2) {
  3843. error_log('Now having orderedlist['.$new_index.'] = '.$this->ordered_items[$new_index], 0);
  3844. }
  3845. $this->current = $this->ordered_items[$new_index];
  3846. if ($this->debug > 2) {
  3847. error_log('new item id is '.$this->current.'-'.$this->get_current_item_id(), 0);
  3848. }
  3849. }
  3850. /**
  3851. * Open a resource = initialise all local variables relative to this resource. Depending on the child
  3852. * class, this might be redefined to allow several behaviours depending on the document type.
  3853. *
  3854. * @param int $id Resource ID
  3855. */
  3856. public function open($id)
  3857. {
  3858. // TODO:
  3859. // set the current resource attribute to this resource
  3860. // switch on element type (redefine in child class?)
  3861. // set status for this item to "opened"
  3862. // start timer
  3863. // initialise score
  3864. $this->index = 0; //or = the last item seen (see $this->last)
  3865. }
  3866. /**
  3867. * Check that all prerequisites are fulfilled. Returns true and an
  3868. * empty string on success, returns false
  3869. * and the prerequisite string on error.
  3870. * This function is based on the rules for aicc_script language as
  3871. * described in the SCORM 1.2 CAM documentation page 108.
  3872. *
  3873. * @param int $itemId Optional item ID. If none given, uses the current open item.
  3874. *
  3875. * @return bool true if prerequisites are matched, false otherwise - Empty string if true returned, prerequisites
  3876. * string otherwise
  3877. */
  3878. public function prerequisites_match($itemId = null)
  3879. {
  3880. $allow = api_get_configuration_value('allow_teachers_to_access_blocked_lp_by_prerequisite');
  3881. if ($allow) {
  3882. if (api_is_allowed_to_edit() ||
  3883. api_is_platform_admin(true) ||
  3884. api_is_drh() ||
  3885. api_is_coach(api_get_session_id(), api_get_course_int_id())
  3886. ) {
  3887. return true;
  3888. }
  3889. }
  3890. $debug = $this->debug;
  3891. if ($debug > 0) {
  3892. error_log('In learnpath::prerequisites_match()');
  3893. }
  3894. if (empty($itemId)) {
  3895. $itemId = $this->current;
  3896. }
  3897. $currentItem = $this->getItem($itemId);
  3898. if ($currentItem) {
  3899. if ($this->type == 2) {
  3900. // Getting prereq from scorm
  3901. $prereq_string = $this->get_scorm_prereq_string($itemId);
  3902. } else {
  3903. $prereq_string = $currentItem->get_prereq_string();
  3904. }
  3905. if (empty($prereq_string)) {
  3906. if ($debug > 0) {
  3907. error_log('Found prereq_string is empty return true');
  3908. }
  3909. return true;
  3910. }
  3911. // Clean spaces.
  3912. $prereq_string = str_replace(' ', '', $prereq_string);
  3913. if ($debug > 0) {
  3914. error_log('Found prereq_string: '.$prereq_string, 0);
  3915. }
  3916. // Now send to the parse_prereq() function that will check this component's prerequisites.
  3917. $result = $currentItem->parse_prereq(
  3918. $prereq_string,
  3919. $this->items,
  3920. $this->refs_list,
  3921. $this->get_user_id()
  3922. );
  3923. if ($result === false) {
  3924. $this->set_error_msg($currentItem->prereq_alert);
  3925. }
  3926. } else {
  3927. $result = true;
  3928. if ($debug > 1) {
  3929. error_log('$this->items['.$itemId.'] was not an object', 0);
  3930. }
  3931. }
  3932. if ($debug > 1) {
  3933. error_log('End of prerequisites_match(). Error message is now '.$this->error, 0);
  3934. }
  3935. return $result;
  3936. }
  3937. /**
  3938. * Updates learnpath attributes to point to the previous element
  3939. * The last part is similar to set_current_item but processing the other way around.
  3940. */
  3941. public function previous()
  3942. {
  3943. $this->last = $this->get_current_item_id();
  3944. $this->items[$this->last]->save(
  3945. false,
  3946. $this->prerequisites_match($this->last)
  3947. );
  3948. $this->autocomplete_parents($this->last);
  3949. $new_index = $this->get_previous_index();
  3950. $this->index = $new_index;
  3951. $this->current = $this->ordered_items[$new_index];
  3952. }
  3953. /**
  3954. * Publishes a learnpath. This basically means show or hide the learnpath
  3955. * to normal users.
  3956. * Can be used as abstract.
  3957. *
  3958. * @param int $lp_id Learnpath ID
  3959. * @param int $set_visibility New visibility
  3960. *
  3961. * @return bool
  3962. */
  3963. public static function toggle_visibility($lp_id, $set_visibility = 1)
  3964. {
  3965. $action = 'visible';
  3966. if ($set_visibility != 1) {
  3967. $action = 'invisible';
  3968. self::toggle_publish($lp_id, 'i');
  3969. }
  3970. return api_item_property_update(
  3971. api_get_course_info(),
  3972. TOOL_LEARNPATH,
  3973. $lp_id,
  3974. $action,
  3975. api_get_user_id()
  3976. );
  3977. }
  3978. /**
  3979. * Publishes a learnpath category.
  3980. * This basically means show or hide the learnpath category to normal users.
  3981. *
  3982. * @param int $id
  3983. * @param int $visibility
  3984. *
  3985. * @throws \Doctrine\ORM\NonUniqueResultException
  3986. * @throws \Doctrine\ORM\ORMException
  3987. * @throws \Doctrine\ORM\OptimisticLockException
  3988. * @throws \Doctrine\ORM\TransactionRequiredException
  3989. *
  3990. * @return bool
  3991. */
  3992. public static function toggleCategoryVisibility($id, $visibility = 1)
  3993. {
  3994. $action = 'visible';
  3995. if ($visibility != 1) {
  3996. $action = 'invisible';
  3997. $list = new LearnpathList(
  3998. api_get_user_id(),
  3999. null,
  4000. null,
  4001. null,
  4002. false,
  4003. $id
  4004. );
  4005. $lpList = $list->get_flat_list();
  4006. foreach ($lpList as $lp) {
  4007. self::toggle_visibility($lp['iid'], 0);
  4008. }
  4009. self::toggleCategoryPublish($id, 0);
  4010. }
  4011. return api_item_property_update(
  4012. api_get_course_info(),
  4013. TOOL_LEARNPATH_CATEGORY,
  4014. $id,
  4015. $action,
  4016. api_get_user_id()
  4017. );
  4018. }
  4019. /**
  4020. * Publishes a learnpath. This basically means show or hide the learnpath
  4021. * on the course homepage
  4022. * Can be used as abstract.
  4023. *
  4024. * @param int $lp_id Learnpath id
  4025. * @param string $set_visibility New visibility (v/i - visible/invisible)
  4026. *
  4027. * @return bool
  4028. */
  4029. public static function toggle_publish($lp_id, $set_visibility = 'v')
  4030. {
  4031. $course_id = api_get_course_int_id();
  4032. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4033. $lp_id = (int) $lp_id;
  4034. $sql = "SELECT * FROM $tbl_lp
  4035. WHERE iid = $lp_id";
  4036. $result = Database::query($sql);
  4037. if (Database::num_rows($result)) {
  4038. $row = Database::fetch_array($result);
  4039. $name = Database::escape_string($row['name']);
  4040. if ($set_visibility == 'i') {
  4041. $v = 0;
  4042. }
  4043. if ($set_visibility == 'v') {
  4044. $v = 1;
  4045. }
  4046. $session_id = api_get_session_id();
  4047. $session_condition = api_get_session_condition($session_id);
  4048. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4049. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4050. $oldLink = 'newscorm/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4051. $sql = "SELECT * FROM $tbl_tool
  4052. WHERE
  4053. c_id = $course_id AND
  4054. (link = '$link' OR link = '$oldLink') AND
  4055. image = 'scormbuilder.gif' AND
  4056. (
  4057. link LIKE '$link%' OR
  4058. link LIKE '$oldLink%'
  4059. )
  4060. $session_condition
  4061. ";
  4062. $result = Database::query($sql);
  4063. $num = Database::num_rows($result);
  4064. if ($set_visibility == 'i' && $num > 0) {
  4065. $sql = "DELETE FROM $tbl_tool
  4066. WHERE
  4067. c_id = $course_id AND
  4068. (link = '$link' OR link = '$oldLink') AND
  4069. image='scormbuilder.gif'
  4070. $session_condition";
  4071. Database::query($sql);
  4072. } elseif ($set_visibility == 'v' && $num == 0) {
  4073. $sql = "INSERT INTO $tbl_tool (category, c_id, name, link, image, visibility, admin, address, added_tool, session_id) VALUES
  4074. ('authoring', $course_id, '$name', '$link', 'scormbuilder.gif', '$v', '0','pastillegris.gif', 0, $session_id)";
  4075. Database::query($sql);
  4076. $insertId = Database::insert_id();
  4077. if ($insertId) {
  4078. $sql = "UPDATE $tbl_tool SET id = iid WHERE iid = $insertId";
  4079. Database::query($sql);
  4080. }
  4081. } elseif ($set_visibility == 'v' && $num > 0) {
  4082. $sql = "UPDATE $tbl_tool SET
  4083. c_id = $course_id,
  4084. name = '$name',
  4085. link = '$link',
  4086. image = 'scormbuilder.gif',
  4087. visibility = '$v',
  4088. admin = '0',
  4089. address = 'pastillegris.gif',
  4090. added_tool = 0,
  4091. session_id = $session_id
  4092. WHERE
  4093. c_id = ".$course_id." AND
  4094. (link = '$link' OR link = '$oldLink') AND
  4095. image='scormbuilder.gif'
  4096. $session_condition
  4097. ";
  4098. Database::query($sql);
  4099. } else {
  4100. // Parameter and database incompatible, do nothing, exit.
  4101. return false;
  4102. }
  4103. } else {
  4104. return false;
  4105. }
  4106. }
  4107. /**
  4108. * Publishes a learnpath.
  4109. * Show or hide the learnpath category on the course homepage.
  4110. *
  4111. * @param int $id
  4112. * @param int $setVisibility
  4113. *
  4114. * @throws \Doctrine\ORM\NonUniqueResultException
  4115. * @throws \Doctrine\ORM\ORMException
  4116. * @throws \Doctrine\ORM\OptimisticLockException
  4117. * @throws \Doctrine\ORM\TransactionRequiredException
  4118. *
  4119. * @return bool
  4120. */
  4121. public static function toggleCategoryPublish($id, $setVisibility = 1)
  4122. {
  4123. $courseId = api_get_course_int_id();
  4124. $sessionId = api_get_session_id();
  4125. $sessionCondition = api_get_session_condition(
  4126. $sessionId,
  4127. true,
  4128. false,
  4129. 't.sessionId'
  4130. );
  4131. $em = Database::getManager();
  4132. /** @var CLpCategory $category */
  4133. $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  4134. if (!$category) {
  4135. return false;
  4136. }
  4137. if (empty($courseId)) {
  4138. return false;
  4139. }
  4140. $link = self::getCategoryLinkForTool($id);
  4141. /** @var CTool $tool */
  4142. $tool = $em->createQuery("
  4143. SELECT t FROM ChamiloCourseBundle:CTool t
  4144. WHERE
  4145. t.cId = :course AND
  4146. t.link = :link1 AND
  4147. t.image = 'lp_category.gif' AND
  4148. t.link LIKE :link2
  4149. $sessionCondition
  4150. ")
  4151. ->setParameters([
  4152. 'course' => (int) $courseId,
  4153. 'link1' => $link,
  4154. 'link2' => "$link%",
  4155. ])
  4156. ->getOneOrNullResult();
  4157. if ($setVisibility == 0 && $tool) {
  4158. $em->remove($tool);
  4159. $em->flush();
  4160. return true;
  4161. }
  4162. if ($setVisibility == 1 && !$tool) {
  4163. $tool = new CTool();
  4164. $tool
  4165. ->setCategory('authoring')
  4166. ->setCId($courseId)
  4167. ->setName(strip_tags($category->getName()))
  4168. ->setLink($link)
  4169. ->setImage('lp_category.gif')
  4170. ->setVisibility(1)
  4171. ->setAdmin(0)
  4172. ->setAddress('pastillegris.gif')
  4173. ->setAddedTool(0)
  4174. ->setSessionId($sessionId)
  4175. ->setTarget('_self');
  4176. $em->persist($tool);
  4177. $em->flush();
  4178. $tool->setId($tool->getIid());
  4179. $em->persist($tool);
  4180. $em->flush();
  4181. return true;
  4182. }
  4183. if ($setVisibility == 1 && $tool) {
  4184. $tool
  4185. ->setName(strip_tags($category->getName()))
  4186. ->setVisibility(1);
  4187. $em->persist($tool);
  4188. $em->flush();
  4189. return true;
  4190. }
  4191. return false;
  4192. }
  4193. /**
  4194. * Check if the learnpath category is visible for a user.
  4195. *
  4196. * @param CLpCategory $category
  4197. * @param User $user
  4198. * @param int
  4199. * @param int
  4200. *
  4201. * @return bool
  4202. */
  4203. public static function categoryIsVisibleForStudent(
  4204. CLpCategory $category,
  4205. User $user,
  4206. $courseId = 0,
  4207. $sessionId = 0
  4208. ) {
  4209. $subscriptionSettings = self::getSubscriptionSettings();
  4210. if ($subscriptionSettings['allow_add_users_to_lp_category'] == false) {
  4211. return true;
  4212. }
  4213. $isAllowedToEdit = api_is_allowed_to_edit(null, true);
  4214. if ($isAllowedToEdit) {
  4215. return true;
  4216. }
  4217. if (empty($category)) {
  4218. return false;
  4219. }
  4220. $users = $category->getUsers();
  4221. if (empty($users) || !$users->count()) {
  4222. return true;
  4223. }
  4224. $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
  4225. $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  4226. if ($category->hasUserAdded($user)) {
  4227. return true;
  4228. }
  4229. $groups = GroupManager::getAllGroupPerUserSubscription($user->getId());
  4230. if (!empty($groups)) {
  4231. $em = Database::getManager();
  4232. /** @var ItemPropertyRepository $itemRepo */
  4233. $itemRepo = $em->getRepository('ChamiloCourseBundle:CItemProperty');
  4234. /** @var CourseRepository $courseRepo */
  4235. $courseRepo = $em->getRepository('ChamiloCoreBundle:Course');
  4236. $session = null;
  4237. if (!empty($sessionId)) {
  4238. $session = $em->getRepository('ChamiloCoreBundle:Session')->find($sessionId);
  4239. }
  4240. $course = $courseRepo->find($courseId);
  4241. // Subscribed groups to a LP
  4242. $subscribedGroupsInLp = $itemRepo->getGroupsSubscribedToItem(
  4243. TOOL_LEARNPATH_CATEGORY,
  4244. $category->getId(),
  4245. $course,
  4246. $session
  4247. );
  4248. if (!empty($subscribedGroupsInLp)) {
  4249. $groups = array_column($groups, 'iid');
  4250. /** @var CItemProperty $item */
  4251. foreach ($subscribedGroupsInLp as $item) {
  4252. if ($item->getGroup() &&
  4253. in_array($item->getGroup()->getId(), $groups)
  4254. ) {
  4255. return true;
  4256. }
  4257. }
  4258. }
  4259. }
  4260. return false;
  4261. }
  4262. /**
  4263. * Check if a learnpath category is published as course tool.
  4264. *
  4265. * @param CLpCategory $category
  4266. * @param int $courseId
  4267. *
  4268. * @return bool
  4269. */
  4270. public static function categoryIsPublished(
  4271. CLpCategory $category,
  4272. $courseId
  4273. ) {
  4274. $link = self::getCategoryLinkForTool($category->getId());
  4275. $em = Database::getManager();
  4276. $tools = $em
  4277. ->createQuery("
  4278. SELECT t FROM ChamiloCourseBundle:CTool t
  4279. WHERE t.cId = :course AND
  4280. t.name = :name AND
  4281. t.image = 'lp_category.gif' AND
  4282. t.link LIKE :link
  4283. ")
  4284. ->setParameters([
  4285. 'course' => $courseId,
  4286. 'name' => strip_tags($category->getName()),
  4287. 'link' => "$link%",
  4288. ])
  4289. ->getResult();
  4290. /** @var CTool $tool */
  4291. $tool = current($tools);
  4292. return $tool ? $tool->getVisibility() : false;
  4293. }
  4294. /**
  4295. * Restart the whole learnpath. Return the URL of the first element.
  4296. * Make sure the results are saved with anoter method. This method should probably be redefined in children classes.
  4297. * To use a similar method statically, use the create_new_attempt() method.
  4298. *
  4299. * @return bool
  4300. */
  4301. public function restart()
  4302. {
  4303. if ($this->debug > 0) {
  4304. error_log('In learnpath::restart()', 0);
  4305. }
  4306. // TODO
  4307. // Call autosave method to save the current progress.
  4308. //$this->index = 0;
  4309. if (api_is_invitee()) {
  4310. return false;
  4311. }
  4312. $session_id = api_get_session_id();
  4313. $course_id = api_get_course_int_id();
  4314. $lp_view_table = Database::get_course_table(TABLE_LP_VIEW);
  4315. $sql = "INSERT INTO $lp_view_table (c_id, lp_id, user_id, view_count, session_id)
  4316. VALUES ($course_id, ".$this->lp_id.",".$this->get_user_id().",".($this->attempt + 1).", $session_id)";
  4317. if ($this->debug > 2) {
  4318. error_log('Inserting new lp_view for restart: '.$sql, 0);
  4319. }
  4320. Database::query($sql);
  4321. $view_id = Database::insert_id();
  4322. if ($view_id) {
  4323. $sql = "UPDATE $lp_view_table SET id = iid WHERE iid = $view_id";
  4324. Database::query($sql);
  4325. $this->lp_view_id = $view_id;
  4326. $this->attempt = $this->attempt + 1;
  4327. } else {
  4328. $this->error = 'Could not insert into item_view table...';
  4329. return false;
  4330. }
  4331. $this->autocomplete_parents($this->current);
  4332. foreach ($this->items as $index => $dummy) {
  4333. $this->items[$index]->restart();
  4334. $this->items[$index]->set_lp_view($this->lp_view_id);
  4335. }
  4336. $this->first();
  4337. return true;
  4338. }
  4339. /**
  4340. * Saves the current item.
  4341. *
  4342. * @return bool
  4343. */
  4344. public function save_current()
  4345. {
  4346. $debug = $this->debug;
  4347. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4348. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4349. if ($debug) {
  4350. error_log('save_current() saving item '.$this->current, 0);
  4351. error_log(''.print_r($this->items, true), 0);
  4352. }
  4353. if (isset($this->items[$this->current]) &&
  4354. is_object($this->items[$this->current])
  4355. ) {
  4356. if ($debug) {
  4357. error_log('Before save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4358. }
  4359. $res = $this->items[$this->current]->save(
  4360. false,
  4361. $this->prerequisites_match($this->current)
  4362. );
  4363. $this->autocomplete_parents($this->current);
  4364. $status = $this->items[$this->current]->get_status();
  4365. $this->update_queue[$this->current] = $status;
  4366. if ($debug) {
  4367. error_log('After save last_scorm_session_time: '.$this->items[$this->current]->getLastScormSessionTime());
  4368. }
  4369. return $res;
  4370. }
  4371. return false;
  4372. }
  4373. /**
  4374. * Saves the given item.
  4375. *
  4376. * @param int $item_id Optional (will take from $_REQUEST if null)
  4377. * @param bool $from_outside Save from url params (true) or from current attributes (false). Default true
  4378. *
  4379. * @return bool
  4380. */
  4381. public function save_item($item_id = null, $from_outside = true)
  4382. {
  4383. $debug = $this->debug;
  4384. if ($debug) {
  4385. error_log('In learnpath::save_item('.$item_id.','.intval($from_outside).')', 0);
  4386. }
  4387. // TODO: Do a better check on the index pointing to the right item (it is supposed to be working
  4388. // on $ordered_items[] but not sure it's always safe to use with $items[]).
  4389. if (empty($item_id)) {
  4390. $item_id = (int) $_REQUEST['id'];
  4391. }
  4392. if (empty($item_id)) {
  4393. $item_id = $this->get_current_item_id();
  4394. }
  4395. if (isset($this->items[$item_id]) &&
  4396. is_object($this->items[$item_id])
  4397. ) {
  4398. if ($debug) {
  4399. error_log('Object exists');
  4400. }
  4401. // Saving the item.
  4402. $res = $this->items[$item_id]->save(
  4403. $from_outside,
  4404. $this->prerequisites_match($item_id)
  4405. );
  4406. if ($debug) {
  4407. error_log('update_queue before:');
  4408. error_log(print_r($this->update_queue, 1));
  4409. }
  4410. $this->autocomplete_parents($item_id);
  4411. $status = $this->items[$item_id]->get_status();
  4412. $this->update_queue[$item_id] = $status;
  4413. if ($debug) {
  4414. error_log('get_status(): '.$status);
  4415. error_log('update_queue after:');
  4416. error_log(print_r($this->update_queue, 1));
  4417. }
  4418. return $res;
  4419. }
  4420. return false;
  4421. }
  4422. /**
  4423. * Saves the last item seen's ID only in case.
  4424. */
  4425. public function save_last()
  4426. {
  4427. $course_id = api_get_course_int_id();
  4428. $debug = $this->debug;
  4429. if ($debug) {
  4430. error_log('In learnpath::save_last()', 0);
  4431. }
  4432. $session_condition = api_get_session_condition(
  4433. api_get_session_id(),
  4434. true,
  4435. false
  4436. );
  4437. $table = Database::get_course_table(TABLE_LP_VIEW);
  4438. if (isset($this->current) && !api_is_invitee()) {
  4439. if ($debug) {
  4440. error_log('Saving current item ('.$this->current.') for later review', 0);
  4441. }
  4442. $sql = "UPDATE $table SET
  4443. last_item = ".$this->get_current_item_id()."
  4444. WHERE
  4445. c_id = $course_id AND
  4446. lp_id = ".$this->get_id()." AND
  4447. user_id = ".$this->get_user_id()." ".$session_condition;
  4448. if ($debug) {
  4449. error_log('Saving last item seen : '.$sql, 0);
  4450. }
  4451. Database::query($sql);
  4452. }
  4453. if (!api_is_invitee()) {
  4454. // Save progress.
  4455. list($progress) = $this->get_progress_bar_text('%');
  4456. if ($progress >= 0 && $progress <= 100) {
  4457. $progress = (int) $progress;
  4458. $sql = "UPDATE $table SET
  4459. progress = $progress
  4460. WHERE
  4461. c_id = $course_id AND
  4462. lp_id = ".$this->get_id()." AND
  4463. user_id = ".$this->get_user_id()." ".$session_condition;
  4464. // Ignore errors as some tables might not have the progress field just yet.
  4465. Database::query($sql);
  4466. $this->progress_db = $progress;
  4467. }
  4468. }
  4469. }
  4470. /**
  4471. * Sets the current item ID (checks if valid and authorized first).
  4472. *
  4473. * @param int $item_id New item ID. If not given or not authorized, defaults to current
  4474. */
  4475. public function set_current_item($item_id = null)
  4476. {
  4477. $debug = $this->debug;
  4478. if ($debug) {
  4479. error_log('In learnpath::set_current_item('.$item_id.')', 0);
  4480. }
  4481. if (empty($item_id)) {
  4482. if ($debug) {
  4483. error_log('No new current item given, ignore...', 0);
  4484. }
  4485. // Do nothing.
  4486. } else {
  4487. if ($debug) {
  4488. error_log('New current item given is '.$item_id.'...', 0);
  4489. }
  4490. if (is_numeric($item_id)) {
  4491. $item_id = (int) $item_id;
  4492. // TODO: Check in database here.
  4493. $this->last = $this->current;
  4494. $this->current = $item_id;
  4495. // TODO: Update $this->index as well.
  4496. foreach ($this->ordered_items as $index => $item) {
  4497. if ($item == $this->current) {
  4498. $this->index = $index;
  4499. break;
  4500. }
  4501. }
  4502. if ($debug) {
  4503. error_log('set_current_item('.$item_id.') done. Index is now : '.$this->index);
  4504. }
  4505. } else {
  4506. if ($debug) {
  4507. error_log('set_current_item('.$item_id.') failed. Not a numeric value: ');
  4508. }
  4509. }
  4510. }
  4511. }
  4512. /**
  4513. * Sets the encoding.
  4514. *
  4515. * @param string $enc New encoding
  4516. *
  4517. * @return bool
  4518. *
  4519. * @todo (as of Chamilo 1.8.8): Check in the future whether this method is needed.
  4520. */
  4521. public function set_encoding($enc = 'UTF-8')
  4522. {
  4523. $enc = api_refine_encoding_id($enc);
  4524. if (empty($enc)) {
  4525. $enc = api_get_system_encoding();
  4526. }
  4527. if (api_is_encoding_supported($enc)) {
  4528. $lp = $this->get_id();
  4529. if ($lp != 0) {
  4530. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4531. $sql = "UPDATE $tbl_lp SET default_encoding = '$enc'
  4532. WHERE iid = ".$lp;
  4533. $res = Database::query($sql);
  4534. return $res;
  4535. }
  4536. }
  4537. return false;
  4538. }
  4539. /**
  4540. * Sets the JS lib setting in the database directly.
  4541. * This is the JavaScript library file this lp needs to load on startup.
  4542. *
  4543. * @param string $lib Proximity setting
  4544. *
  4545. * @return bool True on update success. False otherwise.
  4546. */
  4547. public function set_jslib($lib = '')
  4548. {
  4549. $lp = $this->get_id();
  4550. if ($lp != 0) {
  4551. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  4552. $lib = Database::escape_string($lib);
  4553. $sql = "UPDATE $tbl_lp SET js_lib = '$lib'
  4554. WHERE iid = $lp";
  4555. $res = Database::query($sql);
  4556. return $res;
  4557. }
  4558. return false;
  4559. }
  4560. /**
  4561. * Sets the name of the LP maker (publisher) (and save).
  4562. *
  4563. * @param string $name Optional string giving the new content_maker of this learnpath
  4564. *
  4565. * @return bool True
  4566. */
  4567. public function set_maker($name = '')
  4568. {
  4569. if (empty($name)) {
  4570. return false;
  4571. }
  4572. $this->maker = $name;
  4573. $table = Database::get_course_table(TABLE_LP_MAIN);
  4574. $lp_id = $this->get_id();
  4575. $sql = "UPDATE $table SET
  4576. content_maker = '".Database::escape_string($this->maker)."'
  4577. WHERE iid = $lp_id";
  4578. Database::query($sql);
  4579. return true;
  4580. }
  4581. /**
  4582. * Sets the name of the current learnpath (and save).
  4583. *
  4584. * @param string $name Optional string giving the new name of this learnpath
  4585. *
  4586. * @return bool True/False
  4587. */
  4588. public function set_name($name = null)
  4589. {
  4590. if (empty($name)) {
  4591. return false;
  4592. }
  4593. $this->name = Database::escape_string($name);
  4594. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  4595. $lp_id = $this->get_id();
  4596. $course_id = $this->course_info['real_id'];
  4597. $sql = "UPDATE $lp_table SET
  4598. name = '".Database::escape_string($this->name)."'
  4599. WHERE iid = $lp_id";
  4600. $result = Database::query($sql);
  4601. // If the lp is visible on the homepage, change his name there.
  4602. if (Database::affected_rows($result)) {
  4603. $session_id = api_get_session_id();
  4604. $session_condition = api_get_session_condition($session_id);
  4605. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  4606. $link = 'lp/lp_controller.php?action=view&lp_id='.$lp_id.'&id_session='.$session_id;
  4607. $sql = "UPDATE $tbl_tool SET name = '$this->name'
  4608. WHERE
  4609. c_id = $course_id AND
  4610. (link='$link' AND image='scormbuilder.gif' $session_condition)";
  4611. Database::query($sql);
  4612. return true;
  4613. }
  4614. return false;
  4615. }
  4616. /**
  4617. * Set index specified prefix terms for all items in this path.
  4618. *
  4619. * @param string $terms_string Comma-separated list of terms
  4620. * @param string $prefix Xapian term prefix
  4621. *
  4622. * @return bool False on error, true otherwise
  4623. */
  4624. public function set_terms_by_prefix($terms_string, $prefix)
  4625. {
  4626. $course_id = api_get_course_int_id();
  4627. if (api_get_setting('search_enabled') !== 'true') {
  4628. return false;
  4629. }
  4630. if (!extension_loaded('xapian')) {
  4631. return false;
  4632. }
  4633. $terms_string = trim($terms_string);
  4634. $terms = explode(',', $terms_string);
  4635. array_walk($terms, 'trim_value');
  4636. $stored_terms = $this->get_common_index_terms_by_prefix($prefix);
  4637. // Don't do anything if no change, verify only at DB, not the search engine.
  4638. if ((count(array_diff($terms, $stored_terms)) == 0) && (count(array_diff($stored_terms, $terms)) == 0)) {
  4639. return false;
  4640. }
  4641. require_once 'xapian.php'; // TODO: Try catch every xapian use or make wrappers on API.
  4642. require_once api_get_path(LIBRARY_PATH).'search/xapian/XapianQuery.php';
  4643. $items_table = Database::get_course_table(TABLE_LP_ITEM);
  4644. // TODO: Make query secure agains XSS : use member attr instead of post var.
  4645. $lp_id = (int) $_POST['lp_id'];
  4646. $sql = "SELECT * FROM $items_table WHERE c_id = $course_id AND lp_id = $lp_id";
  4647. $result = Database::query($sql);
  4648. $di = new ChamiloIndexer();
  4649. while ($lp_item = Database::fetch_array($result)) {
  4650. // Get search_did.
  4651. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  4652. $sql = 'SELECT * FROM %s
  4653. WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%d
  4654. LIMIT 1';
  4655. $sql = sprintf($sql, $tbl_se_ref, $this->cc, TOOL_LEARNPATH, $lp_id, $lp_item['id']);
  4656. //echo $sql; echo '<br>';
  4657. $res = Database::query($sql);
  4658. if (Database::num_rows($res) > 0) {
  4659. $se_ref = Database::fetch_array($res);
  4660. // Compare terms.
  4661. $doc = $di->get_document($se_ref['search_did']);
  4662. $xapian_terms = xapian_get_doc_terms($doc, $prefix);
  4663. $xterms = [];
  4664. foreach ($xapian_terms as $xapian_term) {
  4665. $xterms[] = substr($xapian_term['name'], 1);
  4666. }
  4667. $dterms = $terms;
  4668. $missing_terms = array_diff($dterms, $xterms);
  4669. $deprecated_terms = array_diff($xterms, $dterms);
  4670. // Save it to search engine.
  4671. foreach ($missing_terms as $term) {
  4672. $doc->add_term($prefix.$term, 1);
  4673. }
  4674. foreach ($deprecated_terms as $term) {
  4675. $doc->remove_term($prefix.$term);
  4676. }
  4677. $di->getDb()->replace_document((int) $se_ref['search_did'], $doc);
  4678. $di->getDb()->flush();
  4679. }
  4680. }
  4681. return true;
  4682. }
  4683. /**
  4684. * Sets the theme of the LP (local/remote) (and save).
  4685. *
  4686. * @param string $name Optional string giving the new theme of this learnpath
  4687. *
  4688. * @return bool Returns true if theme name is not empty
  4689. */
  4690. public function set_theme($name = '')
  4691. {
  4692. $this->theme = $name;
  4693. $table = Database::get_course_table(TABLE_LP_MAIN);
  4694. $lp_id = $this->get_id();
  4695. $sql = "UPDATE $table
  4696. SET theme = '".Database::escape_string($this->theme)."'
  4697. WHERE iid = $lp_id";
  4698. Database::query($sql);
  4699. return true;
  4700. }
  4701. /**
  4702. * Sets the image of an LP (and save).
  4703. *
  4704. * @param string $name Optional string giving the new image of this learnpath
  4705. *
  4706. * @return bool Returns true if theme name is not empty
  4707. */
  4708. public function set_preview_image($name = '')
  4709. {
  4710. $this->preview_image = $name;
  4711. $table = Database::get_course_table(TABLE_LP_MAIN);
  4712. $lp_id = $this->get_id();
  4713. $sql = "UPDATE $table SET
  4714. preview_image = '".Database::escape_string($this->preview_image)."'
  4715. WHERE iid = $lp_id";
  4716. Database::query($sql);
  4717. return true;
  4718. }
  4719. /**
  4720. * Sets the author of a LP (and save).
  4721. *
  4722. * @param string $name Optional string giving the new author of this learnpath
  4723. *
  4724. * @return bool Returns true if author's name is not empty
  4725. */
  4726. public function set_author($name = '')
  4727. {
  4728. $this->author = $name;
  4729. $table = Database::get_course_table(TABLE_LP_MAIN);
  4730. $lp_id = $this->get_id();
  4731. $sql = "UPDATE $table SET author = '".Database::escape_string($name)."'
  4732. WHERE iid = $lp_id";
  4733. Database::query($sql);
  4734. return true;
  4735. }
  4736. /**
  4737. * Sets the hide_toc_frame parameter of a LP (and save).
  4738. *
  4739. * @param int $hide 1 if frame is hidden 0 then else
  4740. *
  4741. * @return bool Returns true if author's name is not empty
  4742. */
  4743. public function set_hide_toc_frame($hide)
  4744. {
  4745. if (intval($hide) == $hide) {
  4746. $this->hide_toc_frame = $hide;
  4747. $table = Database::get_course_table(TABLE_LP_MAIN);
  4748. $lp_id = $this->get_id();
  4749. $sql = "UPDATE $table SET
  4750. hide_toc_frame = '".(int) $this->hide_toc_frame."'
  4751. WHERE iid = $lp_id";
  4752. Database::query($sql);
  4753. return true;
  4754. }
  4755. return false;
  4756. }
  4757. /**
  4758. * Sets the prerequisite of a LP (and save).
  4759. *
  4760. * @param int $prerequisite integer giving the new prerequisite of this learnpath
  4761. *
  4762. * @return bool returns true if prerequisite is not empty
  4763. */
  4764. public function set_prerequisite($prerequisite)
  4765. {
  4766. $this->prerequisite = (int) $prerequisite;
  4767. $table = Database::get_course_table(TABLE_LP_MAIN);
  4768. $lp_id = $this->get_id();
  4769. $sql = "UPDATE $table SET prerequisite = '".$this->prerequisite."'
  4770. WHERE iid = $lp_id";
  4771. Database::query($sql);
  4772. return true;
  4773. }
  4774. /**
  4775. * Sets the location/proximity of the LP (local/remote) (and save).
  4776. *
  4777. * @param string $name Optional string giving the new location of this learnpath
  4778. *
  4779. * @return bool True on success / False on error
  4780. */
  4781. public function set_proximity($name = '')
  4782. {
  4783. if (empty($name)) {
  4784. return false;
  4785. }
  4786. $this->proximity = $name;
  4787. $table = Database::get_course_table(TABLE_LP_MAIN);
  4788. $lp_id = $this->get_id();
  4789. $sql = "UPDATE $table SET
  4790. content_local = '".Database::escape_string($name)."'
  4791. WHERE iid = $lp_id";
  4792. Database::query($sql);
  4793. return true;
  4794. }
  4795. /**
  4796. * Sets the previous item ID to a given ID. Generally, this should be set to the previous 'current' item.
  4797. *
  4798. * @param int $id DB ID of the item
  4799. */
  4800. public function set_previous_item($id)
  4801. {
  4802. if ($this->debug > 0) {
  4803. error_log('In learnpath::set_previous_item()', 0);
  4804. }
  4805. $this->last = $id;
  4806. }
  4807. /**
  4808. * Sets use_max_score.
  4809. *
  4810. * @param int $use_max_score Optional string giving the new location of this learnpath
  4811. *
  4812. * @return bool True on success / False on error
  4813. */
  4814. public function set_use_max_score($use_max_score = 1)
  4815. {
  4816. $use_max_score = (int) $use_max_score;
  4817. $this->use_max_score = $use_max_score;
  4818. $table = Database::get_course_table(TABLE_LP_MAIN);
  4819. $lp_id = $this->get_id();
  4820. $sql = "UPDATE $table SET
  4821. use_max_score = '".$this->use_max_score."'
  4822. WHERE iid = $lp_id";
  4823. Database::query($sql);
  4824. return true;
  4825. }
  4826. /**
  4827. * Sets and saves the expired_on date.
  4828. *
  4829. * @param string $expired_on Optional string giving the new author of this learnpath
  4830. *
  4831. * @throws \Doctrine\ORM\OptimisticLockException
  4832. *
  4833. * @return bool Returns true if author's name is not empty
  4834. */
  4835. public function set_expired_on($expired_on)
  4836. {
  4837. $em = Database::getManager();
  4838. /** @var CLp $lp */
  4839. $lp = $em
  4840. ->getRepository('ChamiloCourseBundle:CLp')
  4841. ->findOneBy(
  4842. [
  4843. 'iid' => $this->get_id(),
  4844. ]
  4845. );
  4846. if (!$lp) {
  4847. return false;
  4848. }
  4849. $this->expired_on = !empty($expired_on) ? api_get_utc_datetime($expired_on, false, true) : null;
  4850. $lp->setExpiredOn($this->expired_on);
  4851. $em->persist($lp);
  4852. $em->flush();
  4853. return true;
  4854. }
  4855. /**
  4856. * Sets and saves the publicated_on date.
  4857. *
  4858. * @param string $publicated_on Optional string giving the new author of this learnpath
  4859. *
  4860. * @throws \Doctrine\ORM\OptimisticLockException
  4861. *
  4862. * @return bool Returns true if author's name is not empty
  4863. */
  4864. public function set_publicated_on($publicated_on)
  4865. {
  4866. $em = Database::getManager();
  4867. /** @var CLp $lp */
  4868. $lp = $em
  4869. ->getRepository('ChamiloCourseBundle:CLp')
  4870. ->findOneBy(
  4871. [
  4872. 'iid' => $this->get_id(),
  4873. ]
  4874. );
  4875. if (!$lp) {
  4876. return false;
  4877. }
  4878. $this->publicated_on = !empty($publicated_on) ? api_get_utc_datetime($publicated_on, false, true) : null;
  4879. $lp->setPublicatedOn($this->publicated_on);
  4880. $em->persist($lp);
  4881. $em->flush();
  4882. return true;
  4883. }
  4884. /**
  4885. * Sets and saves the expired_on date.
  4886. *
  4887. * @return bool Returns true if author's name is not empty
  4888. */
  4889. public function set_modified_on()
  4890. {
  4891. $this->modified_on = api_get_utc_datetime();
  4892. $table = Database::get_course_table(TABLE_LP_MAIN);
  4893. $lp_id = $this->get_id();
  4894. $sql = "UPDATE $table SET modified_on = '".$this->modified_on."'
  4895. WHERE iid = $lp_id";
  4896. Database::query($sql);
  4897. return true;
  4898. }
  4899. /**
  4900. * Sets the object's error message.
  4901. *
  4902. * @param string $error Error message. If empty, reinits the error string
  4903. */
  4904. public function set_error_msg($error = '')
  4905. {
  4906. if ($this->debug > 0) {
  4907. error_log('In learnpath::set_error_msg()', 0);
  4908. }
  4909. if (empty($error)) {
  4910. $this->error = '';
  4911. } else {
  4912. $this->error .= $error;
  4913. }
  4914. }
  4915. /**
  4916. * Launches the current item if not 'sco'
  4917. * (starts timer and make sure there is a record ready in the DB).
  4918. *
  4919. * @param bool $allow_new_attempt Whether to allow a new attempt or not
  4920. *
  4921. * @return bool
  4922. */
  4923. public function start_current_item($allow_new_attempt = false)
  4924. {
  4925. $debug = $this->debug;
  4926. if ($debug) {
  4927. error_log('In learnpath::start_current_item()');
  4928. error_log('current: '.$this->current);
  4929. }
  4930. if ($this->current != 0 && isset($this->items[$this->current]) && is_object($this->items[$this->current])) {
  4931. $type = $this->get_type();
  4932. $item_type = $this->items[$this->current]->get_type();
  4933. if (($type == 2 && $item_type != 'sco') ||
  4934. ($type == 3 && $item_type != 'au') ||
  4935. ($type == 1 && $item_type != TOOL_QUIZ && $item_type != TOOL_HOTPOTATOES)
  4936. ) {
  4937. if ($debug) {
  4938. error_log('item type: '.$item_type);
  4939. error_log('lp type: '.$type);
  4940. }
  4941. $this->items[$this->current]->open($allow_new_attempt);
  4942. $this->autocomplete_parents($this->current);
  4943. $prereq_check = $this->prerequisites_match($this->current);
  4944. if ($debug) {
  4945. error_log('start_current_item will save item with prereq: '.$prereq_check);
  4946. }
  4947. $this->items[$this->current]->save(false, $prereq_check);
  4948. }
  4949. // If sco, then it is supposed to have been updated by some other call.
  4950. if ($item_type == 'sco') {
  4951. $this->items[$this->current]->restart();
  4952. }
  4953. }
  4954. if ($debug) {
  4955. error_log('lp_view_session_id');
  4956. error_log($this->lp_view_session_id);
  4957. error_log('api session id');
  4958. error_log(api_get_session_id());
  4959. error_log('End of learnpath::start_current_item()');
  4960. }
  4961. return true;
  4962. }
  4963. /**
  4964. * Stops the processing and counters for the old item (as held in $this->last).
  4965. *
  4966. * @return bool True/False
  4967. */
  4968. public function stop_previous_item()
  4969. {
  4970. $debug = $this->debug;
  4971. if ($debug) {
  4972. error_log('In learnpath::stop_previous_item()', 0);
  4973. }
  4974. if ($this->last != 0 && $this->last != $this->current &&
  4975. isset($this->items[$this->last]) && is_object($this->items[$this->last])
  4976. ) {
  4977. if ($debug) {
  4978. error_log('In learnpath::stop_previous_item() - '.$this->last.' is object');
  4979. }
  4980. switch ($this->get_type()) {
  4981. case '3':
  4982. if ($this->items[$this->last]->get_type() != 'au') {
  4983. if ($debug) {
  4984. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 3 is <> au');
  4985. }
  4986. $this->items[$this->last]->close();
  4987. } else {
  4988. if ($debug) {
  4989. error_log('In learnpath::stop_previous_item() - Item is an AU, saving is managed by AICC signals');
  4990. }
  4991. }
  4992. break;
  4993. case '2':
  4994. if ($this->items[$this->last]->get_type() != 'sco') {
  4995. if ($debug) {
  4996. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 2 is <> sco');
  4997. }
  4998. $this->items[$this->last]->close();
  4999. } else {
  5000. if ($debug) {
  5001. error_log('In learnpath::stop_previous_item() - Item is a SCO, saving is managed by SCO signals');
  5002. }
  5003. }
  5004. break;
  5005. case '1':
  5006. default:
  5007. if ($debug) {
  5008. error_log('In learnpath::stop_previous_item() - '.$this->last.' in lp_type 1 is asset');
  5009. }
  5010. $this->items[$this->last]->close();
  5011. break;
  5012. }
  5013. } else {
  5014. if ($debug) {
  5015. error_log('In learnpath::stop_previous_item() - No previous element found, ignoring...');
  5016. }
  5017. return false;
  5018. }
  5019. return true;
  5020. }
  5021. /**
  5022. * Updates the default view mode from fullscreen to embedded and inversely.
  5023. *
  5024. * @return string The current default view mode ('fullscreen' or 'embedded')
  5025. */
  5026. public function update_default_view_mode()
  5027. {
  5028. $table = Database::get_course_table(TABLE_LP_MAIN);
  5029. $sql = "SELECT * FROM $table
  5030. WHERE iid = ".$this->get_id();
  5031. $res = Database::query($sql);
  5032. if (Database::num_rows($res) > 0) {
  5033. $row = Database::fetch_array($res);
  5034. $default_view_mode = $row['default_view_mod'];
  5035. $view_mode = $default_view_mode;
  5036. switch ($default_view_mode) {
  5037. case 'fullscreen': // default with popup
  5038. $view_mode = 'embedded';
  5039. break;
  5040. case 'embedded': // default view with left menu
  5041. $view_mode = 'embedframe';
  5042. break;
  5043. case 'embedframe': //folded menu
  5044. $view_mode = 'impress';
  5045. break;
  5046. case 'impress':
  5047. $view_mode = 'fullscreen';
  5048. break;
  5049. }
  5050. $sql = "UPDATE $table SET default_view_mod = '$view_mode'
  5051. WHERE iid = ".$this->get_id();
  5052. Database::query($sql);
  5053. $this->mode = $view_mode;
  5054. return $view_mode;
  5055. }
  5056. return -1;
  5057. }
  5058. /**
  5059. * Updates the default behaviour about auto-commiting SCORM updates.
  5060. *
  5061. * @return bool True if auto-commit has been set to 'on', false otherwise
  5062. */
  5063. public function update_default_scorm_commit()
  5064. {
  5065. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5066. $sql = "SELECT * FROM $lp_table
  5067. WHERE iid = ".$this->get_id();
  5068. $res = Database::query($sql);
  5069. if (Database::num_rows($res) > 0) {
  5070. $row = Database::fetch_array($res);
  5071. $force = $row['force_commit'];
  5072. if ($force == 1) {
  5073. $force = 0;
  5074. $force_return = false;
  5075. } elseif ($force == 0) {
  5076. $force = 1;
  5077. $force_return = true;
  5078. }
  5079. $sql = "UPDATE $lp_table SET force_commit = $force
  5080. WHERE iid = ".$this->get_id();
  5081. Database::query($sql);
  5082. $this->force_commit = $force_return;
  5083. return $force_return;
  5084. }
  5085. return -1;
  5086. }
  5087. /**
  5088. * Updates the order of learning paths (goes through all of them by order and fills the gaps).
  5089. *
  5090. * @return bool True on success, false on failure
  5091. */
  5092. public function update_display_order()
  5093. {
  5094. $course_id = api_get_course_int_id();
  5095. $table = Database::get_course_table(TABLE_LP_MAIN);
  5096. $sql = "SELECT * FROM $table
  5097. WHERE c_id = $course_id
  5098. ORDER BY display_order";
  5099. $res = Database::query($sql);
  5100. if ($res === false) {
  5101. return false;
  5102. }
  5103. $num = Database::num_rows($res);
  5104. // First check the order is correct, globally (might be wrong because
  5105. // of versions < 1.8.4).
  5106. if ($num > 0) {
  5107. $i = 1;
  5108. while ($row = Database::fetch_array($res)) {
  5109. if ($row['display_order'] != $i) {
  5110. // If we find a gap in the order, we need to fix it.
  5111. $sql = "UPDATE $table SET display_order = $i
  5112. WHERE iid = ".$row['iid'];
  5113. Database::query($sql);
  5114. }
  5115. $i++;
  5116. }
  5117. }
  5118. return true;
  5119. }
  5120. /**
  5121. * Updates the "prevent_reinit" value that enables control on reinitialising items on second view.
  5122. *
  5123. * @return bool True if prevent_reinit has been set to 'on', false otherwise (or 1 or 0 in this case)
  5124. */
  5125. public function update_reinit()
  5126. {
  5127. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5128. $sql = "SELECT * FROM $lp_table
  5129. WHERE iid = ".$this->get_id();
  5130. $res = Database::query($sql);
  5131. if (Database::num_rows($res) > 0) {
  5132. $row = Database::fetch_array($res);
  5133. $force = $row['prevent_reinit'];
  5134. if ($force == 1) {
  5135. $force = 0;
  5136. } elseif ($force == 0) {
  5137. $force = 1;
  5138. }
  5139. $sql = "UPDATE $lp_table SET prevent_reinit = $force
  5140. WHERE iid = ".$this->get_id();
  5141. Database::query($sql);
  5142. $this->prevent_reinit = $force;
  5143. return $force;
  5144. }
  5145. return -1;
  5146. }
  5147. /**
  5148. * Determine the attempt_mode thanks to prevent_reinit and seriousgame_mode db flag.
  5149. *
  5150. * @return string 'single', 'multi' or 'seriousgame'
  5151. *
  5152. * @author ndiechburg <noel@cblue.be>
  5153. */
  5154. public function get_attempt_mode()
  5155. {
  5156. //Set default value for seriousgame_mode
  5157. if (!isset($this->seriousgame_mode)) {
  5158. $this->seriousgame_mode = 0;
  5159. }
  5160. // Set default value for prevent_reinit
  5161. if (!isset($this->prevent_reinit)) {
  5162. $this->prevent_reinit = 1;
  5163. }
  5164. if ($this->seriousgame_mode == 1 && $this->prevent_reinit == 1) {
  5165. return 'seriousgame';
  5166. }
  5167. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 1) {
  5168. return 'single';
  5169. }
  5170. if ($this->seriousgame_mode == 0 && $this->prevent_reinit == 0) {
  5171. return 'multiple';
  5172. }
  5173. return 'single';
  5174. }
  5175. /**
  5176. * Register the attempt mode into db thanks to flags prevent_reinit and seriousgame_mode flags.
  5177. *
  5178. * @param string 'seriousgame', 'single' or 'multiple'
  5179. *
  5180. * @return bool
  5181. *
  5182. * @author ndiechburg <noel@cblue.be>
  5183. */
  5184. public function set_attempt_mode($mode)
  5185. {
  5186. switch ($mode) {
  5187. case 'seriousgame':
  5188. $sg_mode = 1;
  5189. $prevent_reinit = 1;
  5190. break;
  5191. case 'single':
  5192. $sg_mode = 0;
  5193. $prevent_reinit = 1;
  5194. break;
  5195. case 'multiple':
  5196. $sg_mode = 0;
  5197. $prevent_reinit = 0;
  5198. break;
  5199. default:
  5200. $sg_mode = 0;
  5201. $prevent_reinit = 0;
  5202. break;
  5203. }
  5204. $this->prevent_reinit = $prevent_reinit;
  5205. $this->seriousgame_mode = $sg_mode;
  5206. $table = Database::get_course_table(TABLE_LP_MAIN);
  5207. $sql = "UPDATE $table SET
  5208. prevent_reinit = $prevent_reinit ,
  5209. seriousgame_mode = $sg_mode
  5210. WHERE iid = ".$this->get_id();
  5211. $res = Database::query($sql);
  5212. if ($res) {
  5213. return true;
  5214. } else {
  5215. return false;
  5216. }
  5217. }
  5218. /**
  5219. * Switch between multiple attempt, single attempt or serious_game mode (only for scorm).
  5220. *
  5221. * @author ndiechburg <noel@cblue.be>
  5222. */
  5223. public function switch_attempt_mode()
  5224. {
  5225. $mode = $this->get_attempt_mode();
  5226. switch ($mode) {
  5227. case 'single':
  5228. $next_mode = 'multiple';
  5229. break;
  5230. case 'multiple':
  5231. $next_mode = 'seriousgame';
  5232. break;
  5233. case 'seriousgame':
  5234. default:
  5235. $next_mode = 'single';
  5236. break;
  5237. }
  5238. $this->set_attempt_mode($next_mode);
  5239. }
  5240. /**
  5241. * Switch the lp in ktm mode. This is a special scorm mode with unique attempt
  5242. * but possibility to do again a completed item.
  5243. *
  5244. * @return bool true if seriousgame_mode has been set to 1, false otherwise
  5245. *
  5246. * @author ndiechburg <noel@cblue.be>
  5247. */
  5248. public function set_seriousgame_mode()
  5249. {
  5250. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5251. $sql = "SELECT * FROM $lp_table
  5252. WHERE iid = ".$this->get_id();
  5253. $res = Database::query($sql);
  5254. if (Database::num_rows($res) > 0) {
  5255. $row = Database::fetch_array($res);
  5256. $force = $row['seriousgame_mode'];
  5257. if ($force == 1) {
  5258. $force = 0;
  5259. } elseif ($force == 0) {
  5260. $force = 1;
  5261. }
  5262. $sql = "UPDATE $lp_table SET seriousgame_mode = $force
  5263. WHERE iid = ".$this->get_id();
  5264. Database::query($sql);
  5265. $this->seriousgame_mode = $force;
  5266. return $force;
  5267. }
  5268. return -1;
  5269. }
  5270. /**
  5271. * Updates the "scorm_debug" value that shows or hide the debug window.
  5272. *
  5273. * @return bool True if scorm_debug has been set to 'on', false otherwise (or 1 or 0 in this case)
  5274. */
  5275. public function update_scorm_debug()
  5276. {
  5277. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  5278. $sql = "SELECT * FROM $lp_table
  5279. WHERE iid = ".$this->get_id();
  5280. $res = Database::query($sql);
  5281. if (Database::num_rows($res) > 0) {
  5282. $row = Database::fetch_array($res);
  5283. $force = $row['debug'];
  5284. if ($force == 1) {
  5285. $force = 0;
  5286. } elseif ($force == 0) {
  5287. $force = 1;
  5288. }
  5289. $sql = "UPDATE $lp_table SET debug = $force
  5290. WHERE iid = ".$this->get_id();
  5291. Database::query($sql);
  5292. $this->scorm_debug = $force;
  5293. return $force;
  5294. }
  5295. return -1;
  5296. }
  5297. /**
  5298. * Function that makes a call to the function sort_tree_array and create_tree_array.
  5299. *
  5300. * @author Kevin Van Den Haute
  5301. *
  5302. * @param array
  5303. */
  5304. public function tree_array($array)
  5305. {
  5306. $array = $this->sort_tree_array($array);
  5307. $this->create_tree_array($array);
  5308. }
  5309. /**
  5310. * Creates an array with the elements of the learning path tree in it.
  5311. *
  5312. * @author Kevin Van Den Haute
  5313. *
  5314. * @param array $array
  5315. * @param int $parent
  5316. * @param int $depth
  5317. * @param array $tmp
  5318. */
  5319. public function create_tree_array($array, $parent = 0, $depth = -1, $tmp = [])
  5320. {
  5321. if (is_array($array)) {
  5322. for ($i = 0; $i < count($array); $i++) {
  5323. if ($array[$i]['parent_item_id'] == $parent) {
  5324. if (!in_array($array[$i]['parent_item_id'], $tmp)) {
  5325. $tmp[] = $array[$i]['parent_item_id'];
  5326. $depth++;
  5327. }
  5328. $preq = (empty($array[$i]['prerequisite']) ? '' : $array[$i]['prerequisite']);
  5329. $audio = isset($array[$i]['audio']) ? $array[$i]['audio'] : null;
  5330. $path = isset($array[$i]['path']) ? $array[$i]['path'] : null;
  5331. $prerequisiteMinScore = isset($array[$i]['prerequisite_min_score']) ? $array[$i]['prerequisite_min_score'] : null;
  5332. $prerequisiteMaxScore = isset($array[$i]['prerequisite_max_score']) ? $array[$i]['prerequisite_max_score'] : null;
  5333. $ref = isset($array[$i]['ref']) ? $array[$i]['ref'] : '';
  5334. $this->arrMenu[] = [
  5335. 'id' => $array[$i]['id'],
  5336. 'ref' => $ref,
  5337. 'item_type' => $array[$i]['item_type'],
  5338. 'title' => $array[$i]['title'],
  5339. 'path' => $path,
  5340. 'description' => $array[$i]['description'],
  5341. 'parent_item_id' => $array[$i]['parent_item_id'],
  5342. 'previous_item_id' => $array[$i]['previous_item_id'],
  5343. 'next_item_id' => $array[$i]['next_item_id'],
  5344. 'min_score' => $array[$i]['min_score'],
  5345. 'max_score' => $array[$i]['max_score'],
  5346. 'mastery_score' => $array[$i]['mastery_score'],
  5347. 'display_order' => $array[$i]['display_order'],
  5348. 'prerequisite' => $preq,
  5349. 'depth' => $depth,
  5350. 'audio' => $audio,
  5351. 'prerequisite_min_score' => $prerequisiteMinScore,
  5352. 'prerequisite_max_score' => $prerequisiteMaxScore,
  5353. ];
  5354. $this->create_tree_array($array, $array[$i]['id'], $depth, $tmp);
  5355. }
  5356. }
  5357. }
  5358. }
  5359. /**
  5360. * Sorts a multi dimensional array by parent id and display order.
  5361. *
  5362. * @author Kevin Van Den Haute
  5363. *
  5364. * @param array $array (array with al the learning path items in it)
  5365. *
  5366. * @return array
  5367. */
  5368. public function sort_tree_array($array)
  5369. {
  5370. foreach ($array as $key => $row) {
  5371. $parent[$key] = $row['parent_item_id'];
  5372. $position[$key] = $row['display_order'];
  5373. }
  5374. if (count($array) > 0) {
  5375. array_multisort($parent, SORT_ASC, $position, SORT_ASC, $array);
  5376. }
  5377. return $array;
  5378. }
  5379. /**
  5380. * Function that creates a html list of learning path items so that we can add audio files to them.
  5381. *
  5382. * @author Kevin Van Den Haute
  5383. *
  5384. * @return string
  5385. */
  5386. public function overview()
  5387. {
  5388. $return = '';
  5389. $update_audio = isset($_GET['updateaudio']) ? $_GET['updateaudio'] : null;
  5390. // we need to start a form when we want to update all the mp3 files
  5391. if ($update_audio == 'true') {
  5392. $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">';
  5393. }
  5394. $return .= '<div id="message"></div>';
  5395. if (count($this->items) == 0) {
  5396. $return .= Display::return_message(get_lang('YouShouldAddItemsBeforeAttachAudio'), 'normal');
  5397. } else {
  5398. $return_audio = '<table class="data_table">';
  5399. $return_audio .= '<tr>';
  5400. $return_audio .= '<th width="40%">'.get_lang('Title').'</th>';
  5401. $return_audio .= '<th>'.get_lang('Audio').'</th>';
  5402. $return_audio .= '</tr>';
  5403. if ($update_audio != 'true') {
  5404. $return .= '<div class="col-md-12">';
  5405. $return .= self::return_new_tree($update_audio);
  5406. $return .= '</div>';
  5407. $return .= Display::div(
  5408. Display::url(get_lang('Save'), '#', ['id' => 'listSubmit', 'class' => 'btn btn-primary']),
  5409. ['style' => 'float:left; margin-top:15px;width:100%']
  5410. );
  5411. } else {
  5412. $return_audio .= self::return_new_tree($update_audio);
  5413. $return .= $return_audio.'</table>';
  5414. }
  5415. // We need to close the form when we are updating the mp3 files.
  5416. if ($update_audio == 'true') {
  5417. $return .= '<div class="footer-audio">';
  5418. $return .= Display::button(
  5419. 'save_audio',
  5420. '<em class="fa fa-file-audio-o"></em> '.get_lang('SaveAudioAndOrganization'),
  5421. ['class' => 'btn btn-primary', 'type' => 'submit']
  5422. );
  5423. $return .= '</div>';
  5424. }
  5425. }
  5426. // We need to close the form when we are updating the mp3 files.
  5427. if ($update_audio == 'true' && isset($this->arrMenu) && count($this->arrMenu) != 0) {
  5428. $return .= '</form>';
  5429. }
  5430. return $return;
  5431. }
  5432. /**
  5433. * @param string $update_audio
  5434. *
  5435. * @return array
  5436. */
  5437. public function processBuildMenuElements($update_audio = 'false')
  5438. {
  5439. $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
  5440. $arrLP = $this->getItemsForForm();
  5441. $this->tree_array($arrLP);
  5442. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  5443. unset($this->arrMenu);
  5444. $default_data = null;
  5445. $default_content = null;
  5446. $elements = [];
  5447. $return_audio = null;
  5448. $iconPath = api_get_path(SYS_CODE_PATH).'img/';
  5449. $mainUrl = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
  5450. $countItems = count($arrLP);
  5451. $upIcon = Display::return_icon(
  5452. 'up.png',
  5453. get_lang('Up'),
  5454. [],
  5455. ICON_SIZE_TINY
  5456. );
  5457. $disableUpIcon = Display::return_icon(
  5458. 'up_na.png',
  5459. get_lang('Up'),
  5460. [],
  5461. ICON_SIZE_TINY
  5462. );
  5463. $downIcon = Display::return_icon(
  5464. 'down.png',
  5465. get_lang('Down'),
  5466. [],
  5467. ICON_SIZE_TINY
  5468. );
  5469. $disableDownIcon = Display::return_icon(
  5470. 'down_na.png',
  5471. get_lang('Down'),
  5472. [],
  5473. ICON_SIZE_TINY
  5474. );
  5475. for ($i = 0; $i < $countItems; $i++) {
  5476. $parent_id = $arrLP[$i]['parent_item_id'];
  5477. $title = $arrLP[$i]['title'];
  5478. $title_cut = cut($arrLP[$i]['title'], self::MAX_LP_ITEM_TITLE_LENGTH);
  5479. // Link for the documents
  5480. if ($arrLP[$i]['item_type'] === 'document' || $arrLP[$i]['item_type'] == TOOL_READOUT_TEXT) {
  5481. $url = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5482. $title_cut = Display::url(
  5483. $title_cut,
  5484. $url,
  5485. [
  5486. 'class' => 'ajax moved',
  5487. 'data-title' => $title,
  5488. 'title' => $title,
  5489. ]
  5490. );
  5491. }
  5492. // Detect if type is FINAL_ITEM to set path_id to SESSION
  5493. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5494. Session::write('pathItem', $arrLP[$i]['path']);
  5495. }
  5496. $oddClass = 'row_even';
  5497. if (($i % 2) == 0) {
  5498. $oddClass = 'row_odd';
  5499. }
  5500. $return_audio .= '<tr id ="lp_item_'.$arrLP[$i]['id'].'" class="'.$oddClass.'">';
  5501. $icon_name = str_replace(' ', '', $arrLP[$i]['item_type']);
  5502. if (file_exists($iconPath.'lp_'.$icon_name.'.png')) {
  5503. $icon = Display::return_icon('lp_'.$icon_name.'.png');
  5504. } else {
  5505. if (file_exists($iconPath.'lp_'.$icon_name.'.gif')) {
  5506. $icon = Display::return_icon('lp_'.$icon_name.'.gif');
  5507. } else {
  5508. if ($arrLP[$i]['item_type'] === TOOL_LP_FINAL_ITEM) {
  5509. $icon = Display::return_icon('certificate.png');
  5510. } else {
  5511. $icon = Display::return_icon('folder_document.gif');
  5512. }
  5513. }
  5514. }
  5515. // The audio column.
  5516. $return_audio .= '<td align="left" style="padding-left:10px;">';
  5517. $audio = '';
  5518. if (!$update_audio || $update_audio != 'true') {
  5519. if (empty($arrLP[$i]['audio'])) {
  5520. $audio .= '';
  5521. }
  5522. } else {
  5523. $types = self::getChapterTypes();
  5524. if (!in_array($arrLP[$i]['item_type'], $types)) {
  5525. $audio .= '<input type="file" name="mp3file'.$arrLP[$i]['id'].'" id="mp3file" />';
  5526. if (!empty($arrLP[$i]['audio'])) {
  5527. $audio .= '<br />'.Security::remove_XSS($arrLP[$i]['audio']).'<br />
  5528. <input type="checkbox" name="removemp3'.$arrLP[$i]['id'].'" id="checkbox'.$arrLP[$i]['id'].'" />'.get_lang('RemoveAudio');
  5529. }
  5530. }
  5531. }
  5532. $return_audio .= Display::span($icon.' '.$title).
  5533. Display::tag(
  5534. 'td',
  5535. $audio,
  5536. ['style' => '']
  5537. );
  5538. $return_audio .= '</td>';
  5539. $move_icon = '';
  5540. $move_item_icon = '';
  5541. $edit_icon = '';
  5542. $delete_icon = '';
  5543. $audio_icon = '';
  5544. $prerequisities_icon = '';
  5545. $forumIcon = '';
  5546. $previewIcon = '';
  5547. $pluginCalendarIcon = '';
  5548. $orderIcons = '';
  5549. $pluginCalendar = api_get_plugin_setting('learning_calendar', 'enabled') === 'true';
  5550. $plugin = null;
  5551. if ($pluginCalendar) {
  5552. $plugin = LearningCalendarPlugin::create();
  5553. }
  5554. $pluginUrl = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/start.php?';
  5555. if ($is_allowed_to_edit) {
  5556. if (!$update_audio || $update_audio != 'true') {
  5557. if ($arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  5558. $move_icon .= '<a class="moved" href="#">';
  5559. $move_icon .= Display::return_icon(
  5560. 'move_everywhere.png',
  5561. get_lang('Move'),
  5562. [],
  5563. ICON_SIZE_TINY
  5564. );
  5565. $move_icon .= '</a>';
  5566. }
  5567. }
  5568. // No edit for this item types
  5569. if (!in_array($arrLP[$i]['item_type'], ['sco', 'asset', 'final_item'])) {
  5570. if ($arrLP[$i]['item_type'] != 'dir') {
  5571. $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">';
  5572. $edit_icon .= Display::return_icon(
  5573. 'edit.png',
  5574. get_lang('LearnpathEditModule'),
  5575. [],
  5576. ICON_SIZE_TINY
  5577. );
  5578. $edit_icon .= '</a>';
  5579. if (!in_array($arrLP[$i]['item_type'], ['forum', 'thread'])) {
  5580. $forumThread = null;
  5581. if (isset($this->items[$arrLP[$i]['id']])) {
  5582. $forumThread = $this->items[$arrLP[$i]['id']]->getForumThread(
  5583. $this->course_int_id,
  5584. $this->lp_session_id
  5585. );
  5586. }
  5587. if ($forumThread) {
  5588. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5589. 'action' => 'dissociate_forum',
  5590. 'id' => $arrLP[$i]['id'],
  5591. 'lp_id' => $this->lp_id,
  5592. ]);
  5593. $forumIcon = Display::url(
  5594. Display::return_icon(
  5595. 'forum.png',
  5596. get_lang('DissociateForumToLPItem'),
  5597. [],
  5598. ICON_SIZE_TINY
  5599. ),
  5600. $forumIconUrl,
  5601. ['class' => 'btn btn-default lp-btn-dissociate-forum']
  5602. );
  5603. } else {
  5604. $forumIconUrl = $mainUrl.'&'.http_build_query([
  5605. 'action' => 'create_forum',
  5606. 'id' => $arrLP[$i]['id'],
  5607. 'lp_id' => $this->lp_id,
  5608. ]);
  5609. $forumIcon = Display::url(
  5610. Display::return_icon(
  5611. 'forum.png',
  5612. get_lang('AssociateForumToLPItem'),
  5613. [],
  5614. ICON_SIZE_TINY
  5615. ),
  5616. $forumIconUrl,
  5617. ['class' => 'btn btn-default lp-btn-associate-forum']
  5618. );
  5619. }
  5620. }
  5621. } else {
  5622. $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">';
  5623. $edit_icon .= Display::return_icon(
  5624. 'edit.png',
  5625. get_lang('LearnpathEditModule'),
  5626. [],
  5627. ICON_SIZE_TINY
  5628. );
  5629. $edit_icon .= '</a>';
  5630. }
  5631. } else {
  5632. if ($arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM) {
  5633. $edit_icon .= '<a href="'.$mainUrl.'&action=edit_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'" class="btn btn-default">';
  5634. $edit_icon .= Display::return_icon(
  5635. 'edit.png',
  5636. get_lang('Edit'),
  5637. [],
  5638. ICON_SIZE_TINY
  5639. );
  5640. $edit_icon .= '</a>';
  5641. }
  5642. }
  5643. if ($pluginCalendar) {
  5644. $pluginLink = $pluginUrl.
  5645. '&action=toggle_visibility&lp_item_id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5646. $iconCalendar = Display::return_icon('agenda_na.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5647. $itemInfo = $plugin->getItemVisibility($arrLP[$i]['id']);
  5648. if ($itemInfo && $itemInfo['value'] == 1) {
  5649. $iconCalendar = Display::return_icon('agenda.png', get_lang('OneDay'), [], ICON_SIZE_TINY);
  5650. }
  5651. $pluginCalendarIcon = Display::url(
  5652. $iconCalendar,
  5653. $pluginLink,
  5654. ['class' => 'btn btn-default']
  5655. );
  5656. }
  5657. if ($arrLP[$i]['item_type'] != 'final_item') {
  5658. $orderIcons = Display::url(
  5659. $upIcon,
  5660. 'javascript:void(0)',
  5661. ['class' => 'btn btn-default order_items', 'data-dir' => 'up', 'data-id' => $arrLP[$i]['id']]
  5662. );
  5663. $orderIcons .= Display::url(
  5664. $downIcon,
  5665. 'javascript:void(0)',
  5666. ['class' => 'btn btn-default order_items', 'data-dir' => 'down', 'data-id' => $arrLP[$i]['id']]
  5667. );
  5668. }
  5669. $delete_icon .= ' <a
  5670. href="'.$mainUrl.'&action=delete_item&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id.'"
  5671. onclick="return confirmation(\''.addslashes($title).'\');"
  5672. class="btn btn-default">';
  5673. $delete_icon .= Display::return_icon(
  5674. 'delete.png',
  5675. get_lang('LearnpathDeleteModule'),
  5676. [],
  5677. ICON_SIZE_TINY
  5678. );
  5679. $delete_icon .= '</a>';
  5680. $url = $mainUrl.'&view=build&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5681. $previewImage = Display::return_icon(
  5682. 'preview_view.png',
  5683. get_lang('Preview'),
  5684. [],
  5685. ICON_SIZE_TINY
  5686. );
  5687. switch ($arrLP[$i]['item_type']) {
  5688. case TOOL_DOCUMENT:
  5689. case TOOL_LP_FINAL_ITEM:
  5690. case TOOL_READOUT_TEXT:
  5691. $urlPreviewLink = $mainUrl.'&action=view_item&mode=preview_document&id='.$arrLP[$i]['id'].'&lp_id='.$this->lp_id;
  5692. $previewIcon = Display::url(
  5693. $previewImage,
  5694. $urlPreviewLink,
  5695. [
  5696. 'target' => '_blank',
  5697. 'class' => 'btn btn-default',
  5698. 'data-title' => $arrLP[$i]['title'],
  5699. 'title' => $arrLP[$i]['title'],
  5700. ]
  5701. );
  5702. break;
  5703. case TOOL_THREAD:
  5704. case TOOL_FORUM:
  5705. case TOOL_QUIZ:
  5706. case TOOL_STUDENTPUBLICATION:
  5707. case TOOL_LP_FINAL_ITEM:
  5708. case TOOL_LINK:
  5709. $class = 'btn btn-default';
  5710. $target = '_blank';
  5711. $link = self::rl_get_resource_link_for_learnpath(
  5712. $this->course_int_id,
  5713. $this->lp_id,
  5714. $arrLP[$i]['id'],
  5715. 0
  5716. );
  5717. $previewIcon = Display::url(
  5718. $previewImage,
  5719. $link,
  5720. [
  5721. 'class' => $class,
  5722. 'data-title' => $arrLP[$i]['title'],
  5723. 'title' => $arrLP[$i]['title'],
  5724. 'target' => $target,
  5725. ]
  5726. );
  5727. break;
  5728. default:
  5729. $previewIcon = Display::url(
  5730. $previewImage,
  5731. $url.'&action=view_item',
  5732. ['class' => 'btn btn-default', 'target' => '_blank']
  5733. );
  5734. break;
  5735. }
  5736. if ($arrLP[$i]['item_type'] != 'dir') {
  5737. $prerequisities_icon = Display::url(
  5738. Display::return_icon(
  5739. 'accept.png',
  5740. get_lang('LearnpathPrerequisites'),
  5741. [],
  5742. ICON_SIZE_TINY
  5743. ),
  5744. $url.'&action=edit_item_prereq',
  5745. ['class' => 'btn btn-default']
  5746. );
  5747. if ($arrLP[$i]['item_type'] != 'final_item') {
  5748. $move_item_icon = Display::url(
  5749. Display::return_icon(
  5750. 'move.png',
  5751. get_lang('Move'),
  5752. [],
  5753. ICON_SIZE_TINY
  5754. ),
  5755. $url.'&action=move_item',
  5756. ['class' => 'btn btn-default']
  5757. );
  5758. }
  5759. $audio_icon = Display::url(
  5760. Display::return_icon(
  5761. 'audio.png',
  5762. get_lang('UplUpload'),
  5763. [],
  5764. ICON_SIZE_TINY
  5765. ),
  5766. $url.'&action=add_audio',
  5767. ['class' => 'btn btn-default']
  5768. );
  5769. }
  5770. }
  5771. if ($update_audio != 'true') {
  5772. $row = $move_icon.' '.$icon.
  5773. Display::span($title_cut).
  5774. Display::tag(
  5775. 'div',
  5776. "<div class=\"btn-group btn-group-xs\">
  5777. $previewIcon
  5778. $audio
  5779. $edit_icon
  5780. $pluginCalendarIcon
  5781. $forumIcon
  5782. $prerequisities_icon
  5783. $move_item_icon
  5784. $audio_icon
  5785. $orderIcons
  5786. $delete_icon
  5787. </div>",
  5788. ['class' => 'btn-toolbar button_actions']
  5789. );
  5790. } else {
  5791. $row =
  5792. Display::span($title.$icon).
  5793. Display::span($audio, ['class' => 'button_actions']);
  5794. }
  5795. $default_data[$arrLP[$i]['id']] = $row;
  5796. $default_content[$arrLP[$i]['id']] = $arrLP[$i];
  5797. if (empty($parent_id)) {
  5798. $elements[$arrLP[$i]['id']]['data'] = $row;
  5799. $elements[$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5800. } else {
  5801. $parent_arrays = [];
  5802. if ($arrLP[$i]['depth'] > 1) {
  5803. //Getting list of parents
  5804. for ($j = 0; $j < $arrLP[$i]['depth']; $j++) {
  5805. foreach ($arrLP as $item) {
  5806. if ($item['id'] == $parent_id) {
  5807. if ($item['parent_item_id'] == 0) {
  5808. $parent_id = $item['id'];
  5809. break;
  5810. } else {
  5811. $parent_id = $item['parent_item_id'];
  5812. if (empty($parent_arrays)) {
  5813. $parent_arrays[] = intval($item['id']);
  5814. }
  5815. $parent_arrays[] = $parent_id;
  5816. break;
  5817. }
  5818. }
  5819. }
  5820. }
  5821. }
  5822. if (!empty($parent_arrays)) {
  5823. $parent_arrays = array_reverse($parent_arrays);
  5824. $val = '$elements';
  5825. $x = 0;
  5826. foreach ($parent_arrays as $item) {
  5827. if ($x != count($parent_arrays) - 1) {
  5828. $val .= '["'.$item.'"]["children"]';
  5829. } else {
  5830. $val .= '["'.$item.'"]["children"]';
  5831. }
  5832. $x++;
  5833. }
  5834. $val .= "";
  5835. $code_str = $val."[".$arrLP[$i]['id']."][\"load_data\"] = '".$arrLP[$i]['id']."' ; ";
  5836. eval($code_str);
  5837. } else {
  5838. $elements[$parent_id]['children'][$arrLP[$i]['id']]['data'] = $row;
  5839. $elements[$parent_id]['children'][$arrLP[$i]['id']]['type'] = $arrLP[$i]['item_type'];
  5840. }
  5841. }
  5842. }
  5843. return [
  5844. 'elements' => $elements,
  5845. 'default_data' => $default_data,
  5846. 'default_content' => $default_content,
  5847. 'return_audio' => $return_audio,
  5848. ];
  5849. }
  5850. /**
  5851. * @param string $updateAudio true/false strings
  5852. *
  5853. * @return string
  5854. */
  5855. public function returnLpItemList($updateAudio)
  5856. {
  5857. $result = $this->processBuildMenuElements($updateAudio);
  5858. $html = self::print_recursive(
  5859. $result['elements'],
  5860. $result['default_data'],
  5861. $result['default_content']
  5862. );
  5863. if (!empty($html)) {
  5864. $html .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5865. }
  5866. return $html;
  5867. }
  5868. /**
  5869. * @param string $update_audio
  5870. * @param bool $drop_element_here
  5871. *
  5872. * @return string
  5873. */
  5874. public function return_new_tree($update_audio = 'false', $drop_element_here = false)
  5875. {
  5876. $result = $this->processBuildMenuElements($update_audio);
  5877. $list = '<ul id="lp_item_list">';
  5878. $tree = $this->print_recursive(
  5879. $result['elements'],
  5880. $result['default_data'],
  5881. $result['default_content']
  5882. );
  5883. if (!empty($tree)) {
  5884. $list .= $tree;
  5885. } else {
  5886. if ($drop_element_here) {
  5887. $list .= Display::return_message(get_lang('DragAndDropAnElementHere'));
  5888. }
  5889. }
  5890. $list .= '</ul>';
  5891. $return = Display::panelCollapse(
  5892. $this->name,
  5893. $list,
  5894. 'scorm-list',
  5895. null,
  5896. 'scorm-list-accordion',
  5897. 'scorm-list-collapse'
  5898. );
  5899. if ($update_audio === 'true') {
  5900. $return = $result['return_audio'];
  5901. }
  5902. return $return;
  5903. }
  5904. /**
  5905. * @param array $elements
  5906. * @param array $default_data
  5907. * @param array $default_content
  5908. *
  5909. * @return string
  5910. */
  5911. public function print_recursive($elements, $default_data, $default_content)
  5912. {
  5913. $return = '';
  5914. foreach ($elements as $key => $item) {
  5915. if (isset($item['load_data']) || empty($item['data'])) {
  5916. $item['data'] = $default_data[$item['load_data']];
  5917. $item['type'] = $default_content[$item['load_data']]['item_type'];
  5918. }
  5919. $sub_list = '';
  5920. if (isset($item['type']) && $item['type'] === 'dir') {
  5921. // empty value
  5922. $sub_list = Display::tag('li', '', ['class' => 'sub_item empty']);
  5923. }
  5924. if (empty($item['children'])) {
  5925. $sub_list = Display::tag('ul', $sub_list, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5926. $active = null;
  5927. if (isset($_REQUEST['id']) && $key == $_REQUEST['id']) {
  5928. $active = 'active';
  5929. }
  5930. $return .= Display::tag(
  5931. 'li',
  5932. Display::div($item['data'], ['class' => "item_data $active"]).$sub_list,
  5933. ['id' => $key, 'class' => 'record li_container']
  5934. );
  5935. } else {
  5936. // Sections
  5937. $data = '';
  5938. if (isset($item['children'])) {
  5939. $data = self::print_recursive($item['children'], $default_data, $default_content);
  5940. }
  5941. $sub_list = Display::tag('ul', $sub_list.$data, ['id' => 'UL_'.$key, 'class' => 'record li_container']);
  5942. $return .= Display::tag(
  5943. 'li',
  5944. Display::div($item['data'], ['class' => 'item_data']).$sub_list,
  5945. ['id' => $key, 'class' => 'record li_container']
  5946. );
  5947. }
  5948. }
  5949. return $return;
  5950. }
  5951. /**
  5952. * This function builds the action menu.
  5953. *
  5954. * @param bool $returnContent Optional
  5955. * @param bool $showRequirementButtons Optional. Allow show the requirements button
  5956. * @param bool $isConfigPage Optional. If is the config page, show the edit button
  5957. * @param bool $allowExpand Optional. Allow show the expand/contract button
  5958. *
  5959. * @return string
  5960. */
  5961. public function build_action_menu(
  5962. $returnContent = false,
  5963. $showRequirementButtons = true,
  5964. $isConfigPage = false,
  5965. $allowExpand = true
  5966. ) {
  5967. $actionsLeft = '';
  5968. $actionsRight = '';
  5969. $actionsLeft .= Display::url(
  5970. Display::return_icon(
  5971. 'back.png',
  5972. get_lang('ReturnToLearningPaths'),
  5973. '',
  5974. ICON_SIZE_MEDIUM
  5975. ),
  5976. 'lp_controller.php?'.api_get_cidreq()
  5977. );
  5978. $actionsLeft .= Display::url(
  5979. Display::return_icon(
  5980. 'preview_view.png',
  5981. get_lang('Preview'),
  5982. '',
  5983. ICON_SIZE_MEDIUM
  5984. ),
  5985. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5986. 'action' => 'view',
  5987. 'lp_id' => $this->lp_id,
  5988. 'isStudentView' => 'true',
  5989. ])
  5990. );
  5991. $actionsLeft .= Display::url(
  5992. Display::return_icon(
  5993. 'upload_audio.png',
  5994. get_lang('UpdateAllAudioFragments'),
  5995. '',
  5996. ICON_SIZE_MEDIUM
  5997. ),
  5998. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  5999. 'action' => 'admin_view',
  6000. 'lp_id' => $this->lp_id,
  6001. 'updateaudio' => 'true',
  6002. ])
  6003. );
  6004. if (!$isConfigPage) {
  6005. $actionsLeft .= Display::url(
  6006. Display::return_icon(
  6007. 'settings.png',
  6008. get_lang('CourseSettings'),
  6009. '',
  6010. ICON_SIZE_MEDIUM
  6011. ),
  6012. 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6013. 'action' => 'edit',
  6014. 'lp_id' => $this->lp_id,
  6015. ])
  6016. );
  6017. } else {
  6018. $actionsLeft .= Display::url(
  6019. Display::return_icon(
  6020. 'edit.png',
  6021. get_lang('Edit'),
  6022. '',
  6023. ICON_SIZE_MEDIUM
  6024. ),
  6025. 'lp_controller.php?'.http_build_query([
  6026. 'action' => 'build',
  6027. 'lp_id' => $this->lp_id,
  6028. ]).'&'.api_get_cidreq()
  6029. );
  6030. }
  6031. if ($allowExpand) {
  6032. $actionsLeft .= Display::url(
  6033. Display::return_icon(
  6034. 'expand.png',
  6035. get_lang('Expand'),
  6036. ['id' => 'expand'],
  6037. ICON_SIZE_MEDIUM
  6038. ).
  6039. Display::return_icon(
  6040. 'contract.png',
  6041. get_lang('Collapse'),
  6042. ['id' => 'contract', 'class' => 'hide'],
  6043. ICON_SIZE_MEDIUM
  6044. ),
  6045. '#',
  6046. ['role' => 'button', 'id' => 'hide_bar_template']
  6047. );
  6048. }
  6049. if ($showRequirementButtons) {
  6050. $buttons = [
  6051. [
  6052. 'title' => get_lang('SetPrerequisiteForEachItem'),
  6053. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6054. 'action' => 'set_previous_step_as_prerequisite',
  6055. 'lp_id' => $this->lp_id,
  6056. ]),
  6057. ],
  6058. [
  6059. 'title' => get_lang('ClearAllPrerequisites'),
  6060. 'href' => 'lp_controller.php?'.api_get_cidreq().'&'.http_build_query([
  6061. 'action' => 'clear_prerequisites',
  6062. 'lp_id' => $this->lp_id,
  6063. ]),
  6064. ],
  6065. ];
  6066. $actionsRight = Display::groupButtonWithDropDown(
  6067. get_lang('PrerequisitesOptions'),
  6068. $buttons,
  6069. true
  6070. );
  6071. }
  6072. $toolbar = Display::toolbarAction(
  6073. 'actions-lp-controller',
  6074. [$actionsLeft, $actionsRight]
  6075. );
  6076. if ($returnContent) {
  6077. return $toolbar;
  6078. }
  6079. echo $toolbar;
  6080. }
  6081. /**
  6082. * Creates the default learning path folder.
  6083. *
  6084. * @param array $course
  6085. * @param int $creatorId
  6086. *
  6087. * @return bool
  6088. */
  6089. public static function generate_learning_path_folder($course, $creatorId = 0)
  6090. {
  6091. // Creating learning_path folder
  6092. $dir = '/learning_path';
  6093. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6094. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6095. $folder = false;
  6096. if (!is_dir($filepath.'/'.$dir)) {
  6097. $folderData = create_unexisting_directory(
  6098. $course,
  6099. $creatorId,
  6100. 0,
  6101. null,
  6102. 0,
  6103. $filepath,
  6104. $dir,
  6105. get_lang('LearningPaths'),
  6106. 0
  6107. );
  6108. if (!empty($folderData)) {
  6109. $folder = true;
  6110. }
  6111. } else {
  6112. $folder = true;
  6113. }
  6114. return $folder;
  6115. }
  6116. /**
  6117. * @param array $course
  6118. * @param string $lp_name
  6119. * @param int $creatorId
  6120. *
  6121. * @return array
  6122. */
  6123. public function generate_lp_folder($course, $lp_name = '', $creatorId = 0)
  6124. {
  6125. $filepath = '';
  6126. $dir = '/learning_path/';
  6127. if (empty($lp_name)) {
  6128. $lp_name = $this->name;
  6129. }
  6130. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6131. $folder = self::generate_learning_path_folder($course, $creatorId);
  6132. // Limits title size
  6133. $title = api_substr(api_replace_dangerous_char($lp_name), 0, 80);
  6134. $dir = $dir.$title;
  6135. // Creating LP folder
  6136. $documentId = null;
  6137. if ($folder) {
  6138. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document';
  6139. if (!is_dir($filepath.'/'.$dir)) {
  6140. $folderData = create_unexisting_directory(
  6141. $course,
  6142. $creatorId,
  6143. 0,
  6144. 0,
  6145. 0,
  6146. $filepath,
  6147. $dir,
  6148. $lp_name
  6149. );
  6150. if (!empty($folderData)) {
  6151. $folder = true;
  6152. }
  6153. $documentId = $folderData['id'];
  6154. } else {
  6155. $folder = true;
  6156. }
  6157. $dir = $dir.'/';
  6158. if ($folder) {
  6159. $filepath = api_get_path(SYS_COURSE_PATH).$course['path'].'/document'.$dir;
  6160. }
  6161. }
  6162. if (empty($documentId)) {
  6163. $dir = api_remove_trailing_slash($dir);
  6164. $documentId = DocumentManager::get_document_id($course, $dir, 0);
  6165. }
  6166. $array = [
  6167. 'dir' => $dir,
  6168. 'filepath' => $filepath,
  6169. 'folder' => $folder,
  6170. 'id' => $documentId,
  6171. ];
  6172. return $array;
  6173. }
  6174. /**
  6175. * Create a new document //still needs some finetuning.
  6176. *
  6177. * @param array $courseInfo
  6178. * @param string $content
  6179. * @param string $title
  6180. * @param string $extension
  6181. * @param int $parentId
  6182. * @param int $creatorId creator id
  6183. *
  6184. * @return int
  6185. */
  6186. public function create_document(
  6187. $courseInfo,
  6188. $content = '',
  6189. $title = '',
  6190. $extension = 'html',
  6191. $parentId = 0,
  6192. $creatorId = 0
  6193. ) {
  6194. if (!empty($courseInfo)) {
  6195. $course_id = $courseInfo['real_id'];
  6196. } else {
  6197. $course_id = api_get_course_int_id();
  6198. }
  6199. $creatorId = empty($creatorId) ? api_get_user_id() : $creatorId;
  6200. $sessionId = api_get_session_id();
  6201. // Generates folder
  6202. $result = $this->generate_lp_folder($courseInfo);
  6203. $dir = $result['dir'];
  6204. if (empty($parentId) || $parentId == '/') {
  6205. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  6206. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  6207. if ($parentId === '/') {
  6208. $dir = '/';
  6209. }
  6210. // Please, do not modify this dirname formatting.
  6211. if (strstr($dir, '..')) {
  6212. $dir = '/';
  6213. }
  6214. if (!empty($dir[0]) && $dir[0] == '.') {
  6215. $dir = substr($dir, 1);
  6216. }
  6217. if (!empty($dir[0]) && $dir[0] != '/') {
  6218. $dir = '/'.$dir;
  6219. }
  6220. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6221. $dir .= '/';
  6222. }
  6223. } else {
  6224. $parentInfo = DocumentManager::get_document_data_by_id(
  6225. $parentId,
  6226. $courseInfo['code']
  6227. );
  6228. if (!empty($parentInfo)) {
  6229. $dir = $parentInfo['path'].'/';
  6230. }
  6231. }
  6232. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6233. if (!is_dir($filepath)) {
  6234. $dir = '/';
  6235. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  6236. }
  6237. // stripslashes() before calling api_replace_dangerous_char() because $_POST['title']
  6238. // is already escaped twice when it gets here.
  6239. $originalTitle = !empty($title) ? $title : $_POST['title'];
  6240. if (!empty($title)) {
  6241. $title = api_replace_dangerous_char(stripslashes($title));
  6242. } else {
  6243. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  6244. }
  6245. $title = disable_dangerous_file($title);
  6246. $filename = $title;
  6247. $content = !empty($content) ? $content : $_POST['content_lp'];
  6248. $tmp_filename = $filename;
  6249. $i = 0;
  6250. while (file_exists($filepath.$tmp_filename.'.'.$extension)) {
  6251. $tmp_filename = $filename.'_'.++$i;
  6252. }
  6253. $filename = $tmp_filename.'.'.$extension;
  6254. if ($extension == 'html') {
  6255. $content = stripslashes($content);
  6256. $content = str_replace(
  6257. api_get_path(WEB_COURSE_PATH),
  6258. api_get_path(REL_PATH).'courses/',
  6259. $content
  6260. );
  6261. // Change the path of mp3 to absolute.
  6262. // The first regexp deals with :// urls.
  6263. $content = preg_replace(
  6264. "|(flashvars=\"file=)([^:/]+)/|",
  6265. "$1".api_get_path(
  6266. REL_COURSE_PATH
  6267. ).$courseInfo['path'].'/document/',
  6268. $content
  6269. );
  6270. // The second regexp deals with audio/ urls.
  6271. $content = preg_replace(
  6272. "|(flashvars=\"file=)([^/]+)/|",
  6273. "$1".api_get_path(
  6274. REL_COURSE_PATH
  6275. ).$courseInfo['path'].'/document/$2/',
  6276. $content
  6277. );
  6278. // For flv player: To prevent edition problem with firefox,
  6279. // we have to use a strange tip (don't blame me please).
  6280. $content = str_replace(
  6281. '</body>',
  6282. '<style type="text/css">body{}</style></body>',
  6283. $content
  6284. );
  6285. }
  6286. if (!file_exists($filepath.$filename)) {
  6287. if ($fp = @fopen($filepath.$filename, 'w')) {
  6288. fputs($fp, $content);
  6289. fclose($fp);
  6290. $file_size = filesize($filepath.$filename);
  6291. $save_file_path = $dir.$filename;
  6292. $document_id = add_document(
  6293. $courseInfo,
  6294. $save_file_path,
  6295. 'file',
  6296. $file_size,
  6297. $tmp_filename,
  6298. '',
  6299. 0, //readonly
  6300. true,
  6301. null,
  6302. $sessionId,
  6303. $creatorId
  6304. );
  6305. if ($document_id) {
  6306. api_item_property_update(
  6307. $courseInfo,
  6308. TOOL_DOCUMENT,
  6309. $document_id,
  6310. 'DocumentAdded',
  6311. $creatorId,
  6312. null,
  6313. null,
  6314. null,
  6315. null,
  6316. $sessionId
  6317. );
  6318. $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  6319. $new_title = $originalTitle;
  6320. if ($new_comment || $new_title) {
  6321. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6322. $ct = '';
  6323. if ($new_comment) {
  6324. $ct .= ", comment='".Database::escape_string($new_comment)."'";
  6325. }
  6326. if ($new_title) {
  6327. $ct .= ", title='".Database::escape_string($new_title)."' ";
  6328. }
  6329. $sql = "UPDATE ".$tbl_doc." SET ".substr($ct, 1)."
  6330. WHERE c_id = ".$course_id." AND id = ".$document_id;
  6331. Database::query($sql);
  6332. }
  6333. }
  6334. return $document_id;
  6335. }
  6336. }
  6337. }
  6338. /**
  6339. * Edit a document based on $_POST and $_GET parameters 'dir' and 'path'.
  6340. *
  6341. * @param array $_course array
  6342. */
  6343. public function edit_document($_course)
  6344. {
  6345. $course_id = api_get_course_int_id();
  6346. $urlAppend = api_get_configuration_value('url_append');
  6347. // Please, do not modify this dirname formatting.
  6348. $postDir = isset($_POST['dir']) ? $_POST['dir'] : '';
  6349. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir;
  6350. if (strstr($dir, '..')) {
  6351. $dir = '/';
  6352. }
  6353. if (isset($dir[0]) && $dir[0] == '.') {
  6354. $dir = substr($dir, 1);
  6355. }
  6356. if (isset($dir[0]) && $dir[0] != '/') {
  6357. $dir = '/'.$dir;
  6358. }
  6359. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  6360. $dir .= '/';
  6361. }
  6362. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
  6363. if (!is_dir($filepath)) {
  6364. $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
  6365. }
  6366. $table_doc = Database::get_course_table(TABLE_DOCUMENT);
  6367. if (isset($_POST['path']) && !empty($_POST['path'])) {
  6368. $document_id = (int) $_POST['path'];
  6369. $documentInfo = DocumentManager::get_document_data_by_id($document_id, api_get_course_id(), false, null, true);
  6370. if (empty($documentInfo)) {
  6371. // Try with iid
  6372. $table = Database::get_course_table(TABLE_DOCUMENT);
  6373. $sql = "SELECT id, path FROM $table
  6374. WHERE c_id = $course_id AND iid = $document_id AND path NOT LIKE '%_DELETED_%' ";
  6375. $res_doc = Database::query($sql);
  6376. $row = Database::fetch_array($res_doc);
  6377. if ($row) {
  6378. $document_id = $row['id'];
  6379. $documentPath = $row['path'];
  6380. }
  6381. } else {
  6382. $documentPath = $documentInfo['path'];
  6383. }
  6384. $content = stripslashes($_POST['content_lp']);
  6385. $file = $filepath.$documentPath;
  6386. if (!file_exists($file)) {
  6387. return false;
  6388. }
  6389. if ($fp = @fopen($file, 'w')) {
  6390. $content = str_replace(
  6391. api_get_path(WEB_COURSE_PATH),
  6392. $urlAppend.api_get_path(REL_COURSE_PATH),
  6393. $content
  6394. );
  6395. // Change the path of mp3 to absolute.
  6396. // The first regexp deals with :// urls.
  6397. $content = preg_replace(
  6398. "|(flashvars=\"file=)([^:/]+)/|",
  6399. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/',
  6400. $content
  6401. );
  6402. // The second regexp deals with audio/ urls.
  6403. $content = preg_replace(
  6404. "|(flashvars=\"file=)([^:/]+)/|",
  6405. "$1".api_get_path(REL_COURSE_PATH).$_course['path'].'/document/$2/',
  6406. $content
  6407. );
  6408. fputs($fp, $content);
  6409. fclose($fp);
  6410. $sql = "UPDATE $table_doc SET
  6411. title='".Database::escape_string($_POST['title'])."'
  6412. WHERE c_id = $course_id AND id = ".$document_id;
  6413. Database::query($sql);
  6414. }
  6415. }
  6416. }
  6417. /**
  6418. * Displays the selected item, with a panel for manipulating the item.
  6419. *
  6420. * @param int $item_id
  6421. * @param string $msg
  6422. * @param bool $show_actions
  6423. *
  6424. * @return string
  6425. */
  6426. public function display_item($item_id, $msg = null, $show_actions = true)
  6427. {
  6428. $course_id = api_get_course_int_id();
  6429. $return = '';
  6430. if (is_numeric($item_id)) {
  6431. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6432. $sql = "SELECT lp.* FROM $tbl_lp_item as lp
  6433. WHERE lp.iid = ".intval($item_id);
  6434. $result = Database::query($sql);
  6435. while ($row = Database::fetch_array($result, 'ASSOC')) {
  6436. $_SESSION['parent_item_id'] = $row['item_type'] == 'dir' ? $item_id : 0;
  6437. // Prevents wrong parent selection for document, see Bug#1251.
  6438. if ($row['item_type'] != 'dir') {
  6439. $_SESSION['parent_item_id'] = $row['parent_item_id'];
  6440. }
  6441. if ($show_actions) {
  6442. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6443. }
  6444. $return .= '<div style="padding:10px;">';
  6445. if ($msg != '') {
  6446. $return .= $msg;
  6447. }
  6448. $return .= '<h3>'.$row['title'].'</h3>';
  6449. switch ($row['item_type']) {
  6450. case TOOL_THREAD:
  6451. $link = $this->rl_get_resource_link_for_learnpath(
  6452. $course_id,
  6453. $row['lp_id'],
  6454. $item_id,
  6455. 0
  6456. );
  6457. $return .= Display::url(
  6458. get_lang('GoToThread'),
  6459. $link,
  6460. ['class' => 'btn btn-primary']
  6461. );
  6462. break;
  6463. case TOOL_FORUM:
  6464. $return .= Display::url(
  6465. get_lang('GoToForum'),
  6466. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$row['path'],
  6467. ['class' => 'btn btn-primary']
  6468. );
  6469. break;
  6470. case TOOL_QUIZ:
  6471. if (!empty($row['path'])) {
  6472. $exercise = new Exercise();
  6473. $exercise->read($row['path']);
  6474. $return .= $exercise->description.'<br />';
  6475. $return .= Display::url(
  6476. get_lang('GoToExercise'),
  6477. api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$exercise->id,
  6478. ['class' => 'btn btn-primary']
  6479. );
  6480. }
  6481. break;
  6482. case TOOL_LP_FINAL_ITEM:
  6483. $return .= $this->getSavedFinalItem();
  6484. break;
  6485. case TOOL_DOCUMENT:
  6486. case TOOL_READOUT_TEXT:
  6487. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6488. $sql_doc = "SELECT path FROM $tbl_doc
  6489. WHERE c_id = $course_id AND iid = ".intval($row['path']);
  6490. $result = Database::query($sql_doc);
  6491. $path_file = Database::result($result, 0, 0);
  6492. $path_parts = pathinfo($path_file);
  6493. // TODO: Correct the following naive comparisons.
  6494. if (in_array($path_parts['extension'], [
  6495. 'html',
  6496. 'txt',
  6497. 'png',
  6498. 'jpg',
  6499. 'JPG',
  6500. 'jpeg',
  6501. 'JPEG',
  6502. 'gif',
  6503. 'swf',
  6504. 'pdf',
  6505. 'htm',
  6506. ])) {
  6507. $return .= $this->display_document($row['path'], true, true);
  6508. }
  6509. break;
  6510. case TOOL_HOTPOTATOES:
  6511. $return .= $this->display_document($row['path'], false, true);
  6512. break;
  6513. }
  6514. $return .= '</div>';
  6515. }
  6516. }
  6517. return $return;
  6518. }
  6519. /**
  6520. * Shows the needed forms for editing a specific item.
  6521. *
  6522. * @param int $item_id
  6523. *
  6524. * @throws Exception
  6525. * @throws HTML_QuickForm_Error
  6526. *
  6527. * @return string
  6528. */
  6529. public function display_edit_item($item_id)
  6530. {
  6531. $course_id = api_get_course_int_id();
  6532. $return = '';
  6533. $item_id = (int) $item_id;
  6534. if (empty($item_id)) {
  6535. return '';
  6536. }
  6537. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  6538. $sql = "SELECT * FROM $tbl_lp_item
  6539. WHERE iid = ".$item_id;
  6540. $res = Database::query($sql);
  6541. $row = Database::fetch_array($res);
  6542. switch ($row['item_type']) {
  6543. case 'dir':
  6544. case 'asset':
  6545. case 'sco':
  6546. if (isset($_GET['view']) && $_GET['view'] == 'build') {
  6547. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6548. $return .= $this->display_item_form(
  6549. $row['item_type'],
  6550. get_lang('EditCurrentChapter').' :',
  6551. 'edit',
  6552. $item_id,
  6553. $row
  6554. );
  6555. } else {
  6556. $return .= $this->display_item_form(
  6557. $row['item_type'],
  6558. get_lang('EditCurrentChapter').' :',
  6559. 'edit_item',
  6560. $item_id,
  6561. $row
  6562. );
  6563. }
  6564. break;
  6565. case TOOL_DOCUMENT:
  6566. case TOOL_READOUT_TEXT:
  6567. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6568. $sql = "SELECT lp.*, doc.path as dir
  6569. FROM $tbl_lp_item as lp
  6570. LEFT JOIN $tbl_doc as doc
  6571. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6572. WHERE
  6573. doc.c_id = $course_id AND
  6574. lp.iid = ".$item_id;
  6575. $res_step = Database::query($sql);
  6576. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6577. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6578. if ($row['item_type'] === TOOL_DOCUMENT) {
  6579. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6580. }
  6581. if ($row['item_type'] === TOOL_READOUT_TEXT) {
  6582. $return .= $this->displayFrmReadOutText('edit', $item_id, $row_step);
  6583. }
  6584. break;
  6585. case TOOL_LINK:
  6586. $linkId = (int) $row['path'];
  6587. if (!empty($linkId)) {
  6588. $table = Database::get_course_table(TABLE_LINK);
  6589. $sql = 'SELECT url FROM '.$table.'
  6590. WHERE c_id = '.$course_id.' AND iid = '.$linkId;
  6591. $res_link = Database::query($sql);
  6592. $row_link = Database::fetch_array($res_link);
  6593. if (empty($row_link)) {
  6594. // Try with id
  6595. $sql = 'SELECT url FROM '.$table.'
  6596. WHERE c_id = '.$course_id.' AND id = '.$linkId;
  6597. $res_link = Database::query($sql);
  6598. $row_link = Database::fetch_array($res_link);
  6599. }
  6600. if (is_array($row_link)) {
  6601. $row['url'] = $row_link['url'];
  6602. }
  6603. }
  6604. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6605. $return .= $this->display_link_form('edit', $item_id, $row);
  6606. break;
  6607. case TOOL_LP_FINAL_ITEM:
  6608. Session::write('finalItem', true);
  6609. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  6610. $sql = "SELECT lp.*, doc.path as dir
  6611. FROM $tbl_lp_item as lp
  6612. LEFT JOIN $tbl_doc as doc
  6613. ON (doc.iid = lp.path AND lp.c_id = doc.c_id)
  6614. WHERE
  6615. doc.c_id = $course_id AND
  6616. lp.iid = ".$item_id;
  6617. $res_step = Database::query($sql);
  6618. $row_step = Database::fetch_array($res_step, 'ASSOC');
  6619. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6620. $return .= $this->display_document_form('edit', $item_id, $row_step);
  6621. break;
  6622. case TOOL_QUIZ:
  6623. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6624. $return .= $this->display_quiz_form('edit', $item_id, $row);
  6625. break;
  6626. case TOOL_HOTPOTATOES:
  6627. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6628. $return .= $this->display_hotpotatoes_form('edit', $item_id, $row);
  6629. break;
  6630. case TOOL_STUDENTPUBLICATION:
  6631. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6632. $return .= $this->display_student_publication_form('edit', $item_id, $row);
  6633. break;
  6634. case TOOL_FORUM:
  6635. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6636. $return .= $this->display_forum_form('edit', $item_id, $row);
  6637. break;
  6638. case TOOL_THREAD:
  6639. $return .= $this->display_manipulate($item_id, $row['item_type']);
  6640. $return .= $this->display_thread_form('edit', $item_id, $row);
  6641. break;
  6642. }
  6643. return $return;
  6644. }
  6645. /**
  6646. * Function that displays a list with al the resources that
  6647. * could be added to the learning path.
  6648. *
  6649. * @throws Exception
  6650. * @throws HTML_QuickForm_Error
  6651. *
  6652. * @return bool
  6653. */
  6654. public function display_resources()
  6655. {
  6656. $course_code = api_get_course_id();
  6657. // Get all the docs.
  6658. $documents = $this->get_documents(true);
  6659. // Get all the exercises.
  6660. $exercises = $this->get_exercises();
  6661. // Get all the links.
  6662. $links = $this->get_links();
  6663. // Get all the student publications.
  6664. $works = $this->get_student_publications();
  6665. // Get all the forums.
  6666. $forums = $this->get_forums(null, $course_code);
  6667. // Get the final item form (see BT#11048) .
  6668. $finish = $this->getFinalItemForm();
  6669. $headers = [
  6670. Display::return_icon('folder_document.png', get_lang('Documents'), [], ICON_SIZE_BIG),
  6671. Display::return_icon('quiz.png', get_lang('Quiz'), [], ICON_SIZE_BIG),
  6672. Display::return_icon('links.png', get_lang('Links'), [], ICON_SIZE_BIG),
  6673. Display::return_icon('works.png', get_lang('Works'), [], ICON_SIZE_BIG),
  6674. Display::return_icon('forum.png', get_lang('Forums'), [], ICON_SIZE_BIG),
  6675. Display::return_icon('add_learnpath_section.png', get_lang('NewChapter'), [], ICON_SIZE_BIG),
  6676. Display::return_icon('certificate.png', get_lang('Certificate'), [], ICON_SIZE_BIG),
  6677. ];
  6678. echo Display::return_message(get_lang('ClickOnTheLearnerViewToSeeYourLearningPath'), 'normal');
  6679. $dir = $this->display_item_form('dir', get_lang('EnterDataNewChapter'), 'add_item');
  6680. $selected = isset($_REQUEST['lp_build_selected']) ? (int) $_REQUEST['lp_build_selected'] : 0;
  6681. echo Display::tabs(
  6682. $headers,
  6683. [
  6684. $documents,
  6685. $exercises,
  6686. $links,
  6687. $works,
  6688. $forums,
  6689. $dir,
  6690. $finish,
  6691. ],
  6692. 'resource_tab',
  6693. [],
  6694. [],
  6695. $selected
  6696. );
  6697. return true;
  6698. }
  6699. /**
  6700. * Returns the extension of a document.
  6701. *
  6702. * @param string $filename
  6703. *
  6704. * @return string Extension (part after the last dot)
  6705. */
  6706. public function get_extension($filename)
  6707. {
  6708. $explode = explode('.', $filename);
  6709. return $explode[count($explode) - 1];
  6710. }
  6711. /**
  6712. * Displays a document by id.
  6713. *
  6714. * @param int $id
  6715. * @param bool $show_title
  6716. * @param bool $iframe
  6717. * @param bool $edit_link
  6718. *
  6719. * @return string
  6720. */
  6721. public function display_document($id, $show_title = false, $iframe = true, $edit_link = false)
  6722. {
  6723. $_course = api_get_course_info();
  6724. $course_id = api_get_course_int_id();
  6725. $id = (int) $id;
  6726. $return = '';
  6727. $table = Database::get_course_table(TABLE_DOCUMENT);
  6728. $sql_doc = "SELECT * FROM $table
  6729. WHERE c_id = $course_id AND iid = $id";
  6730. $res_doc = Database::query($sql_doc);
  6731. $row_doc = Database::fetch_array($res_doc);
  6732. // TODO: Add a path filter.
  6733. if ($iframe) {
  6734. $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>';
  6735. } else {
  6736. $return .= file_get_contents(api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/'.$row_doc['path']);
  6737. }
  6738. return $return;
  6739. }
  6740. /**
  6741. * Return HTML form to add/edit a quiz.
  6742. *
  6743. * @param string $action Action (add/edit)
  6744. * @param int $id Item ID if already exists
  6745. * @param mixed $extra_info Extra information (quiz ID if integer)
  6746. *
  6747. * @throws Exception
  6748. *
  6749. * @return string HTML form
  6750. */
  6751. public function display_quiz_form($action = 'add', $id = 0, $extra_info = '')
  6752. {
  6753. $course_id = api_get_course_int_id();
  6754. $id = (int) $id;
  6755. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  6756. if ($id != 0 && is_array($extra_info)) {
  6757. $item_title = $extra_info['title'];
  6758. $item_description = $extra_info['description'];
  6759. } elseif (is_numeric($extra_info)) {
  6760. $sql = "SELECT title, description
  6761. FROM $tbl_quiz
  6762. WHERE c_id = $course_id AND iid = ".$extra_info;
  6763. $result = Database::query($sql);
  6764. $row = Database::fetch_array($result);
  6765. $item_title = $row['title'];
  6766. $item_description = $row['description'];
  6767. } else {
  6768. $item_title = '';
  6769. $item_description = '';
  6770. }
  6771. $item_title = Security::remove_XSS($item_title);
  6772. $item_description = Security::remove_XSS($item_description);
  6773. $parent = 0;
  6774. if ($id != 0 && is_array($extra_info)) {
  6775. $parent = $extra_info['parent_item_id'];
  6776. }
  6777. $arrLP = $this->getItemsForForm();
  6778. $this->tree_array($arrLP);
  6779. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  6780. unset($this->arrMenu);
  6781. $form = new FormValidator(
  6782. 'quiz_form',
  6783. 'POST',
  6784. $this->getCurrentBuildingModeURL()
  6785. );
  6786. $defaults = [];
  6787. if ($action === 'add') {
  6788. $legend = get_lang('CreateTheExercise');
  6789. } elseif ($action === 'move') {
  6790. $legend = get_lang('MoveTheCurrentExercise');
  6791. } else {
  6792. $legend = get_lang('EditCurrentExecice');
  6793. }
  6794. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6795. $legend .= Display::return_message(get_lang('Warning').' ! '.get_lang('WarningEditingDocument'));
  6796. }
  6797. $form->addHeader($legend);
  6798. if ($action != 'move') {
  6799. $this->setItemTitle($form);
  6800. $defaults['title'] = $item_title;
  6801. }
  6802. // Select for Parent item, root or chapter
  6803. $selectParent = $form->addSelect(
  6804. 'parent',
  6805. get_lang('Parent'),
  6806. [],
  6807. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  6808. );
  6809. $selectParent->addOption($this->name, 0);
  6810. $arrHide = [
  6811. $id,
  6812. ];
  6813. for ($i = 0; $i < count($arrLP); $i++) {
  6814. if ($action != 'add') {
  6815. if (
  6816. ($arrLP[$i]['item_type'] == 'dir') &&
  6817. !in_array($arrLP[$i]['id'], $arrHide) &&
  6818. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6819. ) {
  6820. $selectParent->addOption(
  6821. $arrLP[$i]['title'],
  6822. $arrLP[$i]['id'],
  6823. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6824. );
  6825. if ($parent == $arrLP[$i]['id']) {
  6826. $selectParent->setSelected($arrLP[$i]['id']);
  6827. }
  6828. } else {
  6829. $arrHide[] = $arrLP[$i]['id'];
  6830. }
  6831. } else {
  6832. if ($arrLP[$i]['item_type'] == 'dir') {
  6833. $selectParent->addOption(
  6834. $arrLP[$i]['title'],
  6835. $arrLP[$i]['id'],
  6836. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  6837. );
  6838. if ($parent == $arrLP[$i]['id']) {
  6839. $selectParent->setSelected($arrLP[$i]['id']);
  6840. }
  6841. }
  6842. }
  6843. }
  6844. if (is_array($arrLP)) {
  6845. reset($arrLP);
  6846. }
  6847. $selectPrevious = $form->addSelect(
  6848. 'previous',
  6849. get_lang('Position'),
  6850. [],
  6851. ['id' => 'previous']
  6852. );
  6853. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  6854. for ($i = 0; $i < count($arrLP); $i++) {
  6855. if ($arrLP[$i]['parent_item_id'] == $parent &&
  6856. $arrLP[$i]['id'] != $id
  6857. ) {
  6858. $selectPrevious->addOption(
  6859. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  6860. $arrLP[$i]['id']
  6861. );
  6862. if (is_array($extra_info)) {
  6863. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6864. $selectPrevious->setSelected($arrLP[$i]['id']);
  6865. }
  6866. } elseif ($action == 'add') {
  6867. $selectPrevious->setSelected($arrLP[$i]['id']);
  6868. }
  6869. }
  6870. }
  6871. if ($action != 'move') {
  6872. $arrHide = [];
  6873. for ($i = 0; $i < count($arrLP); $i++) {
  6874. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  6875. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  6876. }
  6877. }
  6878. }
  6879. if ($action === 'add') {
  6880. $form->addButtonSave(get_lang('AddExercise'), 'submit_button');
  6881. } else {
  6882. $form->addButtonSave(get_lang('EditCurrentExecice'), 'submit_button');
  6883. }
  6884. if ($action === 'move') {
  6885. $form->addHidden('title', $item_title);
  6886. $form->addHidden('description', $item_description);
  6887. }
  6888. if (is_numeric($extra_info)) {
  6889. $form->addHidden('path', $extra_info);
  6890. } elseif (is_array($extra_info)) {
  6891. $form->addHidden('path', $extra_info['path']);
  6892. }
  6893. $form->addHidden('type', TOOL_QUIZ);
  6894. $form->addHidden('post_time', time());
  6895. $form->setDefaults($defaults);
  6896. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  6897. }
  6898. /**
  6899. * Addition of Hotpotatoes tests.
  6900. *
  6901. * @param string $action
  6902. * @param int $id Internal ID of the item
  6903. * @param string $extra_info
  6904. *
  6905. * @return string HTML structure to display the hotpotatoes addition formular
  6906. */
  6907. public function display_hotpotatoes_form($action = 'add', $id = 0, $extra_info = '')
  6908. {
  6909. $course_id = api_get_course_int_id();
  6910. $uploadPath = DIR_HOTPOTATOES;
  6911. if ($id != 0 && is_array($extra_info)) {
  6912. $item_title = stripslashes($extra_info['title']);
  6913. $item_description = stripslashes($extra_info['description']);
  6914. } elseif (is_numeric($extra_info)) {
  6915. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  6916. $sql = "SELECT * FROM $TBL_DOCUMENT
  6917. WHERE
  6918. c_id = $course_id AND
  6919. path LIKE '".$uploadPath."/%/%htm%' AND
  6920. iid = ".(int) $extra_info."
  6921. ORDER BY iid ASC";
  6922. $res_hot = Database::query($sql);
  6923. $row = Database::fetch_array($res_hot);
  6924. $item_title = $row['title'];
  6925. $item_description = $row['description'];
  6926. if (!empty($row['comment'])) {
  6927. $item_title = $row['comment'];
  6928. }
  6929. } else {
  6930. $item_title = '';
  6931. $item_description = '';
  6932. }
  6933. $parent = 0;
  6934. if ($id != 0 && is_array($extra_info)) {
  6935. $parent = $extra_info['parent_item_id'];
  6936. }
  6937. $arrLP = $this->getItemsForForm();
  6938. $legend = '<legend>';
  6939. if ($action == 'add') {
  6940. $legend .= get_lang('CreateTheExercise');
  6941. } elseif ($action == 'move') {
  6942. $legend .= get_lang('MoveTheCurrentExercise');
  6943. } else {
  6944. $legend .= get_lang('EditCurrentExecice');
  6945. }
  6946. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  6947. $legend .= Display:: return_message(
  6948. get_lang('Warning').' ! '.get_lang('WarningEditingDocument')
  6949. );
  6950. }
  6951. $legend .= '</legend>';
  6952. $return = '<form method="POST">';
  6953. $return .= $legend;
  6954. $return .= '<table cellpadding="0" cellspacing="0" class="lp_form">';
  6955. $return .= '<tr>';
  6956. $return .= '<td class="label"><label for="idParent">'.get_lang('Parent').' :</label></td>';
  6957. $return .= '<td class="input">';
  6958. $return .= '<select id="idParent" name="parent" onChange="javascript: load_cbo(this.value);" size="1">';
  6959. $return .= '<option class="top" value="0">'.$this->name.'</option>';
  6960. $arrHide = [$id];
  6961. if (count($arrLP) > 0) {
  6962. for ($i = 0; $i < count($arrLP); $i++) {
  6963. if ($action != 'add') {
  6964. if ($arrLP[$i]['item_type'] == 'dir' &&
  6965. !in_array($arrLP[$i]['id'], $arrHide) &&
  6966. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  6967. ) {
  6968. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6969. } else {
  6970. $arrHide[] = $arrLP[$i]['id'];
  6971. }
  6972. } else {
  6973. if ($arrLP[$i]['item_type'] == 'dir') {
  6974. $return .= '<option '.(($parent == $arrLP[$i]['id']) ? 'selected="selected" ' : '').'style="padding-left:'.($arrLP[$i]['depth'] * 10).'px;" value="'.$arrLP[$i]['id'].'">'.$arrLP[$i]['title'].'</option>';
  6975. }
  6976. }
  6977. }
  6978. reset($arrLP);
  6979. }
  6980. $return .= '</select>';
  6981. $return .= '</td>';
  6982. $return .= '</tr>';
  6983. $return .= '<tr>';
  6984. $return .= '<td class="label"><label for="previous">'.get_lang('Position').' :</label></td>';
  6985. $return .= '<td class="input">';
  6986. $return .= '<select id="previous" name="previous" size="1">';
  6987. $return .= '<option class="top" value="0">'.get_lang('FirstPosition').'</option>';
  6988. for ($i = 0; $i < count($arrLP); $i++) {
  6989. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  6990. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  6991. $selected = 'selected="selected" ';
  6992. } elseif ($action == 'add') {
  6993. $selected = 'selected="selected" ';
  6994. } else {
  6995. $selected = '';
  6996. }
  6997. $return .= '<option '.$selected.'value="'.$arrLP[$i]['id'].'">'.
  6998. get_lang('After').' "'.$arrLP[$i]['title'].'"</option>';
  6999. }
  7000. }
  7001. $return .= '</select>';
  7002. $return .= '</td>';
  7003. $return .= '</tr>';
  7004. if ($action != 'move') {
  7005. $return .= '<tr>';
  7006. $return .= '<td class="label"><label for="idTitle">'.get_lang('Title').' :</label></td>';
  7007. $return .= '<td class="input"><input id="idTitle" name="title" type="text" value="'.$item_title.'" /></td>';
  7008. $return .= '</tr>';
  7009. $id_prerequisite = 0;
  7010. if (is_array($arrLP) && count($arrLP) > 0) {
  7011. foreach ($arrLP as $key => $value) {
  7012. if ($value['id'] == $id) {
  7013. $id_prerequisite = $value['prerequisite'];
  7014. break;
  7015. }
  7016. }
  7017. $arrHide = [];
  7018. for ($i = 0; $i < count($arrLP); $i++) {
  7019. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7020. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7021. }
  7022. }
  7023. }
  7024. }
  7025. $return .= '<tr>';
  7026. $return .= '<td>&nbsp; </td><td><button class="save" name="submit_button" action="edit" type="submit">'.
  7027. get_lang('SaveHotpotatoes').'</button></td>';
  7028. $return .= '</tr>';
  7029. $return .= '</table>';
  7030. if ($action == 'move') {
  7031. $return .= '<input name="title" type="hidden" value="'.$item_title.'" />';
  7032. $return .= '<input name="description" type="hidden" value="'.$item_description.'" />';
  7033. }
  7034. if (is_numeric($extra_info)) {
  7035. $return .= '<input name="path" type="hidden" value="'.$extra_info.'" />';
  7036. } elseif (is_array($extra_info)) {
  7037. $return .= '<input name="path" type="hidden" value="'.$extra_info['path'].'" />';
  7038. }
  7039. $return .= '<input name="type" type="hidden" value="'.TOOL_HOTPOTATOES.'" />';
  7040. $return .= '<input name="post_time" type="hidden" value="'.time().'" />';
  7041. $return .= '</form>';
  7042. return $return;
  7043. }
  7044. /**
  7045. * Return the form to display the forum edit/add option.
  7046. *
  7047. * @param string $action
  7048. * @param int $id ID of the lp_item if already exists
  7049. * @param string $extra_info
  7050. *
  7051. * @throws Exception
  7052. *
  7053. * @return string HTML form
  7054. */
  7055. public function display_forum_form($action = 'add', $id = 0, $extra_info = '')
  7056. {
  7057. $course_id = api_get_course_int_id();
  7058. $tbl_forum = Database::get_course_table(TABLE_FORUM);
  7059. $item_title = '';
  7060. $item_description = '';
  7061. if ($id != 0 && is_array($extra_info)) {
  7062. $item_title = stripslashes($extra_info['title']);
  7063. } elseif (is_numeric($extra_info)) {
  7064. $sql = "SELECT forum_title as title, forum_comment as comment
  7065. FROM $tbl_forum
  7066. WHERE c_id = $course_id AND forum_id = ".$extra_info;
  7067. $result = Database::query($sql);
  7068. $row = Database::fetch_array($result);
  7069. $item_title = $row['title'];
  7070. $item_description = $row['comment'];
  7071. }
  7072. $parent = 0;
  7073. if ($id != 0 && is_array($extra_info)) {
  7074. $parent = $extra_info['parent_item_id'];
  7075. }
  7076. $arrLP = $this->getItemsForForm();
  7077. $this->tree_array($arrLP);
  7078. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7079. unset($this->arrMenu);
  7080. if ($action == 'add') {
  7081. $legend = get_lang('CreateTheForum');
  7082. } elseif ($action == 'move') {
  7083. $legend = get_lang('MoveTheCurrentForum');
  7084. } else {
  7085. $legend = get_lang('EditCurrentForum');
  7086. }
  7087. $form = new FormValidator(
  7088. 'forum_form',
  7089. 'POST',
  7090. $this->getCurrentBuildingModeURL()
  7091. );
  7092. $defaults = [];
  7093. $form->addHeader($legend);
  7094. if ($action != 'move') {
  7095. $this->setItemTitle($form);
  7096. $defaults['title'] = $item_title;
  7097. }
  7098. $selectParent = $form->addSelect(
  7099. 'parent',
  7100. get_lang('Parent'),
  7101. [],
  7102. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  7103. );
  7104. $selectParent->addOption($this->name, 0);
  7105. $arrHide = [
  7106. $id,
  7107. ];
  7108. for ($i = 0; $i < count($arrLP); $i++) {
  7109. if ($action != 'add') {
  7110. if ($arrLP[$i]['item_type'] == 'dir' &&
  7111. !in_array($arrLP[$i]['id'], $arrHide) &&
  7112. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7113. ) {
  7114. $selectParent->addOption(
  7115. $arrLP[$i]['title'],
  7116. $arrLP[$i]['id'],
  7117. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7118. );
  7119. if ($parent == $arrLP[$i]['id']) {
  7120. $selectParent->setSelected($arrLP[$i]['id']);
  7121. }
  7122. } else {
  7123. $arrHide[] = $arrLP[$i]['id'];
  7124. }
  7125. } else {
  7126. if ($arrLP[$i]['item_type'] == 'dir') {
  7127. $selectParent->addOption(
  7128. $arrLP[$i]['title'],
  7129. $arrLP[$i]['id'],
  7130. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7131. );
  7132. if ($parent == $arrLP[$i]['id']) {
  7133. $selectParent->setSelected($arrLP[$i]['id']);
  7134. }
  7135. }
  7136. }
  7137. }
  7138. if (is_array($arrLP)) {
  7139. reset($arrLP);
  7140. }
  7141. $selectPrevious = $form->addSelect(
  7142. 'previous',
  7143. get_lang('Position'),
  7144. [],
  7145. ['id' => 'previous', 'class' => 'learnpath_item_form']
  7146. );
  7147. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7148. for ($i = 0; $i < count($arrLP); $i++) {
  7149. if ($arrLP[$i]['parent_item_id'] == $parent &&
  7150. $arrLP[$i]['id'] != $id
  7151. ) {
  7152. $selectPrevious->addOption(
  7153. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7154. $arrLP[$i]['id']
  7155. );
  7156. if (isset($extra_info['previous_item_id']) &&
  7157. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7158. ) {
  7159. $selectPrevious->setSelected($arrLP[$i]['id']);
  7160. } elseif ($action == 'add') {
  7161. $selectPrevious->setSelected($arrLP[$i]['id']);
  7162. }
  7163. }
  7164. }
  7165. if ($action != 'move') {
  7166. $id_prerequisite = 0;
  7167. if (is_array($arrLP)) {
  7168. foreach ($arrLP as $key => $value) {
  7169. if ($value['id'] == $id) {
  7170. $id_prerequisite = $value['prerequisite'];
  7171. break;
  7172. }
  7173. }
  7174. }
  7175. $arrHide = [];
  7176. for ($i = 0; $i < count($arrLP); $i++) {
  7177. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7178. if (isset($extra_info['previous_item_id']) &&
  7179. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7180. ) {
  7181. $s_selected_position = $arrLP[$i]['id'];
  7182. } elseif ($action == 'add') {
  7183. $s_selected_position = 0;
  7184. }
  7185. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7186. }
  7187. }
  7188. }
  7189. if ($action == 'add') {
  7190. $form->addButtonSave(get_lang('AddForumToCourse'), 'submit_button');
  7191. } else {
  7192. $form->addButtonSave(get_lang('EditCurrentForum'), 'submit_button');
  7193. }
  7194. if ($action == 'move') {
  7195. $form->addHidden('title', $item_title);
  7196. $form->addHidden('description', $item_description);
  7197. }
  7198. if (is_numeric($extra_info)) {
  7199. $form->addHidden('path', $extra_info);
  7200. } elseif (is_array($extra_info)) {
  7201. $form->addHidden('path', $extra_info['path']);
  7202. }
  7203. $form->addHidden('type', TOOL_FORUM);
  7204. $form->addHidden('post_time', time());
  7205. $form->setDefaults($defaults);
  7206. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  7207. }
  7208. /**
  7209. * Return HTML form to add/edit forum threads.
  7210. *
  7211. * @param string $action
  7212. * @param int $id Item ID if already exists in learning path
  7213. * @param string $extra_info
  7214. *
  7215. * @throws Exception
  7216. *
  7217. * @return string HTML form
  7218. */
  7219. public function display_thread_form($action = 'add', $id = 0, $extra_info = '')
  7220. {
  7221. $course_id = api_get_course_int_id();
  7222. if (empty($course_id)) {
  7223. return null;
  7224. }
  7225. $tbl_forum = Database::get_course_table(TABLE_FORUM_THREAD);
  7226. $item_title = '';
  7227. $item_description = '';
  7228. if ($id != 0 && is_array($extra_info)) {
  7229. $item_title = stripslashes($extra_info['title']);
  7230. } elseif (is_numeric($extra_info)) {
  7231. $sql = "SELECT thread_title as title FROM $tbl_forum
  7232. WHERE c_id = $course_id AND thread_id = ".$extra_info;
  7233. $result = Database::query($sql);
  7234. $row = Database::fetch_array($result);
  7235. $item_title = $row['title'];
  7236. $item_description = '';
  7237. }
  7238. $parent = 0;
  7239. if ($id != 0 && is_array($extra_info)) {
  7240. $parent = $extra_info['parent_item_id'];
  7241. }
  7242. $arrLP = $this->getItemsForForm();
  7243. $this->tree_array($arrLP);
  7244. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7245. unset($this->arrMenu);
  7246. $form = new FormValidator(
  7247. 'thread_form',
  7248. 'POST',
  7249. $this->getCurrentBuildingModeURL()
  7250. );
  7251. $defaults = [];
  7252. if ($action == 'add') {
  7253. $legend = get_lang('CreateTheForum');
  7254. } elseif ($action == 'move') {
  7255. $legend = get_lang('MoveTheCurrentForum');
  7256. } else {
  7257. $legend = get_lang('EditCurrentForum');
  7258. }
  7259. $form->addHeader($legend);
  7260. $selectParent = $form->addSelect(
  7261. 'parent',
  7262. get_lang('Parent'),
  7263. [],
  7264. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);']
  7265. );
  7266. $selectParent->addOption($this->name, 0);
  7267. $arrHide = [
  7268. $id,
  7269. ];
  7270. for ($i = 0; $i < count($arrLP); $i++) {
  7271. if ($action != 'add') {
  7272. if (
  7273. ($arrLP[$i]['item_type'] == 'dir') &&
  7274. !in_array($arrLP[$i]['id'], $arrHide) &&
  7275. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7276. ) {
  7277. $selectParent->addOption(
  7278. $arrLP[$i]['title'],
  7279. $arrLP[$i]['id'],
  7280. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7281. );
  7282. if ($parent == $arrLP[$i]['id']) {
  7283. $selectParent->setSelected($arrLP[$i]['id']);
  7284. }
  7285. } else {
  7286. $arrHide[] = $arrLP[$i]['id'];
  7287. }
  7288. } else {
  7289. if ($arrLP[$i]['item_type'] == 'dir') {
  7290. $selectParent->addOption(
  7291. $arrLP[$i]['title'],
  7292. $arrLP[$i]['id'],
  7293. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  7294. );
  7295. if ($parent == $arrLP[$i]['id']) {
  7296. $selectParent->setSelected($arrLP[$i]['id']);
  7297. }
  7298. }
  7299. }
  7300. }
  7301. if ($arrLP != null) {
  7302. reset($arrLP);
  7303. }
  7304. $selectPrevious = $form->addSelect(
  7305. 'previous',
  7306. get_lang('Position'),
  7307. [],
  7308. ['id' => 'previous']
  7309. );
  7310. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  7311. for ($i = 0; $i < count($arrLP); $i++) {
  7312. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  7313. $selectPrevious->addOption(
  7314. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  7315. $arrLP[$i]['id']
  7316. );
  7317. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7318. $selectPrevious->setSelected($arrLP[$i]['id']);
  7319. } elseif ($action == 'add') {
  7320. $selectPrevious->setSelected($arrLP[$i]['id']);
  7321. }
  7322. }
  7323. }
  7324. if ($action != 'move') {
  7325. $this->setItemTitle($form);
  7326. $defaults['title'] = $item_title;
  7327. $id_prerequisite = 0;
  7328. if ($arrLP != null) {
  7329. foreach ($arrLP as $key => $value) {
  7330. if ($value['id'] == $id) {
  7331. $id_prerequisite = $value['prerequisite'];
  7332. break;
  7333. }
  7334. }
  7335. }
  7336. $arrHide = [];
  7337. $s_selected_position = 0;
  7338. for ($i = 0; $i < count($arrLP); $i++) {
  7339. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  7340. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  7341. $s_selected_position = $arrLP[$i]['id'];
  7342. } elseif ($action == 'add') {
  7343. $s_selected_position = 0;
  7344. }
  7345. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7346. }
  7347. }
  7348. $selectPrerequisites = $form->addSelect(
  7349. 'prerequisites',
  7350. get_lang('LearnpathPrerequisites'),
  7351. [],
  7352. ['id' => 'prerequisites']
  7353. );
  7354. $selectPrerequisites->addOption(get_lang('NoPrerequisites'), 0);
  7355. foreach ($arrHide as $key => $value) {
  7356. $selectPrerequisites->addOption($value['value'], $key);
  7357. if ($key == $s_selected_position && $action == 'add') {
  7358. $selectPrerequisites->setSelected($key);
  7359. } elseif ($key == $id_prerequisite && $action == 'edit') {
  7360. $selectPrerequisites->setSelected($key);
  7361. }
  7362. }
  7363. }
  7364. $form->addButtonSave(get_lang('Ok'), 'submit_button');
  7365. if ($action == 'move') {
  7366. $form->addHidden('title', $item_title);
  7367. $form->addHidden('description', $item_description);
  7368. }
  7369. if (is_numeric($extra_info)) {
  7370. $form->addHidden('path', $extra_info);
  7371. } elseif (is_array($extra_info)) {
  7372. $form->addHidden('path', $extra_info['path']);
  7373. }
  7374. $form->addHidden('type', TOOL_THREAD);
  7375. $form->addHidden('post_time', time());
  7376. $form->setDefaults($defaults);
  7377. return $form->returnForm();
  7378. }
  7379. /**
  7380. * Return the HTML form to display an item (generally a dir item).
  7381. *
  7382. * @param string $item_type
  7383. * @param string $title
  7384. * @param string $action
  7385. * @param int $id
  7386. * @param string $extra_info
  7387. *
  7388. * @throws Exception
  7389. * @throws HTML_QuickForm_Error
  7390. *
  7391. * @return string HTML form
  7392. */
  7393. public function display_item_form(
  7394. $item_type,
  7395. $title = '',
  7396. $action = 'add_item',
  7397. $id = 0,
  7398. $extra_info = 'new'
  7399. ) {
  7400. $_course = api_get_course_info();
  7401. global $charset;
  7402. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  7403. $item_title = '';
  7404. $item_description = '';
  7405. $item_path_fck = '';
  7406. if ($id != 0 && is_array($extra_info)) {
  7407. $item_title = $extra_info['title'];
  7408. $item_description = $extra_info['description'];
  7409. $item_path = api_get_path(WEB_COURSE_PATH).$_course['path'].'/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7410. $item_path_fck = '/scorm/'.$this->path.'/'.stripslashes($extra_info['path']);
  7411. }
  7412. $parent = 0;
  7413. if ($id != 0 && is_array($extra_info)) {
  7414. $parent = $extra_info['parent_item_id'];
  7415. }
  7416. $id = (int) $id;
  7417. $sql = "SELECT * FROM $tbl_lp_item
  7418. WHERE
  7419. lp_id = ".$this->lp_id." AND
  7420. iid != $id";
  7421. if ($item_type == 'dir') {
  7422. $sql .= " AND parent_item_id = 0";
  7423. }
  7424. $result = Database::query($sql);
  7425. $arrLP = [];
  7426. while ($row = Database::fetch_array($result)) {
  7427. $arrLP[] = [
  7428. 'id' => $row['iid'],
  7429. 'item_type' => $row['item_type'],
  7430. 'title' => $this->cleanItemTitle($row['title']),
  7431. 'path' => $row['path'],
  7432. 'description' => $row['description'],
  7433. 'parent_item_id' => $row['parent_item_id'],
  7434. 'previous_item_id' => $row['previous_item_id'],
  7435. 'next_item_id' => $row['next_item_id'],
  7436. 'max_score' => $row['max_score'],
  7437. 'min_score' => $row['min_score'],
  7438. 'mastery_score' => $row['mastery_score'],
  7439. 'prerequisite' => $row['prerequisite'],
  7440. 'display_order' => $row['display_order'],
  7441. ];
  7442. }
  7443. $this->tree_array($arrLP);
  7444. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7445. unset($this->arrMenu);
  7446. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&type='.$item_type.'&lp_id='.$this->lp_id;
  7447. $form = new FormValidator('form_'.$item_type, 'POST', $url);
  7448. $defaults['title'] = api_html_entity_decode(
  7449. $item_title,
  7450. ENT_QUOTES,
  7451. $charset
  7452. );
  7453. $defaults['description'] = $item_description;
  7454. $form->addHeader($title);
  7455. $arrHide[0]['value'] = Security::remove_XSS($this->name);
  7456. $arrHide[0]['padding'] = 20;
  7457. $charset = api_get_system_encoding();
  7458. for ($i = 0; $i < count($arrLP); $i++) {
  7459. if ($action != 'add') {
  7460. if ($arrLP[$i]['item_type'] === 'dir' && !in_array($arrLP[$i]['id'], $arrHide) &&
  7461. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7462. ) {
  7463. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7464. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7465. if ($parent == $arrLP[$i]['id']) {
  7466. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7467. }
  7468. }
  7469. } else {
  7470. if ($arrLP[$i]['item_type'] === 'dir') {
  7471. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7472. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7473. if ($parent == $arrLP[$i]['id']) {
  7474. $s_selected_parent = $arrHide[$arrLP[$i]['id']];
  7475. }
  7476. }
  7477. }
  7478. }
  7479. if ($action != 'move') {
  7480. $this->setItemTitle($form);
  7481. } else {
  7482. $form->addElement('hidden', 'title');
  7483. }
  7484. $parentSelect = $form->addElement(
  7485. 'select',
  7486. 'parent',
  7487. get_lang('Parent'),
  7488. '',
  7489. [
  7490. 'id' => 'idParent',
  7491. 'onchange' => 'javascript: load_cbo(this.value);',
  7492. ]
  7493. );
  7494. foreach ($arrHide as $key => $value) {
  7495. $parentSelect->addOption(
  7496. $value['value'],
  7497. $key,
  7498. 'style="padding-left:'.$value['padding'].'px;"'
  7499. );
  7500. $lastPosition = $key;
  7501. }
  7502. if (!empty($s_selected_parent)) {
  7503. $parentSelect->setSelected($s_selected_parent);
  7504. }
  7505. if (is_array($arrLP)) {
  7506. reset($arrLP);
  7507. }
  7508. $arrHide = [];
  7509. // POSITION
  7510. for ($i = 0; $i < count($arrLP); $i++) {
  7511. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id &&
  7512. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM) {
  7513. //this is the same!
  7514. if (isset($extra_info['previous_item_id']) &&
  7515. $extra_info['previous_item_id'] == $arrLP[$i]['id']
  7516. ) {
  7517. $s_selected_position = $arrLP[$i]['id'];
  7518. } elseif ($action == 'add') {
  7519. $s_selected_position = $arrLP[$i]['id'];
  7520. }
  7521. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7522. }
  7523. }
  7524. $position = $form->addElement(
  7525. 'select',
  7526. 'previous',
  7527. get_lang('Position'),
  7528. '',
  7529. ['id' => 'previous']
  7530. );
  7531. $padding = isset($value['padding']) ? $value['padding'] : 0;
  7532. $position->addOption(get_lang('FirstPosition'), 0, 'style="padding-left:'.$padding.'px;"');
  7533. $lastPosition = null;
  7534. foreach ($arrHide as $key => $value) {
  7535. $position->addOption($value['value'], $key, 'style="padding-left:'.$padding.'px;"');
  7536. $lastPosition = $key;
  7537. }
  7538. if (!empty($s_selected_position)) {
  7539. $position->setSelected($s_selected_position);
  7540. }
  7541. // When new chapter add at the end
  7542. if ($action === 'add_item') {
  7543. $position->setSelected($lastPosition);
  7544. }
  7545. if (is_array($arrLP)) {
  7546. reset($arrLP);
  7547. }
  7548. $form->addButtonSave(get_lang('SaveSection'), 'submit_button');
  7549. //fix in order to use the tab
  7550. if ($item_type === 'dir') {
  7551. $form->addElement('hidden', 'type', 'dir');
  7552. }
  7553. $extension = null;
  7554. if (!empty($item_path)) {
  7555. $extension = pathinfo($item_path, PATHINFO_EXTENSION);
  7556. }
  7557. //assets can't be modified
  7558. //$item_type == 'asset' ||
  7559. if (($item_type == 'sco') && ($extension == 'html' || $extension == 'htm')) {
  7560. if ($item_type == 'sco') {
  7561. $form->addElement(
  7562. 'html',
  7563. '<script>alert("'.get_lang('WarningWhenEditingScorm').'")</script>'
  7564. );
  7565. }
  7566. $renderer = $form->defaultRenderer();
  7567. $renderer->setElementTemplate(
  7568. '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{label}<br />{element}',
  7569. 'content_lp'
  7570. );
  7571. $relative_prefix = '';
  7572. $editor_config = [
  7573. 'ToolbarSet' => 'LearningPathDocuments',
  7574. 'Width' => '100%',
  7575. 'Height' => '500',
  7576. 'FullPage' => true,
  7577. 'CreateDocumentDir' => $relative_prefix,
  7578. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/scorm/',
  7579. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().$item_path_fck,
  7580. ];
  7581. $form->addElement('html_editor', 'content_lp', '', null, $editor_config);
  7582. $content_path = api_get_path(SYS_COURSE_PATH).api_get_course_path().$item_path_fck;
  7583. $defaults['content_lp'] = file_get_contents($content_path);
  7584. }
  7585. if (!empty($id)) {
  7586. $form->addHidden('id', $id);
  7587. }
  7588. $form->addElement('hidden', 'type', $item_type);
  7589. $form->addElement('hidden', 'post_time', time());
  7590. $form->setDefaults($defaults);
  7591. return $form->returnForm();
  7592. }
  7593. /**
  7594. * @return string
  7595. */
  7596. public function getCurrentBuildingModeURL()
  7597. {
  7598. $pathItem = isset($_GET['path_item']) ? (int) $_GET['path_item'] : '';
  7599. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  7600. $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
  7601. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : '';
  7602. $currentUrl = api_get_self().'?'.api_get_cidreq().
  7603. '&action='.$action.'&lp_id='.$this->lp_id.'&path_item='.$pathItem.'&view='.$view.'&id='.$id;
  7604. return $currentUrl;
  7605. }
  7606. /**
  7607. * Returns the form to update or create a document.
  7608. *
  7609. * @param string $action (add/edit)
  7610. * @param int $id ID of the lp_item (if already exists)
  7611. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7612. *
  7613. * @throws Exception
  7614. * @throws HTML_QuickForm_Error
  7615. *
  7616. * @return string HTML form
  7617. */
  7618. public function display_document_form($action = 'add', $id = 0, $extra_info = 'new')
  7619. {
  7620. $course_id = api_get_course_int_id();
  7621. $_course = api_get_course_info();
  7622. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7623. $no_display_edit_textarea = false;
  7624. $item_description = '';
  7625. //If action==edit document
  7626. //We don't display the document form if it's not an editable document (html or txt file)
  7627. if ($action === 'edit') {
  7628. if (is_array($extra_info)) {
  7629. $path_parts = pathinfo($extra_info['dir']);
  7630. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7631. $no_display_edit_textarea = true;
  7632. }
  7633. }
  7634. }
  7635. $no_display_add = false;
  7636. // If action==add an existing document
  7637. // We don't display the document form if it's not an editable document (html or txt file).
  7638. if ($action === 'add') {
  7639. if (is_numeric($extra_info)) {
  7640. $extra_info = (int) $extra_info;
  7641. $sql_doc = "SELECT path FROM $tbl_doc
  7642. WHERE c_id = $course_id AND iid = ".$extra_info;
  7643. $result = Database::query($sql_doc);
  7644. $path_file = Database::result($result, 0, 0);
  7645. $path_parts = pathinfo($path_file);
  7646. if ($path_parts['extension'] != 'txt' && $path_parts['extension'] != 'html') {
  7647. $no_display_add = true;
  7648. }
  7649. }
  7650. }
  7651. $item_title = '';
  7652. $item_description = '';
  7653. if ($id != 0 && is_array($extra_info)) {
  7654. $item_title = stripslashes($extra_info['title']);
  7655. $item_description = stripslashes($extra_info['description']);
  7656. if (empty($item_title)) {
  7657. $path_parts = pathinfo($extra_info['path']);
  7658. $item_title = stripslashes($path_parts['filename']);
  7659. }
  7660. } elseif (is_numeric($extra_info)) {
  7661. $sql = "SELECT path, title FROM $tbl_doc
  7662. WHERE
  7663. c_id = ".$course_id." AND
  7664. iid = ".intval($extra_info);
  7665. $result = Database::query($sql);
  7666. $row = Database::fetch_array($result);
  7667. $item_title = $row['title'];
  7668. $item_title = str_replace('_', ' ', $item_title);
  7669. if (empty($item_title)) {
  7670. $path_parts = pathinfo($row['path']);
  7671. $item_title = stripslashes($path_parts['filename']);
  7672. }
  7673. }
  7674. $return = '<legend>';
  7675. $parent = 0;
  7676. if ($id != 0 && is_array($extra_info)) {
  7677. $parent = $extra_info['parent_item_id'];
  7678. }
  7679. $arrLP = $this->getItemsForForm();
  7680. $this->tree_array($arrLP);
  7681. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7682. unset($this->arrMenu);
  7683. if ($action == 'add') {
  7684. $return .= get_lang('CreateTheDocument');
  7685. } elseif ($action == 'move') {
  7686. $return .= get_lang('MoveTheCurrentDocument');
  7687. } else {
  7688. $return .= get_lang('EditTheCurrentDocument');
  7689. }
  7690. $return .= '</legend>';
  7691. if (isset($_GET['edit']) && $_GET['edit'] == 'true') {
  7692. $return .= Display::return_message(
  7693. '<strong>'.get_lang('Warning').' !</strong><br />'.get_lang('WarningEditingDocument'),
  7694. false
  7695. );
  7696. }
  7697. $form = new FormValidator(
  7698. 'form',
  7699. 'POST',
  7700. $this->getCurrentBuildingModeURL(),
  7701. '',
  7702. ['enctype' => 'multipart/form-data']
  7703. );
  7704. $defaults['title'] = Security::remove_XSS($item_title);
  7705. if (empty($item_title)) {
  7706. $defaults['title'] = Security::remove_XSS($item_title);
  7707. }
  7708. $defaults['description'] = $item_description;
  7709. $form->addElement('html', $return);
  7710. if ($action != 'move') {
  7711. $data = $this->generate_lp_folder($_course);
  7712. if ($action != 'edit') {
  7713. $folders = DocumentManager::get_all_document_folders(
  7714. $_course,
  7715. 0,
  7716. true
  7717. );
  7718. DocumentManager::build_directory_selector(
  7719. $folders,
  7720. '',
  7721. [],
  7722. true,
  7723. $form,
  7724. 'directory_parent_id'
  7725. );
  7726. }
  7727. if (isset($data['id'])) {
  7728. $defaults['directory_parent_id'] = $data['id'];
  7729. }
  7730. $this->setItemTitle($form);
  7731. }
  7732. $arrHide[0]['value'] = $this->name;
  7733. $arrHide[0]['padding'] = 20;
  7734. for ($i = 0; $i < count($arrLP); $i++) {
  7735. if ($action != 'add') {
  7736. if ($arrLP[$i]['item_type'] == 'dir' &&
  7737. !in_array($arrLP[$i]['id'], $arrHide) &&
  7738. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  7739. ) {
  7740. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7741. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7742. }
  7743. } else {
  7744. if ($arrLP[$i]['item_type'] == 'dir') {
  7745. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7746. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  7747. }
  7748. }
  7749. }
  7750. $parentSelect = $form->addSelect(
  7751. 'parent',
  7752. get_lang('Parent'),
  7753. [],
  7754. [
  7755. 'id' => 'idParent',
  7756. 'onchange' => 'javascript: load_cbo(this.value);',
  7757. ]
  7758. );
  7759. $my_count = 0;
  7760. foreach ($arrHide as $key => $value) {
  7761. if ($my_count != 0) {
  7762. // The LP name is also the first section and is not in the same charset like the other sections.
  7763. $value['value'] = Security::remove_XSS($value['value']);
  7764. $parentSelect->addOption(
  7765. $value['value'],
  7766. $key,
  7767. 'style="padding-left:'.$value['padding'].'px;"'
  7768. );
  7769. } else {
  7770. $value['value'] = Security::remove_XSS($value['value']);
  7771. $parentSelect->addOption(
  7772. $value['value'],
  7773. $key,
  7774. 'style="padding-left:'.$value['padding'].'px;"'
  7775. );
  7776. }
  7777. $my_count++;
  7778. }
  7779. if (!empty($id)) {
  7780. $parentSelect->setSelected($parent);
  7781. } else {
  7782. $parent_item_id = Session::read('parent_item_id', 0);
  7783. $parentSelect->setSelected($parent_item_id);
  7784. }
  7785. if (is_array($arrLP)) {
  7786. reset($arrLP);
  7787. }
  7788. $arrHide = [];
  7789. // POSITION
  7790. for ($i = 0; $i < count($arrLP); $i++) {
  7791. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) ||
  7792. $arrLP[$i]['item_type'] == TOOL_LP_FINAL_ITEM
  7793. ) {
  7794. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  7795. }
  7796. }
  7797. $selectedPosition = isset($extra_info['previous_item_id']) ? $extra_info['previous_item_id'] : 0;
  7798. $position = $form->addSelect(
  7799. 'previous',
  7800. get_lang('Position'),
  7801. [],
  7802. ['id' => 'previous']
  7803. );
  7804. $position->addOption(get_lang('FirstPosition'), 0);
  7805. foreach ($arrHide as $key => $value) {
  7806. $padding = isset($value['padding']) ? $value['padding'] : 20;
  7807. $position->addOption(
  7808. $value['value'],
  7809. $key,
  7810. 'style="padding-left:'.$padding.'px;"'
  7811. );
  7812. }
  7813. $position->setSelected($selectedPosition);
  7814. if (is_array($arrLP)) {
  7815. reset($arrLP);
  7816. }
  7817. if ($action != 'move') {
  7818. $arrHide = [];
  7819. for ($i = 0; $i < count($arrLP); $i++) {
  7820. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  7821. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  7822. ) {
  7823. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  7824. }
  7825. }
  7826. if (!$no_display_add) {
  7827. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  7828. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  7829. if ($extra_info == 'new' || $item_type == TOOL_DOCUMENT ||
  7830. $item_type == TOOL_LP_FINAL_ITEM || $edit == 'true'
  7831. ) {
  7832. if (isset($_POST['content'])) {
  7833. $content = stripslashes($_POST['content']);
  7834. } elseif (is_array($extra_info)) {
  7835. //If it's an html document or a text file
  7836. if (!$no_display_edit_textarea) {
  7837. $content = $this->display_document(
  7838. $extra_info['path'],
  7839. false,
  7840. false
  7841. );
  7842. }
  7843. } elseif (is_numeric($extra_info)) {
  7844. $content = $this->display_document(
  7845. $extra_info,
  7846. false,
  7847. false
  7848. );
  7849. } else {
  7850. $content = '';
  7851. }
  7852. if (!$no_display_edit_textarea) {
  7853. // We need to calculate here some specific settings for the online editor.
  7854. // The calculated settings work for documents in the Documents tool
  7855. // (on the root or in subfolders).
  7856. // For documents in native scorm packages it is unclear whether the
  7857. // online editor should be activated or not.
  7858. // A new document, it is in the root of the repository.
  7859. $relative_path = '';
  7860. $relative_prefix = '';
  7861. if (is_array($extra_info) && $extra_info != 'new') {
  7862. // The document already exists. Whe have to determine its relative path towards the repository root.
  7863. $relative_path = explode('/', $extra_info['dir']);
  7864. $cnt = count($relative_path) - 2;
  7865. if ($cnt < 0) {
  7866. $cnt = 0;
  7867. }
  7868. $relative_prefix = str_repeat('../', $cnt);
  7869. $relative_path = array_slice($relative_path, 1, $cnt);
  7870. $relative_path = implode('/', $relative_path);
  7871. if (strlen($relative_path) > 0) {
  7872. $relative_path = $relative_path.'/';
  7873. }
  7874. } else {
  7875. $result = $this->generate_lp_folder($_course);
  7876. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  7877. $relative_prefix = '../../';
  7878. }
  7879. $editor_config = [
  7880. 'ToolbarSet' => 'LearningPathDocuments',
  7881. 'Width' => '100%',
  7882. 'Height' => '500',
  7883. 'FullPage' => true,
  7884. 'CreateDocumentDir' => $relative_prefix,
  7885. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  7886. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  7887. ];
  7888. if ($_GET['action'] == 'add_item') {
  7889. $class = 'add';
  7890. $text = get_lang('LPCreateDocument');
  7891. } else {
  7892. if ($_GET['action'] == 'edit_item') {
  7893. $class = 'save';
  7894. $text = get_lang('SaveDocument');
  7895. }
  7896. }
  7897. $form->addButtonSave($text, 'submit_button');
  7898. $renderer = $form->defaultRenderer();
  7899. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp');
  7900. $form->addElement('html', '<div class="editor-lp">');
  7901. $form->addHtmlEditor('content_lp', null, null, true, $editor_config, true);
  7902. $form->addElement('html', '</div>');
  7903. $defaults['content_lp'] = $content;
  7904. }
  7905. } elseif (is_numeric($extra_info)) {
  7906. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7907. $return = $this->display_document($extra_info, true, true, true);
  7908. $form->addElement('html', $return);
  7909. }
  7910. }
  7911. }
  7912. if (isset($extra_info['item_type']) &&
  7913. $extra_info['item_type'] == TOOL_LP_FINAL_ITEM
  7914. ) {
  7915. $parentSelect->freeze();
  7916. $position->freeze();
  7917. }
  7918. if ($action == 'move') {
  7919. $form->addElement('hidden', 'title', $item_title);
  7920. $form->addElement('hidden', 'description', $item_description);
  7921. }
  7922. if (is_numeric($extra_info)) {
  7923. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7924. $form->addElement('hidden', 'path', $extra_info);
  7925. } elseif (is_array($extra_info)) {
  7926. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  7927. $form->addElement('hidden', 'path', $extra_info['path']);
  7928. }
  7929. $form->addElement('hidden', 'type', TOOL_DOCUMENT);
  7930. $form->addElement('hidden', 'post_time', time());
  7931. $form->setDefaults($defaults);
  7932. return $form->returnForm();
  7933. }
  7934. /**
  7935. * Returns the form to update or create a read-out text.
  7936. *
  7937. * @param string $action "add" or "edit"
  7938. * @param int $id ID of the lp_item (if already exists)
  7939. * @param mixed $extra_info Integer if document ID, string if info ('new')
  7940. *
  7941. * @throws Exception
  7942. * @throws HTML_QuickForm_Error
  7943. *
  7944. * @return string HTML form
  7945. */
  7946. public function displayFrmReadOutText($action = 'add', $id = 0, $extra_info = 'new')
  7947. {
  7948. $course_id = api_get_course_int_id();
  7949. $_course = api_get_course_info();
  7950. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  7951. $no_display_edit_textarea = false;
  7952. $item_description = '';
  7953. //If action==edit document
  7954. //We don't display the document form if it's not an editable document (html or txt file)
  7955. if ($action == 'edit') {
  7956. if (is_array($extra_info)) {
  7957. $path_parts = pathinfo($extra_info['dir']);
  7958. if ($path_parts['extension'] != "txt" && $path_parts['extension'] != "html") {
  7959. $no_display_edit_textarea = true;
  7960. }
  7961. }
  7962. }
  7963. $no_display_add = false;
  7964. $item_title = '';
  7965. $item_description = '';
  7966. if ($id != 0 && is_array($extra_info)) {
  7967. $item_title = stripslashes($extra_info['title']);
  7968. $item_description = stripslashes($extra_info['description']);
  7969. $item_terms = stripslashes($extra_info['terms']);
  7970. if (empty($item_title)) {
  7971. $path_parts = pathinfo($extra_info['path']);
  7972. $item_title = stripslashes($path_parts['filename']);
  7973. }
  7974. } elseif (is_numeric($extra_info)) {
  7975. $sql = "SELECT path, title FROM $tbl_doc WHERE c_id = ".$course_id." AND iid = ".intval($extra_info);
  7976. $result = Database::query($sql);
  7977. $row = Database::fetch_array($result);
  7978. $item_title = $row['title'];
  7979. $item_title = str_replace('_', ' ', $item_title);
  7980. if (empty($item_title)) {
  7981. $path_parts = pathinfo($row['path']);
  7982. $item_title = stripslashes($path_parts['filename']);
  7983. }
  7984. }
  7985. $parent = 0;
  7986. if ($id != 0 && is_array($extra_info)) {
  7987. $parent = $extra_info['parent_item_id'];
  7988. }
  7989. $arrLP = $this->getItemsForForm();
  7990. $this->tree_array($arrLP);
  7991. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  7992. unset($this->arrMenu);
  7993. if ($action === 'add') {
  7994. $formHeader = get_lang('CreateTheDocument');
  7995. } else {
  7996. $formHeader = get_lang('EditTheCurrentDocument');
  7997. }
  7998. if ('edit' === $action) {
  7999. $urlAudioIcon = Display::url(
  8000. Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY),
  8001. api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'&'
  8002. .http_build_query(['view' => 'build', 'id' => $id, 'action' => 'add_audio'])
  8003. );
  8004. } else {
  8005. $urlAudioIcon = Display::return_icon('audio.png', get_lang('CreateReadOutText'), [], ICON_SIZE_TINY);
  8006. }
  8007. $form = new FormValidator(
  8008. 'frm_add_reading',
  8009. 'POST',
  8010. $this->getCurrentBuildingModeURL(),
  8011. '',
  8012. ['enctype' => 'multipart/form-data']
  8013. );
  8014. $form->addHeader($formHeader);
  8015. $form->addHtml(
  8016. Display::return_message(
  8017. sprintf(get_lang('FrmReadOutTextIntro'), $urlAudioIcon),
  8018. 'normal',
  8019. false
  8020. )
  8021. );
  8022. $defaults['title'] = !empty($item_title) ? Security::remove_XSS($item_title) : '';
  8023. $defaults['description'] = $item_description;
  8024. $data = $this->generate_lp_folder($_course);
  8025. if ($action != 'edit') {
  8026. $folders = DocumentManager::get_all_document_folders($_course, 0, true);
  8027. DocumentManager::build_directory_selector(
  8028. $folders,
  8029. '',
  8030. [],
  8031. true,
  8032. $form,
  8033. 'directory_parent_id'
  8034. );
  8035. }
  8036. if (isset($data['id'])) {
  8037. $defaults['directory_parent_id'] = $data['id'];
  8038. }
  8039. $this->setItemTitle($form);
  8040. $arrHide[0]['value'] = $this->name;
  8041. $arrHide[0]['padding'] = 20;
  8042. for ($i = 0; $i < count($arrLP); $i++) {
  8043. if ($action != 'add') {
  8044. if ($arrLP[$i]['item_type'] == 'dir' &&
  8045. !in_array($arrLP[$i]['id'], $arrHide) &&
  8046. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8047. ) {
  8048. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8049. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8050. }
  8051. } else {
  8052. if ($arrLP[$i]['item_type'] == 'dir') {
  8053. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8054. $arrHide[$arrLP[$i]['id']]['padding'] = 20 + $arrLP[$i]['depth'] * 20;
  8055. }
  8056. }
  8057. }
  8058. $parent_select = $form->addSelect(
  8059. 'parent',
  8060. get_lang('Parent'),
  8061. [],
  8062. ['onchange' => "javascript: load_cbo(this.value, 'frm_add_reading_previous');"]
  8063. );
  8064. $my_count = 0;
  8065. foreach ($arrHide as $key => $value) {
  8066. if ($my_count != 0) {
  8067. // The LP name is also the first section and is not in the same charset like the other sections.
  8068. $value['value'] = Security::remove_XSS($value['value']);
  8069. $parent_select->addOption(
  8070. $value['value'],
  8071. $key,
  8072. 'style="padding-left:'.$value['padding'].'px;"'
  8073. );
  8074. } else {
  8075. $value['value'] = Security::remove_XSS($value['value']);
  8076. $parent_select->addOption(
  8077. $value['value'],
  8078. $key,
  8079. 'style="padding-left:'.$value['padding'].'px;"'
  8080. );
  8081. }
  8082. $my_count++;
  8083. }
  8084. if (!empty($id)) {
  8085. $parent_select->setSelected($parent);
  8086. } else {
  8087. $parent_item_id = Session::read('parent_item_id', 0);
  8088. $parent_select->setSelected($parent_item_id);
  8089. }
  8090. if (is_array($arrLP)) {
  8091. reset($arrLP);
  8092. }
  8093. $arrHide = [];
  8094. $s_selected_position = null;
  8095. // POSITION
  8096. $lastPosition = null;
  8097. for ($i = 0; $i < count($arrLP); $i++) {
  8098. if (($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) &&
  8099. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8100. ) {
  8101. if ((isset($extra_info['previous_item_id']) &&
  8102. $extra_info['previous_item_id'] == $arrLP[$i]['id']) || $action == 'add'
  8103. ) {
  8104. $s_selected_position = $arrLP[$i]['id'];
  8105. }
  8106. $arrHide[$arrLP[$i]['id']]['value'] = get_lang('After').' "'.$arrLP[$i]['title'].'"';
  8107. }
  8108. $lastPosition = $arrLP[$i]['id'];
  8109. }
  8110. if (empty($s_selected_position)) {
  8111. $s_selected_position = $lastPosition;
  8112. }
  8113. $position = $form->addSelect(
  8114. 'previous',
  8115. get_lang('Position'),
  8116. []
  8117. );
  8118. $position->addOption(get_lang('FirstPosition'), 0);
  8119. foreach ($arrHide as $key => $value) {
  8120. $padding = isset($value['padding']) ? $value['padding'] : 20;
  8121. $position->addOption(
  8122. $value['value'],
  8123. $key,
  8124. 'style="padding-left:'.$padding.'px;"'
  8125. );
  8126. }
  8127. $position->setSelected($s_selected_position);
  8128. if (is_array($arrLP)) {
  8129. reset($arrLP);
  8130. }
  8131. $arrHide = [];
  8132. for ($i = 0; $i < count($arrLP); $i++) {
  8133. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir' &&
  8134. $arrLP[$i]['item_type'] !== TOOL_LP_FINAL_ITEM
  8135. ) {
  8136. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8137. }
  8138. }
  8139. if (!$no_display_add) {
  8140. $item_type = isset($extra_info['item_type']) ? $extra_info['item_type'] : null;
  8141. $edit = isset($_GET['edit']) ? $_GET['edit'] : null;
  8142. if ($extra_info == 'new' || $item_type == TOOL_READOUT_TEXT || $edit == 'true') {
  8143. if (!$no_display_edit_textarea) {
  8144. $content = '';
  8145. if (isset($_POST['content'])) {
  8146. $content = stripslashes($_POST['content']);
  8147. } elseif (is_array($extra_info)) {
  8148. $content = $this->display_document($extra_info['path'], false, false);
  8149. } elseif (is_numeric($extra_info)) {
  8150. $content = $this->display_document($extra_info, false, false);
  8151. }
  8152. // A new document, it is in the root of the repository.
  8153. if (is_array($extra_info) && $extra_info != 'new') {
  8154. } else {
  8155. $this->generate_lp_folder($_course);
  8156. }
  8157. if ($_GET['action'] == 'add_item') {
  8158. $text = get_lang('LPCreateDocument');
  8159. } else {
  8160. $text = get_lang('SaveDocument');
  8161. }
  8162. $form->addTextarea('content_lp', get_lang('Content'), ['rows' => 20]);
  8163. $form
  8164. ->defaultRenderer()
  8165. ->setElementTemplate($form->getDefaultElementTemplate(), 'content_lp');
  8166. $form->addButtonSave($text, 'submit_button');
  8167. $defaults['content_lp'] = $content;
  8168. }
  8169. } elseif (is_numeric($extra_info)) {
  8170. $form->addButtonSave(get_lang('SaveDocument'), 'submit_button');
  8171. $return = $this->display_document($extra_info, true, true, true);
  8172. $form->addElement('html', $return);
  8173. }
  8174. }
  8175. if (is_numeric($extra_info)) {
  8176. $form->addElement('hidden', 'path', $extra_info);
  8177. } elseif (is_array($extra_info)) {
  8178. $form->addElement('hidden', 'path', $extra_info['path']);
  8179. }
  8180. $form->addElement('hidden', 'type', TOOL_READOUT_TEXT);
  8181. $form->addElement('hidden', 'post_time', time());
  8182. $form->setDefaults($defaults);
  8183. return $form->returnForm();
  8184. }
  8185. /**
  8186. * @param array $courseInfo
  8187. * @param string $content
  8188. * @param string $title
  8189. * @param int $parentId
  8190. *
  8191. * @throws \Doctrine\ORM\ORMException
  8192. * @throws \Doctrine\ORM\OptimisticLockException
  8193. * @throws \Doctrine\ORM\TransactionRequiredException
  8194. *
  8195. * @return int
  8196. */
  8197. public function createReadOutText($courseInfo, $content = '', $title = '', $parentId = 0)
  8198. {
  8199. $creatorId = api_get_user_id();
  8200. $sessionId = api_get_session_id();
  8201. // Generates folder
  8202. $result = $this->generate_lp_folder($courseInfo);
  8203. $dir = $result['dir'];
  8204. if (empty($parentId) || $parentId == '/') {
  8205. $postDir = isset($_POST['dir']) ? $_POST['dir'] : $dir;
  8206. $dir = isset($_GET['dir']) ? $_GET['dir'] : $postDir; // Please, do not modify this dirname formatting.
  8207. if ($parentId === '/') {
  8208. $dir = '/';
  8209. }
  8210. // Please, do not modify this dirname formatting.
  8211. if (strstr($dir, '..')) {
  8212. $dir = '/';
  8213. }
  8214. if (!empty($dir[0]) && $dir[0] == '.') {
  8215. $dir = substr($dir, 1);
  8216. }
  8217. if (!empty($dir[0]) && $dir[0] != '/') {
  8218. $dir = '/'.$dir;
  8219. }
  8220. if (isset($dir[strlen($dir) - 1]) && $dir[strlen($dir) - 1] != '/') {
  8221. $dir .= '/';
  8222. }
  8223. } else {
  8224. $parentInfo = DocumentManager::get_document_data_by_id(
  8225. $parentId,
  8226. $courseInfo['code']
  8227. );
  8228. if (!empty($parentInfo)) {
  8229. $dir = $parentInfo['path'].'/';
  8230. }
  8231. }
  8232. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8233. if (!is_dir($filepath)) {
  8234. $dir = '/';
  8235. $filepath = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document/'.$dir;
  8236. }
  8237. $originalTitle = !empty($title) ? $title : $_POST['title'];
  8238. if (!empty($title)) {
  8239. $title = api_replace_dangerous_char(stripslashes($title));
  8240. } else {
  8241. $title = api_replace_dangerous_char(stripslashes($_POST['title']));
  8242. }
  8243. $title = disable_dangerous_file($title);
  8244. $filename = $title;
  8245. $content = !empty($content) ? $content : $_POST['content_lp'];
  8246. $tmpFileName = $filename;
  8247. $i = 0;
  8248. while (file_exists($filepath.$tmpFileName.'.html')) {
  8249. $tmpFileName = $filename.'_'.++$i;
  8250. }
  8251. $filename = $tmpFileName.'.html';
  8252. $content = stripslashes($content);
  8253. if (file_exists($filepath.$filename)) {
  8254. return 0;
  8255. }
  8256. $putContent = file_put_contents($filepath.$filename, $content);
  8257. if ($putContent === false) {
  8258. return 0;
  8259. }
  8260. $fileSize = filesize($filepath.$filename);
  8261. $saveFilePath = $dir.$filename;
  8262. $documentId = add_document(
  8263. $courseInfo,
  8264. $saveFilePath,
  8265. 'file',
  8266. $fileSize,
  8267. $tmpFileName,
  8268. '',
  8269. 0, //readonly
  8270. true,
  8271. null,
  8272. $sessionId,
  8273. $creatorId
  8274. );
  8275. if (!$documentId) {
  8276. return 0;
  8277. }
  8278. api_item_property_update(
  8279. $courseInfo,
  8280. TOOL_DOCUMENT,
  8281. $documentId,
  8282. 'DocumentAdded',
  8283. $creatorId,
  8284. null,
  8285. null,
  8286. null,
  8287. null,
  8288. $sessionId
  8289. );
  8290. $newComment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
  8291. $newTitle = $originalTitle;
  8292. if ($newComment || $newTitle) {
  8293. $em = Database::getManager();
  8294. /** @var CDocument $doc */
  8295. $doc = $em->find('ChamiloCourseBundle:CDocument', $documentId);
  8296. if ($newComment) {
  8297. $doc->setComment($newComment);
  8298. }
  8299. if ($newTitle) {
  8300. $doc->setTitle($newTitle);
  8301. }
  8302. $em->persist($doc);
  8303. $em->flush();
  8304. }
  8305. return $documentId;
  8306. }
  8307. /**
  8308. * Return HTML form to add/edit a link item.
  8309. *
  8310. * @param string $action (add/edit)
  8311. * @param int $id Item ID if exists
  8312. * @param mixed $extra_info
  8313. *
  8314. * @throws Exception
  8315. * @throws HTML_QuickForm_Error
  8316. *
  8317. * @return string HTML form
  8318. */
  8319. public function display_link_form($action = 'add', $id = 0, $extra_info = '')
  8320. {
  8321. $course_id = api_get_course_int_id();
  8322. $tbl_link = Database::get_course_table(TABLE_LINK);
  8323. $item_title = '';
  8324. $item_description = '';
  8325. $item_url = '';
  8326. if ($id != 0 && is_array($extra_info)) {
  8327. $item_title = stripslashes($extra_info['title']);
  8328. $item_description = stripslashes($extra_info['description']);
  8329. $item_url = stripslashes($extra_info['url']);
  8330. } elseif (is_numeric($extra_info)) {
  8331. $extra_info = (int) $extra_info;
  8332. $sql = "SELECT title, description, url
  8333. FROM $tbl_link
  8334. WHERE c_id = $course_id AND iid = $extra_info";
  8335. $result = Database::query($sql);
  8336. $row = Database::fetch_array($result);
  8337. $item_title = $row['title'];
  8338. $item_description = $row['description'];
  8339. $item_url = $row['url'];
  8340. }
  8341. $form = new FormValidator(
  8342. 'edit_link',
  8343. 'POST',
  8344. $this->getCurrentBuildingModeURL()
  8345. );
  8346. $defaults = [];
  8347. $parent = 0;
  8348. if ($id != 0 && is_array($extra_info)) {
  8349. $parent = $extra_info['parent_item_id'];
  8350. }
  8351. $arrLP = $this->getItemsForForm();
  8352. $this->tree_array($arrLP);
  8353. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8354. unset($this->arrMenu);
  8355. if ($action == 'add') {
  8356. $legend = get_lang('CreateTheLink');
  8357. } elseif ($action == 'move') {
  8358. $legend = get_lang('MoveCurrentLink');
  8359. } else {
  8360. $legend = get_lang('EditCurrentLink');
  8361. }
  8362. $form->addHeader($legend);
  8363. if ($action != 'move') {
  8364. $this->setItemTitle($form);
  8365. $defaults['title'] = $item_title;
  8366. }
  8367. $selectParent = $form->addSelect(
  8368. 'parent',
  8369. get_lang('Parent'),
  8370. [],
  8371. ['id' => 'idParent', 'onchange' => 'load_cbo(this.value);', 'class' => 'learnpath_item_form']
  8372. );
  8373. $selectParent->addOption($this->name, 0);
  8374. $arrHide = [
  8375. $id,
  8376. ];
  8377. $parent_item_id = Session::read('parent_item_id', 0);
  8378. for ($i = 0; $i < count($arrLP); $i++) {
  8379. if ($action != 'add') {
  8380. if (
  8381. ($arrLP[$i]['item_type'] == 'dir') &&
  8382. !in_array($arrLP[$i]['id'], $arrHide) &&
  8383. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8384. ) {
  8385. $selectParent->addOption(
  8386. $arrLP[$i]['title'],
  8387. $arrLP[$i]['id'],
  8388. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px;']
  8389. );
  8390. if ($parent == $arrLP[$i]['id']) {
  8391. $selectParent->setSelected($arrLP[$i]['id']);
  8392. }
  8393. } else {
  8394. $arrHide[] = $arrLP[$i]['id'];
  8395. }
  8396. } else {
  8397. if ($arrLP[$i]['item_type'] == 'dir') {
  8398. $selectParent->addOption(
  8399. $arrLP[$i]['title'],
  8400. $arrLP[$i]['id'],
  8401. ['style' => 'padding-left: '.(20 + $arrLP[$i]['depth'] * 20).'px']
  8402. );
  8403. if ($parent_item_id == $arrLP[$i]['id']) {
  8404. $selectParent->setSelected($arrLP[$i]['id']);
  8405. }
  8406. }
  8407. }
  8408. }
  8409. if (is_array($arrLP)) {
  8410. reset($arrLP);
  8411. }
  8412. $selectPrevious = $form->addSelect(
  8413. 'previous',
  8414. get_lang('Position'),
  8415. [],
  8416. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8417. );
  8418. $selectPrevious->addOption(get_lang('FirstPosition'), 0);
  8419. for ($i = 0; $i < count($arrLP); $i++) {
  8420. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8421. $selectPrevious->addOption(
  8422. $arrLP[$i]['title'],
  8423. $arrLP[$i]['id']
  8424. );
  8425. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8426. $selectPrevious->setSelected($arrLP[$i]['id']);
  8427. } elseif ($action == 'add') {
  8428. $selectPrevious->setSelected($arrLP[$i]['id']);
  8429. }
  8430. }
  8431. }
  8432. if ($action != 'move') {
  8433. $urlAttributes = ['class' => 'learnpath_item_form'];
  8434. if (is_numeric($extra_info)) {
  8435. $urlAttributes['disabled'] = 'disabled';
  8436. }
  8437. $form->addElement('url', 'url', get_lang('Url'), $urlAttributes);
  8438. $defaults['url'] = $item_url;
  8439. $arrHide = [];
  8440. for ($i = 0; $i < count($arrLP); $i++) {
  8441. if ($arrLP[$i]['id'] != $id && $arrLP[$i]['item_type'] != 'dir') {
  8442. $arrHide[$arrLP[$i]['id']]['value'] = $arrLP[$i]['title'];
  8443. }
  8444. }
  8445. }
  8446. if ($action == 'add') {
  8447. $form->addButtonSave(get_lang('AddLinkToCourse'), 'submit_button');
  8448. } else {
  8449. $form->addButtonSave(get_lang('EditCurrentLink'), 'submit_button');
  8450. }
  8451. if ($action == 'move') {
  8452. $form->addHidden('title', $item_title);
  8453. $form->addHidden('description', $item_description);
  8454. }
  8455. if (is_numeric($extra_info)) {
  8456. $form->addHidden('path', $extra_info);
  8457. } elseif (is_array($extra_info)) {
  8458. $form->addHidden('path', $extra_info['path']);
  8459. }
  8460. $form->addHidden('type', TOOL_LINK);
  8461. $form->addHidden('post_time', time());
  8462. $form->setDefaults($defaults);
  8463. return '<div class="sectioncomment">'.$form->returnForm().'</div>';
  8464. }
  8465. /**
  8466. * Return HTML form to add/edit a student publication (work).
  8467. *
  8468. * @param string $action
  8469. * @param int $id Item ID if already exists
  8470. * @param string $extra_info
  8471. *
  8472. * @throws Exception
  8473. *
  8474. * @return string HTML form
  8475. */
  8476. public function display_student_publication_form(
  8477. $action = 'add',
  8478. $id = 0,
  8479. $extra_info = ''
  8480. ) {
  8481. $course_id = api_get_course_int_id();
  8482. $tbl_publication = Database::get_course_table(TABLE_STUDENT_PUBLICATION);
  8483. $item_title = get_lang('Student_publication');
  8484. if ($id != 0 && is_array($extra_info)) {
  8485. $item_title = stripslashes($extra_info['title']);
  8486. $item_description = stripslashes($extra_info['description']);
  8487. } elseif (is_numeric($extra_info)) {
  8488. $extra_info = (int) $extra_info;
  8489. $sql = "SELECT title, description
  8490. FROM $tbl_publication
  8491. WHERE c_id = $course_id AND id = ".$extra_info;
  8492. $result = Database::query($sql);
  8493. $row = Database::fetch_array($result);
  8494. if ($row) {
  8495. $item_title = $row['title'];
  8496. }
  8497. }
  8498. $parent = 0;
  8499. if ($id != 0 && is_array($extra_info)) {
  8500. $parent = $extra_info['parent_item_id'];
  8501. }
  8502. $arrLP = $this->getItemsForForm();
  8503. $this->tree_array($arrLP);
  8504. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8505. unset($this->arrMenu);
  8506. $form = new FormValidator('frm_student_publication', 'post', '#');
  8507. if ($action == 'add') {
  8508. $form->addHeader(get_lang('Student_publication'));
  8509. } elseif ($action == 'move') {
  8510. $form->addHeader(get_lang('MoveCurrentStudentPublication'));
  8511. } else {
  8512. $form->addHeader(get_lang('EditCurrentStudentPublication'));
  8513. }
  8514. if ($action != 'move') {
  8515. $this->setItemTitle($form);
  8516. }
  8517. $parentSelect = $form->addSelect(
  8518. 'parent',
  8519. get_lang('Parent'),
  8520. ['0' => $this->name],
  8521. [
  8522. 'onchange' => 'javascript: load_cbo(this.value);',
  8523. 'class' => 'learnpath_item_form',
  8524. 'id' => 'idParent',
  8525. ]
  8526. );
  8527. $arrHide = [$id];
  8528. for ($i = 0; $i < count($arrLP); $i++) {
  8529. if ($action != 'add') {
  8530. if (
  8531. ($arrLP[$i]['item_type'] == 'dir') &&
  8532. !in_array($arrLP[$i]['id'], $arrHide) &&
  8533. !in_array($arrLP[$i]['parent_item_id'], $arrHide)
  8534. ) {
  8535. $parentSelect->addOption(
  8536. $arrLP[$i]['title'],
  8537. $arrLP[$i]['id'],
  8538. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8539. );
  8540. if ($parent == $arrLP[$i]['id']) {
  8541. $parentSelect->setSelected($arrLP[$i]['id']);
  8542. }
  8543. } else {
  8544. $arrHide[] = $arrLP[$i]['id'];
  8545. }
  8546. } else {
  8547. if ($arrLP[$i]['item_type'] == 'dir') {
  8548. $parentSelect->addOption(
  8549. $arrLP[$i]['title'],
  8550. $arrLP[$i]['id'],
  8551. ['style' => 'padding-left: '.(($arrLP[$i]['depth'] * 10) + 20).'px;']
  8552. );
  8553. if ($parent == $arrLP[$i]['id']) {
  8554. $parentSelect->setSelected($arrLP[$i]['id']);
  8555. }
  8556. }
  8557. }
  8558. }
  8559. if (is_array($arrLP)) {
  8560. reset($arrLP);
  8561. }
  8562. $previousSelect = $form->addSelect(
  8563. 'previous',
  8564. get_lang('Position'),
  8565. ['0' => get_lang('FirstPosition')],
  8566. ['id' => 'previous', 'class' => 'learnpath_item_form']
  8567. );
  8568. for ($i = 0; $i < count($arrLP); $i++) {
  8569. if ($arrLP[$i]['parent_item_id'] == $parent && $arrLP[$i]['id'] != $id) {
  8570. $previousSelect->addOption(
  8571. get_lang('After').' "'.$arrLP[$i]['title'].'"',
  8572. $arrLP[$i]['id']
  8573. );
  8574. if ($extra_info['previous_item_id'] == $arrLP[$i]['id']) {
  8575. $previousSelect->setSelected($arrLP[$i]['id']);
  8576. } elseif ($action == 'add') {
  8577. $previousSelect->setSelected($arrLP[$i]['id']);
  8578. }
  8579. }
  8580. }
  8581. if ($action == 'add') {
  8582. $form->addButtonCreate(get_lang('AddAssignmentToCourse'), 'submit_button');
  8583. } else {
  8584. $form->addButtonCreate(get_lang('EditCurrentStudentPublication'), 'submit_button');
  8585. }
  8586. if ($action == 'move') {
  8587. $form->addHidden('title', $item_title);
  8588. $form->addHidden('description', $item_description);
  8589. }
  8590. if (is_numeric($extra_info)) {
  8591. $form->addHidden('path', $extra_info);
  8592. } elseif (is_array($extra_info)) {
  8593. $form->addHidden('path', $extra_info['path']);
  8594. }
  8595. $form->addHidden('type', TOOL_STUDENTPUBLICATION);
  8596. $form->addHidden('post_time', time());
  8597. $form->setDefaults(['title' => $item_title]);
  8598. $return = '<div class="sectioncomment">';
  8599. $return .= $form->returnForm();
  8600. $return .= '</div>';
  8601. return $return;
  8602. }
  8603. /**
  8604. * Displays the menu for manipulating a step.
  8605. *
  8606. * @param id $item_id
  8607. * @param string $item_type
  8608. *
  8609. * @return string
  8610. */
  8611. public function display_manipulate($item_id, $item_type = TOOL_DOCUMENT)
  8612. {
  8613. $_course = api_get_course_info();
  8614. $course_code = api_get_course_id();
  8615. $item_id = (int) $item_id;
  8616. $return = '<div class="actions">';
  8617. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8618. $sql = "SELECT * FROM $tbl_lp_item
  8619. WHERE iid = ".$item_id;
  8620. $result = Database::query($sql);
  8621. $row = Database::fetch_assoc($result);
  8622. $audio_player = null;
  8623. // We display an audio player if needed.
  8624. if (!empty($row['audio'])) {
  8625. $webAudioPath = '../..'.api_get_path(REL_COURSE_PATH).$_course['path'].'/document/audio/'.$row['audio'];
  8626. $audio_player .= '<div class="lp_mediaplayer" id="container">'
  8627. .'<audio src="'.$webAudioPath.'" controls>'
  8628. .'</div><br>';
  8629. }
  8630. $url = api_get_self().'?'.api_get_cidreq().'&view=build&id='.$item_id.'&lp_id='.$this->lp_id;
  8631. if ($item_type != TOOL_LP_FINAL_ITEM) {
  8632. $return .= Display::url(
  8633. Display::return_icon(
  8634. 'edit.png',
  8635. get_lang('Edit'),
  8636. [],
  8637. ICON_SIZE_SMALL
  8638. ),
  8639. $url.'&action=edit_item&path_item='.$row['path']
  8640. );
  8641. $return .= Display::url(
  8642. Display::return_icon(
  8643. 'move.png',
  8644. get_lang('Move'),
  8645. [],
  8646. ICON_SIZE_SMALL
  8647. ),
  8648. $url.'&action=move_item'
  8649. );
  8650. }
  8651. // Commented for now as prerequisites cannot be added to chapters.
  8652. if ($item_type != 'dir') {
  8653. $return .= Display::url(
  8654. Display::return_icon(
  8655. 'accept.png',
  8656. get_lang('LearnpathPrerequisites'),
  8657. [],
  8658. ICON_SIZE_SMALL
  8659. ),
  8660. $url.'&action=edit_item_prereq'
  8661. );
  8662. }
  8663. $return .= Display::url(
  8664. Display::return_icon(
  8665. 'delete.png',
  8666. get_lang('Delete'),
  8667. [],
  8668. ICON_SIZE_SMALL
  8669. ),
  8670. $url.'&action=delete_item'
  8671. );
  8672. if (in_array($item_type, [TOOL_DOCUMENT, TOOL_LP_FINAL_ITEM, TOOL_HOTPOTATOES])) {
  8673. $documentData = DocumentManager::get_document_data_by_id($row['path'], $course_code);
  8674. if (empty($documentData)) {
  8675. // Try with iid
  8676. $table = Database::get_course_table(TABLE_DOCUMENT);
  8677. $sql = "SELECT path FROM $table
  8678. WHERE
  8679. c_id = ".api_get_course_int_id()." AND
  8680. iid = ".$row['path']." AND
  8681. path NOT LIKE '%_DELETED_%'";
  8682. $result = Database::query($sql);
  8683. $documentData = Database::fetch_array($result);
  8684. if ($documentData) {
  8685. $documentData['absolute_path_from_document'] = '/document'.$documentData['path'];
  8686. }
  8687. }
  8688. if (isset($documentData['absolute_path_from_document'])) {
  8689. $return .= get_lang('File').': '.$documentData['absolute_path_from_document'];
  8690. }
  8691. }
  8692. $return .= '</div>';
  8693. if (!empty($audio_player)) {
  8694. $return .= $audio_player;
  8695. }
  8696. return $return;
  8697. }
  8698. /**
  8699. * Creates the javascript needed for filling up the checkboxes without page reload.
  8700. *
  8701. * @return string
  8702. */
  8703. public function get_js_dropdown_array()
  8704. {
  8705. $course_id = api_get_course_int_id();
  8706. $return = 'var child_name = new Array();'."\n";
  8707. $return .= 'var child_value = new Array();'."\n\n";
  8708. $return .= 'child_name[0] = new Array();'."\n";
  8709. $return .= 'child_value[0] = new Array();'."\n\n";
  8710. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8711. $sql = "SELECT * FROM ".$tbl_lp_item."
  8712. WHERE
  8713. c_id = $course_id AND
  8714. lp_id = ".$this->lp_id." AND
  8715. parent_item_id = 0
  8716. ORDER BY display_order ASC";
  8717. $res_zero = Database::query($sql);
  8718. $i = 0;
  8719. $list = $this->getItemsForForm(true);
  8720. foreach ($list as $row_zero) {
  8721. if ($row_zero['item_type'] !== TOOL_LP_FINAL_ITEM) {
  8722. if ($row_zero['item_type'] == TOOL_QUIZ) {
  8723. $row_zero['title'] = Exercise::get_formated_title_variable($row_zero['title']);
  8724. }
  8725. $js_var = json_encode(get_lang('After').' '.$row_zero['title']);
  8726. $return .= 'child_name[0]['.$i.'] = '.$js_var.' ;'."\n";
  8727. $return .= 'child_value[0]['.$i++.'] = "'.$row_zero['iid'].'";'."\n";
  8728. }
  8729. }
  8730. $return .= "\n";
  8731. $sql = "SELECT * FROM $tbl_lp_item
  8732. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8733. $res = Database::query($sql);
  8734. while ($row = Database::fetch_array($res)) {
  8735. $sql_parent = "SELECT * FROM ".$tbl_lp_item."
  8736. WHERE
  8737. c_id = ".$course_id." AND
  8738. parent_item_id = ".$row['iid']."
  8739. ORDER BY display_order ASC";
  8740. $res_parent = Database::query($sql_parent);
  8741. $i = 0;
  8742. $return .= 'child_name['.$row['iid'].'] = new Array();'."\n";
  8743. $return .= 'child_value['.$row['iid'].'] = new Array();'."\n\n";
  8744. while ($row_parent = Database::fetch_array($res_parent)) {
  8745. $js_var = json_encode(get_lang('After').' '.$this->cleanItemTitle($row_parent['title']));
  8746. $return .= 'child_name['.$row['iid'].']['.$i.'] = '.$js_var.' ;'."\n";
  8747. $return .= 'child_value['.$row['iid'].']['.$i++.'] = "'.$row_parent['iid'].'";'."\n";
  8748. }
  8749. $return .= "\n";
  8750. }
  8751. $return .= "
  8752. function load_cbo(id) {
  8753. if (!id) {
  8754. return false;
  8755. }
  8756. var cbo = document.getElementById('previous');
  8757. for(var i = cbo.length - 1; i > 0; i--) {
  8758. cbo.options[i] = null;
  8759. }
  8760. var k=0;
  8761. for(var i = 1; i <= child_name[id].length; i++){
  8762. var option = new Option(child_name[id][i - 1], child_value[id][i - 1]);
  8763. option.style.paddingLeft = '40px';
  8764. cbo.options[i] = option;
  8765. k = i;
  8766. }
  8767. cbo.options[k].selected = true;
  8768. $('#previous').selectpicker('refresh');
  8769. }";
  8770. return $return;
  8771. }
  8772. /**
  8773. * Display the form to allow moving an item.
  8774. *
  8775. * @param int $item_id Item ID
  8776. *
  8777. * @throws Exception
  8778. * @throws HTML_QuickForm_Error
  8779. *
  8780. * @return string HTML form
  8781. */
  8782. public function display_move_item($item_id)
  8783. {
  8784. $return = '';
  8785. if (is_numeric($item_id)) {
  8786. $item_id = (int) $item_id;
  8787. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8788. $sql = "SELECT * FROM $tbl_lp_item
  8789. WHERE iid = $item_id";
  8790. $res = Database::query($sql);
  8791. $row = Database::fetch_array($res);
  8792. switch ($row['item_type']) {
  8793. case 'dir':
  8794. case 'asset':
  8795. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8796. $return .= $this->display_item_form(
  8797. $row['item_type'],
  8798. get_lang('MoveCurrentChapter'),
  8799. 'move',
  8800. $item_id,
  8801. $row
  8802. );
  8803. break;
  8804. case TOOL_DOCUMENT:
  8805. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8806. $return .= $this->display_document_form('move', $item_id, $row);
  8807. break;
  8808. case TOOL_LINK:
  8809. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8810. $return .= $this->display_link_form('move', $item_id, $row);
  8811. break;
  8812. case TOOL_HOTPOTATOES:
  8813. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8814. $return .= $this->display_link_form('move', $item_id, $row);
  8815. break;
  8816. case TOOL_QUIZ:
  8817. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8818. $return .= $this->display_quiz_form('move', $item_id, $row);
  8819. break;
  8820. case TOOL_STUDENTPUBLICATION:
  8821. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8822. $return .= $this->display_student_publication_form('move', $item_id, $row);
  8823. break;
  8824. case TOOL_FORUM:
  8825. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8826. $return .= $this->display_forum_form('move', $item_id, $row);
  8827. break;
  8828. case TOOL_THREAD:
  8829. $return .= $this->display_manipulate($item_id, $row['item_type']);
  8830. $return .= $this->display_forum_form('move', $item_id, $row);
  8831. break;
  8832. }
  8833. }
  8834. return $return;
  8835. }
  8836. /**
  8837. * Return HTML form to allow prerequisites selection.
  8838. *
  8839. * @todo use FormValidator
  8840. *
  8841. * @param int Item ID
  8842. *
  8843. * @return string HTML form
  8844. */
  8845. public function display_item_prerequisites_form($item_id = 0)
  8846. {
  8847. $course_id = api_get_course_int_id();
  8848. $item_id = (int) $item_id;
  8849. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  8850. /* Current prerequisite */
  8851. $sql = "SELECT * FROM $tbl_lp_item
  8852. WHERE iid = $item_id";
  8853. $result = Database::query($sql);
  8854. $row = Database::fetch_array($result);
  8855. $prerequisiteId = $row['prerequisite'];
  8856. $return = '<legend>';
  8857. $return .= get_lang('AddEditPrerequisites');
  8858. $return .= '</legend>';
  8859. $return .= '<form method="POST">';
  8860. $return .= '<div class="table-responsive">';
  8861. $return .= '<table class="table table-hover">';
  8862. $return .= '<thead>';
  8863. $return .= '<tr>';
  8864. $return .= '<th>'.get_lang('LearnpathPrerequisites').'</th>';
  8865. $return .= '<th width="140">'.get_lang('Minimum').'</th>';
  8866. $return .= '<th width="140">'.get_lang('Maximum').'</th>';
  8867. $return .= '</tr>';
  8868. $return .= '</thead>';
  8869. // Adding the none option to the prerequisites see http://www.chamilo.org/es/node/146
  8870. $return .= '<tbody>';
  8871. $return .= '<tr>';
  8872. $return .= '<td colspan="3">';
  8873. $return .= '<div class="radio learnpath"><label for="idNone">';
  8874. $return .= '<input checked="checked" id="idNone" name="prerequisites" type="radio" />';
  8875. $return .= get_lang('None').'</label>';
  8876. $return .= '</div>';
  8877. $return .= '</tr>';
  8878. $sql = "SELECT * FROM $tbl_lp_item
  8879. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  8880. $result = Database::query($sql);
  8881. $selectedMinScore = [];
  8882. $selectedMaxScore = [];
  8883. $masteryScore = [];
  8884. while ($row = Database::fetch_array($result)) {
  8885. if ($row['iid'] == $item_id) {
  8886. $selectedMinScore[$row['prerequisite']] = $row['prerequisite_min_score'];
  8887. $selectedMaxScore[$row['prerequisite']] = $row['prerequisite_max_score'];
  8888. }
  8889. $masteryScore[$row['iid']] = $row['mastery_score'];
  8890. }
  8891. $arrLP = $this->getItemsForForm();
  8892. $this->tree_array($arrLP);
  8893. $arrLP = isset($this->arrMenu) ? $this->arrMenu : [];
  8894. unset($this->arrMenu);
  8895. for ($i = 0; $i < count($arrLP); $i++) {
  8896. $item = $arrLP[$i];
  8897. if ($item['id'] == $item_id) {
  8898. break;
  8899. }
  8900. $selectedMaxScoreValue = isset($selectedMaxScore[$item['id']]) ? $selectedMaxScore[$item['id']] : $item['max_score'];
  8901. $selectedMinScoreValue = isset($selectedMinScore[$item['id']]) ? $selectedMinScore[$item['id']] : 0;
  8902. $masteryScoreAsMinValue = isset($masteryScore[$item['id']]) ? $masteryScore[$item['id']] : 0;
  8903. $return .= '<tr>';
  8904. $return .= '<td '.(($item['item_type'] != TOOL_QUIZ && $item['item_type'] != TOOL_HOTPOTATOES) ? ' colspan="3"' : '').'>';
  8905. $return .= '<div style="margin-left:'.($item['depth'] * 20).'px;" class="radio learnpath">';
  8906. $return .= '<label for="id'.$item['id'].'">';
  8907. $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'].'" />';
  8908. $icon_name = str_replace(' ', '', $item['item_type']);
  8909. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8910. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8911. } else {
  8912. if (file_exists('../img/lp_'.$icon_name.'.png')) {
  8913. $return .= Display::return_icon('lp_'.$icon_name.'.png');
  8914. } else {
  8915. $return .= Display::return_icon('folder_document.png');
  8916. }
  8917. }
  8918. $return .= $item['title'].'</label>';
  8919. $return .= '</div>';
  8920. $return .= '</td>';
  8921. if ($item['item_type'] == TOOL_QUIZ) {
  8922. // lets update max_score Quiz information depending of the Quiz Advanced properties
  8923. $lpItemObj = new LpItem($course_id, $item['id']);
  8924. $exercise = new Exercise($course_id);
  8925. $exercise->read($lpItemObj->path);
  8926. $lpItemObj->max_score = $exercise->get_max_score();
  8927. $lpItemObj->update();
  8928. $item['max_score'] = $lpItemObj->max_score;
  8929. if (empty($selectedMinScoreValue) && !empty($masteryScoreAsMinValue)) {
  8930. // Backwards compatibility with 1.9.x use mastery_score as min value
  8931. $selectedMinScoreValue = $masteryScoreAsMinValue;
  8932. }
  8933. $return .= '<td>';
  8934. $return .= '<input
  8935. class="form-control"
  8936. size="4" maxlength="3"
  8937. name="min_'.$item['id'].'"
  8938. type="number"
  8939. min="0"
  8940. step="1"
  8941. max="'.$item['max_score'].'"
  8942. value="'.$selectedMinScoreValue.'"
  8943. />';
  8944. $return .= '</td>';
  8945. $return .= '<td>';
  8946. $return .= '<input
  8947. class="form-control"
  8948. size="4"
  8949. maxlength="3"
  8950. name="max_'.$item['id'].'"
  8951. type="number"
  8952. min="0"
  8953. step="1"
  8954. max="'.$item['max_score'].'"
  8955. value="'.$selectedMaxScoreValue.'"
  8956. />';
  8957. $return .= '</td>';
  8958. }
  8959. if ($item['item_type'] == TOOL_HOTPOTATOES) {
  8960. $return .= '<td>';
  8961. $return .= '<input
  8962. size="4"
  8963. maxlength="3"
  8964. name="min_'.$item['id'].'"
  8965. type="number"
  8966. min="0"
  8967. step="1"
  8968. max="'.$item['max_score'].'"
  8969. value="'.$selectedMinScoreValue.'"
  8970. />';
  8971. $return .= '</td>';
  8972. $return .= '<td>';
  8973. $return .= '<input
  8974. size="4"
  8975. maxlength="3"
  8976. name="max_'.$item['id'].'"
  8977. type="number"
  8978. min="0"
  8979. step="1"
  8980. max="'.$item['max_score'].'"
  8981. value="'.$selectedMaxScoreValue.'"
  8982. />';
  8983. $return .= '</td>';
  8984. }
  8985. $return .= '</tr>';
  8986. }
  8987. $return .= '<tr>';
  8988. $return .= '</tr>';
  8989. $return .= '</tbody>';
  8990. $return .= '</table>';
  8991. $return .= '</div>';
  8992. $return .= '<div class="form-group">';
  8993. $return .= '<button class="btn btn-primary" name="submit_button" type="submit">'.
  8994. get_lang('ModifyPrerequisites').'</button>';
  8995. $return .= '</form>';
  8996. return $return;
  8997. }
  8998. /**
  8999. * Return HTML list to allow prerequisites selection for lp.
  9000. *
  9001. * @return string HTML form
  9002. */
  9003. public function display_lp_prerequisites_list()
  9004. {
  9005. $course_id = api_get_course_int_id();
  9006. $lp_id = $this->lp_id;
  9007. $tbl_lp = Database::get_course_table(TABLE_LP_MAIN);
  9008. // get current prerequisite
  9009. $sql = "SELECT * FROM $tbl_lp WHERE iid = $lp_id ";
  9010. $result = Database::query($sql);
  9011. $row = Database::fetch_array($result);
  9012. $prerequisiteId = $row['prerequisite'];
  9013. $session_id = api_get_session_id();
  9014. $session_condition = api_get_session_condition($session_id, true, true);
  9015. $sql = "SELECT * FROM $tbl_lp
  9016. WHERE c_id = $course_id $session_condition
  9017. ORDER BY display_order ";
  9018. $rs = Database::query($sql);
  9019. $return = '';
  9020. $return .= '<select name="prerequisites" class="form-control">';
  9021. $return .= '<option value="0">'.get_lang('None').'</option>';
  9022. if (Database::num_rows($rs) > 0) {
  9023. while ($row = Database::fetch_array($rs)) {
  9024. if ($row['id'] == $lp_id) {
  9025. continue;
  9026. }
  9027. $return .= '<option value="'.$row['id'].'" '.(($row['id'] == $prerequisiteId) ? ' selected ' : '').'>'.$row['name'].'</option>';
  9028. }
  9029. }
  9030. $return .= '</select>';
  9031. return $return;
  9032. }
  9033. /**
  9034. * Creates a list with all the documents in it.
  9035. *
  9036. * @param bool $showInvisibleFiles
  9037. *
  9038. * @throws Exception
  9039. * @throws HTML_QuickForm_Error
  9040. *
  9041. * @return string
  9042. */
  9043. public function get_documents($showInvisibleFiles = false)
  9044. {
  9045. $course_info = api_get_course_info();
  9046. $sessionId = api_get_session_id();
  9047. $documentTree = DocumentManager::get_document_preview(
  9048. $course_info,
  9049. $this->lp_id,
  9050. null,
  9051. $sessionId,
  9052. true,
  9053. null,
  9054. null,
  9055. $showInvisibleFiles,
  9056. true
  9057. );
  9058. $headers = [
  9059. get_lang('Files'),
  9060. get_lang('CreateTheDocument'),
  9061. get_lang('CreateReadOutText'),
  9062. get_lang('Upload'),
  9063. ];
  9064. $form = new FormValidator(
  9065. 'form_upload',
  9066. 'POST',
  9067. $this->getCurrentBuildingModeURL(),
  9068. '',
  9069. ['enctype' => 'multipart/form-data']
  9070. );
  9071. $folders = DocumentManager::get_all_document_folders(
  9072. api_get_course_info(),
  9073. 0,
  9074. true
  9075. );
  9076. $lpPathInfo = $this->generate_lp_folder(api_get_course_info());
  9077. DocumentManager::build_directory_selector(
  9078. $folders,
  9079. $lpPathInfo['id'],
  9080. [],
  9081. true,
  9082. $form,
  9083. 'directory_parent_id'
  9084. );
  9085. $group = [
  9086. $form->createElement(
  9087. 'radio',
  9088. 'if_exists',
  9089. get_lang('UplWhatIfFileExists'),
  9090. get_lang('UplDoNothing'),
  9091. 'nothing'
  9092. ),
  9093. $form->createElement(
  9094. 'radio',
  9095. 'if_exists',
  9096. null,
  9097. get_lang('UplOverwriteLong'),
  9098. 'overwrite'
  9099. ),
  9100. $form->createElement(
  9101. 'radio',
  9102. 'if_exists',
  9103. null,
  9104. get_lang('UplRenameLong'),
  9105. 'rename'
  9106. ),
  9107. ];
  9108. $form->addGroup($group, null, get_lang('UplWhatIfFileExists'));
  9109. $fileExistsOption = api_get_setting('document_if_file_exists_option');
  9110. $defaultFileExistsOption = 'rename';
  9111. if (!empty($fileExistsOption)) {
  9112. $defaultFileExistsOption = $fileExistsOption;
  9113. }
  9114. $form->setDefaults(['if_exists' => $defaultFileExistsOption]);
  9115. // Check box options
  9116. $form->addElement(
  9117. 'checkbox',
  9118. 'unzip',
  9119. get_lang('Options'),
  9120. get_lang('Uncompress')
  9121. );
  9122. $url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath=';
  9123. $form->addMultipleUpload($url);
  9124. $new = $this->display_document_form('add', 0);
  9125. $frmReadOutText = $this->displayFrmReadOutText('add');
  9126. $tabs = Display::tabs(
  9127. $headers,
  9128. [$documentTree, $new, $frmReadOutText, $form->returnForm()],
  9129. 'subtab'
  9130. );
  9131. return $tabs;
  9132. }
  9133. /**
  9134. * Creates a list with all the exercises (quiz) in it.
  9135. *
  9136. * @return string
  9137. */
  9138. public function get_exercises()
  9139. {
  9140. $course_id = api_get_course_int_id();
  9141. $session_id = api_get_session_id();
  9142. $userInfo = api_get_user_info();
  9143. // New for hotpotatoes.
  9144. $uploadPath = DIR_HOTPOTATOES; //defined in main_api
  9145. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  9146. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  9147. $condition_session = api_get_session_condition($session_id, true, true);
  9148. $setting = api_get_configuration_value('show_invisible_exercise_in_lp_list');
  9149. $activeCondition = ' active <> -1 ';
  9150. if ($setting) {
  9151. $activeCondition = ' active = 1 ';
  9152. }
  9153. $categoryCondition = '';
  9154. $categoryId = isset($_REQUEST['category_id']) ? (int) $_REQUEST['category_id'] : 0;
  9155. if (api_get_configuration_value('allow_exercise_categories') && !empty($categoryId)) {
  9156. $categoryCondition = " AND exercise_category_id = $categoryId ";
  9157. }
  9158. $keywordCondition = '';
  9159. $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
  9160. if (!empty($keyword)) {
  9161. $keyword = Database::escape_string($keyword);
  9162. $keywordCondition = " AND title LIKE '%$keyword%' ";
  9163. }
  9164. $sql_quiz = "SELECT * FROM $tbl_quiz
  9165. WHERE
  9166. c_id = $course_id AND
  9167. $activeCondition
  9168. $condition_session
  9169. $categoryCondition
  9170. $keywordCondition
  9171. ORDER BY title ASC";
  9172. $sql_hot = "SELECT * FROM $tbl_doc
  9173. WHERE
  9174. c_id = $course_id AND
  9175. path LIKE '".$uploadPath."/%/%htm%'
  9176. $condition_session
  9177. ORDER BY id ASC";
  9178. $res_quiz = Database::query($sql_quiz);
  9179. $res_hot = Database::query($sql_hot);
  9180. $currentUrl = api_get_self().'?'.api_get_cidreq().'&action=add_item&type=step&lp_id='.$this->lp_id.'#resource_tab-2';
  9181. // Create a search-box
  9182. $form = new FormValidator('search_simple', 'get', $currentUrl);
  9183. $form->addHidden('action', 'add_item');
  9184. $form->addHidden('type', 'step');
  9185. $form->addHidden('lp_id', $this->lp_id);
  9186. $form->addHidden('lp_build_selected', '2');
  9187. $form->addCourseHiddenParams();
  9188. $form->addText(
  9189. 'keyword',
  9190. get_lang('Search'),
  9191. false,
  9192. [
  9193. 'aria-label' => get_lang('Search'),
  9194. ]
  9195. );
  9196. if (api_get_configuration_value('allow_exercise_categories')) {
  9197. $manager = new ExerciseCategoryManager();
  9198. $options = $manager->getCategoriesForSelect(api_get_course_int_id());
  9199. if (!empty($options)) {
  9200. $form->addSelect(
  9201. 'category_id',
  9202. get_lang('Category'),
  9203. $options,
  9204. ['placeholder' => get_lang('SelectAnOption')]
  9205. );
  9206. }
  9207. }
  9208. $form->addButtonSearch(get_lang('Search'));
  9209. $return = $form->returnForm();
  9210. $return .= '<ul class="lp_resource">';
  9211. $return .= '<li class="lp_resource_element">';
  9212. $return .= Display::return_icon('new_exercice.png');
  9213. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/exercise_admin.php?'.api_get_cidreq().'&lp_id='.$this->lp_id.'">'.
  9214. get_lang('NewExercise').'</a>';
  9215. $return .= '</li>';
  9216. $previewIcon = Display::return_icon(
  9217. 'preview_view.png',
  9218. get_lang('Preview')
  9219. );
  9220. $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_TINY);
  9221. $moveIcon = Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9222. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/showinframes.php?'.api_get_cidreq();
  9223. // Display hotpotatoes
  9224. while ($row_hot = Database::fetch_array($res_hot)) {
  9225. $link = Display::url(
  9226. $previewIcon,
  9227. $exerciseUrl.'&file='.$row_hot['path'],
  9228. ['target' => '_blank']
  9229. );
  9230. $return .= '<li class="lp_resource_element" data_id="'.$row_hot['id'].'" data_type="hotpotatoes" title="'.$row_hot['title'].'" >';
  9231. $return .= '<a class="moved" href="#">';
  9232. $return .= Display::return_icon(
  9233. 'move_everywhere.png',
  9234. get_lang('Move'),
  9235. [],
  9236. ICON_SIZE_TINY
  9237. );
  9238. $return .= '</a> ';
  9239. $return .= Display::return_icon('hotpotatoes_s.png');
  9240. $return .= '<a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_HOTPOTATOES.'&file='.$row_hot['id'].'&lp_id='.$this->lp_id.'">'.
  9241. ((!empty($row_hot['comment'])) ? $row_hot['comment'] : Security::remove_XSS($row_hot['title'])).$link.'</a>';
  9242. $return .= '</li>';
  9243. }
  9244. $exerciseUrl = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq();
  9245. while ($row_quiz = Database::fetch_array($res_quiz)) {
  9246. $title = strip_tags(
  9247. api_html_entity_decode($row_quiz['title'])
  9248. );
  9249. $visibility = api_get_item_visibility(
  9250. ['real_id' => $course_id],
  9251. TOOL_QUIZ,
  9252. $row_quiz['iid'],
  9253. $session_id
  9254. );
  9255. $link = Display::url(
  9256. $previewIcon,
  9257. $exerciseUrl.'&exerciseId='.$row_quiz['id'],
  9258. ['target' => '_blank']
  9259. );
  9260. $return .= '<li class="lp_resource_element" data_id="'.$row_quiz['id'].'" data_type="quiz" title="'.$title.'" >';
  9261. $return .= Display::url($moveIcon, '#', ['class' => 'moved']);
  9262. $return .= $quizIcon;
  9263. $sessionStar = api_get_session_image(
  9264. $row_quiz['session_id'],
  9265. $userInfo['status']
  9266. );
  9267. $return .= Display::url(
  9268. Security::remove_XSS(cut($title, 80)).$link.$sessionStar,
  9269. api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_QUIZ.'&file='.$row_quiz['id'].'&lp_id='.$this->lp_id,
  9270. [
  9271. 'class' => $visibility == 0 ? 'moved text-muted' : 'moved',
  9272. ]
  9273. );
  9274. $return .= '</li>';
  9275. }
  9276. $return .= '</ul>';
  9277. return $return;
  9278. }
  9279. /**
  9280. * Creates a list with all the links in it.
  9281. *
  9282. * @return string
  9283. */
  9284. public function get_links()
  9285. {
  9286. $selfUrl = api_get_self();
  9287. $courseIdReq = api_get_cidreq();
  9288. $course = api_get_course_info();
  9289. $userInfo = api_get_user_info();
  9290. $course_id = $course['real_id'];
  9291. $tbl_link = Database::get_course_table(TABLE_LINK);
  9292. $linkCategoryTable = Database::get_course_table(TABLE_LINK_CATEGORY);
  9293. $moveEverywhereIcon = Display::return_icon(
  9294. 'move_everywhere.png',
  9295. get_lang('Move'),
  9296. [],
  9297. ICON_SIZE_TINY
  9298. );
  9299. $session_id = api_get_session_id();
  9300. $condition_session = api_get_session_condition(
  9301. $session_id,
  9302. true,
  9303. true,
  9304. 'link.session_id'
  9305. );
  9306. $sql = "SELECT
  9307. link.id as link_id,
  9308. link.title as link_title,
  9309. link.session_id as link_session_id,
  9310. link.category_id as category_id,
  9311. link_category.category_title as category_title
  9312. FROM $tbl_link as link
  9313. LEFT JOIN $linkCategoryTable as link_category
  9314. ON (link.category_id = link_category.id AND link.c_id = link_category.c_id)
  9315. WHERE link.c_id = $course_id $condition_session
  9316. ORDER BY link_category.category_title ASC, link.title ASC";
  9317. $result = Database::query($sql);
  9318. $categorizedLinks = [];
  9319. $categories = [];
  9320. while ($link = Database::fetch_array($result)) {
  9321. if (!$link['category_id']) {
  9322. $link['category_title'] = get_lang('Uncategorized');
  9323. }
  9324. $categories[$link['category_id']] = $link['category_title'];
  9325. $categorizedLinks[$link['category_id']][$link['link_id']] = $link;
  9326. }
  9327. $linksHtmlCode =
  9328. '<script>
  9329. function toggle_tool(tool, id) {
  9330. if(document.getElementById(tool+"_"+id+"_content").style.display == "none"){
  9331. document.getElementById(tool+"_"+id+"_content").style.display = "block";
  9332. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9333. } else {
  9334. document.getElementById(tool+"_"+id+"_content").style.display = "none";
  9335. document.getElementById(tool+"_"+id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9336. }
  9337. }
  9338. </script>
  9339. <ul class="lp_resource">
  9340. <li class="lp_resource_element">
  9341. '.Display::return_icon('linksnew.gif').'
  9342. <a href="'.api_get_path(WEB_CODE_PATH).'link/link.php?'.$courseIdReq.'&action=addlink&lp_id='.$this->lp_id.'" title="'.get_lang('LinkAdd').'">'.
  9343. get_lang('LinkAdd').'
  9344. </a>
  9345. </li>';
  9346. foreach ($categorizedLinks as $categoryId => $links) {
  9347. $linkNodes = null;
  9348. foreach ($links as $key => $linkInfo) {
  9349. $title = $linkInfo['link_title'];
  9350. $linkSessionId = $linkInfo['link_session_id'];
  9351. $link = Display::url(
  9352. Display::return_icon('preview_view.png', get_lang('Preview')),
  9353. api_get_path(WEB_CODE_PATH).'link/link_goto.php?'.api_get_cidreq().'&link_id='.$key,
  9354. ['target' => '_blank']
  9355. );
  9356. if (api_get_item_visibility($course, TOOL_LINK, $key, $session_id) != 2) {
  9357. $sessionStar = api_get_session_image($linkSessionId, $userInfo['status']);
  9358. $linkNodes .=
  9359. '<li class="lp_resource_element" data_id="'.$key.'" data_type="'.TOOL_LINK.'" title="'.$title.'" >
  9360. <a class="moved" href="#">'.
  9361. $moveEverywhereIcon.
  9362. '</a>
  9363. '.Display::return_icon('links.png', '', [], ICON_SIZE_TINY).'
  9364. <a class="moved" href="'.$selfUrl.'?'.$courseIdReq.'&action=add_item&type='.
  9365. TOOL_LINK.'&file='.$key.'&lp_id='.$this->lp_id.'">'.
  9366. Security::remove_XSS($title).$sessionStar.$link.
  9367. '</a>
  9368. </li>';
  9369. }
  9370. }
  9371. $linksHtmlCode .=
  9372. '<li>
  9373. <a style="cursor:hand" onclick="javascript: toggle_tool(\''.TOOL_LINK.'\','.$categoryId.')" style="vertical-align:middle">
  9374. <img src="'.Display::returnIconPath('add.gif').'" id="'.TOOL_LINK.'_'.$categoryId.'_opener"
  9375. align="absbottom" />
  9376. </a>
  9377. <span style="vertical-align:middle">'.Security::remove_XSS($categories[$categoryId]).'</span>
  9378. </li>
  9379. <div style="display:none" id="'.TOOL_LINK.'_'.$categoryId.'_content">'.$linkNodes.'</div>';
  9380. }
  9381. $linksHtmlCode .= '</ul>';
  9382. return $linksHtmlCode;
  9383. }
  9384. /**
  9385. * Creates a list with all the student publications in it.
  9386. *
  9387. * @return string
  9388. */
  9389. public function get_student_publications()
  9390. {
  9391. $return = '<ul class="lp_resource">';
  9392. $return .= '<li class="lp_resource_element">';
  9393. $return .= Display::return_icon('works_new.gif');
  9394. $return .= ' <a href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&lp_id='.$this->lp_id.'">'.
  9395. get_lang('AddAssignmentPage').'</a>';
  9396. $return .= '</li>';
  9397. require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
  9398. $works = getWorkListTeacher(0, 100, null, null, null);
  9399. if (!empty($works)) {
  9400. foreach ($works as $work) {
  9401. $link = Display::url(
  9402. Display::return_icon('preview_view.png', get_lang('Preview')),
  9403. api_get_path(WEB_CODE_PATH).'work/work_list_all.php?'.api_get_cidreq().'&id='.$work['iid'],
  9404. ['target' => '_blank']
  9405. );
  9406. $return .= '<li class="lp_resource_element" data_id="'.$work['iid'].'" data_type="'.TOOL_STUDENTPUBLICATION.'" title="'.Security::remove_XSS(cut(strip_tags($work['title']), 80)).'">';
  9407. $return .= '<a class="moved" href="#">';
  9408. $return .= Display::return_icon(
  9409. 'move_everywhere.png',
  9410. get_lang('Move'),
  9411. [],
  9412. ICON_SIZE_TINY
  9413. );
  9414. $return .= '</a> ';
  9415. $return .= Display::return_icon('works.png', '', [], ICON_SIZE_TINY);
  9416. $return .= ' <a class="moved" href="'.api_get_self().'?'.api_get_cidreq().'&action=add_item&type='.TOOL_STUDENTPUBLICATION.'&file='.$work['iid'].'&lp_id='.$this->lp_id.'">'.
  9417. Security::remove_XSS(cut(strip_tags($work['title']), 80)).' '.$link.'
  9418. </a>';
  9419. $return .= '</li>';
  9420. }
  9421. }
  9422. $return .= '</ul>';
  9423. return $return;
  9424. }
  9425. /**
  9426. * Creates a list with all the forums in it.
  9427. *
  9428. * @return string
  9429. */
  9430. public function get_forums()
  9431. {
  9432. require_once '../forum/forumfunction.inc.php';
  9433. $forumCategories = get_forum_categories();
  9434. $forumsInNoCategory = get_forums_in_category(0);
  9435. if (!empty($forumsInNoCategory)) {
  9436. $forumCategories = array_merge(
  9437. $forumCategories,
  9438. [
  9439. [
  9440. 'cat_id' => 0,
  9441. 'session_id' => 0,
  9442. 'visibility' => 1,
  9443. 'cat_comment' => null,
  9444. ],
  9445. ]
  9446. );
  9447. }
  9448. $forumList = get_forums();
  9449. $a_forums = [];
  9450. foreach ($forumCategories as $forumCategory) {
  9451. // The forums in this category.
  9452. $forumsInCategory = get_forums_in_category($forumCategory['cat_id']);
  9453. if (!empty($forumsInCategory)) {
  9454. foreach ($forumList as $forum) {
  9455. if (isset($forum['forum_category']) &&
  9456. $forum['forum_category'] == $forumCategory['cat_id']
  9457. ) {
  9458. $a_forums[] = $forum;
  9459. }
  9460. }
  9461. }
  9462. }
  9463. $return = '<ul class="lp_resource">';
  9464. // First add link
  9465. $return .= '<li class="lp_resource_element">';
  9466. $return .= Display::return_icon('new_forum.png');
  9467. $return .= Display::url(
  9468. get_lang('CreateANewForum'),
  9469. api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq().'&'.http_build_query([
  9470. 'action' => 'add',
  9471. 'content' => 'forum',
  9472. 'lp_id' => $this->lp_id,
  9473. ]),
  9474. ['title' => get_lang('CreateANewForum')]
  9475. );
  9476. $return .= '</li>';
  9477. $return .= '<script>
  9478. function toggle_forum(forum_id) {
  9479. if (document.getElementById("forum_"+forum_id+"_content").style.display == "none") {
  9480. document.getElementById("forum_"+forum_id+"_content").style.display = "block";
  9481. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('remove.gif').'";
  9482. } else {
  9483. document.getElementById("forum_"+forum_id+"_content").style.display = "none";
  9484. document.getElementById("forum_"+forum_id+"_opener").src = "'.Display::returnIconPath('add.gif').'";
  9485. }
  9486. }
  9487. </script>';
  9488. foreach ($a_forums as $forum) {
  9489. if (!empty($forum['forum_id'])) {
  9490. $link = Display::url(
  9491. Display::return_icon('preview_view.png', get_lang('Preview')),
  9492. api_get_path(WEB_CODE_PATH).'forum/viewforum.php?'.api_get_cidreq().'&forum='.$forum['forum_id'],
  9493. ['target' => '_blank']
  9494. );
  9495. $return .= '<li class="lp_resource_element" data_id="'.$forum['forum_id'].'" data_type="'.TOOL_FORUM.'" title="'.$forum['forum_title'].'" >';
  9496. $return .= '<a class="moved" href="#">';
  9497. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9498. $return .= ' </a>';
  9499. $return .= Display::return_icon('forum.png', '', [], ICON_SIZE_TINY);
  9500. $return .= '<a onclick="javascript:toggle_forum('.$forum['forum_id'].');" style="cursor:hand; vertical-align:middle">
  9501. <img src="'.Display::returnIconPath('add.gif').'" id="forum_'.$forum['forum_id'].'_opener" align="absbottom" />
  9502. </a>
  9503. <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">'.
  9504. Security::remove_XSS($forum['forum_title']).' '.$link.'</a>';
  9505. $return .= '</li>';
  9506. $return .= '<div style="display:none" id="forum_'.$forum['forum_id'].'_content">';
  9507. $a_threads = get_threads($forum['forum_id']);
  9508. if (is_array($a_threads)) {
  9509. foreach ($a_threads as $thread) {
  9510. $link = Display::url(
  9511. Display::return_icon('preview_view.png', get_lang('Preview')),
  9512. api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.api_get_cidreq().'&forum='.$forum['forum_id'].'&thread='.$thread['thread_id'],
  9513. ['target' => '_blank']
  9514. );
  9515. $return .= '<li class="lp_resource_element" data_id="'.$thread['thread_id'].'" data_type="'.TOOL_THREAD.'" title="'.$thread['thread_title'].'" >';
  9516. $return .= '&nbsp;<a class="moved" href="#">';
  9517. $return .= Display::return_icon('move_everywhere.png', get_lang('Move'), [], ICON_SIZE_TINY);
  9518. $return .= ' </a>';
  9519. $return .= Display::return_icon('forumthread.png', get_lang('Thread'), [], ICON_SIZE_TINY);
  9520. $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.'">'.
  9521. Security::remove_XSS($thread['thread_title']).' '.$link.'</a>';
  9522. $return .= '</li>';
  9523. }
  9524. }
  9525. $return .= '</div>';
  9526. }
  9527. }
  9528. $return .= '</ul>';
  9529. return $return;
  9530. }
  9531. /**
  9532. * // TODO: The output encoding should be equal to the system encoding.
  9533. *
  9534. * Exports the learning path as a SCORM package. This is the main function that
  9535. * gathers the content, transforms it, writes the imsmanifest.xml file, zips the
  9536. * whole thing and returns the zip.
  9537. *
  9538. * This method needs to be called in PHP5, as it will fail with non-adequate
  9539. * XML package (like the ones for PHP4), and it is *not* a static method, so
  9540. * you need to call it on a learnpath object.
  9541. *
  9542. * @TODO The method might be redefined later on in the scorm class itself to avoid
  9543. * creating a SCORM structure if there is one already. However, if the initial SCORM
  9544. * path has been modified, it should use the generic method here below.
  9545. *
  9546. * @return string Returns the zip package string, or null if error
  9547. */
  9548. public function scormExport()
  9549. {
  9550. api_set_more_memory_and_time_limits();
  9551. $_course = api_get_course_info();
  9552. $course_id = $_course['real_id'];
  9553. // Create the zip handler (this will remain available throughout the method).
  9554. $archivePath = api_get_path(SYS_ARCHIVE_PATH);
  9555. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  9556. $temp_dir_short = uniqid('scorm_export', true);
  9557. $temp_zip_dir = $archivePath.'/'.$temp_dir_short;
  9558. $temp_zip_file = $temp_zip_dir.'/'.md5(time()).'.zip';
  9559. $zip_folder = new PclZip($temp_zip_file);
  9560. $current_course_path = api_get_path(SYS_COURSE_PATH).api_get_course_path();
  9561. $root_path = $main_path = api_get_path(SYS_PATH);
  9562. $files_cleanup = [];
  9563. // Place to temporarily stash the zip file.
  9564. // create the temp dir if it doesn't exist
  9565. // or do a cleanup before creating the zip file.
  9566. if (!is_dir($temp_zip_dir)) {
  9567. mkdir($temp_zip_dir, api_get_permissions_for_new_directories());
  9568. } else {
  9569. // Cleanup: Check the temp dir for old files and delete them.
  9570. $handle = opendir($temp_zip_dir);
  9571. while (false !== ($file = readdir($handle))) {
  9572. if ($file != '.' && $file != '..') {
  9573. unlink("$temp_zip_dir/$file");
  9574. }
  9575. }
  9576. closedir($handle);
  9577. }
  9578. $zip_files = $zip_files_abs = $zip_files_dist = [];
  9579. if (is_dir($current_course_path.'/scorm/'.$this->path) &&
  9580. is_file($current_course_path.'/scorm/'.$this->path.'/imsmanifest.xml')
  9581. ) {
  9582. // Remove the possible . at the end of the path.
  9583. $dest_path_to_lp = substr($this->path, -1) == '.' ? substr($this->path, 0, -1) : $this->path;
  9584. $dest_path_to_scorm_folder = str_replace('//', '/', $temp_zip_dir.'/scorm/'.$dest_path_to_lp);
  9585. mkdir(
  9586. $dest_path_to_scorm_folder,
  9587. api_get_permissions_for_new_directories(),
  9588. true
  9589. );
  9590. copyr(
  9591. $current_course_path.'/scorm/'.$this->path,
  9592. $dest_path_to_scorm_folder,
  9593. ['imsmanifest'],
  9594. $zip_files
  9595. );
  9596. }
  9597. // Build a dummy imsmanifest structure.
  9598. // Do not add to the zip yet (we still need it).
  9599. // This structure is developed following regulations for SCORM 1.2 packaging in the SCORM 1.2 Content
  9600. // Aggregation Model official document, section "2.3 Content Packaging".
  9601. // We are going to build a UTF-8 encoded manifest.
  9602. // Later we will recode it to the desired (and supported) encoding.
  9603. $xmldoc = new DOMDocument('1.0');
  9604. $root = $xmldoc->createElement('manifest');
  9605. $root->setAttribute('identifier', 'SingleCourseManifest');
  9606. $root->setAttribute('version', '1.1');
  9607. $root->setAttribute('xmlns', 'http://www.imsproject.org/xsd/imscp_rootv1p1p2');
  9608. $root->setAttribute('xmlns:adlcp', 'http://www.adlnet.org/xsd/adlcp_rootv1p2');
  9609. $root->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
  9610. $root->setAttribute(
  9611. 'xsi:schemaLocation',
  9612. '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'
  9613. );
  9614. // Build mandatory sub-root container elements.
  9615. $metadata = $xmldoc->createElement('metadata');
  9616. $md_schema = $xmldoc->createElement('schema', 'ADL SCORM');
  9617. $metadata->appendChild($md_schema);
  9618. $md_schemaversion = $xmldoc->createElement('schemaversion', '1.2');
  9619. $metadata->appendChild($md_schemaversion);
  9620. $root->appendChild($metadata);
  9621. $organizations = $xmldoc->createElement('organizations');
  9622. $resources = $xmldoc->createElement('resources');
  9623. // Build the only organization we will use in building our learnpaths.
  9624. $organizations->setAttribute('default', 'chamilo_scorm_export');
  9625. $organization = $xmldoc->createElement('organization');
  9626. $organization->setAttribute('identifier', 'chamilo_scorm_export');
  9627. // To set the title of the SCORM entity (=organization), we take the name given
  9628. // in Chamilo and convert it to HTML entities using the Chamilo charset (not the
  9629. // learning path charset) as it is the encoding that defines how it is stored
  9630. // in the database. Then we convert it to HTML entities again as the "&" character
  9631. // alone is not authorized in XML (must be &amp;).
  9632. // The title is then decoded twice when extracting (see scorm::parse_manifest).
  9633. $org_title = $xmldoc->createElement('title', api_utf8_encode($this->get_name()));
  9634. $organization->appendChild($org_title);
  9635. $folder_name = 'document';
  9636. // Removes the learning_path/scorm_folder path when exporting see #4841
  9637. $path_to_remove = '';
  9638. $path_to_replace = '';
  9639. $result = $this->generate_lp_folder($_course);
  9640. if (isset($result['dir']) && strpos($result['dir'], 'learning_path')) {
  9641. $path_to_remove = 'document'.$result['dir'];
  9642. $path_to_replace = $folder_name.'/';
  9643. }
  9644. // Fixes chamilo scorm exports
  9645. if ($this->ref === 'chamilo_scorm_export') {
  9646. $path_to_remove = 'scorm/'.$this->path.'/document/';
  9647. }
  9648. // For each element, add it to the imsmanifest structure, then add it to the zip.
  9649. $link_updates = [];
  9650. $links_to_create = [];
  9651. foreach ($this->ordered_items as $index => $itemId) {
  9652. /** @var learnpathItem $item */
  9653. $item = $this->items[$itemId];
  9654. if (!in_array($item->type, [TOOL_QUIZ, TOOL_FORUM, TOOL_THREAD, TOOL_LINK, TOOL_STUDENTPUBLICATION])) {
  9655. // Get included documents from this item.
  9656. if ($item->type === 'sco') {
  9657. $inc_docs = $item->get_resources_from_source(
  9658. null,
  9659. $current_course_path.'/scorm/'.$this->path.'/'.$item->get_path()
  9660. );
  9661. } else {
  9662. $inc_docs = $item->get_resources_from_source();
  9663. }
  9664. // Give a child element <item> to the <organization> element.
  9665. $my_item_id = $item->get_id();
  9666. $my_item = $xmldoc->createElement('item');
  9667. $my_item->setAttribute('identifier', 'ITEM_'.$my_item_id);
  9668. $my_item->setAttribute('identifierref', 'RESOURCE_'.$my_item_id);
  9669. $my_item->setAttribute('isvisible', 'true');
  9670. // Give a child element <title> to the <item> element.
  9671. $my_title = $xmldoc->createElement(
  9672. 'title',
  9673. htmlspecialchars(
  9674. api_utf8_encode($item->get_title()),
  9675. ENT_QUOTES,
  9676. 'UTF-8'
  9677. )
  9678. );
  9679. $my_item->appendChild($my_title);
  9680. // Give a child element <adlcp:prerequisites> to the <item> element.
  9681. $my_prereqs = $xmldoc->createElement(
  9682. 'adlcp:prerequisites',
  9683. $this->get_scorm_prereq_string($my_item_id)
  9684. );
  9685. $my_prereqs->setAttribute('type', 'aicc_script');
  9686. $my_item->appendChild($my_prereqs);
  9687. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9688. //$xmldoc->createElement('adlcp:maxtimeallowed','');
  9689. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9690. //$xmldoc->createElement('adlcp:timelimitaction','');
  9691. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9692. //$xmldoc->createElement('adlcp:datafromlms','');
  9693. // Give a child element <adlcp:masteryscore> to the <item> element.
  9694. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9695. $my_item->appendChild($my_masteryscore);
  9696. // Attach this item to the organization element or hits parent if there is one.
  9697. if (!empty($item->parent) && $item->parent != 0) {
  9698. $children = $organization->childNodes;
  9699. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  9700. if (is_object($possible_parent)) {
  9701. $possible_parent->appendChild($my_item);
  9702. } else {
  9703. if ($this->debug > 0) {
  9704. error_log('Parent ITEM_'.$item->parent.' of item ITEM_'.$my_item_id.' not found');
  9705. }
  9706. }
  9707. } else {
  9708. if ($this->debug > 0) {
  9709. error_log('No parent');
  9710. }
  9711. $organization->appendChild($my_item);
  9712. }
  9713. // Get the path of the file(s) from the course directory root.
  9714. $my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  9715. $my_xml_file_path = $my_file_path;
  9716. if (!empty($path_to_remove)) {
  9717. // From docs
  9718. $my_xml_file_path = str_replace($path_to_remove, $path_to_replace, $my_file_path);
  9719. // From quiz
  9720. if ($this->ref === 'chamilo_scorm_export') {
  9721. $path_to_remove = 'scorm/'.$this->path.'/';
  9722. $my_xml_file_path = str_replace($path_to_remove, '', $my_file_path);
  9723. }
  9724. }
  9725. $my_sub_dir = dirname($my_file_path);
  9726. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9727. $my_xml_sub_dir = $my_sub_dir;
  9728. // Give a <resource> child to the <resources> element
  9729. $my_resource = $xmldoc->createElement('resource');
  9730. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9731. $my_resource->setAttribute('type', 'webcontent');
  9732. $my_resource->setAttribute('href', $my_xml_file_path);
  9733. // adlcp:scormtype can be either 'sco' or 'asset'.
  9734. if ($item->type === 'sco') {
  9735. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  9736. } else {
  9737. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9738. }
  9739. // xml:base is the base directory to find the files declared in this resource.
  9740. $my_resource->setAttribute('xml:base', '');
  9741. // Give a <file> child to the <resource> element.
  9742. $my_file = $xmldoc->createElement('file');
  9743. $my_file->setAttribute('href', $my_xml_file_path);
  9744. $my_resource->appendChild($my_file);
  9745. // Dependency to other files - not yet supported.
  9746. $i = 1;
  9747. if ($inc_docs) {
  9748. foreach ($inc_docs as $doc_info) {
  9749. if (count($doc_info) < 1 || empty($doc_info[0])) {
  9750. continue;
  9751. }
  9752. $my_dep = $xmldoc->createElement('resource');
  9753. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  9754. $my_dep->setAttribute('identifier', $res_id);
  9755. $my_dep->setAttribute('type', 'webcontent');
  9756. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  9757. $my_dep_file = $xmldoc->createElement('file');
  9758. // Check type of URL.
  9759. if ($doc_info[1] == 'remote') {
  9760. // Remote file. Save url as is.
  9761. $my_dep_file->setAttribute('href', $doc_info[0]);
  9762. $my_dep->setAttribute('xml:base', '');
  9763. } elseif ($doc_info[1] === 'local') {
  9764. switch ($doc_info[2]) {
  9765. case 'url':
  9766. // Local URL - save path as url for now, don't zip file.
  9767. $abs_path = api_get_path(SYS_PATH).
  9768. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9769. $current_dir = dirname($abs_path);
  9770. $current_dir = str_replace('\\', '/', $current_dir);
  9771. $file_path = realpath($abs_path);
  9772. $file_path = str_replace('\\', '/', $file_path);
  9773. $my_dep_file->setAttribute('href', $file_path);
  9774. $my_dep->setAttribute('xml:base', '');
  9775. if (strstr($file_path, $main_path) !== false) {
  9776. // The calculated real path is really inside Chamilo's root path.
  9777. // Reduce file path to what's under the DocumentRoot.
  9778. $replace = $file_path;
  9779. $file_path = substr($file_path, strlen($root_path) - 1);
  9780. $destinationFile = $file_path;
  9781. if (strstr($file_path, 'upload/users') !== false) {
  9782. $pos = strpos($file_path, 'my_files/');
  9783. if ($pos !== false) {
  9784. $onlyDirectory = str_replace(
  9785. 'upload/users/',
  9786. '',
  9787. substr($file_path, $pos, strlen($file_path))
  9788. );
  9789. }
  9790. $replace = $onlyDirectory;
  9791. $destinationFile = $replace;
  9792. }
  9793. $zip_files_abs[] = $file_path;
  9794. $link_updates[$my_file_path][] = [
  9795. 'orig' => $doc_info[0],
  9796. 'dest' => $destinationFile,
  9797. 'replace' => $replace,
  9798. ];
  9799. $my_dep_file->setAttribute('href', $file_path);
  9800. $my_dep->setAttribute('xml:base', '');
  9801. } elseif (empty($file_path)) {
  9802. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  9803. $file_path = str_replace('//', '/', $file_path);
  9804. if (file_exists($file_path)) {
  9805. // We get the relative path.
  9806. $file_path = substr($file_path, strlen($current_dir));
  9807. $zip_files[] = $my_sub_dir.'/'.$file_path;
  9808. $link_updates[$my_file_path][] = [
  9809. 'orig' => $doc_info[0],
  9810. 'dest' => $file_path,
  9811. ];
  9812. $my_dep_file->setAttribute('href', $file_path);
  9813. $my_dep->setAttribute('xml:base', '');
  9814. }
  9815. }
  9816. break;
  9817. case 'abs':
  9818. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  9819. $my_dep_file->setAttribute('href', $doc_info[0]);
  9820. $my_dep->setAttribute('xml:base', '');
  9821. // The next lines fix a bug when using the "subdir" mode of Chamilo, whereas
  9822. // an image path would be constructed as /var/www/subdir/subdir/img/foo.bar
  9823. $abs_img_path_without_subdir = $doc_info[0];
  9824. $relp = api_get_path(REL_PATH); // The url-append config param.
  9825. $pos = strpos($abs_img_path_without_subdir, $relp);
  9826. if ($pos === 0) {
  9827. $abs_img_path_without_subdir = trim('/'.substr($abs_img_path_without_subdir, strlen($relp)));
  9828. }
  9829. $file_path = realpath(api_get_path(SYS_APP_PATH).$abs_img_path_without_subdir);
  9830. $file_path = str_replace(['\\', '//'], '/', $file_path);
  9831. // Prepare the current directory path (until just under 'document') with a trailing slash.
  9832. $cur_path = substr($current_course_path, -1) == '/' ? $current_course_path : $current_course_path.'/';
  9833. // Check if the current document is in that path.
  9834. if (strstr($file_path, $cur_path) !== false) {
  9835. $destinationFile = substr($file_path, strlen($cur_path));
  9836. $filePathNoCoursePart = substr($file_path, strlen($cur_path));
  9837. $fileToTest = $cur_path.$my_file_path;
  9838. if (!empty($path_to_remove)) {
  9839. $fileToTest = str_replace(
  9840. $path_to_remove.'/',
  9841. $path_to_replace,
  9842. $cur_path.$my_file_path
  9843. );
  9844. }
  9845. $relative_path = api_get_relative_path($fileToTest, $file_path);
  9846. // Put the current document in the zip (this array is the array
  9847. // that will manage documents already in the course folder - relative).
  9848. $zip_files[] = $filePathNoCoursePart;
  9849. // Update the links to the current document in the
  9850. // containing document (make them relative).
  9851. $link_updates[$my_file_path][] = [
  9852. 'orig' => $doc_info[0],
  9853. 'dest' => $destinationFile,
  9854. 'replace' => $relative_path,
  9855. ];
  9856. $my_dep_file->setAttribute('href', $file_path);
  9857. $my_dep->setAttribute('xml:base', '');
  9858. } elseif (strstr($file_path, $main_path) !== false) {
  9859. // The calculated real path is really inside Chamilo's root path.
  9860. // Reduce file path to what's under the DocumentRoot.
  9861. $file_path = substr($file_path, strlen($root_path));
  9862. $zip_files_abs[] = $file_path;
  9863. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9864. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9865. $my_dep->setAttribute('xml:base', '');
  9866. } elseif (empty($file_path)) {
  9867. // Probably this is an image inside "/main" directory
  9868. $file_path = api_get_path(SYS_PATH).$abs_img_path_without_subdir;
  9869. $abs_path = api_get_path(SYS_PATH).str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  9870. if (file_exists($file_path)) {
  9871. if (strstr($file_path, 'main/default_course_document') !== false) {
  9872. // We get the relative path.
  9873. $pos = strpos($file_path, 'main/default_course_document/');
  9874. if ($pos !== false) {
  9875. $onlyDirectory = str_replace(
  9876. 'main/default_course_document/',
  9877. '',
  9878. substr($file_path, $pos, strlen($file_path))
  9879. );
  9880. }
  9881. $destinationFile = 'default_course_document/'.$onlyDirectory;
  9882. $fileAbs = substr($file_path, strlen(api_get_path(SYS_PATH)));
  9883. $zip_files_abs[] = $fileAbs;
  9884. $link_updates[$my_file_path][] = [
  9885. 'orig' => $doc_info[0],
  9886. 'dest' => $destinationFile,
  9887. ];
  9888. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9889. $my_dep->setAttribute('xml:base', '');
  9890. }
  9891. }
  9892. }
  9893. break;
  9894. case 'rel':
  9895. // Path relative to the current document.
  9896. // Save xml:base as current document's directory and save file in zip as subdir.file_path
  9897. if (substr($doc_info[0], 0, 2) === '..') {
  9898. // Relative path going up.
  9899. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  9900. $current_dir = str_replace('\\', '/', $current_dir);
  9901. $file_path = realpath($current_dir.$doc_info[0]);
  9902. $file_path = str_replace('\\', '/', $file_path);
  9903. if (strstr($file_path, $main_path) !== false) {
  9904. // The calculated real path is really inside Chamilo's root path.
  9905. // Reduce file path to what's under the DocumentRoot.
  9906. $file_path = substr($file_path, strlen($root_path));
  9907. $zip_files_abs[] = $file_path;
  9908. $link_updates[$my_file_path][] = ['orig' => $doc_info[0], 'dest' => $file_path];
  9909. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  9910. $my_dep->setAttribute('xml:base', '');
  9911. }
  9912. } else {
  9913. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  9914. $my_dep_file->setAttribute('href', $doc_info[0]);
  9915. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  9916. }
  9917. break;
  9918. default:
  9919. $my_dep_file->setAttribute('href', $doc_info[0]);
  9920. $my_dep->setAttribute('xml:base', '');
  9921. break;
  9922. }
  9923. }
  9924. $my_dep->appendChild($my_dep_file);
  9925. $resources->appendChild($my_dep);
  9926. $dependency = $xmldoc->createElement('dependency');
  9927. $dependency->setAttribute('identifierref', $res_id);
  9928. $my_resource->appendChild($dependency);
  9929. $i++;
  9930. }
  9931. }
  9932. $resources->appendChild($my_resource);
  9933. $zip_files[] = $my_file_path;
  9934. } else {
  9935. // If the item is a quiz or a link or whatever non-exportable, we include a step indicating it.
  9936. switch ($item->type) {
  9937. case TOOL_LINK:
  9938. $my_item = $xmldoc->createElement('item');
  9939. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  9940. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  9941. $my_item->setAttribute('isvisible', 'true');
  9942. // Give a child element <title> to the <item> element.
  9943. $my_title = $xmldoc->createElement(
  9944. 'title',
  9945. htmlspecialchars(
  9946. api_utf8_encode($item->get_title()),
  9947. ENT_QUOTES,
  9948. 'UTF-8'
  9949. )
  9950. );
  9951. $my_item->appendChild($my_title);
  9952. // Give a child element <adlcp:prerequisites> to the <item> element.
  9953. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  9954. $my_prereqs->setAttribute('type', 'aicc_script');
  9955. $my_item->appendChild($my_prereqs);
  9956. // Give a child element <adlcp:maxtimeallowed> to the <item> element - not yet supported.
  9957. //$xmldoc->createElement('adlcp:maxtimeallowed', '');
  9958. // Give a child element <adlcp:timelimitaction> to the <item> element - not yet supported.
  9959. //$xmldoc->createElement('adlcp:timelimitaction', '');
  9960. // Give a child element <adlcp:datafromlms> to the <item> element - not yet supported.
  9961. //$xmldoc->createElement('adlcp:datafromlms', '');
  9962. // Give a child element <adlcp:masteryscore> to the <item> element.
  9963. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  9964. $my_item->appendChild($my_masteryscore);
  9965. // Attach this item to the organization element or its parent if there is one.
  9966. if (!empty($item->parent) && $item->parent != 0) {
  9967. $children = $organization->childNodes;
  9968. for ($i = 0; $i < $children->length; $i++) {
  9969. $item_temp = $children->item($i);
  9970. if ($item_temp->nodeName == 'item') {
  9971. if ($item_temp->getAttribute('identifier') == 'ITEM_'.$item->parent) {
  9972. $item_temp->appendChild($my_item);
  9973. }
  9974. }
  9975. }
  9976. } else {
  9977. $organization->appendChild($my_item);
  9978. }
  9979. $my_file_path = 'link_'.$item->get_id().'.html';
  9980. $sql = 'SELECT url, title FROM '.Database::get_course_table(TABLE_LINK).'
  9981. WHERE c_id = '.$course_id.' AND id = '.$item->path;
  9982. $rs = Database::query($sql);
  9983. if ($link = Database::fetch_array($rs)) {
  9984. $url = $link['url'];
  9985. $title = stripslashes($link['title']);
  9986. $links_to_create[$my_file_path] = ['title' => $title, 'url' => $url];
  9987. $my_xml_file_path = $my_file_path;
  9988. $my_sub_dir = dirname($my_file_path);
  9989. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  9990. $my_xml_sub_dir = $my_sub_dir;
  9991. // Give a <resource> child to the <resources> element.
  9992. $my_resource = $xmldoc->createElement('resource');
  9993. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  9994. $my_resource->setAttribute('type', 'webcontent');
  9995. $my_resource->setAttribute('href', $my_xml_file_path);
  9996. // adlcp:scormtype can be either 'sco' or 'asset'.
  9997. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  9998. // xml:base is the base directory to find the files declared in this resource.
  9999. $my_resource->setAttribute('xml:base', '');
  10000. // give a <file> child to the <resource> element.
  10001. $my_file = $xmldoc->createElement('file');
  10002. $my_file->setAttribute('href', $my_xml_file_path);
  10003. $my_resource->appendChild($my_file);
  10004. $resources->appendChild($my_resource);
  10005. }
  10006. break;
  10007. case TOOL_QUIZ:
  10008. $exe_id = $item->path;
  10009. // Should be using ref when everything will be cleaned up in this regard.
  10010. $exe = new Exercise();
  10011. $exe->read($exe_id);
  10012. $my_item = $xmldoc->createElement('item');
  10013. $my_item->setAttribute('identifier', 'ITEM_'.$item->get_id());
  10014. $my_item->setAttribute('identifierref', 'RESOURCE_'.$item->get_id());
  10015. $my_item->setAttribute('isvisible', 'true');
  10016. // Give a child element <title> to the <item> element.
  10017. $my_title = $xmldoc->createElement(
  10018. 'title',
  10019. htmlspecialchars(
  10020. api_utf8_encode($item->get_title()),
  10021. ENT_QUOTES,
  10022. 'UTF-8'
  10023. )
  10024. );
  10025. $my_item->appendChild($my_title);
  10026. $my_max_score = $xmldoc->createElement('max_score', $item->get_max());
  10027. $my_item->appendChild($my_max_score);
  10028. // Give a child element <adlcp:prerequisites> to the <item> element.
  10029. $my_prereqs = $xmldoc->createElement('adlcp:prerequisites', $item->get_prereq_string());
  10030. $my_prereqs->setAttribute('type', 'aicc_script');
  10031. $my_item->appendChild($my_prereqs);
  10032. // Give a child element <adlcp:masteryscore> to the <item> element.
  10033. $my_masteryscore = $xmldoc->createElement('adlcp:masteryscore', $item->get_mastery_score());
  10034. $my_item->appendChild($my_masteryscore);
  10035. // Attach this item to the organization element or hits parent if there is one.
  10036. if (!empty($item->parent) && $item->parent != 0) {
  10037. $children = $organization->childNodes;
  10038. $possible_parent = $this->get_scorm_xml_node($children, 'ITEM_'.$item->parent);
  10039. if ($possible_parent) {
  10040. if ($possible_parent->getAttribute('identifier') === 'ITEM_'.$item->parent) {
  10041. $possible_parent->appendChild($my_item);
  10042. }
  10043. }
  10044. } else {
  10045. $organization->appendChild($my_item);
  10046. }
  10047. // Get the path of the file(s) from the course directory root
  10048. //$my_file_path = $item->get_file_path('scorm/'.$this->path.'/');
  10049. $my_file_path = 'quiz_'.$item->get_id().'.html';
  10050. // Write the contents of the exported exercise into a (big) html file
  10051. // to later pack it into the exported SCORM. The file will be removed afterwards.
  10052. $scormExercise = new ScormExercise($exe, true);
  10053. $contents = $scormExercise->export();
  10054. $tmp_file_path = $archivePath.$temp_dir_short.'/'.$my_file_path;
  10055. $res = file_put_contents($tmp_file_path, $contents);
  10056. if ($res === false) {
  10057. error_log('Could not write into file '.$tmp_file_path.' '.__FILE__.' '.__LINE__, 0);
  10058. }
  10059. $files_cleanup[] = $tmp_file_path;
  10060. $my_xml_file_path = $my_file_path;
  10061. $my_sub_dir = dirname($my_file_path);
  10062. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10063. $my_xml_sub_dir = $my_sub_dir;
  10064. // Give a <resource> child to the <resources> element.
  10065. $my_resource = $xmldoc->createElement('resource');
  10066. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10067. $my_resource->setAttribute('type', 'webcontent');
  10068. $my_resource->setAttribute('href', $my_xml_file_path);
  10069. // adlcp:scormtype can be either 'sco' or 'asset'.
  10070. $my_resource->setAttribute('adlcp:scormtype', 'sco');
  10071. // xml:base is the base directory to find the files declared in this resource.
  10072. $my_resource->setAttribute('xml:base', '');
  10073. // Give a <file> child to the <resource> element.
  10074. $my_file = $xmldoc->createElement('file');
  10075. $my_file->setAttribute('href', $my_xml_file_path);
  10076. $my_resource->appendChild($my_file);
  10077. // Get included docs.
  10078. $inc_docs = $item->get_resources_from_source(null, $tmp_file_path);
  10079. // Dependency to other files - not yet supported.
  10080. $i = 1;
  10081. foreach ($inc_docs as $doc_info) {
  10082. if (count($doc_info) < 1 || empty($doc_info[0])) {
  10083. continue;
  10084. }
  10085. $my_dep = $xmldoc->createElement('resource');
  10086. $res_id = 'RESOURCE_'.$item->get_id().'_'.$i;
  10087. $my_dep->setAttribute('identifier', $res_id);
  10088. $my_dep->setAttribute('type', 'webcontent');
  10089. $my_dep->setAttribute('adlcp:scormtype', 'asset');
  10090. $my_dep_file = $xmldoc->createElement('file');
  10091. // Check type of URL.
  10092. if ($doc_info[1] == 'remote') {
  10093. // Remote file. Save url as is.
  10094. $my_dep_file->setAttribute('href', $doc_info[0]);
  10095. $my_dep->setAttribute('xml:base', '');
  10096. } elseif ($doc_info[1] == 'local') {
  10097. switch ($doc_info[2]) {
  10098. case 'url': // Local URL - save path as url for now, don't zip file.
  10099. // Save file but as local file (retrieve from URL).
  10100. $abs_path = api_get_path(SYS_PATH).
  10101. str_replace(api_get_path(WEB_PATH), '', $doc_info[0]);
  10102. $current_dir = dirname($abs_path);
  10103. $current_dir = str_replace('\\', '/', $current_dir);
  10104. $file_path = realpath($abs_path);
  10105. $file_path = str_replace('\\', '/', $file_path);
  10106. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10107. $my_dep->setAttribute('xml:base', '');
  10108. if (strstr($file_path, $main_path) !== false) {
  10109. // The calculated real path is really inside the chamilo root path.
  10110. // Reduce file path to what's under the DocumentRoot.
  10111. $file_path = substr($file_path, strlen($root_path));
  10112. $zip_files_abs[] = $file_path;
  10113. $link_updates[$my_file_path][] = [
  10114. 'orig' => $doc_info[0],
  10115. 'dest' => 'document/'.$file_path,
  10116. ];
  10117. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10118. $my_dep->setAttribute('xml:base', '');
  10119. } elseif (empty($file_path)) {
  10120. $file_path = $_SERVER['DOCUMENT_ROOT'].$abs_path;
  10121. $file_path = str_replace('//', '/', $file_path);
  10122. if (file_exists($file_path)) {
  10123. $file_path = substr($file_path, strlen($current_dir));
  10124. // We get the relative path.
  10125. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10126. $link_updates[$my_file_path][] = [
  10127. 'orig' => $doc_info[0],
  10128. 'dest' => 'document/'.$file_path,
  10129. ];
  10130. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10131. $my_dep->setAttribute('xml:base', '');
  10132. }
  10133. }
  10134. break;
  10135. case 'abs':
  10136. // Absolute path from DocumentRoot. Save file and leave path as is in the zip.
  10137. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10138. $current_dir = str_replace('\\', '/', $current_dir);
  10139. $file_path = realpath($doc_info[0]);
  10140. $file_path = str_replace('\\', '/', $file_path);
  10141. $my_dep_file->setAttribute('href', $file_path);
  10142. $my_dep->setAttribute('xml:base', '');
  10143. if (strstr($file_path, $main_path) !== false) {
  10144. // The calculated real path is really inside the chamilo root path.
  10145. // Reduce file path to what's under the DocumentRoot.
  10146. $file_path = substr($file_path, strlen($root_path));
  10147. $zip_files_abs[] = $file_path;
  10148. $link_updates[$my_file_path][] = [
  10149. 'orig' => $doc_info[0],
  10150. 'dest' => $file_path,
  10151. ];
  10152. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10153. $my_dep->setAttribute('xml:base', '');
  10154. } elseif (empty($file_path)) {
  10155. $docSysPartPath = str_replace(
  10156. api_get_path(REL_COURSE_PATH),
  10157. '',
  10158. $doc_info[0]
  10159. );
  10160. $docSysPartPathNoCourseCode = str_replace(
  10161. $_course['directory'].'/',
  10162. '',
  10163. $docSysPartPath
  10164. );
  10165. $docSysPath = api_get_path(SYS_COURSE_PATH).$docSysPartPath;
  10166. if (file_exists($docSysPath)) {
  10167. $file_path = $docSysPartPathNoCourseCode;
  10168. $zip_files[] = $my_sub_dir.'/'.$file_path;
  10169. $link_updates[$my_file_path][] = [
  10170. 'orig' => $doc_info[0],
  10171. 'dest' => $file_path,
  10172. ];
  10173. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10174. $my_dep->setAttribute('xml:base', '');
  10175. }
  10176. }
  10177. break;
  10178. case 'rel':
  10179. // Path relative to the current document. Save xml:base as current document's
  10180. // directory and save file in zip as subdir.file_path
  10181. if (substr($doc_info[0], 0, 2) === '..') {
  10182. // Relative path going up.
  10183. $current_dir = dirname($current_course_path.'/'.$item->get_file_path()).'/';
  10184. $current_dir = str_replace('\\', '/', $current_dir);
  10185. $file_path = realpath($current_dir.$doc_info[0]);
  10186. $file_path = str_replace('\\', '/', $file_path);
  10187. if (strstr($file_path, $main_path) !== false) {
  10188. // The calculated real path is really inside Chamilo's root path.
  10189. // Reduce file path to what's under the DocumentRoot.
  10190. $file_path = substr($file_path, strlen($root_path));
  10191. $file_path_dest = $file_path;
  10192. // File path is courses/CHAMILO/document/....
  10193. $info_file_path = explode('/', $file_path);
  10194. if ($info_file_path[0] == 'courses') {
  10195. // Add character "/" in file path.
  10196. $file_path_dest = 'document/'.$file_path;
  10197. }
  10198. $zip_files_abs[] = $file_path;
  10199. $link_updates[$my_file_path][] = [
  10200. 'orig' => $doc_info[0],
  10201. 'dest' => $file_path_dest,
  10202. ];
  10203. $my_dep_file->setAttribute('href', 'document/'.$file_path);
  10204. $my_dep->setAttribute('xml:base', '');
  10205. }
  10206. } else {
  10207. $zip_files[] = $my_sub_dir.'/'.$doc_info[0];
  10208. $my_dep_file->setAttribute('href', $doc_info[0]);
  10209. $my_dep->setAttribute('xml:base', $my_xml_sub_dir);
  10210. }
  10211. break;
  10212. default:
  10213. $my_dep_file->setAttribute('href', $doc_info[0]); // ../../courses/
  10214. $my_dep->setAttribute('xml:base', '');
  10215. break;
  10216. }
  10217. }
  10218. $my_dep->appendChild($my_dep_file);
  10219. $resources->appendChild($my_dep);
  10220. $dependency = $xmldoc->createElement('dependency');
  10221. $dependency->setAttribute('identifierref', $res_id);
  10222. $my_resource->appendChild($dependency);
  10223. $i++;
  10224. }
  10225. $resources->appendChild($my_resource);
  10226. $zip_files[] = $my_file_path;
  10227. break;
  10228. default:
  10229. // Get the path of the file(s) from the course directory root
  10230. $my_file_path = 'non_exportable.html';
  10231. //$my_xml_file_path = api_htmlentities(api_utf8_encode($my_file_path), ENT_COMPAT, 'UTF-8');
  10232. $my_xml_file_path = $my_file_path;
  10233. $my_sub_dir = dirname($my_file_path);
  10234. $my_sub_dir = str_replace('\\', '/', $my_sub_dir);
  10235. //$my_xml_sub_dir = api_htmlentities(api_utf8_encode($my_sub_dir), ENT_COMPAT, 'UTF-8');
  10236. $my_xml_sub_dir = $my_sub_dir;
  10237. // Give a <resource> child to the <resources> element.
  10238. $my_resource = $xmldoc->createElement('resource');
  10239. $my_resource->setAttribute('identifier', 'RESOURCE_'.$item->get_id());
  10240. $my_resource->setAttribute('type', 'webcontent');
  10241. $my_resource->setAttribute('href', $folder_name.'/'.$my_xml_file_path);
  10242. // adlcp:scormtype can be either 'sco' or 'asset'.
  10243. $my_resource->setAttribute('adlcp:scormtype', 'asset');
  10244. // xml:base is the base directory to find the files declared in this resource.
  10245. $my_resource->setAttribute('xml:base', '');
  10246. // Give a <file> child to the <resource> element.
  10247. $my_file = $xmldoc->createElement('file');
  10248. $my_file->setAttribute('href', 'document/'.$my_xml_file_path);
  10249. $my_resource->appendChild($my_file);
  10250. $resources->appendChild($my_resource);
  10251. break;
  10252. }
  10253. }
  10254. }
  10255. $organizations->appendChild($organization);
  10256. $root->appendChild($organizations);
  10257. $root->appendChild($resources);
  10258. $xmldoc->appendChild($root);
  10259. $copyAll = api_get_configuration_value('add_all_files_in_lp_export');
  10260. // then add the file to the zip, then destroy the file (this is done automatically).
  10261. // http://www.reload.ac.uk/scormplayer.html - once done, don't forget to close FS#138
  10262. foreach ($zip_files as $file_path) {
  10263. if (empty($file_path)) {
  10264. continue;
  10265. }
  10266. $filePath = $sys_course_path.$_course['path'].'/'.$file_path;
  10267. $dest_file = $archivePath.$temp_dir_short.'/'.$file_path;
  10268. if (!empty($path_to_remove) && !empty($path_to_replace)) {
  10269. $dest_file = str_replace($path_to_remove, $path_to_replace, $dest_file);
  10270. }
  10271. $this->create_path($dest_file);
  10272. @copy($filePath, $dest_file);
  10273. // Check if the file needs a link update.
  10274. if (in_array($file_path, array_keys($link_updates))) {
  10275. $string = file_get_contents($dest_file);
  10276. unlink($dest_file);
  10277. foreach ($link_updates[$file_path] as $old_new) {
  10278. // This is an ugly hack that allows .flv files to be found by the flv player that
  10279. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10280. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10281. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10282. if (substr($old_new['dest'], -3) === 'flv' &&
  10283. substr($old_new['dest'], 0, 5) === 'main/'
  10284. ) {
  10285. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10286. } elseif (substr($old_new['dest'], -3) === 'flv' &&
  10287. substr($old_new['dest'], 0, 6) === 'video/'
  10288. ) {
  10289. $old_new['dest'] = str_replace('video/', '../../../../video/', $old_new['dest']);
  10290. }
  10291. // Fix to avoid problems with default_course_document
  10292. if (strpos('main/default_course_document', $old_new['dest']) === false) {
  10293. $newDestination = $old_new['dest'];
  10294. if (isset($old_new['replace']) && !empty($old_new['replace'])) {
  10295. $newDestination = $old_new['replace'];
  10296. }
  10297. } else {
  10298. $newDestination = str_replace('document/', '', $old_new['dest']);
  10299. }
  10300. $string = str_replace($old_new['orig'], $newDestination, $string);
  10301. // Add files inside the HTMLs
  10302. $new_path = str_replace(api_get_path(REL_COURSE_PATH), '', $old_new['orig']);
  10303. $destinationFile = $archivePath.$temp_dir_short.'/'.$old_new['dest'];
  10304. if (file_exists($sys_course_path.$new_path) && is_file($sys_course_path.$new_path)) {
  10305. copy(
  10306. $sys_course_path.$new_path,
  10307. $destinationFile
  10308. );
  10309. }
  10310. }
  10311. file_put_contents($dest_file, $string);
  10312. }
  10313. if (file_exists($filePath) && $copyAll) {
  10314. $extension = $this->get_extension($filePath);
  10315. if (in_array($extension, ['html', 'html'])) {
  10316. $containerOrigin = dirname($filePath);
  10317. $containerDestination = dirname($dest_file);
  10318. $finder = new Finder();
  10319. $finder->files()->in($containerOrigin)
  10320. ->notName('*_DELETED_*')
  10321. ->exclude('share_folder')
  10322. ->exclude('chat_files')
  10323. ->exclude('certificates')
  10324. ;
  10325. if (is_dir($containerOrigin) &&
  10326. is_dir($containerDestination)
  10327. ) {
  10328. $fs = new Filesystem();
  10329. $fs->mirror(
  10330. $containerOrigin,
  10331. $containerDestination,
  10332. $finder
  10333. );
  10334. }
  10335. }
  10336. }
  10337. }
  10338. foreach ($zip_files_abs as $file_path) {
  10339. if (empty($file_path)) {
  10340. continue;
  10341. }
  10342. if (!is_file($main_path.$file_path) || !is_readable($main_path.$file_path)) {
  10343. continue;
  10344. }
  10345. $dest_file = $archivePath.$temp_dir_short.'/document/'.$file_path;
  10346. if (strstr($file_path, 'upload/users') !== false) {
  10347. $pos = strpos($file_path, 'my_files/');
  10348. if ($pos !== false) {
  10349. $onlyDirectory = str_replace(
  10350. 'upload/users/',
  10351. '',
  10352. substr($file_path, $pos, strlen($file_path))
  10353. );
  10354. $dest_file = $archivePath.$temp_dir_short.'/document/'.$onlyDirectory;
  10355. }
  10356. }
  10357. if (strstr($file_path, 'default_course_document/') !== false) {
  10358. $replace = str_replace('/main', '', $file_path);
  10359. $dest_file = $archivePath.$temp_dir_short.'/document/'.$replace;
  10360. }
  10361. if (empty($dest_file)) {
  10362. continue;
  10363. }
  10364. $this->create_path($dest_file);
  10365. copy($main_path.$file_path, $dest_file);
  10366. // Check if the file needs a link update.
  10367. if (in_array($file_path, array_keys($link_updates))) {
  10368. $string = file_get_contents($dest_file);
  10369. unlink($dest_file);
  10370. foreach ($link_updates[$file_path] as $old_new) {
  10371. // This is an ugly hack that allows .flv files to be found by the flv player that
  10372. // will be added in document/main/inc/lib/flv_player/flv_player.swf and that needs
  10373. // to find the flv to play in document/main/, so we replace main/ in the flv path by
  10374. // ../../.. to return from inc/lib/flv_player to the document/main path.
  10375. if (substr($old_new['dest'], -3) == 'flv' &&
  10376. substr($old_new['dest'], 0, 5) == 'main/'
  10377. ) {
  10378. $old_new['dest'] = str_replace('main/', '../../../', $old_new['dest']);
  10379. }
  10380. $string = str_replace($old_new['orig'], $old_new['dest'], $string);
  10381. }
  10382. file_put_contents($dest_file, $string);
  10383. }
  10384. }
  10385. if (is_array($links_to_create)) {
  10386. foreach ($links_to_create as $file => $link) {
  10387. $content = '<!DOCTYPE html><head>
  10388. <meta charset="'.api_get_language_isocode().'" />
  10389. <title>'.$link['title'].'</title>
  10390. </head>
  10391. <body dir="'.api_get_text_direction().'">
  10392. <div style="text-align:center">
  10393. <a href="'.$link['url'].'">'.$link['title'].'</a></div>
  10394. </body>
  10395. </html>';
  10396. file_put_contents($archivePath.$temp_dir_short.'/'.$file, $content);
  10397. }
  10398. }
  10399. // Add non exportable message explanation.
  10400. $lang_not_exportable = get_lang('ThisItemIsNotExportable');
  10401. $file_content = '<!DOCTYPE html><head>
  10402. <meta charset="'.api_get_language_isocode().'" />
  10403. <title>'.$lang_not_exportable.'</title>
  10404. <meta http-equiv="Content-Type" content="text/html; charset='.api_get_system_encoding().'" />
  10405. </head>
  10406. <body dir="'.api_get_text_direction().'">';
  10407. $file_content .=
  10408. <<<EOD
  10409. <style>
  10410. .error-message {
  10411. font-family: arial, verdana, helvetica, sans-serif;
  10412. border-width: 1px;
  10413. border-style: solid;
  10414. left: 50%;
  10415. margin: 10px auto;
  10416. min-height: 30px;
  10417. padding: 5px;
  10418. right: 50%;
  10419. width: 500px;
  10420. background-color: #FFD1D1;
  10421. border-color: #FF0000;
  10422. color: #000;
  10423. }
  10424. </style>
  10425. <body>
  10426. <div class="error-message">
  10427. $lang_not_exportable
  10428. </div>
  10429. </body>
  10430. </html>
  10431. EOD;
  10432. if (!is_dir($archivePath.$temp_dir_short.'/document')) {
  10433. @mkdir($archivePath.$temp_dir_short.'/document', api_get_permissions_for_new_directories());
  10434. }
  10435. file_put_contents($archivePath.$temp_dir_short.'/document/non_exportable.html', $file_content);
  10436. // Add the extra files that go along with a SCORM package.
  10437. $main_code_path = api_get_path(SYS_CODE_PATH).'lp/packaging/';
  10438. $fs = new Filesystem();
  10439. $fs->mirror($main_code_path, $archivePath.$temp_dir_short);
  10440. // Finalize the imsmanifest structure, add to the zip, then return the zip.
  10441. $manifest = @$xmldoc->saveXML();
  10442. $manifest = api_utf8_decode_xml($manifest); // The manifest gets the system encoding now.
  10443. file_put_contents($archivePath.'/'.$temp_dir_short.'/imsmanifest.xml', $manifest);
  10444. $zip_folder->add(
  10445. $archivePath.'/'.$temp_dir_short,
  10446. PCLZIP_OPT_REMOVE_PATH,
  10447. $archivePath.'/'.$temp_dir_short.'/'
  10448. );
  10449. // Clean possible temporary files.
  10450. foreach ($files_cleanup as $file) {
  10451. $res = unlink($file);
  10452. if ($res === false) {
  10453. error_log(
  10454. 'Could not delete temp file '.$file.' '.__FILE__.' '.__LINE__,
  10455. 0
  10456. );
  10457. }
  10458. }
  10459. $name = api_replace_dangerous_char($this->get_name()).'.zip';
  10460. DocumentManager::file_send_for_download($temp_zip_file, true, $name);
  10461. }
  10462. /**
  10463. * @param int $lp_id
  10464. *
  10465. * @return bool
  10466. */
  10467. public function scorm_export_to_pdf($lp_id)
  10468. {
  10469. $lp_id = (int) $lp_id;
  10470. $files_to_export = [];
  10471. $sessionId = api_get_session_id();
  10472. $course_data = api_get_course_info($this->cc);
  10473. if (!empty($course_data)) {
  10474. $scorm_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/scorm/'.$this->path;
  10475. $list = self::get_flat_ordered_items_list($lp_id);
  10476. if (!empty($list)) {
  10477. foreach ($list as $item_id) {
  10478. $item = $this->items[$item_id];
  10479. switch ($item->type) {
  10480. case 'document':
  10481. // Getting documents from a LP with chamilo documents
  10482. $file_data = DocumentManager::get_document_data_by_id($item->path, $this->cc);
  10483. // Try loading document from the base course.
  10484. if (empty($file_data) && !empty($sessionId)) {
  10485. $file_data = DocumentManager::get_document_data_by_id(
  10486. $item->path,
  10487. $this->cc,
  10488. false,
  10489. 0
  10490. );
  10491. }
  10492. $file_path = api_get_path(SYS_COURSE_PATH).$course_data['path'].'/document'.$file_data['path'];
  10493. if (file_exists($file_path)) {
  10494. $files_to_export[] = [
  10495. 'title' => $item->get_title(),
  10496. 'path' => $file_path,
  10497. ];
  10498. }
  10499. break;
  10500. case 'asset': //commes from a scorm package generated by chamilo
  10501. case 'sco':
  10502. $file_path = $scorm_path.'/'.$item->path;
  10503. if (file_exists($file_path)) {
  10504. $files_to_export[] = [
  10505. 'title' => $item->get_title(),
  10506. 'path' => $file_path,
  10507. ];
  10508. }
  10509. break;
  10510. case 'dir':
  10511. $files_to_export[] = [
  10512. 'title' => $item->get_title(),
  10513. 'path' => null,
  10514. ];
  10515. break;
  10516. }
  10517. }
  10518. }
  10519. $pdf = new PDF();
  10520. $result = $pdf->html_to_pdf(
  10521. $files_to_export,
  10522. $this->name,
  10523. $this->cc,
  10524. true,
  10525. true,
  10526. true,
  10527. $this->get_name()
  10528. );
  10529. return $result;
  10530. }
  10531. return false;
  10532. }
  10533. /**
  10534. * Temp function to be moved in main_api or the best place around for this.
  10535. * Creates a file path if it doesn't exist.
  10536. *
  10537. * @param string $path
  10538. */
  10539. public function create_path($path)
  10540. {
  10541. $path_bits = explode('/', dirname($path));
  10542. // IS_WINDOWS_OS has been defined in main_api.lib.php
  10543. $path_built = IS_WINDOWS_OS ? '' : '/';
  10544. foreach ($path_bits as $bit) {
  10545. if (!empty($bit)) {
  10546. $new_path = $path_built.$bit;
  10547. if (is_dir($new_path)) {
  10548. $path_built = $new_path.'/';
  10549. } else {
  10550. mkdir($new_path, api_get_permissions_for_new_directories());
  10551. $path_built = $new_path.'/';
  10552. }
  10553. }
  10554. }
  10555. }
  10556. /**
  10557. * Delete the image relative to this learning path. No parameter. Only works on instanciated object.
  10558. *
  10559. * @return bool The results of the unlink function, or false if there was no image to start with
  10560. */
  10561. public function delete_lp_image()
  10562. {
  10563. $img = $this->get_preview_image();
  10564. if ($img != '') {
  10565. $del_file = $this->get_preview_image_path(null, 'sys');
  10566. if (isset($del_file) && file_exists($del_file)) {
  10567. $del_file_2 = $this->get_preview_image_path(64, 'sys');
  10568. if (file_exists($del_file_2)) {
  10569. unlink($del_file_2);
  10570. }
  10571. $this->set_preview_image('');
  10572. return @unlink($del_file);
  10573. }
  10574. }
  10575. return false;
  10576. }
  10577. /**
  10578. * Uploads an author image to the upload/learning_path/images directory.
  10579. *
  10580. * @param array The image array, coming from the $_FILES superglobal
  10581. *
  10582. * @return bool True on success, false on error
  10583. */
  10584. public function upload_image($image_array)
  10585. {
  10586. if (!empty($image_array['name'])) {
  10587. $upload_ok = process_uploaded_file($image_array);
  10588. $has_attachment = true;
  10589. }
  10590. if ($upload_ok && $has_attachment) {
  10591. $courseDir = api_get_course_path().'/upload/learning_path/images';
  10592. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  10593. $updir = $sys_course_path.$courseDir;
  10594. // Try to add an extension to the file if it hasn't one.
  10595. $new_file_name = add_ext_on_mime(stripslashes($image_array['name']), $image_array['type']);
  10596. if (filter_extension($new_file_name)) {
  10597. $file_extension = explode('.', $image_array['name']);
  10598. $file_extension = strtolower($file_extension[sizeof($file_extension) - 1]);
  10599. $filename = uniqid('');
  10600. $new_file_name = $filename.'.'.$file_extension;
  10601. $new_path = $updir.'/'.$new_file_name;
  10602. // Resize the image.
  10603. $temp = new Image($image_array['tmp_name']);
  10604. $temp->resize(104);
  10605. $result = $temp->send_image($new_path);
  10606. // Storing the image filename.
  10607. if ($result) {
  10608. $this->set_preview_image($new_file_name);
  10609. //Resize to 64px to use on course homepage
  10610. $temp->resize(64);
  10611. $temp->send_image($updir.'/'.$filename.'.64.'.$file_extension);
  10612. return true;
  10613. }
  10614. }
  10615. }
  10616. return false;
  10617. }
  10618. /**
  10619. * @param int $lp_id
  10620. * @param string $status
  10621. */
  10622. public function set_autolaunch($lp_id, $status)
  10623. {
  10624. $course_id = api_get_course_int_id();
  10625. $lp_id = (int) $lp_id;
  10626. $status = (int) $status;
  10627. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  10628. // Setting everything to autolaunch = 0
  10629. $attributes['autolaunch'] = 0;
  10630. $where = [
  10631. 'session_id = ? AND c_id = ? ' => [
  10632. api_get_session_id(),
  10633. $course_id,
  10634. ],
  10635. ];
  10636. Database::update($lp_table, $attributes, $where);
  10637. if ($status == 1) {
  10638. //Setting my lp_id to autolaunch = 1
  10639. $attributes['autolaunch'] = 1;
  10640. $where = [
  10641. 'iid = ? AND session_id = ? AND c_id = ?' => [
  10642. $lp_id,
  10643. api_get_session_id(),
  10644. $course_id,
  10645. ],
  10646. ];
  10647. Database::update($lp_table, $attributes, $where);
  10648. }
  10649. }
  10650. /**
  10651. * Gets previous_item_id for the next element of the lp_item table.
  10652. *
  10653. * @author Isaac flores paz
  10654. *
  10655. * @return int Previous item ID
  10656. */
  10657. public function select_previous_item_id()
  10658. {
  10659. $course_id = api_get_course_int_id();
  10660. $table_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10661. // Get the max order of the items
  10662. $sql = "SELECT max(display_order) AS display_order FROM $table_lp_item
  10663. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  10664. $rs_max_order = Database::query($sql);
  10665. $row_max_order = Database::fetch_object($rs_max_order);
  10666. $max_order = $row_max_order->display_order;
  10667. // Get the previous item ID
  10668. $sql = "SELECT iid as previous FROM $table_lp_item
  10669. WHERE
  10670. c_id = $course_id AND
  10671. lp_id = ".$this->lp_id." AND
  10672. display_order = '$max_order' ";
  10673. $rs_max = Database::query($sql);
  10674. $row_max = Database::fetch_object($rs_max);
  10675. // Return the previous item ID
  10676. return $row_max->previous;
  10677. }
  10678. /**
  10679. * Copies an LP.
  10680. */
  10681. public function copy()
  10682. {
  10683. // Course builder
  10684. $cb = new CourseBuilder();
  10685. //Setting tools that will be copied
  10686. $cb->set_tools_to_build(['learnpaths']);
  10687. //Setting elements that will be copied
  10688. $cb->set_tools_specific_id_list(
  10689. ['learnpaths' => [$this->lp_id]]
  10690. );
  10691. $course = $cb->build();
  10692. //Course restorer
  10693. $course_restorer = new CourseRestorer($course);
  10694. $course_restorer->set_add_text_in_items(true);
  10695. $course_restorer->set_tool_copy_settings(
  10696. ['learnpaths' => ['reset_dates' => true]]
  10697. );
  10698. $course_restorer->restore(
  10699. api_get_course_id(),
  10700. api_get_session_id(),
  10701. false,
  10702. false
  10703. );
  10704. }
  10705. /**
  10706. * Verify document size.
  10707. *
  10708. * @param string $s
  10709. *
  10710. * @return bool
  10711. */
  10712. public static function verify_document_size($s)
  10713. {
  10714. $post_max = ini_get('post_max_size');
  10715. if (substr($post_max, -1, 1) == 'M') {
  10716. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
  10717. } elseif (substr($post_max, -1, 1) == 'G') {
  10718. $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
  10719. }
  10720. $upl_max = ini_get('upload_max_filesize');
  10721. if (substr($upl_max, -1, 1) == 'M') {
  10722. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
  10723. } elseif (substr($upl_max, -1, 1) == 'G') {
  10724. $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
  10725. }
  10726. $documents_total_space = DocumentManager::documents_total_space();
  10727. $course_max_space = DocumentManager::get_course_quota();
  10728. $total_size = filesize($s) + $documents_total_space;
  10729. if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
  10730. return true;
  10731. }
  10732. return false;
  10733. }
  10734. /**
  10735. * Clear LP prerequisites.
  10736. */
  10737. public function clear_prerequisites()
  10738. {
  10739. $course_id = $this->get_course_int_id();
  10740. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10741. $lp_id = $this->get_id();
  10742. // Cleaning prerequisites
  10743. $sql = "UPDATE $tbl_lp_item SET prerequisite = ''
  10744. WHERE c_id = $course_id AND lp_id = $lp_id";
  10745. Database::query($sql);
  10746. // Cleaning mastery score for exercises
  10747. $sql = "UPDATE $tbl_lp_item SET mastery_score = ''
  10748. WHERE c_id = $course_id AND lp_id = $lp_id AND item_type = 'quiz'";
  10749. Database::query($sql);
  10750. }
  10751. public function set_previous_step_as_prerequisite_for_all_items()
  10752. {
  10753. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  10754. $course_id = $this->get_course_int_id();
  10755. $lp_id = $this->get_id();
  10756. if (!empty($this->items)) {
  10757. $previous_item_id = null;
  10758. $previous_item_max = 0;
  10759. $previous_item_type = null;
  10760. $last_item_not_dir = null;
  10761. $last_item_not_dir_type = null;
  10762. $last_item_not_dir_max = null;
  10763. foreach ($this->ordered_items as $itemId) {
  10764. $item = $this->getItem($itemId);
  10765. // if there was a previous item... (otherwise jump to set it)
  10766. if (!empty($previous_item_id)) {
  10767. $current_item_id = $item->get_id(); //save current id
  10768. if ($item->get_type() != 'dir') {
  10769. // Current item is not a folder, so it qualifies to get a prerequisites
  10770. if ($last_item_not_dir_type == 'quiz') {
  10771. // if previous is quiz, mark its max score as default score to be achieved
  10772. $sql = "UPDATE $tbl_lp_item SET mastery_score = '$last_item_not_dir_max'
  10773. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $last_item_not_dir";
  10774. Database::query($sql);
  10775. }
  10776. // now simply update the prerequisite to set it to the last non-chapter item
  10777. $sql = "UPDATE $tbl_lp_item SET prerequisite = '$last_item_not_dir'
  10778. WHERE c_id = $course_id AND lp_id = $lp_id AND iid = $current_item_id";
  10779. Database::query($sql);
  10780. // record item as 'non-chapter' reference
  10781. $last_item_not_dir = $item->get_id();
  10782. $last_item_not_dir_type = $item->get_type();
  10783. $last_item_not_dir_max = $item->get_max();
  10784. }
  10785. } else {
  10786. if ($item->get_type() != 'dir') {
  10787. // Current item is not a folder (but it is the first item) so record as last "non-chapter" item
  10788. $last_item_not_dir = $item->get_id();
  10789. $last_item_not_dir_type = $item->get_type();
  10790. $last_item_not_dir_max = $item->get_max();
  10791. }
  10792. }
  10793. // Saving the item as "previous item" for the next loop
  10794. $previous_item_id = $item->get_id();
  10795. $previous_item_max = $item->get_max();
  10796. $previous_item_type = $item->get_type();
  10797. }
  10798. }
  10799. }
  10800. /**
  10801. * @param array $params
  10802. *
  10803. * @throws \Doctrine\ORM\OptimisticLockException
  10804. *
  10805. * @return int
  10806. */
  10807. public static function createCategory($params)
  10808. {
  10809. $em = Database::getManager();
  10810. $item = new CLpCategory();
  10811. $item->setName($params['name']);
  10812. $item->setCId($params['c_id']);
  10813. $em->persist($item);
  10814. $em->flush();
  10815. api_item_property_update(
  10816. api_get_course_info(),
  10817. TOOL_LEARNPATH_CATEGORY,
  10818. $item->getId(),
  10819. 'visible',
  10820. api_get_user_id()
  10821. );
  10822. return $item->getId();
  10823. }
  10824. /**
  10825. * @param array $params
  10826. *
  10827. * @throws \Doctrine\ORM\ORMException
  10828. * @throws \Doctrine\ORM\OptimisticLockException
  10829. * @throws \Doctrine\ORM\TransactionRequiredException
  10830. */
  10831. public static function updateCategory($params)
  10832. {
  10833. $em = Database::getManager();
  10834. /** @var CLpCategory $item */
  10835. $item = $em->find('ChamiloCourseBundle:CLpCategory', $params['id']);
  10836. if ($item) {
  10837. $item->setName($params['name']);
  10838. $em->merge($item);
  10839. $em->flush();
  10840. }
  10841. }
  10842. /**
  10843. * @param int $id
  10844. *
  10845. * @throws \Doctrine\ORM\ORMException
  10846. * @throws \Doctrine\ORM\OptimisticLockException
  10847. * @throws \Doctrine\ORM\TransactionRequiredException
  10848. */
  10849. public static function moveUpCategory($id)
  10850. {
  10851. $id = (int) $id;
  10852. $em = Database::getManager();
  10853. /** @var CLpCategory $item */
  10854. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10855. if ($item) {
  10856. $position = $item->getPosition() - 1;
  10857. $item->setPosition($position);
  10858. $em->persist($item);
  10859. $em->flush();
  10860. }
  10861. }
  10862. /**
  10863. * @param int $id
  10864. *
  10865. * @throws \Doctrine\ORM\ORMException
  10866. * @throws \Doctrine\ORM\OptimisticLockException
  10867. * @throws \Doctrine\ORM\TransactionRequiredException
  10868. */
  10869. public static function moveDownCategory($id)
  10870. {
  10871. $id = (int) $id;
  10872. $em = Database::getManager();
  10873. /** @var CLpCategory $item */
  10874. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10875. if ($item) {
  10876. $position = $item->getPosition() + 1;
  10877. $item->setPosition($position);
  10878. $em->persist($item);
  10879. $em->flush();
  10880. }
  10881. }
  10882. /**
  10883. * @param int $courseId
  10884. *
  10885. * @throws \Doctrine\ORM\Query\QueryException
  10886. *
  10887. * @return int|mixed
  10888. */
  10889. public static function getCountCategories($courseId)
  10890. {
  10891. if (empty($courseId)) {
  10892. return 0;
  10893. }
  10894. $em = Database::getManager();
  10895. $query = $em->createQuery('SELECT COUNT(u.id) FROM ChamiloCourseBundle:CLpCategory u WHERE u.cId = :id');
  10896. $query->setParameter('id', $courseId);
  10897. return $query->getSingleScalarResult();
  10898. }
  10899. /**
  10900. * @param int $courseId
  10901. *
  10902. * @return mixed
  10903. */
  10904. public static function getCategories($courseId)
  10905. {
  10906. $em = Database::getManager();
  10907. // Using doctrine extensions
  10908. /** @var SortableRepository $repo */
  10909. $repo = $em->getRepository('ChamiloCourseBundle:CLpCategory');
  10910. $items = $repo
  10911. ->getBySortableGroupsQuery(['cId' => $courseId])
  10912. ->getResult();
  10913. return $items;
  10914. }
  10915. /**
  10916. * @param int $id
  10917. *
  10918. * @throws \Doctrine\ORM\ORMException
  10919. * @throws \Doctrine\ORM\OptimisticLockException
  10920. * @throws \Doctrine\ORM\TransactionRequiredException
  10921. *
  10922. * @return CLpCategory
  10923. */
  10924. public static function getCategory($id)
  10925. {
  10926. $id = (int) $id;
  10927. $em = Database::getManager();
  10928. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10929. return $item;
  10930. }
  10931. /**
  10932. * @param int $courseId
  10933. *
  10934. * @return array
  10935. */
  10936. public static function getCategoryByCourse($courseId)
  10937. {
  10938. $em = Database::getManager();
  10939. $items = $em->getRepository('ChamiloCourseBundle:CLpCategory')->findBy(
  10940. ['cId' => $courseId]
  10941. );
  10942. return $items;
  10943. }
  10944. /**
  10945. * @param int $id
  10946. *
  10947. * @throws \Doctrine\ORM\ORMException
  10948. * @throws \Doctrine\ORM\OptimisticLockException
  10949. * @throws \Doctrine\ORM\TransactionRequiredException
  10950. *
  10951. * @return mixed
  10952. */
  10953. public static function deleteCategory($id)
  10954. {
  10955. $em = Database::getManager();
  10956. $item = $em->find('ChamiloCourseBundle:CLpCategory', $id);
  10957. if ($item) {
  10958. $courseId = $item->getCId();
  10959. $query = $em->createQuery('SELECT u FROM ChamiloCourseBundle:CLp u WHERE u.cId = :id AND u.categoryId = :catId');
  10960. $query->setParameter('id', $courseId);
  10961. $query->setParameter('catId', $item->getId());
  10962. $lps = $query->getResult();
  10963. // Setting category = 0.
  10964. if ($lps) {
  10965. foreach ($lps as $lpItem) {
  10966. $lpItem->setCategoryId(0);
  10967. }
  10968. }
  10969. // Removing category.
  10970. $em->remove($item);
  10971. $em->flush();
  10972. $courseInfo = api_get_course_info_by_id($courseId);
  10973. $sessionId = api_get_session_id();
  10974. // Delete link tool
  10975. $tbl_tool = Database::get_course_table(TABLE_TOOL_LIST);
  10976. $link = 'lp/lp_controller.php?cidReq='.$courseInfo['code'].'&id_session='.$sessionId.'&gidReq=0&gradebook=0&origin=&action=view_category&id='.$id;
  10977. // Delete tools
  10978. $sql = "DELETE FROM $tbl_tool
  10979. WHERE c_id = ".$courseId." AND (link LIKE '$link%' AND image='lp_category.gif')";
  10980. Database::query($sql);
  10981. return true;
  10982. }
  10983. return false;
  10984. }
  10985. /**
  10986. * @param int $courseId
  10987. * @param bool $addSelectOption
  10988. *
  10989. * @return mixed
  10990. */
  10991. public static function getCategoryFromCourseIntoSelect($courseId, $addSelectOption = false)
  10992. {
  10993. $items = self::getCategoryByCourse($courseId);
  10994. $cats = [];
  10995. if ($addSelectOption) {
  10996. $cats = [get_lang('SelectACategory')];
  10997. }
  10998. if (!empty($items)) {
  10999. foreach ($items as $cat) {
  11000. $cats[$cat->getId()] = $cat->getName();
  11001. }
  11002. }
  11003. return $cats;
  11004. }
  11005. /**
  11006. * @param string $courseCode
  11007. * @param int $lpId
  11008. * @param int $user_id
  11009. *
  11010. * @return learnpath
  11011. */
  11012. public static function getLpFromSession($courseCode, $lpId, $user_id)
  11013. {
  11014. $debug = 0;
  11015. $learnPath = null;
  11016. $lpObject = Session::read('lpobject');
  11017. if ($lpObject !== null) {
  11018. $learnPath = UnserializeApi::unserialize('lp', $lpObject);
  11019. if ($debug) {
  11020. error_log('getLpFromSession: unserialize');
  11021. error_log('------getLpFromSession------');
  11022. error_log('------unserialize------');
  11023. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11024. error_log("api_get_sessionid: ".api_get_session_id());
  11025. }
  11026. }
  11027. if (!is_object($learnPath)) {
  11028. $learnPath = new learnpath($courseCode, $lpId, $user_id);
  11029. if ($debug) {
  11030. error_log('------getLpFromSession------');
  11031. error_log('getLpFromSession: create new learnpath');
  11032. error_log("create new LP with $courseCode - $lpId - $user_id");
  11033. error_log("lp_view_session_id: ".$learnPath->lp_view_session_id);
  11034. error_log("api_get_sessionid: ".api_get_session_id());
  11035. }
  11036. }
  11037. return $learnPath;
  11038. }
  11039. /**
  11040. * @param int $itemId
  11041. *
  11042. * @return learnpathItem|false
  11043. */
  11044. public function getItem($itemId)
  11045. {
  11046. if (isset($this->items[$itemId]) && is_object($this->items[$itemId])) {
  11047. return $this->items[$itemId];
  11048. }
  11049. return false;
  11050. }
  11051. /**
  11052. * @return int
  11053. */
  11054. public function getCurrentAttempt()
  11055. {
  11056. $attempt = $this->getItem($this->get_current_item_id());
  11057. if ($attempt) {
  11058. $attemptId = $attempt->get_attempt_id();
  11059. return $attemptId;
  11060. }
  11061. return 0;
  11062. }
  11063. /**
  11064. * @return int
  11065. */
  11066. public function getCategoryId()
  11067. {
  11068. return (int) $this->categoryId;
  11069. }
  11070. /**
  11071. * @param int $categoryId
  11072. *
  11073. * @return bool
  11074. */
  11075. public function setCategoryId($categoryId)
  11076. {
  11077. $this->categoryId = (int) $categoryId;
  11078. $table = Database::get_course_table(TABLE_LP_MAIN);
  11079. $lp_id = $this->get_id();
  11080. $sql = "UPDATE $table SET category_id = ".$this->categoryId."
  11081. WHERE iid = $lp_id";
  11082. Database::query($sql);
  11083. return true;
  11084. }
  11085. /**
  11086. * Get whether this is a learning path with the possibility to subscribe
  11087. * users or not.
  11088. *
  11089. * @return int
  11090. */
  11091. public function getSubscribeUsers()
  11092. {
  11093. return $this->subscribeUsers;
  11094. }
  11095. /**
  11096. * Set whether this is a learning path with the possibility to subscribe
  11097. * users or not.
  11098. *
  11099. * @param int $value (0 = false, 1 = true)
  11100. *
  11101. * @return bool
  11102. */
  11103. public function setSubscribeUsers($value)
  11104. {
  11105. $this->subscribeUsers = (int) $value;
  11106. $table = Database::get_course_table(TABLE_LP_MAIN);
  11107. $lp_id = $this->get_id();
  11108. $sql = "UPDATE $table SET subscribe_users = ".$this->subscribeUsers."
  11109. WHERE iid = $lp_id";
  11110. Database::query($sql);
  11111. return true;
  11112. }
  11113. /**
  11114. * Calculate the count of stars for a user in this LP
  11115. * This calculation is based on the following rules:
  11116. * - the student gets one star when he gets to 50% of the learning path
  11117. * - the student gets a second star when the average score of all tests inside the learning path >= 50%
  11118. * - the student gets a third star when the average score of all tests inside the learning path >= 80%
  11119. * - the student gets the final star when the score for the *last* test is >= 80%.
  11120. *
  11121. * @param int $sessionId Optional. The session ID
  11122. *
  11123. * @return int The count of stars
  11124. */
  11125. public function getCalculateStars($sessionId = 0)
  11126. {
  11127. $stars = 0;
  11128. $progress = self::getProgress(
  11129. $this->lp_id,
  11130. $this->user_id,
  11131. $this->course_int_id,
  11132. $sessionId
  11133. );
  11134. if ($progress >= 50) {
  11135. $stars++;
  11136. }
  11137. // Calculate stars chapters evaluation
  11138. $exercisesItems = $this->getExercisesItems();
  11139. if (!empty($exercisesItems)) {
  11140. $totalResult = 0;
  11141. foreach ($exercisesItems as $exerciseItem) {
  11142. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11143. $this->user_id,
  11144. $exerciseItem->path,
  11145. $this->course_int_id,
  11146. $sessionId,
  11147. $this->lp_id,
  11148. $exerciseItem->db_id
  11149. );
  11150. $exerciseResultInfo = end($exerciseResultInfo);
  11151. if (!$exerciseResultInfo) {
  11152. continue;
  11153. }
  11154. if (!empty($exerciseResultInfo['exe_weighting'])) {
  11155. $exerciseResult = $exerciseResultInfo['exe_result'] * 100 / $exerciseResultInfo['exe_weighting'];
  11156. } else {
  11157. $exerciseResult = 0;
  11158. }
  11159. $totalResult += $exerciseResult;
  11160. }
  11161. $totalExerciseAverage = $totalResult / (count($exercisesItems) > 0 ? count($exercisesItems) : 1);
  11162. if ($totalExerciseAverage >= 50) {
  11163. $stars++;
  11164. }
  11165. if ($totalExerciseAverage >= 80) {
  11166. $stars++;
  11167. }
  11168. }
  11169. // Calculate star for final evaluation
  11170. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11171. if (!empty($finalEvaluationItem)) {
  11172. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11173. $this->user_id,
  11174. $finalEvaluationItem->path,
  11175. $this->course_int_id,
  11176. $sessionId,
  11177. $this->lp_id,
  11178. $finalEvaluationItem->db_id
  11179. );
  11180. $evaluationResultInfo = end($evaluationResultInfo);
  11181. if ($evaluationResultInfo) {
  11182. $evaluationResult = $evaluationResultInfo['exe_result'] * 100 / $evaluationResultInfo['exe_weighting'];
  11183. if ($evaluationResult >= 80) {
  11184. $stars++;
  11185. }
  11186. }
  11187. }
  11188. return $stars;
  11189. }
  11190. /**
  11191. * Get the items of exercise type.
  11192. *
  11193. * @return array The items. Otherwise return false
  11194. */
  11195. public function getExercisesItems()
  11196. {
  11197. $exercises = [];
  11198. foreach ($this->items as $item) {
  11199. if ($item->type != 'quiz') {
  11200. continue;
  11201. }
  11202. $exercises[] = $item;
  11203. }
  11204. array_pop($exercises);
  11205. return $exercises;
  11206. }
  11207. /**
  11208. * Get the item of exercise type (evaluation type).
  11209. *
  11210. * @return array The final evaluation. Otherwise return false
  11211. */
  11212. public function getFinalEvaluationItem()
  11213. {
  11214. $exercises = [];
  11215. foreach ($this->items as $item) {
  11216. if ($item->type != 'quiz') {
  11217. continue;
  11218. }
  11219. $exercises[] = $item;
  11220. }
  11221. return array_pop($exercises);
  11222. }
  11223. /**
  11224. * Calculate the total points achieved for the current user in this learning path.
  11225. *
  11226. * @param int $sessionId Optional. The session Id
  11227. *
  11228. * @return int
  11229. */
  11230. public function getCalculateScore($sessionId = 0)
  11231. {
  11232. // Calculate stars chapters evaluation
  11233. $exercisesItems = $this->getExercisesItems();
  11234. $finalEvaluationItem = $this->getFinalEvaluationItem();
  11235. $totalExercisesResult = 0;
  11236. $totalEvaluationResult = 0;
  11237. if ($exercisesItems !== false) {
  11238. foreach ($exercisesItems as $exerciseItem) {
  11239. $exerciseResultInfo = Event::getExerciseResultsByUser(
  11240. $this->user_id,
  11241. $exerciseItem->path,
  11242. $this->course_int_id,
  11243. $sessionId,
  11244. $this->lp_id,
  11245. $exerciseItem->db_id
  11246. );
  11247. $exerciseResultInfo = end($exerciseResultInfo);
  11248. if (!$exerciseResultInfo) {
  11249. continue;
  11250. }
  11251. $totalExercisesResult += $exerciseResultInfo['exe_result'];
  11252. }
  11253. }
  11254. if (!empty($finalEvaluationItem)) {
  11255. $evaluationResultInfo = Event::getExerciseResultsByUser(
  11256. $this->user_id,
  11257. $finalEvaluationItem->path,
  11258. $this->course_int_id,
  11259. $sessionId,
  11260. $this->lp_id,
  11261. $finalEvaluationItem->db_id
  11262. );
  11263. $evaluationResultInfo = end($evaluationResultInfo);
  11264. if ($evaluationResultInfo) {
  11265. $totalEvaluationResult += $evaluationResultInfo['exe_result'];
  11266. }
  11267. }
  11268. return $totalExercisesResult + $totalEvaluationResult;
  11269. }
  11270. /**
  11271. * Check if URL is not allowed to be show in a iframe.
  11272. *
  11273. * @param string $src
  11274. *
  11275. * @return string
  11276. */
  11277. public function fixBlockedLinks($src)
  11278. {
  11279. $urlInfo = parse_url($src);
  11280. $platformProtocol = 'https';
  11281. if (strpos(api_get_path(WEB_CODE_PATH), 'https') === false) {
  11282. $platformProtocol = 'http';
  11283. }
  11284. $protocolFixApplied = false;
  11285. //Scheme validation to avoid "Notices" when the lesson doesn't contain a valid scheme
  11286. $scheme = isset($urlInfo['scheme']) ? $urlInfo['scheme'] : null;
  11287. $host = isset($urlInfo['host']) ? $urlInfo['host'] : null;
  11288. if ($platformProtocol != $scheme) {
  11289. Session::write('x_frame_source', $src);
  11290. $src = 'blank.php?error=x_frames_options';
  11291. $protocolFixApplied = true;
  11292. }
  11293. if ($protocolFixApplied == false) {
  11294. if (strpos(api_get_path(WEB_PATH), $host) === false) {
  11295. // Check X-Frame-Options
  11296. $ch = curl_init();
  11297. $options = [
  11298. CURLOPT_URL => $src,
  11299. CURLOPT_RETURNTRANSFER => true,
  11300. CURLOPT_HEADER => true,
  11301. CURLOPT_FOLLOWLOCATION => true,
  11302. CURLOPT_ENCODING => "",
  11303. CURLOPT_AUTOREFERER => true,
  11304. CURLOPT_CONNECTTIMEOUT => 120,
  11305. CURLOPT_TIMEOUT => 120,
  11306. CURLOPT_MAXREDIRS => 10,
  11307. ];
  11308. $proxySettings = api_get_configuration_value('proxy_settings');
  11309. if (!empty($proxySettings) &&
  11310. isset($proxySettings['curl_setopt_array'])
  11311. ) {
  11312. $options[CURLOPT_PROXY] = $proxySettings['curl_setopt_array']['CURLOPT_PROXY'];
  11313. $options[CURLOPT_PROXYPORT] = $proxySettings['curl_setopt_array']['CURLOPT_PROXYPORT'];
  11314. }
  11315. curl_setopt_array($ch, $options);
  11316. $response = curl_exec($ch);
  11317. $httpCode = curl_getinfo($ch);
  11318. $headers = substr($response, 0, $httpCode['header_size']);
  11319. $error = false;
  11320. if (stripos($headers, 'X-Frame-Options: DENY') > -1
  11321. //|| stripos($headers, 'X-Frame-Options: SAMEORIGIN') > -1
  11322. ) {
  11323. $error = true;
  11324. }
  11325. if ($error) {
  11326. Session::write('x_frame_source', $src);
  11327. $src = 'blank.php?error=x_frames_options';
  11328. }
  11329. }
  11330. }
  11331. return $src;
  11332. }
  11333. /**
  11334. * Check if this LP has a created forum in the basis course.
  11335. *
  11336. * @return bool
  11337. */
  11338. public function lpHasForum()
  11339. {
  11340. $forumTable = Database::get_course_table(TABLE_FORUM);
  11341. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11342. $fakeFrom = "
  11343. $forumTable f
  11344. INNER JOIN $itemProperty ip
  11345. ON (f.forum_id = ip.ref AND f.c_id = ip.c_id)
  11346. ";
  11347. $resultData = Database::select(
  11348. 'COUNT(f.iid) AS qty',
  11349. $fakeFrom,
  11350. [
  11351. 'where' => [
  11352. 'ip.visibility != ? AND ' => 2,
  11353. 'ip.tool = ? AND ' => TOOL_FORUM,
  11354. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11355. 'f.lp_id = ?' => intval($this->lp_id),
  11356. ],
  11357. ],
  11358. 'first'
  11359. );
  11360. return $resultData['qty'] > 0;
  11361. }
  11362. /**
  11363. * Get the forum for this learning path.
  11364. *
  11365. * @param int $sessionId
  11366. *
  11367. * @return bool
  11368. */
  11369. public function getForum($sessionId = 0)
  11370. {
  11371. $forumTable = Database::get_course_table(TABLE_FORUM);
  11372. $itemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
  11373. $fakeFrom = "$forumTable f
  11374. INNER JOIN $itemProperty ip ";
  11375. if ($this->lp_session_id == 0) {
  11376. $fakeFrom .= "
  11377. ON (
  11378. f.forum_id = ip.ref AND f.c_id = ip.c_id AND (
  11379. f.session_id = ip.session_id OR ip.session_id IS NULL
  11380. )
  11381. )
  11382. ";
  11383. } else {
  11384. $fakeFrom .= "
  11385. ON (
  11386. f.forum_id = ip.ref AND f.c_id = ip.c_id AND f.session_id = ip.session_id
  11387. )
  11388. ";
  11389. }
  11390. $resultData = Database::select(
  11391. 'f.*',
  11392. $fakeFrom,
  11393. [
  11394. 'where' => [
  11395. 'ip.visibility != ? AND ' => 2,
  11396. 'ip.tool = ? AND ' => TOOL_FORUM,
  11397. 'f.session_id = ? AND ' => $sessionId,
  11398. 'f.c_id = ? AND ' => intval($this->course_int_id),
  11399. 'f.lp_id = ?' => intval($this->lp_id),
  11400. ],
  11401. ],
  11402. 'first'
  11403. );
  11404. if (empty($resultData)) {
  11405. return false;
  11406. }
  11407. return $resultData;
  11408. }
  11409. /**
  11410. * Create a forum for this learning path.
  11411. *
  11412. * @param int $forumCategoryId
  11413. *
  11414. * @return int The forum ID if was created. Otherwise return false
  11415. */
  11416. public function createForum($forumCategoryId)
  11417. {
  11418. require_once api_get_path(SYS_CODE_PATH).'/forum/forumfunction.inc.php';
  11419. $forumId = store_forum(
  11420. [
  11421. 'lp_id' => $this->lp_id,
  11422. 'forum_title' => $this->name,
  11423. 'forum_comment' => null,
  11424. 'forum_category' => (int) $forumCategoryId,
  11425. 'students_can_edit_group' => ['students_can_edit' => 0],
  11426. 'allow_new_threads_group' => ['allow_new_threads' => 0],
  11427. 'default_view_type_group' => ['default_view_type' => 'flat'],
  11428. 'group_forum' => 0,
  11429. 'public_private_group_forum_group' => ['public_private_group_forum' => 'public'],
  11430. ],
  11431. [],
  11432. true
  11433. );
  11434. return $forumId;
  11435. }
  11436. /**
  11437. * Get the LP Final Item form.
  11438. *
  11439. * @throws Exception
  11440. * @throws HTML_QuickForm_Error
  11441. *
  11442. * @return string
  11443. */
  11444. public function getFinalItemForm()
  11445. {
  11446. $finalItem = $this->getFinalItem();
  11447. $title = '';
  11448. if ($finalItem) {
  11449. $title = $finalItem->get_title();
  11450. $buttonText = get_lang('Save');
  11451. $content = $this->getSavedFinalItem();
  11452. } else {
  11453. $buttonText = get_lang('LPCreateDocument');
  11454. $content = $this->getFinalItemTemplate();
  11455. }
  11456. $courseInfo = api_get_course_info();
  11457. $result = $this->generate_lp_folder($courseInfo);
  11458. $relative_path = api_substr($result['dir'], 1, strlen($result['dir']));
  11459. $relative_prefix = '../../';
  11460. $editorConfig = [
  11461. 'ToolbarSet' => 'LearningPathDocuments',
  11462. 'Width' => '100%',
  11463. 'Height' => '500',
  11464. 'FullPage' => true,
  11465. 'CreateDocumentDir' => $relative_prefix,
  11466. 'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
  11467. 'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/'.$relative_path,
  11468. ];
  11469. $url = api_get_self().'?'.api_get_cidreq().'&'.http_build_query([
  11470. 'type' => 'document',
  11471. 'lp_id' => $this->lp_id,
  11472. ]);
  11473. $form = new FormValidator('final_item', 'POST', $url);
  11474. $form->addText('title', get_lang('Title'));
  11475. $form->addButtonSave($buttonText);
  11476. $form->addHtml(
  11477. Display::return_message(
  11478. 'Variables :</br></br> <b>((certificate))</b> </br> <b>((skill))</b>',
  11479. 'normal',
  11480. false
  11481. )
  11482. );
  11483. $renderer = $form->defaultRenderer();
  11484. $renderer->setElementTemplate('&nbsp;{label}{element}', 'content_lp_certificate');
  11485. $form->addHtmlEditor(
  11486. 'content_lp_certificate',
  11487. null,
  11488. true,
  11489. false,
  11490. $editorConfig,
  11491. true
  11492. );
  11493. $form->addHidden('action', 'add_final_item');
  11494. $form->addHidden('path', Session::read('pathItem'));
  11495. $form->addHidden('previous', $this->get_last());
  11496. $form->setDefaults(
  11497. ['title' => $title, 'content_lp_certificate' => $content]
  11498. );
  11499. if ($form->validate()) {
  11500. $values = $form->exportValues();
  11501. $lastItemId = $this->getLastInFirstLevel();
  11502. if (!$finalItem) {
  11503. $documentId = $this->create_document(
  11504. $this->course_info,
  11505. $values['content_lp_certificate'],
  11506. $values['title']
  11507. );
  11508. $this->add_item(
  11509. 0,
  11510. $lastItemId,
  11511. 'final_item',
  11512. $documentId,
  11513. $values['title'],
  11514. ''
  11515. );
  11516. Display::addFlash(
  11517. Display::return_message(get_lang('Added'))
  11518. );
  11519. } else {
  11520. $this->edit_document($this->course_info);
  11521. }
  11522. }
  11523. return $form->returnForm();
  11524. }
  11525. /**
  11526. * Check if the current lp item is first, both, last or none from lp list.
  11527. *
  11528. * @param int $currentItemId
  11529. *
  11530. * @return string
  11531. */
  11532. public function isFirstOrLastItem($currentItemId)
  11533. {
  11534. $lpItemId = [];
  11535. $typeListNotToVerify = self::getChapterTypes();
  11536. // Using get_toc() function instead $this->items because returns the correct order of the items
  11537. foreach ($this->get_toc() as $item) {
  11538. if (!in_array($item['type'], $typeListNotToVerify)) {
  11539. $lpItemId[] = $item['id'];
  11540. }
  11541. }
  11542. $lastLpItemIndex = count($lpItemId) - 1;
  11543. $position = array_search($currentItemId, $lpItemId);
  11544. switch ($position) {
  11545. case 0:
  11546. if (!$lastLpItemIndex) {
  11547. $answer = 'both';
  11548. break;
  11549. }
  11550. $answer = 'first';
  11551. break;
  11552. case $lastLpItemIndex:
  11553. $answer = 'last';
  11554. break;
  11555. default:
  11556. $answer = 'none';
  11557. }
  11558. return $answer;
  11559. }
  11560. /**
  11561. * Get whether this is a learning path with the accumulated SCORM time or not.
  11562. *
  11563. * @return int
  11564. */
  11565. public function getAccumulateScormTime()
  11566. {
  11567. return $this->accumulateScormTime;
  11568. }
  11569. /**
  11570. * Set whether this is a learning path with the accumulated SCORM time or not.
  11571. *
  11572. * @param int $value (0 = false, 1 = true)
  11573. *
  11574. * @return bool Always returns true
  11575. */
  11576. public function setAccumulateScormTime($value)
  11577. {
  11578. $this->accumulateScormTime = (int) $value;
  11579. $lp_table = Database::get_course_table(TABLE_LP_MAIN);
  11580. $lp_id = $this->get_id();
  11581. $sql = "UPDATE $lp_table
  11582. SET accumulate_scorm_time = ".$this->accumulateScormTime."
  11583. WHERE iid = $lp_id";
  11584. Database::query($sql);
  11585. return true;
  11586. }
  11587. /**
  11588. * Returns an HTML-formatted link to a resource, to incorporate directly into
  11589. * the new learning path tool.
  11590. *
  11591. * The function is a big switch on tool type.
  11592. * In each case, we query the corresponding table for information and build the link
  11593. * with that information.
  11594. *
  11595. * @author Yannick Warnier <ywarnier@beeznest.org> - rebranding based on
  11596. * previous work (display_addedresource_link_in_learnpath())
  11597. *
  11598. * @param int $course_id Course code
  11599. * @param int $learningPathId The learning path ID (in lp table)
  11600. * @param int $id_in_path the unique index in the items table
  11601. * @param int $lpViewId
  11602. *
  11603. * @return string
  11604. */
  11605. public static function rl_get_resource_link_for_learnpath(
  11606. $course_id,
  11607. $learningPathId,
  11608. $id_in_path,
  11609. $lpViewId
  11610. ) {
  11611. $session_id = api_get_session_id();
  11612. $course_info = api_get_course_info_by_id($course_id);
  11613. $learningPathId = (int) $learningPathId;
  11614. $id_in_path = (int) $id_in_path;
  11615. $lpViewId = (int) $lpViewId;
  11616. $em = Database::getManager();
  11617. $lpItemRepo = $em->getRepository('ChamiloCourseBundle:CLpItem');
  11618. /** @var CLpItem $rowItem */
  11619. $rowItem = $lpItemRepo->findOneBy([
  11620. 'cId' => $course_id,
  11621. 'lpId' => $learningPathId,
  11622. 'iid' => $id_in_path,
  11623. ]);
  11624. if (!$rowItem) {
  11625. // Try one more time with "id"
  11626. /** @var CLpItem $rowItem */
  11627. $rowItem = $lpItemRepo->findOneBy([
  11628. 'cId' => $course_id,
  11629. 'lpId' => $learningPathId,
  11630. 'id' => $id_in_path,
  11631. ]);
  11632. if (!$rowItem) {
  11633. return -1;
  11634. }
  11635. }
  11636. $course_code = $course_info['code'];
  11637. $type = $rowItem->getItemType();
  11638. $id = empty($rowItem->getPath()) ? '0' : $rowItem->getPath();
  11639. $main_dir_path = api_get_path(WEB_CODE_PATH);
  11640. $main_course_path = api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/';
  11641. $link = '';
  11642. $extraParams = api_get_cidreq(true, true, 'learnpath').'&session_id='.$session_id;
  11643. switch ($type) {
  11644. case 'dir':
  11645. return $main_dir_path.'lp/blank.php';
  11646. case TOOL_CALENDAR_EVENT:
  11647. return $main_dir_path.'calendar/agenda.php?agenda_id='.$id.'&'.$extraParams;
  11648. case TOOL_ANNOUNCEMENT:
  11649. return $main_dir_path.'announcements/announcements.php?ann_id='.$id.'&'.$extraParams;
  11650. case TOOL_LINK:
  11651. $linkInfo = Link::getLinkInfo($id);
  11652. if (isset($linkInfo['url'])) {
  11653. return $linkInfo['url'];
  11654. }
  11655. return '';
  11656. case TOOL_QUIZ:
  11657. if (empty($id)) {
  11658. return '';
  11659. }
  11660. // Get the lp_item_view with the highest view_count.
  11661. $learnpathItemViewResult = $em
  11662. ->getRepository('ChamiloCourseBundle:CLpItemView')
  11663. ->findBy(
  11664. ['cId' => $course_id, 'lpItemId' => $rowItem->getId(), 'lpViewId' => $lpViewId],
  11665. ['viewCount' => 'DESC'],
  11666. 1
  11667. );
  11668. /** @var CLpItemView $learnpathItemViewData */
  11669. $learnpathItemViewData = current($learnpathItemViewResult);
  11670. $learnpathItemViewId = $learnpathItemViewData ? $learnpathItemViewData->getId() : 0;
  11671. return $main_dir_path.'exercise/overview.php?'.$extraParams.'&'
  11672. .http_build_query([
  11673. 'lp_init' => 1,
  11674. 'learnpath_item_view_id' => $learnpathItemViewId,
  11675. 'learnpath_id' => $learningPathId,
  11676. 'learnpath_item_id' => $id_in_path,
  11677. 'exerciseId' => $id,
  11678. ]);
  11679. case TOOL_HOTPOTATOES: //lowercase because of strtolower above
  11680. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  11681. $result = Database::query("SELECT * FROM ".$TBL_DOCUMENT." WHERE c_id = $course_id AND iid=$id");
  11682. $myrow = Database::fetch_array($result);
  11683. $path = $myrow['path'];
  11684. return $main_dir_path.'exercise/showinframes.php?file='.$path.'&cid='.$course_code.'&uid='
  11685. .api_get_user_id().'&learnpath_id='.$learningPathId.'&learnpath_item_id='.$id_in_path
  11686. .'&lp_view_id='.$lpViewId.'&'.$extraParams;
  11687. case TOOL_FORUM:
  11688. return $main_dir_path.'forum/viewforum.php?forum='.$id.'&lp=true&'.$extraParams;
  11689. case TOOL_THREAD:
  11690. // forum post
  11691. $tbl_topics = Database::get_course_table(TABLE_FORUM_THREAD);
  11692. if (empty($id)) {
  11693. return '';
  11694. }
  11695. $sql = "SELECT * FROM $tbl_topics WHERE c_id = $course_id AND thread_id=$id";
  11696. $result = Database::query($sql);
  11697. $myrow = Database::fetch_array($result);
  11698. return $main_dir_path.'forum/viewthread.php?thread='.$id.'&forum='.$myrow['forum_id'].'&lp=true&'
  11699. .$extraParams;
  11700. case TOOL_POST:
  11701. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11702. $result = Database::query("SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=$id");
  11703. $myrow = Database::fetch_array($result);
  11704. return $main_dir_path.'forum/viewthread.php?post='.$id.'&thread='.$myrow['thread_id'].'&forum='
  11705. .$myrow['forum_id'].'&lp=true&'.$extraParams;
  11706. case TOOL_READOUT_TEXT:
  11707. return api_get_path(WEB_CODE_PATH).
  11708. 'lp/readout_text.php?&id='.$id.'&lp_id='.$learningPathId.'&'.$extraParams;
  11709. case TOOL_DOCUMENT:
  11710. $repo = $em->getRepository('ChamiloCourseBundle:CDocument');
  11711. $document = $repo->findOneBy(['cId' => $course_id, 'iid' => $id]);
  11712. if (empty($document)) {
  11713. // Try with normal id
  11714. $document = $repo->findOneBy(['cId' => $course_id, 'id' => $id]);
  11715. if (empty($document)) {
  11716. return '';
  11717. }
  11718. }
  11719. $documentPathInfo = pathinfo($document->getPath());
  11720. $mediaSupportedFiles = ['mp3', 'mp4', 'ogv', 'flv', 'm4v'];
  11721. $extension = isset($documentPathInfo['extension']) ? $documentPathInfo['extension'] : '';
  11722. $showDirectUrl = !in_array($extension, $mediaSupportedFiles);
  11723. $openmethod = 2;
  11724. $officedoc = false;
  11725. Session::write('openmethod', $openmethod);
  11726. Session::write('officedoc', $officedoc);
  11727. if ($showDirectUrl) {
  11728. $file = $main_course_path.'document'.$document->getPath().'?'.$extraParams;
  11729. if (api_get_configuration_value('allow_pdf_viewerjs_in_lp')) {
  11730. if (Link::isPdfLink($file)) {
  11731. $pdfUrl = api_get_path(WEB_LIBRARY_PATH).'javascript/ViewerJS/index.html#'.$file;
  11732. return $pdfUrl;
  11733. }
  11734. }
  11735. return $file;
  11736. }
  11737. return api_get_path(WEB_CODE_PATH).'document/showinframes.php?id='.$id.'&'.$extraParams;
  11738. case TOOL_LP_FINAL_ITEM:
  11739. return api_get_path(WEB_CODE_PATH).'lp/lp_final_item.php?&id='.$id.'&lp_id='.$learningPathId.'&'
  11740. .$extraParams;
  11741. case 'assignments':
  11742. return $main_dir_path.'work/work.php?'.$extraParams;
  11743. case TOOL_DROPBOX:
  11744. return $main_dir_path.'dropbox/index.php?'.$extraParams;
  11745. case 'introduction_text': //DEPRECATED
  11746. return '';
  11747. case TOOL_COURSE_DESCRIPTION:
  11748. return $main_dir_path.'course_description?'.$extraParams;
  11749. case TOOL_GROUP:
  11750. return $main_dir_path.'group/group.php?'.$extraParams;
  11751. case TOOL_USER:
  11752. return $main_dir_path.'user/user.php?'.$extraParams;
  11753. case TOOL_STUDENTPUBLICATION:
  11754. if (!empty($rowItem->getPath())) {
  11755. return $main_dir_path.'work/work_list.php?id='.$rowItem->getPath().'&'.$extraParams;
  11756. }
  11757. return $main_dir_path.'work/work.php?'.api_get_cidreq().'&id='.$rowItem->getPath().'&'.$extraParams;
  11758. }
  11759. return $link;
  11760. }
  11761. /**
  11762. * Gets the name of a resource (generally used in learnpath when no name is provided).
  11763. *
  11764. * @author Yannick Warnier <ywarnier@beeznest.org>
  11765. *
  11766. * @param string $course_code Course code
  11767. * @param int $learningPathId
  11768. * @param int $id_in_path The resource ID
  11769. *
  11770. * @return string
  11771. */
  11772. public static function rl_get_resource_name($course_code, $learningPathId, $id_in_path)
  11773. {
  11774. $_course = api_get_course_info($course_code);
  11775. if (empty($_course)) {
  11776. return '';
  11777. }
  11778. $course_id = $_course['real_id'];
  11779. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  11780. $learningPathId = (int) $learningPathId;
  11781. $id_in_path = (int) $id_in_path;
  11782. $sql = "SELECT item_type, title, ref
  11783. FROM $tbl_lp_item
  11784. WHERE c_id = $course_id AND lp_id = $learningPathId AND iid = $id_in_path";
  11785. $res_item = Database::query($sql);
  11786. if (Database::num_rows($res_item) < 1) {
  11787. return '';
  11788. }
  11789. $row_item = Database::fetch_array($res_item);
  11790. $type = strtolower($row_item['item_type']);
  11791. $id = $row_item['ref'];
  11792. $output = '';
  11793. switch ($type) {
  11794. case TOOL_CALENDAR_EVENT:
  11795. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  11796. $result = Database::query("SELECT * FROM $TABLEAGENDA WHERE c_id = $course_id AND id=$id");
  11797. $myrow = Database::fetch_array($result);
  11798. $output = $myrow['title'];
  11799. break;
  11800. case TOOL_ANNOUNCEMENT:
  11801. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  11802. $result = Database::query("SELECT * FROM $tbl_announcement WHERE c_id = $course_id AND id=$id");
  11803. $myrow = Database::fetch_array($result);
  11804. $output = $myrow['title'];
  11805. break;
  11806. case TOOL_LINK:
  11807. // Doesn't take $target into account.
  11808. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  11809. $result = Database::query("SELECT * FROM $TABLETOOLLINK WHERE c_id = $course_id AND id=$id");
  11810. $myrow = Database::fetch_array($result);
  11811. $output = $myrow['title'];
  11812. break;
  11813. case TOOL_QUIZ:
  11814. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  11815. $result = Database::query("SELECT * FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $id");
  11816. $myrow = Database::fetch_array($result);
  11817. $output = $myrow['title'];
  11818. break;
  11819. case TOOL_FORUM:
  11820. $TBL_FORUMS = Database::get_course_table(TABLE_FORUM);
  11821. $result = Database::query("SELECT * FROM $TBL_FORUMS WHERE c_id = $course_id AND forum_id = $id");
  11822. $myrow = Database::fetch_array($result);
  11823. $output = $myrow['forum_name'];
  11824. break;
  11825. case TOOL_THREAD:
  11826. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11827. // Grabbing the title of the post.
  11828. $sql_title = "SELECT * FROM $tbl_post WHERE c_id = $course_id AND post_id=".$id;
  11829. $result_title = Database::query($sql_title);
  11830. $myrow_title = Database::fetch_array($result_title);
  11831. $output = $myrow_title['post_title'];
  11832. break;
  11833. case TOOL_POST:
  11834. $tbl_post = Database::get_course_table(TABLE_FORUM_POST);
  11835. $sql = "SELECT * FROM $tbl_post p WHERE c_id = $course_id AND p.post_id = $id";
  11836. $result = Database::query($sql);
  11837. $post = Database::fetch_array($result);
  11838. $output = $post['post_title'];
  11839. break;
  11840. case 'dir':
  11841. case TOOL_DOCUMENT:
  11842. $title = $row_item['title'];
  11843. $output = '-';
  11844. if (!empty($title)) {
  11845. $output = $title;
  11846. }
  11847. break;
  11848. case 'hotpotatoes':
  11849. $tbl_doc = Database::get_course_table(TABLE_DOCUMENT);
  11850. $result = Database::query("SELECT * FROM $tbl_doc WHERE c_id = $course_id AND iid = $id");
  11851. $myrow = Database::fetch_array($result);
  11852. $pathname = explode('/', $myrow['path']); // Making a correct name for the link.
  11853. $last = count($pathname) - 1; // Making a correct name for the link.
  11854. $filename = $pathname[$last]; // Making a correct name for the link.
  11855. $myrow['path'] = rawurlencode($myrow['path']);
  11856. $output = $filename;
  11857. break;
  11858. }
  11859. return stripslashes($output);
  11860. }
  11861. /**
  11862. * Get the parent names for the current item.
  11863. *
  11864. * @param int $newItemId Optional. The item ID
  11865. *
  11866. * @return array
  11867. */
  11868. public function getCurrentItemParentNames($newItemId = 0)
  11869. {
  11870. $newItemId = $newItemId ?: $this->get_current_item_id();
  11871. $return = [];
  11872. $item = $this->getItem($newItemId);
  11873. $parent = $this->getItem($item->get_parent());
  11874. while ($parent) {
  11875. $return[] = $parent->get_title();
  11876. $parent = $this->getItem($parent->get_parent());
  11877. }
  11878. return array_reverse($return);
  11879. }
  11880. /**
  11881. * Reads and process "lp_subscription_settings" setting.
  11882. *
  11883. * @return array
  11884. */
  11885. public static function getSubscriptionSettings()
  11886. {
  11887. $subscriptionSettings = api_get_configuration_value('lp_subscription_settings');
  11888. if (empty($subscriptionSettings)) {
  11889. // By default allow both settings
  11890. $subscriptionSettings = [
  11891. 'allow_add_users_to_lp' => true,
  11892. 'allow_add_users_to_lp_category' => true,
  11893. ];
  11894. } else {
  11895. $subscriptionSettings = $subscriptionSettings['options'];
  11896. }
  11897. return $subscriptionSettings;
  11898. }
  11899. /**
  11900. * Exports a LP to a courseBuilder zip file. It adds the documents related to the LP.
  11901. */
  11902. public function exportToCourseBuildFormat()
  11903. {
  11904. if (!api_is_allowed_to_edit()) {
  11905. return false;
  11906. }
  11907. $courseBuilder = new CourseBuilder();
  11908. $itemList = [];
  11909. /** @var learnpathItem $item */
  11910. foreach ($this->items as $item) {
  11911. $itemList[$item->get_type()][] = $item->get_path();
  11912. }
  11913. if (empty($itemList)) {
  11914. return false;
  11915. }
  11916. if (isset($itemList['document'])) {
  11917. // Get parents
  11918. foreach ($itemList['document'] as $documentId) {
  11919. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id(), true);
  11920. if (!empty($documentInfo['parents'])) {
  11921. foreach ($documentInfo['parents'] as $parentInfo) {
  11922. if (in_array($parentInfo['iid'], $itemList['document'])) {
  11923. continue;
  11924. }
  11925. $itemList['document'][] = $parentInfo['iid'];
  11926. }
  11927. }
  11928. }
  11929. $courseInfo = api_get_course_info();
  11930. foreach ($itemList['document'] as $documentId) {
  11931. $documentInfo = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
  11932. $items = DocumentManager::get_resources_from_source_html(
  11933. $documentInfo['absolute_path'],
  11934. true,
  11935. TOOL_DOCUMENT
  11936. );
  11937. if (!empty($items)) {
  11938. foreach ($items as $item) {
  11939. // Get information about source url
  11940. $url = $item[0]; // url
  11941. $scope = $item[1]; // scope (local, remote)
  11942. $type = $item[2]; // type (rel, abs, url)
  11943. $origParseUrl = parse_url($url);
  11944. $realOrigPath = isset($origParseUrl['path']) ? $origParseUrl['path'] : null;
  11945. if ($scope == 'local') {
  11946. if ($type == 'abs' || $type == 'rel') {
  11947. $documentFile = strstr($realOrigPath, 'document');
  11948. if (strpos($realOrigPath, $documentFile) !== false) {
  11949. $documentFile = str_replace('document', '', $documentFile);
  11950. $itemDocumentId = DocumentManager::get_document_id($courseInfo, $documentFile);
  11951. // Document found! Add it to the list
  11952. if ($itemDocumentId) {
  11953. $itemList['document'][] = $itemDocumentId;
  11954. }
  11955. }
  11956. }
  11957. }
  11958. }
  11959. }
  11960. }
  11961. $courseBuilder->build_documents(
  11962. api_get_session_id(),
  11963. $this->get_course_int_id(),
  11964. true,
  11965. $itemList['document']
  11966. );
  11967. }
  11968. if (isset($itemList['quiz'])) {
  11969. $courseBuilder->build_quizzes(
  11970. api_get_session_id(),
  11971. $this->get_course_int_id(),
  11972. true,
  11973. $itemList['quiz']
  11974. );
  11975. }
  11976. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  11977. /*if (!empty($itemList['thread'])) {
  11978. $postList = [];
  11979. foreach ($itemList['thread'] as $postId) {
  11980. $post = get_post_information($postId);
  11981. if ($post) {
  11982. if (!isset($itemList['forum'])) {
  11983. $itemList['forum'] = [];
  11984. }
  11985. $itemList['forum'][] = $post['forum_id'];
  11986. $postList[] = $postId;
  11987. }
  11988. }
  11989. if (!empty($postList)) {
  11990. $courseBuilder->build_forum_posts(
  11991. $this->get_course_int_id(),
  11992. null,
  11993. null,
  11994. $postList
  11995. );
  11996. }
  11997. }*/
  11998. if (!empty($itemList['thread'])) {
  11999. $threadList = [];
  12000. $em = Database::getManager();
  12001. $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
  12002. foreach ($itemList['thread'] as $threadId) {
  12003. /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
  12004. $thread = $repo->find($threadId);
  12005. if ($thread) {
  12006. $itemList['forum'][] = $thread->getForumId();
  12007. $threadList[] = $thread->getIid();
  12008. }
  12009. }
  12010. if (!empty($threadList)) {
  12011. $courseBuilder->build_forum_topics(
  12012. api_get_session_id(),
  12013. $this->get_course_int_id(),
  12014. null,
  12015. $threadList
  12016. );
  12017. }
  12018. }
  12019. $forumCategoryList = [];
  12020. if (isset($itemList['forum'])) {
  12021. foreach ($itemList['forum'] as $forumId) {
  12022. $forumInfo = get_forums($forumId);
  12023. $forumCategoryList[] = $forumInfo['forum_category'];
  12024. }
  12025. }
  12026. if (!empty($forumCategoryList)) {
  12027. $courseBuilder->build_forum_category(
  12028. api_get_session_id(),
  12029. $this->get_course_int_id(),
  12030. true,
  12031. $forumCategoryList
  12032. );
  12033. }
  12034. if (!empty($itemList['forum'])) {
  12035. $courseBuilder->build_forums(
  12036. api_get_session_id(),
  12037. $this->get_course_int_id(),
  12038. true,
  12039. $itemList['forum']
  12040. );
  12041. }
  12042. if (isset($itemList['link'])) {
  12043. $courseBuilder->build_links(
  12044. api_get_session_id(),
  12045. $this->get_course_int_id(),
  12046. true,
  12047. $itemList['link']
  12048. );
  12049. }
  12050. if (!empty($itemList['student_publication'])) {
  12051. $courseBuilder->build_works(
  12052. api_get_session_id(),
  12053. $this->get_course_int_id(),
  12054. true,
  12055. $itemList['student_publication']
  12056. );
  12057. }
  12058. $courseBuilder->build_learnpaths(
  12059. api_get_session_id(),
  12060. $this->get_course_int_id(),
  12061. true,
  12062. [$this->get_id()],
  12063. false
  12064. );
  12065. $courseBuilder->restoreDocumentsFromList();
  12066. $zipFile = CourseArchiver::createBackup($courseBuilder->course);
  12067. $zipPath = CourseArchiver::getBackupDir().$zipFile;
  12068. $result = DocumentManager::file_send_for_download(
  12069. $zipPath,
  12070. true,
  12071. $this->get_name().'.zip'
  12072. );
  12073. if ($result) {
  12074. api_not_allowed();
  12075. }
  12076. return true;
  12077. }
  12078. /**
  12079. * Get whether this is a learning path with the accumulated work time or not.
  12080. *
  12081. * @return int
  12082. */
  12083. public function getAccumulateWorkTime()
  12084. {
  12085. return (int) $this->accumulateWorkTime;
  12086. }
  12087. /**
  12088. * Get whether this is a learning path with the accumulated work time or not.
  12089. *
  12090. * @return int
  12091. */
  12092. public function getAccumulateWorkTimeTotalCourse()
  12093. {
  12094. $table = Database::get_course_table(TABLE_LP_MAIN);
  12095. $sql = "SELECT SUM(accumulate_work_time) AS total
  12096. FROM $table
  12097. WHERE c_id = ".$this->course_int_id;
  12098. $result = Database::query($sql);
  12099. $row = Database::fetch_array($result);
  12100. return (int) $row['total'];
  12101. }
  12102. /**
  12103. * Set whether this is a learning path with the accumulated work time or not.
  12104. *
  12105. * @param int $value (0 = false, 1 = true)
  12106. *
  12107. * @return bool
  12108. */
  12109. public function setAccumulateWorkTime($value)
  12110. {
  12111. if (!api_get_configuration_value('lp_minimum_time')) {
  12112. return false;
  12113. }
  12114. $this->accumulateWorkTime = (int) $value;
  12115. $table = Database::get_course_table(TABLE_LP_MAIN);
  12116. $lp_id = $this->get_id();
  12117. $sql = "UPDATE $table SET accumulate_work_time = ".$this->accumulateWorkTime."
  12118. WHERE c_id = ".$this->course_int_id." AND id = $lp_id";
  12119. Database::query($sql);
  12120. return true;
  12121. }
  12122. /**
  12123. * @param int $lpId
  12124. * @param int $courseId
  12125. *
  12126. * @return mixed
  12127. */
  12128. public static function getAccumulateWorkTimePrerequisite($lpId, $courseId)
  12129. {
  12130. $lpId = (int) $lpId;
  12131. $courseId = (int) $courseId;
  12132. $table = Database::get_course_table(TABLE_LP_MAIN);
  12133. $sql = "SELECT accumulate_work_time
  12134. FROM $table
  12135. WHERE c_id = $courseId AND id = $lpId";
  12136. $result = Database::query($sql);
  12137. $row = Database::fetch_array($result);
  12138. return $row['accumulate_work_time'];
  12139. }
  12140. /**
  12141. * @param int $courseId
  12142. *
  12143. * @return int
  12144. */
  12145. public static function getAccumulateWorkTimeTotal($courseId)
  12146. {
  12147. $table = Database::get_course_table(TABLE_LP_MAIN);
  12148. $courseId = (int) $courseId;
  12149. $sql = "SELECT SUM(accumulate_work_time) AS total
  12150. FROM $table
  12151. WHERE c_id = $courseId";
  12152. $result = Database::query($sql);
  12153. $row = Database::fetch_array($result);
  12154. return (int) $row['total'];
  12155. }
  12156. /**
  12157. * In order to use the lp icon option you need to create the "lp_icon" LP extra field
  12158. * and put the images in.
  12159. *
  12160. * @return array
  12161. */
  12162. public static function getIconSelect()
  12163. {
  12164. $theme = api_get_visual_theme();
  12165. $path = api_get_path(SYS_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/';
  12166. $icons = ['' => get_lang('SelectAnOption')];
  12167. if (is_dir($path)) {
  12168. $finder = new Finder();
  12169. $finder->files()->in($path);
  12170. $allowedExtensions = ['jpeg', 'jpg', 'png'];
  12171. /** @var SplFileInfo $file */
  12172. foreach ($finder as $file) {
  12173. if (in_array(strtolower($file->getExtension()), $allowedExtensions)) {
  12174. $icons[$file->getFilename()] = $file->getFilename();
  12175. }
  12176. }
  12177. }
  12178. return $icons;
  12179. }
  12180. /**
  12181. * @param int $lpId
  12182. *
  12183. * @return string
  12184. */
  12185. public static function getSelectedIcon($lpId)
  12186. {
  12187. $extraFieldValue = new ExtraFieldValue('lp');
  12188. $lpIcon = $extraFieldValue->get_values_by_handler_and_field_variable($lpId, 'lp_icon');
  12189. $icon = '';
  12190. if (!empty($lpIcon) && isset($lpIcon['value'])) {
  12191. $icon = $lpIcon['value'];
  12192. }
  12193. return $icon;
  12194. }
  12195. /**
  12196. * @param int $lpId
  12197. *
  12198. * @return string
  12199. */
  12200. public static function getSelectedIconHtml($lpId)
  12201. {
  12202. $icon = self::getSelectedIcon($lpId);
  12203. if (empty($icon)) {
  12204. return '';
  12205. }
  12206. $theme = api_get_visual_theme();
  12207. $path = api_get_path(WEB_PUBLIC_PATH).'css/themes/'.$theme.'/lp_icons/'.$icon;
  12208. return Display::img($path);
  12209. }
  12210. /**
  12211. * @param string $value
  12212. *
  12213. * @return string
  12214. */
  12215. public function cleanItemTitle($value)
  12216. {
  12217. $value = Security::remove_XSS(strip_tags($value));
  12218. return $value;
  12219. }
  12220. /**
  12221. * @param FormValidator $form
  12222. */
  12223. public function setItemTitle(FormValidator $form)
  12224. {
  12225. if (api_get_configuration_value('save_titles_as_html')) {
  12226. $form->addHtmlEditor(
  12227. 'title',
  12228. get_lang('Title'),
  12229. true,
  12230. false,
  12231. ['ToolbarSet' => 'TitleAsHtml']
  12232. );
  12233. } else {
  12234. $form->addText('title', get_lang('Title'), true, ['id' => 'idTitle', 'class' => 'learnpath_item_form']);
  12235. $form->applyFilter('title', 'trim');
  12236. $form->applyFilter('title', 'html_filter');
  12237. }
  12238. }
  12239. /**
  12240. * @return array
  12241. */
  12242. public function getItemsForForm($addParentCondition = false)
  12243. {
  12244. $tbl_lp_item = Database::get_course_table(TABLE_LP_ITEM);
  12245. $course_id = api_get_course_int_id();
  12246. $sql = "SELECT * FROM $tbl_lp_item
  12247. WHERE c_id = $course_id AND lp_id = ".$this->lp_id;
  12248. if ($addParentCondition) {
  12249. $sql .= ' AND parent_item_id = 0 ';
  12250. }
  12251. $sql .= ' ORDER BY display_order ASC';
  12252. $result = Database::query($sql);
  12253. $arrLP = [];
  12254. while ($row = Database::fetch_array($result)) {
  12255. $arrLP[] = [
  12256. 'iid' => $row['iid'],
  12257. 'id' => $row['iid'],
  12258. 'item_type' => $row['item_type'],
  12259. 'title' => $this->cleanItemTitle($row['title']),
  12260. 'path' => $row['path'],
  12261. 'description' => Security::remove_XSS($row['description']),
  12262. 'parent_item_id' => $row['parent_item_id'],
  12263. 'previous_item_id' => $row['previous_item_id'],
  12264. 'next_item_id' => $row['next_item_id'],
  12265. 'display_order' => $row['display_order'],
  12266. 'max_score' => $row['max_score'],
  12267. 'min_score' => $row['min_score'],
  12268. 'mastery_score' => $row['mastery_score'],
  12269. 'prerequisite' => $row['prerequisite'],
  12270. 'max_time_allowed' => $row['max_time_allowed'],
  12271. 'prerequisite_min_score' => $row['prerequisite_min_score'],
  12272. 'prerequisite_max_score' => $row['prerequisite_max_score'],
  12273. ];
  12274. }
  12275. return $arrLP;
  12276. }
  12277. /**
  12278. * Get the depth level of LP item.
  12279. *
  12280. * @param array $items
  12281. * @param int $currentItemId
  12282. *
  12283. * @return int
  12284. */
  12285. private static function get_level_for_item($items, $currentItemId)
  12286. {
  12287. $parentItemId = 0;
  12288. if (isset($items[$currentItemId])) {
  12289. $parentItemId = $items[$currentItemId]->parent;
  12290. }
  12291. if ($parentItemId == 0) {
  12292. return 0;
  12293. } else {
  12294. return self::get_level_for_item($items, $parentItemId) + 1;
  12295. }
  12296. }
  12297. /**
  12298. * Generate the link for a learnpath category as course tool.
  12299. *
  12300. * @param int $categoryId
  12301. *
  12302. * @return string
  12303. */
  12304. private static function getCategoryLinkForTool($categoryId)
  12305. {
  12306. $categoryId = (int) $categoryId;
  12307. $link = 'lp/lp_controller.php?'.api_get_cidreq().'&'
  12308. .http_build_query(
  12309. [
  12310. 'action' => 'view_category',
  12311. 'id' => $categoryId,
  12312. ]
  12313. );
  12314. return $link;
  12315. }
  12316. /**
  12317. * Return the scorm item type object with spaces replaced with _
  12318. * The return result is use to build a css classname like scorm_type_$return.
  12319. *
  12320. * @param $in_type
  12321. *
  12322. * @return mixed
  12323. */
  12324. private static function format_scorm_type_item($in_type)
  12325. {
  12326. return str_replace(' ', '_', $in_type);
  12327. }
  12328. /**
  12329. * Check and obtain the lp final item if exist.
  12330. *
  12331. * @return learnpathItem
  12332. */
  12333. private function getFinalItem()
  12334. {
  12335. if (empty($this->items)) {
  12336. return null;
  12337. }
  12338. foreach ($this->items as $item) {
  12339. if ($item->type !== 'final_item') {
  12340. continue;
  12341. }
  12342. return $item;
  12343. }
  12344. }
  12345. /**
  12346. * Get the LP Final Item Template.
  12347. *
  12348. * @return string
  12349. */
  12350. private function getFinalItemTemplate()
  12351. {
  12352. return file_get_contents(api_get_path(SYS_CODE_PATH).'lp/final_item_template/template.html');
  12353. }
  12354. /**
  12355. * Get the LP Final Item Url.
  12356. *
  12357. * @return string
  12358. */
  12359. private function getSavedFinalItem()
  12360. {
  12361. $finalItem = $this->getFinalItem();
  12362. $doc = DocumentManager::get_document_data_by_id(
  12363. $finalItem->path,
  12364. $this->cc
  12365. );
  12366. if ($doc && file_exists($doc['absolute_path'])) {
  12367. return file_get_contents($doc['absolute_path']);
  12368. }
  12369. return '';
  12370. }
  12371. }